#esoteric-python
1 messages · Page 125 of 1
if you want to see what an instruction does go into ceval.c and ctrl+f the name of the instruction
still not working in my case
rip
for globals()["var"] in (5,):...
print(var)
```You've been defining variables wrong
oh an idea: could use the c __FILE__ and __LINE__ macros for some extra info
is it a macro? if so what does the current macro look like
as in the way assert is being replaced
!e ```py
Py_TPFLAGS_VALID_VERSION_TAG = 1 << 19
Py_TPFLAGS_HEAPTYPE = 1 << 9
def sizeof(obj):
return type(obj).sizeof(obj)
def getmem(addr, size, fmt='c'):
from ctypes import c_char
return memoryview((c_char * size).from_address(addr))
.cast('c')
.cast(fmt)
def PyType_Modified(cls):
cls_mem = getmem(id(cls), sizeof(cls), 'L')
orig = cls.flags
flag_offset = cls_mem.tolist().index(orig)
if not cls.flags & (1 << 19):
return
for subcls in cls.subclasses():
PyType_Modified(subcls)
cls_mem[flag_offset] &= ~(1 << 19)
def alloc(size, _storage=[]):
mem = bytes(size)
_storage.append(mem)
return id(mem) + bytes.basicsize - 1
def get_structs(structs=[]):
if structs:
return structs
class htc:
slots = ()
offsets = []
for idx, ptr in enumerate(getmem(id(htc), sizeof(htc), 'L')):
if id(htc) < ptr < id(htc) + sizeof(htc):
offsets.append((idx, ptr))
last = None
for idx, ptr in sorted(offsets, key=lambda i:i[1]):
if last:
offset, lp = last
structs.append((offset, ptr - lp))
last = idx, ptr
return structs
def hook(cls, name=None, attr=None):
def wrapper(attr):
cls_mem = getmem(id(cls), sizeof(cls), 'L')
for offset, size in get_structs():
if not cls_mem[offset]:
cls_mem[offset] = alloc(size)
orig = cls.flags
flag_offset = cls_mem.tolist().index(orig)
cls_mem[flag_offset] = orig | (1 << 9)
try:
setattr(cls, name or attr.name, attr)
finally:
cls_mem[flag_offset] = orig
PyType_Modified(cls)
return attr
if attr is None:
return wrapper
else:
return wrapper(attr)
@hook(int)
def matmul(self, other):
return self, other
print(1 @ 2)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
(1, 2)
@golden finch ^ smaller implementation for hooking builtin classes
thank you
it uses a method i discovered after i wrote fishhook
@pastel ibex you may find this interesting ^
@pure dew ^ you too
hmmm
its a @hook implementation in less then 65 lines
do you actually need to do all this or is this code just written for flexibility
get_structs is needed for the code to work on multiple python versions (you could hardcode it if you only care about one)
almost all other code is needed for any hook to be stable
oh okay
you could also inline the functions but that would be clunky
please tell me you changed plus to @ and thats not some weird crap idk about
wait i just saw the eval now im even more confused
i think numpy uses it
ahh
but anyway yeah ill save this then once i understand the fish hook code ill look at that
also i was busy so im about where i left off 2.5ish hours ago
ya this implementation uses a different method then fishhook does
simpler but has some very small differences
Brilliant. Now do it again without ctypes.
this implementation makes it easy to swap out with a LOAD_* hack
just replace getmem
eval
?
along with my smallest LOAD_CONST implementation yet
Brilliant. I can't think of any other challenges.
These is my base
As you were told, this is the wrong channel @zinc wagon
For help with Python you should claim a help channel (as per #❓|how-to-get-help)
okay sry
my guess is that this is a bug with co_lnotab - what happens if you change that?
What can I do with ctypes.py_object.from_address?
WHOA! You can do that with python (so if i want smth like a $ b = (a + b)(a - 2b) I can do that with python?)
i have no idea what any of that code says so yea
You might be able to do it with @.
the bit you need to worry about is the last 5 lines
Anyone have some nice part-Python polyglots lying around?
It's prob an issue with the co_lnotab
I have one that does exactly the same thing in brainfuck
Just scroll up a lot
what in the world is a polyglot?
A program that can be run in more than one language.
(Or a person who can speak multiple languages.)
programming languages or actual languages
Programming languages.
I can't find it 
Though for my purposes I'd then need a bf console command 
search the channel for polyglot and from me
Do you mean this?
ooh
It works
```
Fatal error's py/bf polyglot
-
Python
-------------------------- output --------------------------
69 -
Brainfuck
-------------------------- output --------------------------
69
2/2 programs successfully run!
2/2 had the exact same stdout!
------------------------------------------------------------------------------------------```
I have a thing that can run multiple languages from one file so the original looks like https://paste.pythondiscord.com/eritenorur
crashing when a function stops running and there's still stuff on the stack?
wow
now catch it
I wonder if you could make fuckitpy at the bytecode level
woah
from random import shuffle as __eq__;__builtins__.globals()['__import__']=__import__('sys')
globals()['وٹرجتٹ']=([*__builtins__.globals().items()][~1|1**1][(10^11)<<0].stdout); globals()['']=[72,101,108,108,111,32,87,111,114,108,100,33]
while(not not not not not not not not bool()-16777216*10101011):
__eq__(__builtins__.globals()['']); __builtins__.globals()['وٹرجتٹ'].write(''.join([chr(i) for i in (globals()['']+[13])]));
if(''.join([chr(i) for i in (globals()[''])]).__eq__('Hello World!')):
print=__import__('sys');
__eq__=print.stdout.write('\n') if(print.stdout.writable()) else(__eq__); raise(SystemExit);
thoughts? first esoteric program ive made
i agree
makes it harder to figure out whats the truthiness
what about you catch everything humanly possible
@sick hound what's your goal?
its much more stable to just modify the base object type
BaseException
mhm
!e ```py
try:raise KeyboardInterrupt(69)
except BaseException as e:print(e)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
can't you just do except Exception as e?
also, that won't catch segfaults, right?
if you wanna catch segfault, use signal
!e ```py
def doot(whatever):
print("Hello World!")
return 0
from signal import
from ctypes import*
signal(11,doot)
string_at(0)
@floral meteor :warning: Your eval job timed out or ran out of memory.
[No output]
rood
!e ```py
def doot(whatever):
print("Hello World!")
return 0
from signal import
from ctypes import*
signal(11,doot)
py_object.from_address(0)
@floral meteor :warning: Your eval job has completed with return code 0.
[No output]
it just hangs
!e ```py
import('signal').signal(11,lambda*a:69)
import('ctypes').py_object.from_address(69)
@floral meteor :warning: Your eval job has completed with return code 0.
[No output]
bruh
Python Code Golf Calculator:
while True: print(exec(input("Input math problem here: ")))```
you want eval not exec
and there's an unecessary space
after the colon
i=input
while 1:i(eval(i("math>")))
now make it more complicated
someone wanted a brainfuck console? ```py
from collections import*
=()==[]
__=[defaultdict(int),,,]
@lambda :()
class :
=not _
=lambda _0,_1:_1[[0.<<0.]]
@property
def ():return __[][[not ]]
@.setter
def (, ____):[_][[not ]]=___
def 0():
.+=not _
.%=.<<8
return _
def 1():
.-=not _
.%=.<<8
return _
def 2():
[not ]-=not _
return _
def 3():
[not ]+=not _
return _
def 4():
print(end=chr(.))
return _
def _5():
import sys as __
.=ord(.stdin.read(.))
return _
def 6():
return+. if . else _
def 7():
return _ if . else-.
def 1(0):
while _<=[.<<.]<len(_0):
if [-.]:[-.]+=(.(0)=='[')-(.(0)==']')
else:[-.]=[0,1,2,3,4,5,6,7,lambda:]'+-<>.,[]'.find(_.(_0))
[.<<.]+=.-([-.]<)
return~~(not [.<<_.])
def __2():
_3=
while not __3:__3=1(input('|'))
god I love this channel
alright this looks new
what are the property and classname.setter decorators?
property is for adding getter functions and setter functions to attributes of an object.
How do that?
To quote the docstring:
'''
Property attribute.
fget
function to be used for getting an attribute value
fset
function to be used for setting an attribute value
fdel
function to be used for del'ing an attribute
doc
docstring
Typical use is to define a managed attribute x:
'''
class C(object):
def getx(self): return self._x
def setx(self, value): self._x = value
def delx(self): del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
# Decorators make defining new properties or modifying existing ones easy:
class C(object):
@property
def x(self):
"I am the 'x' property."
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
Uh huh - so what's the use of that?
Also, what's the difference between a property and attribute?
Properties are attributes that have special functions for getting and setting.
Not exactly. There are up to three methods.
so do you have some examples of further usage?
In [1]: class Foo:
...: def __init__(self, x):
...: self.__x = x
...: @property
...: def x(self):
...: return self.__x
...: @x.setter
...: def x(self, value):
...: if value < 0:
...: raise ValueError("Must be positive")
...: self.__x = value
...:
In [2]: bar = Foo(100)
In [3]: bar.x
Out[3]: 100
In [4]: bar.x = 200
In [5]: bar.x
Out[5]: 200
In [6]: bar.x = -1
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-6-ae603ede9ab2> in <module>
----> 1 bar.x = -1
<ipython-input-1-0c6fcdea6a56> in x(self, value)
8 def x(self, value):
9 if value < 0:
---> 10 raise ValueError("Must be positive")
11 self.__x = value
12
ValueError: Must be positive
Here's a class that doesn't let you set x to be negative.
A nicer version might just clamp the value of x at zero. You can write whatever code you want. It's common in object-oriented programming.
huh
cool
So how does the @property decorator work?
After all, since property appears to be a callable, it takes arguments
Does it replace x with a property object? If so, that's evil
On investigation, I think I get it.
@sick hound catch all errors, I dare you
anything that throws an arror in cpython must be caught
yes
Will python 3.11 be for python for workgroups?
is there a shorter way to convert a func return as True -> True and False -> -1 than func()or-1?
4 chars is pretty good but wondering if I'm missing some obvious bitwise trick
I can brute-force it if you'd like
!e ```py
def load_addr(a):
m = lambda n:lambda:n
m.code = (M:=m.code).replace(
co_consts=(c:=M.co_consts)+(r:=iter(range(a+1)),),
co_code=M.co_code.replace(b'\x87\0',bytes([100,len(c)])),
)
return r.setstate(a) or m(0)()
print(load_addr(id(1)))```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1
voodoo magic
its my smallest arbitrary address loader yet
and it doesnt need to know about pointer sizes or endianness
I'm curious about how this works
so the core of it is abusing LOAD_DEREF
never heard of that opcode
its used when you have nested functions and the inner function has a variable from the upper one
python passes a tuple of cell objects into the inner function when running the bytecode of the outer function
mhm
the code above changes the LOAD_CLOSURE to a LOAD_CONST that loads a range_iterator instead of a cell
this means that when the inner function tries to retrieve cell.cell_contents (cell + 8) (the first pointer on cell) it instead tries to load range_iterator.index (range_iterator + 8)
so i use __setstate__ to set index to the address a and call the inner function
mhm
i just had another idea one sec
vaguely understanding this
lemme add offsets into my description
!e ```py
m = lambda n:lambda v:r.setstate(v)or n
m.code = (M:=m.code).replace(
co_consts=(c:=M.co_consts)+(r:=iter(range(2**63-1)),),
co_code=M.co_code.replace(b'\x87\0',bytes([100,len(c)])),
)
load_addr = m(0)
print(load_addr(id(1)))```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1
@golden finch i made it worse
basically, m makes a function that refers to its own fake closure
so the returned function calls __setstate__ to set the address, then loads n (LOAD_DEREF) which reads from the range iterator
I brute-forced all of the 4-byters and got:
func()*2-1
func()-1|1
func()or-1
func()or~0
will try 3-byters now
!e ```py
r = iter(range(2**63-1)),
m = lambda n:lambda v,r=r[0]:r.setstate(v)or n
m.code = (M:=m.code).replace(
co_consts=(c:=M.co_consts)+r,
co_code=M.co_code.replace(b'\x87\0',bytes([100,len(c)])),
)
load_addr = m(0)
print(load_addr(id(1)))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1
no 3-byters exist
no 2-byters either
curiously all of them end in a number, and one does actually use ~, but only as a way of generating -1
this is literal black magic
Why do you have that iter()?
it makes my range_iterator object
yea it needs to be a range_iterator
Objects/rangeobject.c lines 767 to 773
typedef struct {
PyObject_HEAD
long index;
long start;
long step;
long len;
} rangeiterobject;```
^ __setstate__ on range_iterator objects lets me control index
class foo:
def __init__(self,value):
self.value=value
...
bar=foo()
bar=2#bar is still an instance of foo, but its .value is 2
bar=-1#don't change, or throw valueError
Include/cellobject.h lines 9 to 12
typedef struct {
PyObject_HEAD
PyObject *ob_ref; /* Content of the cell or NULL when empty */
} PyCellObject;```
you would need to do a lot of trickery
is it possible without bytecode manipulation?
@snow beacon i made a much smaller load_addr
no
well
maybe with a tracefunc
You can only use this command in the following channel(s): #878695047112040448, #878694844212592670, #878694948810137621, #878694991784972309, #476196062214750219, #310-release-stream
Firstly, wow. Secondly, wow.
!e ```py
m = lambda n,s:lambda v:s(v)or n
load_addr = type(m)((M:=m.code).replace(
co_consts=(c:=M.co_consts)+(r:=iter(range(2**63-1)),),
co_code=M.co_code.replace(b'\x87\0',bytes([100,len(c)]),1),
),{})(0,r.setstate)
print(load_addr(id(1)))```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1
tracefunc?
!doc sys.settrace
sys.settrace(tracefunc)```
Set the system’s trace function, which allows you to implement a Python source code debugger in Python. The function is thread-specific; for a debugger to support multiple threads, it must register a trace function using [`settrace()`](https://docs.python.org/3.10/library/sys.html#sys.settrace "sys.settrace") for each thread being debugged or use [`threading.settrace()`](https://docs.python.org/3.10/library/threading.html#threading.settrace "threading.settrace").
Trace functions should have three arguments: *frame*, *event*, and *arg*. *frame* is the current stack frame. *event* is a string: `'call'`, `'line'`, `'return'`, `'exception'` or `'opcode'`. *arg* depends on the event type.
The trace function is invoked (with *event* set to `'call'`) whenever a new local scope is entered; it should return a reference to a local trace function to be used for the new scope, or `None` if the scope shouldn’t be traced.
Uh huh - now I'm not sure what do do with that
interesting
welp idle broke
so what should the trace function return?
it says "a local trace function" - can it return itself?
yes, apparently
!e Just a dash of golfing.```py
load_addr=type(m:=lambda n,s:lambda v:s(v)or n)((M:=m.code).replace(co_code=M.co_code.replace(b'\x87\0',bytes([100,len(c:=M.co_consts)]),1),co_consts=c+(r:=iter(range(2**63-1)),)),{})(0,r.setstate)
print(load_addr(id(1)))
@snow beacon :white_check_mark: Your eval job has completed with return code 0.
1
it also breaks idle for reads I don't understand
What's your trace function?
def recurse(frame,event,arg):
print(frame,event,arg)
return recurse
nice
when i was hacking that together i found a bug in cpython that im now fixing lol
range_iterator.__reduce__ returned a wrong value
I try to type print(2) in idle and after I type the left parenthesis it hangs (not responding)
I think it's something to do with scope. Maybe try:```py
f = lambda f: lambda frame, event, arg: print(frame, event, arg) or f(f)
recurse = f(f)
hmm???
File ???, line 84 in ??? ? In the shell, isn't it a <input>? And most recent call first? It's last?
!e ```py
i=iter(range(263-1))
i.setstate(260)
print(i.reduce()[-1], 2**60) # these should be equal
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
0 1152921504606846976
msvcrt has such a convenient way of directly getting keyboard input.
How do you emulate getch with curses?
It might be useful to ask in one of the help channels.
@floral meteor its possible to change the terminal settings to make stdin.read(1) function the same way
Now that's something I'd like to implement in an esoteric interface
https://stackoverflow.com/questions/2408560/non-blocking-console-input take a look at this
pygame documentation just told me get rect
I just thoroughly got rect by this documentation
!e ```py
int_ = int
int = lambda x: sum(map(int_, str(x).replace("-", "")))
print(int(6))
print(int(598))
@lime bane :white_check_mark: Your eval job has completed with return code 0.
001 | 6
002 | 22
!e segfault free cursed python behaviour ```py
from ctypes import*;n=5;
import builtins as builtins
@lambda c:c()
class annotations(dict):
def setitem(self, item, value):
builtins.dict.update(globals(),{item:value})
class globals(dict):
def missing(self, key):
return builtins.dict.get(key,None)
def setitem(self, name, value):
annotations.update({name:value})
victim = py_object.from_address(id(globals())+8)
victim.value,flogbals=globals,victim.value
n = 2 + 2
print(n)
b: 69 = int
print(b, annotations['b'])
victim.value=dict
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 5
002 | 69 <class 'int'>
@lambda c:c()
I invented that
a long time ago
for when I want the custom object, not the custom class
will follow up with working script
!e ```py
from ctypes import*
import builtins as builtins
class flogbals(dict):
cls_reg=[]
partial={}
done=set()
def missing(self, key):
return builtins.dict.get(key,None)
def setitem(referencing_this_will_segfault, name, value):
if name in flogbals.partial:
a=flogbals.partial.pop(name)
flogbals.done.add(name)
dict.update(globals(),{name:a(value)})
elif name in flogbals.done:
py_object.from_address(id(globals())+8).value=dict
raise ValueError(name)
elif type(value)is type:
flogbals.cls_reg+=[value]
dict.update(globals(),{name:lambda:value})
elif value in flogbals.cls_reg:
flogbals.partial[name]=value
dict.update(globals(),{name:type('',(),{'repr':lambda s:flogbals.cls_reg[name].name+'()'})()})
else:dict.update(globals(),{name:value})
py_object.from_address(id(globals())+8).value=flogbals
class foo:
def init(self,value):
self.value=value
...
bar=foo()
bar=2#bar is still an instance of foo, but its .value is 2
print(bar.value)
bar=-1#don't change, or throw valueError
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | Traceback (most recent call last):
002 | File "<string>", line 34, in <module>
003 | AttributeError: 'int' object has no attribute 'value'
eh bugger it i need sleep
!e
from ctypes import*
import builtins as __builtins__
class flogbals(dict):
cls_reg=[]
partial={}
done=set()
def __missing__(self, key):
return __builtins__.__dict__.get(key,None)
def __setitem__(referencing_this_will_segfault, name, value):
if name in flogbals.partial:
a=flogbals.partial.pop(name)
flogbals.done.add(name)
dict.update(globals(),{name:a(value)})
elif name in flogbals.done:
py_object.from_address(id(globals())+8).value=dict
raise ValueError(name)
elif type(value)is type:
flogbals.cls_reg+=[value]
dict.update(globals(),{name:lambda:value})
elif value in flogbals.cls_reg:
flogbals.partial[name]=value
dict.update(globals(),{name:type('',(),{'__repr__':lambda s:flogbals.cls_reg[name].__name__+'()'})()})
else:dict.update(globals(),{name:value})
py_object.from_address(id(globals())+8).value=flogbals
class foo:
def __init__(self,value):
self.value=value
...
bar=foo()
bar.value=2#bar is still an instance of foo, but its .value is 2
print(bar.value)
bar.value=-1#don't change, or throw valueError
@rich hound :x: Your eval job has completed with return code 139 (SIGSEGV).
2
ty
np
im just in a war with my own creation rn
you assigned bar to an int, and not the value
what did you do
if this isnt evidence of machine intelligence, i dont know what is
i told it to recover from a stack overflow inducing script so it rolled back to before i made the abort function
"permission level" how many are there
how does that even happen
0:everyone
1:admin
2:dev
3 is owner i assume
and 2 aswell?
00 everyone
01 admin
10 dev
11 dev and admin
oh
@command(2)
async def restart(message):
__import__("os").system("python ."),exit(0)
@command(2)
async def abort(message):
if message.channel.last_message.author!=message.guild.me:
await message.channel.send("Attempting to recover from: SIGTERM")
__import__('ctypes').py_object.from_address(69).value=420
custom command decorator, i like it
ty ;)
can i see how it works?
>>> eval
<built-in function eval>
>>> @command(2)
... async def eval(message):
... ...
...
>>> eval
<built-in function eval>
>>> COMMANDS['eval']
<coroutine eval at 0xf84098b0cd09823>
powered by an invention i call the hack_wrapper
interesting
which uses frame inspection to prevent namespace pollution
i dont understand what that means but ill listen still
def _missing(_s,k):
def missing(message,*_options,flags=0):
return message.channel.send(f"Unknown command `{k}` for permission level {flags}")
return missing
COMMANDS=type('defaultdict',(dict,),{'__missing__':_missing})()
def command(_flags:int):
def wrapper(af):
async def inner(message, *options, flags:int=0):
if flags<_flags:return await message.channel.send('ACCESS DENIED')
else:return await af(message, *options)
COMMANDS[af.__name__] = inner
return hack_wrapper(1)(af)
return wrapper
seems small
there's also a simplified version that passes the flags to the function
def _command(af):
COMMANDS[af.__name__] = af
return hack_wrapper(1)(af)
def hack_wrapper(n):
import sys
fl = sys._getframe(n+1).f_locals
fg = sys._getframe(n+1).f_globals
fb = __import__('builtins').__dict__
return lambda f:fl.get(f.__name__,fg.get(f.__name__,fb.get(f.__name__,None)))
thats complicated.
alternatively, ```py
def hack_wrapper(n):
from sys import _getframe
frame=_getframe(n+1)
fl = frame.f_locals
fg = frame.f_globals
fb = frame.f_builtins
return lambda f:fl.get(f.name,fg.get(f.name,fb.get(f.name,None)))
what is _getframe
frame inspection
show an example?
!e ```py
a=4
try:raise
except Exception as e:print(e.traceback.tb_frame.f_globals['a'])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
4
globals()['a']
oh bruh
!e ```py
from ctypes import*
py_object.from_address(id(2)+1).value = 1
print(2)
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
what even is a segfault 
load_addr = type(m:=lambda n,s:lambda v:s(v)or n)(
(M:=m.__code__).replace(
co_code=M.co_code.replace(b'\x87',b'\x88',1)
),{}
)(r:=iter(range(2**63-1)),r.__setstate__)``` @floral meteor even smaller now
@rich hound a segfault is when you attempt to read from/ write to memory that your process does not own
oh
thanks
np
Hey @sick hound!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
w h a t
I don't know what it does with enhanced, but ?
no
it has a few extra lines
Lol
wait you changed the driver code not the preprocessing
the point is to change the preprocessing to make the driver code work
what
you did
bar=foo()
bar**.value**=2#bar is still an instance of foo, but its .value is 2
print(bar.value)
bar.value=-1#don't change, or throw valueError
The initial specs were
class foo:
def __init__(self,value):
self.value=value
...
bar=foo()
bar=2#bar is still an instance of foo, but its .value is 2
bar=-1#don't change, or throw valueError
plus, you segfaulted and bar got set to -1
so this is harder than thought?
is this a reimplementation of globals?
they edited it to look like it worked but they edited the driver not the preprocessing, so the original is...
here
alright I'll try and work out what this does
it tells globals there's special cases, and it has a state of having a value, being a "partially instantiated object", but being the actual class, not nested in a lambda
mhmmm
I am very confused
>>> __import__('ctypes').py_object.from_address(id(globals())+8).value=type('',(dict,),{'__setitem__':lambda a,b,c:print(b,c)})
>>> a=2
a 2
>>> a
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
a
NameError: name 'a' is not defined
managed to implement it this far
why it has to be a class, I don't know
so it's best to start with a full class statement
and then you make cases for variable types
if its a type object, make it lambda:thatobject
i.e. use dict.update(globals(),{b:c}) to prevent segfault
and implement missing with normal builtins access behaviour to prevent stack overflow or recursionerror
alright - so... making come sense here
How would I go about __missing__?
also, by type object you just mean anything that is a subclass of type?
k
!eval
load_addr = type(m:=lambda n,s:lambda v:s(v)or n)(
(M:=m.__code__).replace(
co_code=M.co_code.replace(b'\x87',b'\x88',1)
),{}
)(r:=iter(range(2**63-1)),r.__setstate__
@olive rose :x: Your eval job has completed with return code 1.
001 | File "<string>", line 5
002 | )(r:=iter(range(2**63-1)),r.__setstate__
003 | ^
004 | SyntaxError: unexpected EOF while parsing
!eval
def hack_wrapper(n):
from sys import _getframe
frame=_getframe(n+1)
fl = frame.f_locals
fg = frame.f_globals
fb = frame.f_builtins
return lambda f:fl.get(f.__name__,fg.get(f.__name__,fb.get(f.__name__,None)))
hack_wrapper(1503)
hashable dicts yayyyyy
I'm not sure what to think about this use of my hack_wrapper decorator.
alright here's a juicy excercise.
if i can do it youse can do it
chop an error in half
like this
gl
p.s. i'll give you a clue, the last line of my code was XD and the code was three lines
This is esoteric python, the number of lines means nothing haha
and the longest line was 39 characters
hahahahah
39 not 38 sorry
!e print(19+1+39+1+2)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
62
ok do it in less than 62 characters
def function(python_str):
def anon():
return eval(python_str)
return anon
you noobs figured it out yet?
raise an error where the class __repr__ halts execution
or, probably, hooking into NameError
@sonic ginkgo
ns.py
#define NS_BEGIN(name) __import__("builtins").__ns_globals__ = globals().copy(); globals().clear(); __ns_name__ = #name ;
#define NS_END __ns__=__import__("types").SimpleNamespace(**{k: v for k, v in globals().items() if k != "__ns_name__"}); __import__("builtins").__ns_globals__[__ns_name__]=__ns__; globals().clear(); globals().update(__import__("builtins").__ns_globals__)
#include "ns.py"
NS_BEGIN(foo)
x = 1
y = 2
z = 3
NS_END
print(foo)
gcc -E -x c main.py > temp.py && python3 temp.py
``` output: ```
namespace(x=1, y=2, z=3)
i hate this channel

😆
that's pretty impressive, i have no idea how it works
this is... python syntax in a C macro?
might as well use GPP https://logological.org/gpp
It expands into (minus ;s)
#include "ns.py"
__import__("builtins").__ns_globals__ = globals().copy()
globals().clear()
__ns_name__ = "foo"
x = 1
y = 2
z = 3
__ns__=__import__("types").SimpleNamespace(**{k: v for k, v in globals().items() if k != "__ns_name__"})
__import__("builtins").__ns_globals__[__ns_name__]=__ns__
globals().clear()
globals().update(__import__("builtins").__ns_globals__)
print(foo)
yeah
but the command will look less scary
gotta make it scary
it uses builtins as a stash because I clear globals
wait, I can make it better
I don't need to use builtins, right
#define NS_BEGIN(name) __import__("ctypes").__ns_globals__ = globals().copy(); globals().clear(); __ns_name__ = #name ;
#define NS_END __ns__=__import__("types").SimpleNamespace(**{k: v for k, v in globals().items() if k != "__ns_name__"}); __import__("ctypes").__ns_globals__[__ns_name__]=__ns__; globals().clear(); globals().update(__import__("ctypes").__ns_globals__)
now it seems like I'm using ctypes!
it's also easy to confuse with just types
@formal sandal you could make a preprocess.py that runs gcc on the importing file to make it even more streamlined
I'll write up a demo later today
test_preprocess.py
import preprocess
#include "ns.py"
#define PRINT(name) print("output:", name)
NS_BEGIN(foo)
x = 1
y = 2
z = 3
NS_END
PRINT(foo)```
`python3 test_preprocess.py`
```py
output: namespace(x=1, y=2, z=3)``` @formal sandal
preprocess.py ```py
import sys, dis, subprocess
frame = sys._getframe()
while frame := frame.f_back:
f_code = frame.f_code
if f_code.co_code[frame.f_lasti] == dis.opmap['IMPORT_NAME']
and f_code.co_names[f_code.co_code[frame.f_lasti + 1]] == 'preprocess':
file = frame.f_globals['file']
if file:
processed = subprocess.run(['gcc', '-E','-x','c', file], stdout=subprocess.PIPE)
if processed.returncode == 0:
exec(processed.stdout.decode())
exit(processed.returncode)
^ this does introduce the requirement that all the gcc directives have to be parseable by python

i didnt want to bother writing an entire import hook so i just do some frame inspection to get the importing file
then i process it, exec it, and exit
Nice
You might notice the offending line of code is also omitted
from the error
And don't forget <= 62 characters
def gadget(n):
def f(*v):
nonlocal n
if v:
n = v[0]
else:
return n
return f
gadget.__code__ = (M:=gadget.__code__).replace(
co_code=b'\x88'+M.co_code[1:]
)
getclsdict = lambda cls:gadget(cls.__dict__)()
``` i wrote a gadget based off of closure type confusion. `gadget(obj)` can read or write the 3rd pointer on `obj`
how on earth does that work?
i swap op \x87 for \x88 so the inner function object now thinks that whatever is passed into gadget is a cell object
!e ```py
def gadget(n):
def f(*v):
nonlocal n
if v:
n = v[0]
else:
return n
return f
gadget.code = (M:=gadget.code).replace(
co_code=b'\x88'+M.co_code[1:]
)
print(gadget(1).closure)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
(1,)
what op codes are \x87 and \x88?
LOAD_CLOSURE and LOAD_DEREF respectively
@radiant anchor found some new bytecode bugs
i havent seen them talked about anywhere
the bytecodes are relatively new
load_addr = type(m:=lambda n,s:lambda v:s(v)or n)(
(M:=m.__code__).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(r:=iter(range(2**63-1)),r.__setstate__)``` my new `load_addr` function
very concise
yea it abuses range_iterators internal structure
why does it need to be the max size for a range_iterator?
because i need to be able to set the range iterators index to any valid address
max size ensures i have the most space
oh so thats the max size of an id() call?
its the max for an 8byte unsigned value
do you have a less one-liner-y version? kinda hard to follow with the lambdas etc
!e ```py
def gadget(n):
def f(*v):
nonlocal n
if v:
n = v[0]
else:
return n
return f
gadget.code = (M:=gadget.code).replace(
co_code=b'\x88'+M.co_code[1:]
)
def load_addr(address):
magic_iter = iter(range(2**63-1))
magic_iter.setstate(address)
return gadget(magic_iter)()
print(load_addr(id(1)))```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1
since load_addr only reads you could just have def f():return n
!e ```py
import dis
def gadget(n):
def f(*v):
nonlocal n
if v:
n = v[0]
else:
return n
return f
gadget.code = (M:=gadget.code).replace(
co_code=b'\x88'+M.co_code[1:]
)
dis.dis(gadget)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 3 0 LOAD_DEREF 0 (n)
002 | 2 BUILD_TUPLE 1
003 | 4 LOAD_CONST 1 (<code object f at 0x7f64991bc9d0, file "<string>", line 3>)
004 | 6 LOAD_CONST 2 ('gadget.<locals>.f')
005 | 8 MAKE_FUNCTION 8 (closure)
006 | 10 STORE_FAST 1 (f)
007 |
008 | 9 12 LOAD_FAST 1 (f)
009 | 14 RETURN_VALUE
010 |
011 | Disassembly of <code object f at 0x7f64991bc9d0, file "<string>", line 3>:
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/bututurebu.txt?noredirect
@radiant anchor it swaps a LOAD_CLOSURE for a LOAD_DEREF. this makes MAKE_FUNCTION construct a function with an arbitrary object as the closure instead of a cell
neat
so when f calls LOAD_DEREF(n) it is actually reading the 3rd pointer of n
im messing with gadget right now because slot_wrappers store their type at the 3rd pointer so i can change that type and call different slot_wrappers on other types
>>> gadget(list.__setitem__)(tuple)
>>> x = (0,)
>>> list.__setitem__((x,0,1,2), 3, x)
>>> x
((...),)
>>> gadget(list.__setitem__)(list)
>>> ```
This is the second or so time I've used a pattern like this, does this pattern have a well known or is it just called something obvious like a 'class decorator' or whatever?
def UniqueStyle(ttk_class, root_style=None):
"""Used to create a unique substyle for every instance of a ttk class,
the superstyle can still be modified to broadcast changes to all substyles,
but the substyles can now be changed without affecting the main style.
"""
def getrootstyle(ttk_class):
if tk._default_root:
dont_destroy_root=True
root = tk._default_root
else:
dont_destroy_root=False
root = tk.Tk()
s = ttk_class(root)
ret = s.winfo_class()
s.destroy()
if not dont_destroy_root:
root.destroy()
return ret
if not root_style:
root_style = getrootstyle(ttk_class)
index = [0]
class UniqueStyle_helperclass(ttk_class):
def __init__(self, master, *a, **k):
index[0] += 1
_style_name = f'UniqueStyle{index[0]}.{root_style}'
super().__init__(master, *a, style=_style_name, **k)
self._style = ttk.Style(self)
self._style_name = _style_name
def style_configure(self, query_option=None, **kw):
return self._style.configure(self._style_name, query_option, **kw)
UniqueStyle_helperclass.__name__ = f'UniqueStyle_{ttk_class.__name__}'
return UniqueStyle_helperclass```
guys pls sorry for my ignorance, but what's esoteric-python? Are you guys trying to invoke hell in earth? 🤣
yes
@floral meteor do you have a minimal reproduction of globals that doesn't inherit from dict?
Previous stuff like builtins would have to be stored in the custom class and a new dataclass made to store the global means it's like moving house: chaotic and traumatic, you have to clean up perfectly, you have to redirect all the mail, you have to package everything and actually move it there, you're living in a local namespace until you've moved everything over, etc..
a reproduction merely means reinventing the wheel and making my own interpretation of dict so that globals works
It would be far less optimised
It might involve sets of two-tuples, the formal notation for a dictionary
A non dict override with custom behavior is easy enough, just one catch: you cannot reference self
once i figure out how python loads literals, I will do some truly evil things in python.
i think it was instruction 74...
duptop and that dot-join every two bytes of bytecode would make an elegant debug wrapper
You mean LOAD_CONST?
literals, not const
or is that it?
wait
LOAD_CONST would only do literals...
but that's after building the literal, it's already stored in the function code
but then i could replace that, and change the behaviour of load_const
so that instead of loading an integer, it would... overwrite the next instruction in the bytecode with the byte of that integer if its less than 256 of course
Any static literals are built by the compiler
so i cant corrupt them?
Not like that
ouch
so i'll have to play with already built ast then
well that's okay it shouldn't be too hard, then
just the number of stack values the instruction takes and gives has to be the same as building the literal
or i could just ignore the non-integer code and only parse the 'new' bytecode
but not rn im drunk
maybe i make esolang of just arbitrary integers
it probably gonna end up becoming machine language, only twisted and evil
and integers
so do i make it stack based, object oriented or neither?
the catch?
the python interpreter will be a decorator that takes all the integers from the function its decorating, not a string interpretation
actually its starting to sound like too much effort
alright here's a simpler project: swap all integers and strings
@radiant anchor figured out a way to use gadget so id is no longer needed to get addresses
!e ```py
allows for reading and writing the 3rd pointer of an object
def gadget(n):
def f(*v):
nonlocal n
if v:
n = v[0]
else:
return n
return f
gadget.code = (M:=gadget.code).replace(
co_code=b'\x88'+M.co_code[1:]
)
def cast(v, t1, t2, bufsize=tuple.itemsize):
conv = memoryview(bytearray(bufsize))
conv.cast(t1)[0] = v
return conv.cast(t2)[0]
def set_obj_at_addr(addr, obj):
# uses complex to build a list-like structure
gadget(list.setitem)(complex)
list.setitem(complex(
cast(1, 'l', 'd'),
cast(addr, 'l', 'd')
), 0, obj)
gadget(list.setitem)(list)
def get_obj_at_addr(addr):
# uses float as a cell-like structure
return gadget(cast(addr, 'l', 'd'))()
def addressof(obj):
# uses float as a cell-like structure
r = 0.0
gadget(r)(obj)
return cast(r, 'd', 'l')
print(get_obj_at_addr(addressof(1)))```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1
!e ```py
def func():
_00
_01
_02
_03
print(func.code.co_code)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
b't\x00\x01\x00t\x01\x01\x00t\x02\x01\x00t\x03\x01\x00d\x00S\x00'
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
{'POP_TOP': 1, 'ROT_TWO': 2, 'ROT_THREE': 3, 'DUP_TOP': 4, 'DUP_TOP_TWO': 5, 'ROT_FOUR': 6, 'NOP': 9, 'UNARY_POSITIVE': 10, 'UNARY_NEGATIVE': 11, 'UNARY_NOT': 12, 'UNARY_INVERT': 15, 'BINARY_MATRIX_MULTIPLY': 16, 'INPLACE_MATRIX_MULTIPLY': 17, 'BINARY_POWER': 19, 'BINARY_MULTIPLY': 20, 'BINARY_MODULO': 22, 'BINARY_ADD': 23, 'BINARY_SUBTRACT': 24, 'BINARY_SUBSCR': 25, 'BINARY_FLOOR_DIVIDE': 26, 'BINARY_TRUE_DIVIDE': 27, 'INPLACE_FLOOR_DIVIDE': 28, 'INPLACE_TRUE_DIVIDE': 29, 'RERAISE': 48, 'WITH_EXCEPT_START': 49, 'GET_AITER': 50, 'GET_ANEXT': 51, 'BEFORE_ASYNC_WITH': 52, 'END_ASYNC_FOR': 54, 'INPLACE_ADD': 55, 'INPLACE_SUBTRACT': 56, 'INPLACE_MULTIPLY': 57, 'INPLACE_MODULO': 59, 'STORE_SUBSCR': 60, 'DELETE_SUBSCR': 61, 'BINARY_LSHIFT': 62, 'BINARY_RSHIFT': 63, 'BINARY_AND': 64, 'BINARY_XOR': 65, 'BINARY_OR': 66, 'INPLACE_POWER': 67, 'GET_ITER': 68, 'GET_YIELD_FROM_ITER': 69, 'PRINT_EXPR': 70, 'LOAD_BUILD_CLASS': 71, 'YIELD_FROM': 72, 'GET_AWAITABLE': 73, 'LOAD_ASSERTION_ERROR': 74, 'INP
... (truncated - too long)
Full output: https://paste.pythondiscord.com/uhiraqibob.txt?noredirect
pop_top
!e py import dis print(dis.opname[1])
load_global pop_top
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
POP_TOP
so what does d do?
load const
0
return value
0
got it
i just manually disassembled a function
yea that tends to get added to all function co_code
!e ```py
def raw(f):
code = f.code
r = code.co_code.decode().iter()
a = []
try:
while 1:
this, that = next(r), next(r)
if this=='t':
name = code.co_names[ord(that)].removeprefix('_')
if name.isdigit():a+=[int(name)]
except StopIteration:...
return type(f)(code.replace(co_code=bytes(a)),{})
@raw
def main(a):
_70
_0
_100
_0
_83
_0
main(type('',(),{'repr':lambda s:'Hello World!'})())
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
gottim
ze ultimate obfusacation
@rugged sparrow do you like my latest evil creation?
It's clever
ty
!e ```py
def raw(f):
code = f.code
r = code.co_code.decode().iter()
a = []
try:
while 1:
this, that = next(r), next(r)
if this=='t':
name = code.co_names[ord(that)].removeprefix('_')
if name.isdigit():a+=[int(name)]
except StopIteration:...
return type(f)(code.replace(co_code=bytes(a)),{})
@raw
def main(thought_crime):
_124
_0
_124
_0
_124
_0
_26
_0
_23
_0
_70
_0
_100
_0
_83
_0
main(2 + 2)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5
it's such an elegant obfuscation
!pypi hax
take a look at this ^
ooh nice
precompiled function ;)
they got a lot more lines in their code
awwwwww
i thought that was gonna work
!e ```py
def raw(f):
code = f.code
r = code.co_code.decode().iter()
a = []
try:
while 1:
this, that = next(r), next(r)
if this=='t':
name = code.co_names[ord(that)].removeprefix('_')
if name.isdigit():a+=[int(name)]
except StopIteration:...
return type(f)(code.replace(co_code=bytes(a)),{})
@raw
def main(thought_crime):
4
_124
_0
_124
_0
_100
_1
_26
_0
_23
_0
_70
_0
_100
_0
_83
_0
main(2 + 2)
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
WHY CANT I DIVIDE BY 4?
you removed the call to LOAD_CONST
!e
for i in range(1,int(input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also
exec('def k(x):\n x=x*2\n y=0\n j=0\n while j<x:\n y+=((10**(j))//9)-((10**(j//2))//9)\n j+=1\n print(y)\nk(i)')
@mystic epoch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
!e
for i in range(1,int(input())+1):
exec('def k(x):\n x=x*2\n y=0\n j=0\n while j<x:\n y+=((10(j))//9)-((10(j//2))//9)\n j+=1\n print(y)\nk(i)')```
@mystic epoch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
@mystic epoch and where do you think it is going to input from?
oh, yeah, it doesn't support input()
I thought i did that, there's two ds
i call d with 1 then d with 0
You can't get much more load_const than that
!e ```py
def raw(f):
code=f.code
r=code.co_code.decode().iter()
a=[]
try:
while 1:
this,that=next(r),next(r)
if that and this=='d':
num=code.co_consts[ord(that)]
if num is not None:a+=[*bytes(num)]
except StopIteration:...
return type(f)(code.replace(co_code=bytes(a)),{})
@raw
def dystopia(value):'|';0;'|';0;'|';0;26;0;23;0;70;0;'d';0;'S';0
dystopia(2+2)
@floral meteor :x: Your eval job has completed with return code 1.
001 | XXX lineno: 15, opcode: 0
002 | Traceback (most recent call last):
003 | File "<string>", line 17, in <module>
004 | File "<string>", line 15, in dystopia
005 | SystemError: unknown opcode
bruh
or are they?
Are they?
hello friends someone knows linear programming
In [47]: def g():
...: pass
...:
In [48]: type(g)
Out[48]: function
In [49]: functiontype = type(g)
In [50]: class DefaultMethod(functiontype, Enum):
...: ...
...:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-50-a53f56e93d0f> in <module>
----> 1 class DefaultMethod(functiontype, Enum):
2 ...
3
c:\program files\python39\lib\enum.py in __new__(metacls, cls, bases, classdict, **kwds)
212 classdict['__doc__'] = 'An enumeration.'
213
--> 214 enum_class = super().__new__(metacls, cls, bases, classdict, **kwds)
215 enum_class._member_names_ = [] # names in definition order
216 enum_class._member_map_ = {} # name->value map
TypeError: type 'function' is not an acceptable base type
enumerable functions --- help me out esoteric-python
I'm pretty sure you can overwrite it somehow with __builtins__.
Random flight-of-fancy...
I was thinking about reduce, and how when you reduce a collection of sets with the union operation, the initial value you start off with would be an empty set:
reduce(set.union, list_of_sets, set())
But if you were to reduce a collection of sets with the intersection operation, what would the initial value be? It would have to be the opposite of the empty set -- the set that contains everything.
But you can't make a set that contains everything in Python... or can you
Vsauce music starts playing
So I wrote this: https://paste.pythondiscord.com/kilefexite.py
Enjoy 😄
Interesting. What if you made a class that represents the complement of a set? If x in inner_set then x not in Complement(inner_set). That way the universal set is just Complement(set()).
Also I'd suggest raising NotImplementedError() for __iter__ and co.
Yeah, although I was thinking for difference and symmetric_difference I could create another class called EverythingExcept.
That would represent everything except for a finite set of values.
Why bother making two classes, when the universal set is a special case of EverythingExcept?
so the goal is to specifically perform a union of all sets with a fold, but using the intersection operation instead?
In regards to reduce, you can just omit the initial value, and it will start by calling the function on the first two items.
wont matter if the goal is to perform the same thing as a union fold with intersection instead
need a little more clarity on what the goal of reducing a collection of sets should be in this context.
That's just what gave me the idea to make an everything-set. Currently working on a Complement class.
ok so then just to be absolutely sure, passing {1, 2, 3} {2, 3, 4} {3, 4, 5} into this intersection based function should give {1, 2, 3, 4, 5} right? same as if it was using union?
and likewise for all the other operations?
Well you could do py reduce(set.intersection, [{1, 2, 3}, {2, 3, 4}, {3, 4, 5}]) and the answer would be {3}. You could also do py reduce(set.intersection, [{1, 2, 3}, {2, 3, 4}]) for which the answer would be {2, 3}. Or py reduce(set.intersection, [{1, 2, 3}]) for which the answer would be {1, 2, 3}. But what would the answer be for ```py
reduce(set.intersection, [])
oh ok, was thinking of a different problem
The question is effectively what is the identity element of the set-intersection monoid.
(An identity element of set intersection is an object I where the intersection of I and x is always x. If set intersection is a monoid, then it's associative, and the object I has to exist. Associativity means if you take the intersection of a bunch of sets, then it doesn't matter where you put the brackets; you always get the same result.)
@snow beacon New and improved, based on your suggestions: https://paste.pythondiscord.com/kecuyuduba.py
Might have got the logic wrong in a couple of places, not sure 
Should write tests, but nah.
I don't see any maths errors.
Now then, does the set of all sets which don't contain themselves contain itself?
woof
It's not even that scary today.
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello world!
What's the goal?
noice
disassemble it and find out
!e ```py
builtins.dict['build_class']=print
class A:
print('what')
a=4
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
<function A at 0x7f9cf5835040> A
!e ```py
builtins.dict['build_class']=lambda f,n:print(f.code.co_code)
class A:
print('what')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
b'e\x00Z\x01d\x00Z\x02e\x03d\x01\x83\x01\x01\x00d\x02S\x00'
!e ```py
from dis import dis
builtins.dict['build_class']=lambda f,n:dis(f)
class A:
print('what')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 3 0 LOAD_NAME 0 (__name__)
002 | 2 STORE_NAME 1 (__module__)
003 | 4 LOAD_CONST 0 ('A')
004 | 6 STORE_NAME 2 (__qualname__)
005 |
006 | 4 8 LOAD_NAME 3 (print)
007 | 10 LOAD_CONST 1 ('what')
008 | 12 CALL_FUNCTION 1
009 | 14 POP_TOP
010 | 16 LOAD_CONST 2 (None)
011 | 18 RETURN_VALUE
this dis library looks interesting
the "function" basically corresponding to the class body
Can this be constituted as esoteric:
from __future__ import annotations
@lambda c:c()
class __annotations__:
def __setitem__(self, name, value):
globals()[value] = globals()[name]
iㅤthink: twoㅤplusㅤtwo = 5
amㅤiㅤcorrect: no,ㅤtheㅤcalculatorㅤbegsㅤtoㅤdifferㅤitㅤsaysㅤtwoㅤplusㅤtwo = 4
yes but it shouldn't parse
it does parse
!e
from __future__ import annotations
@lambda c:c()
class __annotations__:
def __setitem__(self, name, value):
globals()[value] = globals()[name]
iㅤthink: twoㅤplusㅤtwo = 5
amㅤiㅤcorrect: noㅤtheㅤcalculatorㅤbegsㅤtoㅤdifferㅤitㅤsaysㅤtwoㅤplusㅤtwo = 4
wait
OH
that
@shut trail :warning: Your eval job has completed with return code 0.
[No output]
!charinfo iㅤthink
You are not allowed to use that command here. Please use the #bot-commands channel instead.
hangul, I see
Yep
is pointers in python impossible
in this channel nothing is impossible with enough creativity
weakref is a kind of a pointer
!e ```py
freevars = f->f_fastlocals + co->co_nlocals
this means if co->co_nlocals is 0, freevars points to the top of the stack
LOAD_DEREF(n - co_nlocals) pushes fastlocal[co_nlocals-n] as obj->cell_contents
LOAD_DEREF(n + co_nfreevars) pushes stack[n] as obj->cell_contents
LOAD_CLOSURE(n + co_nfreevars) pushes stack[n]
import dis
gadget = lambda v,*s:(v,v,v)
gadget.code = gadget.code.replace(co_code=bytes([
dis.opmap['LOAD_FAST'], 0, # 00: PUSH(fastlocals[0])
dis.opmap['LOAD_FAST'], 1, # 02: PUSH(fastlocals[1])
dis.opmap['JUMP_IF_TRUE_OR_POP'], 10, # 04: JUMPTO(10) if TOP() else POP()
dis.opmap['LOAD_DEREF'], 0, # 06: PUSH(freevars[0]->cell_contents)
dis.opmap['JUMP_FORWARD'], 6, # 08: JUMPTO(16)
dis.opmap['UNPACK_SEQUENCE'], 1, # 10: PUSH(POP()[0])
dis.opmap['STORE_DEREF'], 0, # 12: freevars[0]->cell_contents = POP()
dis.opmap['LOAD_CONST'], 0, # 14: PUSH(GETITEM(consts, 0))
dis.opmap['RETURN_VALUE'], 0 # 16: RETURN POP()
]))
x = (0,)
gadget(list.setitem, tuple)
list.setitem((x, 1, 2, 3), 3, x)
gadget(list.setitem, list)
print(x)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
((...),)
the function is run, and the namespace at the end of the function is converted into the class namespace
!e ```py
def ㅤ():
try:ㅤ()
except:ㅤ()
()
ㅤ()
@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 0x00007f6d99836740 (most recent call first):
005 | File "<string>", line 2 in \u1160
006 | File "<string>", line 2 in \u1160
007 | File "<string>", line 2 in \u1160
008 | File "<string>", line 2 in \u1160
009 | File "<string>", line 2 in \u1160
010 | File "<string>", line 2 in \u1160
011 | File "<string>", line 2 in \u1160
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/hojipohucu.txt?noredirect
it just hangs for me
I'm on 3.9.1
It usually signals abort
If you want hang, do the above but with a signal callback
ah, did you use a non-unicode char
!e
!e
import sys
for i in range(sys.getsizeof("龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘"),sys.getsizeof("龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘
龘龘龘龘龘龘龘龘龘龘龘龘")):
print(i)
@knotty delta :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | for i in range(sys.getsizeof("龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘"),sys.getsizeof("龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘
003 | ^
004 | SyntaxError: EOL while scanning string literal
ok
!e
eeeee
import sys
for i in range(sys.getsizeof("龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘"), sys.getsizeof("龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘")):
print(i)
@knotty delta :white_check_mark: Your eval job has completed with return code 0.
001 | 120
002 | 121
003 | 122
004 | 123
005 | 124
006 | 125
007 | 126
008 | 127
009 | 128
010 | 129
011 | 130
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/umimipacol.txt?noredirect
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
001 | 2 0 LOAD_CONST 1 (True)
002 | 2 POP_JUMP_IF_TRUE 8
003 | 4 LOAD_ASSERTION_ERROR
004 | 6 RAISE_VARARGS 1
005 | >> 8 LOAD_CONST 0 (None)
006 | 10 RETURN_VALUE
It’s also used if you do if not x or use or.
a neater interface to goto
!e ```py
from ctypes import pythonapi, py_object
import sys
PyType_Modified = pythonapi.PyType_Modified
PyType_Modified.argtypes = [py_object]
load_off3 = type(m:=lambda n:(lambda:n)())(
(M:=m.code).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)
old_format = str.format
def new_format(self, *args, **kwargs):
if args:
return old_format(self, *args, **kwargs)
f = sys._getframe(1)
return eval('f' + repr(self), f.f_globals, {**f.f_locals, **kwargs})
load_off3(str.dict)['format'] = new_format
PyType_Modified(str)
template = '{a=}'
print(template.format(a = 1))
a = 2
print(template.format())```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | a=1
002 | a=2
^ str.format that works like an fstring
str.format that's almost literally an fstring lol
Yea it does cheat with eval
is there a way to make id(a) == id(b) True when a and b are different objects? (without messing with C structs or similar)
could a get garbage collected after its id is taken and b end up in the same memory location before its id is taken?
without redefining id of course
gonna err towards no in CPython. CPython id literally just returns the PyObject pointer as a python int
Python/bltinmodule.c lines 1191 to 1203
static PyObject *
builtin_id(PyModuleDef *self, PyObject *v)
/*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/
{
PyObject *id = PyLong_FromVoidPtr(v);
if (id && PySys_Audit("builtins.id", "O", id) < 0) {
Py_DECREF(id);
return NULL;
}
return id;
}```
ah ok
the closest i can think of is with weakrefs maybe
let's see
ah nvm id(ref(A())()) will just give the id of None
!e py print(id([0]) == id([1]))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
True
[0] is deallocated after id is called, and added to the top of the list freelist
ah nice
then [1] uses that first item in the list freelist
I had a feeling you'd know haha
can you do this with non ephemeral objects though
you could use threads
how would you time the gc correctly?
you'd just run it till it fails
>>> from threading import Thread
>>>
>>> def t():
... global a, b
... while True:
... a, b = b, a
...
>>> a, b = 1, 0
>>> Thread(target=t).start()
>>> print(id(a) == id(b))
True
>>> ```
theres no guarantee this will succeed though
could just as easily have printed False
could just hook id to flip a and b
imagine youre so cosmically unlucky it always prints False lmao
like forever getting one of those weird captchas with the strange untypable symbols
problem description says not allowed to mess with C stuff
oh yeah you could just replace builtins.id
yea lol
my entire world view is crushed wtf...
>>> # The operators is and is not test for an object’s identity: x is y is true if and only if x and y are the same object. An Object’s identity is determined using the id() function.
>>> id([1])
140603291947136
>>> id([0])
140603291947136
>>> [1] is [0]
False
It works because of the order that cpython evaluates the line
yeah by the time you're dealing with what id returns the object you got the id of can be gone
I am pro is I think it's a useful and foundational tool, at lest for investigating the language but might as well use it since it's there
oh another thing, does the threading/swapping trick really satisfy the problem since a and b are the same object? eh
yeah it does imo
the important thing is that objects not being called can apparently have the same id in the same expression but not be the same object when the expression begins evaluation
a problem is solves
...
!e
from threading import Thread
def t():
global a, b
while True:
a, b = b, a
a, b = 1, 0
Thread(target=t).start()
for _ in range(10):
print(id(a) == id(b), a is b)```
@simple crystal :x: Your eval job timed out or ran out of memory.
001 | False False
002 | True True
003 | False False
004 | True True
005 | False False
006 | False False
007 | False False
008 | False False
009 | False False
010 | False False
so @floral meteor do you have a minimal reimplementation of vanilla globals?
!e
print("hi")
@last locust :white_check_mark: Your eval job has completed with return code 0.
hi
You need a space after the !e
Otherwise Python thinks the command is !e\nprint("hi") rather than just !e
@sick hound :white_check_mark: Your eval job has completed with return code 0.
0
!e
print("test")
@brisk gorge :white_check_mark: Your eval job has completed with return code 0.
test
!e
for i in range(5):
print(f"test {i}")
@brisk gorge :white_check_mark: Your eval job has completed with return code 0.
001 | test 0
002 | test 1
003 | test 2
004 | test 3
005 | test 4
ok...
!e
import time, random
def main():
myList = []
for i in range(100000):
myList.append(random.randint(0, 100))
myList.sort()
def debug():
start = time.time()
main()
end = time.time()
print(f"{round((end - start) * 1000, 3)}ms")
if __name__ == '__main__':
debug()
@brisk gorge :white_check_mark: Your eval job has completed with return code 0.
217.071ms
I doubt this has numba... but
!e
import time, random
from numba import jit
#main function defined with jit decorator
@jit(nopython=True)
def main():
myList = []
for i in range(100000):
myList.append(random.randint(0, 100))
myList.sort()
#debug information gathering speed of main() function
def debug():
main() #compiles for the first time
start = time.time()
main() #now the compiled version runs
end = time.time()
print(f"{round((end - start) * 1000, 3)}ms with jit") #printing result in ms rounded to second decimal
#good practice ;)
if __name__ == '__main__':
debug()
@brisk gorge :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | ModuleNotFoundError: No module named 'numba'
Hey @rose torrent!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
@sick hound :white_check_mark: Your eval job has completed with return code 0.
6
uh maybe we should stop this spam?
🅱️irus
Tried magic methods for the first time
Hey @sly root!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
dict() << "test" >> (var() == {"a": 20, "b": "hello", "c": "world"})
test.__type__() #<class '__main__.dict'>
test["a"] #20
cout << test #...
cfout << test >> "file.txt"```
int() << "a" >> (var() == 3)
str() << "b" >> (var() == "hello")
cout << a + b #3hello without any error
cout << a * b #hellohellohello
cout << b * a #hellohellohello```
Now I like it so much👍
they are extremely nice
also, what the fuck
I'm guessing you redefined dict
oh
my
god
All types are starting with a underscore to not break everything and make all new classes based on old ones
it's very impressive
Something like a static typing but in a shitty way
And it has some bonuses like concatenation of integer and string
Normally python throws an error
But not this time :)
int() << "a" >> (var() == 59283772718)
str() << "b" >> (var() == "test")
cout << a + b #59283772718test```
list() << "test" >> (var() == [])
test << 30 #test.append(30)
test << "hello" #test.append("hello")
cout << test #[30, "hello"]
del test["hello"] #.pop element by value
cout << test #[30]```
#string multiplication
#you can do it normally
int() << "a" >> (var() == 3)
str() << "b" >> (var() == "test")
cout << b * a #testtesttest
#and in reverse
cout << a * b #testtesttest
#it will work anyway```
sorry for bad english
>>> a='҉҉҉҉҉҉'
>>> a
'҉҉҉҉҉҉'
>>> a*100
'҉҉҉҉҉҉҉҉҉҉'
this is insanely useful
!e ```py
import sys, dis
from ctypes import c_char
def getmem(addr, size):
return memoryview((c_char * size).from_address(addr)).cast('B')
class Tmeta(type):
def lt(cls, ocls):
frame = sys._getframe(1)
mem = getmem(id(frame.f_code.co_code) + bytes.basicsize - 1, len(frame.f_code.co_code))
instructions = [*dis.get_instructions(frame.f_code)]
for idx, instruction in enumerate(instructions):
if idx * 2 < frame.f_lasti:
continue
if instruction.opname == 'COMPARE_OP' and instruction.argval == '>':
if instructions[idx+1].opname == 'JUMP_FORWARD':
if instructions[idx+2].opname == 'ROT_TWO':
if instructions[idx+3].opname == 'POP_TOP':
inj_code = bytes([
dis.opmap['ROT_TWO'], 0,
dis.opmap['ROT_THREE'], 0,
dis.opmap['CALL_FUNCTION'], 2,
dis.opmap['NOP'], 0,
])
mem[frame.f_lasti] = dis.opmap['POP_TOP']
mem[frame.f_lasti + 2] = dis.opmap['NOP']
mem[idx * 2:idx * 2 + len(inj_code)] = inj_code
return cls
class Array(metaclass=Tmeta):
def init(self, T, args):
self.T = T
self.args = args
def __repr__(self):
return f'{type(self).__name__}<{self.T.__name__}>{self.args}'
print(Array<int>(1,2,3))```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
Array<int>(1, 2, 3)
yay it still works on 3.9
That character can be used as a variable name, i think
I don't think you need the black magic with memory
it does the black magic with the memory to modify the program code in process
!e py import dis dis.dis('x < y > z')
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (x)
002 | 2 LOAD_NAME 1 (y)
003 | 4 DUP_TOP
004 | 6 ROT_THREE
005 | 8 COMPARE_OP 0 (<)
006 | 10 JUMP_IF_FALSE_OR_POP 18
007 | 12 LOAD_NAME 2 (z)
008 | 14 COMPARE_OP 4 (>)
009 | 16 RETURN_VALUE
010 | >> 18 ROT_TWO
011 | 20 POP_TOP
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ifelejucub.txt?noredirect
^ i need the bytecode modifications because x < y > z becomes x < y and y > z
mhm
You implement Array.__lt__ to return Array() with its "datatype" attribute set to other. Then, implement Array.__gt__ to return Array() with the same datatype attribute and, say, the "content" set to that tuple
!e ```py
class A:
def lt(self, other):
print('A.lt')
return self
def gt(self, other):
print('A.gt')
return self
print(A() < 1 > 2)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | A.__lt__
002 | False
A.__gt__ is never called, because the code A() < 1 > 2 becomes A() < 1 and 1 > 2 so only A.__lt__ is called
your idea would work if the code was instead transformed from A() < 1 > 2 to (A() < 1) > 2 but that is sadly not the case
just hack in object.__gt__
hmmm, that's irritating
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
False
TIL
guess that makes more sense
it must be possible to do this without bytecode modification
doesn't look like it tho
woah thats actually kinda trippie so even though theres a name error python never actually gets to it
Yea the name is never loaded
Top tip. not not x is almost 2x faster than just running bool(x).
what. the. heck.
See the description of the channel #esoteric-python
Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness
well yeah, i know this channel is cursed and i come here weekly for my dose of code insanity to remind myself just how powerful and terrifying esotericness is
but how tf-
how is not not x faster than bool(x)
- No function call so theres no function lookup
- Avoiding to run the function bool, rather we just call for its creation directly in the bytecode instead.
ohhh... wow, very interesting
Should you use this? Heck no.
i guess i'll start using not not x now lmao
you saw that video too huh
oop- why
i'd take 2x efficiency over readability tbh
Premature optimization is a bad thing to do. And writing ugly hard to read code is the worst you can do.
it's not that bad, it's just one line and easy to comment
ex: # hack, 2x more efficient than bool
"If the performance difference between bool(x) and not not x matters, quite likely Python is not the best language for your use case."
ah yes.
i do agree on that lmao
dog it doesnt even make that much of a difference youd have to do over a million of them to be able to save a microsecond
and if youre doing a million bool converts theres probably a better way to do it
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (x)
002 | 2 UNARY_NOT
003 | 4 UNARY_NOT
004 | 6 RETURN_VALUE
Computers do not care about programs being readable, but people do, and people are going to read your programs many time. Readable code has a plethora of advantages including lower error rates, being easier to debug and modify, and having shorter development time. Make code readable first, and only optimize when you can make measurable improvements to measurable performance bottlenecks.
!e
__import__('dis').dis('bool(x)')
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (bool)
002 | 2 LOAD_NAME 1 (x)
003 | 4 CALL_FUNCTION 1
004 | 6 RETURN_VALUE
Also like you get this "performance boost" from just doing if x anyways. No jank needed.
note the fact it uses load_name twice (which is expensive iirc, and call_function is incredibly expensive)
The whole thing with not not is just jank for return values and variables definitions
readable code has a shorter development time
you sure?
this is the esoteric channel how dare you say readability is important
I find it interesting it doesnt optimize away the not not 
that's because not not x != x
Yeah. They said they were gonna pick it up for writing normal programs
consider, say, 2
!e ```py
import('dis').dis("if x: pass")
@little pilot :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (x)
002 | 2 POP_JUMP_IF_FALSE 4
003 | >> 4 LOAD_CONST 0 (None)
004 | 6 RETURN_VALUE
This is what i mean.
!e ```py
import('dis').dis("if not not x: pass")
@little pilot :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (x)
002 | 2 POP_JUMP_IF_FALSE 4
003 | >> 4 LOAD_CONST 0 (None)
004 | 6 RETURN_VALUE
This is the optimization i talk about
that's bizzare
In if, it removes the not not
Its optimization
because if only cares about truthiness, not type
but for cases where type matters
such as
I just find it facinating that with just not not x it doesnt just jump to LOAD_CONST
Im thinking there might be a implementation where not doesnt directly mean to make a boolean
!e
print(('zero','other')[not not 0])
print(('zero','other')[not not 1])
print(('zero','other')[not not 2])
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | zero
002 | other
003 | other
In the same vein as how x == +x is not always true.
i.e for everything except ints
heres a challenge for you all. If a variable contains a string value or integer value make it so that when you reverse the variable name it also reverses the string or integer contained in the variable ```py
Example
ab = "12"
print(ab) #12
print(ba) #21
(except custom classes)
that's a fun one, will try tonight
Most things return true. The few things that dont can be two Decimals instantiated at different times.
huh
True==1 is true
oh yeah true and false can be their integer counterparts 1 and 0
!e py print(int(True), int(False))
@pastel ibex :white_check_mark: Your eval job has completed with return code 0.
1 0
I guess +number is valid syntax
!e ```py
from decimal import Decimal, getcontext
a = Decimal("3.1415")
getcontext().prec = 3
print(a == +a)
@little pilot :white_check_mark: Your eval job has completed with return code 0.
False
:D
Hmm thats pretty interesting actually
The short of it is. +a makes a new decimal instance. And it will follow the new .prec while the old a follows the previous
Would this happen in real code? Extremely unlikely. Could you make some cursed flooring function abusing this? Heck yeah
!e
x=type('',(),{'__pos__':lambda _:0})()
print(x==+x)
another exception
@golden finch :white_check_mark: Your eval job has completed with return code 0.
False
really i find that weird cause dis doesnt seem to show anything like that
!e This might show it better ```py
from decimal import Decimal, getcontext
a = Decimal("3.1415")
getcontext().prec = 2
print(a, +a)
@little pilot :white_check_mark: Your eval job has completed with return code 0.
3.1415 3.1
no i got that part but now that i look at it, i see what i missed
Nice :D
5 32 LOAD_NAME 5 (print)
34 LOAD_NAME 3 (a)
36 LOAD_NAME 3 (a)
38 UNARY_POSITIVE
40 COMPARE_OP 2 (==)
42 CALL_FUNCTION 1
44 POP_TOP
46 LOAD_CONST 4 (None)
48 RETURN_VALUE
``` so im guessing UNARY_POSITIVE is what creates the new instance then
very interesting i cant wait to actually learn assembly so i can actually start understanding this stuff
this isn't assembly
it's just bytecode
essentially all you need to understand is what a stack is
!e
from dis import dis
print(dis("if not not x: pass"))
@cloud fossil :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (x)
002 | 2 POP_JUMP_IF_FALSE 4
003 | >> 4 LOAD_CONST 0 (None)
004 | 6 RETURN_VALUE
005 | None
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | 2 0 LOAD_GLOBAL 0 (x)
002 | 2 POP_JUMP_IF_FALSE 4
003 | >> 4 LOAD_CONST 0 (None)
004 | 6 RETURN_VALUE
005 | b't\x00r\x04d\x00S\x00'
interesting that if isn't optimised out
in fact most pass things should be optimised out
though I guess that only applies to things that don't call_function
does co_linetable do anything?
I find that replacing co_lnotab with b'' by default makes no difference
lambda*a, since you dont know what args it will be taking?
What did you expect?
Just throw an argumentless lambda in the class slot of some random bytes object
Specifically, the code for an active frame
And expect it to be able to print a traceback?
Try it on windows, but from a cmd nested in another python, and print the return
If its segfault itll be 0xc0000005, around negative a billion
But you might get 0xc0000409 instead
!e ```py
print(-(1<<32)+0xc0000005)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
-1073741819
you should get that exit code in windows
NTSTATUS_ACCESS_VIOLATION
py -c "__import__('ctypes').py_object.from_address(id(2)+1).value=1"
Whats the exception offset?
Noice
If you repeatedly crash python, reliability monitor will think something is wrong with your computer
replacing code objects in memory is fragile
@sick hound :white_check_mark: Your eval job has completed with return code 0.
69
niiiiice
it cannot optimise the if out because bool(x) could have side effects
Damn you're talented
!e py from ctypes import py_object py_object().value
@rugged sparrow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | ValueError: PyObject is NULL
your trying to read a null pointer as a py_object
you are setting undefined_id not null_id
no prob
wow
you dont need to use forbiddenfruit to patch those classes
just do UndefinedType.undefined_id = ...
!e ```py
print((lambda r:(out:={(1,),},set(f'{set((f"{set(out.add(tuple(sorted(_i[:_j]+(_i[_j]+1,)+_i[_j+1:]))) for _j in range(len(_i)))}",f"{out.add(tuple(sorted(_i+(1,))))}") for _i in (lambda a:(set(a),set(a.remove(i) for i in set(a)))[0])(out))}' for _ in range(r-1)))[0] if r>0 else "Enter a natural number")(20))
@indigo mirage :white_check_mark: Your eval job has completed with return code 0.
{(1, 1, 1, 1, 1, 2, 2, 3, 3, 5), (1, 2, 2, 3, 4, 4, 4), (1, 1, 1, 1, 1, 1, 1, 2, 3, 8), (3, 3, 7, 7), (1, 3, 3, 5, 8), (1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3), (2, 4, 14), (2, 3, 5, 10), (1, 1, 1, 2, 2, 6, 7), (1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3), (2, 2, 3, 3, 10), (1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3), (1, 1, 1, 1, 1, 1, 2, 2, 2, 8), (2, 4, 6, 8), (1, 1, 1, 2, 2, 2, 3, 4, 4), (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4), (1, 2, 2, 2, 2, 5, 6), (1, 1, 1, 1, 1, 1, 2, 3, 3, 6), (4, 4, 12), (1, 2, 2, 2, 2, 2, 2, 2, 2, 3), (1, 1, 1, 1, 2, 2, 4, 4, 4), (2, 2, 2, 2, 3, 9), (1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 7), (1, 2, 3, 3, 3, 8), (1, 2, 2, 2, 6, 7), (1, 1, 1, 2, 2, 4, 9), (1, 1, 3, 3, 4, 8), (1, 1, 1, 2, 4, 11), (3, 7, 10), (1, 1, 1, 1, 1, 2, 2, 2, 4, 5), (1, 2, 2, 3, 5, 7), (1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4), (1, 1, 1, 5, 12), (1, 1, 1, 3, 5, 9), (1, 2, 2, 2, 2, 2, 2, 7), (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4), (1, 1, 1, 2, 2, 2, 2, 9), (1, 1, 2, 2, 2, 2, 2, 2, 3, 3), (1, 4, 4, 4, 7), (2
... (truncated - too long)
Full output: too long to upload
well not bad 👀
oh okay i see now they just look similar
god so theres multiple stages of bytecode then?
Basically, python is a virtual machine which acts as a "computer" for python bytecode
The same way your CPU executes machine code, except it's inside a process instead of hardware.
I've reached the point where I'm trying to optimise deoptimisation
you see, the beefier the computer, the slower this runs
and less efficient
with more processors
one does not simply keyboardinterrupt a hang
There are a few projects available on the web that seem to take python code and compile it into straight executable for Linux. This might be an interesting little experiment to see how well they manage this type of a situation.
Does python have a way to bind a program to a single processor?
well above script assigned the program to every available processor
it would otherwise be single thread
How would this be different using multiple processors package versus the threading package?
Would it be more efficient as a multiple processor subprocess
if you only have one cpu core, no difference
you will blue screen in such a case
with multiple, all cores will be occupied
So it could theoretically Drive the load up to the point that the operating system automatic kill processes enabled?
linux should recognise it and terminate it
windows will either blue screen or grey screen
grey screen being a sort of graphics hang
where it's just the backlight, and depending on the computer model, sometimes you get a perfectly functioning mouse pointer
Rather than spinning threads infinitely, would some kind of a limiting process of counting threads maintain control of it so that it doesn't spiral out of control?
then you'd have to count your cpus
So this is limited to one thread to one CPU? I'm used to a situation where one CPU can context switch between multiple threads...
The thing that comes to mind with this example is a real-world server process that has to manage large number of incoming requests. I can see how this can quickly overwhelm any server without some type of a limiting or safeguard mechanism...
!e print(import('os').cpu_count())
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
2
Is there a way of determining how many threads can be created on a single CPU?
Or, how many threads are currently running on a single CPU?
!e print(str(9**7)[-import('os').cpu_count():])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
probably not
or probably indefinite
This is fascinating for me as I am in the process of building a server system in python. It's very different (in many respects) than the ANSI C mechanisms I am used to so it requires me to learn a lot more...
With the example you provided, I noticed you're not joining any of the threads in process or waiting for them.
This is just creating them. It seems to be a process of a never-ending creation cycle. Is that where the fault of this program lies that causes it to crash?
👍 yeah, and hunter said that it's like a difference of a nanosecond or less so it's not worth caring about
i always forget that, i hear "2x faster" and i go crazy, without realizing that the scale is nanoscopic lmao
i love sets for memory management.. useful to trash out similar entries... very useful to golf stuff which otherwise would require good amount of memory 👀
in single thread, it just hangs, and eventually your graphics drivers crash
For Linux based systems, this would simply be killed off by the operating system for consuming too many resources?
@floral meteor thank you for the information
WSL
small windows device will blue screen in about 10 minutes in the single thread version
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Sheeh, I have no ideas what to add in my utilities for python
Currently I have something like a statical typing
And utilities for variables
Can someone give me ideas?
!e repost with a slight edit; once you see it you can't unsee it. ```py
from future import annotations
from ctypes import*
flogbals = py_object.from_address(id(globals())+8).value
name = 'Throwable'
class TypeException(TypeError):
def init(self, message):
super().init(message)
py_object.from_address(id(globals())+8).value=flogbals
class annotations(metaclass=lambda*a:type(*a)()):
() = queue = []
() = type_hints = {}
def setitem(self, cls_name, name):
if name in self.type_hints:
()=self.queue[:]=()
raise TypeException(f'Variable '{name}' already declared as '{self.type_hints[name]}'.')
if not self.queue:
self.type_hints[name] = globals()[cls_name]
return
cls, value = self.queue.pop(0)
self.type_hints.update({name:cls})
if cls==cls_name:raise NameError(f'Type {cls} not found')
dict.update(globals(),{name:cls(value)})
class globals(dict):
def missing(self, key):
return builtins.dict.get(key,key)
def setitem(self, key, value):
if key in annotations.type_hints:
dict.update(globals(), {key:annotations.type_hintskey})
return
annotations.queue+=[(globals()[key], value)]
py_object.from_address(id(globals())+8).value=globals
str: n
n = 6
str: m = 9
int: result = n + m
print(result, end='\n\nThis will make error: ')
str: result = 420 # eror
@floral meteor :x: Your eval job has completed with return code 1.
001 | 69
002 |
003 | This will make error: Traceback (most recent call last):
004 | File "<string>", line 43, in <module>
005 | File "<string>", line 17, in __setitem__
006 | Throwable.TypeException: Variable 'result' already declared as '<class 'int'>'.
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
!e ```py
import inspect
def conv_args(func):
code = func.code
flags = code.co_flags
argcount = code.co_argcount
converters = []
kwarg_conv = None
arg_conv = None
for name, param in inspect.signature(func).parameters.items():
if param.annotation is not param.empty:
conv = param.annotation
else:
conv = lambda a:a
if not param.kind & (param.VAR_KEYWORD | param.VAR_POSITIONAL):
converters.append(conv)
elif param.kind & param.VAR_KEYWORD:
flags -= flags & 0x8
argcount += 1
kwarg_conv = conv
elif param.kind & param.VAR_POSITIONAL:
flags -= flags & 0x4
argcount += 1
arg_conv = conv
func.code = code.replace(
co_flags = flags,
co_argcount = argcount,
)
def wrapper(*args, **kwargs):
return func(
*(conv(arg) for conv, arg in zip(converters, args[:code.co_argcount])),
*() if arg_conv is None else [arg_conv(args[code.co_argcount:])],
*() if kwarg_conv is None else [kwarg_conv(kwargs)]
)
return wrapper
from dataclasses import dataclass
@dataclass
class Foo:
a: int = None
b: int = None
@classmethod
def from_dict(cls, dct):
return cls(**dct)
@conv_args
def foo_func(a:int, b:tuple, *args: list, **kwargs: Foo.from_dict):
print(a, b, args, kwargs)
foo_func('1', 'string', 'a', 'b', a=1, b=2)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1 ('s', 't', 'r', 'i', 'n', 'g') ['a', 'b'] Foo(a=1, b=2)
@floral meteor argtype converter ^
you could also pass in functions that ensure the input is a specified type
>>> @conv_args
... def int_add(a: verify(int), b: verify(int)):
... return a + b
...
>>> int_add('a', 'b')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/chilaxan/Desktop/Coding/python/pysnippets/framehacks.py", line 230, in wrapper
return func(
File "/Users/chilaxan/Desktop/Coding/python/pysnippets/framehacks.py", line 231, in <genexpr>
*(conv(arg) for conv, arg in zip(converters, args[:code.co_argcount])),
File "/Users/chilaxan/Desktop/Coding/python/pysnippets/framehacks.py", line 239, in wrapper
assert isinstance(arg, typ), f'{arg!r} is not an instance of {typ!r}'
AssertionError: 'a' is not an instance of <class 'int'>
>>> int_add(1, 1)
2
>>> ``` like this
black magic but awesome
Hello, how can I get all arguments on function call?```py
class cout:
def init(self):
pass
def __lshift__(self, data):
self._ = data
getattr(getattr(sys, "stdout"), "write")(_str(getattr(self, "_")))
return self
def __rshift__(self, attribute):
self.attr = getattr(getattr(self, "_"), attribute)
return getattr(self, "attr") or self
Because this code:```py
a = 2
b = 502
cout << a, b
Prints only а (2)
!e
@lambda c:c()
class cout:
def __lshift__(self,data):
print(data,end='')
return self
a=2
b=502
cout << a << b
@golden finch :white_check_mark: Your eval job has completed with return code 0.
2502
the problem is that it's parsed as a tuple expression, of the form (cout<<a,b)
hey
Fine
Do you have a query?
#ot0-psvm’s-eternal-disapproval, #ot1-perplexing-regexing, and #ot2-never-nester’s-nightmare are perhaps more apt channels.
!e
cout=type('',(),{'__lshift__':lambda self,data:(print(data,end=''),self)[1]})()
a=2
b=502
cout << a << b
@golden finch :white_check_mark: Your eval job has completed with return code 0.
2502
Is that python?!
I thought << was in C++ only?
operator overloading
Defines an object called cout.
!e
cout=0
std=type('',(),{'__getitem__':lambda self,name:type('',(),{'__lshift__':lambda self,data:(print(data,end=''),self)[1]})()})()
a=2
b=502
std[::cout] << a << b
@golden finch :white_check_mark: Your eval job has completed with return code 0.
2502
what
(possibly shorter than the pinned version)
confusing 😅
It defines an object that prints whatever it's left-shifted with.
basically it's just an obfuscated version of
class cout:
def __lshift__(self,data):
print(data)
return self
cout=cout()
class std:
def __getitem__(self,name):
return cout
std=std()
a=2
b=502
std[::cout] << a << b
a lot more black magic is needed to get cin working
std,cout=type('',(),{'__getitem__':lambda self,name:type('',(),{'__lshift__':lambda self,data:(__import__('sys').stdout.write(str(data)),self)[1],'__repr__':lambda self:''})()})(),0
#include <iostream>
a=2
b=502
std[::cout] << a << b
still no cin but hey
cin requires some bytecode modifications
It's been a while since I've used C++ so what is actually different between python's input() and cin?
Like why is it so special here?
I think my brain got deleted after trying to find 10 ways to crash the python interpreter
the issue is that cin >> s gets the variable name
Oh right...
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (cin)
002 | 2 LOAD_NAME 1 (s)
003 | 4 BINARY_RSHIFT
004 | 6 RETURN_VALUE
And you gave to make the right compatible with the "stream"
shouldn't be an issue
You could make LOAD_NAME(cin) grab the variable name and store into it

