#esoteric-python

1 messages ยท Page 109 of 1

night quarryBOT
#

@twilit grotto :white_check_mark: Your eval job has completed with return code 0.

1
simple crystal
#

!e

from math import factorial as f
print(f(0))
night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

1
simple crystal
#

!e

from math import factorial as f
print(f(False))
night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

1
toxic jewel
#

!e print(__import__("math").factorial(__import__("__main__").__doc__.__bool__()))

night quarryBOT
#

@toxic jewel :white_check_mark: Your eval job has completed with return code 0.

1
sick hound
#

how tell us your secrets

fluid tree
#

Better to use a metaclass

alpine flower
#

so ive been told

toxic jewel
#

!e True = False; print(True)

night quarryBOT
#

@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
toxic jewel
#

;^(

snow beacon
#

Only on Python 2.

wary falcon
#

ya'll in here pushing the oneliner limits i see lol

#

!e def ๐’‰๐–Š๐–‘๐™กo(๐•Ÿ๐—ฎ๐—†๐‘’):
๐“…๐™ง๐’พ๐“ท๐—(f"Hello {๐ง๐•’๐—†๐ž}!")

๐ก๐’†lโ„“โ‚’('World')

night quarryBOT
#

@wary falcon :white_check_mark: Your eval job has completed with return code 0.

Hello World!
wary falcon
#

whaaaa

autumn saffron
#

!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)
night quarryBOT
#

@autumn saffron :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | False
autumn saffron
#

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)
night quarryBOT
#

@autumn saffron :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | True
autumn saffron
#

!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)
night quarryBOT
#

@autumn saffron :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | True
autumn saffron
#

gottem

#

sadly it needs to return a string for printing purposes

valid crow
#

!e

night quarryBOT
#
Command Help

!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!*

valid crow
#

!e print("hello world")

night quarryBOT
#

@valid crow :white_check_mark: Your eval job has completed with return code 0.

hello world
valid crow
#

!e
n1 = int(input("enter your first number"))
n2 = int(input("enter your second number"))
print(n1+n2)

night quarryBOT
#

@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
valid crow
#

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)

night quarryBOT
#

@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
valid crow
#

sadness

snow beacon
#

Feel free to use #bot-commands for more testing.

strange basin
verbal totem
#

!e

z = lambda: (print("hello") or True) and print("world")
z()โ€Š
night quarryBOT
#

@verbal totem :white_check_mark: Your eval job has completed with return code 0.

001 | hello
002 | world
verbal totem
#

Does this count as cheating?

granite cloak
#

No.

snow beacon
#

What's your goal?

floral meteor
#

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")

night quarryBOT
#

@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

floral meteor
#

there

#

the first two worked, but the second one worked, then made python die

earnest wing
#

!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)

night quarryBOT
#

@earnest wing :x: Your eval job has completed with return code 139 (SIGSEGV).

001 | 0
002 | 1
003 | 2
004 | 3
steep mural
#

why doesn't that have the faulthandler thing

floral meteor
#

what faulthandler thing?

#

hey i have an idea for... effect

earnest wing
#

because it's a memory access violation

#

the interpreter can't really catch it

steep mural
#

isn't that how faulthandler works in the first place pithink

floral meteor
#

!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)

night quarryBOT
#

@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

snow beacon
#

The interpreter would have to check every memory access. It would be even slower.

earnest wing
#

might need to enable it with a commandline flag

steep mural
#

faulthandler catches the SIGSEGV signal

#

the interpreter doesn't have to check

earnest wing
#

yeah, python3 -X faulthandler

snow beacon
#

I'm unfamiliar with the faulthandler. What's its use case?

earnest wing
#

just took a quick read

snow beacon
#

Cool beans.

earnest wing
#

odd that it doesn't work for some faults

#

you'd expect stack overflows and bad reads both trigger it

steep mural
#

funny it actually has an example using ctypes.string_at(0)

earnest wing
#

implementation specific behavior :mystery:

steep mural
#

turns out you don't need faulthandler to get the stack overflow message makes sense

earnest wing
#

so each call just gets checked on the c side for overflow?

steep mural
#

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

viscid nymph
#

I thought you can recurse 1000 times until a recursion error

earnest wing
#

You can catch the error, or prevent it altogether with sys.setrecursionlimit

floral meteor
#

