#esoteric-python

1 messages · Page 125 of 1

woven bridge
#

lmao nice

#

if you want to see what an instruction does go into ceval.c and ctrl+f the name of the instruction

golden finch
#

still not working in my case

woven bridge
#

rip

gritty mesa
#
for globals()["var"] in (5,):...

print(var)
```You've been defining variables wrong
woven bridge
#

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

rugged sparrow
#

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

night quarryBOT
#

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

(1, 2)
rugged sparrow
#

@golden finch ^ smaller implementation for hooking builtin classes

golden finch
#

thank you

rugged sparrow
#

it uses a method i discovered after i wrote fishhook

#

@pastel ibex you may find this interesting ^

#

@pure dew ^ you too

pastel ibex
#

hmmm

rugged sparrow
#

its a @hook implementation in less then 65 lines

pastel ibex
#

do you actually need to do all this or is this code just written for flexibility

rugged sparrow
#

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

pastel ibex
#

oh okay

rugged sparrow
#

you could also inline the functions but that would be clunky

pastel ibex
#

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

rugged sparrow
#

oh __matmul__ is a dunder

#

for @

pastel ibex
#

ohhh

#

is @ even used on anything in normal python?

rugged sparrow
#

i think numpy uses it

pastel ibex
#

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

rugged sparrow
#

ya this implementation uses a different method then fishhook does

#

simpler but has some very small differences

snow beacon
rugged sparrow
#

this implementation makes it easy to swap out with a LOAD_* hack

#

just replace getmem

pastel ibex
#

do esoteric python without using any periods in the code

#

now thats a challenge

golden finch
#

eval

pastel ibex
#

?

rugged sparrow
#

along with my smallest LOAD_CONST implementation yet

snow beacon
#

Brilliant. I can't think of any other challenges.

zinc wagon
#

Hello

#

Can someone help me

#

How can i add a code if the Passwort is correct? (Im 13)

next flame
#

wrong channel

#

@zinc wagon

zinc wagon
#

These is my base

last locust
#

As you were told, this is the wrong channel @zinc wagon

zinc wagon
#

okay sry

golden finch
#

my guess is that this is a bug with co_lnotab - what happens if you change that?

golden finch
#

What can I do with ctypes.py_object.from_address?

thorny tapir
golden finch
#

sort of

#

I don't think $ is an operator

snow beacon
#

You might be able to do it with @.

golden finch
#

the bit you need to worry about is the last 5 lines

tribal moon
#

Try to randomize all the built-in functions

#

and numbers if you can

sick hound
#

Anyone have some nice part-Python polyglots lying around?

rugged sparrow
#

It's prob an issue with the co_lnotab

floral meteor
#

Just scroll up a lot

pastel ibex
#

what in the world is a polyglot?

snow beacon
#

(Or a person who can speak multiple languages.)

pastel ibex
#

programming languages or actual languages

snow beacon
#

Programming languages.

sick hound
#

Though for my purposes I'd then need a bf console command MHXThink

floral meteor
snow beacon
#

Do you mean this?

sick hound
#

ooh

sick hound
#

It works rooPraise ```

Fatal error's py/bf polyglot

  1. Python
    -------------------------- output --------------------------
    69

  2. Brainfuck
    -------------------------- output --------------------------
    69


2/2 programs successfully run!
2/2 had the exact same stdout!
------------------------------------------------------------------------------------------```

golden finch
#

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

quasi shard
#
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

golden finch
#

what about you catch everything humanly possible

rugged sparrow
#

@sick hound what's your goal?

rugged sparrow
#

its much more stable to just modify the base object type

floral meteor
golden finch
#

mhm

floral meteor
#

!e ```py
try:raise KeyboardInterrupt(69)
except BaseException as e:print(e)

night quarryBOT
#

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

69
golden finch
#

also, that won't catch segfaults, right?

floral meteor
#

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)

night quarryBOT
#

@floral meteor :warning: Your eval job timed out or ran out of memory.

[No output]
floral meteor
#

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)

night quarryBOT
#

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

[No output]
floral meteor
#

it just hangs

#

!e ```py
import('signal').signal(11,lambda*a:69)
import('ctypes').py_object.from_address(69)

night quarryBOT
#

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

[No output]
floral meteor
#

bruh

cursive pine
#

Python Code Golf Calculator:

while True: print(exec(input("Input math problem here: ")))```
floral meteor
#

