#esoteric-python
1 messages ยท Page 109 of 1
!e
from math import factorial as f
print(f(0))
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
1
!e
from math import factorial as f
print(f(False))
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
1
!e print(__import__("math").factorial(__import__("__main__").__doc__.__bool__()))
@toxic jewel :white_check_mark: Your eval job has completed with return code 0.
1
how tell us your secrets
Better to use a metaclass
so ive been told
python reads those characters as abc
!e True = False; print(True)
@toxic jewel :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | True = False; print(True)
003 | ^
004 | SyntaxError: cannot assign to True
;^(
Only on Python 2.
ya'll in here pushing the oneliner limits i see lol
!e def ๐๐๐๐กo(๐๐ฎ๐๐):
๐
๐ง๐พ๐ท๐(f"Hello {๐ง๐๐๐}!")
๐ก๐lโโ('World')
@wary falcon :white_check_mark: Your eval job has completed with return code 0.
Hello World!
whaaaa
!e
from ctypes import c_void_p
from random import randint
class foo:
def __repr__(self):
return "True" if randint(0, 10) <= 5 else "False"
class bar:
def __repr__(self):
return "False" if randint(0, 10) <= 5 else "True"
c_void_p.from_address(id(True)+8).value = id(foo)
c_void_p.from_address(id(False)+8).value = id(bar)
print(True)
print(False)
@autumn saffron :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | False
hm
!e
from ctypes import c_void_p
from random import randint
class foo:
def __repr__(self):
return "True" if randint(0, 10) <= 5 else "False"
class bar:
def __repr__(self):
return "False" if randint(0, 10) <= 5 else "True"
c_void_p.from_address(id(True)+8).value = id(foo)
c_void_p.from_address(id(False)+8).value = id(bar)
print(True)
print(False)
@autumn saffron :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | True
!e
from ctypes import c_void_p
from random import randint
class foo:
def __repr__(self):
return "True" if randint(0, 10) <= 5 else "False"
class bar:
def __repr__(self):
return "False" if randint(0, 10) <= 5 else "True"
c_void_p.from_address(id(True)+8).value = id(foo)
c_void_p.from_address(id(False)+8).value = id(bar)
print(True)
print(False)
@autumn saffron :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | True
!e
!eval [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.
We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*
!e print("hello world")
@valid crow :white_check_mark: Your eval job has completed with return code 0.
hello world
!e
n1 = int(input("enter your first number"))
n2 = int(input("enter your second number"))
print(n1+n2)
@valid crow :x: Your eval job has completed with return code 1.
001 | enter your first numberTraceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
n1 = int(input("enter your first number"))
n2 = int(input("enter your second number"))
print(n1+n2)
n1 = int(input("enter your first number"))
n1 = 5
n2 = int(input("enter your second number"))
n2 = 5
print(n1+n2)
!e n1 = int(input("enter your first number"))
n1 = 5
n2 = int(input("enter your second number"))
n2 = 5
print(n1+n2)
@valid crow :x: Your eval job has completed with return code 1.
001 | enter your first numberTraceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
sadness
Feel free to use #bot-commands for more testing.
All identifiers are converted into the normal form NFKC while parsing; comparison of identifiers is based on NFKC.
https://docs.python.org/3/reference/lexical_analysis.html#identifiers
!e
z = lambda: (print("hello") or True) and print("world")
z()โ
@verbal totem :white_check_mark: Your eval job has completed with return code 0.
001 | hello
002 | world
Does this count as cheating?
No.
What's your goal?
to make print have a 1 in 3 chance of Segmentation Fault
my first attempt made it 1 in 3 chance a recursion would occur each recursion
this one isn't properly crashing
!e ```py
def print(*args,sep=chr(32),end=chr(10),file=import('sys').stdout):
try:
import random
file.write(str(sep).join([str(e)for e in args])+str(end))
1/random.randint(0,2)
except:
def print(*a,**k):
try:print(*a,**k)
except:print(*a,**k)
print (*args,sep=sep,end=end,file=file)
print ("Hello", "World", end="!\n")
print ("Hello", "World", end="!\n")
print ("Hello", "World", end="!\n")
print ("Hello", "World", end="!\n")
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | Hello World!
002 | Hello World!
003 | Hello World!
004 | Fatal Python error: _Py_CheckRecursiveCall: Cannot recover from stack overflow.
005 | Python runtime state: initialized
006 |
007 | Current thread 0x00007fe62b4d5740 (most recent call first):
008 | File "<string>", line 8 in print
009 | File "<string>", line 8 in print
010 | File "<string>", line 8 in print
011 | File "<string>", line 8 in print
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ifiwajifut.txt
!e ```py
import ctypes, random
def unstable(f):
def inner(*args, **kwargs):
if random.randint(0, 2) == 0:
ctypes.string_at(0)
f(*args, **kwargs)
return inner
print = unstable(print)
for x in range(10):
print(x)
@earnest wing :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | 0
002 | 1
003 | 2
004 | 3
why doesn't that have the faulthandler thing
isn't that how faulthandler works in the first place 
!e ```py
def print(*args,sep=chr(32),end=chr(10),file=import('sys').stdout):
try:
import random
file.write(str(sep).join([str(e)for e in args])+str(end))
1/random.randint(0,3)
except:
def print(*a,**k):
try:builtins.print(*a,**k)or print(*a,**k)
except:print(*a,**k)
print (*args,sep=sep,end=end,file=file)
for i in range(10): print (i)
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 6
009 | 6
010 | 6
011 | 6
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/begiwokivi.txt
The interpreter would have to check every memory access. It would be even slower.
might need to enable it with a commandline flag
yeah, python3 -X faulthandler
I'm unfamiliar with the faulthandler. What's its use case?
Cool beans.
odd that it doesn't work for some faults
you'd expect stack overflows and bad reads both trigger it
funny it actually has an example using ctypes.string_at(0)
implementation specific behavior :mystery:
turns out you don't need faulthandler to get the stack overflow message makes sense
so each call just gets checked on the c side for overflow?
i think the python vm doesn't check if the python stack is getting too large after every FAST instruction (and some others?). i'm also pretty sure that you can ignore a recursion error (and keep recusing) 50 times until the python vm says there was a fatal error and dies. Also seems like an actual stack overflow will cause a MemoryError and not a RecursionError
maybe not 50 times... i was just reading the source code but apparently I was wrong. It only worked 1 time before dying.
wait i'm wrong again, it only hits the except block 1 time but it does allow you to keep recursing 50 times
I thought you can recurse 1000 times until a recursion error
You can catch the error, or prevent it altogether with sys.setrecursionlimit
!e ```py
import('sys').setrecursionlimit(9999999)
def print(*args):
try: print (*args)
except: print (*args)
print ("Hello World!")
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
huh, much better than the last one
Is it possible to use list comprehension to flatten a list?
Here's my looping code:
def flatten(list_to_flatten):
flat_list = []
for item in list_to_flatten:
if type(item) is list:
flat_list += flatten(item)
else:
flat_list.append(item)
return flat_list
Tried to convert it into this but it doesn't run:
def fl(list_to_flatten):
return [i for i in fl(item) if type(item) is list else item for item in list_to_flatten]
so then I tried this:
def fl(list_to_flatten):
return [i for i in [fl(item) if type(item) is list else item for item in list_to_flatten]]
but it turns out that's just a glorified way to return the exact item passed in
fl([1,2,3[4,5,6]]) = [1,2,3[4,5,6]]
the tricky part is getting fl(item) and item to work in the same comprehension, somehow
If I can manage to write it using list comprehension then that opens the door for flattening lambda functions which would be super cool
imagine using max with a flattening lambda function as a key, for example
[x for item in input_list for x in item if isinstance(item, list) else [item]] might work.
File "<stdin>", line 1
t = [x for item in input_list for x in item if isinstance(item, list) else [item]]
^
SyntaxError: invalid syntax
swap the condition and the for
Or bracket the item if ... [item] part.
>>> input_list = [1,2,3,[4,5,6],7]
>>> [x for item in input_list for x in [item if isinstance(item, list) else [item]]]
[[1], [2], [3], [4, 5, 6], [7]]
same as my attempt, just replicates the list 1:1
Regular brackets, not square ones.
parenthesis?
I stand by what I said. () these things.
Alright, i'll try it out :)
eyy yeah it totally works
nice one
so, out of curiosity
why do the parens make it work?
(and here is the code for anybody curious):
[x for item in input_list for x in (item if isinstance(item, list) else [item])]
also, looks like it's not fully recursive, only works on singly nested lists
although it wouldn't be hard to make it recursive, I think
Without them it parses as [expr for var in iterable if condition], but then it sees the else keyword and gets confused.
here's a version that works on arbitrarily nested lists:
def fl(input_list):
return [x for item in input_list for x in (fl(item) if isinstance(item, list) else [item])]
i'll post a lambda soon
fl = lambda input_list: [x for item in input_list for x in (fl(item) if isinstance(item, list) else [item])]
Alright I made a simple death module
You just import death and it will kill python so hard it will die to death
It prints out...
Fatal Python error: _py_MorsObitusDecessus: Python has died.
Python runtime state: deceased
To sys.stderr then sets recursion limit to 99999 then tortures python to death with pseudo infinite recursion.
Do y'all ever just feel like doing something cursed but having zero ideas
Idea: implement a DSL using decorator and matmul syntax
You'd need at least a few letters
Unless you assume all files use the unicode-escape codec
even then you'll need x
How'd you write code with no letters? ๐
if you mean "without string/bytes literals", then it makes more sense, and might even be possible
actually, even easy if this is allowed:
!e
class hello:pass
class world:pass
print(hello.__name__.title(),world.__name__.title())
@hard spoke :white_check_mark: Your eval job has completed with return code 0.
Hello World
Ha
I think that is part of the challenge. I also think the challenge is impossible.
Can you not use octal \OOO literals in a unicode-escape codec?
fair enough. Like, I don't think there's any valid code which compiles to at least one instruction you can write without any letters or numbers
_=[]?
of course #esoteric-python people would solve this in an instant ๐ฉ
Anything juicy from there probably requires attribute access.
printing anything is still a problem, though. You could get print from builtins, but that'd requires getting the builtins at the very least...
You can construct arbitrary numbers pretty easily.
You wouldn't have easy access to any functions though.
Bytecode manipulation when
Hmm, how? I get how to construct arbitrary numbers after getting some int, but how'd you get that first int?
oh, I got it
+([]==[]) is 1, although you can also use []==[].
yeah, that's what I thought, bool being a subclass of int finally pays off
That fact is also good for array indexing with code golf.
def generate_special_number(x:int) -> str:
if x<0:
return "-"+generate_special_number(-x)
s = []
one = "([]==[])"
two = f"({one}+{one})"
if x==0:
return f"{one}-{one}"
if x==1:
return one
if x==2:
return two
div,mod = divmod(x,2)
s = f"({generate_special_number(div)})*{two}"
if mod:
s+= "+"+generate_special_number(mod)
return s
probably not the most efficient way, but it works
((((((([]==[]))*(([]==[])+([]==[]))+([]==[]))*(([]==[])+([]==[])))*(([]==[])+([]==[])))*(([]==[])+([]==[])))*(([]==[])+([]==[])))*(([]==[])+([]==[]))+([]==[])
is 97, for example
Well, it is nice to have numbers, now we need to have code!
Someone made a generator with True and << at some point, which should be easily modifiable should a smaller number encoding prove useful.
edited above message: fixed bug which included zeros in the representation
What would be an optimal number generator under these rules (i.e. returns the shortest string that evaluates to a number N that doesn't use alphanumeric chars)?
!e ```py
globals()["builtins"].print(globals()["builtins"].int(globals()["builtins"].str(globals()["builtins"].round(111.222333, 3)).replace(".","")))
@fossil estuary :white_check_mark: Your eval job has completed with return code 0.
111222
Good question, this is exactly what I'm doing ๐
well, I'm doing dumb bruteforce search of these combinations
** and << are definitely useful for large numbers
~ and - useful for small ones.
yeah
""<"" seems to be a short way to get 0.
i have some code that errors and runs in the same string lol, idk how it works tbh
If you could somehow get bytes objects...
[*bytes] is an easy way to get certain bytes in the printable ascii range
Or simply indexing into the byte object.
huh, where are floats coming from?..
I somehow got floats from ints using only * + << ** - ~
a ** -b
ah, I see
I think I'll just drop these
0 ([]==[])-([]==[])
1 []==[]
-1 ~(([]==[])-([]==[]))
2 ([]==[])+([]==[])
-2 ~([]==[])
3 ([]==[])-(~([]==[]))
-3 ~(([]==[])+([]==[]))
4 (~([]==[]))*(~([]==[]))
-4 (~([]==[]))+(~([]==[]))
-5 ~((~([]==[]))*(~([]==[])))
5 ([]==[])+((~([]==[]))*(~([]==[])))
6 (~([]==[]))*(~(([]==[])+([]==[])))
-6 (([]==[])-(~([]==[])))*(~([]==[]))
7 ~((~([]==[]))**(([]==[])-(~([]==[]))))
-7 ~((~([]==[]))*(~(([]==[])+([]==[]))))
8 (~([]==[]))*((~([]==[]))+(~([]==[])))
-8 (~([]==[]))**(([]==[])-(~([]==[])))
9 (~(([]==[])+([]==[])))**(([]==[])+([]==[]))
-9 ~((~([]==[]))*((~([]==[]))+(~([]==[]))))
-10 ~((~(([]==[])+([]==[])))**(([]==[])+([]==[])))
10 (~([]==[]))*(~((~([]==[]))*(~([]==[]))))
Though it would be pretty funny to make a function that can yield every possible floating point value
here are some supposedly shortest representations
0: +(''<'')?
I'm not doing strings yet, but hmm
I think it'll only provide a benefit for 0, so no big reason to include it here
the complexity of my algorithm is something like 6**<number of iterations> ๐
the above is only 3 iterations because of that
I could probably use dynamic programming instead if I could inverse all the operations I'm using
like, quickly find, for all the functions I'm using and all a and c, the b such that f(a,b)=c
https://paste.pythondiscord.com/rosejujeva.php
My take on generating shortest representations
Example: output of
results = generate_shortest_reprs(10,-100,100,verbose=False)
for val, rep in results.items():
print(f"{val:4} {rep}")
like, how do you give it the input (like you provided)
!e
print(eval("([]==[])-(((~([]==[]))*(~((~([]==[]))*(~([]==[])))))**(([]==[])+([]==[])))"))
@hard spoke :white_check_mark: Your eval job has completed with return code 0.
-99
it's valid Python code
Yeah, I can tell.
how did you give it this as an input, is what im asking
Oh wait, nvm i had just realised what it was
weird
for val, rep in results.items():
res = eval(rep)
if val!=res:
print(val,res,rep)
-39 -161 ([]==[])-(((~(([]==[])+([]==[])))**((~([]==[]))*(~([]==[]))))<<([]==[]))
40 162 ((~(([]==[])+([]==[])))**((~([]==[]))*(~([]==[]))))<<([]==[])
-41 -164 (~((~(([]==[])+([]==[])))**((~([]==[]))*(~([]==[])))))<<([]==[])
41 163 ([]==[])+(((~(([]==[])+([]==[])))**((~([]==[]))*(~([]==[]))))<<([]==[]))
-42 -164 (~([]==[]))-(((~(([]==[])+([]==[])))**((~([]==[]))*(~([]==[]))))<<([]==[]))
why are these ones bugged?
there we go, fixed it
I mixed up lshift and rshift
Updated outputs:
https://paste.pythondiscord.com/dixuletoso.txt
I added | & ^, but they provided literally zero improvements in length 
hm
this code has this output in my side log
Line 4 : Need type annotation for 's'
Line 14 : Incompatible types in assignment (expression has type "str", variable has type "List[Any]")
Line 17 : Incompatible return value type (got "List[Any]", expected "str")
``` strange.
yeah that's just from reusing s and not giving it a generic type at first
its just my IDE that returns that stuff
no effect on runtime
just lints
mypy doesn't know how to infer generic type parameters for e.g. empty list literals
Huh, i dont use that
most static type checkers don't
i don't know of any that do, beyond some rare circumstances
print(eval("([]==[])-(((~([]==[]))*(~((~([]==[]))*(~([]==[])))))**(([]==[])+([]==[])))"))
How does this get numbers? Does it take the []==[] result and do numerical operations on it? Like int(True) * 10
https://paste.pythondiscord.com/lorumotovu.py
refactored version. mypy checks pass on it.
[]==[] is equal to 1 @plucky wedge
Yes because of True?
mhm
Also, lol, Pycharm's linter (but not mypy) gives me a TypeError here:
(wrongly - this is List[Tuple[str,int]], not List[int])
hey
i copied it from the link and got this
Traceback (most recent call last):
File "<fstring>", line 1
(repres=)
^
SyntaxError: invalid syntax
``` @hard spoke
This means you're using an old Python version where {repres=} wasn't allowed, I'd suggest
i use 3.7
I don't remember where this was added, I'm using 3.8
well, thats your answer then?
you can fix it by changing such occurences from {a=} to a={a}
What does ~ do?
Bitwise negation
Represent the number in binary, negate each bit (0->1, 1->0), and that's your result
Wait so it inverses? Like inverses the binary
Hey, ConfusedReptile dm me quickly :)
actually, not sure if that's the correct description, hold on
@hard spoke
Line 72 : Argument 2 to "apply_funcs" has incompatible type "Dict[str, Callable[[Any, Any], Any]]"; expected "Dict[str, Callable[[int, int], int]]"
Line 72 : "Dict" is invariant
Line 72 : Consider using "Mapping" instead, which is covariant in the value type
Line 72 : Argument 3 to "apply_funcs" has incompatible type "Dict[str, Callable[[Any], Any]]"; expected "Dict[str, Callable[[int], int]]"
``` interesting...
is that mypy?
its from my IDE, so i am unsure
also, that last error at least is very weird
because Dict[str, Callable[[Any], Any]] fits Dict[str, Callable[[int], int]] 
oooh, that's probably exactly why it says to use Mapping, so that it's covariant
yea
huh, how do I declare a function with 2 arguments with Mapping?..
i do not know.
ah, looks like it might just be that all arguments before the last one are inputs nope
Yes, it inverts it in 2's-complement binary, which is equivalent to doing -x-1.
Cool
Bitwise == smort
Most of the time it just overcomplicates, but in situations like this we need all the operators we can get.
Also it's good for golfing: -~x is x+1 if you need different precedence/whitespace.
(~-x is x-1.)
@plucky wedge :white_check_mark: Your eval job has completed with return code 0.
2
!e
print(-~3<<1)
@plucky wedge :white_check_mark: Your eval job has completed with return code 0.
8
Iโm gonna continue this in bot commands lol
!e ```py
def number(n: int) -> str:
if n > 0:
return "-~" * n + "0"
else:
return "~-" * n + "0"
for i in range(20):
print(i, number(i), eval(number(i)))
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
001 | 0 0 0
002 | 1 -~0 1
003 | 2 -~-~0 2
004 | 3 -~-~-~0 3
005 | 4 -~-~-~-~0 4
006 | 5 -~-~-~-~-~0 5
007 | 6 -~-~-~-~-~-~0 6
008 | 7 -~-~-~-~-~-~-~0 7
009 | 8 -~-~-~-~-~-~-~-~0 8
010 | 9 -~-~-~-~-~-~-~-~-~0 9
011 | 10 -~-~-~-~-~-~-~-~-~-~0 10
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/mezacupasa.txt
Example of using ~- as succ/pred
this has intrigued me
Thatโs cool
Golfing is a good way to learn how to abuse operators for new purposes. For instance, a Boolean not is just x<1.
Iโm gonna replace all my division with >> lol
this is very nice, hmm
I wonder how I can incorporate that. The problem is determining when I can or can't drop parantheses.
There should be a precedence chart somewhere for Python.
Alternatively, the ast module might have a utility for it.
There is indeed, but it doesn't make it easy anyway ๐
hmm, perhaps I can consider two cases - with or without them
On the expressions documentation page
Too complicated for my liking, even eliminating the ones with words.
yikes, I think I managed to autogenerate my way to some code eval hangs on
I don't seem to be able to suspend it with the debugger
it happened after I added the option to omit ()s
okay, there, managed to calculate for -10..10:
0 []<[]
1 []==[]
-1 ~([]<[])
2 -~([]==[])
-2 ~([]==[])
-3 ~-~([]==[])
3 -~-~([]==[])
4 -~-~-~([]==[])
-4 ~-~-~([]==[])
5 -~-~-~-~([]==[])
-5 ~-~-~-~([]==[])
-6 ~-~-~-~-~([]==[])
6 -~-~-~-~-~([]==[])
7 -~-~-~-~-~-~([]==[])
-7 ~-~-~-~-~-~([]==[])
8 -~([]==[])<<-~([]==[])
-8 ~([]==[])<<-~([]==[])
9 ~-~([]==[])*~-~([]==[])
-9 ~-~([]==[])*-~-~([]==[])
-10 ~-~-~-~([]==[])<<([]==[])
10 ~([]==[])*~-~-~-~([]==[])
whoa, that 10
that's what, -2 * -5? yikes
now the question is
can pypy take this lol
wait, pypy is 3.7... will have to do some backwards-compat.
oh god, why is pypy 3 times slower
Maybe the compilation time. For larger scripts it would be amortised.
nah, it's likely the evals - they are probably more expensive in pypy, and I do a lot of them in the parantheses processing
and by "3 times", I mean 800ms instead of 300ms
here's -50 to 50:
and here's -100 to 100:
https://paste.pythondiscord.com/odokisutad.txt
wait, where the hell is positives
oh, I messed up
Yay, my program managed to autogenerate code that hangs eval!
(~(([]==[])+([]==[])))**-~(([]==[])+([]==[]))**(-~-~([]==[])<<-~(([]==[])+([]==[])))
two **s and a <<? better be a huge number
it's (-3)**16777217, I believe
right, so how can I fix this?...
perhaps I can try evaluating with numpy ints first
A container for the eval call?
Or just using sized ints & failing on overflow I guess
Looks like Javascript
woah
it freezes repl.it owo
!e print(~(~([]==[])<<([]==[]<[]==[])>>((~~(([]==[])&~([]==[])))))+([]==[]))
@toxic jewel :white_check_mark: Your eval job has completed with return code 0.
2
took some inspiration and created this
!e
print(chr(((~(~([]==[])<<([]==[]<[]==[])>>((~~(([]==[])&~([]==[])))))++(([]==[]))<<([]==[])+~(~([]==[])+([]==[]))<<([]==[])++~(~([]==[])<<([]==[])))^~(~([]==[]))++([]==[])++(([]==[])<<([]==[]))+~(~(([]<[])++([]==[])))<<(([]==[])&([]==[])<<([]==[]))<<([]==[])++(()==())^(()==())++(()==())+~((~(()==())++(()==())))%([]==[])<<(([]==[])++([]==[]))++(([]==[])+(([]==[]))))+~(([]==[])<<([]==[]))+~(([]==[])++([]==[]))++([]==[]))+chr(((([]==[])++([]==[]))++(([]==[])++([]==[]))++(([]==[])+([]==[])++~(~(([]==[])++([]==[]))))<<(([]==[])++~(~([]==[])++([]==[])))^([]==[])<<([]==[])++~(~([]==[])+([]==[]))<<(([]==[])++([]==[]))<<(([]==[])++(([]==[])++([]==[])))++([]==[]))++~(([]==[])++(([]==[])<<([]==[])++([]==[])++([]==[])<<([]==[]))++(([]==[])<<([]==[]))<<([]==[]))++(([]==[])<<(([]==[])++([]==[]))++([]==[])<<([]==[]))++~(([]==[])++([]==[]))+([]==[]))+chr(((~(~([]==[])<<([]==[]<[]==[])>>((~~(([]==[])&~([]==[])))))++(([]==[]))<<([]==[])+~(~([]==[])+([]==[]))<<([]==[])++~(~([]==[])<<([]==[])))^~(~([]==[]))++([]==[])++(([]==[])<<([]==[]))+~(~(([]<[])++([]==[])))<<(([]==[])&([]==[])<<([]==[]))<<([]==[])++(()==())^(()==())++(()==())+~((~(()==())++(()==())))%([]==[])<<(([]==[])++([]==[]))++(([]==[])+(([]==[]))))+~(([]==[])<<([]==[]))+~(([]==[])++([]==[]))++([]==[])))
@toxic jewel :white_check_mark: Your eval job has completed with return code 0.
owo
!e
_=chr(((~(~([]==[])<<([]==[]<[]==[])>>((~~(([]==[])&~([]==[])))))++(([]==[]))<<([]==[])+~(~([]==[])+([]==[]))<<([]==[])++~(~([]==[])<<([]==[])))^~(~([]==[]))++([]==[])++(([]==[])<<([]==[]))+~(~(([]<[])++([]==[])))<<(([]==[])&([]==[])<<([]==[]))<<([]==[])++(()==())^(()==())++(()==())+~((~(()==())++(()==())))%([]==[])<<(([]==[])++([]==[]))++(([]==[])+(([]==[]))))+~(([]==[])<<([]==[]))+~(([]==[])++([]==[]))++([]==[]))
print(_+chr(((([]==[])++([]==[]))++(([]==[])++([]==[]))++(([]==[])+([]==[])++~(~(([]==[])++([]==[]))))<<(([]==[])++~(~([]==[])++([]==[])))^([]==[])<<([]==[])++~(~([]==[])+([]==[]))<<(([]==[])++([]==[]))<<(([]==[])++(([]==[])++([]==[])))++([]==[]))++~(([]==[])++(([]==[])<<([]==[])++([]==[])++([]==[])<<([]==[]))++(([]==[])<<([]==[]))<<([]==[]))++(([]==[])<<(([]==[])++([]==[]))++([]==[])<<([]==[]))++~(([]==[])++([]==[]))+([]==[]))+_)
@hard spoke :white_check_mark: Your eval job has completed with return code 0.
owo
yay, optimizations ๐
!e
(~(([]==[])+([]==[])))-~(([]==[])+([]==[]))(-~-~([]==[])<<-~(([]==[])+([]==[])))
@lucid shell :warning: Your eval job timed out or ran out of memory.
[No output]
!e
print((~(([]==[])+([]==[])))-~(([]==[])+([]==[]))(-~-~([]==[])<<-~(([]==[])+([]==[]))))
@lucid shell :warning: Your eval job timed out or ran out of memory.
[No output]
!e
a=(~(([]==[])+([]==[])))**-~(([]==[])+([]==[]))**(-~-~([]==[])<<-~(([]==[])+([]==[])))
print(a)
@lucid shell :warning: Your eval job timed out or ran out of memory.
[No output]
@lucid shell :x: Your eval job has completed with return code 1.
001 | 0 0 0
002 | Traceback (most recent call last):
003 | File "<string>", line 12, in <module>
004 | File "<string>", line 1
005 | -~
006 | ^
007 | SyntaxError: invalid syntax
@lucid shell :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | https://paste.pythondiscord.com/uraditeciq.lua
003 | ^
004 | SyntaxError: invalid syntax
#bot-commands
should try fitting & into it
I have used &, actually, and didn't get any improvements.
ah
i just tried to think of every possible mathematical operator possible to fit into my equation
except i used no **, //, or --
kinda wanna create a program to create these
create what exactly?
arbitrary strings using chr and this number notation? that's pretty easy, just wrap the numbers in chrs
yeah
!e
Did you know that Python has tail recursion?
class Factorial:
def __init__(self, n, acc=1):
self.n = n
self.acc = acc
def __del__(self):
if self.n <= 1:
print(self.acc)
else:
type(self)(self.n - 1, self.n * self.acc)
Factorial(2000)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
3316275092450633241175393380576324038281117208105780394571935437060380779056008224002732308597325922554023529412258341092580848174152937961313866335263436889056340585561639406051172525718706478563935440454052439574670376741087229704346841583437524315808775336451274879954368592474080324089465615072332506527976557571796715367186893590561128158716017172326571561100042140124204338425737127001758835477968999212835289966658534055798549036573663501333865504011720121526354880382681521522469209952060315644185654806759464970515522882052348999957264508140655366789695321014676226713320268315522051944944616182392752040265297226315025747520482960647509273941658562835317795744828763145964503739913273341772636088524900935066216101444597094127078213137325638315723020199499149583164709427744738703279855496742986088393763268241524788343874695958292577405745398375015858154681362942179499723998135994810165565638760342273129122503847098729096266224619710766059315502018951355831653578714922909167790497022470
... (truncated - too long)
Full output: https://paste.pythondiscord.com/cisitadexo.txt
Ooh, that is a very cool find.
Whats this about?
I knew about tail end recursion but execute on delete I will so abuse that
I will make a class called Essential that when deleted,it crashes python Ahahahahahahaha
Hello there fix error
!e
class GcBomb:
def __del__(self):
cls = type(self)
[cls(), cls(), cls(), cls()]
GcBomb()
@formal sandal :warning: Your eval job timed out or ran out of memory.
[No output]
Awww no sigsegv
that actually eats memory away very quickly
Hey now my computer is acting weird I am definitely putting this in my cursedutils module
This is better than sigsegv
I like it
Even better this deserves the death module
atm it's a lame
import sys,os;os.system("")or sys.stderr.write('\x1b[31mFatal Python error: _Py_MorsObitusDecessus: Python has died.\nPython runtime state: deceased\x1b[0m\r\n')
def morte():
try:sys.setrecursionlimit(99999);morte()
except:morte()
try:morte()
except: - mors . obitus . decessus
but now it will be potent
@formal sandal I have turned your GcBomb class into an importable utility.
but i'm undecided whether the program that imports death should call a function from death (depending on whether they want to simply raise an error, crash the interpreter or their pc) ...
or...
just straight up create an instance of this class when they import it, then when they try to exit, that's when it gets them?
oh, os.abort() is more powerful
@formal sandal I have found the weakness of your bomb.
E:\__py__\__modules__>py
Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from death import *
>>> nuke_pc()
<death.RecreationalMcNuke object at 0x00000239F690BCA0>
>>> __import__('os').abort()
E:\__py__\__modules__>
Aww my sound drivers corrupted again
alright, who wins, nuke or error?
huh
it exits python just parsing it lol
>>> import death
>>> nuke = death.nuke_pc()
>>> def test():
... nuke.execute()
E:\__py__\__modules__>
i wasn't even finished writing the function
>>> def test():
... import death
... nuke = death.nuke_pc()
... nuke.execute()
... raise Exception
...
>>>
who will win, the grim reaper, or the Exception?
just in case the grim reaper wins i'm gonna add
>>> from death import abort
oh wait, that's not gonna work after it, is it?
huh, Exception won
>>> test();abort()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in test
Exception
>>>
so, deleting it seems to do nothing, which means it's still stored somewhere after the function finishes.
which means... there's something to exploit to access locals.
It's not actually as potent as i thought. There's several exit methods that can bypass del
!e ```py
fix error's code
class GcBomb:
def del(self):
cls = type(self)
[cls(), cls(), cls(), cls()]
f = GcBomb()
bypass
def bypass():
try:1/0
except:bypass()
print ('testing: we've made it this far')
bypass() # should signal segmentation fault
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | testing: we've made it this far
002 | Fatal Python error: _Py_CheckRecursiveCall: Cannot recover from stack overflow.
003 | Python runtime state: initialized
004 |
005 | Current thread 0x00007f11ca67c740 (most recent call first):
006 | File "<string>", line 10 in bypass
007 | File "<string>", line 11 in bypass
008 | File "<string>", line 11 in bypass
009 | File "<string>", line 11 in bypass
010 | File "<string>", line 11 in bypass
011 | File "<string>", line 11 in bypass
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/mudidugasu.txt
!e ```py
exec('%c'10%(((((((([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[])),((((((([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])),((((((([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]),((((((([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])),((((((([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[])),(((((([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[])),(((((([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])),((((((([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]),(((((([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])),(((((([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[])))*(([]==[])+([]==[]))+([]==[]),))
@fossil estuary :white_check_mark: Your eval job has completed with return code 0.
a
:)
!e ```py
import ctypes
from contextlib import suppress
while True:
with suppress(Exception):
ctypes.resize(ctypes.c_int(0x99), 0x32 << 0x32)```
lol
@tribal moon :warning: Your eval job timed out or ran out of memory.
[No output]
lol nice
no, i made a converter for it
can you do Hello, World!
damn nice
ty
is it possible without the exec part and stuff
havent tried
>>> cursed.exit
Exception ignored in: <function <dictcomp>.<lambda> at 0x0000021358F8FEE0>
Traceback (most recent call last):
File "E:\__py__\__modules__\cursed.py", line 4, in <lambda>
File "E:\__py__\__modules__\death.py", line 16, in kill_python
ImportError: sys.meta_path is None, Python is likely shutting down
E:\__py__\__modules__>
I find new errors all the time.
I didn't even call the function
how
i don't even know. There's no where where death.kill_python could've been called
how does it kill python, im interested
def kill_python():
import sys,os;os.system("")or sys.stderr.write('\x1b[31mFatal Python error: _Py_MorsObitusDecessus: Python has died.\nPython runtime state: deceased\x1b[0m\r\n')
def morte():
try:sys.setrecursionlimit(99999);morte()
except:morte()
try:morte()
except: - mors . obitus . decessus
explain it.
but there's only two places in cursed where this is reference, where it's imported, and where it's passed as attributes to an anonymous class.
explain it.
os.system("")allows colour print
\x1b[31mis colour print
the error message is a rip-off of what you get when you try to execute
def print(*a):
try: print (*a)
except: print (*a)
print ("Hello World!")
and then sys.setrecursionlimit(99999) allows the same function above to execute without printing that error
then morte is executed within a try except suite for extra impact
Has anyone actually broken Snekbox or NSJail before?
probably soon.
when i'm satisfied with it
apparantly three times in the past, amongst millions of attempts.
damn
i even tried once
What's the shortest code that brings SIGSEGV
ctypes.string_at(0) iirc
!e py import ctypes ctypes.string_at(0)
@tribal moon :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
Nice
OSError ๐
Is there a proper way to search for bugs in Snekbox for the bot?
Which one?
def add_one(obj: Union[list, tuple, set]):
if isinstance(obj, tuple):
return tuple(i + 1 for i in obj)
if isinstance(obj, list):
return [i + 1 for i in obj]
if isinstance(obj, set):
return {i + 1 for i in obj}
def add_one_in_one_line(obj: Union[list, tuple, set]):
return type(obj)(i + 1 for i in obj)
Not sure if this is the right channel to ask in...
the second one could be turned into a lambda to make it actually one line
agreed!
add_one = lambda x: type(x)(i + 1 for i in x)
now remove the space around the operators :P
!e ```py
print((lambda x:type(x)(i+1for i in x))([0,1,2,3]))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3, 4]
yep it works
nice
It only works for iterables of ints tho
def Chain():
""":return: cause, effect"""
def cause(f):
t=type("chained_function",(),{'__call__':lambda*a:lambda*a:None,'call':lambda s,*a:f.__call__(*a),'__code__':f.__code__,'__name__':f.__name__})()
def decorator(F):_f=t.call;t.call = lambda*a,:F(*_f(*a));return t
t.__setattr__('__call__',decorator)
return t
def effect(t):
def wrapper(f):
_f=lambda*a:f(*t.call(*a));_f.__name__,_f.__doc__=f.__name__,f.__doc__
return _f
return wrapper
return cause, effect
cause, effect = Chain()
ok atm this doesn't work.
Hey, I have a question about the way data types in Python work. I did some research but couldn't find anything.
Say, I create a list a with 3 integers, then I create a variable b and assign a to it.
If I append something to b, the changes are made to the a too.
I am not sure, but my theory is that when you clone the variable, it just copies the memory address and not the contents.
>>> a = [1, 2, 3]
>>> b = a
>>> b.append(4)
>>> b
[1, 2, 3, 4]
>>> a
[1, 2, 3, 4]
Why does this happen?
!e
Pure Python segfault:
import time
time.pthread_getcpuclockid(-1)โ
@thin trout :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
whoa
does someone know how do I modify python code at runtime?
maybe like if I want line 4 to be changed to print("hello world") if it's executing line 2 rn...
i'm guessing the code is stored in memory at run time so just modifying the code file won't work
You are right. a and b refer to the same list.
Technically.
For e.g. an integer, it doesn't matter because you don't change 1 itself when you add to it, you just create a 2.
if you want to know more i recommend this read:
https://nedbatchelder.com/text/names.html
Thank you both
Nitpick: Values -5..256 always point to their own memory address so you technically don't "create" it
!e
a = 10
print(a is 10)
b = 1000
print(b is 1000)
@hot crypt :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:2: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | <string>:4: SyntaxWarning: "is" with a literal. Did you mean "=="?
003 | True
004 | True
!e
a=10 print(a is not not 10)
@toxic jewel :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | print(a is not not 10)
003 | ^
004 | SyntaxError: invalid syntax
:^(
!e
a=10
print(a)
@jagged path :white_check_mark: Your eval job has completed with return code 0.
10
not not 1 is not (not 1) is (not not 1)
||False||?
Apparently, python 3.10 was released yesterday with structural pattern matching, but I can't seem to find the download on the official website
Anyone know where I can get 3.10?
The 6th alpha was released yesterday
There is no stable release first, but you can build it from source to access the alpha
!e python caches objects in a single compilation unit
a = 1000
b = 10
exec('print(a is 1000)')
print(a is b + 990)
print (a is 10+990)
print (a is (lambda:1000)())
@proper vault :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:5: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
003 | False
004 | False
005 | True
006 | True
import time
string = "vinam sleep"
for i in range(len(string)):
print(string[:i+1].ljust(11),end="")
print(string[:i+1].rjust(11),end="")
print(string[:i+1].ljust(11),end="")
print(string[:i+1].rjust(11),end="")
print(string[:i+1].ljust(11),end="")
print(string[:i+1].rjust(11),end="")
print(string[:i+1].ljust(11),end="")
print(string[:i+1].rjust(11),end="")
print(string[:i+1].ljust(11),end="")
print(string[:i+1].rjust(11))
time.sleep(0.5)
for i in range(len(string),-1,-1):
print(string[:i+1].ljust(11),end="")
print(string[:i+1].rjust(11),end="")
print(string[:i+1].ljust(11),end="")
print(string[:i+1].rjust(11),end="")
print(string[:i+1].ljust(11),end="")
print(string[:i+1].rjust(11),end="")
print(string[:i+1].ljust(11),end="")
print(string[:i+1].rjust(11),end="")
print(string[:i+1].ljust(11),end="")
print(string[:i+1].rjust(11))
time.sleep(0.5)
use this code to make someone sleep
replace vinam with any name
-regards
nice
state = bytearray(9)
turns = b'\1\2\2\1'
for i in range(3):
print(*state[i * 3:(i + 1) * 3])
turn = turns[reduce(xor, state)]
i = int(input(f'player {turn} move'))
state[i] = turn
```a very odd way to swap players in noughts and crosses (players are 1 and 2)
!eval [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.
We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*
!e
_=True
__=_+_
___=__<<__
____=___<<__
____=____*__
____=____*__
____=____-___
_____=_+_+_
print(chr(int(____/__+___+__+__)),chr(int(____-___-___-_-__)),chr(int(____-___-___+__+__)),chr(int(____-___-___+__+__)),chr(int(____-___-___+__+__+__+_)),chr(int(____/__/__+__+_____+___+_)),chr(int(____/__/__+__)),chr(int(____/___*__*_____-_____)),chr(int(____-___-___+__+__+__+_)),chr(int(____-_____-_____)),chr(int(____-___-___+__+__)),chr(int(____-___-___-__-__)),chr(int(____/__/__+__+_)),sep=str())
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello, World!
now that's esoteric, lol
You don't need all those ints tho
i tried to implement a private in python, have fun trying to break it.
!e ```py
import inspect
class Private:
def setattr(self, name, value):
raise RuntimeError("Attribute setting disabled.")
def call(self, f):
super().setattr("f_code", f.code)
def wrapper(*args, **kwargs):
f.code = self.f_code
if self.code == inspect.currentframe().f_back.f_code:
return f(*args, **kwargs)
raise RuntimeError("This private function cannot be called directly.")
return wrapper
def setcode(self, code):
super().setattr("code", code)
def alt(*args, **kwargs):
raise RuntimeError("Cannot set code state for this class, already set.")
super().setattr("setcode", alt)
def allowed(private):
def wrapper(f):
private.setcode(f.code)
return f
def alt(*args, **kwargs):
raise RuntimeError("Cannot set allowed state for other callers.")
allowed.code = alt.code
return wrapper
private = Private()
@private
def private_func():
print("its run")
return 1
@allowed(private)
def permitted_caller():
private_func()
print("called from the allowed caller")
############################################################################
dont modify above this line
challenge: call private_func without goign through permitted_caller
permitted_caller()
@broken mesa :white_check_mark: Your eval job has completed with return code 0.
001 | its run
002 | called from the allowed caller
gist of this, if anyone cares: https://gist.github.com/laundmo/6ac0e667d15657fdc61863d34e7d4877
!e
import inspect
class Private:
def setattr(self, name, value):
raise RuntimeError("Attribute setting disabled.")
def call(self, f):
super().setattr("f_code", f.code)
def wrapper(*args, **kwargs):
f.code = self.f_code
if self.code == inspect.currentframe().f_back.f_code:
return f(*args, **kwargs)
raise RuntimeError("This private function cannot be called directly.")
return wrapper
def setcode(self, code):
super().setattr("code", code)
def alt(*args, **kwargs):
raise RuntimeError("Cannot set code state for this class, already set.")
super().setattr("setcode", alt)
def allowed(private):
def wrapper(f):
private.setcode(f.code)
return f
def alt(*args, **kwargs):
raise RuntimeError("Cannot set allowed state for other callers.")
allowed.code = alt.code
return wrapper
private = Private()
@private
def private_func():
print("its run")
return 1
@allowed(private)
def permitted_caller():
private_func()
print("called from the allowed caller")
############################################################################
dont modify above this line
challenge: call private_func without goign through permitted_caller
permitted_caller()
yeah that didn't work, you might wanna retry or even better, use #bot-commands or test locally
Ok sorry
>>> private_func.__closure__[0].cell_contents()
its run
1
>>> ```
or i could replace the self object in the closure
hm, nice approach
(clarification: im done working on this, there will always be workarounds, just wanted to give people a fun challenge)
huh, I crashed Python trying
yep, happened a few times developing too
class OK:
def __eq__(self,other):
return True
def __getattr__(self,name):
return self
def curframe():
return OK()
inspect.currentframe=curframe
private_func()
# its run
# 1
does that count as a dependency poisoning attack? ๐
idk maybe? but i love the various solutions people have come up with
its very interesting to see the different approaches
object.__setattr__(private, "code", inspect.currentframe().f_code)
print(private_func())
Well, one thing to do would be to set __slots__ and then store those descriptors elsewhere, so you can't simply read __dict__ to grab everything.
@broken mesa its possible to defeat this approach by getting the current frame from an exception
You could make your own inspect module and ez
!e py try:raise Exception except Exception as e: frame = e.__traceback__.tb_frame print(frame)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
<frame at 0x7fc15a0abcf0, file '<string>', line 4, code <module>>
foo = lambda:0
foo.__code__ = private.f_code
print(foo())
Not quite calling private_func, but has the same result.
Might as well exec(private.f_code)
exec always feels like cheating.
I agree.
Not as 'honourable' perhaps?
Indeed.
esowtewic python
no.
๐ฅบ
esotewic pyfon
esotewic pyfuwu
!e ```python
class W:
def matmul(self, other):
if other is not ...:
raise TypeError("what are you doing?")
def function_printer(func):
words = func.name.split("_")
words[0] = words[0].title()
string_constants = (const for const in func.code.co_consts if isinstance(const, str))
print(*words, end=next(string_constants)+"\n")
return func
return function_printer
w = W()
@w@...
def whats_this(): "?"
@snow beacon :white_check_mark: Your eval job has completed with return code 0.
Whats this?
What's the second @ and how is that valid syntax 
That's the matrix multiplication operator.
w @ ... is doing a matrix multiplication between the W object and the Ellipsis.
And I'm assuming __matmul__ is the dunder for that
It is.
Why are they called dunders 
double under

Lol
TIL
Lol
!e __๐ฆ๐ช๐ญ๐ฌ๐ฏ๐ฑ__("sys").๐ฐ๐ฑ๐ก๐ฌ๐ฒ๐ฑ. ๐ด๐ฏ๐ฆ๐ฑ๐ข("esowtewic pyfon")
@toxic jewel :white_check_mark: Your eval job has completed with return code 0.
esowtewic pyfon
https://replit.com/talk/share/Dijkstras-algorithm-one-liner-1-line-seriesno6/130067 i did it again lol
made dijkstras algorithm in one line
!e import subprocess; print(subprocess.Popen("uname -a", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.read().decode())
@worthy iris :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "/usr/local/lib/python3.9/subprocess.py", line 951, in __init__
004 | self._execute_child(args, executable, preexec_fn, close_fds,
005 | File "/usr/local/lib/python3.9/subprocess.py", line 1756, in _execute_child
006 | self.pid = _posixsubprocess.fork_exec(
007 | BlockingIOError: [Errno 11] Resource temporarily unavailable

Pffft pure python segfault can be done without imports
you can get complete process memory r/w without imports
!e ```py
from ctypes import *
import os
def rerun(flags):
_argv = POINTER(c_wchar_p)()
_argc = c_int()
pythonapi.Py_GetArgcArgv(byref(_argc), byref(_argv))
orig_argv = _argv[:_argc.value]
orig_argv.insert(1, flags)
os.execv(orig_argv[0], orig_argv)
if debug:
print(debug)
rerun('-O')
print(debug)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | False
^ uses os.execv to rerun the current bot eval with different python flags
Easy, inject malicious code into the inspect module. Dependencies are a great weakness
!e py from ctypes import * _argv = POINTER(c_wchar_p)() _argc = c_int() pythonapi.Py_GetArgcArgv(byref(_argc), byref(_argv)) print(_argv[_argc.value - 1])
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | from ctypes import *
002 | _argv = POINTER(c_wchar_p)()
003 | _argc = c_int()
004 | pythonapi.Py_GetArgcArgv(byref(_argc), byref(_argv))
005 | print(_argv[_argc.value - 1])
!e Alrighty, no imports exit 139, using only "noob code"
def print(a):
try: print (a)
except: print (a)
print ("Hello World!")
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | Fatal Python error: _Py_CheckRecursiveCall: Cannot recover from stack overflow.
002 | Python runtime state: initialized
003 |
004 | Current thread 0x00007f4b50421740 (most recent call first):
005 | File "<string>", line 2 in print
006 | File "<string>", line 2 in print
007 | File "<string>", line 2 in print
008 | File "<string>", line 2 in print
009 | File "<string>", line 2 in print
010 | File "<string>", line 2 in print
011 | File "<string>", line 2 in print
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/uzocodunir.txt
That's pretty cool
i think ive posted it here before but you can abuse the fact that LOAD_CONST doesnt have bounds checking to make a bytearray that points to pythons entire memory space
!e Now, exit negative a billion, at least on my pc lol.
import sys
sys.setrecursionlimit(9999999)
def print(a):
try: print (a)
except: print (a)
print ("Hello World!")โ
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
Huh still 139
oh right yeah I remember this discussion
pyctypes or something
I run the above on pc it exits something like negative a billion instead of 139
alright, now for the "inside out wrapper"
!e ```py
execute_with=lambda*a,**k:lambda f:f(*a,**k)
execute=execute_with()
@execute_with(69)
def output():
return int.mul((//10)*10,(_%10)-2)
@execute
class cout:lshift=print
cout << output
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
420
completely redefine the way functions and classes are used
I stole this cool bit of code although I'm not sure who wrote it:
!e ```py
import inspect
class compose:
def init(self, *fs):
self.fs = fs
def __getattr__(self, f):
return type(self)(*self.fs, eval(f, globals(), inspect.currentframe().f_back.f_locals))
def __matmul__(self, x):
return self(x)
__rrshift__ = __matmul__
def __call__(self, *xs):
fs = list(self.fs)
x = fs.pop()(*xs)
while len(fs) != 0:
x = fs.pop()(x)
return x
@compose
def double(n):
return n * 2
@compose
def successor(n):
return n + 1
print(successor.double.successor @ 9)
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
21
!e ```py
def_if=lambda c:(c and(lambda f:f))or(lambda f:lambdau,**ck:None)
execute=(execute_with:=lambdau,ck:lambda f:f(*u,ck))()
@execute_with("Hello World!")
@def_if(FalseFalse)
def _do(s): print (s)
@execute
@def_if(FalseTrue)
def _do(): print ("error")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
Remaking all the statements with def cos they all suck. :>
Jk
!e ```py
def_for=lambda iterable:lambda f:lambdau,**ck:[f(i,u,**ck)for i in iterable]
def_while=lambdaa:lambda f:lambdau,**ck:{f(*u,**ck)for _ in iter(a)}
execute=(execute_with:=lambdau,**ck:lambda f:f(*u,**ck))()
@execute
@def_for(range(10))
def do(i): print (i+1)
@execute
@def_while(lambda:True,0)
def do_forever():
print (end='.')
@floral meteor :x: Your eval job has completed with return code 143 (SIGTERM).
001 | 1
002 | 2
003 | 3
004 | 4
005 | 5
006 | 6
007 | 7
008 | 8
009 | 9
010 | 10
011 | .................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
... (truncated - too long)
Full output: too long to upload
143 (SIGTERM)
Hey! I got a new exit code!
That's just the process getting killed by the bot
I don't really pay attention to random evals
yield from
what does that do lol
!e ```py
a=[0,0,0,0,0,1,0]
def floofers(a):
yield from a
while not print(*floofers(a)): pass
@floral meteor :x: Your eval job has completed with return code 143 (SIGTERM).
001 | 0 0 0 0 0 1 0
002 | 0 0 0 0 0 1 0
003 | 0 0 0 0 0 1 0
004 | 0 0 0 0 0 1 0
005 | 0 0 0 0 0 1 0
006 | 0 0 0 0 0 1 0
007 | 0 0 0 0 0 1 0
008 | 0 0 0 0 0 1 0
009 | 0 0 0 0 0 1 0
010 | 0 0 0 0 0 1 0
011 | 0 0 0 0 0 1 0
... (truncated - too many lines)
Full output: too long to upload
so that just packs an iterable into a generator.
!e ```py
a = [0,1,1,2,3,5,8]
def floofers(a):
return (o for o in a)
for i in floofers(a):print (i)
def floofers(a):
yield from a
for i in floofers(a):print (i)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 1
004 | 2
005 | 3
006 | 5
007 | 8
008 | 0
009 | 1
010 | 1
011 | 2
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/uwaqehazoy.txt
just replaced with return don't need fancy defs and decorators :/
yield from x
Is the same as
for y in x:
yield y
or ```py
return(y for y in x)
Technically not the same thing
well if you wanna yield some more but who wants to do that?
What's the point of returning a generator expression
to do the same thing as yield from
only don't keep going
!e ```py
def increment_four_times(n):
@lambda f:f(f(f(f(n))))
def output(a):return a+1
return output
print(increment_four_times(4))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
8
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 9, in <module>
003 | File "<string>", line 3, in self_reference
004 | ValueError: <lambda>() requires a code object with 1 free vars, not 0
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 7, in <module>
003 | File "<string>", line 4, in self_reference
004 | ValueError: <lambda>() requires a code object with 1 free vars, not 0
looks like i'm gonna have to do some extra hacky stuff.
@rugged sparrow this is your forte, how do i inject local variables?
so self(...) will actually compile as LOAD_GLOBAL 'self' so you just need to inject self into globals for the duration of the function
so ```py
def wrapper(*args, **kwargs):
save orig self if in globals
set self to func
try:
return func(*args, **kwargs)
finally:
# set self to original value (or delete it)
@floral meteor ^
ah, thank you
!e ```py
def self_reference(self):
def wrapper(*a,**k):
if'self'in globals():
rollback=globals()['self']
globals()['self']=self
v = self(*a,**k)
if'self'in globals()and'rollback'in locals():globals()['self']=locals()['rollback']
return v
return wrapper
@self_reference
def fibonacci(a,b):
print (a)
return self(b,a+b)
fibonacci(1,1)
@floral meteor :x: Your eval job has completed with return code 1.
001 | 1
002 | 1
003 | 2
004 | 3
005 | 5
006 | 8
007 | 13
008 | 21
009 | 34
010 | 55
011 | 89
... (truncated - too many lines)
Full output: too long to upload
my cursedutils module is acting very cursed rn
E:\__py__\__modules__>py
Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from cursedutils import*
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> import cursedutils
>>> dir(cursedutils)
['__builtins__', '__cached__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__file__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__loader__', '__lt__', '__main__', '__module__', '__name__', '__ne__', '__new__', '__package__', '__path__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__spec__', '__str__', '__subclasshook__', '__weakref__', 'ctx', 'cursed', 'death', 'iostreams', 'main', 'wrappers']
>>>
It acts empty when unpacked o_o
>>> from cursedutils import *
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> from cursedutils import cursed
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'cursed']
>>> from cursedutils import*
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'cursed', 'death', 'iostreams', 'wrappers']
>>>
one does not simply import everything from cursedutils
one must first import cursed from cursedutils. then they can import everything from cursedutils.
This is legit badass i would release it with pypi but the death module is dodgy af
should I just make a non-deathy version?
or remove the malicious bit and make a comment that malicious code was redacted?
cos i don't want to post something too dodgy
but i still want it for personal use
Show me the way ๐
Oh I see it
Haha, that's stupid
def print(a):
try: print (a)
except: print (a)
print ("Hello World!")
use sys.setrecursionlimit if you dont want it to print error message
!e
!eval [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.
We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*
!e import this
@desert iris :white_check_mark: Your 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/difofulefi.txt
!e
while not print(x:=x if'x'in globals()else 0):x+=1
@viscid nymph :x: Your eval job has completed with return code 143 (SIGTERM).
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
011 | 10
... (truncated - too many lines)
Full output: too long to upload
What's sigterm 
Killed by the OS
Oh lol
Actually it's snekbox terminating the process, it was recently changed to use terminate (which sends SIGTERM) instead of kill (which sends SIGKILL)
Your reminder will arrive in 30 minutes!
@thin trout
Here's your reminder: update.
[Jump back to when you created the reminder](#esoteric-python message)
This looks like the place I want to be
I am working on an incredibly cursed python project (yes, no one should ever ever ever code like this, it's for a meme). Is there anyway to override the BaseException class? I want to make my own raisable error that doesn't actually throw an exception, it just executes a print statement or something
so you want raise MyException to be automatically caught and instead run an arbitrary function?
If that's possible
it might be
This is heading towards me overwriting NameError
so that NameError doesn't actually error and just runs my stuff
ooo that is actually easier
you can hook into dict.__getitem__ and if the dict is globals() and the key isnt found, run your hook
can you use dependencies?
cause my fishhook module makes hooking dict.__getitem__ easy but i can show how to do it directly with ctypes
The latter please
I want this to be as scuffed as possible
I can probably look at the code tho
your welcome to, its on pypi and github
ill write a quick example of hooking dict.__getitem__ (with ctypes)
ahahaha this is so cursed i love it
just a warning, fishhook is a weird module to go thru cause i wanted to make it as dynamic as possible
Couldn't it be simpler by hooking __missing__
i have never seen that dunder ๐
__missing__ is why defaultdict works in the first place, if I remember correctly
in the mean time wanna see a prime generator
L=100;i=p=2
while i<L**.5:[p:=p|1<<x for x in range(i*i,L,i)];i+=1
[print(n)for n in range(2,L)if~p&1<<n]```
It's used when getitem fails, similar to getattr/getattribute. Makes subclassing dict much easier
does it get called if it is set on dict
acc ill just test that
yea it is only called if the object is a subclass of dict
not on dict
so how do I do this hook thing for the exception
im trying to figure out a way
ah ok sorry
hooking dict.__getitem__ breaks a lot lol
i was able to get code running when a NameError is raised using a tracing function
now i just need to find a way to cancel the exception
awesome
thank you for working very hard on this
I'll share the final code also, I think you'll like it
Excellent, I actually needed one of those XD
@pulsar isle this is proving more difficult then i expected with my current method
gonna try something else
!e ```py
from ctypes import py_object
import atexit
class dict_sub(dict):
def missing(self, key, dict=dict, id=id, py_object=py_object):
try:
py_object.from_address(id(self) + 8).value = dict
return eval(key) # hacky, didnt want to have to rewrite name precedence
except:
# name is missing, do what you want
# code here can use variables normally
print(key)
finally:
py_object.from_address(id(self) + 8).value = class
py_object.from_address(id(globals()) + 8).value = dict_sub
@atexit.register
def unhook_globals():
py_object.from_address(id(globals()) + 8).value = dict
this_name_does_not_exist
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
this_name_does_not_exist
@pulsar isle got it working
wasnt able to hook all exceptions sadly (that was my first attempt)
This isnโt exactly a python question, but I think this is the best place to ask it: how do I comment out multiline comments?
Like how do I comment out the multiline comment starts and ends
Python doesn't have real multi line comments
Also not the place for that question
The closest thing python has to multi line comments are multi line strings
I know, I know, thatโs why itโs not a python question
!ot
Off-topic channels
There are three off-topic channels:
โข #ot0-psvmโs-eternal-disapproval
โข #ot1-perplexing-regexing
โข #ot2-never-nesterโs-nightmare
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
!e ```py
from ctypes import py_object
import atexit, builtins
def dict_sub(ob_base_p, func):
class sub(dict):
slots = ()
def missing(self, key, ob_base_p=ob_base_p, builtins=builtins):
try:
ob_base_p.value = builtins.dict
return {**builtins.dict, **self}[key]
except:
return func(self, key)
finally:
ob_base_p.value = class
return sub
def init_missing_hook(dct, func):
ob_base_p = py_object.from_address(id(dct) + 8)
ob_base_p.value = dict_sub(ob_base_p, func)
@atexit.register
def unhook():
ob_base_p.value = dict
return unhook
unhook = init_missing_hook(globals(), lambda s,k:print(k))
this_name_does_not_exist
unhook()
this_name_does_not_exist_after_unhook```
@rugged sparrow :x: Your eval job has completed with return code 1.
001 | this_name_does_not_exist_after_hook
002 | Traceback (most recent call last):
003 | File "<string>", line 28, in <module>
004 | NameError: name 'this_name_does_not_exist_after_unhook' is not defined
Hi all was just wondering if anyone knows how to handle code objects? Am interested in breaking functions into two function compositions and was thinking code objects/bytecode might be the key to that.
Why are you importing builtins 
# '''
foo()
# '''
```will run `foo`.
'''
foo()
'''
```will not.
i needed a reference to it that was guarenteed to be a module
__builtins__?
thats not always a module
it can sometimes be a dict
from ctypes import py_object
import atexit, builtins
def init_missing_hook(dct, func):
ob_base_p = py_object.from_address(id(dct) + 8)
class missing_hook(dict):
__slots__ = ()
def __missing__(self, key, ob_base_p=ob_base_p, builtins=builtins):
try:
ob_base_p.value = builtins.dict
return {**builtins.__dict__, **self}[key]
except:
return func(self, key)
finally:
ob_base_p.value = __class__
ob_base_p.value = missing_hook
@atexit.register
def unhook():
ob_base_p.value = dict
return unhook
unhook = init_missing_hook(globals(), lambda s,k:print(k))
this_name_does_not_exist
unhook()
this_name_does_not_exist_after_unhook```
also because globals if is hooked variable lookup in the function is janky
Oh lmao I was so confused when it was a dict one time and it was a module another time
yea its one of the weird artifacts from python2
!e
def foo():
0/0
def bar():
print("lol")
foo.__code__ = bar.__code__
foo()
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
lol
!e
def foo():
0/0
foo.__code__ = compile("print('lol')", __name__, "exec")
foo()
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
lol
@viscid nymph Thatโs so cool! Do you know how to extract certain lines from the function? Is it possible to compile only a certain part of the bytecode?
@tiny hazel not easily
Iโm about to try some really cursed things lmao
!e
def foo():
print("lol")
import dis
dis.dis(foo)
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
001 | 2 0 LOAD_GLOBAL 0 (print)
002 | 2 LOAD_CONST 1 ('lol')
003 | 4 CALL_FUNCTION 1
004 | 6 POP_TOP
005 | 8 LOAD_CONST 0 (None)
006 | 10 RETURN_VALUE
you know you can merge dicts with the | operator?
!e ```py
print (globals()|{'sixty-nine':420,'four-twenty':69})
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'sixty-nine': 420, 'four-twenty': 69}
I do know that... i just forgot lmao
!e ```py
globals() |= {'a':420}
print (a)
@floral meteor :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | globals() |= {'a':420}
003 | ^
004 | SyntaxError: 'function call' is an illegal expression for augmented assignment
my screen:
001 | File "<string>", line 1
002 | globals() |= {'a':420}
003 | ^
004 | SyntaxError: 'function call' is an illegal expression for augmented assignment
text messages:
Dad:
Why is the FBI at the door?
that's what I think when I see illegal :/
I don't think that's Python.
!e
zอกฬฏฬฏaฬงอฬบlฬกอฬซgฬนฬฒoฬกฬผฬ = 69
print(zอกฬฏฬฏaฬงอฬบlฬกอฬซgฬนฬฒoฬกฬผฬ)
@strange basin :white_check_mark: Your eval job has completed with return code 0.
69
But it is a perfectly fine variable name...
Even so, it would throw an error if it were the code on it's own.
...
enjoy your atrocity immunity
which, itself, is an atrocity
the thing is i literally don't understand this... what does this code even do?
print's 1 five times
wut? but why?
it's a lambda
I want to see one of these which registers an import hook so that importing some special string which gets obtained by running an async generator print 1
alias, it can be declared inline
wait but why is this code useful?
some of tyhe insight comes from a website with a lot of lambda horrors
why would you just print 1
we are in esoteric python
oh
well it's just a proof of concept
ohhhhhh i see
sick
brain == fried
yeah i come here once every other day to get my dose of insanity, i've had enough today
i remember i did that at a time where i was writing a parser for clojure styled action sequences
which needed to be able do do multiple actions asynchronously
also, why not
[ print(next(g)) for gen in [lambda: [(yield 1), (yield from gen())]] for g in [gen()] for i in range(5) ]
so i used generators to do the multiple actions
:= is for schmucks /s
idk i'm not that good a dev so i just used what i could think of at the time
yeah, makes sense
@proper vault @dire yew here, the cursed knowledge i was inspired from http://p-nand-q.com/python/lambda.html
just went thru that shit and it's eye opening
that article is definitely a bit out of date, for if statements you could just use the if expression, for for statements you could just use a generator expression/comprehension, for while statements you could also use a generator expression f() for _ in iter(lambda: None, 0) , for local variables you could use an assignment expression. (seems like there's an expression for everything now.)
awesome, sorry about my absence, taking a look now
@rugged sparrow
nice
i have more things that would be cool tho
lol
do you understand how it works?
yeah roughly
could the same theoretically be done for syntax error
or is that a different mechanism
syntax errors are raised by the compiler
basically all i did here is write a way to add __missing__ to existing dictionarys
Ah yeah I see
ooo i could use this to add numeric literals
like one_hundred_and_one would be 101
yep
!e ```py
from ctypes import py_object
import atexit, builtins
def init_missing_hook(dct, func):
ob_base_p = py_object.from_address(id(dct) + 8)
class missing_hook(dict):
slots = ()
def missing(self, key, ob_base_p=ob_base_p, builtins=builtins):
try:
ob_base_p.value = builtins.dict
return (builtins.dict | self)[key]
except KeyError:
return func(self, key)
finally:
ob_base_p.value = class
ob_base_p.value = missing_hook
@atexit.register
def unhook():
ob_base_p.value = dict
return unhook
shamelessly grabbed from https://ao.gl/how-to-convert-numeric-words-into-numbers-using-python/
def parse_int(dct, textnum, numwords={}):
if not numwords:
units = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen",
]
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
scales = ["hundred", "thousand", "million", "billion", "trillion"]
numwords["and"] = (1, 0)
for idx, word in enumerate(units): numwords[word] = (1, idx)
for idx, word in enumerate(tens): numwords[word] = (1, idx * 10)
for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0)
current = result = 0
for word in textnum.replace("_"," ").split():
if word not in numwords:
raise NameError(f"name {textnum!r} is not defined") from None
scale, increment = numwords[word]
current = current * scale + increment
if scale > 100:
result += current
current = 0
return result + current
unhook = init_missing_hook(globals(), parse_int)
print(one_hundred_and_one)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
101
@pulsar isle found a quick and dirty converter online and it works
That's disgusting
ahh i remember that
match = False
match match:
case match if match is match: print(match)
guess python has context keywords now?
That works?
yes
making match a keyword would break so many things
case is also a "context keyword?" 
oh interesting
what if they did that with ALL the keywords >:)
(excluding making True, False and None valid variable names)
for in in in in in:
if if and or:
with = as```
although that would make not not in in ambiguous
how about
with with as as
Every other channel is a better bet than #esoteric-python, but I don't know which channels cater to that in particular.
Imma refer to this later,; tag natural numbers
I wanna search my message later
Discord is not a good archive, to be honest.
Python 3.9.0 (v3.9.0:9cf6752276, Oct 5 2020, 11:29:23)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import name_hooks
>>> name_hooks.better_name_errors()
>>> x = 1,2,3
>>> print(X)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'X' is not defined, did you mean 'x'
>>> sys.version
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: module 'sys' is not imported here
>>> import sys
>>> version
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'version' is not defined here, but is defined in module 'sys'
>>>
oh no I like it
probably would be better if i implemented it as an excepthook
sounds like effort
currently it hooks into globals
(which is worse)
the final version will do it properly
my CS professor wants it for students to use
cause itll help with new python students
def advanced_name_error(dct, name):
for key in dct:
if name.lower() == key.lower():
return builtinexc(NameError(f'name {name!r} is not defined, did you mean {key!r}'), 3)
if name in sys.modules:
return builtinexc(NameError(f'module {name!r} is not imported here'), 3)
for modname, mod in sys.modules.items():
if getattr(mod, name, None):
return builtinexc(NameError(f'name {name!r} is not defined here, but is defined in module {modname!r}'), 3)
return builtinexc(NameError(f'name {name!r} is not defined'), 3)
def better_name_errors():
init_missing_hook(sys._getframe(1).f_globals, advanced_name_error)
``` this is the code rn @grave rover
Seems surprisingly well thought out
other than the 2 magic functions, init_missing_hook which hotswaps the type of the dict passed in and builtinexc which fakes a builtin exception
Wait does init_missing_hook just modifying a dict to have __missing__
it creates a dict subclass that has a __missing__ that has some custom handling to make sure globals still works mostly
and then it calls the passed in func with globals() and name
What does id(x) + 8 mean
@grave rover ```py
import sys
def better_name_hook(exctype, value, traceback):
if isinstance(value, NameError):
name = str(value).split("'")[1]
f_globals = traceback.tb_frame.f_globals
f_locals = traceback.tb_frame.f_locals
for dct in [f_locals, f_globals]:
for key in dct:
if name.lower() == key.lower():
return sys.excepthook(exctype, exctype(f'name {name!r} is not defined, did you mean {key!r}'), traceback)
if name in sys.modules:
return sys.excepthook(exctype, exctype(f'module {name!r} is not imported here'), traceback)
for modname, mod in sys.modules.items():
if getattr(mod, name, None):
return sys.excepthook(exctype, exctype(f'name {name!r} is not defined here, but is defined in module {modname!r}'), traceback)
return sys.excepthook(exctype, value, traceback)
sys.excepthook = better_name_hook``` this is better
@viscid nymph that is the offset for the object x's type
which iirc is the address of its type...?
^ it is
Yeah I knew that part lol
idk where this question fits in but why does it show this error when i try to play sounds
/usr/bin/python3 /home/chrispy_/os.py
Traceback (most recent call last):
File "/home/chrispy_/os.py", line 2, in <module>
playsound('startup.mp3')
File "/home/chrispy_/.local/lib/python3.7/site-packages/playsound.py", line 92, in _playsoundNix
gi.require_version('Gst', '1.0')
File "/usr/lib/python3/dist-packages/gi/__init__.py", line 129, in require_version
raise ValueError('Namespace %s not available' % namespace)
ValueError: Namespace Gst not available
chrispy_@penguin:~$ /usr/bin/python3 /home/chrispy_/os.py
Traceback (most recent call last):
File "/home/chrispy_/os.py", line 2, in <module>
playsound('startup.mp3')
File "/home/chrispy_/.local/lib/python3.7/site-packages/playsound.py", line 92, in _playsoundNix
gi.require_version('Gst', '1.0')
File "/usr/lib/python3/dist-packages/gi/__init__.py", line 129, in require_version
raise ValueError('Namespace %s not available' % namespace)
ValueError: Namespace Gst not available
would here be the right place to discuss a language based on python using exclusively graphs as input and output?
@red wasp this is not the place for that question
@dark solar maybe, what is the language?
It isn't its just a fun idea I had
If Python is an important part of it, probably discuss it in... actually I have no familiarity with any other channels on this server. If Python isn't what's important about the language, there are there are other cool servers about esoteric programming languages/esolangs.
it's certainly fit for offtopic, not sure about the others
Do someone have thing that could turn python 3x code to one-line?
I do
Where I can find it? Github etc.
I'll dm it
Ok
onelinerizer
Pretty sure it works with Python 3x with 1 exception of __builtins__
just put code in it and change __builtins__ to builtins
## YOUR CODE HERE
def f(x):
return x * 4
y = f(5)
print y``` to this: ```py
(lambda __g, __print: [[(__print(y), None)[1] for __g['y'] in [(f(5))]][0] for __g['f'], f.__name__ in [(lambda x: (lambda __l: [(__l['x'] * 4) for __l['x'] in [(x)]][0])({}), 'f')]][0])(globals(), __import__('builtins', level=0).__dict__['print'])```: http://www.onelinerizer.com/
Convert any Python 2 script into a single line. No newlines allowed. No semicolons, either. No silly file I/O tricks, or eval or exec. Just good, old-fashioned lambda.
!e py (lambda __g, __print: [[(__print(y), None)[1] for __g['y'] in [(f(5))]][0] for __g['f'], f.__name__ in [(lambda x: (lambda __l: [(__l['x'] * 4) for __l['x'] in [(x)]][0])({}), 'f')]][0])(globals(), __import__('builtins', level=0).__dict__['print'])
@tribal moon :white_check_mark: Your eval job has completed with return code 0.
20
it doesnt support 3x @tribal moon
which part
any syntax added in 3x
damn they need to update that
;tag; natural numbers
def self(n=0):
n+=[0,2,print(f"accessing frame: {n+1}"),(f:=lambda*a:None)][1]
def b(c):
try:raise Exception("Top level frame, cannot reference.")
except Exception as e:fr=e.__traceback__.tb_frame;return[{(fr:=getattr(fr,'f_back'))for _ in range(c)},fr.f_code][1]
return setattr(f,'__code__',b(n))or f
I'm starting to break free from single responsibility principle.
why not just return setattr(f,'__code__',b(n))or f ๐ฉ
are you familiar with the else statement in while and for loops?
There's one in try as well.
#PEP 3150 "given" status=deferred
class PEP3150_Given_BaseClass:
def __init__(s,**k):[setattr(s,this,that)for this,that in k.items()]
class PEP3150_Given_MetaClass(type):
def __init__(cls,name,parents,attrs):
for i,attr in enumerate(attrs):
if hasattr(attr,'__call__'):attrs[i]=attr()
super().__init__(name,parents,attrs)
def _pep3150_example(a=4,b=5,op=lambda x,y:x*y):
"""PEP 3150 example:
op(?.f, ?.g) given bound_a=a, bound_b=b in:
def f():
return bound_a + bound_b
def g():
return bound_a - bound_b
"""
@(lambda**k:lambda f:f(**k))(bound_a=a,bound_b=b)
class given(PEP3150_Given_BaseClass,metaclass=PEP3150_Given_MetaClass):
def f(s):return s.bound_a + s.bound_b
def g(s):return s.bound_a - s.bound_b
return op(given.f,given.g)
I therefore declare PEP 3150 redundant
!pep 3150
pep 3150 is deferred last i checked :>
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
๐
!e ```py
execute=(execute_with:=lambda*a,**k:lambda f:f(*a,**k))()
@int
@execute
class n:int=lambda _:69
@execute
class cout:lshift=print
@execute_with(n)
def output(n):
return(n//10)10((n%10)-2)
cout << output
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
420
@viscid nymph you like it?
Why is n a a class though lol
it's an int declaration
@int makes an int object
@execute instantiates the following class
class n actually assigns whatever the result of literally everything is to n
__int__ tells int how to interpret it
lambda _: 69 the actual data that ends up being assigned to n. this will be coerced into an integer.
@execute instantiates
class cout: __lshift__=print very basic c++ iostreams
@execute_with(n) takes the 69 from the class n and executes the function with that as input
def output(n): assign the result of the function to output ;)
return(n//10*10*((n%10)-2) convert 69 to 420
cout << output
call the lshift method of the instantiated cout object with the output
Might as well def n(): return "69"
well, no. then i'd have to do
n = int(n())
why do that, when i can instead use int as a decorator, and make a decorator to handling calling n?
like i could do
@int
@execute
def n:return'69'
but
@int
@execute
class n:__int__=lambda _:69
fucks your brains more
!e ```py
def a():
def b():
def c():
def d():
def e(f): f()
@a()()()
def g():print (69)
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 6, in <module>
003 | TypeError: 'NoneType' object is not callable
huh
XD
!e ```py
a=lambda:lambda:lambda:lambda:lambda:lambda f: f()
@a()()()()()
def b():print (69)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
!e ```py
from _sitebuiltins import Quitter as Exit
@lambda f:f()
class exit:
str=lambda s:"Now I am become Dev, Helloer of Worlds!"
repr=lambda s:Exit(*'ab')(69)
print ( exit )
print ([exit])
print ('this wont print')
@floral meteor :x: Your eval job has completed with return code 69.
Now I am become Dev, Helloer of Worlds!
Is that joke from something? Because I would very much like to steal it.
It's a nerd chuck-off at the quote
Now I am become Death, Destroyer of Worlds!
I know, but I wondered if the variation was a thing before you said it.
probs not
it is now.
XD
I'll just make a compact version cos OCD
@lambda f:f()
class exit:__str__,__repr__=lambda s:"Now I am become Dev, Helloer of Worlds!",lambda s:__import__("_sitebuiltins").Quitter(*'ab')(69)
print ( exit );print ([exit]);print ('this wont print')
feel free to steal
you see, the __str__ method of a list calls the __repr__ methods of all its elements.
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
~ ~ ~ ~ ~ ~ ~ ~ ~ ~!
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
~~~~~~~~~~~~[, , , , , , , , , , , ]
It's because it only resolves this after the loop.
interesting, cos it still assigns it to every printable ascii character in globals
Yes, but it's the same function each time.
There's no closure because it's in the global scope.
chr(126) is '~' by the way.
ik
Try printing this after the update.
but it creates and instantiates the type with the current iteration of this
There are two references to this.
Me wondering where this was defined
One is in the dictionary key, resolved immediately. The other in the lambda, resolved when you print.
but this is not defined
Interesting, but the point remains.
Wait nvm I'm just dumb
(Testing can go in #bot-commands by the way.)
!e alright it works now ```py
globals().update({chr(this):(lambda that:type("",(),{'repr':lambda s:print (end=chr(that))or""})())(this)for this in range(1,127)})
str([H,e,l,l,o,globals()[' '],W,o,r,l,d,globals()['!']])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
!e @rugged sparrow I has figurez out ze ctypes! I can now edit ellipsis!
__import__('ctypes').py_object.from_address(id(...)+8).value = type("Ellipsis",(),{'__repr__':lambda s:print("Hello World!")or __import__('_sitebuiltins').Quitter(*'ab')(139)})
str([...])
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
Hello World!
wait that means i can edit globals dict
@floral meteor yea thats what i did with my init_missing_hook
I'm struggling to edit globals tho
see #bot-commands for some cursed results
!e ```py
import("ctypes").py_object.from_address(id(globals())+8).value=type("dict",(dict,),{"missing":lambda _,key:lambda n:n})
builtins.import('sys').stdout.write(n)
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | AttributeError: 'str' object has no attribute 'stdout'
__missing__ is called for anything located in __builtins__
n doesnt exist at all
yeah...
oh
!e ```py
import("ctypes").py_object.from_address(id(globals())+8).value=type("dict",(dict,),{"missing":lambda _,key:key})
builtins.print (Hello, World, end='!')
also messing with the globals dict has some funky requirements to stop segfaulting
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
Hello World!
you need to unhook before the interpreter closes
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 50, in <module>
003 | File "<string>", line 12, in __missing__
004 | File "<string>", line 41, in parse_int
005 | NameError: name 'one_hundred_and_three_thousand_and_five_hundred_and_forty_two_point_seven' is not defined
no point
that's right, there's no point in doing this...
there should be a point to return floats XD
add it
@floral meteor this is my github repo for weird stuff like this https://github.com/chilaxan/pysnippets
I should move my cursedutils module to a repository
I'm lazy how do i do this again?
github?
ye
google a tutorial lol
!e ```py
from ctypes import py_object
import atexit, builtins
def init_missing_hook(dct, func):
ob_base_p = py_object.from_address(id(dct) + 8)
class missing_hook(dict):
slots = ()
def missing(self, key, ob_base_p=ob_base_p, builtins=builtins):
try:
ob_base_p.value = builtins.dict
return (builtins.dict | self)[key]
except KeyError:
return func(self, key)
finally:
ob_base_p.value = class
ob_base_p.value = missing_hook
@atexit.register
def unhook():
ob_base_p.value = dict
return unhook
shamelessly grabbed from https://ao.gl/how-to-convert-numeric-words-into-numbers-using-python/
def parse_int(dct, textnum, numwords={}):
if not numwords:
units = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen",
]
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
scales = ["hundred", "thousand", "million", "billion", "trillion"]
numwords["and"] = (1, 0)
for idx, word in enumerate(units): numwords[word] = (1, idx)
for idx, word in enumerate(tens): numwords[word] = (1, idx * 10)
for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0)
current = result = 0
for word in textnum.replace("_"," ").split():
if word not in numwords:
raise NameError(f"name {textnum!r} is not defined") from None
scale, increment = numwords[word]
current = current * scale + increment
if scale > 100:
result += current
current = 0
return result + current
unhook = init_missing_hook(globals(), parse_int)
print(one_hundred_and_three_thousand_and_five_hundred_and_forty_two)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
103542
!e print(import('sys').version)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 3.9.2 (default, Mar 12 2021, 19:04:51)
002 | [GCC 8.3.0]
Sorry for very late answer but it already found this and it is what I want but it doesn't work with Python 3x
one of my project ideas is recreating that for python 3.x, most likely 3.9 because then it can be a subclass of the ast unparser.
interesting
alas, i am too busy with too many other things and projects
the ast unparser is quite neat tho, for this type of thing. source: https://github.com/python/cpython/blob/3.9/Lib/ast.py#L670
Me trying to figure out where __class__ is defined 
not here
@viscid nymph its a dunder
if the name exists in a classes scope, its assigned to the class
Oh I didn't know you can access class attributes in methods
its not a class attribute in this case
Oh I see
__class__ is used by super
Isn't it a property
It is, but in this case it is a magic variable filled by the compiler
Not really
It's a cellvar (closure) from the class scope