!e ```py
import('sys').setrecursionlimit(9999999)
def print(*args):
try: print (*args)
except: print (*args)

print ("Hello World!")

night quarryBOT
#

@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).

[No output]
floral meteor
#

huh, much better than the last one

final night
#

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

snow beacon
#

[x for item in input_list for x in item if isinstance(item, list) else [item]] might work.

final night
#
  File "<stdin>", line 1
    t = [x for item in input_list for x in item if isinstance(item, list) else [item]]
                                                                          ^
SyntaxError: invalid syntax
earnest wing
#

swap the condition and the for

snow beacon
#

Or bracket the item if ... [item] part.

final night
#

same as my attempt, just replicates the list 1:1

snow beacon
#

Regular brackets, not square ones.

final night
#

parenthesis?

snow beacon
#

I stand by what I said. () these things.

final night
#

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

snow beacon
#

Without them it parses as [expr for var in iterable if condition], but then it sees the else keyword and gets confused.

final night
#

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

snow beacon
#
fl = lambda input_list: [x for item in input_list for x in (fl(item) if isinstance(item, list) else [item])]
final night
#

yep, that works

#

wow, that's super cool

floral meteor
#

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.

grave rover
#

Nice

#

Meanwhile I made my pipeline/chain thing work with async stuff

grave rover
#

Do y'all ever just feel like doing something cursed but having zero ideas

earnest wing
#

Idea: implement a DSL using decorator and matmul syntax

snow beacon
#

Hello World using no letters or numbers?

#

Actually that's probably impossible.

earnest wing
#

You'd need at least a few letters

#

Unless you assume all files use the unicode-escape codec

#

even then you'll need x

hard spoke
#

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())
night quarryBOT
#

@hard spoke :white_check_mark: Your eval job has completed with return code 0.

Hello World
thin trout
#

Ha

snow beacon
snow beacon
hard spoke
#

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

snow beacon
#

_=[]?

hard spoke
snow beacon
#

Anything juicy from there probably requires attribute access.

hard spoke
#

printing anything is still a problem, though. You could get print from builtins, but that'd requires getting the builtins at the very least...

snow beacon
#

You can construct arbitrary numbers pretty easily.

#

You wouldn't have easy access to any functions though.

thin trout
#

Bytecode manipulation when

hard spoke
#

oh, I got it

snow beacon
#

+([]==[]) is 1, although you can also use []==[].

hard spoke
#

yeah, that's what I thought, bool being a subclass of int finally pays off

snow beacon
#

That fact is also good for array indexing with code golf.

hard spoke
#
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

thin trout
#

Noice

#

How do you execute numbers now

hard spoke
#

huh?

#

ah, how to get functions from this? no idea, lol

thin trout
#

Well, it is nice to have numbers, now we need to have code!

snow beacon
#

Someone made a generator with True and << at some point, which should be easily modifiable should a smaller number encoding prove useful.

hard spoke
#

edited above message: fixed bug which included zeros in the representation

fossil estuary
#

does this count as esoteric :p

#

Let me get it

earnest wing
#

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)?

fossil estuary
#

!e ```py
globals()["builtins"].print(globals()["builtins"].int(globals()["builtins"].str(globals()["builtins"].round(111.222333, 3)).replace(".","")))

night quarryBOT
#

@fossil estuary :white_check_mark: Your eval job has completed with return code 0.

111222
hard spoke
#

well, I'm doing dumb bruteforce search of these combinations

earnest wing
#

** and << are definitely useful for large numbers

snow beacon
#

~ and - useful for small ones.

earnest wing
#

but using temporary variables also shortens programs

#

_ of course

fossil estuary
#

yeah

snow beacon
#

""<"" seems to be a short way to get 0.

fossil estuary
#

i have some code that errors and runs in the same string lol, idk how it works tbh

earnest wing
#

If you could somehow get bytes objects...

#

[*bytes] is an easy way to get certain bytes in the printable ascii range

snow beacon
#

Or simply indexing into the byte object.

hard spoke
#

huh, where are floats coming from?..

#

I somehow got floats from ints using only * + << ** - ~

earnest wing
#

a ** -b

hard spoke
#

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 (~([]==[]))*(~((~([]==[]))*(~([]==[]))))
earnest wing
#

Though it would be pretty funny to make a function that can yield every possible floating point value

hard spoke
#

here are some supposedly shortest representations

earnest wing
#

0: +(''<'')?

hard spoke
#

I'm not doing strings yet, but hmm

earnest wing
#

or without the +()

#

if bools are okay

#

otherwise []!=[]

hard spoke
#

I think it'll only provide a benefit for 0, so no big reason to include it here

earnest wing
#

I mean it contributes to the other numbers as well

#

maybe?

#

no

hard spoke
#

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

fossil estuary
#

:o

#

how would you give it that input?

hard spoke
#

wdym?

#

also, whoops, it's bugged

fossil estuary
#

like, how do you give it the input (like you provided)

hard spoke
#

!e

print(eval("([]==[])-(((~([]==[]))*(~((~([]==[]))*(~([]==[])))))**(([]==[])+([]==[])))"))
night quarryBOT
#

@hard spoke :white_check_mark: Your eval job has completed with return code 0.

-99
hard spoke
#

it's valid Python code

fossil estuary
#

Yeah, I can tell.

fossil estuary
#

Oh wait, nvm i had just realised what it was

hard spoke
#

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

#

I added | & ^, but they provided literally zero improvements in length pithink

fossil estuary
#

hm

fossil estuary
hard spoke
#

very possible, I haven't actually mypyed it yet

#

currently refactoring

earnest wing
#

yeah that's just from reusing s and not giving it a generic type at first

fossil estuary
#

its just my IDE that returns that stuff

earnest wing
#

no effect on runtime

#

just lints

#

mypy doesn't know how to infer generic type parameters for e.g. empty list literals

fossil estuary
#

Huh, i dont use that

earnest wing
#

most static type checkers don't

#

i don't know of any that do, beyond some rare circumstances

fossil estuary
#

my IDE probably just uses it for some reason

#

but yeah.

plucky wedge
#
print(eval("([]==[])-(((~([]==[]))*(~((~([]==[]))*(~([]==[])))))**(([]==[])+([]==[])))"))

How does this get numbers? Does it take the []==[] result and do numerical operations on it? Like int(True) * 10

hard spoke
fossil estuary
#

[]==[] is equal to 1 @plucky wedge

plucky wedge
#

Yes because of True?

fossil estuary
#

mhm

hard spoke
#

Also, lol, Pycharm's linter (but not mypy) gives me a TypeError here:

#

(wrongly - this is List[Tuple[str,int]], not List[int])

fossil estuary
#

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
hard spoke
fossil estuary
#

i use 3.7

hard spoke
#

I don't remember where this was added, I'm using 3.8

fossil estuary
#

well, thats your answer then?

hard spoke
#

you can fix it by changing such occurences from {a=} to a={a}

plucky wedge
#

What does ~ do?

hard spoke
#

Bitwise negation