you want eval not exec

cursive pine
#

I was wondering why it broke all the sudden

#

Can't even make a joke right

floral meteor
#

and there's an unecessary space

#

after the colon

#
i=input
while 1:i(eval(i("math>")))
rich hound
#

now make it more complicated

floral meteor
#

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

rich hound
#

what

#

the fuck

golden finch
#

god I love this channel

#

alright this looks new

#

what are the property and classname.setter decorators?

snow beacon
#

property is for adding getter functions and setter functions to attributes of an object.

floral meteor
#

How do that?

snow beacon
# floral meteor 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
golden finch
#

Uh huh - so what's the use of that?

#

Also, what's the difference between a property and attribute?

snow beacon
#

Properties are attributes that have special functions for getting and setting.

floral meteor
#

property is like a method without the call brackets

#

And you can equals at them

snow beacon
golden finch
#

so do you have some examples of further usage?

snow beacon
#
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.

golden finch
#

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.

golden finch
#

@sick hound catch all errors, I dare you

#

anything that throws an arror in cpython must be caught

#

yes

floral meteor
#

All in the same file?

#

You can catch segfault it just hangs

ruby kelp
#

Will python 3.11 be for python for workgroups?

simple crystal
#

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

floral meteor
#

~ won't help you there

#

And anything else is either similar or greater size

golden finch
#

I can brute-force it if you'd like

rugged sparrow
#

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

night quarryBOT
#

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

1
golden finch
#

voodoo magic

rugged sparrow
#

its my smallest arbitrary address loader yet

#

and it doesnt need to know about pointer sizes or endianness

golden finch
#

I'm curious about how this works

rugged sparrow
#

so the core of it is abusing LOAD_DEREF

golden finch
#

never heard of that opcode

rugged sparrow
#

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

golden finch
#

mhm

rugged sparrow
#

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

golden finch
#

mhm

rugged sparrow
#

i just had another idea one sec

golden finch
#

vaguely understanding this

rugged sparrow
#

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

night quarryBOT
#

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

1
rugged sparrow
#

@golden finch i made it worse

golden finch
#

oh lrod what

#

black magic

rugged sparrow
#

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

golden finch
#

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

rugged sparrow
#

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

night quarryBOT
#

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

1
golden finch
#

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

golden finch
#

Why do you have that iter()?

rugged sparrow
#

it makes my range_iterator object

golden finch
#

Can't you just do iter(int,1)?

#

or is that not a range_iterator?

rugged sparrow
#

yea it needs to be a range_iterator

golden finch
#

I have another question

#

how can I make a class that has custom = operators

#

i.e

night quarryBOT
#

Objects/rangeobject.c lines 767 to 773

typedef struct {
        PyObject_HEAD
        long    index;
        long    start;
        long    step;
        long    len;
} rangeiterobject;```
rugged sparrow
#

^ __setstate__ on range_iterator objects lets me control index

golden finch
#
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
night quarryBOT
#

Include/cellobject.h lines 9 to 12

typedef struct {
    PyObject_HEAD
    PyObject *ob_ref;       /* Content of the cell or NULL when empty */
} PyCellObject;```
rugged sparrow
golden finch
#

is it possible without bytecode manipulation?

rugged sparrow
#

@snow beacon i made a much smaller load_addr

rugged sparrow
#

well

#

maybe with a tracefunc

turbid dewBOT
snow beacon
rugged sparrow
#

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

night quarryBOT
#

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

1
rugged sparrow
#

im quite proud of this method

#

it doesnt use LOAD_CONST anymore

golden finch
#

tracefunc?

rugged sparrow
#

!doc sys.settrace

night quarryBOT
#

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.
golden finch
#

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

snow beacon
night quarryBOT
#

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

1
golden finch
#

it also breaks idle for reads I don't understand

snow beacon
golden finch
#
def recurse(frame,event,arg):
  print(frame,event,arg)
  return recurse
rugged sparrow
#

when i was hacking that together i found a bug in cpython that im now fixing lol

#

range_iterator.__reduce__ returned a wrong value

golden finch
#

I try to type print(2) in idle and after I type the left parenthesis it hangs (not responding)

snow beacon
golden finch
#

woah

#

that does my head in

quasi shard
#

hmm???

mystic epoch
#

File ???, line 84 in ??? ? In the shell, isn't it a <input>? And most recent call first? It's last?

rugged sparrow
#

