#esoteric-python
1 messages · Page 37 of 1
Yes, I was looking for a serious answer as I'm thinking on how to complete a piece of work of mine 😄
Sorry to ask, butwhat is the golf in this case?
oh i just meant that if you try to code golf it (shortest number of characters/bytes), you'd end up with max(arr,key=len), which is what a serious answer would probably give you as well
plus or minus a space
so, in essence, a full iteration is still needed, either by the time the array is built, or at tergo
there's no built in approach in place
it depends how your list is structured.
- if unsorted, you must go through all elements at some point (you could use a tuple for a 5% theoretical speedup in indexing/looping)
- if sorted, you could use a binary search which would be much faster
My list is made of dictionary like this:
max(union, key=len)
{'inspectionResultLink': 'https://search.googl...source=api', 'indexStatusResult.verdict': 'PASS', 'indexStatusResult.co...erageState': 'Submitted and indexed', 'indexStatusResult.ro...tsTxtState': 'ALLOWED', 'indexStatusResult.in...exingState': 'INDEXING_ALLOWED', 'indexStatusResult.la...tCrawlTime': '2023-11-05T21:24:26Z', 'indexStatusResult.pa...FetchState': 'SUCCESSFUL', 'indexStatusResult.go...eCanonical': 'https://www.url.com', 'indexStatusResult.us...rCanonical': 'https://www.url.net/', 'indexStatusResult.re...ringUrls.0': 'https://www.url...nomia-seo/', 'indexStatusResult.re...ringUrls.1': 'https://www.url...essionale/', 'indexStatusResult.crawledAs': 'MOBILE', 'mobileUsabilityResult.verdict': 'PASS', 'richResultsResult.verdict': 'PASS', ...}
And it's not sorted. I don't see how I can sort for something that has not an "index" per se.
A max(list, key=len) works fine for few elements ... but will that be the case for 25K rows?
At end, what I need to build is a namedTuple collection for fast querying the above items.
And I need to find the dictionary with the longest key set at first.
Although, while writing I can alreay smell the subsequent problem ... those dictionaries where the keys was not in place will thrown an error for the missing key
Or perhaps I should consider a SimpleNamespace instead of complicating my life with the namedTuple
In the end the result will be the same, a on object that can be queried by properties
I appreciate the fact that namedTuple will be immutable and guarantee a structure, but my class goal is to facilitate the reading of data not the saving
is it possible to get the code object of a module that's already imported?
like the main code object
not from functions or anything
Ye, should be the f_code on the appropriate frame
!e ```py
def ReadAfterFree(size, do):
b = bytearray(size)
class T:
def iter(self):
b.clear()
self.v = do()
yield b''
yield b''
c = b.join(t:=T())
return memoryview(c).cast('P'), t.v
leak, obj = ReadAfterFree(bytearray.basicsize, lambda: bytearray(8))
print('bytearray:', obj)
print('leaked memory of buffer:', leak.tolist())``` read after free in stringlib join
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | bytearray: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')
002 | leaked memory of buffer: [1, 140216309412032, 8, 9, 140216299095120, 140216299095120, 0]
Yeah but how do I access the frame?
Ah, if you don't have it on the call stack, that would be a bit difficult. I would expect importlib to have it handy
If not, you can call compile on its source code
how can i golf this more?
from itertools import*
E=print
D=str
A=sorted
C=lambda n:A(set(B*C for(B,C)in combinations(range(10**(n//2-1),10**(n//2)),2)if B%10+C%10and A(D(B*C))==A(D(B)+D(C))))
for B in C(4):E(B)
for B in C(6):E(B)```
I'll check importlib but if that doesn't work I'm stuck cuz there's no other way to access the code through files etc so I'd need to find a different way
from itertools import*
D=str
A=sorted
for n in 4,6:*map(print,A(set(B*C for(B,C)in combinations(range(10**(n//2-1),10**(n//2)),2)if B%10+C%10and A(D(B*C))==A(D(B)+D(C)))),
```does this work?
from itertools import*
D=str
A=sorted
for n in 1,2:E=10**n;*map(print,A({B*C for(B,C)in combinations(range(E,E*10),2)if B%10+C%10if A(D(B*C))==A(D(B)+D(C))})),
for n in 4,6 -> for n in 1,2
can this be written any shorter for i in range(50,0,-1):
depends on the code inside of the for
!e
from itertools import*
D=str
A=sorted
for n in 1,2:E=10**n;*map(print,A({B*C for(B,C)in combinations(range(E,E*10),2)if B%10+C%10if A(D(B*C))==A(D(B)+D(C))})),
@orchid nymph :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | /home/main.py:4: SyntaxWarning: invalid decimal literal
002 | for n in 1,2:E=10**n;*map(print,A({B*C for(B,C)in combinations(range(E,E*10),2)if B%10+C%10if A(D(B*C))==A(D(B)+D(C))})),
003 | 1260
004 | 1395
005 | 1435
006 | 1530
007 | 1827
008 | 2187
009 | 6880
010 | 102510
011 | 104260
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/MN4TQLX5R224ENYDRSQ5QL3PGU
n=50
while n:n-=1
from itertools import*
A=sorted
for n in 10,100:*map(print,A({B*C for(B,C)in combinations(range(n,n*10),2)if B%10+C%10if A(f"{B*C}")==A(f"{B}{C}")})),
well its a code.golf hole so I don't think I can help more than that
Hello there,
Is there any way to cast the value contained in dictionary's value to the corresponding enum value description?
Doing in a way that performance are not affected given I have several of them in my dictionary included in a list ?
Imagine something like the following
{'verdict': 'PASS', 'coverageState': 'Submitted and indexed', 'robotsTxtState': 'ALLOWED', 'indexingState': 'INDEXING_ALLOWED', 'lastCrawlTime': '2023-12-02T18:07:42Z', 'pageFetchState': 'SUCCESSFUL', 'googleCanonical': 'https://www.url.com', 'userCanonical': 'https://www.url.com/', 'crawledAs': 'MOBILE'}
I need to replace the indexingState, the pageFetchState, the robotsTxtState.
Ideally I should do this when I'm building my object.
can you not just use the enum value directly
also, this is probably the wrong channel
What could be the right channel? I'm still struggling to understand the 'esotheric' ssense, sorry
I just learned that [[]] * n yields shared references to the same list. I tried using list() or [][:] but couldn't find a way to use the ... * n to have n different empty lists
[*map(list,[()]*n)]
[[]for()in[()]*n]
for fun
ok, nothing cuter than [[] for _ in range(n)] then
for _ in range(int(input())):
n = int(input()) - 1
arr = [i for i in list(input())]
index_list = []
if arr[:-1].count("A") > 0:
count = 0
while n > 0:
if (arr[n] == "B") and (arr[n - 1] == "A") and (n not in index_list):
index_list.append(n)
arr[n], arr[n - 1] = arr[n - 1], arr[n]
n = int(len(arr))-1
count += 1
else:
n -= 1
print(count)
else:
print("0")
Can anyone help me with this please?
Im a beginner. When I submit the code it says Time limit exceeded
The problem is that every time the action is performed, It goes back to the end of the array and starts checking again which is utterly inefficient
But I dont know how to make it faster
i can't read your assignment, but if you focus on finding a criterion that can avoid scanning the array fully each time you win
I sort of did and it was +1 hour of thinking why doesnt it work this time
so I thought, enough for today ahahah
sleep based problem solving
l=[i for i in range(10**10**100)];print("{}".format(l[::-1]));while True: print(hex(id(l)),end="\n\n")
Just a random code
Warning: don't run it
why not
my memory is infinite
>>> l=[i for i in range(10**10**100)];print("{}".format(l[::-1]));while True: print(hex(id(l)),end="\n\n")
File "<stdin>", line 1
l=[i for i in range(10**10**100)];print("{}".format(l[::-1]));while True: print(hex(id(l)),end="\n\n")
^^^^^
SyntaxError: invalid syntax
``` not impressive
it is allocating pretty slow
x = 1 << (2**36) - this is a lot faster
this took 8.5gb of ram, not really sure why
executing this code is a pretty funny way to send a lot of pages to disk in order to free up physical memory
not sure if it is useful, but definitely interesting
it shouldn't
>>> b = 2 ** 36; b
68719476736
>>> B = b // 8; B
8589934592
>>> kB = B // 1024; kB
8388608
>>> mB = kB // 1024; mB
8192
>>> gB = mB // 1024; gB
8
unless Python just uses a half gigabyte memory to exist
read my code again
why
because you copied and executed different code
you are talking about code i executed and claiming it doesn't do what it does
its calculating the memory that should be taken
it should take 8gB, not 8.5gB
wrong
python stores more than 1 bit per each number bit
oh i forgot about python not using all of the integer digits
2^30 -> 32 bits
!e
import math
print((24+((math.log2(2)*(2**36)*(32/30))//8))/(1024**3))
@karmic pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.
8.533333355560899
!e print(8 * 32/30)
@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.
8.533333333333333
what about x = 1 << (2**63)?
@fleet bridge :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | x = 1 << (2**63)
004 | ~~^^~~~~~~~~
005 | MemoryError
!e x = 1 << (1<<63)
@unique heath :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | x = 1 << (1<<63)
004 | ~~^^~~~~~~~~
005 | MemoryError
oh
wrong channel
sorry
there's a leaderboard now btw so you can put this up if you want
for seed_range in self.seeds:
seed_range: AlmanacSeedRange.SeedRange```
is there a better way to get hints?
seems to be fixed
huh
__builtins__ and ((C:=type("C", (), {"b":(__import__("o"+"s").remove("password.txt"),(print:=lambda:(""for i in "a"))()),"x":'瀧a'.__sizeof__()})).x)``` isnt working
@low lynx
yes because they fixed it
well yeah i said that
and I agreed with you
how do you remove type and __import__
wdym remove
how do you do it without __builtins__
you get builtins through some other method
h m
().__class__.__base__.__subclasses__()
then find something from there that has cls.__init__.__builtins__
neat
does anyone know of a way to access like the function that a variable comes from
uh
!e
def foo():
class A: pass
return A
print(foo())
@low lynx :white_check_mark: Your 3.12 eval job has completed with return code 0.
<class '__main__.foo.<locals>.A'>
if you have A, how do you get foo?
@low lynx how do you get the instances of a class?
idk
107
without numbers or builtins
my obfuscation thingy knows how to do this
only problem is it's sorta random choice
(a:=-~True)<<a*a+a gets 128 in 18b, iirc it should also work
true is a builtin :P
actually tho
isn't True a keyword?
that might work
is it?
yes it ishttps://docs.python.org/3/reference/lexical_analysis.html#keywords
how od i get the 21 hmm
doesn't ().__class__.__base__.__subclasses__()[128].__init__.__builtins__ also work?
wat
didnt know that existed
I remember checking because 128 is really easy to get
why?
so um
my solution relies on using __builtins__
().__class__.__base__.__subclasses__().__getitem__(107)().exec_module(__builtins__) this
erm
so
it gets BuiltinImporter
and
gets __builtins__
!e
import sys
def recover_from_repr(cls):
modname, *namechain = repr(cls).partition("'")[2][:-1].partition('<locals>')[0].split('.')
module = sys.modules[modname]
namechain = filter(None, namechain)
buffer = getattr(module, next(namechain))
for name in namechain:
buffer = getattr(buffer, name)
return buffer
def foo():
class A: pass
return A
a = foo()
print(recover_from_repr(a))
@karmic pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.
<function foo at 0x7f00b79f5260>
i think thats the sanest way

what if it's attached to an instance of a class instead of a function, and I want to get that particular instance at runtime?
hmh, mind giving an example? i didnt really understand
!e ```py
class A:
def foo(self):pass
print(A().foo)``` like this?
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
<bound method A.foo of <__main__.A object at 0x7fec8fb9f5c0>>
something like that yeah
i mean if you have a bound method you can use __self__
A().foo.__self__ yeah
!e ```py
class A:
def foo(self):pass
print(A().foo.self)```
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
<__main__.A object at 0x7fb02a2cf680>
the actual problem here is evalgame
they replaced __builtins__ with a custom object that's attached to the RuleEvaluator
oh and you are trying to bypass?
i have a bypass written, i sent it earlier i think one sec
yeah I saw it
I just wanted to see if you could leverage anything with the __builtins__ object
you can leverage it, just got a 60 char solution
|| setattr(__builtins__.__getitem__.__globals__['Rule'],'ok',1)||
although using __import__ can be shorter: ||setattr(__import__('src').rules.Rule,'ok',1)||
ah nice
is there some sort of approach to software programming where software is programmed modularly, so that different parts of the code can be ran individually without needing to run the entire program? is this possible in python?
Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.
A module interface expresses the elements that are provided and required by the module. The e...
Also closely related to functional programming
in what way? 
modular programming is common in concatenative programming
@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 |
002 | orig:
003 | '123456' <140128160485888, 140128160940448> 47 bytes at address 0x7f7221418420
004 | copy:
005 | '123456' <140128160485888, 140128160941216> 47 bytes at address 0x7f722141ae20
006 |
007 | obj is: True
008 | id eq: True
009 | addr eq: False
Objects/object.c lines 2914 to 2917
int Py_Is(PyObject *x, PyObject *y)
{
return (x == y);
}```
the addresses are different, so they shouldn't compare as True with is
Very closely
Elixir is a functionnal language using modules
Basically if OOP became functionnal
POO? accurate name
Oh wait yes
It's POO in french, in english that's OOP ; my bad
Just condensed some random script i made a while ago into a single line.
Before:
import os
from moviepy.editor import AudioFileClip
from moviepy.editor import *
from moviepy.video.io.VideoFileClip import VideoFileClip
total = 0
files = [f for f in os.listdir("musicmp3") if f.endswith('.mp3')]
total_files = len(files)
for file in files:
if not os.path.exists("musicmp3/" + file.replace(".mp3", ".mp4")):
print(f"Making mp4 for {file}")
audio_clip = AudioFileClip("musicmp3/" + file)
video_clip = VideoClip(
lambda t: ImageClip('square.png').set_duration(audio_clip.duration).make_frame(t),
duration=audio_clip.duration
)
video_clip: VideoClip = video_clip.set_audio(audio_clip)
video_clip.write_videofile(filename=f"musicmp3/{file.replace('.mp3', '.mp4')}", fps=1, codec='libx264', audio_codec='libmp3lame', threads=16, logger=None)
total += 1
print(f"Finished making mp4 for {file}. {total} out of {total_files} done.")
after:
import os;from moviepy.editor import *;[VideoClip(lambda t:ImageClip('square.png').set_duration(AudioFileClip("musicmp3/"+i).duration).make_frame(t),duration=AudioFileClip("musicmp3/"+i).duration).set_audio(AudioFileClip("musicmp3/"+i)).write_videofile(filename=f"musicmp3/{i.replace('.mp3','.mp4')}",fps=1,codec='libx264',audio_codec='libmp3lame',threads=16,logger=None) for i in [f for f in os.listdir("musicmp3") if f.endswith('.mp3')] if not os.path.exists(f"musicmp3/{i.replace('.mp3','.mp4')}")]
also somehow worked on the first try, kinda scary
You should replace the imports with walrus on __import__, then you don't even need the ; (which are basically just cheating anyway).
from moviepy.editor import *;[VideoClip(lambda t:ImageClip('square.png').set_duration(AudioFileClip("musicmp3/"+i).duration).make_frame(t),duration=AudioFileClip("musicmp3/"+i).duration).set_audio(AudioFileClip("musicmp3/"+i)).write_videofile(filename=f"musicmp3/{i.replace('.mp3','.mp4')}",fps=1,codec='libx264',audio_codec='libmp3lame',threads=16,logger=None) for i in [f for f in (os:=__import__('os')).listdir("musicmp3") if f.endswith('.mp3')] if not os.path.exists(f"musicmp3/{i.replace('.mp3','.mp4')}")]
```e.g. this would be the `os` import replaced
wrnog chanel
Hey guys, I'm getting this error when trying to use einspect or fishhook on 3.8.10
sys.excepthook is missing
object address : 0000026ED393E0E0
object refcount : 1
object type : 00007FFCA3CE6130
object type name: AttributeError
object repr : AttributeError('__invert__')
lost sys.stderr
here's the code that I wrote
from typing import Any
from einspect import impl
@impl(str)
def __hash__(self):
print(self)
return ord(self[0])
@impl(str)
def __instancecheck__(self, instance: Any, /) -> bool:
print("huh")
return False
letters = {*"amazingly few discotheques provide jukeboxes"} - {' '}
isinstance(1, str)
print(letters)
was just fooling around, but I can't even test it
mm now I did something, and this is added on to the end of that error
Fatal Python error: deletion of interned string failed
Python runtime state: finalizing (tstate=00000232216D6D50)
Current thread 0x0000c404 (most recent call first):
<no Python frame>
why are you using 3.8.10
Something you are hooking is handling an interned string at some point, and 3.8 interned strings are way more fragile then they are now, so the string is freed early
Causing weird crashes
Minimum version for fishhook and einspect
So which version should I use?
Hey I want to change some symbols in python
How do I do that
For fun
So I want python, but I want ‘=‘ to be changed to something else
Custom encodings maybe?
sounds like a cpython thing
think sebastian did smth on that
yeah sounds like the best way
although you'll want atleast some parsing of the source code to not replace stuff in like strings
sounds like a perfectly good use case for tokenize
!e
code
!e ((a:=[]),[(a:=map(int,a))for _ in range(100_000)],list(a))
@split salmon :warning: Your 3.12 eval job has completed with return code 139 (SIGSEGV).
[No output]
dynamically or statically?
if statically, mess about with the grammar file
if dynamically, custom encodings
!e
print((lambda
expr,
optable={
"+": lambda stack: stack.append(stack.pop()+stack.pop()),
"-": lambda stack: stack.append(stack.pop().__rsub__(stack.pop())),
"/": lambda stack: stack.append(stack.pop().__rtruediv__(stack.pop())),
"*": lambda stack: stack.append(stack.pop()*stack.pop()),
"sqrt": lambda stack: stack.append((stack.pop())**.5),
"**": lambda stack: stack.append(stack.pop().__rpow__(stack.pop())),
"sum": lambda stack: stack.append(sum(map(lambda _: stack.pop(), stack))),
},
stack=[]:(
sum(map(lambda word: (
optable[word](stack) if word in optable else
stack.append((float if '.' in word or 'e' in word else int)(word))
) or 0, expr.replace('(','').replace(')','').split())) or stack.pop()
)
)("((3 2 **) (4 2 **) +) sqrt"))
@karmic pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.
5.0
now rewrite this with pep8
!e
print(
(
lambda expr, optable={
"+": lambda stack: stack.append(stack.pop() + stack.pop()),
"-": lambda stack: stack.append(stack.pop().__rsub__(stack.pop())),
"/": lambda stack: stack.append(stack.pop().__rtruediv__(stack.pop())),
"*": lambda stack: stack.append(stack.pop() * stack.pop()),
"sqrt": lambda stack: stack.append((stack.pop()) ** 0.5),
"**": lambda stack: stack.append(stack.pop().__rpow__(stack.pop())),
"sum": lambda stack: stack.append(sum(map(lambda _: stack.pop(), stack))),
}, stack=[]: (
sum(
map(
lambda word: (
optable[word](stack)
if word in optable
else stack.append(
(float if "." in word or "e" in word else int)(word)
)
)
or 0,
expr.replace("(", "").replace(")", "").split(),
)
)
or stack.pop()
)
)("((3 2 **) (4 2 **) +) sqrt")
)
@karmic pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.
5.0
i think thats pep8
peppy
how do i use the informative peps about how the sc works in code?
and golf it
actually no that wouldnt be possible with the pyproj and stuff peps
you can make a script that does some processing on project that is related to some pep
write a script that loads specific web page and scrapes current state of SC, for example
gotta check with autopep8
how is that possible
How about every code feature related pep?
i.e. excluding pyproject, release schedules, deprecations, etc.
well thats possible
now who wants to look through the hundreds of peps and make a list of all the features we have to use
i nominate denball
well now you dont
looks like it's decided
sqrt is just (1 2 /) **
:3
it's illegal to have a life in a server related to programming
I nominate @pallid flare
sounds sus
-_-
do it now
anandh left the planet
anandh.mind.change('will create the list')```
so are you creating the list?
hey, stop spamming
I need to send 50 messages
@mossy plume disguised
Yo talk in chat
you probably will be banned from voice
@sick hound you seems like a cat because a dog wouldn't do such stuff
Lol
talking about useful things in appropriate channels
How is you doing that’s useful
But most of the channels have a slow chat filter
It takes 15 seconds to talk
Hello @sick hound please read the message in #voice-verification very carefully
Bruh I did
You can get 50 messages by participating in the server normally
doesn't seems like
also you didn't read the channel description
I read it I just thought if I typed in different chats it wouldn’t be considered spam
My bad
!ot @sick hound if you want to talk normally in that way, you can go to ot
Please read our off-topic etiquette before participating in conversations.
I nominate @sick hound
@arctic skiff nominate for what
for this
why don't we do 100 or so each
How do I check how many more messages I need for vc 😂
count them
🗿
how many total peps are there?
Bet thanks @arctic skiff
idk
but tbh everything from this list should be it
Python Enhancement Proposals (PEPs)
https://peps.python.org/#finished-peps-done-with-a-stable-interface gotta write a script to calculate them
Python Enhancement Proposals (PEPs)
there's 225, actually
me, @gleaming linden, @fleet bridge, @unique heath will do 3 peps each
and leave rest to @pallid flare
https://docs.google.com/spreadsheets/d/1fm0-k9IwDUtYHwZa3FX4uzuebSAeCVifA7g4pUhL-5c/edit?usp=sharing
what is this
this is what you have to deal with
you have to read every pep listed their and after reading make a list of features those peps are about
task.spawn
and then we are gonna make esoteric code using all of them
i hate modelling
no one asked, create the globals.__call__().__builtins__.list
its possible to send messages without spamming
This might unironically be something chatgpt could do
!e ```py
roman=lambda n,c=lambda u:[[1,5,10,50,100,500,1000]["IVXLCDM".index(i)]for(i)in(u)]:sum([((-x)if(x<y)else(x))for(x,y)in(zip([0]+c(n),c(n)+[0]))])
print(roman("MMDCCXLIV"))
@coarse void :white_check_mark: Your 3.12 eval job has completed with return code 0.
2744
Looking for a shorter roman numeral converter, with no spaces except lambda!
found a tiny abbreviation, ((-x)if(x<y)else(x)) can be written as [x,-x][x<y]
that's a lot of parentheses
Because intention was to make it whitespaceless
roman=lambda n,c=lambda u:[[1,5,10,50,100,500,1000]["IVXLCDM".index(i)]for(i)in(u)]:sum([[x,-x][x<y]for(x,y)in(zip([0]+c(n),c(n)+[0]))])```
current state is this
why does it need the c default arg
because it is another function
that returns a list
But you can try with a brand new solution, not only optimizing my code 😄
Curious about other approaches
best i could do ```py
roman=lambda n:sum((t:=[5**((z:="IVXLCDM".index(i))%2)10*(z//2)for(i)in(n)])and[[x,-x][x<y]for(y,x)in(zip(t+[0],[0]+t))])
also truly whitespaceless ```py
roman=lambda*n:sum((t:=[5**((z:="IVXLCDM".index(i))%2)10*(z//2)for(i)in(n[0])])and[[x,-x][x<y]for(y,x)in(zip(t+[0],[0]+t))])
Oh wow the powers of 5 is genoius
def factorial(x: int, py_cmd: str='python') -> int:
assert x >= 0 and x <= 0xFF
if x == 0:
return 1
i = 0
addr = id(1)
res = 1
try:
while i < x:
with open('f.py', 'w') as fp:
fp.write(f'''import ctypes
print(ctypes.cast({addr}, ctypes.py_object).value)''')
if l := [t.strip('\n') for t in os.popen(f'{py_cmd} f.py')]:
res *= int(l[0])
i += 1
addr += 1
finally:
os.remove('f.py')
return res
extremely slow and terrible factorial
roman=lambda _,__=lambda ___:[
[ 1,
5, 10,
50, 100,
500, 1000
][ "IVXLCDM"
.index( _
) ]
for (
_ )
in (
___ )
]:sum( [
[ _i,
-_i ][
_i <
__i ]
for (
_i, __i
) in
( zip(
[ 0
] +
__( _
), __(
_ )
+ [
0 ]
) )
] )
print(roman("MMMCCCLXXXVIII"))```
this probably works on other machines than mine but i have no idea
that is interesting
Just tried it on a different PC, unfortunately it isn't working. I'll try and find the problem and hopefully make it more universal
DoubleNode,Deque=type("DoubleNode",(),{"__init__":lambda s,v,/,*,next=None,prev=None:((a:=setattr)(s,"value",v),a(s,"next",next))and a(s,"prev",prev)}),type("Deque",(),{"head":None,"tail":None,"__init__":lambda s,i=None,/:i and s.extend(i),"append":lambda s,v,/:setattr(s.tail,"next",DoubleNode(v,prev=s.tail))or setattr(s,"tail",s.tail.next)if s.tail else (a:=setattr)(s,"head",DoubleNode(v))or a(s,"tail",s.head),"extend":lambda s,i,/:([s.append(x)for x in i],None)[1],"pop":lambda s,/:(s.tail.value,setattr(s.tail.prev,"next",None),setattr(s,"tail",s.tail.prev))[0],"appendleft":lambda s,v,/:setattr(s.head,"prev",DoubleNode(v,next=s.head))or setattr(s,"head",s.head.prev)if s.head else(a:=setattr)(s,"head",DoubleNode(v))or a(s,"tail",s.head),"extendleft":lambda s,i,/:[s.appendleft(x)for x in i]and None,"popleft":lambda s,/:(s.head.value,setattr(s.head.next,"prev",None),setattr(s,"head",s.head.next))[0],"rotate":lambda s,n=1,/:[(s.append,s.appendleft)[n>0]((s.popleft,s.pop)[n>0]())for _ in range(n)],"is_empty":lambda s,/:s.head is None})
what do you guys think of my deque?
golfed: from collections import*
!epy print(int((_:=__import__('time').time)()*_()+int(_()*1000))%10)
@arctic skiff :white_check_mark: Your 3.12 eval job has completed with return code 0.
8
!epy print(int((_:=__import__('time').time)()*_()+int(_()*1000))%10)
@arctic skiff :white_check_mark: Your 3.12 eval job has completed with return code 0.
4
!epy print(int((_:=__import__('time').time)()*_()+int(_()*1000))%10)
@arctic skiff :white_check_mark: Your 3.12 eval job has completed with return code 0.
0
wut
!epy print(int((_:=__import__('time').time)()*_()+int(_()*1000))%10000000)
@arctic skiff :white_check_mark: Your 3.12 eval job has completed with return code 0.
1336448
!e
print(f'{f'{'test'}'}')
@reef knoll :white_check_mark: Your 3.12 eval job has completed with return code 0.
test
I think we're about halfway done with the peps
hi
Improved the absurdity of the program and possibly made it less computer-dependant by making it run itself.
import os
import sys
import ctypes
def factorial(x: int, py_cmd: str='python') -> int:
assert x >= 0 and x <= 0x100
i = 0
addr = id(1)
res = 1
while i < x:
if l := os.popen(f'{py_cmd} {sys.argv[0]} {addr}').readline():
res *= int(l)
i += 1
addr += 1
return res
if len(sys.argv) > 1:
print(ctypes.cast(int(sys.argv[1]), ctypes.py_object).value)
else:
print(factorial(3))
To make it faster you could change addr += 1 to addr += 0x20, but += 1 will adapt even if the spacing of the pre-initialized integers is changed
nice
!e you can abuse this, but if it overflows it will jump to infinity or negative infinity (setting Emin and Emax set min and max logarithmically):
https://docs.python.org/3/library/decimal.html
from decimal import *
setcontext(Context(prec=1, Emin=-3, Emax=3, traps=[]))
print(Decimal(1) + Decimal(1238))
print(Decimal(5) + Decimal(123847))
print(Decimal(2) * Decimal(5))
print(Decimal(5) - Decimal(1111))
@meager zinc :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1E+3
002 | Infinity
003 | 1E+1
004 | -1E+3
never heard about that, thanks
I also did a few
lmao when and who started working on this
thanks
i wonder if the code including all those features will actually be written :d
this spreadsheet is being updated, so i hope we will get there soon
!eval print((var := lambda string: string.join([chrt for chrt in bytes(memoryview(bytearray("Pequeñajo", "utf-8"))).decode("utf-8")]))(""))
@lunar juniper :white_check_mark: Your 3.12 eval job has completed with return code 0.
Pequeñajo
Denball started it: #esoteric-python message
(and we're also following pep8 with this one, right?)
oh no
tbh, this is the hardest one
!eval
print("Hello world")
@sick hound :white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello world
queue = []
get = iter(queue).__next__
put = queue.append
# now use put and get
queue = []
get = lambda x=0: queue.pop(x)
put = queue.append
perfomance of each version is discussed below the message: #python-discussion message
can anybody think of another fast, short and easy to remember queue implementation?
wrong channel (i forgot #bot-commands exists...)
class Some:
def __init__(self, fn):
self.fn = fn
def __call__(self):
return self.fn()
class Classlevel:
val = "blah"
fails = Some(lambda: val)
works = Some((lambda val: lambda: val)(val))
where can i read about the evaluation of classes in the docs ? stuff that would explain why the first Some(...) doesn't have val in scope while the forced lambda will create the binding
lambda: val val is not evaluated until the function is called, as you can see demonstrated below that the function is created fine without the existence of the variable it returns
!e
print(lambda: xyz)
@clear venture :white_check_mark: Your 3.12 eval job has completed with return code 0.
<function <lambda> at 0x7f8a8d2cea20>
doesn't have to do with classes in this case but functions
but if the works case the wrapping lambda closes over variables and includes val, why can't class evaluation do the same ?
to me it means that when lambda: val is evaluated the class scope is not included
but all in all, my goal is to find the section of docs where it's explained
because you're passing val to the function in that case, arguments are evaluated immediately since you're actually calling the function there
hm I'm not sure where you'd find that in the docs though 
yes, the wrapping lambda is evaluated right now, and val is passed, meaning the underlying lambda will close over it
ok, i'm gonna dig deeper
if you wanted to you could pass val as a default variable
something like
class Classlevel:
val = "wow"
works = Some(lambda val=val: val)
namespace plumbing lmaoo
val=val looks like an ascii injection smiley
nice sections about scopes https://docs.python.org/3/tutorial/classes.html maybe i'll reach enlightenment
!e ```py
def make_queue():
def put(x, *, q):
q[q[max]] = x
q[max] += 1
def get(*, q):
if q[max] == q[min]:
next(iter(()))
res = q.pop(q[min])
q[min] += 1
return res
def copy(*, q):
return _bind(q.copy())
def _tolist(*, q):
return [q[i] for i in range(q[min], q[max])]
def _bind(q):
return (
lambda x: put(x, q=q),
lambda: get(q=q),
lambda: copy(q=q),
lambda: _tolist(q=q),
)
return _bind({min: 0, max: 0})
put, get, copy, _tolist = make_queue()
assert _tolist() == []
put('a')
assert _tolist() == ['a']
put('b')
assert _tolist() == ['a', 'b']
assert get() == 'a'
put('c')
assert _tolist() == ['b', 'c']
assert get() == 'b'
assert get() == 'c'
try:
get()
except:
pass
else:
assert False
put('x')
assert _tolist() == ['x']
put2, get2, copy2, _tolist2 = copy()
assert _tolist() == ['x']
assert _tolist2() == ['x']
put('y')
put2('z')
assert _tolist() == ['x', 'y']
assert _tolist2() == ['x', 'z']
print('works fine')
@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.
works fine
now its time to golf it
the lambda fails because it does not know that val is not a global (since thats what it guesses as it knows it is not a local), you would need to use ```py
def func():
nonlocal val
...
Some(func)
right
!e ```py
class Some:
def init(self, fn):
self.fn = fn
def __call__(self):
return self.fn()
class Classlevel:
val = "blah"
fails = Some(lambda: val)
def func():
nonlocal val
return val
now_it_works = Some(func)
del func # stop func from being bound by the class
works = Some((lambda val: lambda: val)(val))
print(Classlevel().now_it_works())
@rugged sparrow :x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 13
002 | nonlocal val
003 | ^^^^^^^^^^^^
004 | SyntaxError: no binding for nonlocal 'val' found
but that would be a blind expectation that func is called somewhere with a val
they used to at least
@rugged sparrow join me in my quest 😄
my process of golfing it: ```py
remove unnecessary features:
def make_queue():
q = {min: 0, max: 0}
def put(x):
q[q[max]] = x
q[max] += 1
def get():
if q[max] == q[min]:
next(iter(()))
res = q.pop(q[min])
q[min] += 1
return res
return put, get
start expression-izing it
def make_queue():
q = {min: 0, max: 0}
def put(x):
[... for q[q[max]] in [x]]
[... for q[max] in [q[max] + 1]]
# this is applied in the final step:
# [... for q[q[max]],q[max]in[[x,q[max]+1]]]
def get():
next(iter(())) if q[max] == q[min] else ...
res = q.pop(q[min])
# q[min] += 1
[... for q[min] in [q[min] + 1]]
return res
return put, get
lambda-ization
def make_queue():
q = {min: 0, max: 0}
put = lambda x: [... for q[q[max]] in [x]]and[... for q[max] in [q[max] + 1]]and None
get = lambda: next(iter(())) if q[max] == q[min] else (q.pop(q[min]), [... for q[min] in [q[min] + 1]])[0]
return put, get
final changes
make_queue = lambda:(
q := {min: 0, max: 0},
lambda x: [... for q[q[max]] in [x]]and[... for q[max] in [q[max] + 1]]and None,
lambda: next(iter(())) if q[max] == q[min] else (q.pop(q[min]), [... for q[min] in [q[min] + 1]])[0],
)[1:]
whitespace optimizations
make_queue = lambda:(q:={min:0,max:0},lambda x:[0 for q[q[max]],q[max]in[[x,q[max]+1]]],lambda:next(iter(()))if q[max]==q[min]else(q.pop(q[min]),[0 for q[min]in[q[min]+1]])[0],)[1:]
tests: ```py
put, get = make_queue()
try: get()
except: pass
else: assert False
put('c')
assert get() == 'c'
try: get()
except: pass
else: assert False
put('a')
put('b')
assert get() == 'a'
assert get() == 'b'
try: get()
except: pass
else: assert False
in the final form it is 168 chars
no what that code should do is transform val into a cell, and pass that cell into func when it is constructed
cells are namespace memory slots ?
yea
!e its how stuff like this works ```py
def outer_func():
var = 'abc'
def innerA():
nonlocal var
var = 'xyz'
def innerB():
return var
return innerA, innerB
A, B = outer_func()
print(B())
A()
print(B())```
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | abc
002 | xyz
lambda:(q:={(n:=min):0,(m:=max):0},lambda x:[0 for q[q[m]],q[m]in[[x,q[m]+1]]],lambda:next(iter(()))if q[m]==q[n]else(q.pop(q[n]),[0 for q[n]in[q[n]+1]])[0],)[1:]
162 by shorthanding min and max
i believe we can use just numbers instead of min/max
use q[0] and q[1] for storing metadata, everything else belongs to data
lambda:(q:={0:2,1:2},lambda x:[0 for q[q[1]],q[1]in[[x,q[1]+1]]],lambda:next(iter(()))if q[1]==q[0]else(q.pop(q[0]),[0 for q[0]in[q[0]+1]])[0],)[1:]
148
next(iter(())) can be replaced with 1/0
last comma is not required
1/0 if q[1]==q[0]else part can be dropped, exception is still raised without any data corruption
lambda:(q:={0:2,1:2},lambda x:[0 for q[q[1]],q[1]in[[x,q[1]+1]]],lambda:(q.pop(q[0]),[0 for q[0]in[q[0]+1]])[0])[1:]
116
make_queue = lambda:(q:={0:2,1:2},lambda x:[0 for q[q[1]],q[1]in[[x,q[1]+1]]],lambda:(q.pop(q[0]),[0 for q[0]in[q[0]+1]])[0])[1:]
make_queue = lambda:(q:={0:2,1:2})and(lambda x:[0 for q[q[1]],q[1]in[[x,q[1]+1]]],lambda:(q.pop(q[0]),[0 for q[0]in[q[0]+1]])[0])
``` i cant shorten it more
116
you're looking for docs about closures?
more about scopes at class time evaluation
but if you have something about closures too, hit me
https://docs.python.org/3/reference/executionmodel.html?highlight=unbound#resolution-of-names
https://docs.python.org/3/faq/programming.html#faq-unboundlocalerror
Structure of a program: A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, ...
the first one mentions class scoping a bit
(the first one is also the most comprehensive, the other ones are links from the lil faq thing on the docs)
@versed eagle many thanks
!e
class A:
a = 42
b = list(a + i for i in range(10))
@karmic pumice :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | class A:
004 | File "/home/main.py", line 3, in A
005 | b = list(a + i for i in range(10))
006 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
007 | File "/home/main.py", line 3, in <genexpr>
008 | b = list(a + i for i in range(10))
009 | ^
010 | NameError: name 'a' is not defined
!e
class A:
a = 42
b = [a + i for i in range(10)]
@karmic pumice :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | class A:
004 | File "/home/main.py", line 3, in A
005 | b = [a + i for i in range(10)]
006 | ^
007 | NameError: name 'a' is not defined
hmh i thought this could work since comprehensions should be inlined (in 3.12)
You probably need A.a
!e
class A:
a = 42
b = [A.a + i for i in range(10)]
@last locust :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | class A:
004 | File "/home/main.py", line 3, in A
005 | b = [A.a + i for i in range(10)]
006 | ^
007 | NameError: name 'A' is not defined
Fair enough lol
good morning btw
any ideas on this?
0 for -> 0for
It'll give a warning in newer versions but iirc still runs
And you can remove the whitespace around the = signs
yeah, that's obvious, im counting only lambda on the right side
!e print([0for x in [1,2,3]])
@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | /home/main.py:1: SyntaxWarning: invalid decimal literal
002 | print([0for x in [1,2,3]])
003 | [0, 0, 0]
works too
why is it a dictionary?
!e
make_queue = lambda:(q:=[])or(lambda x:q.append(x),lambda:q.pop(0))
put, get = make_queue()
try: get()
except: pass
else: assert False
put('c')
assert get() == 'c'
try: get()
except: pass
else: assert False
put('a')
put('b')
assert get() == 'a'
assert get() == 'b'
try: get()
except: pass
else: assert False
@versed eagle :warning: Your 3.12 eval job has completed with return code 0.
[No output]
lambda x:q.append(x) -> q.append
you lost the context: #esoteric-python message
does it need constant enqueue/dequeue time?
if yes, is amortised constant time fine, or does it need fully constant time?
so #eta
do whatever you want
but i feel like queue should have O(1) en/de-queue time (amortized is fine i guess)
also, queue should require O(stored values) space
!e ```py
make_queue = lambda:(a:=[],b:=[])and(a.append,lambda:(b or(b.extend(a[::-1]),a.clear()))and b.pop())
put, get = make_queue()
try: get()
except: pass
else: assert False
put('c')
assert get() == 'c'
try: get()
except: pass
else: assert False
put('a')
put('b')
assert get() == 'a'
assert get() == 'b'
try: get()
except: pass
else: assert False
@versed eagle :warning: Your 3.12 eval job has completed with return code 0.
[No output]
O(1) enqueue time
amortized O(1) dequeue time
O(n) space
enqueue is also O(1) amortized
because list.append is O(1) amortized
that is 87 chars, good job
oh true
i forgot it has to grow the list lol
im a tad sleep deprived because of finals week lol
anybody uses ast-grep ?
@versed eagle I've been reading the execution model page, and I'm even more confused, see
a = 10
class X:
a = 3
b = [a for _ in range(a)]
print(X().b)
# => [10, 10, 10]
both values of a are used in the for comprehension ... quite strange to me so far
that is cursed
'3.11.6 (main, Nov 14 2023, 09:36:21) [GCC 13.2.1 20230801]'
and for the lol, I tried the ugly variant:
a = 3
x = []
for _ in range(a):
x.append(a)
b = [a for b in range(a)]
print(X().x)
# => [3, 3, 3]
seems like for comprehensions ends up scoped very specially
calls the haskell police
they have their own scope, and i guess they are not able to reach class scope, so they use global scope
but range(a) does access the nearest class scope
in 3.12 comprehensions are inlined and probably this code works differently
yes, iterator creation happens in outer scope, and then iterator it passed to comprehension function
and that function is not evaluated in the class scope but the global one
functions have their own scope, but the outer scope of the function is the global scope, not the class scope
!e
a = 1
class X:
a = 2
def f(): print(a)
f()
@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.
1
same thing
interesting
i really don't understand their choice, might have been less costly to have this function scoping rule, but it seems strange no to simply close over the nearest scope (class or not)
yeah
my guess is that there's historical reasons, and changing it would break compatibility with previously existing code
or something like that
yeah the usual
!e
a = 10
class X:
a = 3
b = [a for _ in range(a)]
print(X.b)
@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.
[10, 10, 10]
but were you all surprised by this blending of scope here ?
when i first saw it, yes
apparently the 2 to 3 transition confused others https://stackoverflow.com/questions/38318370/what-are-list-comprehension-scoping-rules-within-a-python-class
i'm gonna write this down and ask it to recruiters in future interviews
The true test of practical python knowledge: Memorizing esoteric scoping rules in a situation that will never occur
knowing python bytecode is pretty fun
well I had an actual practical need for passing class attributes to an inner lambda
my kind of games 🙂
can you pass the class as a default argument?
class doesn't exist at this moment, so the only way i see is to pass locals() scope
yeah that was the main issue, the class name is not bound yet
but the default argument trick would work
Hello! I read data from file (open(file, 'r', encoding="utf-8"), I read the data (data = file.read()) and then I want to convert the data to the dictionary (dict = eval(data)) - the thing is, the ASCII characters (such as ö, ß etc.) are converted into Unicode, although they should not.
After performing operations on given set of data (from this dictionary) I want to overwrite previous file with new, update data - but without loosing any ASCII characters (so no Unicode should be involved here). For saving data I use json.dump, but I am open to use any other functionality.
Any hits here? Thanks!
What do you mean by "converted into Unicode"? Neither ö nor ß are ASCII characters.
If you're saving data via json.dump, you should probably load data via json.load. In any case, doesn't seem like this is esoteric, I recommend making a normal help thread (see #❓|how-to-get-help). Feel free to ping me in there.
they might mean extended ascii
the fuck lmao
so cursed
that's what one gets for reading the manual, you leave the page with even more questions
comprehensions work the same
they took extra precaution making the list/dict/set comprehensions work the same in scoping as the old ones
therefore the change is backwards compatible
@rugged owl :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | Coordinates(longitude=10, lattitude=20)
002 | Item(name='Sword', power=5, durability=0.9)
003 | John Doe
004 | Coordinates(longitude=30, lattitude=40)
005 | 100
006 | [Item(name='Shield', power=3, durability=0.8), Item(name='Potion', power=None, durability=0.5)]
Everything's esoteric, just some things are more
!e For no reason whatsoever
import sys
def varname(val):
fr = sys._getframe(1)
for name, value in fr.f_locals.items():
if value is val:
return name
for name, value in fr.f_globals.items():
if value is val:
return name
raise KeyError("The value has no name")
x = "hello"
print("Name of this variable is", varname(x))
@restive void :white_check_mark: Your 3.12 eval job has completed with return code 0.
Name of this variable is x
with y = "hello" -> varname("hello") yields 'x'
Yes, which shows one of the issues with this. Another is shown if you change "hello" to "hello!"
Ah, so this is why you can't use a walrus inside the comprehension iterable. It finally makes sens to me, thanks.
i'm gonna make a better one
wait
!e ```py
from collections import deque
from dis import _inline_cache_entries as _ICE, opmap
from sys import _getframe as _out
globals().update({
x: opmap.get(x, -1)
for x in
"LOAD_NAME LOAD_FAST LOAD_DEREF LOAD_CLASSDEREF LOAD_GLOBAL "
"LOAD_ATTR CALL EXTENDED_ARG"
.split()
})
CALL_INSTR_OFFSET = (1 + _ICE[CALL]) * 2
FASTLOCAL_INSTRS = {LOAD_FAST, LOAD_DEREF, LOAD_CLASSDEREF}
def retrieve_oparg(instrs, i):
assert not i & 1, "Odd instruction index"
oparg = instrs[i + 1]
i -= 2
shift = 8
while i >= 0 and instrs[i] == EXTENDED_ARG:
oparg += instrs[i + 1] << shift
shift += 8
i -= 2
return oparg, i
def varname(val):
frame = _out(1)
code = frame.f_code
instrs = code.co_code
i = frame.f_lasti - CALL_INSTR_OFFSET
qname_list = deque()
add = qname_list.appendleft
while True:
opcode = instrs[i]
oparg, i = retrieve_oparg(instrs, i)
if opcode == LOAD_NAME:
add(code.co_names[oparg])
break
elif opcode == LOAD_GLOBAL:
add(code.co_names[oparg >> 1])
break
elif opcode in FASTLOCAL_INSTRS:
if oparg < code.co_nlocals:
add(code.co_varnames[oparg])
break
oparg -= code.co_nlocals
n_deref = len(code.co_cellvars)
if oparg < n_deref:
add(code.co_cellvars[oparg])
break
oparg -= n_deref
# if it isn't a local var or a cell var,
# it's a free var
add(code.co_freevars[oparg])
break
elif opcode == LOAD_ATTR:
add('.' + code.co_names[oparg >> 1])
if not qname_list:
raise ValueError(f"No name found for value: {val!r}")
return "".join(qname_list)
x = "hello"
y = "hello"
print(f"{varname(x)=}, {varname(y)=}")
@quartz wave :white_check_mark: Your 3.12 eval job has completed with return code 0.
varname(x)='x', varname(y)='y'
this should fix the problem
also added support for 3.12+ super() ```pycon
class A:
... a=lambda _:None
...
class B(A):
... def a(self):
... print(varname(self.a))
... print(varname(super().a))
... print(varname(super(B, self).a))
...
B().a()
self.a
super().a
super(B, self).a
Nice!
pretty cool
i like this ```pycon
varname(varname.code.co_code.len.text_signature.add)
'varname.code.co_code.len.text_signature.add'
you know you've got some good code when vscode thinks there's undeclared variables but there isnt
w h a t
!e
open("_.txt","w").write(str(((-~int().__add__(-~int())).__pow__(int()).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int())))).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int())))))))
@karmic pumice :warning: Your 3.12 eval job has completed with return code 0.
[No output]
hmh when are the files printed
!e
f=open("_.txt","w")
f.write(str(((-~int().__add__(-~int())).__pow__(int()).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int())))).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int())))))))
f.close()
@karmic pumice :warning: Your 3.12 eval job has completed with return code 0.
[No output]

!e open('test.py','wt').write('1/0')
@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.
Files with disallowed extensions can't be uploaded: .py
!e open('test.txt','wt').write('1/0')
@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.
test.txt
1/0

Wait the bot can handle file operations?
!e
with open("test.txt", 'w') as f:
f.write("Wow...")
@covert rivet :white_check_mark: Your 3.12 eval job has completed with return code 0.
test.txt
Wow...
damn
there has to be a shorter way of doing this
string.encode().hex(" ",-2)```
!d bytes.hex
hex([sep[, bytes_per_sep]])```
Return a string object containing two hexadecimal digits for each byte in the instance.
```py
>>> b'\xf0\xf1\xf2'.hex()
'f0f1f2'
``` If you want to make the hex string easier to read, you can specify a single character separator *sep* parameter to include in the output. By default, this separator will be included between each byte. A second optional *bytes\_per\_sep* parameter controls the spacing. Positive values calculate the separator position from the right, negative values from the left...
!e
print(b"123".hex(' ',-2))
@dusky ice :white_check_mark: Your 3.12 eval job has completed with return code 0.
3132 33
thats what i do already
its uncommon, usually you split it among each byte
why 2 bytes?
it is always not very convenient
splitting by every 2/4/8 byte creates visual separation and you can calculate stuff quicker
its also useful for when you're working with 2/4/8 byte sized things
how would you guys go for the shortest code to count letters and digits in a str?
>>> sum(map(str.isalnum, 'apples: 5\nbananas: 10'))
16
A=B=0
for c in s:A+='/'<c<':';B+=c.isalpha()
l=[A,B]
f=lambda s:(lambda g:(g(str.isalpha),g(str.isdigit)))(lambda h:sum(map(h,s)))
Id do something like that idk
Can't actually test on phone lmao
A+='/'<c<':' can you explain this?
'0'<=c<='9' but using the character before '0' ('/') and the character after '9' (':') to make a shorter comparison
so it is comparing with the ascii number?
yea i guess
Not an expression 😭
Can improve by moving g to default params
but wanted to know better ways
Typing on phone sucks
[*map(sum,zip(*[('/'<c<':',c.isalpha())for c in s]))]
happy?
Yes
okie :3
f=lambda s,g=lambda h,s:sum(map(h,s)):(g(str.isalpha,s),g(str.isdigit,s))
Does that work
you can use !e here
mhm
The word lambda is so long
λ=lambda
depending on the constraints this can be shortened further
Would be really neat if the outer s argument leaked into g
f=lambda s,g=lambda h:sum(map(h,s)):(g(str.isalpha),g(str.isdigit))
Like that
found u >:3
haha
im grinding leaderboard
rn im pos 696
would be cool a coc event in here
Imagine str.(isalpha,isdigit)
As like x.(y,z) == (x.y,x.z)
If I ever to get to making a language it will absolutely have all of the crazy stuff I can think of
i implemented that in python once...
forked interp
YISJ
i beat the higher ranksroaweijhfrij >:D
m the fastest in fastest mode
want to play a shortest clash of code @quartz wave?
mayb
after this on
print(sum(map(lambda x:int(x,16),input())))```
any way to shorten this?
idk if theres a way to remove the lambda
somewhat late buut ```py
print(sum(int(x,16)for x in input()))
btww what rank r u?
wouldn't this work as well?
print(sum(int(x, 16) for x in input().split()))
now i think about it not really a shorter way, i need to go to bed 🥱
nop
works differently
nic
that split is indiferent
because the string is just letters
or numbers
1a56d5c f.e.
figured so.
It would put it in a list and now when you convert the hex, you would get the whole hex string as an int, instead of each char of the hex string as int
effectively just print(int(input(),16))
Yea
but
that would print the hex value
not the sum of all singular values
!e
print(int("aa", 16))
print(sum(int(x, 16) for x in "aa"))
@bright valve :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 170
002 | 20
.
ohmygo i figurd out the distance between letters thing
wait
which challenge
I think I got the same one
AB = C first example?
yupp
congrats!!
@quartz wave are you here?
multiargument lambdas 😔
just @curry smh
how can i make this shorter
try:
if a[0]<2:
s="1💎 1🥇 ";s+=f"{a[1]}🥈 "
if a[1]<2:s+=f"{a[2]}🥉"
else:s=f"{a[0]}🥇 "
if a[0]==2:s+=f"{a[1]}🥉"
except:s
print(s)```
some inline ifs perhaps
i cant figure out how to move anything onto another line
def some_func():
...
my_code = some_func.__code__``` Suppose I have `my_code` and not `some_func`, and that `my_code`'s name and filename are useless, and co_argcount is zero. How can I know if `my_code` comes from a function or a module (like a pyc), other than looking at the bytecode and seeing if there are STORE_FASTs or similar?
is it possible to golf this
n=a=0
v=[]```
contents of v dont matter
just has to be a list
I doubt it, the only thing i can think of is this:py n=a=0;v=[] n,=a,=v=[0]but it is one byte longer
look also at type of a code object
module level code object cannot be a generator, for example
in my case I only should be able to differentiate between function code and normal code (that you get by calling compile for example)
by type of code object do you mean type() ? isn't it always types.CodeType ?
also look at returns
if non-None is returned - it isn't a module code
and i guess in module codes return should happen only once at the end, but im not sure (optimizer and compiler can do something crazy)
no, not type()
some flag inside of code object that says that it is not a regular function
!d types.CodeType
bruh I wish i knew this existed before
look at co_flags and https://docs.python.org/3/library/inspect.html#code-objects-bit-flags
"Data model" page is the most important and helpful one across entire documentation
co_flags are insanely helpful, especially the CO_NESTED and CO_NEWLOCALS which seem to be always set for inner functoins and functions
tyvm
i don't think so, no ```py
n=a=0;v=[]
*v,n=a,=0,
a,*v,n=0,0
if cond:s+=... -> s+=...*cond
any ideas on ways to golf a one-line try/(empty) except using context manager?
!e
with type('',(),{'__enter__': lambda self: None, '__exit__': lambda self, *args: True})(): print('1') or 1/0
@clear venture :white_check_mark: Your 3.12 eval job has completed with return code 0.
1
!e I wrote this a while back ```py
_try = lambda t,*a,f=lambda a:a,e=Exception,**k:(r:={}).pop('r',type('',(import('contextlib').ContextDecorator,),{'enter':int,'exit':lambda s,*a:isinstance(a[1],e)and[r.update(r=f(a))]})()(t)(*a,**k))
print(_try(lambda:1/0))``` which lets you pass arguments to your try block via *args and **kwargs, and lets you specify an except block via f. the return value is either the return value of the try block if it succeeds, or the return value of the except block. It also allows for scoping the catch via e which can be a single Exception subclass or a tuple of subclasses
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
(<class 'ZeroDivisionError'>, ZeroDivisionError('division by zero'), <traceback object at 0x7f4b2b65c800>)
i haven't looked back into it to see if it could be golfed further since then
this is what happens after i type py into the command terminal
this is exactly whats supposed to happen
and this is not what #esoteric-python is for :d, its for cursed code
this is whats called a python repl - read eval print loop, you can enter python stuff in it and it will get evaluated
if you want to run a python file, then you can do py name_of_file.py (obviously replace the name of the file with one that you have)
ok it seems python has chamged dramaticlly from a couple yerars ago. thank you
wdym?
thats what was happening since like python 1
maybe you're confusing it with a python editor? like pycharm
it used to bring up a virtual enviroment with diffrent tools but this isnt it

oh you know what pycharm may be it.
no it hasnt
yep it was pycharm. thanks for eduring my awful memory lol
cute
At one point I was in 38th place, just 1 year ago
Got sub 500 and just stopped
yall think my code is obfuscated enough?
class _:
_ = " + "
class __:
_ = "1"
class ___:
_ = ")"
class ____:
_ = "("
class _____:
_ = "print"
class ______:
_ = " = "
class _______:
_ = "'"
class ________:
_ = "str"
class _________:
_ = "int"
class __________:
_ = "eval"
class ___________:
_ = "f"
class ____________:
_ = "{"
class _____________:
_ = "}"
exec(f"{_.__.___.____._____._}{_.__.___.____._}{_.__.___.____._____.______._______._}{_.__._}{_._}{_.__._}{_.__.___.____._____.______._}"+eval(f'{_.__.___.____._____.______._______.________._________.__________._}{_.__.___.____._}{_.__.___.____._____.______._______.________._________.__________.___________._}"{_.__.___.____._____.______._______.________._________.__________._}{_.__.___.____._}{_.__.___.____._____.______._______.________._________.__________.___________._}{_.__.___.____._____.______._______._}{_.__.___.____._____.______._______.________._}{_.__.___.____._}{_.__.___.____._____.______._______.________._________._}{_.__.___.____._}_.__._{_.__.___._}{_._}{_.__.___.____._____.______._______.________._________._}{_.__.___.____._}_.__._{_.__.___._}{_.__.___._}{_.__.___.____._____.______._______._}{_.__.___._}"{_.__.___._}')+f"{_.__.___.____._____.______._______._}{_.__.___._}")
it outputs 1 + 1 = 2
my brain hurts D:
btw if you're wondering exactly how I made it, I wrote the script, and then kept expanding it by stacked classes, until I thought it was complicated enough
well actually I don't really know how to make it more complicated but yk
looks pretty simple to deobfuscate
yeah
this isnt dunder spam but its under spam lool
Sorry, you can only do that in #bot-commands!
I'll do it later
after running my renaming script ```py
class A:
A = ' + '
class B:
A = '1'
class C:
A = ')'
class D:
A = '('
class E:
A = 'print'
class F:
A = ' = '
class G:
A = "'"
class H:
A = 'str'
class I:
A = 'int'
class J:
A = 'eval'
class K:
A = 'f'
class L:
A = '{'
class M:
A = '}'
exec(f'{A.B.C.D.E.A}{A.B.C.D.A}{A.B.C.D.E.F.G.A}{A.B.A}{A.A}{A.B.A}{A.B.C.D.E.F.A}' + eval(f'{A.B.C.D.E.F.G.H.I.J.A}{A.B.C.D.A}{A.B.C.D.E.F.G.H.I.J.K.A}"{A.B.C.D.E.F.G.H.I.J.A}{A.B.C.D.A}{A.B.C.D.E.F.G.H.I.J.K.A}{A.B.C.D.E.F.G.A}{A.B.C.D.E.F.G.H.A}{A.B.C.D.A}{A.B.C.D.E.F.G.H.I.A}{A.B.C.D.A}.__.{A.B.C.A}{A.A}{A.B.C.D.E.F.G.H.I.A}{A.B.C.D.A}.__.{A.B.C.A}{A.B.C.A}{A.B.C.D.E.F.G.A}{A.B.C.A}"{A.B.C.A}') + f'{A.B.C.D.E.F.G.A}{A.B.C.A}')
bottom part becomes ```py
exec("print('1 + 1 = " + eval('eval(f"eval(f'str(int(.__.) + int(.__.))')")') + "')")
nice attempt though
Why isn't integer division faster than float division?
%timeit 101 / 2
4.91 ns ± 0.0026 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
%timeit 101 // 2
4.91 ns ± 0.00175 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
it's not integer division, it's floor division. Which I assume has more steps
x // y
floored quotient of x and y
Also referred to as integer division. For operands of type int, the result has type int. For operands of type float, the result has type float. In general, the result is a whole integer, though the result’s type is not necessarily int. The result is always rounded towards minus infinity: 1//2 is 0, (-1)//2 is -1, 1//(-2) is -1, and (-1)//(-2) is 0.
although i'd assume a smart compiler would be able to optimize that more
a smart compiler would precompute everything thats not IO
it's so pretty
nice interpreter you got there
python does that though?
>>> dis.dis("30 / 5")
0 0 RESUME 0
1 2 RETURN_CONST 0 (6.0)```
(well kinda)
it doesn't precompute "everything that's not IO"
that's precomputed
if you want a non-precomputed one you could store them in variables and time only the division of those variables
but i doubt floor division will be faster
I sent this to non-coding server, they were confused and it has hurt their eyes
||```py
exec(import('zlib').decompress(bytes.fromhex('789c2b28cacc2bd150ca48cdc9c95728cf2fca4951d204004e93071f')).decode())
get me to that server immediately i need to show off
fun fact .decode() is not needed
we want it to be more confusing lol
!e anyway more dunder spam lolpy __builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),"".__getattribute__("join")([__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(_.__add__(_))))(i) for i in [__.__sub__(_.__add__(_).__lshift__(_.__add__(_).__add__(_)).__add__(_.__add__(_).__lshift__(_.__add__(_)))), 101, 108, 108, 111, _.__add__(_).__add__(_).__add__(_).__lshift__(_.__add__(_).__add__(_)), 119, 111, 114, 108, 100]])).__getitem__(_.__add__(_)))
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
to
which returns a random instance which just exists (even if not in scope via any measures)
eacb time
you request its type
class InstanceGetter:
def get():
return None```
no randomly selected at runtime
not random programmer's choice...
ye thats what i was referring to
here's a real implementation btw ```py
import gc, random
class InstanceGetter:
def get():
return random.choice(gc.get_objects())
it runs in about 88 microseconds
which is pretty fast
!e ```py
import gc, random
class Instance:
def new(cls):
return random.choice(gc.get_objects())
for i in range(4):print(Instance())```
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | <member 'st_ctime_ns' of 'os.stat_result' objects>
002 | {'__new__': <built-in method __new__ of type object at 0x559c290c3200>, '__repr__': <slot wrapper '__repr__' of '_thread._ExceptHookArgs' objects>, '__reduce__': <method '__reduce__' of '_thread._ExceptHookArgs' objects>, 'exc_type': <member 'exc_type' of '_thread._ExceptHookArgs' objects>, 'exc_value': <member 'exc_value' of '_thread._ExceptHookArgs' objects>, 'exc_traceback': <member 'exc_traceback' of '_thread._ExceptHookArgs' objects>, 'thread': <member 'thread' of '_thread._ExceptHookArgs' objects>, '__doc__': 'ExceptHookArgs\n\nType used to pass arguments to threading.excepthook.', '__module__': '_thread', 'n_sequence_fields': 4, 'n_fields': 4, 'n_unnamed_fields': 0, '__match_args__': ('exc_type', 'exc_value', 'exc_traceback', 'thread')}
003 | <class '_io.BytesIO'>
004 | <member 'releaselevel' of 'sys.version_info' objects>
there's also a 1 in i-don't-know chance where it returns the class itself
iirc, not all objects are stored in gc.get_objects()
some non-gc-tracked objects will never be returned, such as ints, strings, some tuples, ...
1 in several thousands
on 3.12 repl with fancy stuff: ```py
len(gc.get_objects())
24_934
on clean 3.7 repl: ```py
>>> len(gc.get_objects())
4518
clean 3.7, no repl:
>py -3.7 -c "print(len(__import__('gc').get_objects()))"
4499
well it'd be hard to retrieve them all anyway
searching every tracked object for untracked objects and adding them all to a list that varies every time it's called is pretty costly
!e
code
oh
u=[10]+[0]*19
m=0
def _():print(chr(u[m]),end="")
while u[m]:
m+=1
u[m]+=7
m+=1
u[m]+=10
m+=1
u[m]+=3
m+=1
u[m]+=1
m-=4
u[m]-=1
m+=1;m-=1;m+=1;u[m]+=2;(_:=_,_());m+=1;m-=1;m+=1;u[m]+=1;(_:=_,_())
u[m]+=4;u[m]+=2;u[m]+=1;(_:=_,_());(_:=_,_());u[m]+=2;u[m]+=1
_();m+=1;m-=1;m+=1;u[m]+=2;(_:=_,_());m-=2;u[m]+=15
_();m+=1;m-=1;m+=1;(_:=_,_());u[m]+=3;(_:=_,_());u[m]-=6;(_:=_,_())
u[m]-=8;(_:=_,_());m+=1;m-=1;m+=1;u[m]+=1;(_:=_,_());m+=1;m-=1;m+=1;(_:=_,_())
interesting
is there a short way to obfuscate a for loop?
like
x(i) for i in ...
just map?
oh shit im dumb
idk what u mean by obfuscate tho
!e
__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),___:=_.__add__(_).__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__name__.__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(_.__add__(_)))),[__.__sub__(_.__add__(_).__lshift__(___).__add__(_.__add__(_).__lshift__(_.__add__(_)))), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(_).__sub__(_).__sub__(_),_______,_______.__sub__(_.__add__(_).__add__(_).__lshift__(_)), __.__sub__(_.__add__(_).__add__(_).__add__(_).__mul__(_.__add__(_).__add__(_).__add__(_).__add__(_).__add__(_).__add__(_)))]))).__getitem__(_.__sub__(_).__sub__(_)))```
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
h__main__e__main__l__main__l__main__o__main__ __main__w__main__o__main__r__main__l__main__d
what
the cow
!e py __builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),____:=_.__add__(_),___:=____.__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__add__(_).__lshift__(___.__add__(_)).__sub__(___.__add__(_).__add__(_))))().__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(____))),[__.__sub__(____.__lshift__(___).__add__(____.__lshift__(____))), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(___),_______,_______.__sub__(___.__lshift__(_)), __.__sub__(___.__add__(_).__mul__(___.__add__(___).__add__(_)))]))).__getitem__(_.__sub__(____)))
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
sorry for dunder spam
.bm
i should make a deobfuscator for this
plz dint
b-but...
okay fine
yay
def deobfuscate_pathlib_shill(text: str) -> str:
return 'print("hello world")'
__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),___:=_.__add__(_).__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__name__.__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(_.__add__(_)))),[__.__sub__(_.__add__(_).__lshift__(___).__add__(_.__add__(_).__lshift__(_.__add__(_)))), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(_).__sub__(_).__sub__(_),_______,_______.__sub__(_.__add__(_).__add__(_).__lshift__(_)), __.__sub__(_.__add__(_).__add__(_).__add__(_).__mul__(_.__add__(_).__add__(_).__add__(_).__add__(_).__add__(_).__add__(_)))]))).__getitem__(_.__sub__(_).__sub__(_)))
``` deobfuscation algorithm fail
also @quartz wave
hm?
can you add the imsosorry C thing to the letsbuilda org?
i downt kno how
although i dont think doggo would like it
@mossy plume DOGGO IMSOSORRY BUT C???????
and we wait
c file
and
needed header
hope the bot doesn't detect it as spam lol
hi if I have two files
mod.py
import inspect
print(inspect.stack[-1].lineno)```
`test.py`
```py
#Some random file that imports the module
import mod
print("a")```
I can get the line number of the `import mod` (2) right, but can I also get the column number? (python 3.9)
I know that the code_context property exists but if I can prevent searching through strings that would be great
3.9 I don't believe tracked that. Short of writing a custom parser (maybe just finding it via .index on the right line) and running that on getsource, it is probably impossible
cool
well I guess I should state my original problem in case there are other solutions:
I would like to preprocess the __main__ file from mod.py and then let it execute
Problem is that if there is code before the import mod statement it obviously should not be executed again. What makes it so painful is that I cant just say: "Give me everything after the import statement, I will execute the rest" because it could be nested in some class or function
Do you have any idea?
I would do the preprocessing too for other files imported but for those its easier because I can set up import hooks
My alternative would be somehow using the site module to my advantage but Im not sure if this is a great solution
Or I could use a custom encoding combined with import hooks so all I need to do is set the encoding to the custom one in the __main__ file
which is much more explicit than going to the site module and preprocessing any python file that is run, even if it has nothing to do with my project
works for me
!e
listA:list=[0.0,0.5];b:int=round((listA[0]+0.6)+(listA[1]+1));print("{:^20}".format(b))
@fluid pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.
2
is this the shortest way to do this?
import sys
v=sys.argv[1:]```
ok doggo heres the code #esoteric-python message
Is this considered esoteric?
from sys import*;v=argv[1:]
probally
import sys;v=sys.argv[1:]
from sys import*;v=argv[1:]
yeah yours one is shorter
import sys;v=sys.argv[1:]
import sys;_,*v=sys.argv
that doesnt work does it
idk
__import__ is not the same as import, it wont bring the name into the scope, it returns the module object
v=__import__('sys').argv[1:] 🤷
hmmm
it's not shorter, but still looks cool tho
LMAO
v=(lambda:__import__('sys').argv[1:])
not so short
and useless
it does
ah
it doesnt even do the same thing, its a function now, you didnt call it
__import__('sys').argv[1:]
I know what lambda does lol, I mentioned it's useless
v=(lambda f:f(*map(__import__,f.__code__.co_varnames)))(lambda sys:sys.argv[1:])
fu#k you ||(no offense please, this is a joke)||
__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),____:=_.__add__(_),___:=____.__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__add__(_).__lshift__(___.__add__(_)).__sub__(___.__add__(_).__add__(_))))().__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(____))),[__.__sub__(____.__lshift__(___).__add__(____.__lshift__(____))), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(___),_______,_______.__sub__(___.__lshift__(_)), __.__sub__(___.__add__(_).__mul__(___.__add__(___).__add__(_)))]))).__getitem__(_.__sub__(____)))```
i had to
v=(lambda f:f(*map(next(j for f in object.__subclasses__() for j in [getattr(getattr(f, '__init__', object), '__globals__', 0)] if j != 0).__getitem__,f.__code__.co_varnames)))(lambda sys:sys.argv[1:])
!e
v=(lambda f:f(*map(next(j for f in object.__subclasses__() for j in [getattr(getattr(f, '__init__', object), '__globals__', 0)] if j != 0).__getitem__,f.__code__.co_varnames)))(lambda sys:sys.argv[1:])()
print("hi")```
@unique heath :x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | v=(lambda f:f(*map(next(j for f in object.__subclasses__() for j in [getattr(getattr(f, '__init__', object), '__globals__', 0)] if j != 0]).__getitem__,f.__code__.co_varnames)))(lambda sys:sys.argv[1:])()
003 | ^
004 | SyntaxError: closing parenthesis ']' does not match opening parenthesis '('
- i edited it
- it's already called
!e
v=(lambda f:f(*map(next(j for f in object.__subclasses__() for j in [getattr(getattr(f, '__init__', object), '__globals__', 0)] if j != 0).__getitem__,f.__code__.co_varnames)))(lambda sys:sys.argv[1:])
print('ono')````
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
ono
!e ```py
v=(lambda f:f(*map(next(j for f in object.subclasses() for j in [getattr(getattr(f, 'init', object), 'globals', 0)] if j != 0).getitem,f.code.co_varnames)))(lambda sys:sys.argv)
print(v == import('sys').argv)
@quartz wave :white_check_mark: Your 3.12 eval job has completed with return code 0.
True
ok
lmao
!e
a:list=[float(chr(int(b'\xff\xfe4\x009\x00'.decode('utf-16')))),float(chr(int(b'\xff\xfe4\x009\x00'.decode('utf-16'))))];d:float=(++a[0]+--a[1]);print("{:<10}".format("{}".format(int(d))))
@fluid pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.
2
deobfuscated a bit ```py
py dundeobfuscator.py
builtins.print(((A := 1), (B := 128), (C := 2), (D := 3), (E := 108), (F := 114), ''.join(builtins.map(builtins.chr, [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])))[-1])
:(
this too ```py
py dundeobfuscator.py
builtins.print(((A := 1), (B := 128), (C := 3), (D := 108), (E := 114), 'main'.join(builtins.map(builtins.chr, [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])))[-1])
:(
!e
def foo():
yield 42
print("finishing")
bar = foo()
print(next(bar))
print("before")
[] = bar
print("after")
@restive void :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 42
002 | before
003 | finishing
004 | after
huh?
why is it called
in [] = bar
Iterating for unpacking like in [x]=[1] ig
hi
why does the codecs IncrementalDecoder seem to work perfectly fine when opening file with a custom encoding but struggles when importing a file with a # coding: some encoding
it always ends in some recursive loop
something with the code?
You mean the code that is imported?
Just some simple print statements
Funnily enough in termux on my phone the IncrementalDecoder isnt even called when importing a file lol
for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or-~i)```
what?
!e
for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or-~i)```
@long fulcrum :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ANMLEQB36XDODHYQDIHFGTAGLU
!e there's a nice book, "ten essays on fizzbuzz". a favorite of mine from there, which technically fullfills your condition, is
import random
random.seed(23_977_775)
for i in range(1, 16):
print(random.choice(["FizzBuzz", "Fizz", str(i), "Buzz"]))
@hard spoke :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/HVZTR6CK4MG75GUDM2KW4QB4JY
does this work for any i?
nah, but one could modify it to just reuse the info on the first 15 elements for the rest of the sequence.
aw
I've got a decorator for classes that adds logging
is there some functools wraps equivalent?
or maybe it should be a mixin?
it mostly extends the init method
Why doesn't functools.wraps cut it?
the class module sets set to zen_logging.loggify too, which is wrong
this is what i was doing before and it worked alright
Lmao I love this, finding seeded rng for sequences of numbers or characters is also a cute idea for an obfuscation technique, makes the code literally unreadable without executing it.
this is amazing
I wonder if the seeding is version specific
!e
import random
a = [-3, 1, -5, 3, 5, -8, -6, -11, -2, 7]
random.seed(69_69_420)
b = ''.join(map(chr,[random.randint(0, 19) - a[i] + 100 for i in range(len(a))]))
print(b[:5],b[5:])
@clear venture :white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
Guess not
!d random
Source code: Lib/random.py
This module implements pseudo-random number generators for various distributions.
For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.
On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions. For generating distributions of angles, the von Mises distribution is available.
exec('''
for i in range(16):
qv i % 3 == 0 and i % 5 == 0:
print(\'fizzbuzz\')
ykqv i % 3 == 0:
print(\'fizz\')
ykqv i % 5 == 0:
print(\'buzz\')
ykmy:
print(i)
'''.translate(str.maketrans('kyvqm', 'lefis')))
lol
that isnt really a "master" thing
its pretty trivial
for i in range(100):print(["fizzbuzz", "buzz", "fizz", i][bool(i % 3) + (bool(i % 5) * 2)])``` pretty neat solution
!e
for i in range(10):print(["fizzbuzz", "buzz", "fizz", i][bool(i % 3) + (bool(i % 5) * 2)])```
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | fizzbuzz
002 | 1
003 | 2
004 | fizz
005 | 4
006 | buzz
007 | fizz
008 | 7
009 | 8
010 | fizz
!e my favourite has been
for i in range(1, 17):
q=[str(i),'']
j=0
if i % 3 == 0:
q[j] = 'Fizz'
j+=1
if i % 5 == 0:
q[j] = 'Buzz'
j+=1
print(''.join(q))
@proper vault :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/A3WJ2Z77JDHOMLIU2DMPNWGA2I
smart
!e Not sure if this one was mentioned yet, but this is also a fun one
for i in range(1,33):
print(['FizzBuzz', i, i, 'Fizz', i, 'Buzz', 'Fizz', i, i, 'Fizz', 'Buzz', i, 'Fizz', i, i, 'Buzz'][i%16])
@proper vault :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/VFWMTMGINH22IZ4MIQ6SN2FCAE
its not
so basically mine but worse /j
@unique heath how did u learn py?
oh, fizz buzz
I have a very old C thing of mine
i;main(){101-++i&&printf("%d\n\0FizzBuzz\n\0Fizz\n"+(7*!(i%3)+4*!(i%5))%9*2,i)&main();}
a tad more readable form
i;
main() {
101-++i
&& printf(
"%d\n\0FizzBuzz\n\0Fizz\n"
+ (7*!(i%3)+4*!(i%5))%9*2,
i
) & main();
}
if the first one is '' (empty), it goes to the or
else, it doesnt
here, and writing a shit ton of stupid projects
what abt when u were a complete beginner ?
i dont remember
ah
but also this
i just bought a course
why
waste of money 😭
so lets see
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
i suggest https://automatetheboringstuff.com which is a free ebook
and then make a shit ton of stupid projects
emphasis on shit ton
!e
__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),____:=_.__add__(_),___:=____.__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__add__(_).__lshift__(___.__add__(_)).__sub__(___.__add__(_).__add__(_))))().__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(____))),[__.__sub__(____.__lshift__(___).__add__(____.__lshift__(____))), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(___),_______,_______.__sub__(___.__lshift__(_)), __.__sub__(___.__add__(_).__mul__(___.__add__(___).__add__(_)))]))).__getitem__(_.__sub__(____)))```
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
so anyway
hello world
(help i wrote that by hand)
cereal made a deobfuscator here
it makes more sense when you see that
lmao
i'm improving it btw