plucky wedge
#

Mmmm yes

#

A bit wise negation

#

Imma google it

hard spoke
plucky wedge
#

Wait so it inverses? Like inverses the binary

fossil estuary
#

Hey, ConfusedReptile dm me quickly :)

hard spoke
#

actually, not sure if that's the correct description, hold on

plucky wedge
#

Donโ€™t worry Iโ€™m just gonna google it

#

Iโ€™m not to knowledgeable on this stuffs

fossil estuary
#

@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...
fossil estuary
#

its from my IDE, so i am unsure

hard spoke
#

also, that last error at least is very weird

#

because Dict[str, Callable[[Any], Any]] fits Dict[str, Callable[[int], int]] pithink

#

oooh, that's probably exactly why it says to use Mapping, so that it's covariant

fossil estuary
#

yea

hard spoke
#

huh, how do I declare a function with 2 arguments with Mapping?..

fossil estuary
#

i do not know.

hard spoke
#

ah, looks like it might just be that all arguments before the last one are inputs nope

snow beacon
snow beacon
#

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
#

Not weird just havenโ€™t seen that before

#

!e
print(-~1)

night quarryBOT
#

@plucky wedge :white_check_mark: Your eval job has completed with return code 0.

2
plucky wedge
#

!e
print(-~3<<1)

night quarryBOT
#

@plucky wedge :white_check_mark: Your eval job has completed with return code 0.

8
plucky wedge
#

Iโ€™m gonna continue this in bot commands lol

earnest wing
#

!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)))

night quarryBOT
#

@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

earnest wing
#

Example of using ~- as succ/pred

fossil estuary
#

this has intrigued me

plucky wedge
#

Thatโ€™s cool

snow beacon
#

Golfing is a good way to learn how to abuse operators for new purposes. For instance, a Boolean not is just x<1.

plucky wedge
#

Iโ€™m gonna replace all my division with >> lol

hard spoke
#

I wonder how I can incorporate that. The problem is determining when I can or can't drop parantheses.

snow beacon
#

There should be a precedence chart somewhere for Python.

#

Alternatively, the ast module might have a utility for it.

hard spoke
#

hmm, perhaps I can consider two cases - with or without them

earnest wing
snow beacon
#

Too complicated for my liking, even eliminating the ones with words.

hard spoke
#

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

earnest wing
#

Smells like big chained pows

#

x ** (y ** (z ** w))

hard spoke
#

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

snow beacon
#

Maybe the compilation time. For larger scripts it would be amortised.

hard spoke
#

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:

#

wait, where the hell is positives

#

oh, I messed up

hard spoke
#

Yay, my program managed to autogenerate code that hangs eval!

#
(~(([]==[])+([]==[])))**-~(([]==[])+([]==[]))**(-~-~([]==[])<<-~(([]==[])+([]==[])))
earnest wing
#

two **s and a <<? better be a huge number

hard spoke
#

it's (-3)**16777217, I believe

#

right, so how can I fix this?...

#

perhaps I can try evaluating with numpy ints first

earnest wing
#

A container for the eval call?

#

Or just using sized ints & failing on overflow I guess

tribal moon
#

Looks like Javascript

toxic jewel
#

!e print(~(~([]==[])<<([]==[]<[]==[])>>((~~(([]==[])&~([]==[])))))+([]==[]))

night quarryBOT
#

@toxic jewel :white_check_mark: Your eval job has completed with return code 0.

2
rose stump
#

!e

#

print

toxic jewel
#

!e

print(chr(((~(~([]==[])<<([]==[]<[]==[])>>((~~(([]==[])&~([]==[])))))++(([]==[]))<<([]==[])+~(~([]==[])+([]==[]))<<([]==[])++~(~([]==[])<<([]==[])))^~(~([]==[]))++([]==[])++(([]==[])<<([]==[]))+~(~(([]<[])++([]==[])))<<(([]==[])&([]==[])<<([]==[]))<<([]==[])++(()==())^(()==())++(()==())+~((~(()==())++(()==())))%([]==[])<<(([]==[])++([]==[]))++(([]==[])+(([]==[]))))+~(([]==[])<<([]==[]))+~(([]==[])++([]==[]))++([]==[]))+chr(((([]==[])++([]==[]))++(([]==[])++([]==[]))++(([]==[])+([]==[])++~(~(([]==[])++([]==[]))))<<(([]==[])++~(~([]==[])++([]==[])))^([]==[])<<([]==[])++~(~([]==[])+([]==[]))<<(([]==[])++([]==[]))<<(([]==[])++(([]==[])++([]==[])))++([]==[]))++~(([]==[])++(([]==[])<<([]==[])++([]==[])++([]==[])<<([]==[]))++(([]==[])<<([]==[]))<<([]==[]))++(([]==[])<<(([]==[])++([]==[]))++([]==[])<<([]==[]))++~(([]==[])++([]==[]))+([]==[]))+chr(((~(~([]==[])<<([]==[]<[]==[])>>((~~(([]==[])&~([]==[])))))++(([]==[]))<<([]==[])+~(~([]==[])+([]==[]))<<([]==[])++~(~([]==[])<<([]==[])))^~(~([]==[]))++([]==[])++(([]==[])<<([]==[]))+~(~(([]<[])++([]==[])))<<(([]==[])&([]==[])<<([]==[]))<<([]==[])++(()==())^(()==())++(()==())+~((~(()==())++(()==())))%([]==[])<<(([]==[])++([]==[]))++(([]==[])+(([]==[]))))+~(([]==[])<<([]==[]))+~(([]==[])++([]==[]))++([]==[])))
night quarryBOT
#

@toxic jewel :white_check_mark: Your eval job has completed with return code 0.