!e ```py
i=iter(range(263-1))
i.setstate(2
60)
print(i.reduce()[-1], 2**60) # these should be equal

night quarryBOT
#

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

0 1152921504606846976
floral meteor
#

msvcrt has such a convenient way of directly getting keyboard input.
How do you emulate getch with curses?

snow beacon
rugged sparrow
#

@floral meteor its possible to change the terminal settings to make stdin.read(1) function the same way

floral meteor
#

Now that's something I'd like to implement in an esoteric interface

rugged sparrow
floral meteor
#

pygame documentation just told me get rect

#

I just thoroughly got rect by this documentation

lime bane
#

!e ```py
int_ = int

int = lambda x: sum(map(int_, str(x).replace("-", "")))
print(int(6))
print(int(598))

night quarryBOT
#

@lime bane :white_check_mark: Your eval job has completed with return code 0.

001 | 6
002 | 22
floral meteor
#

!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

night quarryBOT
#

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

001 | 5
002 | 69 <class 'int'>
stark fable
#

@lambda c:c()

floral meteor
#

I invented that

#

a long time ago

#

for when I want the custom object, not the custom class

earnest wing
#

not really

#

it's a common eso usage

floral meteor
#

!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

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 34, in <module>
003 | AttributeError: 'int' object has no attribute 'value'
floral meteor
#

eh bugger it i need sleep

rich hound
#

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

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

2
rich hound
#

@floral meteor

#

did it for u lol

floral meteor
#

ty

rich hound
#

np

floral meteor
#

im just in a war with my own creation rn

rich hound
#

you assigned bar to an int, and not the value

floral meteor
rich hound
#

what did you do

floral meteor
# floral meteor

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

rich hound
#

"permission level" how many are there

floral meteor
#

0:everyone
1:admin
2:dev

rich hound
#

3 is owner i assume

floral meteor
#

3 is dev and admin

#

it goes by binary flags

rich hound
#

and 2 aswell?

floral meteor
#

00 everyone
01 admin
10 dev
11 dev and admin

rich hound
#

oh

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

custom command decorator, i like it

floral meteor
#

ty ;)

rich hound
#

can i see how it works?

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

rich hound
#

interesting

floral meteor
#

which uses frame inspection to prevent namespace pollution

rich hound
#

i dont understand what that means but ill listen still

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

seems small

floral meteor
#

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)))
rich hound
#

thats complicated.

floral meteor
#

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

rich hound
#

what is _getframe

floral meteor
#

frame inspection

rich hound
#

show an example?

floral meteor
#

!e ```py
a=4
try:raise
except Exception as e:print(e.traceback.tb_frame.f_globals['a'])

night quarryBOT
#

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

4
rich hound
#

oh

#

is there other ways to get that variable

#

by not directly referencing it

floral meteor
#

globals()['a']

rich hound
#

hm

#

that's good to know, not sure of any usecases for it

floral meteor
rich hound
#

oh bruh

floral meteor
#

!e ```py
from ctypes import*
py_object.from_address(id(2)+1).value = 1
print(2)

night quarryBOT
#

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

[No output]
floral meteor
#

That's a segfault

#

It's more powerful than system exit

rich hound
#

what even is a segfault wot

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

rich hound
#

oh

golden finch
#

np

night quarryBOT
golden finch
#

w h a t

#

I don't know what it does with enhanced, but ?

#

no

#

it has a few extra lines

golden finch
#

It may interest you to know that python optimises it down

#

oh lord wtf

#

or

#

not

floral meteor
#

Lol

floral meteor
#

the point is to change the preprocessing to make the driver code work

rich hound
#

what

floral meteor
#

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

golden finch
#

so this is harder than thought?

golden finch
floral meteor
golden finch
floral meteor
#

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

golden finch
#

mhmmm

golden finch
#

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

floral meteor
#

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

golden finch
#

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?

deep heart
#

k

olive rose
#

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

@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
olive rose
#

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

Lol wat

#

it's a decorator

floral meteor
#

hashable dicts yayyyyy

floral meteor
floral meteor
#

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

sudden osprey
#

This is esoteric python, the number of lines means nothing haha

floral meteor
#

and the longest line was 39 characters

#

hahahahah

#

39 not 38 sorry

#

!e print(19+1+39+1+2)

night quarryBOT
#

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

62
floral meteor
#

ok do it in less than 62 characters

sick hound
#

