#esoteric-python
1 messages · Page 16 of 1
If you will create program to do that - yes 🙂
that's relatively simple to do-
for loop -> generator/comprehension expression, or maybe map
while loop -> for loop but with iter
import -> __import__
etc
basically, turn everything into an expression rather than a statement
and then, put it all into a tuple
ooh thats a good idea
i feel like exec and eval are cheating
yes, but it's not so easy on hard constructions
i have a made a small program some months ago which does some things but i am lazy to continue
how so?
yeah thats generally why most of my projects get abandoned lol
I mean for example functions with several returns, globals and locals variables mixing
globals() and locals() fixes the variables problem
for several returns, you can (usually) use a tuple and index into it based on what you want to return
what about not execute blocks after return?
you can use iter or ternaries to accomplish that
!e
(lambda: [globals().__setitem__('A', type("A", (object,), {"__init__": (lambda self, value: [globals().__setitem__('''__RV''', None), [setattr(self,'value', value)]].clear() or globals()['__RV']), "__str__": (lambda self: [globals().__setitem__('''__RV''', None), [globals().__setitem__('__RV', self.value)]].clear() or globals()['__RV'])})), globals().__setitem__('B', type("B", (object,), {"__init__": (lambda self, value: [globals().__setitem__('''__RV''', None), [setattr(self,'value', value)]].clear() or globals()['__RV']), "__str__": (lambda self: [globals().__setitem__('''__RV''', None), [globals().__setitem__('__RV', self.value)]].clear() or globals()['__RV'])})), print_hello := (lambda : [globals().__setitem__('''__RV''', None), [a := A("hello"), b := B("world!"), print(a, b)]].clear() or globals()['__RV']), print_hello()])()
@dreamy pier :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world!
is this even all used or is it extra random stuff
It is generated with my code, that's why it is so bad. No one did a good one-line-maker yet 😦
Source code was: (i know, B is exactly copy of A)
class A:
def __init__(self, value):
self.value = value
def __str__(self):
return self.value
class B:
def __init__(self, value):
self.value = value
def __str__(self):
return self.value
def print_hello():
a = A("hello")
b = B("world!")
print(a, b)
print_hello()
No one did a good one-line-maker yet 😦
cereals obfuscator handles most things pretty well
link please?
this you mean? doesn't it work only for obfuscationg one line of code? https://github.com/thatbirdguythatuknownot/sniplections/blob/main/obfuscator.py
fuck it, i'll make one
!e ```py
print((:=import("sys"),1:=.getattribute(.dir()[94]),2:=import("io"),.setattr(_.dir()[94],_2.getattribute(2.dir()[18])()),3:=import("this"),.setattr(.dir()[94],_1),_3.s)[6])
@austere mauve :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Gur Mra bs Clguba, ol Gvz Crgref
002 |
003 | Ornhgvshy vf orggre guna htyl.
004 | Rkcyvpvg vf orggre guna vzcyvpvg.
005 | Fvzcyr vf orggre guna pbzcyrk.
006 | Pbzcyrk vf orggre guna pbzcyvpngrq.
007 | Syng vf orggre guna arfgrq.
008 | Fcnefr vf orggre guna qrafr.
009 | Ernqnovyvgl pbhagf.
010 | Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.
011 | Nygubhtu cenpgvpnyvgl orngf chevgl.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/zefivetote.txt?noredirect
good luck xd
doesn't it work only for one line of code
the output is 1 line of code
the input can be almost anything
How should i run it?
'UnparseObfuscate' object has no attribute '_indent' ¯\_(ツ)_/¯
you're not meant to put a file into it
there's probably a way to make a one line converter that works for a limited set of things
you're meant to feed it expressions
and it will return an obfuscated form of the expression
to get an obfuscated value, use Obfuscator.ge
it returns an obfuscated expression that evaluates to what you passed in
UnparserObfuscator takes an expression as a string and returns an obfuscated expression that does the same thing
if you want to do classes Obfuscator.ge can do that, but I don't think the unparser can
it should all be in sniplections/README.md
ye, not all but it is 😄
!e ```py
print(True | False << False | False << (False | False << False) | False << (False << (False << False)) | False << (False | False << (False << False)) | False << (False << False | False << (False << False)))
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
!e
print(1 + True | False << False | False << (False | False << False) | False << (False << (False << False)) | False << (False | False << (False << False)) | False << (False << False | False << (False << False)))
@dreamy pier :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
changed the number/
the entire right part is just 0
the left part is 1
aka 1
crackpot code @dreamy pier
here's formatted
not much better
here's the input
there's probably so many fucking bugs with this
anyways it's better than mine
Hey @sick hound!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
great
https://paste.pythondiscord.com/xopijarotu @dreamy pier here is the code
please excuse my dogshit code
it's not finished yet
the root nodes aren't even visited
without much optimization i redid that one thing i did (no color, this time sadly) in ACTUALLY 1 line
print("\n".join(["".join(["█▓▒░ "[((x//2)|(y//2))%5] for x in range(60)]) for y in range(60)]))
what's the original
I might be able to get color to work
you need semicolons
(lambda r,g,b:f"{whatever the escape code}")(args)
it requires you to import os and do os.system("") to enable color in terminal
__import__("os").system("blah")
this is the original
print(__import__("os").system("blah") or WHATEVER_CODE)
wait why do you need os.system("")
terminal thing
it turns on color
otherwise it just prints the ansi codes
¯_(ツ)_/¯
that works if os.system() returns an empty string which it appears is what is happening
lemme cook something up
I think there are other improvements also
like
print(not(w:=60,__import__("os").system(""))or"".join([f"\x1B[48;5;{16+(i%w|i//w)}m {chr(10)if(i%w==0)else''}"for i in range(w**2)]))
print(__import__("os").system("cls")or"\n".join(["".join([f"\x1B[48;5;{16+(x|y)}m " for x in range(60)])for y in range(60)]))
that's what I've got after some basic stuff
and knowing nothing about the calculations
it's just x|y
ok
print(__import__("os").system("cls")or"\n".join("".join(f"\x1B[48;5;{16+(x|y)}m "for x in range(60))for y in range(60)))
that is just a shorter version
print(__import__("os").system("")or"\n".join("".join(f"\x1B[48;5;{16+(x|y)}m "for x in range(60))for y in range(60)))
!d os.system
os.system(command)```
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function `system()`, and has the same limitations. Changes to [`sys.stdin`](https://docs.python.org/3/library/sys.html#sys.stdin "sys.stdin"), etc. are not reflected in the environment of the executed command. If *command* generates any output, it will be sent to the interpreter standard output stream. The C standard does not specify the meaning of the return value of the C function, so the return value of the Python function is system-dependent.
On Unix, the return value is the exit status of the process encoded in the format specified for [`wait()`](https://docs.python.org/3/library/os.html#os.wait "os.wait").
hmm
It might be better to use a double .replace() + exec
which could take out the repeated ".join( and in range(60)
i might try pi and eulers in proper 1 line now that i know you can import like that
print("\n".join("".join("█▓▒░ "[(x|y)//2%5]for x in range(60))for y in range(60)))
``` shortened
that's without color tho
smart math improvement
((x//2)|(y//2))%5
(x|y)//2%5
I wonder if we can look over x and y at the same time and it's smaller
*loop over
awesome
nah you can't collapse the loop
you can have one loop and do i%60|i//60
euler = lambda steps: __builtins__.sum([(0^1 & (0 | 1))/(__import__(name=(__import__('base64').b64decode("bWF0aA==").decode('utf-8'))).factorial(_)) for _ in __builtins__.iter(__builtins__.range(steps))])
is this cursed enough? 🤷
why so many __builtins__.(in global scope)
for the funny
base64 encoded math?
yep
print((lambda a:sum([1/(__import__("math").factorial(i))for i in range(a)]))(30))
thats not cursed tho
print(sum(1/(__import__("math").factorial(i))for i in range(30)))
import os;os.system("");print("".join(f"\x1B[48;5;{16+(i%60|i//60)}m "+"\n"[i%60:]for i in range(3600)))
``` the previous shortest solution (that doesn't break copy-pasting for me, has color, and doesn't have pausing)
cool
why do you have to add +"\n" instead of combining it with the fstring
oh I see
the indexing stuff
what's the shortest way to approximate pi
I have this:
print(__import__('math').sqrt(sum(6/n**2for n in range(1,99))))
but the sqrt is very expensive in terms of length
this is based on the infinite sum Sum[6 / n^2, x -> inf] = pi ^ 2
cant you just do ** 0.5?
you can, may or may not be faster
yes but they want shortness
definitely less fcall overhead
def pi_approx_old(steps):return sum([1/(i*(((i)%4)-2)*-1) for i in range(1,steps*2,2)])*4
is how i did it
gonna rewrite tho
also
def is_pwr_2(n):return(n&-n)==n
what 🤷 and i thought (x and (not(x & (x - 1)))) was optimized
is_pwr_2=lambda n:(n&-n)==n
slightly shorter
can't believe I didn't think of that
sadly i don't think this can be extended to other powers
for future reference:
def nth_root(x, n=2):
return x ** (1 / n)
print(sum(6/n**2for n in range(1,999))**0.5)
It can be partially
I'm guessing it can be applied somehow to powers of two
damn this is slow
it works because a power of two in binary is always 1 bit on and the rest off
>>> print(sum(6/n/n for n in range(1,99999999))**.5)
3.141592643650717
have been doing this for.. forever XD
i have no damn clue how i discovered it but i found it in my e2 code
how does that even.. ok
one of the only times i was like 'wtf is this doing' for my own code
oh yeah btw shortened ```py
print(sum(6/n/n for n in range(1,99))**.5)
don't worry about it euler already figured it out
none of those operations are right-to-left
they're left-to-right, same precedence
so 6/n*n would be (6/n)*n AKA n*6/n
yeah it's really cool
oh man.. e2
whats e2
gmod scripting mod
ah
horrendously slow and wacky language
its horridly modified version of lua iirc
it barely even resembles it but yeah maybe
like for one it uses curly braces for branches and loops
the ingame IDE for it was pretty decent though ngl, one of the only examples of a good IDE for coding ingame
anyways, updated the pi approximation:
pi_appx=lambda n:sum(1/(i*((i%4)-2)*-1)for i in range(1,n*2,2))*4
what abbout approximating the golden ratio
a,b=0,1
for i in range(99):a,b=b,a+b
print(b/a)
base
99 is your accuracy measurement
it's literally the best accuracy you can get
python floats can't exceed more digits than that
I suppose
try extracting the digits of pi
there's gotta be some parentheses you can remove here
operator ordering
so ```py
print(5**.5/2+.5)
ye actually ```py
pi_appx=lambda n:sum(1/i/(2-i%4)for i in range(1,n*2,2))*4
the leibniz formula is horrendously slow
not in computation time, it just converges really slowly
pi approximation: 21.991148575127898 / 7
more improvement ```py
pi_appx=lambda n:sum(4/i/(2-i%4)for i in range(1,n*2,2))
wait nvm we already did euler's
yep
anyways if we're still doing the non-formula version ```py
a=b=1
exec('b=a-b;a+=b;'*99)
print(a/b-1)
smart
only for windows
if you're using an operating system that recognizes ansi then it just works
dont kill me but
def hello():
print("hello world")
hello.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__()
call hell.
each .__call__() is a different instance wtf ```pycon
def hello():
... print("hello world")
...
hello.call
<method-wrapper 'call' of function object at 0x00000205F41A04A0>
hello.call.call
<method-wrapper 'call' of method-wrapper object at 0x00000205F41E71C0>
hello.call.call.call
<method-wrapper 'call' of method-wrapper object at 0x00000205F41E7040>
hello.call.call.call.call
<method-wrapper 'call' of method-wrapper object at 0x00000205F41E5810>
hello.call.call.call.call.call
<method-wrapper 'call' of method-wrapper object at 0x00000205F4697BB0>
hello.call.call.call.call.call.call
<method-wrapper 'call' of method-wrapper object at 0x00000205F4697D00>
yep
if you do it enough you can fill your ram
that moment when python MemoryError
@quartz wave what's the craziest thing you've seen/done in this channel?
i don't know because there's just so many things
like that code golfer i made
!epy (lambda:print('Hello World!')).__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__()
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello World!
!e ```py
print(0x0 and TxT.are(not things.that.I.understand *so. perfectly + f"ine{python:code}" is special))
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
0
da hell
!e```py
builtins.getattribute(builtins.str.call().join.call(([*globals.call().keys.call()][0][0:2],[*globals.call().keys.call()][6][-5],[*globals.call().values.call()][0][2],[*globals.call().keys.call()][2][2],[*globals.call().keys.call()][1][3],[*globals.call().keys.call()][3][7],[*globals.call().keys.call()][5][6],[*globals.call().keys.call()][0][0:2]))).call(builtins.str.call().join.call(([*globals.call().keys.call()][0][0:2],builtins.chr.call(104),[*globals.call().keys.call()][2][8],[*globals.call().keys.call()][3][2]*2,[*globals.call().keys.call()][1][3],[*globals.call().keys.call()][0][0:2]))).getattribute.call(builtins.str.call().join(([*globals.call().values.call()][0][2:6]))).call()
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello world!
!e 3.10```py
builtins.getattribute(builtins.str.call().join.call(([*globals.call().keys.call()][0][0:2],[*globals.call().keys.call()][6][-5],[*globals.call().values.call()][0][2],[*globals.call().keys.call()][2][2],[*globals.call().keys.call()][1][3],[*globals.call().keys.call()][3][7],[*globals.call().keys.call()][5][6],[*globals.call().keys.call()][0][0:2]))).call(builtins.str.call().join.call(([*globals.call().keys.call()][0][0:2],builtins.chr.call(104),[*globals.call().keys.call()][2][8],[*globals.call().keys.call()][3][2]*2,[*globals.call().keys.call()][1][3],[*globals.call().keys.call()][0][0:2])))
@arctic skiff :white_check_mark: Your 3.10 eval job has completed with return code 0.
Hello world!
it just doesn't run because of and
!e ```py
print(1<0>1 is n >= 1 .maybe*but + i. do(not know))
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | False
huh
why doesn't it run the right part now
!e
print(0>1 is n)
print(1 is n)
print(False is n)
@dreamy pier :x: Your 3.11 eval job has completed with return code 1.
001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | <string>:2: SyntaxWarning: "is" with a literal. Did you mean "=="?
003 | False
004 | Traceback (most recent call last):
005 | File "<string>", line 2, in <module>
006 | NameError: name 'n' is not defined
isn't it a little confusing
!e
n = 1
print(1 is n)
@dreamy pier :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:2: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | True
it is ._.
you'll notice that is has the same precedence as all the other known comparison operators
therefore it can be changed
You mean chained, I assume?
!e perhaps a more evil version
print("let's see if 1 != 2:", 1 == 2 is False)
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | let's see if 1 != 2: False
!e ```py
print("let's see if 1 != 2:", 1 == 2 is False(but(not actually)))
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | <string>:1: SyntaxWarning: 'bool' object is not callable; perhaps you missed a comma?
003 | let's see if 1 != 2: False
Tell me a better way to generate strings
Hello world! How are you? 🙂
Someone can help me with me code please? I would like to do something with my button after one command but i don't know how do
Wrong channel
Here you will get help but not in a expected way
Use __doc__ and index specific chars in the docstring
I dont know waht doc does can you give a example
!e ```py
print(print.doc)
@gleaming linden :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Prints the values to a stream, or to sys.stdout by default.
002 |
003 | sep
004 | string inserted between values, default a space.
005 | end
006 | string appended after the last value, default a newline.
007 | file
008 | a file-like object (stream); defaults to the current sys.stdout.
009 | flush
010 | whether to forcibly flush the stream.
Oh help(print)
Yeah
!e print(doc.doc)
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
None
Cereal's obfuscator uses it
You have to access it as an attribute
may i see
!e
print([0x1for x in range(2)])
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:1: SyntaxWarning: invalid hexadecimal literal
002 | [31]
!e
n = 1
print(1 is n)
print(2 is n)
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:2: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | <string>:3: SyntaxWarning: "is" with a literal. Did you mean "=="?
003 | True
004 | False
Can true false be used as numbers
If so I can make a number by just adding trues and falses
!e print((True << (True << (True << 1))) * (True << (True << 1)) + (True << (True << 1)) + True)
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
69
True = 1
False = 0
Thanks both of you
How to use << and >>
Binary shifting to right and left
n >> k move number n k bits right
For example
1011100 >> 1 = 101110
technically, it is just dividing and multiplication by 2**k
!e
print(8 >> 1)
print(8 << 1)
@dreamy pier :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 4
002 | 16
!e ```py
orig = 121
print(f"Original: {bin(orig)}")
print(f"Shifted left by 2: {bin(orig << 2)}")
print(f"Shifted right by 2: {bin(orig >> 2)}")
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Original: 0b1111001
002 | Shifted left by 2: 0b111100100
003 | Shifted right by 2: 0b11110
it basically just adds or removes binary digits from the end of the number
idk how to use binary
!e```py
while 1:import('sys').stdout.write('skill issue\n')
@arctic skiff :x: Your 3.11 eval job has completed with return code 143 (SIGTERM).
001 | skill issue
002 | skill issue
003 | skill issue
004 | skill issue
005 | skill issue
006 | skill issue
007 | skill issue
008 | skill issue
009 | skill issue
010 | skill issue
011 | skill issue
... (truncated - too many lines)
Full output: too long to upload
tell me another way
.__repr__ also
as for just the built-in objects, str() and repr() are different for str objects, they are the same for every other object
I meant object.__repr__
Ok
https://github.com/python/cpython/blob/main/Parser/token.c jesus fucking christ
@tough willow :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
okay
!e
𩳅=chr
𩳆=ord
𩳈=divmod
𩳁=print
𩳉="""\x62\x69\x74\x5f\x6c\x65\x6e\x67\x74\x68"""
𩳊="""\x5f\x5f\x63\x6c\x61\x73\x73\x5f\x5f"""
𩳇=getattr
𩳀,𩳂=0b1010101100000110001101001001010101111010000010b100b100b100b110b1110b1010110b11111110b101111111*0b11100101101011,0
𩳃=(𩳇(𩳀,𩳉)()+(1<<3)-1)//1<<3-1
while 𩳀:𩳀,𩳄=𩳈(𩳀,1<<8);𩳁(𩳅(𩳄),end=𩳇(𩳅(𩳄),𩳊)());𩳂+=1
𩳁()
@tough willow :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
yeah
!e ```py
print(['a''b''c''d''e''f''g''h'])
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
['abcdefgh']
it's just abusing the fact that strings can combine
!e py print([__import__('string').ascii_lowercase])
@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.
['abcdefghijklmnopqrstuvwxyz']
You could even do something like that ^
Which is fairly easy to further esotericise/obfuscate if you wanted
!e print(*import('string').ascii_lowercase)
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
a b c d e f g h i j k l m n o p q r s t u v w x y z
you can do bytes(list_of_numbers)
and then decode it and index into it
to get characters
!e print(__import__(f'{type("").__name__}''ing').ascii_lowercase)
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
abcdefghijklmnopqrstuvwxyz
and it still uses the sneaky string manipulation
*combination
whatever it's called
like this
(alphabet:=bytes([*(_:=[*map((65).__add__, range(26))]), *map((32).__add__, _)]).decode("utf-8"))
f string?
no the combination of strings
like when they fold together
!e print((hi:= "hello") + f"{hi}"'abc')
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
hellohelloabc
!e ```py
"foo""bar"
@old socket :warning: Your 3.11 eval job has completed with return code 0.
[No output]
oh
I just thought that was normal-
!e print("""a"""'''b'''"c"'d')
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
abcd
is this tru?
since C/C++ also do it
wrong channel
wrong channel
jinx
great minds think alike ✨
I guess that all comes down to how good python is for ML
since tbh that's really the only innovating thing I've heard abt python for a while
tensorflow isn't written in python
I think it's meant to be an "x language is better than y language"
which isn't very nice to users of y language
in this case, java
!e ```py
import os
os.system("py -m pip install numpy")
import numpy as np
print(np.array([1,2,3]))
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
[1 2 3]
!e ```py
import numpy as np
print(np.array([1,2,3]))
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
[1 2 3]
wait what packages are installed
!e ```py
import os
print(os.system("py -m pip list"))
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
32512
iirc einspect
Exit status 32512?
yeah idk
!e ```py
import subprocess
print(subprocess.check_output("py -m pip list"))
@meager zinc :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | File "/usr/local/lib/python3.11/subprocess.py", line 466, in check_output
004 | return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
005 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
006 | File "/usr/local/lib/python3.11/subprocess.py", line 548, in run
007 | with Popen(*popenargs, **kwargs) as process:
008 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
009 | File "/usr/local/lib/python3.11/subprocess.py", line 1024, in __init__
010 | self._execute_child(args, executable, preexec_fn, close_fds,
011 | File "/usr/local/lib/python3.11/subprocess.py", line 1901, in _execute_child
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/usilogizuk.txt?noredirect
wat the
os.system returns the exit code iirc
huh
!e ```py
import os
print(os.system("export PIPLIST=python3 -m pip list"))
print(os.getenv("PIPLIST"))
py prob doesn't exist since linux
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 32512
002 | None
!e ```py
import subprocess
print(subprocess.run("python -m pip list", stdout=subprocess.PIPE).stdout)
@meager zinc :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | File "/usr/local/lib/python3.11/subprocess.py", line 548, in run
004 | with Popen(*popenargs, **kwargs) as process:
005 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
006 | File "/usr/local/lib/python3.11/subprocess.py", line 1024, in __init__
007 | self._execute_child(args, executable, preexec_fn, close_fds,
008 | File "/usr/local/lib/python3.11/subprocess.py", line 1901, in _execute_child
009 | raise child_exception_type(errno_num, err_msg, err_filename)
010 | FileNotFoundError: [Errno 2] No such file or directory: 'python -m pip list'
hm
python is python2
use python3
wouldn't change anything for that one
!e ```py
import os
print(os.system("export PIPLIST=ls -a"))
print(os.getenv("PIPLIST"))
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 32512
002 | None
not working
is sandboxed too well
!d subprocess.run
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, ...)```
Run the command described by *args*. Wait for command to complete, then return a [`CompletedProcess`](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess "subprocess.CompletedProcess") instance.
The arguments shown above are merely the most common ones, described below in [Frequently Used Arguments](https://docs.python.org/3/library/subprocess.html#frequently-used-arguments) (hence the use of keyword-only notation in the abbreviated signature). The full function signature is largely the same as that of the [`Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen "subprocess.Popen") constructor - most of the arguments to this function are passed through to that interface. (*timeout*, *input*, *check*, and *capture\_output* are not.)
Lemme try this
!e ```py
import subprocess
print(subprocess.run(["python", "-m", "pip", "list"], stdout=subprocess.PIPE).stdout.decode('u8'))
@meager zinc :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | File "/usr/local/lib/python3.11/subprocess.py", line 548, in run
004 | with Popen(*popenargs, **kwargs) as process:
005 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
006 | File "/usr/local/lib/python3.11/subprocess.py", line 1024, in __init__
007 | self._execute_child(args, executable, preexec_fn, close_fds,
008 | File "/usr/local/lib/python3.11/subprocess.py", line 1901, in _execute_child
009 | raise child_exception_type(errno_num, err_msg, err_filename)
010 | FileNotFoundError: [Errno 2] No such file or directory: 'python'
!e ```py
import os
for foo in os.scandir():
print(foo)
@old socket :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <DirEntry 'requirements'>
002 | <DirEntry 'user_base'>
003 | <DirEntry 'config'>
Ooh
!e ```py
import subprocess
print(subprocess.run(["dir"], stdout=subprocess.PIPE).stdout.decode('u8'))
@meager zinc :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | File "/usr/local/lib/python3.11/subprocess.py", line 548, in run
004 | with Popen(*popenargs, **kwargs) as process:
005 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
006 | File "/usr/local/lib/python3.11/subprocess.py", line 1024, in __init__
007 | self._execute_child(args, executable, preexec_fn, close_fds,
008 | File "/usr/local/lib/python3.11/subprocess.py", line 1901, in _execute_child
009 | raise child_exception_type(errno_num, err_msg, err_filename)
010 | FileNotFoundError: [Errno 2] No such file or directory: 'dir'
huh?
kek
ok subprocess is not gonna work
If you want the directory you can just use os.scandir
Oh
!e ```py
import os
for foo in os.scandir("./user_base/lib/python3.11/site-packages/"):
print(foo)
@old socket :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <DirEntry 'arrow'>
002 | <DirEntry 'matplotlib-3.6.3.dist-info'>
003 | <DirEntry 'einspect'>
004 | <DirEntry 'scipy'>
005 | <DirEntry 'mpl_toolkits'>
006 | <DirEntry 'numpy'>
007 | <DirEntry 'toml-0.10.2.dist-info'>
008 | <DirEntry 'contourpy'>
009 | <DirEntry 'async_generator'>
010 | <DirEntry 'numpy-1.23.5.dist-info'>
011 | <DirEntry 'pandas'>
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/huzerixuzu.txt?noredirect
that's what we want
!e ```py
import os
for foo in os.scandir("./user_base/lib/python3.11/site-packages/"):
print(str(foo)[11:-2])
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | arrow
002 | matplotlib-3.6.3.dist-info
003 | einspect
004 | scipy
005 | mpl_toolkits
006 | numpy
007 | toml-0.10.2.dist-info
008 | contourpy
009 | async_generator
010 | numpy-1.23.5.dist-info
011 | pandas
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/osararaxer.txt?noredirect
It's all here as well
!e ```py
import os
set_ = set()
for foo in os.scandir("./user_base/lib/python3.11/site-packages/"):
out = str(foo)[11:-2]
if "-" in out:
set_.insert(out.split('-')[0])
else:
set_.insert(out)
print(set_)
@meager zinc :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 9, in <module>
003 | AttributeError: 'set' object has no attribute 'insert'
!e ```py
import os
set_ = set()
for foo in os.scandir("./user_base/lib/python3.11/site-packages/"):
out = str(foo)[11:-2]
if "-" in out:
set_.add(out.split('-')[0])
else:
set_.add(out)
print(set_)
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
{'pylab.py', 'cycler', 'fonttools', 'attr', 'mpl_toolkits', 'bs4', 'forbiddenfruit', 'contourpy', 'numpy.libs', 'idna', 'typing_extensions.py', 'fuzzywuzzy', 'anyio', 'pyparsing', 'Pillow', 'lark', 'fishhook', 'python_dateutil', 'pytzdata', 'more_itertools', 'cycler.py', 'beautifulsoup4', 'mpmath', 'six.py', 'pendulum', 'pytz', 'dateutil', 'arrow', 'scipy', 'einspect', 'networkx', 'sortedcontainers', 'PyYAML', 'Pillow.libs', 'scipy.libs', 'trio', '_yaml', '__pycache__', 'attrs', 'multidict', 'PIL', 'numpy', 'six', 'pandas', 'kiwisolver', 'packaging', 'toml', 'sympy', 'outcome', 'isympy.py', 'tzdata', 'matplotlib', 'fontTools', 'sniffio', 'soupsieve', 'yarl', 'async_generator', 'typing_extensions', 'yaml'}
Lark?
!e ```py
import os
set_ = set()
for foo in os.scandir("./user_base/lib/python3.11/site-packages/"):
out = str(foo)[11:-2]
if "-" in out:
set_.add(out.split('-')[0])
elif '.' in out:
set_.add(out.split('.')[0])
else:
set_.add(out)
print(set_)
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
{'attr', 'scipy', 'idna', 'outcome', 'six', 'mpmath', 'python_dateutil', 'kiwisolver', 'tzdata', 'bs4', '__pycache__', '_yaml', 'matplotlib', 'attrs', 'numpy', 'Pillow', 'pandas', 'forbiddenfruit', 'packaging', 'isympy', 'sympy', 'toml', 'soupsieve', 'dateutil', 'einspect', 'beautifulsoup4', 'multidict', 'fuzzywuzzy', 'typing_extensions', 'yarl', 'more_itertools', 'fontTools', 'pendulum', 'cycler', 'pylab', 'arrow', 'PyYAML', 'contourpy', 'pyparsing', 'pytz', 'PIL', 'mpl_toolkits', 'fonttools', 'yaml', 'sortedcontainers', 'pytzdata', 'fishhook', 'sniffio', 'anyio', 'networkx', 'lark', 'async_generator', 'trio'}
Ah yes, __pycache__
!e ```py
import os
set_ = set()
for foo in os.scandir("./user_base/lib/python3.11/site-packages/"):
out = str(foo)[11:-2]
if "-" in out:
set_.add(out.split('-')[0])
elif '.' in out:
set_.add(out.split('.')[0])
else:
set_.add(out)
print(sorted(list(set_)))
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
['PIL', 'Pillow', 'PyYAML', '__pycache__', '_yaml', 'anyio', 'arrow', 'async_generator', 'attr', 'attrs', 'beautifulsoup4', 'bs4', 'contourpy', 'cycler', 'dateutil', 'einspect', 'fishhook', 'fontTools', 'fonttools', 'forbiddenfruit', 'fuzzywuzzy', 'idna', 'isympy', 'kiwisolver', 'lark', 'matplotlib', 'more_itertools', 'mpl_toolkits', 'mpmath', 'multidict', 'networkx', 'numpy', 'outcome', 'packaging', 'pandas', 'pendulum', 'pylab', 'pyparsing', 'python_dateutil', 'pytz', 'pytzdata', 'scipy', 'six', 'sniffio', 'sortedcontainers', 'soupsieve', 'sympy', 'toml', 'trio', 'typing_extensions', 'tzdata', 'yaml', 'yarl']
you've just given me a horrible idea
I could make a module called __pycache__
this is all on the github 😔
anyio[trio]~=3.6
arrow~=1.2
attrs~=22.1
beautifulsoup4~=4.11
fishhook~=0.2
forbiddenfruit~=0.1
fuzzywuzzy~=0.18
lark~=1.1
more-itertools~=9.0
networkx~=2.8
numpy~=1.23
pandas~=1.5
pendulum~=2.1
python-dateutil~=2.8
pyyaml~=6.0
sympy~=1.11
toml~=0.10
typing-extensions~=4.4
tzdata~=2022.6
yarl~=1.8
No, you're wrong -- it doesn't include dependencies
oh right I see a few missing
like scipy isn't on there but it is included as a dependency
What was this for anyways kek
idk
!e ```py
import os
set_ = set()
for foo in os.scandir("./user_base/lib/python3.11/site-packages/"):
out = str(foo)[11:-2]
if "-" in out:
set_.add(out.split('-')[0])
elif '.' in out:
set_.add(out.split('.')[0])
else:
set_.add(out)
imports = []
for to_import in sorted(list(set_)):
try:
imports.append(import(to_import))
except ImportError: pass
for import_ in imports:
print(dir(import_))
@meager zinc :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 15, in <module>
003 | File "/snekbox/user_base/lib/python3.11/site-packages/matplotlib/__init__.py", line 900, in <module>
004 | dict.update(rcParams, _rc_params_in_file(matplotlib_fname()))
005 | ^^^^^^^^^^^^^^^^^^
006 | File "/snekbox/user_base/lib/python3.11/site-packages/matplotlib/__init__.py", line 583, in matplotlib_fname
007 | for fname in gen_candidates():
008 | File "/snekbox/user_base/lib/python3.11/site-packages/matplotlib/__init__.py", line 580, in gen_candidates
009 | yield os.path.join(get_configdir(), 'matplotlibrc')
010 | ^^^^^^^^^^^^^^^
011 | File "/snekbox/user_base/lib/python3.11/site-packages/matplotlib/__init__.py", line 279, in wrapper
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/lelayajete.txt?noredirect
!e ```py
import os
set_ = set()
for foo in os.scandir("./user_base/lib/python3.11/site-packages/"):
out = str(foo)[11:-2]
if "-" in out:
set_.add(out.split('-')[0])
elif '.' in out:
set_.add(out.split('.')[0])
else:
set_.add(out)
imports = []
for to_import in sorted(list(set_)):
try:
imports.append(import(to_import))
except Exception: pass
for import_ in imports:
print(dir(import_))
@meager zinc :warning: Your 3.11 eval job timed out or ran out of memory.
[No output]
wat
lmao
!e ```py
import os
set_ = set()
for foo in os.scandir("./user_base/lib/python3.11/site-packages/"):
out = str(foo)[11:-2]
if "-" in out:
set_.add(out.split('-')[0])
elif '.' in out:
set_.add(out.split('.')[0])
else:
set_.add(out)
imports = []
for to_import in sorted(list(set_)):
try:
imports.append(import(to_import))
except Exception as e: print(e)
for import_ in imports:
print(dir(import_))
@meager zinc :x: Your 3.11 eval job timed out or ran out of memory.
001 | No module named 'Pillow'
002 | No module named 'PyYAML'
003 | No module named 'beautifulsoup4'
004 | No module named 'fonttools'
005 | Could not determine home directory.
@meager zinc fun fact
The install name doesn't always mean import name
!e print(import("sys").path)
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
['', '/snekbox/user_base/lib/python3.11/site-packages', '/usr/local/lib/python311.zip', '/usr/local/lib/python3.11', '/usr/local/lib/python3.11/lib-dynload']
yeah the problem is just that importing every package is a little much
!e ```py
import os
set_ = set()
for foo in os.scandir("./user_base/lib/python3.11/site-packages/"):
out = str(foo)[11:-2]
if "-" in out:
set_.add(out.split('-')[0])
elif '.' in out:
set_.add(out.split('.')[0])
else:
set_.add(out)
imports = []
for to_import in sorted(list(set_))[:10]:
try:
imports.append(import(to_import))
except Exception as e: print(e)
for import_ in imports:
print(dir(import_))
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | No module named 'Pillow'
002 | No module named 'PyYAML'
003 | ['UnidentifiedImageError', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_plugins']
004 | ['__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
005 | ['AliasEvent', 'AliasToken', 'AnchorToken', 'BlockEndToken', 'BlockEntryToken', 'BlockMappingStartToken', 'BlockSequenceStartToken', 'CEmitter', 'CParser', 'ComposerError', 'ConstructorError', 'DirectiveToken', 'DocumentEndEvent', 'DocumentEndToken', 'DocumentStartEvent', 'DocumentStartToken', 'EmitterError', 'FlowEntryToken', 'FlowMappingEndToken', 'FlowMappingStartToken', 'FlowSequenceEndToken', 'FlowSequenceStartToken', 'KeyToken', 'MappingEndEvent', 'MappingNode', 'MappingStartEvent', 'Mark', 'ParserError', 'ReaderError', 'RepresenterError', 'ScalarEvent', 'ScalarNode', 'ScalarToken', 'ScannerError', 'SequenceEndEvent', 'SequenceNode', 'SequenceSt
... (truncated - too long)
Full output: https://paste.pythondiscord.com/higajazira.txt?noredirect
this has funny potential
!e ```py
(t:=(...).dir(),print(t[5][2]+t[0][3]+t[8][4]*2+t[4][3]))
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
['__new__', '__repr__', '__getattribute__', '__reduce__', '__doc__', '__hash__', '__str__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__init__', '__reduce_ex__', '__getstate__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
!e ```py
(t:=(...).dir(),print(t[5][2]+t[0][3]+t[8][4]*2+t[4][3]))
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello
trole
!e print((exec("...")).dir())
@turbid dragon :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print((…).__dir__())
003 | ^
004 | SyntaxError: invalid character '…' (U+2026)
!e print((exec("...")).dir())
@turbid dragon :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1
004 | \.\.\.
005 | ^
006 | SyntaxError: unexpected character after line continuation character
!e print(exec("print"))
@turbid dragon :white_check_mark: Your 3.11 eval job has completed with return code 0.
None
!e print(eval("print"))
@turbid dragon :white_check_mark: Your 3.11 eval job has completed with return code 0.
<built-in function print>
!e print((eval("...")).dir())
@turbid dragon :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1
004 | \.\.\.
005 | ^
006 | SyntaxError: unexpected character after line continuation character
your phone is pranking you
!e print(eval("...").dir_())
@sick hound :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AttributeError: 'ellipsis' object has no attribute '_dir__'. Did you mean: '__dir__'?
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
['__new__', '__repr__', '__getattribute__', '__reduce__', '__doc__', '__hash__', '__str__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__init__', '__reduce_ex__', '__getstate__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
@turbid dragon :white_check_mark: Your 3.11 eval job has completed with return code 0.
['__new__', '__repr__', '__getattribute__', '__reduce__', '__doc__', '__hash__', '__str__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__init__', '__reduce_ex__', '__getstate__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
yeah ... is just an alias for Elipsis
!e ... is Elipsis
@sick hound :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'Elipsis' is not defined. Did you mean: 'Ellipsis'?
no but
!e print(... is Ellipsis)
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
mobile moment
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
None
As far as I know that's the only way to have four periods in a row as valid syntax (like not in a string or something)
!e besides ```py
class Formattable:
def format(*_):
return "hello world"
print(f"{Formattable():.............................}")
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
!e
import sys
import importlib
installed_packages = sys.stdlib_module_names
installed_packages_list = [package for package in installed_packages]
for package in installed_packages_list:
try:
importlib.import_module(package)
print(f"Imported {package}")
except Exception as e:
print(f"Exception occured while importing {package}\n{e}")
@rugged owl :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Imported _pydecimal
002 | Imported datetime
003 | Imported os
004 | Exception occured while importing msvcrt
005 | Imported msvcrt
006 | Imported ssl
007 | Imported zlib
008 | Imported _imp
009 | Imported multiprocessing
010 | Imported optparse
011 | Imported http
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/tabikuzere.txt?noredirect
that's the stdlib
Hey esoteric people! Y'all seem like the types to enjoy a problem like lexing. Anyone able to lend some wisdom?
!e here's what I actually wanted (basically but not perfect) -- I had it figured out already just didn't put it here ```py
import os
set_ = set()
for foo in os.scandir("./user_base/lib/python3.11/site-packages/"):
out = str(foo)[11:-2]
if "-" in out:
set_.add(out.split('-')[0])
elif '.' in out:
set_.add(out.split('.')[0])
else:
set_.add(out)
for to_import in sorted(list(set_))[:10]:
try:
pkg = import(to_import)
print(dir(pkg))
del pkg
except Exception as e: print(e)
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ['UnidentifiedImageError', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_plugins']
002 | No module named 'Pillow'
003 | No module named 'PyYAML'
004 | ['__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
005 | ['AliasEvent', 'AliasToken', 'AnchorToken', 'BlockEndToken', 'BlockEntryToken', 'BlockMappingStartToken', 'BlockSequenceStartToken', 'CEmitter', 'CParser', 'ComposerError', 'ConstructorError', 'DirectiveToken', 'DocumentEndEvent', 'DocumentEndToken', 'DocumentStartEvent', 'DocumentStartToken', 'EmitterError', 'FlowEntryToken', 'FlowMappingEndToken', 'FlowMappingStartToken', 'FlowSequenceEndToken', 'FlowSequenceStartToken', 'KeyToken', 'MappingEndEvent', 'MappingNode', 'MappingStartEvent', 'Mark', 'ParserError', 'ReaderError', 'RepresenterError', 'ScalarEvent', 'ScalarNode', 'ScalarToken', 'ScannerError', 'SequenceEndEvent', 'SequenceNode', 'SequenceSt
... (truncated - too long)
Full output: https://paste.pythondiscord.com/anosehidad.txt?noredirect
👍
actually it's not quite working right but whatever
should be a lot longer
!e maybe ```py
import os
set_ = set()
for foo in os.scandir("./user_base/lib/python3.11/site-packages/"):
out = str(foo)[11:-2]
if "-" in out:
set_.add(out.split('-')[0])
elif '.' in out:
set_.add(out.split('.')[0])
else:
set_.add(out)
for to_import in sorted(list(set_))[:10]:
try:
print(dir(import(to_import)))
exec(f"del {to_import}")
except Exception as e: print(e)
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ['UnidentifiedImageError', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_plugins']
002 | name 'PIL' is not defined
003 | No module named 'Pillow'
004 | No module named 'PyYAML'
005 | ['__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
006 | name '__pycache__' is not defined
007 | ['AliasEvent', 'AliasToken', 'AnchorToken', 'BlockEndToken', 'BlockEntryToken', 'BlockMappingStartToken', 'BlockSequenceStartToken', 'CEmitter', 'CParser', 'ComposerError', 'ConstructorError', 'DirectiveToken', 'DocumentEndEvent', 'DocumentEndToken', 'DocumentStartEvent', 'DocumentStartToken', 'EmitterError', 'FlowEntryToken', 'FlowMappingEndToken', 'FlowMappingStartToken', 'FlowSequenceEndToken', 'FlowSequenceStartToken', 'KeyToken', 'MappingEndEvent', 'MappingNode', 'MappingStartEvent', 'Mark', 'ParserError', 'ReaderError', 'RepresenterError', 'ScalarEvent', 'ScalarNode', 'Scala
... (truncated - too long, too many lines)
Full output: https://paste.pythondiscord.com/osutuqosij.txt?noredirect
depends on what you want to know
does python have a multithreaded map() function?
Pool.map or Pool.imap seem to do that
also why is this in esoteric python
#async-and-concurrency exists
my bad, didnt see that channel
!e just gonna leave this here 👀
from einspect import view, impl
@impl(str)
def append(self, value):
with view(self).unsafe() as v:
size = len(enc := value.encode())
v.length += size
v.buffer[-size:] = enc
@impl(str)
def __setitem__(self, index, value):
size = len(enc := value.encode())
view(self).buffer[index:index+size] = enc
s = "hello"
s.append(" 🐍!")
print(s)
s[6] = "🦀"
print(s)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | hello 🐍!
002 | hello 🦀!
i actually wouldn't mind a mutable string type
i assume this probably has lots of issues for hashing and stuff tho right
Ruby has mutable strings.
Example:
str = "This is a test!"
puts str
str.gsub!(/t\w+/i, "MUTATED")
puts str
outputs:
This is a test!
MUTATED is a MUTATED!
einspect got added to the sandbox?
nice
Ruby has another textual type, Symbol:
s = "string"
sym = :symbol
Symbols have many string methods as well, but there is one major difference between strings and symbols: while strings are mutable, symbols are immutable. The latter are also never repeatable in memory or garbage collected.
You can also simulate string mutability with lists or io.StringIO.
hey guys could u help me ??
If it's general Python help, open a thread in #1035199133436354600
!e sort of yeah, strs cache their hash on their first computation, so if you mutate them the hash still stays the same
from einspect import view
a = "dog"
print(hash(a))
view(a).buffer[:] = b"cat"
print(hash(a))
print({a, "cat"})
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | -7289724339505222381
002 | -7289724339505222381
003 | {'cat', 'cat'}
now the question is, which cat comes first?
!e ints don't cache their hashes though, so it works fine 👀
from einspect import view
view(78).value = 10
print(78 == 10)
print({78, 10})
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | True
002 | {10}
!e
from einspect import view
a = "dog"
print(hash(a))
view(a).buffer[:] = b"cat"
print(hash(a))
v = "cat"
print(hash(v))
print(id(v))
print(id(a))
print({a, v})
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 2419205319950006731
002 | 2419205319950006731
003 | -6876611859696956495
004 | 139750880081904
005 | 139750880081840
006 | {'cat', 'cat'}
These two strings have different object IDs, and different hashes too
yeah v there has the correct hash for "cat", since thats the first computation
a will forever have the hash of "dog" because its cached
this doesn't answer the question of which cat comes first
!e
from einspect import view
a = "dog"
print(hash(a))
view(a).buffer[:] = b"cat"
print(hash(a))
print(a.__hash__())
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1869120424909424972
002 | 1869120424909424972
003 | 1869120424909424972
So the hash is cached in the object.
you can manually invalidate the string cache though
it's the hash attribute of PyUnicodeObject, if you set it to -1 it means it'll recompute it next time
!e
from einspect import view
from einspect.structs.py_unicode import State
a = "dog"
print(hash(a))
v = view(a)
v.buffer[:] = b"cat"
with v.unsafe():
v.interned = State.NOT_INTERNED
v.hash = -1
print(hash(a))
print({"dog", "cat"})
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 3197805330524608556
002 | -1252139742680397454
003 | {'cat'}
!e here's a set within itself as well 👀
from einspect import view
from einspect.structs import PyObject
s = {1, 3}
item = view(s).smalltable[2]
item.key = PyObject.from_object(s).as_ref()
print(s)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
{1, set(...), 3}
!e me when i ```py
s = [[], [1, 2, 3]]
s[0] = s
print(s)
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
[[...], [1, 2, 3]]
!e ```py
import sys
sys.setrecursionlimit(1 << 30)
t = lambda t: t(t)
t(t)
@sick hound :warning: Your 3.11 eval job timed out or ran out of memory.
[No output]
!e
𩳅=chr
𩳆=ord
𩳈=divmod
𩳁=print
𩳉="""\x62\x69\x74\x5f\x6c\x65\x6e\x67\x74\x68"""
𩳊="""\x5f\x5f\x63\x6c\x61\x73\x73\x5f\x5f"""
𩳇=getattr
𩳀,𩳂=0b1010101100000110001101001001010101111010000010b100b100b100b110b1110b1010110b11111110b101111111*0b11100101101011,0
𩳃=(𩳇(𩳀,𩳉)()+(1<<3)-1)//1<<3-1
while 𩳀:𩳀,𩳄=𩳈(𩳀,1<<8);𩳁(𩳅(𩳄),end=𩳇(𩳅(𩳄),𩳊)());𩳂+=1
𩳁()
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
👍
I love how readable it is
!e ```py
real = "bals"
𝘱𝘳𝘪𝘯𝘵(𝘳𝘦𝘢𝘭)
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
bals
@sick hound :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print(42738617653645554487425669417955367763548489178153791212890331885138890998900808508146311757939093198954220995963493880469893655060010272737530068485887533886750263319088128875100617961740172918691094829068947024559255417843694122849355986039999784721779678479610340520316257460780653331211115191175921001686550288449540320526606015935656176339986358350085020871937781528861776129372953594883435388246572243486971684762525383211187114336334622961088849148988499044550772500949253994140989436531257826950153336030112478731838434316764895787741660597458158488889333869972691535297977686181013053333952226427170791307608470557004650494024440810638395846001231063108520585007047155467529084874545828487195466969383678372084948900
003 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
... (truncated - too long)
Full output: https://paste.pythondiscord.com/eyapezawek.txt?noredirect
I'm feeling esoteric today, any ideas?
emulate the behaviour of std::stoll in Python
and then golf it
!e ithis esoteric?
goldprint = lambda gold=int(): (gold.__add__(__import__('random').choice([(x:=((o:=-~int().__add__(-~int())).__pow__(o).__add__(-~int()))),y:=x.__mul__(o),z:=y.__add__(x.__add__(y)),w:=z.__add__(z),w.__add__(z)]))); print(goldprint())
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
10
"Is this esoteric?" is like asking "Is this art?"
True.
thats actually a really good way of putting it
!e
print((goldprint:=lambda gold=int(): (gold.__add__(__import__('random').choice([(x:=((o:=-~int().__add__(-~int())).__pow__(o).__add__(-~int()))),y:=x.__mul__(o),z:=y.__add__(x.__add__(y)),w:=z.__add__(z),w.__add__(z)]))))())
@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.
75
I'd change it to this, but otherwise good @karmic pumice
oh thanks, i was wondering of how could i make it an actual 1 liner here but didnt know
!e
print((goldprint:=lambda gold=int(): (gold.__add__(__import__('random').choice([(x:=((o:=-~int().__add__(-~int())).__pow__(o).__add__(-~int()))),y:=x.__mul__(o),z:=y.__add__(x.__add__(y)),w:=z.__add__(z),w.__add__(z)]))))())
print(goldprint())
@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 25
002 | 50
yeah walrus is cool
Walrus is amazing for esoteric python
If you want to add more obfuscation use hex escapes instead of 'random'
!e
print((goldprint:=lambda gold=int(): (gold.__add__(__import__('\x72\x61\x6e\x64\x6f\x6d').choice([(x:=((o:=-~int().__add__(-~int())).__pow__(o).__add__(-~int()))),y:=x.__mul__(o),z:=y.__add__(x.__add__(y)),w:=z.__add__(z),w.__add__(z)]))))())
Like I did here: #esoteric-python message
@karmic pumice
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
25
like that?
Yep
oh yeah i see
:)
cool 👍 thanks for teaching me the dark arts of esoteric python
also, i was wondering of how could i make use of import this?
like, len(dir(__import__('this')) = 12 but it also prints the zen
!e
print(len(dir(__import__('this'))))
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | The Zen of Python, by Tim Peters
002 |
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/vosegiviga.txt?noredirect
im curious, does anyone happen to know a way to pass kwargs without the use of ** or =
You can use *
Wait no
I don't think you can do that
I mean you could partially do it with a dict instead of =
Or * instead of ** and then specify the names
If you want to stop it from outputting then change stdout
try golfing gray code
using * with a dict only gives keys
** gives key value pairs but i want to avoid using it
def foo(*, x): # x has to be passed as a kwarg```this is what I meant
thats not what i meant-
what i meant is, how do you then call the function without using ** or =
ik how to define them
sorry for the confusion, i should have specified what i meant more clearly
You can make it use one or the other (or both), but not neither
how would i do that in this case? havent worked with stdin/out yet
import sys
orginal_stdout = sys.stdout
sys.stdout = None
import this
print("hello")
sys.stdout = original_stdout
print("hi")```
!e ```py
import sys
original_stdout = sys.stdout
sys.stdout = None
import this # doesn't output
print("hello") # doesn't output
sys.stdout = original_stdout
print("hi")```
sys.__stdout__ already stores the original stdout
@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.
hi
!e ```py
import threading as t
def f(*, x): print(x)
u = t.Thread(target=f, kwargs={'x': 1})
u.start()
u.join()
!e
import sys
sys.stdout = None
import this
print("hello")
sys.stdout = None
print("hi")
@proper vault :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
this does work technically
@karmic pumice :warning: Your 3.11 eval job has completed with return code 0.
[No output]
I recommend using contextlib.redirect_stdout for this
it works correctly with exceptions and such
why is it 65 but 64 for vscode 🤷
ah, you can even avoid the thread by doing this:
>>> u=t.Thread(target=lambda x: print(x), kwargs={'x':5})
>>> u.run()
5
different versions of python, perhaps
!e
print(len(dir(__import__('math'))))
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
66
oh so its 66 here but 65 for me
!e ```py
print(len(dir(import('math'))))
@old socket :white_check_mark: Your 3.10 eval job has completed with return code 0.
64
In 3.10 it's 64
3.11 added math.cbrt and math.exp2
t.Thread(None, lambda x: print(x), None, (), {'x':5}).run()
but im already on 3.11.1 🤷
Print the two lists and find the difference 
sets have ^ for symmetric difference which can useful for finding these things
!e
print(dir(__import__('math')))
interesting
I haven't played around with threads too much (in python, at least)
can it be made blocking?
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
it's blocking, this doesn't even create a thread, though it does lose the return value. .run() is the method that is run in the new thread, and you can run it manually in the main thread (you are meant to override it by subclassing). .start() starts a thread, and .join would then wait for the thread
this way, it just calls the function
!e
set1 = set(['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp'])
set2 = set(['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp'])
print(set2-set1)
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
{'__file__'}
__file__ 💀
ah, alright
thank you
why could i not have __file__ 🤷
you on 3.10?
No, that copy pasted one was for 3.11
the dir one should be 3.10
What that doesn't make sense lol
oh __file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module
func = lambda: ...
function = func.__class__
code = func.__code__.__class__
my_dynamic_function = function(code())
While learning about metaclasses, I stumbled across this rather odd discovery. This raises the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: code expected at least 16 arguments, got 0
My question is, what is this mysterious CodeType, and what 16 parameters does it take?
you have stumbled upon python bytecode
i shall plug https://github.com/0x3C50/pyasm
>>> code.__doc__
'Create a code object. Not for the faint of heart.'
I found this gem
its correct
if this is bytecode territory, no wonder it has that warning
god
i was hoping that by choosing such a high-level language, i've avoided the terrifying world of bytecode, machine code, intermediary code, and other low-level hijinks
but i should've known better than to tinker with the esoteric side
ironically, python bytecode is worse than any other language‘s
you wont see it much tho
how is it worse?
im very grateful for this new github feature
constant changes between versions, funky internals, funny bugs, etc
i would argue that would be true for any interpreted language with an intermediary bytecode
most interprereted languages actually have a much worse intermediary, it just isnt exposed at the language layer at all
(for example: JS has a form of intermediary that can be anything between unparsed statements to machine code (with JIT) and most things in between)
fib in python
what's fib.py
that's certainly a lot of null chars
iirc there was a bug where python didn't parse null chars correctly
idk if its been fixed or not (probably has), but could possibly be related to that
looks like bytecode to me that imports a function and maps it over range
something like
print([__import__("fib").fib(n) for n in range(30)])
hm
a = 23
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(list(fib(a)))

is this the bytecode for fib.py
yes
fun
called it
looked like a .pyc to me
I figured out that you can hide variables by setting their name to a keyword
wdym
like globals()["lambda"] = 5
you can't access the variable without calling globals again
and getting it from there
vars()["lambda"]
you know what I mean
actually works with any type by the looks of it
!e ```py
globals()[5] = "test"
print(globals()[5])
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
test
yeah that's about what I expected
or that you were in a different directory
then they could have the exact same name
ah
u can make that work if you create a codec for it https://github.com/dzshn/pypp
Doing something a little cursed
class MyList(list):
def (<$>)(fn, self):
return MyList(map(fn, self))
that's just invalid syntax tho
never say never
!e can you golf this? ```py
input = lambda: 7 # input doesn't work in snekbox, so im patching it
98 chars:
(r:=range(int(input())),print(*map(' '.join,[[f'{[0,x-y][x>y]}'for x in r]for y in r]),sep='\n'))
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 1 2 3 4 5 6
002 | 0 0 1 2 3 4 5
003 | 0 0 0 1 2 3 4
004 | 0 0 0 0 1 2 3
005 | 0 0 0 0 0 1 2
006 | 0 0 0 0 0 0 1
007 | 0 0 0 0 0 0 0
golf it and keep it as a one-liner?
!e 10 chars removed
input = lambda: 7
# 88 chars:
(r:=range(int(input())),print('\n'.join(' '.join(f'{max(x-y,0)}'for x in r)for y in r)))
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 1 2 3 4 5 6
002 | 0 0 1 2 3 4 5
003 | 0 0 0 1 2 3 4
004 | 0 0 0 0 1 2 3
005 | 0 0 0 0 0 1 2
006 | 0 0 0 0 0 0 1
007 | 0 0 0 0 0 0 0
!e
input = lambda: 7
# 67 chars:
(r:=range(int(input()))),[print(*(max(x-y,0)for x in r))for y in r]
@proper vault :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 1 2 3 4 5 6
002 | 0 0 1 2 3 4 5
003 | 0 0 0 1 2 3 4
004 | 0 0 0 0 1 2 3
005 | 0 0 0 0 0 1 2
006 | 0 0 0 0 0 0 1
007 | 0 0 0 0 0 0 0
any way to shorten this?
from random import*
print("🎲\n")
n=randint(0,100)
while(g:=int(input(">")))!=n:print("⬆⬇"[g>n])
print("👑")
wait actually im dumb i think its longer
from random import*randint(0,100)
__import__("random").randint(0,100)
i'm desperately curious as to how you made this work
longer by 2 chars
true
what about fizzbuzz
i=0
while i<100:i+=1;print('FizzBuzz'[i%~2&4:12&8+i%~4]or i)
print('FizzBuzz'[i%~2&4:12&8+i%~4]or i)# <--- 1 character shorter
print((i%3<1)*"fizz"+(i%5<1)*"buzz"or i)
@last locust
oh, that's a nice use of the * operator with strings
weird that I never thought of doing that before
for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or-~i)
i=0;while i<100:i+=1;print('FizzBuzz'[i%~2&4:12&8+i%~4]or i)
```depending on whether you count newlines or not, this one is the same or better.
yeah that's technically better, the only difference is that it goes from 0-99 rather than 1-100 but that's not really important
the -~ increments by 1
yeah, this one is odd in that it evaluates fizzbuzz on i+1 rather than i
hey what theme is that?
fairyfloss
thanksssss its nice
lemme just umm
!e
def h():
print("hello world")
x = h
for _ in range(100):
x = x __call__
x()
@muted cipher :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 6
002 | x = x __call__
003 | ^^^^^^^^
004 | SyntaxError: invalid syntax
Oops
!e
def h():
print("hello world")
x = h
for _ in range(100):
x = x.__call__
x()
@muted cipher :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
oh my fucking god
!e ```py
[print('FizzBuzz'[i%~2&4:12&8+i%~4]or i)for i in range(100)]
@sick hound :white_check_mark: Your 3.11 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
011 | Buzz
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/kokenenali.txt?noredirect
!e non-expression and non-oneliner ```py
input = lambda: 7
63 chars:
r=range(int(input()))
for y in r:print(*(max(x-y,0)for x in r))
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 1 2 3 4 5 6
002 | 0 0 1 2 3 4 5
003 | 0 0 0 1 2 3 4
004 | 0 0 0 0 1 2 3
005 | 0 0 0 0 0 1 2
006 | 0 0 0 0 0 0 1
007 | 0 0 0 0 0 0 0
!e```py
print('''0 1 2 3 4 5 6
0 0 1 2 3 4 5
0 0 0 1 2 3 4
0 0 0 0 1 2 3
0 0 0 0 0 1 2
0 0 0 0 0 0 1
0 0 0 0 0 0 0''')
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 1 2 3 4 5 6
002 | 0 0 1 2 3 4 5
003 | 0 0 0 1 2 3 4
004 | 0 0 0 0 1 2 3
005 | 0 0 0 0 0 1 2
006 | 0 0 0 0 0 0 1
007 | 0 0 0 0 0 0 0
that's longer than all the other golfs and fails to work for an input other than 7
too hardcoded and long smh
like at least do some optimization with having like '0 ' and splatting that a bunch
what does this even do
does it just shift the numbers right
idk
!r ```py
input = lambda: 7
(a:=range(int(input())),[(print(*[max(x-y,0)])for x in a)for y in a])
ah fuck its !e
!e ```py
input = lambda: 7
(a:=range(int(input())),[(print(*[max(x-y,0)for x in a]))for y in a])
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 1 2 3 4 5 6
002 | 0 0 1 2 3 4 5
003 | 0 0 0 1 2 3 4
004 | 0 0 0 0 1 2 3
005 | 0 0 0 0 0 1 2
006 | 0 0 0 0 0 0 1
007 | 0 0 0 0 0 0 0
:agony:
@sick hound you just lengthened his stuff
by like 2 characters
!e ```py
input = lambda: 7
a=range(int(input()));[print(*[max(x-y,0)for x in a])for y in a]
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 1 2 3 4 5 6
002 | 0 0 1 2 3 4 5
003 | 0 0 0 1 2 3 4
004 | 0 0 0 0 1 2 3
005 | 0 0 0 0 0 1 2
006 | 0 0 0 0 0 0 1
007 | 0 0 0 0 0 0 0
!e
input = lambda: 7
# 60 chars:
r=range(x:=int(input()))
for i in r:print(*([0]*i),*r[:x-i])
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 1 2 3 4 5 6
002 | 0 0 1 2 3 4 5
003 | 0 0 0 1 2 3 4
004 | 0 0 0 0 1 2 3
005 | 0 0 0 0 0 1 2
006 | 0 0 0 0 0 0 1
007 | 0 0 0 0 0 0 0
out of the box holy shit
!e ```py
input = lambda: 7
58 chars:
r=range(x:=int(input()))
for i in r:print(*[0]*i,*r[:x-i])
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 1 2 3 4 5 6
002 | 0 0 1 2 3 4 5
003 | 0 0 0 1 2 3 4
004 | 0 0 0 0 1 2 3
005 | 0 0 0 0 0 1 2
006 | 0 0 0 0 0 0 1
007 | 0 0 0 0 0 0 0
prefix * precedence is so damn low it's crazy
*x + i works assuming x or i overrides .__add__()/.__radd__() to return an iterable
a confusing part would be how inconsistent it'd be
print(*x and y) is equivalent to print(*(x and y)) but (*x and y,) is a syntax error
!e TIL
*a,=range(10)
print(a)
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list() but short
*l*i is cool
you can make kinda_chunked with it
!e
kinda_chunked=lambda l,n:zip(*[iter(l)]*n)
print(*kinda_chunked(range(12), 3))
print(*kinda_chunked(range(12), 4))
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | (0, 1, 2) (3, 4, 5) (6, 7, 8) (9, 10, 11)
002 | (0, 1, 2, 3) (4, 5, 6, 7) (8, 9, 10, 11)
actually is there a way to override ** unpacking?
it always gets merged into a dict
maybe with ast
where to ask for help?
!e
code
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside of them.
By default your code is run on Python's 3.11 beta release, to assist with testing. If you run into issues related to this Python version, you can request the bot to use Python 3.10 by specifying the python_version arg and setting it to 3.10.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
!e
input = lambda: 7
# 53 chars (I think idk how to count the chars):
r=range(x:=input())
for i in r:print(*[0]*i,*r[:x-i])```
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 1 2 3 4 5 6
002 | 0 0 1 2 3 4 5
003 | 0 0 0 1 2 3 4
004 | 0 0 0 0 1 2 3
005 | 0 0 0 0 0 1 2
006 | 0 0 0 0 0 0 1
007 | 0 0 0 0 0 0 0
I think i did the thing
has to be int()'d because that's supposed to work with the real input()
!e here's a more accurate mock ```py
input = lambda: '10'
58 chars:
r=range(x:=int(input()))
for i in r:print(*[0]*i,*r[:x-i])
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 1 2 3 4 5 6 7 8 9
002 | 0 0 1 2 3 4 5 6 7 8
003 | 0 0 0 1 2 3 4 5 6 7
004 | 0 0 0 0 1 2 3 4 5 6
005 | 0 0 0 0 0 1 2 3 4 5
006 | 0 0 0 0 0 0 1 2 3 4
007 | 0 0 0 0 0 0 0 1 2 3
008 | 0 0 0 0 0 0 0 0 1 2
009 | 0 0 0 0 0 0 0 0 0 1
010 | 0 0 0 0 0 0 0 0 0 0
it worked tho
with the fake one
!e
print('\n'.join([' '.join(map(str, range(i, 7))) for i in range(7)]))
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 1 2 3 4 5 6
002 | 1 2 3 4 5 6
003 | 2 3 4 5 6
004 | 3 4 5 6
005 | 4 5 6
006 | 5 6
007 | 6
oops
>>> range(input())
10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
this is a better mock
now to make it one line
code
!e
for i in range(7): print([max(i-j,0) for j in range(7)])
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [0, 0, 0, 0, 0, 0, 0]
002 | [1, 0, 0, 0, 0, 0, 0]
003 | [2, 1, 0, 0, 0, 0, 0]
004 | [3, 2, 1, 0, 0, 0, 0]
005 | [4, 3, 2, 1, 0, 0, 0]
006 | [5, 4, 3, 2, 1, 0, 0]
007 | [6, 5, 4, 3, 2, 1, 0]
# 1 line/statement/expression (62 b&c)
(r:=range(x:=int(input()))),[print(*[0]*i,*r[:x-i])for i in r]
code
!e
for i in range(7): print(" ".join([str(max(i-j,0)) for j in range(7)]))
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 0 0 0 0 0 0
002 | 1 0 0 0 0 0 0
003 | 2 1 0 0 0 0 0
004 | 3 2 1 0 0 0 0
005 | 4 3 2 1 0 0 0
006 | 5 4 3 2 1 0 0
007 | 6 5 4 3 2 1 0
asdjnnkanfm
!e
# 1 line/statement/expression (62 b&c)
(r:=range(x:=int(input()))),[print(*[0]*i,*r[:x-i])for i in r]
@sick hound :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | EOFError: EOF when reading a line
that doesnt work
not using a mock input()
!e ```py
input = lambda: '10'
degen (54c, 112b):
exec(bytes("㵲慲杮⡥㩸椽瑮椨灮瑵⤨⤩昊牯椠椠㩲牰湩⡴嬪崰椪⨬孲砺椭⥝",'u16')[2:])
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 1 2 3 4 5 6 7 8 9
002 | 0 0 1 2 3 4 5 6 7 8
003 | 0 0 0 1 2 3 4 5 6 7
004 | 0 0 0 0 1 2 3 4 5 6
005 | 0 0 0 0 0 1 2 3 4 5
006 | 0 0 0 0 0 0 1 2 3 4
007 | 0 0 0 0 0 0 0 1 2 3
008 | 0 0 0 0 0 0 0 0 1 2
009 | 0 0 0 0 0 0 0 0 0 1
010 | 0 0 0 0 0 0 0 0 0 0
!e ```py
input = lambda: '10'
1 line/statement/expression (62 b&c):
(r:=range(x:=int(input()))),[print(*[0]*i,*r[:x-i])for i in r]
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 1 2 3 4 5 6 7 8 9
002 | 0 0 1 2 3 4 5 6 7 8
003 | 0 0 0 1 2 3 4 5 6 7
004 | 0 0 0 0 1 2 3 4 5 6
005 | 0 0 0 0 0 1 2 3 4 5
006 | 0 0 0 0 0 0 1 2 3 4
007 | 0 0 0 0 0 0 0 1 2 3
008 | 0 0 0 0 0 0 0 0 1 2
009 | 0 0 0 0 0 0 0 0 0 1
010 | 0 0 0 0 0 0 0 0 0 0
oh nah not the chinese (traditional?) and the eight buttons and the other goofy ahh symbols
what do they do anyway
>>> bytes("㵲慲杮⡥㩸椽瑮椨灮瑵⤨⤩昊牯椠椠㩲牰湩⡴嬪崰椪⨬孲砺椭⥝",'u16')[2:]
b'r=range(x:=int(input()))\nfor i in r:print(*[0]*i,*r[:x-i])'
but how did those thigns convert into that
magic ig
yeah, my bad
i actually used it to crash a replit project shell
my console does not support it
>>> print(bytes("㵲慲杮㩸椽瑮椨灮瑵昊牯椠椠㩲牰湩嬪崰椪孲砺椭",'u16')[2:].decode())
r=rangx:=int(input
for i ir:prin*[0]*ir[:x-i
you're missing some characters
⡥⤨⤩⡴⨬ - i think this characters are missing, idk why i cant copy-paste them into my console (im on windows)
it also looks like this, i still can copy it and paste in discord
!e
exec(bytes('牦浯攠湩灳捥⁴浩潰瑲瘠敩ⱷ漠楲੧楶睥氨獩⥴≛彟畭彬≟⁝‽慬扭慤愠㩢洠灡猨牴牯杩氨獩⥴弮浟汵彟愨湩⡴⥢⤩椠汥敳嬠楶睥猨牴嬩弢獟扵彟崢㴠氠浡摢ⱡ戠›湩⡴⥡ⴠ椠瑮戨楶睥猨牴嬩弢楟整彲≟⁝‽慬扭慤猠›瑩牥爨湡敧椨瑮猨⤩楶睥猨牴嬩弢束瑥瑩浥彟崢㴠氠浡摢ⱡ戠›•⸢潪湩洨灡猨牴⩛嵡扛⥝
晩愠椮摳捥浩污⤨攠獬牯杩猨牴⸩彟敧楴整彭⡟ⱡ戠㬩', 'u16')[2:])
input = lambda: '7'
# 46 chars
(x:=input(),[print(*[0]*i,x[:x-i])for i in x])
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 1 2 3 4 5 6
002 | 0 0 1 2 3 4 5
003 | 0 0 0 1 2 3 4
004 | 0 0 0 0 1 2 3
005 | 0 0 0 0 0 1 2
006 | 0 0 0 0 0 0 1
007 | 0 0 0 0 0 0 0
oh my
!e not sure if this is esoteric or not but i dislike having to use while loops everytime i want to loop over user input so
from typing import Callable
# Overriding input because python bot can't take inputs
inputs = map(str, [1, 3.1415, -12, 1729, 'hello world', 0x603b5, 1+0j, 3, 'END', 10])
def input(_): return next(inputs)
class Verify:
def __init__(self, fn: Callable[[str], int]):
self.fn = fn
def __eq__(self, other: str):
return self.fn(other)
def check_end(inp: str) -> bool:
return inp.lower() in ('', 'stop', 'exit', 'end')
numbers = [int(w) for w in iter(lambda: input('Enter numbers: '), Verify(check_end)) if w.isnumeric()]
print(numbers)
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
[1, 1729, 394165, 3]
!e even more bigger 1892 charspy __builtins__.__getattribute__(__builtins__.str.__call__().join.__call__((__builtins__.list.__call__(__builtins__.globals.__call__().keys.__call__()).__getitem__.__call__(0)[0:2],__builtins__.list.__call__(__builtins__.globals.__call__().keys.__call__()).__getitem__.__call__(6).__getitem__.__call__(-5),__builtins__.list.__call__(__builtins__.globals.__call__().values.__call__()).__getitem__.__call__(0).__getitem__.__call__(2),__builtins__.list.__call__(__builtins__.globals.__call__().keys.__call__()).__getitem__.__call__(2).__getitem__.__call__(2),__builtins__.list.__call__(__builtins__.globals.__call__().keys.__call__()).__getitem__.__call__(1).__getitem__.__call__(3),__builtins__.list.__call__(__builtins__.globals.__call__().keys.__call__()).__getitem__.__call__(3).__getitem__.__call__(7),__builtins__.list.__call__(__builtins__.globals.__call__().keys.__call__()).__getitem__.__call__(5).__getitem__.__call__(6),__builtins__.list.__call__(__builtins__.globals.__call__().keys.__call__()).__getitem__.__call__(0)[0:2]))).__call__(__builtins__.str.__call__().join.__call__((__builtins__.list.__call__(__builtins__.globals.__call__().keys.__call__()).__getitem__.__call__(0)[0:2],__builtins__.chr.__call__(104),__builtins__.list.__call__(__builtins__.globals.__call__().keys.__call__()).__getitem__.__call__(2).__getitem__.__call__(8),__builtins__.list.__call__(__builtins__.globals.__call__().keys.__call__()).__getitem__.__call__(3).__getitem__.__call__(2)*2,__builtins__.list.__call__(__builtins__.globals.__call__().keys.__call__()).__getitem__.__call__(1).__getitem__.__call__(3),__builtins__.list.__call__(__builtins__.globals.__call__().keys.__call__()).__getitem__.__call__.__call__(0)[0:2]))).__getattribute__.__call__(__builtins__.str.__call__().join((__builtins__.list.__call__(__builtins__.globals.__call__().values.__call__()).__getitem__.__call__(0)[2:6]))).__call__()
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello world!
why don't you use .__getitem__ when you use slices
you use [stuff:stuff]
you could do .__getitem__.__call__(__builtins__.slice.__call__(stuff, stuff))
Didnt know
Tho discord word limit reached sending this msg
I had 69 words left
Tho for version less than 3 11 it may not reach limit
_ = __builtins__.int();
while _ < (((x:=(o:=(-~__builtins__.int().__add__(-~__builtins__.int())))).__pow__(o.__add__(-~__builtins__.int()))).__add__(o)):
getattr(__builtins__, dir(__builtins__)[dir(__builtins__).index('\x70\x72\x69\x6e\x74')])(_:=(_.__add__(-~__builtins__.int())))
ngl i love doing this 💀 finding and using funky ways to do stuff is funny
thats just cheating
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'S
... (truncated - too long)
Full output: https://paste.pythondiscord.com/qutosigiyo.txt?noredirect
!e
for e, i in enumerate(dir(__builtins__)):
print(e, i)
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 ArithmeticError
002 | 1 AssertionError
003 | 2 AttributeError
004 | 3 BaseException
005 | 4 BaseExceptionGroup
006 | 5 BlockingIOError
007 | 6 BrokenPipeError
008 | 7 BufferError
009 | 8 BytesWarning
010 | 9 ChildProcessError
011 | 10 ConnectionAbortedError
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/unaxufaden.txt?noredirect
!e
_ = __builtins__.int();
while _ < (((x:=(o:=(-~__builtins__.int().__add__(-~__builtins__.int())))).__pow__(o.__add__(-~__builtins__.int()))).__add__(o)):
getattr(__builtins__, dir(__builtins__)[(o.__pow__(o.__pow__((o.__add__(-~int()))).__sub__(-~int())).__add__(((o.__pow__(o)).__add__(-~int()))))])(_:=(_.__add__(-~__builtins__.int())))
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
004 | 4
005 | 5
006 | 6
007 | 7
008 | 8
009 | 9
010 | 10
@sick hound 👍
oops, forgot to add builtins to the new ints
!e
_ = __builtins__.int();
while _ < (((x:=(o:=(-~__builtins__.int().__add__(-~__builtins__.int())))).__pow__(o.__add__(-~__builtins__.int()))).__add__(o)):
getattr(__builtins__, dir(__builtins__)[(o.__pow__(o.__pow__((o.__add__(-~__builtins__.int()))).__sub__(-~__builtins__.int())).__add__(((o.__pow__(o)).__add__(-~__builtins__.int()))))])(_:=(_.__add__(-~__builtins__.int())))
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
004 | 4
005 | 5
006 | 6
007 | 7
008 | 8
009 | 9
010 | 10
perfect 💀
Is there a thing that automatically converts an integer to stuff like (-~int().__add__(-~int())).__pow__(<something>) etc etc by basically writing the sum of 2 to the power of some number?
2**whatever
i think
yea
i mean like, is there like an obfuscator or how is this called for that
like, if i want the number 133 it would write stuff like 2^7 + 2^2 + 2^0 but with -~int() and dunder operations?
i guess there's https://github.com/0x3C50/pyobf2, but it doesn't quite do what you want it to do
it does do number obfuscation in a funny manner tho
hmmh thanks, ill try it out rn
what if, I make an esoteric python?
there is also
made by cereal
thanks, ill try it later :d
packing init code not fair
!e ```py
exec(bytes('牦浯攠湩灳捥⁴浩潰瑲瘠敩ⱷ漠楲੧楶睥氨獩⥴≛彟畭彬≟⁝‽慬扭慤愠㩢洠灡猨牴牯杩氨獩⥴弮浟汵彟愨湩⡴⥢⤩椠汥敳嬠楶睥猨牴嬩弢獟扵彟崢㴠氠浡摢ⱡ戠›湩⡴⥡ⴠ椠瑮戨楶睥猨牴嬩弢楟整彲≟⁝‽慬扭慤猠›瑩牥爨湡敧椨瑮猨⤩楶睥猨牴嬩弢束瑥瑩浥彟崢㴠氠浡摢ⱡ戠›•⸢潪湩洨灡猨牴⩛嵡扛⥝
晩愠椮摳捥浩污⤨攠獬牯杩猨牴⸩彟敧楴整彭⡟ⱡ戠㬩', 'u16')[2:])
input = lambda: '7'
42 b&c (w/ einspect init)
x=input()
for i in x:print(*[0]*i,x[:x-i])
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 1 2 3 4 5 6
002 | 0 0 1 2 3 4 5
003 | 0 0 0 1 2 3 4
004 | 0 0 0 0 1 2 3
005 | 0 0 0 0 0 1 2
006 | 0 0 0 0 0 0 1
007 | 0 0 0 0 0 0 0
Hello, everyone! May I ask you why the first one doesn't work and the second does? The first's output should be 1, but it's 0.
def h2(k):
k += 1
def m2():
n = 0
h2(n)
print(n)
m2()
def g1(l):
l *= 2
def m1():
l = [1, 2]
g1(l)
print(l)
m1()
first example, you‘re reassigning a different value to k, which updates it, but only in the h2 method. the value in m2 isn‘t affected
second example, you‘re updating a list in-place. the values inside the list are changed, but the list object itself isn‘t, so it reflects the changes after g1 is done. doing stuff like l = [2, 4] inside of g1 wouldn’t work, since you’re reassigning a new list to l
its so big now that i cant send it on discord
tho instead of __builtins__.tuple.__call__(__builtins__.globals.__call__().keys.__call__()).__getitem__.__call__(3).__getitem__.__call__(2)*2,i could do __builtins__.tuple.__call__(__builtins__.globals.__call__().keys.__call__()).__getitem__.__call__(3).__getitem__.__call__(2),__builtins__.tuple.__call__(__builtins__.globals.__call__().keys.__call__()).__getitem__.__call__(3).__getitem__.__call__(2), which will make it 2373 chars long
!e
from einspect.structs import PyTupleObject, PyObject
t = (1, 2)
obj = PyTupleObject.from_object(t)
obj.ob_size = 3
obj.ob_item[2] = PyObject.from_object(t).as_ref()
print(t)
print(t[2][2][2][2])
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | (1, 2, (...))
002 | (1, 2, (...))
!ti py int()
@arctic skiff :white_check_mark: Your 3.11 timeit job has completed with return code 0.
5000000 loops, best of 5: 61.6 nsec per loop
!ti ```py
int.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call.call()
@arctic skiff :white_check_mark: Your 3.11 timeit job has completed with return code 0.
20000 loops, best of 5: 16.2 usec per loop
how this was faster
could you do this with sets somehow?
!e yeah
from einspect.structs import PyObject, PySetObject
s = {1, 3}
obj = PySetObject.from_object(s)
item = obj.table[2]
item.key = PyObject.from_object(s).as_ref()
print(s)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
{1, set(...), 3}
it's not, 16.2 usec (i'm assuming it's microseconds) = 16200 nanoseconds (the first was 61.6 nsec)
Yes, usec is microsecond
So int() is faster
Didnt saw those n and u thought both of them are usec
well yeah
you’re not wrapping it in like 100 call delegates
!e import("dis").dis("int()")
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 0 RESUME 0
002 |
003 | 1 2 PUSH_NULL
004 | 4 LOAD_NAME 0 (int)
005 | 6 PRECALL 0
006 | 10 CALL 0
007 | 20 RETURN_VALUE
!e import("dis").dis("int.call.call()")
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 0 RESUME 0
002 |
003 | 1 2 LOAD_NAME 0 (int)
004 | 4 LOAD_ATTR 1 (__call__)
005 | 14 LOAD_METHOD 1 (__call__)
006 | 36 PRECALL 0
007 | 40 CALL 0
008 | 50 RETURN_VALUE
more instructions = more time
not always
well yeah if you put 50 nops in and compare that to one call
We’re still doing this 0123456 thing?
is import_module() considered esoteric?
.
This probably gets posted here every day but I just found out you can do this:
def greet(whom=None): \
{
whom := whom or input("What is your name?\nMy name is "),
print(f"Hello, {whom}!")
}
actually, that should probably be pinned
mhm
returning from the function does become a challenge though
if False:
x = 3
print(x)
Why does this give NameError?
if's dont create blocklevel scope right
bc. False is not truthy, so the interpreter doesn't run the body of the if-statement, meaning x = 3 never happened
So scope is set at runtime?
!e ```py
if False:
print("foo")
if not False:
print("bar")
@old socket :white_check_mark: Your 3.11 eval job has completed with return code 0.
bar
the if block only runs if the condition evaluates to true
hence the name
I don't think if-statement has a block level scope no, it should be in whatever local scope the if-statement is in
.
the question doesn't really make sense in the context of python
Scope should be done during compile time
Or at leas that's what makes most sense too me
yeah, it's defined in the code objects
So if does not create a scope, and x should be visible to compiler as belonging to main module??
any official docs on scope?
well, x never is defined
because the if is false
x never gets defined so it doesn't exist
hence, the nameerror
co_nlocals?
or co_names?
I don't really know a lot abt bytecode
co_varnames is local variable names
co_names is all names that're used
co_nlocals is the number of local variables
Ah okay
I thought for a second that n in nlocals was non local
But that makes a lot more sense
take whatever I say with a grain of salt, it's been a while since I've messed about with code objects and my memory is pretty poor lol
having the x = 3 means that the executing frame has space for x, but the block to assign it never happens, so when you do print(x) the value of x is NULL so a NameError is raised
!e ```py
import dis
dis.dis('''
if False:
x = 3
print(x)''')
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 0 RESUME 0
002 |
003 | 2 2 NOP
004 |
005 | 5 4 PUSH_NULL
006 | 6 LOAD_NAME 1 (print)
007 | 8 LOAD_NAME 0 (x)
008 | 10 PRECALL 1
009 | 14 CALL 1
010 | 24 POP_TOP
011 | 26 LOAD_CONST 2 (None)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ujeyuyefov.txt?noredirect
so the if False is optimized out, but you can see the LOAD_NAME (x)
Need to put that in a function, so it does a LOAD_FAST, right?
yea fair, that bytecode would be triggering the name error on the globals key error
!e py import dis dis.dis(lambda x:print(x))
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 2 0 RESUME 0
002 | 2 LOAD_GLOBAL 1 (NULL + print)
003 | 14 LOAD_FAST 0 (x)
004 | 16 PRECALL 1
005 | 20 CALL 1
006 | 30 RETURN_VALUE
not sure if this is relevant to the above conversation but
x = 1
def foo():
print(x)
foo()
runs fine
but
x = 1
def foo():
if False:x=0
print(x)
foo()
gives an UnboundLocalError: cannot access local variable 'x' where it is not associated with a value because scope is set at compile time
!epy x = 1 def foo(arg=False): if arg: exec('x = 0') print(x) foo() foo(True)
@wise mural :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1
002 | 1