owo
hard spoke
#

!e

_=chr(((~(~([]==[])<<([]==[]<[]==[])>>((~~(([]==[])&~([]==[])))))++(([]==[]))<<([]==[])+~(~([]==[])+([]==[]))<<([]==[])++~(~([]==[])<<([]==[])))^~(~([]==[]))++([]==[])++(([]==[])<<([]==[]))+~(~(([]<[])++([]==[])))<<(([]==[])&([]==[])<<([]==[]))<<([]==[])++(()==())^(()==())++(()==())+~((~(()==())++(()==())))%([]==[])<<(([]==[])++([]==[]))++(([]==[])+(([]==[]))))+~(([]==[])<<([]==[]))+~(([]==[])++([]==[]))++([]==[]))
print(_+chr(((([]==[])++([]==[]))++(([]==[])++([]==[]))++(([]==[])+([]==[])++~(~(([]==[])++([]==[]))))<<(([]==[])++~(~([]==[])++([]==[])))^([]==[])<<([]==[])++~(~([]==[])+([]==[]))<<(([]==[])++([]==[]))<<(([]==[])++(([]==[])++([]==[])))++([]==[]))++~(([]==[])++(([]==[])<<([]==[])++([]==[])++([]==[])<<([]==[]))++(([]==[])<<([]==[]))<<([]==[]))++(([]==[])<<(([]==[])++([]==[]))++([]==[])<<([]==[]))++~(([]==[])++([]==[]))+([]==[]))+_)
night quarryBOT
#

@hard spoke :white_check_mark: Your eval job has completed with return code 0.

owo
hard spoke
#

yay, optimizations ๐Ÿ˜…

lucid shell
#

!e
(~(([]==[])+([]==[])))-~(([]==[])+([]==[]))(-~-~([]==[])<<-~(([]==[])+([]==[])))

night quarryBOT
#

@lucid shell :warning: Your eval job timed out or ran out of memory.

[No output]
lucid shell
#

!e
print((~(([]==[])+([]==[])))-~(([]==[])+([]==[]))(-~-~([]==[])<<-~(([]==[])+([]==[]))))

night quarryBOT
#

@lucid shell :warning: Your eval job timed out or ran out of memory.

[No output]
lucid shell
#

!e

a=(~(([]==[])+([]==[])))**-~(([]==[])+([]==[]))**(-~-~([]==[])<<-~(([]==[])+([]==[])))
print(a)
night quarryBOT
#

@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
night quarryBOT
#

@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
toxic jewel
#

#bot-commands

hard spoke
toxic jewel
#

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

hard spoke
#

create what exactly?

#

arbitrary strings using chr and this number notation? that's pretty easy, just wrap the numbers in chrs

toxic jewel
#

yeah

formal sandal
#

!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)
night quarryBOT
#

@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

snow beacon
#

Ooh, that is a very cool find.

sick hound
#

Whats this about?

floral meteor
floral meteor
#

I will make a class called Essential that when deleted,it crashes python Ahahahahahahaha

#

Hello there fix error

formal sandal
#

!e

class GcBomb:
    def __del__(self):
        cls = type(self)
        [cls(), cls(), cls(), cls()]

GcBomb()
night quarryBOT
#

@formal sandal :warning: Your eval job timed out or ran out of memory.

[No output]
floral meteor
#

Awww no sigsegv

formal sandal
#

that actually eats memory away very quickly

floral meteor
#

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

floral meteor
#

@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
>>> 
floral meteor
#

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

night quarryBOT
#

@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

floral meteor
#

ahhhhhh I see

#

ok, if there's an init method, it just doesn't work. :/

fossil estuary
#

!e ```py
exec('%c'10%(((((((([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[])),((((((([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])),((((((([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]),((((((([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])),((((((([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[])),(((((([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[])),(((((([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])),((((((([]==[]))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]),(((((([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])),(((((([]==[])+([]==[])))(([]==[])+([]==[]))+([]==[]))(([]==[])+([]==[])))(([]==[])+([]==[])))*(([]==[])+([]==[]))+([]==[]),))

night quarryBOT
#

@fossil estuary :white_check_mark: Your eval job has completed with return code 0.

a
fossil estuary
#

:)

tribal moon
#

!e ```py
import ctypes
from contextlib import suppress

while True:
with suppress(Exception):
ctypes.resize(ctypes.c_int(0x99), 0x32 << 0x32)```

#

lol

night quarryBOT
#

@tribal moon :warning: Your eval job timed out or ran out of memory.

[No output]
fossil estuary
#

lol nice

tribal moon
#

did you do that []==[] thing by hand?

#

like to get a

fossil estuary
#

no, i made a converter for it

tribal moon
#

can you do Hello, World!

fossil estuary
#

it doesnt even fit in discord messages.

#

but sure, i can

#

already did.

tribal moon
#

damn nice

fossil estuary
#

ty

tribal moon
#

is it possible without the exec part and stuff

fossil estuary
#

havent tried

floral meteor
#
>>> 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

fossil estuary
#

how

floral meteor
#

i don't even know. There's no where where death.kill_python could've been called

fossil estuary
#

how does it kill python, im interested

floral meteor
#
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
fossil estuary
#

explain it.

floral meteor
#

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[31m is 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

fossil estuary
#

damn, thats kinda cool

#

is this so called "cursed" lib public?

tribal moon
#

Has anyone actually broken Snekbox or NSJail before?

floral meteor
floral meteor
tribal moon
#

damn

fossil estuary
#

i even tried once

tribal moon
#

What's the shortest code that brings SIGSEGV

twilit grotto
#

ctypes.string_at(0) iirc

tribal moon
#

!e py import ctypes ctypes.string_at(0)

night quarryBOT
#

@tribal moon :warning: Your eval job has completed with return code 139 (SIGSEGV).

[No output]
tribal moon
#

Nice

floral meteor
#

except it doesn't work on windows 10

#

access at 0 is forbidden

twilit grotto
#

OSError ๐Ÿ˜”

tribal moon
#

Is there a proper way to search for bugs in Snekbox for the bot?

tiny lodge
#

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...

floral meteor
#

the second one could be turned into a lambda to make it actually one line

tiny lodge
#

agreed!
add_one = lambda x: type(x)(i + 1 for i in x)

floral meteor
#

now remove the space around the operators :P

#

!e ```py
print((lambda x:type(x)(i+1for i in x))([0,1,2,3]))

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