def function(python_str):
def anon():
return eval(python_str)
return anon

floral meteor
#

im thinking of making a befunge98 interpreter in python

#

cant be that hard, right?

floral meteor
#

you noobs figured it out yet?

earnest wing
#

raise an error where the class __repr__ halts execution

#

or, probably, hooking into NameError

formal sandal
#

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

main.py

#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)
sonic ginkgo
#

i hate this channel

formal sandal
sonic ginkgo
#

😆

#

that's pretty impressive, i have no idea how it works

#

this is... python syntax in a C macro?

formal sandal
# sonic ginkgo that's pretty impressive, i have no idea how it works

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

sonic ginkgo
#

gotta make it scary

formal sandal
#

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

rugged sparrow
#

@formal sandal you could make a preprocess.py that runs gcc on the importing file to make it even more streamlined

formal sandal
#

I haven't worked with import magic

#

so

#

dew it

rugged sparrow
#

I'll write up a demo later today

rugged sparrow
#

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

rugged sparrow
#

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

floral meteor
#

Nice

floral meteor
#

from the error

#

And don't forget <= 62 characters

rugged sparrow
#
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`
astral rover
#

how on earth does that work?

rugged sparrow
#

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

night quarryBOT
#

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

(1,)
astral rover
#

what op codes are \x87 and \x88?

rugged sparrow
#

LOAD_CLOSURE and LOAD_DEREF respectively

#

@radiant anchor found some new bytecode bugs

radiant anchor
#

oh nice

#

are those new?

rugged sparrow
#

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
radiant anchor
#

very concise

rugged sparrow
#

yea it abuses range_iterators internal structure

astral rover
#

why does it need to be the max size for a range_iterator?

rugged sparrow
#

because i need to be able to set the range iterators index to any valid address

#

max size ensures i have the most space

astral rover
#

oh so thats the max size of an id() call?

rugged sparrow
#

its the max for an 8byte unsigned value

radiant anchor
rugged sparrow
#

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

night quarryBOT
#

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

1
rugged sparrow
#

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

night quarryBOT
#

@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

rugged sparrow
#

@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

radiant anchor
#

neat

rugged sparrow
#

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)
>>> ```
vague cairn
#

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```
rapid kettle
#

guys pls sorry for my ignorance, but what's esoteric-python? Are you guys trying to invoke hell in earth? 🤣

golden finch
#

yes

golden finch
#

@floral meteor do you have a minimal reproduction of globals that doesn't inherit from dict?

floral meteor
#

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

floral meteor
#

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

floral meteor
#

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

rugged sparrow
#

Any static literals are built by the compiler

floral meteor
#

so i cant corrupt them?

rugged sparrow
#

Not like that

floral meteor
#

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

rugged sparrow
#

@radiant anchor figured out a way to use gadget so id is no longer needed to get addresses

young stag
#

was thinking about

def x(y): print y
x 3
#

repost

rugged sparrow
#

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

night quarryBOT
#

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

1
floral meteor
#

!e ```py
def func():
_00
_01
_02
_03
print(func.code.co_code)

night quarryBOT
#

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

t 0
1 0
t 1
1 0
t 2
1 0
t 3
1 0
d 0
S 0

#