[1, 2, 3, 4]
floral meteor
#

yep it works

tiny lodge
#

nice

floral meteor
#

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.

somber nest
#

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?

thin trout
#

!e
Pure Python segfault:

import time
time.pthread_getcpuclockid(-1)โ€Š
night quarryBOT
#

@thin trout :warning: Your eval job has completed with return code 139 (SIGSEGV).

[No output]
fair vigil
#

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

snow beacon
somber nest
#

Thank you for responding

#

Is this true for every data type in Python tho?

snow beacon
#

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.

broken mesa
somber nest
#

Thank you both

hot crypt
#

!e

a = 10
print(a is 10)
b = 1000
print(b is 1000)
night quarryBOT
#

@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
hot crypt
#

wait lemon_thinking

#

this works on console 3.8.7

toxic jewel
#

!e
a=10 print(a is not not 10)

night quarryBOT
#

@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
toxic jewel
#

:^(

jagged path
#

!e
a=10
print(a)

night quarryBOT
#

@jagged path :white_check_mark: Your eval job has completed with return code 0.

10
earnest wing
#
not not 1 is not (not 1) is (not not 1)
thin trout
#

||False||?

sick hound
#

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?

thin trout
#

The 6th alpha was released yesterday

#

There is no stable release first, but you can build it from source to access the alpha

proper vault
night quarryBOT
#

@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
hollow kiln
#
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

round violet
#

nice

proper vault
#
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)
sick hound
#

my first one here

#

!e

night quarryBOT
#
Command Help

!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!*

sick hound
#

!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())
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

Hello, World!
tidal magnet
#

now that's esoteric, lol

viscid nymph
#

You don't need all those ints tho

broken mesa
#

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()

night quarryBOT
#

@broken mesa :white_check_mark: Your eval job has completed with return code 0.

001 | its run
002 | called from the allowed caller
broken mesa
pale mirage
#

!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()

broken mesa
pale mirage
#

Ok sorry

rugged sparrow
#
>>> private_func.__closure__[0].cell_contents()
its run
1
>>> ```
#

or i could replace the self object in the closure

broken mesa
#

hm, nice approach

#

(clarification: im done working on this, there will always be workarounds, just wanted to give people a fun challenge)

hard spoke
#

huh, I crashed Python trying

broken mesa
#

yep, happened a few times developing too

hard spoke
#

does that count as a dependency poisoning attack? ๐Ÿ˜›

broken mesa
#

idk maybe? but i love the various solutions people have come up with

#

its very interesting to see the different approaches

frigid wharf
#
object.__setattr__(private, "code", inspect.currentframe().f_code)
print(private_func())
potent comet
#

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.

rugged sparrow
viscid nymph
#

You could make your own inspect module and ez

rugged sparrow
#

!e py try:raise Exception except Exception as e: frame = e.__traceback__.tb_frame print(frame)

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

<frame at 0x7fc15a0abcf0, file '<string>', line 4, code <module>>
snow beacon
#
foo = lambda:0
foo.__code__ = private.f_code
print(foo())
#

Not quite calling private_func, but has the same result.

viscid nymph
#

Might as well exec(private.f_code)

fossil estuary
#

yeah true

#

but its not as "cool"?

#

probably the wrong term

snow beacon
#

exec always feels like cheating.

fossil estuary
#

I agree.

snow beacon
#

Not as 'honourable' perhaps?

fossil estuary
#

Indeed.

sick hound
#

makes it look more

#

more

#

yk?

toxic jewel
#

esowtewic python

fossil estuary
#

no.

toxic jewel
#

๐Ÿฅบ

terse mortar
plucky wedge
#

esotewic pyfuwu

snow beacon
#

!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(): "?"

night quarryBOT
#

@snow beacon :white_check_mark: Your eval job has completed with return code 0.

Whats this?
viscid nymph
#

What's the second @ and how is that valid syntax pithink

snow beacon
#

That's the matrix multiplication operator.

#

w @ ... is doing a matrix multiplication between the W object and the Ellipsis.

viscid nymph
#

And I'm assuming __matmul__ is the dunder for that

snow beacon
#

It is.

sick hound
#

Why are they called dunders vvBlank

twilit grotto
#

double under

sick hound
viscid nymph
#

Lol

grave rover
viscid nymph
#

Lol

toxic jewel
#

!e __๐”ฆ๐”ช๐”ญ๐”ฌ๐”ฏ๐”ฑ__("sys").๐”ฐ๐”ฑ๐”ก๐”ฌ๐”ฒ๐”ฑ. ๐”ด๐”ฏ๐”ฆ๐”ฑ๐”ข("esowtewic pyfon")

night quarryBOT
#

@toxic jewel :white_check_mark: Your eval job has completed with return code 0.

esowtewic pyfon
sick hound
#

made dijkstras algorithm in one line

worthy iris
#

!e import subprocess; print(subprocess.Popen("uname -a", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.read().decode())

night quarryBOT
#

@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
worthy iris
floral meteor
rugged sparrow
#

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)```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | False
rugged sparrow
#