!e ```py
import dis
print(dis.opmap)

night quarryBOT
#

@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

floral meteor
#

pop_top

rugged sparrow
#

!e py import dis print(dis.opname[1])

floral meteor
#

load_global pop_top

night quarryBOT
#

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

POP_TOP
floral meteor
#

so what does d do?

#

load const

#

0

#

return value

#

0

#

got it

#

i just manually disassembled a function

rugged sparrow
#

yea that tends to get added to all function co_code

floral meteor
#

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

night quarryBOT
#

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

Hello World!
floral meteor
#

gottim

#

ze ultimate obfusacation

#

@rugged sparrow do you like my latest evil creation?

rugged sparrow
#

It's clever

floral meteor
#

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)

night quarryBOT
#

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

5
floral meteor
#

it's such an elegant obfuscation

rugged sparrow
#

!pypi hax

night quarryBOT
#

Write compiled bytecode inline with standard Python syntax.

rugged sparrow
#

take a look at this ^

floral meteor
#

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)

night quarryBOT
#

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

[No output]
floral meteor
#

WHY CANT I DIVIDE BY 4?

rugged sparrow
#

you removed the call to LOAD_CONST

mystic epoch
#

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

night quarryBOT
#

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

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

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

@mystic epoch and where do you think it is going to input from?

mystic epoch
#

oh, yeah, it doesn't support input()

floral meteor
#

You going to go where the bot is hosted and enter the input?

#

XD

floral meteor
#

i call d with 1 then d with 0

#

You can't get much more load_const than that

floral meteor
#

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

night quarryBOT
#

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

bruh

floral meteor
#

or are they?

pastel ibex
#

Are they?

blazing seal
#

hello friends someone knows linear programming

zealous widget
#
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

snow beacon
#

I'm pretty sure you can overwrite it somehow with __builtins__.

river idol
#

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 thinkmon Vsauce music starts playing

So I wrote this: https://paste.pythondiscord.com/kilefexite.py

Enjoy 😄

snow beacon
#

Also I'd suggest raising NotImplementedError() for __iter__ and co.

river idol
#

That would represent everything except for a finite set of values.

snow beacon
#

Why bother making two classes, when the universal set is a special case of EverythingExcept?

river idol
#

Ohh, I see.

#

That's what Complement would be right.

#

Back to the editor I go...

woven bridge
potent comet
#

In regards to reduce, you can just omit the initial value, and it will start by calling the function on the first two items.

woven bridge
#

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.

river idol
woven bridge
#

and likewise for all the other operations?

river idol
woven bridge
#

oh ok, was thinking of a different problem

snow beacon
#

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

river idol
#

Might have got the logic wrong in a couple of places, not sure lemon_sweat

#

Should write tests, but nah.

snow beacon
#

I don't see any maths errors.

#

Now then, does the set of all sets which don't contain themselves contain itself?

simple crystal
#

woof

hollow kiln
#

hello hell

#

exits quietly

snow beacon
#

It's not even that scary today.

night quarryBOT
#

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

Hello world!
true mortar
#

Omg!

#

Is it faster than using print()?

floral meteor
#

noice

floral meteor
#

disassemble it and find out

#

!e ```py
builtins.dict['build_class']=print
class A:
print('what')
a=4

night quarryBOT
#

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

<function A at 0x7f9cf5835040> A
floral meteor
#

!e ```py
builtins.dict['build_class']=lambda f,n:print(f.code.co_code)
class A:
print('what')

night quarryBOT
#

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

!e ```py
from dis import dis
builtins.dict['build_class']=lambda f,n:dis(f)
class A:
print('what')

night quarryBOT
#

@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
pastel ibex
#

this dis library looks interesting

earnest wing
#

the "function" basically corresponding to the class body

shut trail
#

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
earnest wing
#

yes but it shouldn't parse

shut trail
#

!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

night quarryBOT
#

@shut trail :warning: Your eval job has completed with return code 0.

[No output]
earnest wing
#

!charinfo iㅤthink

night quarryBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

earnest wing
#

hangul, I see

shut trail
#

Yep

sick hound
#

is pointers in python impossible

rugged sparrow
#

in this channel nothing is impossible with enough creativity

earnest wing
#

weakref is a kind of a pointer

median crown
#

rate my walpaper XDD

rugged sparrow
#

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

night quarryBOT
#

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

((...),)
golden finch
#

the function is run, and the namespace at the end of the function is converted into the class namespace

floral meteor
#

!e ```py
def ㅤ():
try:ㅤ()
except:ㅤ()
()
ㅤ()

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

golden finch
#

what

#

how does that work?

#

doesn't crash for me

astral rover
#

it just hangs for me

golden finch
#

I'm on 3.9.1

floral meteor
#

It usually signals abort

#

If you want hang, do the above but with a signal callback

golden finch
#

ah, did you use a non-unicode char

knotty delta
#

!e
!e

import sys
for i in range(sys.getsizeof("龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘"),sys.getsizeof("龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘
龘龘龘龘龘龘龘龘龘龘龘龘")):
    print(i)
night quarryBOT
#

@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
knotty delta
#

ok

#

!e
eeeee

import sys
for i in range(sys.getsizeof("龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘"), sys.getsizeof("龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘龘")):
    print(i)
night quarryBOT
#

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

Asserts

#

!e ```py
def foo():
assert True
import dis
dis.dis(foo)

night quarryBOT
#

@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
potent comet
#

It’s also used if you do if not x or use or.

earnest wing
#

a neater interface to goto

rugged sparrow
#

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

night quarryBOT
#

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