^ uses os.execv to rerun the current bot eval with different python flags

floral meteor
rugged sparrow
#

!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])

night quarryBOT
#

@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])
floral meteor
#

!e Alrighty, no imports exit 139, using only "noob code"

def print(a):
 try: print (a)
 except: print (a)
print ("Hello World!")
night quarryBOT
#

@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

earnest wing
rugged sparrow
#

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

floral meteor
#

!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!")โ€Š
night quarryBOT
#

@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).

[No output]
floral meteor
#

Huh still 139

earnest wing
#

pyctypes or something

floral meteor
#

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

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

420
floral meteor
#

completely redefine the way functions and classes are used

earnest wing
#

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)

night quarryBOT
#

@earnest wing :white_check_mark: Your eval job has completed with return code 0.

21
floral meteor
#

!e ```py
def_if=lambda c:(c and(lambda f:f))or(lambda f:lambdau,**ck:None)
execute=(execute_with:=lambda
u,ck:lambda f:f(*u,ck))()
@execute_with("Hello World!")
@def_if(False
False)
def _do(s): print (s)
@execute
@def_if(False
True)
def _do(): print ("error")

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

Hello World!
floral meteor
#

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=lambda
a:lambda f:lambda
u,**ck:{f(*u,**ck)for _ in iter(a)}
execute=(execute_with:=lambda
u,**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='.')

night quarryBOT
#

@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

floral meteor
#

143 (SIGTERM)
Hey! I got a new exit code!

earnest wing
#

That's just the process getting killed by the bot

floral meteor
#

ik

#

You like my if, for and while suite replacements?

earnest wing
#

I don't really pay attention to random evals

floral meteor
#

k

#

What other statements could I replaced with a decorated def?

earnest wing
#

yield from

floral meteor
#

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

night quarryBOT
#

@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

floral meteor
#

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)

night quarryBOT
#

@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

floral meteor
#

just replaced with return don't need fancy defs and decorators :/

viscid nymph
#
yield from x

Is the same as

for y in x:
    yield y
floral meteor
#

or ```py
return(y for y in x)

viscid nymph
#

Technically not the same thing

floral meteor
#

well if you wanna yield some more but who wants to do that?

viscid nymph
#

What's the point of returning a generator expression

floral meteor
#

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))

night quarryBOT
#

@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
floral meteor
#

looks like i'm gonna have to do some extra hacky stuff.
@rugged sparrow this is your forte, how do i inject local variables?

rugged sparrow
#

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 ^

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)

night quarryBOT
#

@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

floral meteor
#

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

floral meteor
#

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

thin trout
#

Oh I see it

#

Haha, that's stupid

floral meteor
#
def print(a):
 try: print (a)
 except: print (a)
print ("Hello World!")
#

use sys.setrecursionlimit if you dont want it to print error message

desert iris
#

!e

night quarryBOT
#
Command Help

!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!*

desert iris
#

!e import this

night quarryBOT
#

@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

viscid nymph
#

!e

while not print(x:=x if'x'in globals()else 0):x+=1
night quarryBOT
#

@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

viscid nymph
#

What's sigterm pithink

thin trout
#

Killed by the OS

viscid nymph
#

Oh lol

steep mural
#

Actually it's snekbox terminating the process, it was recently changed to use terminate (which sends SIGTERM) instead of kill (which sends SIGKILL)

thin trout
#

Ooh we need to update that

#

!remind 30M update

night quarryBOT
#
Sure.

Your reminder will arrive in 30 minutes!

night quarryBOT
#

@thin trout

It has arrived!

Here's your reminder: update.
[Jump back to when you created the reminder](#esoteric-python message)

pulsar isle
#

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

rugged sparrow
pulsar isle
#

If that's possible

rugged sparrow
#

it might be

pulsar isle
#

This is heading towards me overwriting NameError

#

so that NameError doesn't actually error and just runs my stuff

rugged sparrow
#

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

pulsar isle
#

Ok

#

How does that go

#

Haven't done that before

rugged sparrow
#

can you use dependencies?

#

cause my fishhook module makes hooking dict.__getitem__ easy but i can show how to do it directly with ctypes

pulsar isle
#

The latter please

#

I want this to be as scuffed as possible

#

I can probably look at the code tho

rugged sparrow
#

your welcome to, its on pypi and github

#

ill write a quick example of hooking dict.__getitem__ (with ctypes)

pulsar isle
#

ahahaha this is so cursed i love it

rugged sparrow
pulsar isle
#

ye

#

looking at it now

proper vault
#

Couldn't it be simpler by hooking __missing__

rugged sparrow
naive roost
#

__missing__ is why defaultdict works in the first place, if I remember correctly

pulsar isle
#

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]```
proper vault
#

It's used when getitem fails, similar to getattr/getattribute. Makes subclassing dict much easier

rugged sparrow
#

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

pulsar isle
#

so how do I do this hook thing for the exception

rugged sparrow
#

im trying to figure out a way

pulsar isle
#

ah ok sorry

rugged sparrow
#

hooking dict.__getitem__ breaks a lot lol

rugged sparrow
#

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

pulsar isle
#

awesome

#

thank you for working very hard on this

#

I'll share the final code also, I think you'll like it

floral meteor
rugged sparrow
#

@pulsar isle this is proving more difficult then i expected with my current method

#

gonna try something else

rugged sparrow
#

!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

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

this_name_does_not_exist
rugged sparrow
#

@pulsar isle got it working

#

wasnt able to hook all exceptions sadly (that was my first attempt)

rustic aspen
#

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

rugged sparrow
#

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

rustic aspen
#

I know, I know, thatโ€™s why itโ€™s not a python question

plucky wedge
#

!ot

night quarryBOT
rugged sparrow
#

!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```

night quarryBOT
#

@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
rugged sparrow
#

@pulsar isle ^ cleaner now

#

(and mostly stable)

tiny hazel
#

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.

snow beacon
#
'''
foo()
'''
```will not.
rugged sparrow
rugged sparrow
#

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

viscid nymph
rugged sparrow
#

yea its one of the weird artifacts from python2

viscid nymph
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

lol
viscid nymph
#

!e

def foo():
    0/0
foo.__code__ = compile("print('lol')", __name__, "exec")
foo()
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

lol
tiny hazel
#

@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?

viscid nymph
#

Not 100% sure thonk

#

There's code.co_code

rugged sparrow
#

@tiny hazel not easily

tiny hazel
#

Iโ€™m about to try some really cursed things lmao

viscid nymph
#

!e

def foo():
    print("lol")
import dis
dis.dis(foo)
night quarryBOT
#

@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
floral meteor
#

!e ```py
print (globals()|{'sixty-nine':420,'four-twenty':69})

night quarryBOT
#

@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}
rugged sparrow
#

I do know that... i just forgot lmao

floral meteor
#

!e ```py
globals() |= {'a':420}
print (a)

night quarryBOT
#

@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
floral meteor
#

illegal

#

damn, the FBI gonna coma after me?

floral meteor
#

that's what I think when I see illegal :/

snow beacon
#

I don't think that's Python.

strange basin
#

!e
zอกฬฏฬฏaฬงอŽฬบlฬกอ“ฬซgฬนฬฒoฬกฬผฬ˜ = 69
print(zอกฬฏฬฏaฬงอŽฬบlฬกอ“ฬซgฬนฬฒoฬกฬผฬ˜)

night quarryBOT
#

@strange basin :white_check_mark: Your eval job has completed with return code 0.

69
strange basin
snow beacon
#

Even so, it would throw an error if it were the code on it's own.

dire yew
#

...

regal osprey
dire yew
dire yew
proper vault
#

print's 1 five times

dire yew
#

wut? but why?

regal osprey
#

it's a lambda

proper vault
#

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

regal osprey
#

alias, it can be declared inline

dire yew
#

wait but why is this code useful?

regal osprey
#

some of tyhe insight comes from a website with a lot of lambda horrors

dire yew
#

why would you just print 1

regal osprey
#

oh

#

well it's just a proof of concept

dire yew
#

of what concept?

#

bruh my brain == fried

regal osprey
#

it could probably do anything a generator can do

#

with a lot more code

dire yew
#

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

regal osprey
#

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

proper vault
#

also, why not

[ print(next(g)) for gen in  [lambda: [(yield 1), (yield from gen())]] for g in [gen()] for i in range(5) ]
regal osprey
#

so i used generators to do the multiple actions

proper vault
#

:= is for schmucks /s

regal osprey
#

idk i'm not that good a dev so i just used what i could think of at the time

proper vault
#

yeah, makes sense

regal osprey
dire yew
steep mural
#

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.)

pulsar isle
pulsar isle
#

@rugged sparrow

rugged sparrow
#

nice

pulsar isle
#

i have more things that would be cool tho

rugged sparrow
#

i might make bare words returned undefined

#

like js lol

pulsar isle
#

lol

rugged sparrow
#

do you understand how it works?

pulsar isle
#

yeah roughly

#

could the same theoretically be done for syntax error

#

or is that a different mechanism

rugged sparrow
#

syntax errors are raised by the compiler

#

basically all i did here is write a way to add __missing__ to existing dictionarys

pulsar isle
#

Ah yeah I see

rugged sparrow
#

ooo i could use this to add numeric literals

pulsar isle
#

ohno

#

.exe

rugged sparrow
#

like one_hundred_and_one would be 101

pulsar isle
#

yep

rugged sparrow
#

!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)```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

101
rugged sparrow
#

@pulsar isle found a quick and dirty converter online and it works

rugged sparrow
#

ahh i remember that

steep mural
#
match = False
match match:
    case match if match is match: print(match)

guess python has context keywords now?

viscid nymph
#

That works?

steep mural
#

yes

#

making match a keyword would break so many things

#

case is also a "context keyword?" lemon_pleased

proper vault
#

yeah, weak keywords are a thing

#

async was also that for a while

steep mural
#

oh interesting

viscid nymph
#

They should do that for some other keywords

#

Like with