001 | a=1
002 | a=2
rugged sparrow
#

^ str.format that works like an fstring

earnest wing
#

str.format that's almost literally an fstring lol

rugged sparrow
#

Yea it does cheat with eval

wintry heath
#

The Roomba Cat has blessed this channel

simple crystal
#

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?

vestal solstice
#

without redefining id of course

simple crystal
#

yepyep

night quarryBOT
#

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;
}```
woven bridge
#

let's see

#

ah nvm id(ref(A())()) will just give the id of None

rugged sparrow
#

!e py print(id([0]) == id([1]))

night quarryBOT
#

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

True
rugged sparrow
#

[0] is deallocated after id is called, and added to the top of the list freelist

simple crystal
#

ah nice

rugged sparrow
#

then [1] uses that first item in the list freelist

simple crystal
#

I had a feeling you'd know haha

woven bridge
#

can you do this with non ephemeral objects though

rugged sparrow
#

you could use threads

woven bridge
#

how would you time the gc correctly?

simple crystal
#

you'd just run it till it fails

rugged sparrow
#
>>> 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
>>> ```
woven bridge
#

theres no guarantee this will succeed though

#

could just as easily have printed False

rugged sparrow
#

could just hook id to flip a and b

woven bridge
#

imagine youre so cosmically unlucky it always prints False lmao

#

like forever getting one of those weird captchas with the strange untypable symbols

woven bridge
#

oh yeah you could just replace builtins.id

rugged sparrow
#

yea lol

sick hound
rugged sparrow
#

It works because of the order that cpython evaluates the line

simple crystal
#

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

woven bridge
# rugged sparrow yea lol

oh another thing, does the threading/swapping trick really satisfy the problem since a and b are the same object? eh

simple crystal
#

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

@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
simple crystal
#

oh

#

it doesn't fix shit haha

golden finch
#

so @floral meteor do you have a minimal reimplementation of vanilla globals?

sick hound
#

print("hi")

#

How to make python work

#

!e
print("hi")

#

!e
print(72 % 4)

last locust
#

!e
print("hi")

night quarryBOT
#

@last locust :white_check_mark: Your eval job has completed with return code 0.

hi
last locust
#

Otherwise Python thinks the command is !e\nprint("hi") rather than just !e

sick hound
#

!e\nprint(1700 % 4)

#

!e
print(1700 % 4)

night quarryBOT
#

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

0
brisk gorge
#

!e
print("test")

night quarryBOT
#

@brisk gorge :white_check_mark: Your eval job has completed with return code 0.

test
brisk gorge
#

!e
for i in range(5):
print(f"test {i}")

night quarryBOT
#

@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
brisk gorge
#

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

@brisk gorge :white_check_mark: Your eval job has completed with return code 0.

217.071ms
brisk gorge
#

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

@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'
brisk gorge
#

yeah.

#