stark fable
#

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```
stark fable
#

although that would make not not in in ambiguous

proper vault
#

how about

with with as as
snow beacon
#

Every other channel is a better bet than #esoteric-python, but I don't know which channels cater to that in particular.

floral meteor
#

I wanna search my message later

snow beacon
#

Discord is not a good archive, to be honest.

rugged sparrow
#
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'
>>> 
grave rover
#

oh no I like it

rugged sparrow
#

probably would be better if i implemented it as an excepthook

grave rover
#

sounds like effort

rugged sparrow
#

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
grave rover
#

Seems surprisingly well thought out

rugged sparrow
#

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

viscid nymph
#

Wait does init_missing_hook just modifying a dict to have __missing__

rugged sparrow
#

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

viscid nymph
#

What does id(x) + 8 mean

rugged sparrow
#

@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

stark fable
rugged sparrow
#

@viscid nymph that is the offset for the object x's type

stark fable
#

which iirc is the address of its type...?

rugged sparrow
#

^ it is

viscid nymph
red wasp
#

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
dark solar
#

would here be the right place to discuss a language based on python using exclusively graphs as input and output?

rugged sparrow
#

@red wasp this is not the place for that question

#

@dark solar maybe, what is the language?

dark solar
#

It isn't its just a fun idea I had

snow beacon
#

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.

hard spoke
#

it's certainly fit for offtopic, not sure about the others

dusk root
#

Do someone have thing that could turn python 3x code to one-line?

fossil estuary
#

I do

dusk root
fossil estuary
#

I'll dm it

dusk root
#

Ok

tribal moon
#

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/
#

!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'])

night quarryBOT
#

@tribal moon :white_check_mark: Your eval job has completed with return code 0.

20
rugged sparrow
#

it doesnt support 3x @tribal moon

tribal moon
#

which part

rugged sparrow
#

any syntax added in 3x

tribal moon
#

damn they need to update that

floral meteor
#
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.

viscid nymph
#

why not just return setattr(f,'__code__',b(n))or f ๐Ÿ˜ฉ

floral meteor
#

huh true

#

looks much better

tired jungle
#

are you familiar with the else statement in while and for loops?

snow beacon
#

There's one in try as well.

floral meteor
#
#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

night quarryBOT
#
**PEP 3150 - Statement local namespaces (aka "given" clause)**
Status

Deferred

Python-Version

3.4

Created

09-Jul-2010

Type

Standards Track

floral meteor
#

pep 3150 is deferred last i checked :>

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

69
viscid nymph
#

๐Ÿ‘€

floral meteor
#

!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

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

420
floral meteor
#

@viscid nymph you like it?

viscid nymph
#

Why is n a a class though lol

floral meteor
#

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

viscid nymph
#

Might as well def n(): return "69"

floral meteor
#

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)

night quarryBOT
#

@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
floral meteor
#

huh

viscid nymph
#

Return

#

Or something

#

But yeah a doesn't return anything

floral meteor
#

XD

#

!e ```py
a=lambda:lambda:lambda:lambda:lambda:lambda f: f()
@a()()()()()
def b():print (69)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

69
floral meteor
#

!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')

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 69.

Now I am become Dev, Helloer of Worlds!
snow beacon
floral meteor
#

It's a nerd chuck-off at the quote

Now I am become Death, Destroyer of Worlds!
snow beacon
#

I know, but I wondered if the variation was a thing before you said it.

floral meteor
#

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.

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

~ ~ ~ ~ ~  ~ ~ ~ ~ ~!
floral meteor
#

lmfao

#

it doesn't error :/

#

but whytf is it squiggles?

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

~~~~~~~~~~~~[, , , , , , , , , , , ]
floral meteor
#

lmfao thats even worse

#

I have created an abomination

snow beacon
#

It's because it only resolves this after the loop.

floral meteor
#

interesting, cos it still assigns it to every printable ascii character in globals

snow beacon
#

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.

floral meteor
#

ik

snow beacon
#

Try printing this after the update.

floral meteor
#

but it creates and instantiates the type with the current iteration of this

snow beacon
#

There are two references to this.

viscid nymph
#

Me wondering where this was defined

snow beacon
#

One is in the dictionary key, resolved immediately. The other in the lambda, resolved when you print.

floral meteor
#

but this is not defined

snow beacon
#

Interesting, but the point remains.

viscid nymph
#

Wait nvm I'm just dumb

snow beacon
#

(Testing can go in #bot-commands by the way.)

floral meteor
#

!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()['!']])

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

Hello World!
floral meteor
#

XD

#

if only changes to globals affected literals.

#

like numbers

floral meteor
#

!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([...])
night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).

Hello World!
floral meteor
#

wait that means i can edit globals dict

rugged sparrow
#

@floral meteor yea thats what i did with my init_missing_hook

floral meteor
#

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)

night quarryBOT
#

@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'
floral meteor
#

why is the module a string object?

#

ooh

rugged sparrow
#

__missing__ is called for anything located in __builtins__

floral meteor
#

oh

#

now what?

rugged sparrow
#

n doesnt exist at all

floral meteor
#

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='!')

rugged sparrow
#

also messing with the globals dict has some funky requirements to stop segfaulting

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).

Hello World!
rugged sparrow
#

you need to unhook before the interpreter closes

floral meteor
#

lol

#

not happening XDDDDDDDDDDDD

night quarryBOT
#

@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
floral meteor
#

i borke it already

#

XD

rugged sparrow
#

no point

floral meteor
#

that's right, there's no point in doing this...

#

there should be a point to return floats XD

rugged sparrow
#

add it

floral meteor
#

I should move my cursedutils module to a repository

#

I'm lazy how do i do this again?

rugged sparrow
#

github?

floral meteor
#

ye

rugged sparrow
#

google a tutorial lol

floral meteor
#

!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)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

103542
floral meteor
#

!e print(import('sys').version)

night quarryBOT
#

@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]
dusk root
# tribal moon onelinerizer

Sorry for very late answer but it already found this and it is what I want but it doesn't work with Python 3x

broken mesa
broken mesa
#

alas, i am too busy with too many other things and projects

viscid nymph
spring rose
#

can we resize pixels in pygame

#

??????????????????????????????????????????////

viscid nymph
#

not here

rugged sparrow
#

@viscid nymph its a dunder

#

if the name exists in a classes scope, its assigned to the class

viscid nymph
#

Oh I didn't know you can access class attributes in methods

rugged sparrow
#

its not a class attribute in this case

viscid nymph
#

Oh I see

rugged sparrow
#

__class__ is used by super

astral rover
#

Isn't it a property

rugged sparrow
#

It is, but in this case it is a magic variable filled by the compiler

fluid tree
#

It's a cellvar (closure) from the class scope