Put numba on the bot >:(

night quarryBOT
rose torrent
#

Just Finished building my first Python bot can anyone tell me how is it

sick hound
#

!e
print(150 % 8

#

!e
print(150 % 8)

night quarryBOT
#

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

6
golden finch
#

uh maybe we should stop this spam?

golden finch
sly root
#

Tried magic methods for the first time

night quarryBOT
sly root
#
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```
sly root
golden finch
#

they are extremely nice
also, what the fuck

#

I'm guessing you redefined dict

#

oh

#

my

#

god

sly root
golden finch
#

it's very impressive

sly root
#

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

sick hound
#
>>> a='҉҉҉҉҉҉'
>>> a
'҉҉҉҉҉҉'
>>> a*100
'҉҉҉҉҉҉҉҉҉҉'
rugged sparrow
#

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

night quarryBOT
#

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

Array<int>(1, 2, 3)
rugged sparrow
#

yay it still works on 3.9

floral meteor
golden finch
rugged sparrow
#

it does the black magic with the memory to modify the program code in process

golden finch
#

I still don't think it's needed

#

suppose that

rugged sparrow
#

!e py import dis dis.dis('x < y > z')

night quarryBOT
#

@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

rugged sparrow
#

^ i need the bytecode modifications because x < y > z becomes x < y and y > z

golden finch
#

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

rugged sparrow
#

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

night quarryBOT
#

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

001 | A.__lt__
002 | False
rugged sparrow
#

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

astral rover
#

just hack in object.__gt__

rugged sparrow
#

that would work as well

#

I wanted to do it with bytecode modification

rugged sparrow
#

yea it is

#

it does mean it short circuits tho

#

!e py print(1 < 0 > A)

night quarryBOT
#

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

False
golden finch
#

TIL

#

guess that makes more sense

#

it must be possible to do this without bytecode modification

#

doesn't look like it tho

pastel ibex
rugged sparrow
#

Yea the name is never loaded

little pilot
#

Top tip. not not x is almost 2x faster than just running bool(x).

little pilot
#

Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness

dire yew
#

but how tf-
how is not not x faster than bool(x)

little pilot
little pilot
#

Should you use this? Heck no.

dire yew
#

i guess i'll start using not not x now lmao

dire yew
#

i'd take 2x efficiency over readability tbh

little pilot
dire yew
#

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

pastel ibex
#

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
#

slight explanation:

#

!e

__import__('dis').dis('not not x')
night quarryBOT
#

@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
little pilot
# dire yew ex: `# hack, 2x more efficient than bool`

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.

golden finch
#

!e

__import__('dis').dis('bool(x)')
night quarryBOT
#

@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
little pilot
#

Also like you get this "performance boost" from just doing if x anyways. No jank needed.

golden finch
#

note the fact it uses load_name twice (which is expensive iirc, and call_function is incredibly expensive)

little pilot
#

The whole thing with not not is just jank for return values and variables definitions

golden finch
pastel ibex
#

this is the esoteric channel how dare you say readability is important

little pilot
little pilot
golden finch
#

consider, say, 2

little pilot
#

!e ```py
import('dis').dis("if x: pass")

night quarryBOT
#

@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
little pilot
#

This is what i mean.

golden finch
#

you've missed the point

#

let me brew a code example

little pilot
#

!e ```py
import('dis').dis("if not not x: pass")

night quarryBOT
#

@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
little pilot
#

This is the optimization i talk about

golden finch
#

that's bizzare

little pilot
#

In if, it removes the not not

golden finch
#

I don't think that should happen

#

ah wait yeah

#

of course

little pilot
golden finch
#

because if only cares about truthiness, not type

#

but for cases where type matters

#

such as

little pilot
#

I just find it facinating that with just not not x it doesnt just jump to LOAD_CONST

golden finch
#
print(('zero','other')[not not x])
#

consider this

little pilot
#

Im thinking there might be a implementation where not doesnt directly mean to make a boolean

golden finch
#

!e

print(('zero','other')[not not 0])
print(('zero','other')[not not 1])
print(('zero','other')[not not 2])
night quarryBOT
#

@golden finch :white_check_mark: Your eval job has completed with return code 0.

001 | zero
002 | other
003 | other
little pilot
#

In the same vein as how x == +x is not always true.

golden finch
pastel ibex
#

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

golden finch
#

(except custom classes)

golden finch
little pilot
#

Most things return true. The few things that dont can be two Decimals instantiated at different times.

golden finch
#
print(True==+True)
#

okay, that's bizzare

pastel ibex
#

huh

golden finch
#

True==1 is true

pastel ibex
#

oh yeah true and false can be their integer counterparts 1 and 0

#

!e py print(int(True), int(False))

night quarryBOT
#

@pastel ibex :white_check_mark: Your eval job has completed with return code 0.

1 0
golden finch
#
print(+True)
#

==1

pastel ibex
#

I guess +number is valid syntax

little pilot
#

!e ```py
from decimal import Decimal, getcontext
a = Decimal("3.1415")
getcontext().prec = 3
print(a == +a)

night quarryBOT
#

@little pilot :white_check_mark: Your eval job has completed with return code 0.

False
little pilot
#

:D

pastel ibex
little pilot
#

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

golden finch
#

!e

x=type('',(),{'__pos__':lambda _:0})()
print(x==+x)

another exception

night quarryBOT
#

@golden finch :white_check_mark: Your eval job has completed with return code 0.

False
pastel ibex
little pilot
night quarryBOT
#

@little pilot :white_check_mark: Your eval job has completed with return code 0.

3.1415 3.1
pastel ibex
#

no i got that part but now that i look at it, i see what i missed

little pilot
#

Nice :D

pastel ibex
#
  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

golden finch
#

this isn't assembly

#

it's just bytecode

#

essentially all you need to understand is what a stack is

cloud fossil
#

!e

from dis import dis
print(dis("if not not x: pass"))
night quarryBOT
#

@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'
golden finch
#

interesting that if isn't optimised out

golden finch
#

in fact most pass things should be optimised out

#

though I guess that only applies to things that don't call_function

golden finch
#

does co_linetable do anything?

#

I find that replacing co_lnotab with b'' by default makes no difference

floral meteor
#

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)

night quarryBOT
#

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

-1073741819
floral meteor
#

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

earnest wing
#

replacing code objects in memory is fragile

night quarryBOT
#

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

69
floral meteor
#

niiiiice

rugged sparrow
acoustic gust
#

Damn you're talented

rugged sparrow
#

!e py from ctypes import py_object py_object().value

night quarryBOT
#

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

your trying to read a null pointer as a py_object

#

you are setting undefined_id not null_id

#

no prob

floral meteor
#

wow

rugged sparrow
#

you dont need to use forbiddenfruit to patch those classes

#

just do UndefinedType.undefined_id = ...

indigo mirage
#

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

night quarryBOT
#

@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

indigo mirage
#

well not bad 👀

pastel ibex
#

god so theres multiple stages of bytecode then?

earnest wing
#

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.

floral meteor
#

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

torpid pumice
torpid pumice
floral meteor
#

well above script assigned the program to every available processor

#

it would otherwise be single thread

torpid pumice
floral meteor
#

if you only have one cpu core, no difference

#

you will blue screen in such a case

#

with multiple, all cores will be occupied

torpid pumice
floral meteor
#

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

torpid pumice
#

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?

floral meteor
#

then you'd have to count your cpus

torpid pumice
floral meteor
#

it probably can

#

but then adding threads would be redundant

torpid pumice
#

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

floral meteor
#

!e print(import('os').cpu_count())

night quarryBOT
#

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

2
torpid pumice
floral meteor
#

!e print(str(9**7)[-import('os').cpu_count():])

night quarryBOT
#

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

69
floral meteor
#

or probably indefinite

torpid pumice
#

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?

dire yew
indigo mirage
#

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 👀

floral meteor
torpid pumice
floral meteor
#

iirc

#

except WSL exhibits windows behaviour

torpid pumice
#

@floral meteor thank you for the information

floral meteor
#

small windows device will blue screen in about 10 minutes in the single thread version

sick hound
#

!code

night quarryBOT
#

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.

sly root
#

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?

floral meteor
#

!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

night quarryBOT
#

@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'>'.
sick hound
#

!code

night quarryBOT
#

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.

rugged sparrow
#

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

night quarryBOT
#

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

@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
golden finch
#

black magic but awesome

sly root
#

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)

marsh void
#

it is buffer << a << b

#

actually uh

golden finch
#

!e

@lambda c:c()
class cout:
  def __lshift__(self,data):
    print(data,end='')
    return self

a=2
b=502
cout << a << b
night quarryBOT
#

@golden finch :white_check_mark: Your eval job has completed with return code 0.

2502
golden finch
#

hey

#

Fine

#

Do you have a query?

#

!e

cout=type('',(),{'__lshift__':lambda self,data:(print(data,end=''),self)[1]})()

a=2
b=502
cout << a << b
night quarryBOT
#

@golden finch :white_check_mark: Your eval job has completed with return code 0.

2502
thorny tapir
#

Is that python?!

golden finch
#

yes

#

hail satan

thorny tapir
#

I thought << was in C++ only?

golden finch
#

operator overloading

thorny tapir
#

whaat

#

also whaht does the first line do

golden finch
#

uh

#

it's equivalent to

snow beacon
#

Defines an object called cout.

golden finch
#

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

@golden finch :white_check_mark: Your eval job has completed with return code 0.

2502
thorny tapir
#

what

golden finch
#

(possibly shorter than the pinned version)

thorny tapir
#

confusing 😅

snow beacon
#

It defines an object that prints whatever it's left-shifted with.

golden finch
#

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

near gust
#

I think I should make a package for this

#

It's so stupid I have to do it

golden finch
#

cin requires some bytecode modifications

near gust
#

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

golden finch
#

the issue is that cin >> s gets the variable name

near gust
#

Oh right...

golden finch
#

so you need to do something like

#

!e

__import__('dis').dis('cin>>s')
night quarryBOT
#

@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
near gust
#

And you gave to make the right compatible with the "stream"

golden finch
#

shouldn't be an issue

rugged sparrow
#

You could make LOAD_NAME(cin) grab the variable name and store into it