#esoteric-python
1 messages · Page 23 of 1
!e ```py
q=[-~x10**x9for x in range(20)]
def c(n):
i=0
while n>q[i]:n-=q[i];i+=1
return int(str(10i+~-n//-~i)[~-n%-~i])
f=lambda k,a=1:f(k-1,a*c(10k))if k else a
for _ in range(1,7):
print(f(_))
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:1: SyntaxWarning: invalid decimal literal
002 | 1
003 | 5
004 | 15
005 | 105
006 | 210
007 | 210
is not using divmod shorter
q=[-~x*10**x*9for x in range(20)]
def c(n):
i=0
while n>q[i]:n-=q[i];i+=1
return int(str(10**i+~-n//-~i)[~-n%-~i])
f=lambda k:0**k or c(10**k)*f(k-1)
152
what if you put it in variables
d,m=divmod(n-1,i+1);return int(str(10**i+d)[m])
return int(str(10**i+~-n//-~i)[~-n%-~i])
g=~-n;h=-~i;return int(str(10**i+g//h)[g%h])
return int(str(10**i+~-n//-~i)[~-n%-~i])
still longer
122 ```py
def c(n):
while n>(t:=-~i10**i9):n-=t;i+=1
return int(str(10i+~-n//-~i)[~-n%-~i])
f=lambda k:0k or c(10**k)*f(k-1)
!e```py
def c(n):
i=0
while n>(t:=-~i10**i9):n-=t;i+=1
return int(str(10i+~-n//-~i)[~-n%-~i])
f=lambda k:0k or c(10**k)*f(k-1)
for _ in range(1,7):
print(f(_))
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1
002 | 5
003 | 15
004 | 105
005 | 210
006 | 210
why not put the i=0 in the function argument
oh yeah
126 ```py
def c(n,i=0):
while n>(t:=-~i10**i9):n-=t;i+=1
return int(str(10i+~-n//-~i)[~-n%-~i])
f=lambda k:0k or c(10**k)*f(k-1)
you forgot about the newline
yeah but newline
117
c=lambda n,i=0:c(k,i+1)if(k:=n+~i*10**i*9)>0else int(str(10**i+~-n//-~i)[~-n%-~i])
f=lambda k:0**k or c(10**k)*f(k-1)
!e
import ctypes
ctypes.cast(-1, ctypes.py_object)
!e
from fishhook import hook
@hook(list)
def __hash__(self):
return hash(tuple(self))
@hook(dict)
def __hash__(self):
return hash(tuple(self.items()))
d = {[[1], 2, [3]]: 1, {1: 2, [3, {4: 5}]: 6}: 1}
print(d)
print([[1], 2, [3]] in d)
d[([1], 2, [3])] = 3
print(d)
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | {[[1], 2, [3]]: 1, {1: 2, [3, {4: 5}]: 6}: 1}
002 | True
003 | {[[1], 2, [3]]: 1, {1: 2, [3, {4: 5}]: 6}: 1, ([1], 2, [3]): 3}
@pearl socket :warning: Your 3.11 eval job has completed with return code 0.
[No output]
this works surprisingly well
JSON achieved
Mutation cares about hashability?
the idea of the hash is to return a unique integer for each thingy, right?
!e
from fishhook import hook
@hook(list)
def __hash__(self):
return hash(tuple(self))
a = [1]
b = [2]
s = {a, b}
print(s)
a[:] = b
print(s)
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | {[1], [2]}
002 | {[2], [2]}
im fairly sure thats what a hash does
but i dont remember
yeah
why not return id(self) then
Why doesn't this code end up with one list if it's the same hash
hash(1) and hash(1.0) should both be the same
it's how python implements hashing
!e print(hash(1), hash(1.0))
@cloud fossil :white_check_mark: Your 3.11 eval job has completed with return code 0.
1 1
probably because sets i would assume
for something like
d = {-1, 1j, 1, -1j}
you don't want
-1+0j in d
to be false
same with dicts
Wait, why? Does this work?
well. if you want it to be true then you could use complex numbers for all of them
rather than using ints for some and complex's for others
idk, its not really important. i was just curious lol
Did you just answer yourself
no
i explained the reason for my question
and dismissed the line of questioning as non-important
you mean, x == y iff hash(x) == hash(y)?
The __hash__() method should return an integer. The only required property is that objects which compare equal have the same hash value; it is advised to mix together the hash values of the components of the object that also play a part in comparison of objects by packing them into a tuple and hashing the tuple.
from the docs
ah
intuitively you'd want __contains__ to look something like
def __contains__(self, item):
for i in self:
if i == item:
return True
return False
i think
yeah
!e
from fishhook import hook
@hook(range)
def __contains__(self, item: int):
return isinstance(item, int) and item >= self.start and item < self.stop and item % self.step == 0
print(2 in range(5))
@fair quartz :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
!e
from fishhook import hook
@hook(range)
def __contains__(self, item: int):
return isinstance(item, int) and item >= self.start and item < self.stop and item % self.step == 0
print(2 in range(0, 4, 2))
@fair quartz :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
guys, how is fishook built into snekbox?
is it actually installed on the snekbox's venv or is snekbox installing dependencies dynamically then caching it?
ah i see
it is indeed built in
but why would such a small, yet such a good library be built-in
interesting
range does this already tho
!e
print(5 in range(2, 10, 3))
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
Is this correcly implemented? What if the range does not start at zero? In any case, the operator in can be used with a range object. This is a built-in functionality.
hey im back
Hey @agile frigate!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
code
Back when I first released fishhook myself and a handful of people who frequented #esoteric-python wanted to use the lib in the eval command so we requested it be added
that is very cool
technically it's installed on the nsjail venv if that's what you're asking
snekbox itself (the server) doesn't have those dependencies
so security isn't a huge concern, since they're all in the isolated environment
Just thought about this now, but is the time complexity of range.__contains__ O(1)? Since I mean, you could really just check if start <= x <= stop
I believe it is for int and possibly integer floats
In [3]: class A:
...: def __eq__(s, o): return False
...:
In [4]: A() in range(1, 100000000000)
^C---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
Cell In [4], line 1
----> 1 A() in range(1, 100000000000)
Cell In [3], line 2, in A.__eq__(s, o)
----> 2 def __eq__(s, o): return False
KeyboardInterrupt:
In [5]: 10000000000000000000 in range(1, 100000000000)
Out[5]: False
it depends is the short of it
Objects/rangeobject.c lines 481 to 489
range_contains(rangeobject *r, PyObject *ob)
{
if (PyLong_CheckExact(ob) || PyBool_Check(ob))
return range_contains_long(r, ob);
return (int)_PySequence_IterSearch((PyObject*)r, ob,
PY_ITERSEARCH_CONTAINS);
}```
interesting
what's funny is that this isn't telling the whole story
nvm it is
I haven't read all of the LOC but I mean I see an iterator somewhere so I don't think it's O(1)
I was testing the wrong example
I wonder why its iterating instead of just checking if its in the open interval though
Wouldn't it just be the same exact thing but less intensive
a given class may only implement equality but not comparison
In [10]: %timeit 1e10 in range(1, 10000000)
431 ms ± 7.32 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [11]: %timeit 10 ** 10 in range(1, 10000000)
191 ns ± 1.37 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
I see that would make sense
I would've thought there would be some optimisation for ints or something though
There is
there is if (PyLong_CheckExact(ob) || PyBool_Check(ob)) return range_contains_long(r, ob); this thing
that's what the PyLong_CheckExact is
Oh lmao 😔 facepalming
int is PyLong internally
I guess this is a TIL
I found a bug that lets me get into a state where I can execute python code with an exception set, anyone know any spots that I could use this to provoke even an weirder state?
wdym "with an exception set"?
as in, after an exception has been thrown but before its been handled?
results in this weird traceback py Traceback (most recent call last): File "bug.py", line 31, in <module> 1 in weird_range File "bug.py", line 22, in __gt__ print() # this is normal builtin print ^^^^^^^ File "bug.py", line 27, in __le__ raise self.E Exception: This exception is handled late
and __le__ is called directly before __gt__
so __le__ raises the exception, but __gt__ is called despite that
so the print() call happens to check for a set exception (haven't checked where yet) and finds one, so it returns NULL which triggers the interpreter to check for set exception
if you dont call print, does it just keep going?
yea
what happens if you raise another exception
until it hits something else that happens to check for an exception
while the first is in flight
it just overwrites the first one
ah
actually wait
my test for that was bugged
because i did raise Exception('second') but that call to create the exception is what was checking for an exception
- yea it did just overwrite it
none of them have been like critical vulns so far
mostly stuff that would require specific code to hit the bug so it is unlikely to see vulnerable code in the wild
what do you guys think of my anonymous recursion
!e
import sys, types, gc
print(
(lambda fun,*args:fun(*args,fun))(lambda n,self_:1if n<2else self_(n-1,self_)*n,5)
)
print(
(lambda n:1if n<2else types.LambdaType(sys._getframe().f_code,globals(),'',(n-1,),())()*n)(5)
)
print(
(lambda n:1if n<2else[o for o in gc.get_referrers(sys._getframe().f_code)if isinstance(o,types.LambdaType)][0](n-1)*n)(5)
)
@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:3: SyntaxWarning: invalid decimal literal
002 | <string>:3: SyntaxWarning: invalid decimal literal
003 | <string>:7: SyntaxWarning: invalid decimal literal
004 | <string>:7: SyntaxWarning: invalid decimal literal
005 | <string>:11: SyntaxWarning: invalid decimal literal
006 | <string>:11: SyntaxWarning: invalid decimal literal
007 | 120
008 | 120
009 | 120
the y combinator would like to have a word
here's a helper for anonymous recursion:
import sys, types
@lambda _:_()
class lambda_self:
__call__=lambda _,*a,**k:types.LambdaType(sys._getframe().f_back.f_code,globals(),'',(),())(*a,**k)
print((lambda n:1if n<2else lambda_self(n-1)*n)(5))
why not sys._getframe(1).f_code
!e ```py
import sys
import gc
def self(*args, **kwargs):
for o in gc.get_referrers(sys._getframe(1).f_code):
if isinstance(o, type(lambda:0)):
return o(*args, **kwargs)
print((lambda n:1 if n < 2 else self(n - 1) * n)(5))```
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
120
no reason besides the fact that I forgot
any reason why you are making a new function object instead of reusing the original function object like above?
either method works
no reason in particular
I would guess that gc.get_referrers is slower though
but perhaps it's not
doesn't gc.get_referrers(...)[1] suffice?
technically, the order of gc.get_referrers(...) is not specified
it might work for CPython but I'm unsure about other implementations
sys._getframe is also a cpython implementation detail
you can replace it with inspect.getframe() which I presume is cross-impl
https://docs.python.org/3/library/inspect.html#inspect.currentframe this specifies that frames in general are a cpython implementation detail
oh interesting
didn't know that
I'm curious if there's a shorter solution for CPython anyways because I couldn't figure out a solution with just using the sys._getframe().f_code.replace function but I feel like there should be...
would you have to use a Y combinator then?
for other non-Cpython versions?
yea
my personal rule of thumb is if an object uses attributes like prefix_attrname (f_code, gen_code, etc) that object is probably a cpython implementation detail and those attributes are not part of the spec
well _getframe is different - there are other functions that are not implementation specific that have a _name scheme
afaik all the functions with the _name scheme are either implementation specific or not guaranteed stable api
what other ones are there?
not stable
I am referring to the platform-specific modules
and also
non-stable apis
such as
pickle._Pickler
i would consider stuff like pickle._Pickler as implementation specific since they are defined in C
I suppose
Yeah RustPython gives:
Traceback (most recent call last):
File "<wasm>", line 5, in <module>
File "<wasm>", line 5, in <lambda>
File "gc", line 113, in get_referrers
NotImplementedError
or (compiler panic!?)
RuntimeError: panicked at 'The symbol must be present in the symbol table, even when it is undefined in python.', compiler/src/compile.rs:436:48
or
Traceback (most recent call last):
File "<wasm>", line 3, in <module>
File "<wasm>", line 3, in <lambda>
TypeError: unexpected payload for __call__
interesting that RustPython is using the webassembly build
that's not local
thats on https://rustpython.github.io/demo/
Rust is a "first-class citizen" for WASM so practically all things that can be used on WASM have been.
ah makes sense
the panic is from this:
import sys, types
@lambda _:_()
class lambda_self:
__call__=lambda _,*a,**k:types.FunctionType(sys._getframe().f_back.f_code,globals(),'',(),())(*a,**k)
print((lambda n:1if n<2else lambda_self(n-1)*n)(5))
I don't know what part makes it bad
might be the @lambda _:_()
because
import sys
import gc
self=lambda *a,**k:types.LambdaType(sys._getframe().f_back.f_code,globals(),'',(),())(*a,**k)
print((lambda n:1 if n < 2 else self(n - 1) * n)(5))
gives that "TypeError: unexpected payload for __call__"
I'm gonna look into the source for RustPython and see if I can construct a RustPython version
it's more tricky than I thought
it can't bind the FuncArgs to the &VirtualMachine and it seems that is because the RustPython actually prevents type coercion in that stage
Esoteric challenge - probably impossible without C tricks like einspect. Get at the raw yielded value of an async generator - that is, the wrapped value object.
Hopefully it still exists in 3.11
what?
what does that mean
Python/ceval.c line 2637
PyObject *w = _PyAsyncGenValueWrapperNew(retval);```
You normally can't access it, but it is a python object
It is unwrapped by AsyncGenASend
No idea where it is in 3.11 though
If it even still exists
it's gone in 3.12 but still there in 3.11
so basically just get the wrapper?
!e @proper vault this? ```py
from opcode import opmap
async def g(): yield 2
g.code = g.code.replace(co_code=g.code.co_code.replace(opmap['YIELD_VALUE'].to_bytes(), opmap['RETURN_VALUE'].to_bytes()))
print(anext(g()))
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
<async_generator_asend object at 0x7f5215ecbb80>
!e ```py
async def g(): yield 2
import dis
dis.dis(g)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1 0 RETURN_GENERATOR
002 | 2 POP_TOP
003 | 4 RESUME 0
004 | 6 LOAD_CONST 1 (2)
005 | 8 ASYNC_GEN_WRAP
006 | 10 YIELD_VALUE
007 | 12 RESUME 1
008 | 14 POP_TOP
009 | 16 LOAD_CONST 0 (None)
010 | 18 RETURN_VALUE
Not quite, you still have to run the asyncgen_send, which I am not sure does anything when given a return value.
Huh, in 3.11 it's an instruction
In 3.10 it's just special behavior of YIELD_VALUE
Is it true that between lines (= after one statement is completely executed) stack is always empty?
Afaik no, for example a with statement leaves the context manager on the stack for its body
What should hold however is that the stack before and after a statement is the same
There could be exceptions though
Indeed.
I am asking that because i am thinking about safety of goto inside of one function. I guess, it is safe to jump inside one "block" statement (with, for, try-except, ...)
!e
async def f(): yield
f.__code__=f.__code__.replace(co_flags=f.__code__.co_flags &~0x200)
print(f().send(None))
``` here it is in 3.11, but this won't work in 3.10
@proper vault :white_check_mark: Your 3.11 eval job has completed with return code 0.
<async_generator_wrapped_value object at 0x7f58969f9120>
hi guys can you recommend any obfuscator?
how to compile dis.get_instructions(codeobj) back to code object?
is it possible?
how to get the exact number of CACHE entries every instruction needs?
seems like LOAD_GLOBAL uses 5, LOAD_ATTR - 4, POP_TOP - 0
It is possible, I might have code to do it somewhere
dis.get_instructions(codeobj, show_caches=True) will include cache ops
my code turned to mess again
so i am now using bytecode package for bytecode manipulations
it is a lot easier with this package
@goto
def gcd(a: int, b: int) -> int:
label.start
if a < b:
goto.swap
else:
goto.main
label.swap
a, b = b, a
label.main
a, b = b, a % b
if not a:
goto.end
if not b:
goto.end
goto.start
label.end
return a
``` now it works
nice
Does anybody have a reference implementation of __build_class__? I'm looking to cook up something cursed
What do you mean by "reference implementation"? What the builtin __build_class__ does, or something else?
Here's the definition of __build_class__: https://github.com/python/cpython/blob/main/Python/bltinmodule.c#L88
I did spellchecking of classes with it once: https://github.com/L3viathan/spelcheck
Python/bltinmodule.c line 88
/* AC: cannot convert yet, waiting for *args support */```
Exactly that, an implementation of the builtin __build_class__ function in Python. I've read bltinmodule.c but my C is beginner-level and I'm not 100% sure I can implement it correctly directly from C code
I could have sworn someone posted one here before
You mean this? #esoteric-python message
I've used that in the past, but there are some weird edge cases where it doesn't work and I'm not sure why
Interestingly, when I use this as __build_class__ and then define class Foo:a=2 I get a TypeError: Foo() takes 0 positional arguments but 1 was given. Any ideas?
(See #bot-commands message for traceback & code)
Bug fixed, the line
newnamespace = func(namespace)
should be replaced with
import copy
newnamespace = copy.copy(namespace) # do I need to deepcopy this? not sure about impementation details
exec(func.__code__,func.__globals__,newnamespace)
do you even need to copy the namespace?
I don't think so but it's included in the original
I can't think of anything that would ever trigger that
it works fine without it
!e metaclasses can be used to create a forwards linked list
def tp_linked_list(data_to_encode):
class end_link(type, metaclass = type):
pass
current_link = end_link
for obj in tuple(data_to_encode)[::-1]:
class link(type, metaclass = current_link):
next = current_link
data = obj
current_link = link
return current_link
ll = tp_linked_list((1, 2, 3))
print(ll.data)
print(type(ll).data)
print(type(type(ll)).data)
print(type(type(type(ll))).data) # errors, since it goes out of bounds of the list
@versed eagle :x: Your 3.11 eval job has completed with return code 1.
001 | 1
002 | 2
003 | 3
004 | Traceback (most recent call last):
005 | File "<string>", line 17, in <module>
006 | AttributeError: type object 'end_link' has no attribute 'data'
ive been told that in the lean language, type = type 1, type (type 1) = type 2, type (type 2) = type 3, etc
kinda reminds me of church encoding for numbers
🥴
where is that?
oh cool so
lean is based off of lambda calculus
no wonder i thought of church encoding lmao
!e
from ctypes import c_void_p
c_void_p.from_address(id(True)+8).value = id(False)
c_void_p.from_address(id(False)+8).value = id(True)
@pearl socket :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
That code is changing the type of True to False and vice versa, since True and False are not types it crashes
class Namespace(dict):
def __init__(self):
self.times = {}
def __setitem__(self,name,value):
if isinstance(value,type(lambda:0)) and type(value.__doc__)is str and value.__doc__.isnumeric():
if name not in self or name in self.times:
if name in self.times:
if int(value.__doc__)>self.times[name]:
self.times[name]=int(value.__doc__)
dict.__setitem__(self,name,value)
else:
self.times[name]=int(value.__doc__)
dict.__setitem__(self,name,value)
else:
dict.__setitem__(self,name,value)
@lambda f:setattr(__builtins__,"__build_class__",f)
def build_class(func, name, *bases, metaclass=None, **kwds):
if metaclass is None:
if not bases:
metaclass = type
else:
metaclass = bases[0].__class__
if hasattr(metaclass,"__prepare__") and metaclass is not type:
namespace = metaclass.__prepare__(name, bases, **kwds)
else:
namespace = Namespace()
exec(func.__code__,func.__globals__,namespace)
return metaclass(name, bases, dict(namespace), **kwds)
demo:
class Foo: # it hooks the internal class creation process itself, no special syntax needed
def A(): # later timestamps override newer ones
'1678163895'
print('New A')
def A():
'1678163878'
print('Old A')
def B():
print('Old B')
def B():
print("Methods without a version docstring will override all others, including themselves if defined sequentially")
def B():
'1'
print('Old B1')
attr = 'Attributes are unaffected'
Foo.A() # New A
Foo.B() # Methods without a version docstring will override all others, including themselves if defined sequentially
print(Foo.attr) # Attributes are unaffected
i opted for a full implementation
https://github.com/thatbirdguythatuknownot/sniplections/blob/main/pybuild_class.py
tysm
pyarmor?
esopy starter pack:
ctypes
~
lambda
@ hook
;
:=
and that
!e love it when ```py
from _testcapi import*;fatal_error(b"unspecified reason")
@quartz wave :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
001 | Fatal Python error: test_fatal_error: unspecified reason
002 | Python runtime state: initialized
003 |
004 | Current thread 0x00007f17f07da740 (most recent call first):
005 | File "<string>", line 1 in <module>
006 |
007 | Extension modules: _testcapi (total: 1)
can anybody here asnwer my quiestion on #discord-bots maybe?
this is esopy
ask in pygen
i dont think you want to be here
this is the forbidden lands
esoteric discord bot
tfw import discord as np
@silent tartan stuff like this
no
Can you shortest this?
from collections import deque
t = int(input())
for _ in range(t):
s = input().rstrip()
n = int(input())
a = input().rstrip()[1:-1].split(',')
if a[0]=='':
a=deque()
else:
a=deque(a)
f = False
fa = False
for i in s:
if i=='R':
fa=not fa
elif i=='D':
if not a:
f=True
break
if fa:
a.pop()
else:
a.popleft()
if f:
print('error')
else:
if fa:
a.reverse()
print('[{}]'.format(','.join(a)))
what is it supposed to do?
is there a way i can obfuscate my code in python very good
I=input;P=print
for _ in range(int(I())):
s=I().rstrip();I();a=I().rstrip()[1:-1].split(',');a=a if a[0]else[];f=0
for i in s:
if i=='R':f=1-f
if i=='D':
if not a:P('error');break
a.pop(-f)
else:P(f'[{",".join(a[::1-2*f])}]')
``` idk if this works
thanks
this saves a char
a=a if a[0]else[] -> a=a[0]and a or[]
which gives us this
I=input;P=print
for _ in range(int(I())):
s=I().rstrip();I();a=I().rstrip()[1:-1].split(',');a=a[0]and a or[];f=0
for i in s:
if i=='R':f=1-f
if i=='D':
if not a:P('error');break
a.pop(-f)
else:P(f'[{",".join(a[::1-2*f])}]')
does anyone happen to have an implementation of the cpp written in Python?
the cpp?
Yes
Can u send or show me it please
C PreProcessor
the program is called cpp on most Unix-based systems
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello World.
!e ```py
print("".join(sum([[*_]for _ in zip("hlowrd", "el ol.")],[])).title())
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello World.
i was discussing the classic “how cursed can you make isOdd when you dont use mod 2” with some friends, and ended up with these two:
isOdd = lambda n:("{:n}".format(n/2)*2)[-2]=="."
isOdd = lambda l:l//2-l/2
using l for confusion with 1 is sorta cheating as far as I’m concerned so
isOdd = lambda v:v//2-v/2
probably looks nicer as it goes with the angle of the /
is_odd = lambda v:v&1
destroyed
well i wasn’t golfing :P
if you dont care about length then a few longer options can be employed
such as,
from ctypes import *
is_odd = lambda n: bool(c_int8.from_address(id(n) + 24).value & 1)
Does python's c_int8 overflow?
!e print(2**8)
@old socket :white_check_mark: Your 3.11 eval job has completed with return code 0.
256
!e ```py
from ctypes import *
is_odd = lambda n: bool(c_int8.from_address(id(n) + 24).value & 1)
is_odd(257)
@old socket :warning: Your 3.11 eval job has completed with return code 0.
[No output]
Oh I guess not?
Past 8-bits?
because after 255
is 0
which is even
odd and even always alternate
so the overflow doesn't matter
Oh okay
are you planning on using it with python code?
yeah. though ive started writing my own since i couldnt find one
its a lot harder than i thought it'd be
I made one specific for python a while ago lol https://github.com/dzshn/pypp
doesn't have conditions yet though I should get back
also oops I missed your reply earlier
hey guys is a bad practice to use the all() method? or why i never see it?
it's usually not that used for most normal cases
hey class do you use a lot lambdas functions?
esopy doesn't have bad practices
not that many
forget it
if you're talking about outside of esopy I use all pretty often
lambdas are more for esopy
I mean you're asking in #esoteric-python so I'd assume your context is for esopy
I didn't realize you meant the function all
@goto
def test_loop(l: list[int], x: int) -> list[int]:
res: list[int] = []
for i in l:
if i == x:
goto.loop2
res.append(i)
for i in ():
res.append(i)
label.loop2
return res
assert test_loop([1, 2, 3, 2, 4, 5], 2) == [1, 3, 2, 4, 5]
this code removes first occurrence of x in l
is this open source?
it requires only bytecode package
it works on this version: 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)]
i didn't test it on other versions
that's super helpful, actually
ty
that's ok lol
!e 
from einspect import view
view(True).swap(False)
print(True == 0)
print(False == 1)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | True
002 | True
Is it True because the answer is swapped or is it True because the boolean literals' values are swapped
It's like the paradox where you ask someone whether they lied to you and they answer yes, what would you make out of it 
I guess that's because the result of True == 0 is optimised during compile time into False and then False and True are swapped.
No, im wrong
bool.__repr__ works like this:
lambda self: "True" if id(self) == TRUE_ID else "False", where TRUE_ID is a pointer to True that is hardcoded in binary code.
When you swap True and False, their values are swapped, but reprs are still the same.
So repr(True) is "True" even after swap
And in this example == returns True, because 0 and True(that is swapped with False) are equal, so the output is True
!e __import__("dis").dis("True==1")
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 0 RESUME 0
002 |
003 | 1 2 LOAD_CONST 0 (True)
004 | 4 LOAD_CONST 1 (1)
005 | 6 COMPARE_OP 2 (==)
006 | 12 RETURN_VALUE
equalities aren't inlined to constants
technically both of those prints return the value of False, it just happens that bool repr uses object identity
despite swapping the memory of False and True, their reprs won't change
this is real
from ctypes import c_void_p
tp = type("", (), {})
c_void_p.from_address(id(object)+8).value = id(tp)
object.<tab>
i really need to learn how the structure of all of this works
!e```py
def fib():
a, b = 0, 1
for i in range(20):
print(a)
a, b = (a ^ b) & ((1 << 32) - 1), ((a & b) << 1) & ((1 << 32) - 1)
fib()
@cursive moon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0
002 | 1
003 | 1
004 | 1
005 | 1
006 | 1
007 | 1
008 | 1
009 | 1
010 | 1
011 | 1
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/gidocisaqo.txt?noredirect
Lmao
for starters, at least
tab is invalid syntax, that shouldn't get pass compiling stage
doing object.<tab here> segfaults for me at least
so I don't see how it can segfault
in the repl
oh do you have the autosuggest on?
pressing tab in the repl shows suggestions
that's what's happening here
i don't know why it crashes but its funny nontheless
the [1] is part of the shell message for the segfault on some machines
maybe the autocomplete fetching attributes crashes
probably
but it's not too strange
well you set the type of object to an integer
so accessing any attributes of object would break, right?
well no it set the pointer to the address of tp
oh wait- i read it wrong
but object isn't supposed to have a type of that
regardless, i used it wrong
that's why it crashed
sometimes cpython makes assumptions to locate object
sorry! thought it said py_object not c_void_p
apparently im too tired to read lmao
also you might have to incref your new type so it doesn't get GC'd
it would already have a reference, no?
from being assigned to tp
it'd be stored in the globals dict
but tp would get dropped afterwards if it has no references
well, not in the repl but
normally it would
!e
from einspect import view, unsafe
with unsafe():
view(object).type = type("", (), {"a": 123})
print(object.a)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
123
~: $ cat gc_test.py
import gc
tp = type("test", (), {})
gc.collect()
print("tp" in globals())
~: $ python3 gc_test.py
True
the variable never goes out of scope so it never gets collected
yeah in this case, but if you called it in a function tp would go out of scope
well yeah
regardless it's not safe ref counting wise
object is supposed to "own" the reference to its type
how so?
well say if object was GC'd before tp, tp now points to invalid memory
since object will DecRef the type as it owns it
i don't think that will happen though
not with object, no, but other types yeah
ah. you meant, it's not safe in general
not that its not safe for this specific case
i misunderstood what you meant originally
!e
from ctypes import c_void_p
tp = type("", (), {})
def main():
class Foo:
pass
c_void_p.from_address(id(Foo)+8).value = id(tp)
main()
print(tp)
@dry mirage :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
<class '__main__.'>
>>> res(1,x=2)
Traceback (most recent call last):
...
UnboundLocalError: cannot access local variable '_c' where it is not associated with a value
>>> res(1,x=2,_c=3)
Traceback (most recent call last):
...
TypeError: _test.<locals>.f() got an unexpected keyword argument '_c'
``` cursed
!e ```py
def f(a,*,x):_c=2;del _c;_c
f(1,x=2)
@quartz wave :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | File "<string>", line 1, in f
004 | UnboundLocalError: cannot access local variable '_c' where it is not associated with a value
!e ```py
def f(a,*,x):_c=2;del _c;_c
f(1,x=2,_c=3)
@quartz wave :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | TypeError: f() got an unexpected keyword argument '_c'
ok
In my case it is a bug that happened while changing bytecode
I removed arg _c but forgot to change LOAD_FAST _c
# Create the hook
import ctypes
globals_type=ctypes.py_object.from_address(id(globals())+8) # extract the type of the globals() dict
class new_globals(dict):
__slots__=()
def __getitem__(self,name,bound1=dict,globals_type=globals_type):
try:
globals_type.value = bound1
if name[0]=='λ' and len(name)>1:
return 'λ'
return self[name]
finally:
globals_type.value=__class__
globals_type.value = new_globals # so when methods are looked up they are looked up in the new globals
I've been digging through some of my old snippets I've been experimenting on that I saved from this channel, and I found this one, which I never understood how it worked.
Specifically
• Why does adding an except clause crash?
• Why do we need to bind dict and the globals type to the local scope?
• Why do we need __slots__?
• Why do we set the globals type's value to __class__ (which should be undefined, but isn't, apparently?)?
I presume what this is doing is modifying the class of globals so it has a modded __getitem__ method
__slots__ is to prevent it from segfaulting
setting it to __class__ is to set it back to the same type
since it gets set to dict in the try block
binding the things to local scope is so it doesn't recurse
because if they're global, then accessing them leads to calling the __getitem__ method again
though there's a better way to do that imo
*more specifically, __slots__ being added ensures that the instances of the new_globals type are the exact same layout as instances of dict
(Along with other cache space)
Where is __class__ defined?
it is a magic variable, part of how argumentless super works
its added as a cell variable at compile time if __class__ or super is referenced
!e ```py
class A:
def foo():
super
print(A.foo.closure[0].cell_contents is A)```
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
thanks
yea back when I first wrote that hook strategy it seemed like the best/only way to get a safe stable reference to the class itself
Include/object.h lines 102 to 106
struct _object {
_PyObject_HEAD_EXTRA
Py_ssize_t ob_refcnt;
PyTypeObject *ob_type;
};```
To catch reference related errors
negative values are used to indicate errors then?
If you do REF_DEC too often, ob_refcnt will eventually become negative
right
Otherwise if ob_refcnt is unsigned, it would be difficult, because 0-1==2**32-1
2**32-1 > 0
And i guess there is no if (ob_refcnt==0) then throw BadReferenceError; check in REF_DEC in release mode because it would be a bit slow
It is actually Py_DECREF, not a REF_DEC 🙃
dw, i understood what you meant
as long as you can call it i see no reason to expect anything out of the ordinary
that's how they're usually defined if you're using the type constructor
!e
class EmptyString:
__str__ = str
print(repr(str(EmptyString())))
When compiled with debug mode there is an assert that is hit if any refcount hits a negative value, which acts like a rudimentary catch all for refcounting bugs. And it would be essentially impossible (on average current hardware) to produce enough references to a given object to need an unsigned 8byte value for the refcount
@languid hare :white_check_mark: Your 3.11 eval job has completed with return code 0.
''
That's because you can't bind a built-in function as a method because they do not implement the descriptor protocol
mm
It is not possible on any 64-bit hardware to produce 2**63 references, because this number of references would require 8(bytes per pointer)*2**63=2**66 bytes of memory to store, which is bigger than biggest possible memory
Also, today's 64-bit pointers are not actually containing 64 bit of data, there is a lot of unused values
!e print(object())
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
<object object at 0x7f5716524160>
!e this works though?
class Foo:
__eq__ = print
Foo() == 1
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
though I guess it isn't really bound
Yes, builtin_function_or_method class doesn't implement descriptor methods
!e ```py
def f():...
f.get # ok
print.get # should fail here
@fleet bridge :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | AttributeError: 'builtin_function_or_method' object has no attribute '__get__'. Did you mean: '__ge__'?
!e ```py
print(hasattr(print, "code"))
print = lambda *x: print(x)
print(print.code)
@vast wave :x: Your 3.11 eval job has completed with return code 1.
001 | False
002 | Traceback (most recent call last):
003 | File "<string>", line 3, in <module>
004 | File "<string>", line 2, in <lambda>
005 | File "<string>", line 2, in <lambda>
006 | File "<string>", line 2, in <lambda>
007 | [Previous line repeated 996 more times]
008 | RecursionError: maximum recursion depth exceeded
@vast wave :x: Your 3.11 eval job has completed with return code 1.
001 | False
002 | Traceback (most recent call last):
003 | File "<string>", line 3, in <module>
004 | File "<string>", line 2, in <lambda>
005 | File "<string>", line 2, in <lambda>
006 | File "<string>", line 2, in <lambda>
007 | [Previous line repeated 996 more times]
008 | RecursionError: maximum recursion depth exceeded
i forgor
!e ```py
orig_pr = builtins.print
print(hasattr(print, "code"))
print = lambda *x: orig_pr(*x)
print(print.code)
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | False
002 | (<code object <lambda> at 0x7fcc123258b0, file "<string>", line 3>,)
!e what about 👀
from einspect import view
v = view(sum)
t = type(v.ml.ml_meth)
v.ml.ml_meth = t(lambda *x: 50)
print(hasattr(sum, "__code__"))
print(sum(1, 1))
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | False
002 | 50
anyone knows how to get the pytransform runtime files from pyinstxtractor
i extracted all files of an exe with pyinstxtractor and then decompiled the main file with uncompyle6 the code is protected with pyarmor and i cant seem to find its runtime files in the folder which pyinstxtractor made
!e
stuff = iter([2, 4, 0, 1, 7, 3, 5])
input = lambda _: print(_) or next(stuff)
*I,r=7,0,5,2,4,6,3,8,1,range
d=lambda:"\n".join(' '.join(map(str,x))for*x,in zip(*[iter([i,*"xo"][b[i]]for i in I)]*3))
b=[p:=0]*9
while(e:=next((b[x]for x in r(9)for y in r(x)for z in r(y)if x+y+z==12and b[x]&b[y]&b[z]>0),69))>13>sum(b):
if b[o:=int(input(f'Player {p+1}, enter a cell:\n{d()}\n'))]<1:b[o],p=1+p,1-p
print(d()+("\nIt's a tie.",f'\nPlayer {e} wins!')[e<3])
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:7: SyntaxWarning: invalid decimal literal
002 | Player 1, enter a cell:
003 | 7 0 5
004 | 2 4 6
005 | 3 8 1
006 |
007 | Player 2, enter a cell:
008 | 7 0 5
009 | x 4 6
010 | 3 8 1
011 |
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/acobiwijuz.txt?noredirect
trying to make this the most unnecessarily complicated as possible
console = (lambda o:(setattr(o,"log",print))or o)(type("",(),{}))
console.log("i hate js")
I've re-framed the problem.
I now have a 2D numpy array, and an equivalent 2D mask.
However, if I try to use boolean indexing I get a 1D array.
Is there a way to keep the shape of the original array and mask and fill the "false" values with something?
Do you mean something like:
import numpy as np
a = np.arange(9).reshape(3, 3)
mask = np.array([[True, False, True], [False, True, False], [True, False, True]])
a[mask] = 0
I want a[mask] to somehow return a 3x3 matrix that would look like this:
0, -1, 3,
-1, 5, -1,
7, -1, 9
Hmmm, actually it's not even that
Now that I think about it, it's that my mask has at most 10 elements == True in each row
Sort of
My mask has at most 10 elements true, some rows have less.
I somehow want the output to have shape (n, 10), filled with invalid values when not
np.nonzero will help with this somewhat. But I don't know a good way to pad things like you want.
@noble locust The best way I can think of to do this is:
import operator
import numpy as np
a = np.arange(9).reshape(3, 3)
mask = np.array([[True, False, True], [False, True, False], [True, False, True]])
b = np.full((3, 2), -1)
for src_row, dst_row, nzs in zip(a, b, map(operator.methodcaller('nonzero'), mask)):
dst_row[:nzs[0].size] = src_row[nzs]
you want it to be -1 if the mask is False, otherwise you want the index?
i think you have the wrong channel
this still isn't the right channel
what you're looking for is #bot-commands
ah
yeah, this channel is for esoteric python
#bot-commands is for general bot stuff
or running commands that aren't specifically related to a channel
@low lynx
i tried this code in vsc but why this part marks me like an error := from b[o:=int(input(f'Player {p+....
yeah syrulol had that issue as well
it's a python version issue
i think
something along those lines
!epy globals().update({'console':type('console',(),{'log':print})}) console.log('...')
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
...
!e```py
globals().update({'cout':type('cout',(),{'lshift':lambda self,:(print(,end=''),self)[-1]})()})
cout << 'hello ' << 'world';
cout << '...';```
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world...
How?????
That's actually amazing.
!e```
class cin:
def rshift(self, _):
global x
j = input()
x = j
globals().update({"cin" : cin()})
x = None
cin >> x;
print(x)
@sick hound :x: Your 3.11 eval job has completed with return code 1.
:warning: Note: input is not supported by the bot :warning:
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 11, in <module>
003 | cin >> x;
004 | ~~~~^^~~
005 | File "/home/main.py", line 5, in __rshift__
006 | j = input()
007 | ^^^^^^^
008 | EOFError: EOF when reading a line
oh forgot
!e so this is fixed now with snekbox updating to einspect 0.5.12
from einspect import impl
@impl(int)
def __getitem__(self, item):
return self * item
x = 5
print(x[2])
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
10
what was the issue before?
the PyMethods allocation was just for subclasses and not all subclasses of subclasses
like adding __getitem__ here requires allocating tp_as_sequence / tp_as_mapping for int
since those fields previously were null
!e also TpFlags is a enum.IntFlag now
from einspect import view
print(repr(view(list).tp_flags))
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
<TpFlags.SEQUENCE|IMMUTABLETYPE|BASETYPE|READY|HAVE_GC|VALID_VERSION_TAG|MATCH_SELF|LIST_SUBCLASS: 38294816>
!e and the NULL singleton can now be used in more places, auto converting to the appropriately typed null value
from einspect import view, NULL
view(int).tp_as_number[0].nb_power = NULL
print(3 ** 85)
@dry mirage :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 5, in <module>
003 | print(3 ** 85)
004 | ~~^^~~~
005 | TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'int'
exciting
TypeView.__delitem__ will also remove existing methods with null and with the ability to restore them later
!e
from einspect import view
del view(int)["__pow__"]
print(3 ** 85)
@dry mirage :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 5, in <module>
003 | print(3 ** 85)
004 | ~~^^~~~
005 | TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'int'
!e
from einspect import view
del view(int)["__pow__"]
view(int).restore("__pow__")
print(3 ** 85)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
35917545547686059365808220080151141317043
can you use orig on view(sometype)["some_method"]?
hm? like how
orig(view(sometype)["some_method"])(args_to_some_method...)
something like that?
idk
like for non builtin types?
at all
yeah it works the same way
!e
from einspect import view, orig
class Foo:
def abc(self):
return 5
view(Foo)["abc"] = lambda s: 100
print(Foo().abc())
print(orig(Foo).abc(Foo()))
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 100
002 | 5
orig(<type>) gives you a view of that type before any modifications
mhm
oh hey i have an idea
you could store all changes to a type on a stack
and then the type can be accessed as any of its past states
well, maybe not all changes
but "high level" changes
such as using impl on it
or stuff like that
sorry for my stupid ideas. its well past when i should have gone to bed so my brain isn't functioning quite properly anymore
hm, how would you specify which past state though
good question
i hadnt thought that far ahead yet
i assume you'd want to support two separate ways though
index based and key based
since it'd be nice to do something like "i want the 4th state of this class" or "i want the -1th state (the most recent state) of this class"
and also "i want the state of this class right after X change was made to it"
both would be super useful to be able to do
might be interesting yeah 

!e
from einspect import view, orig
class Foo:
def abc(self):
return 5
view(Foo)["abc"] = lambda s: 100
print(Foo().abc())
print(orig(Foo)().abc())
print(orig(Foo).abc(Foo()))
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 100
002 | 100
003 | 5
only attribute calls are forwarded
__call__ is like running Foo() with the current one
ah
is there any way to get like
a copy of a class?
something like
class Bar(orig(Foo)):
that should be possible? haven't really thought of that use case
well i was thinking if you were to implement Herald's idea
would be nice to make copies of a base type to modify each copy to make new states
i have no clue how this stuff works tho so
I thought this would work but
seems like deepcopying a class does nothing lol
!e
from copy import deepcopy
class Foo:
pass
print(deepcopy(Foo) is Foo)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
it does not work
!e
from einspect import view, orig
o = orig(int)
class thing(o):
pass
@versed eagle :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | class thing(o):
004 | TypeError: orig.__new__() takes 2 positional arguments but 4 were given
over this weekend im going to try to implement the stack thingy
if i get it working i'll make a PR
oh I meant like I think it should be possible, currently not there
maybe you can override __init_subclass__
i'll look into it 👍
globals().update({'cin':type('cin',(),{'__rshift__':lambda self,inp:(globals().update({[i for i in __import__('inspect').stack()[-2][0].f_globals if id(inp)==id(__import__('inspect').stack()[-2][0].f_globals[i])][0]:input()}),self)[-1]})(),'cout':type('cout',(),{'__lshift__':lambda self,inp:(print(inp,end=''),self)[-1]})(),'cerr':type('cerr',(),{'__lshift__':lambda self,inp:(print(inp,end='',file=__import__('sys').stderr),self)[-1]})(),'endl':'\n'})
a = ''
b = ''
cout << "hello ";
cin >> a >> b;
cerr << a << b << endl;
Ig i should also add flushl
i rember this breaking with cin at some point
!e ```py
input = lambda *_: "hello chat"
globals().update({'cin':type('cin',(),{'rshift':lambda self,inp:(globals().update({[i for i in import('inspect').stack()[-2][0].f_globals if id(inp)==id(import('inspect').stack()[-2][0].f_globals[i])][0]:input()}),self)[-1]})(),'cout':type('cout',(),{'lshift':lambda self,inp:(print(inp,end=''),self)[-1]})(),'cerr':type('cerr',(),{'lshift':lambda self,inp:(print(inp,end='',file=import('sys').stderr),self)[-1]})(),'endl':'\n'})
a = None
b = None
cin >> b
print(b)
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
None
huh
Huh?
How is this possible because the code actually extract the var name given to cin.__rshift__ as parameter and then do globals().update({varname:input()})
as far as i can see, it just looks for the first variable that has the same content as given into rshift
which will break if you have 2 variables with the same content and pass one of them in
then the wrong var will be set in some cases
Hmm
Will fix that
I actually copied borrowed The varname extracting part of code from stackoverflow and then rewrote the code in single line
is this entry level for python coding
yes
cool help me install pygame cuz i installed it now i cant find it
i installed visual studio code
i installed python
i installed pygame snippets
whats next
im in kubuntu
so this is gona be annoying but ill learn eventually
tutorials on you tube dont clarify enough stuff and it mostly how to do it on windows
everything i found is based on outdated information so it never works the way it should
ok my concise is killing me
this is the weirdest channel here
just ask your question in general chat
no, this is for esoteric python.
also no.
that's cause it's for esoteric stuff
def add(x: int, y: int) -> int:
return x + y
@inline(funcs=True)
def sum(l: list[int]) -> int:
res = 0
for i in l:
res = add(res, i)
return res
assert sum([1,2,3]) == 6
dis(sum)
``` ```py
431 0 RESUME 0
433 2 LOAD_CONST 1 (0)
4 STORE_FAST 1 (res)
434 6 LOAD_FAST 0 (l)
8 GET_ITER
>> 10 FOR_ITER 11 (to 34)
12 STORE_FAST 2 (i)
435 14 LOAD_FAST 1 (res)
16 STORE_FAST 3 (_inline_x)
18 LOAD_FAST 2 (i)
20 STORE_FAST 4 (_inline_y)
22 LOAD_FAST 3 (_inline_x)
24 LOAD_FAST 4 (_inline_y)
429 26 BINARY_OP 0 (+)
435 30 STORE_FAST 1 (res)
32 JUMP_BACKWARD 12 (to 10)
436 >> 34 LOAD_FAST 1 (res)
36 RETURN_VALUE
def add(x: int, y: int) -> int:
return x + y
@inline(funcs=True)
def sum(l: list[int]) -> int:
res = {0: 0}
for i in l:
res[0] = add(res[0], (i + i) // 2)
return res[0]
``` this also works
currently it works only for functions with positional arguments, all of them must be provided in call
i am very happy
what's @inline?
from context clues I would assume its a function they wrote that looks for function calls in a wrapped function and attempts to inline the bytecode
fixed it
class str(str):
def __init__(self, _o=''):
super().__init__()
self._t = 0
for i in globals().values():
if isinstance(i, str) and i._t == self._t:
self._t += 1
globals().update({'cin':type('cin',(),{'__rshift__':lambda self,inp:(globals().update({[_ for _ in [(i if isinstance(_i,str) and _i._t==inp._t else ...) for i,_i in globals().items()] if _!=...][0]:str(input())}),self)[-1]})(),'cout':type('cout',(),{'__lshift__':lambda self,inp:(print(inp,end=''),self)[-1]})(),'cerr':type('cerr',(),{'__lshift__':lambda self,inp:(print(inp,end='',file=__import__(name='sys',fromlist=['stderr']).stderr),self)[-1]})(),'endl':'\n'})```
by overwriting str
a = str()
b = str()
cin >> b
print(repr(a), repr(b))```
(py311_venv) E:\co>py esoteric/cpp.py
fef
'' 'fef'
(py311_venv) E:\co>```
tho it still have point where it can break but fixed that one
[_ for _ in [(i if isinstance(_i,str) and _i._t==inp._t else ...) for i,_i in globals().items()] if _!=...]```now it looks for str._t which is different for every str init
made it shorter py globals().update({'cin':type('cin',(),{'__rshift__':lambda self,inp:(globals().update({[i for i,_i in globals().items()if isinstance(_i,str)and _i._t==inp._t][0]:str(input())}),self)[-1]})(),'cout':type('cout',(),{'__lshift__':lambda self,inp:(print(inp,end=''),self)[-1]})(),'cerr':type('cerr',(),{'__lshift__':lambda self,inp:(print(inp,end='',file=__import__(name='sys',fromlist=['stderr']).stderr),self)[-1]})(),'endl':'\n'})
by doing py [i for i,_i in globals().items()if isinstance(_i,str)and _i._t==inp._t]
I couldnt make the str class in single line
why?
super
it does nothing
there is no str.__init__ and object.__init__ does nothing
!epy print(dir(str))
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
There is str.__init__
!e print(str.__init__)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
<slot wrapper '__init__' of 'object' objects>
<slot wrapper 'init' of 'object' objects>
Ok
you'd need to call str.__new__(str)
then what is it exactly?
something you definitely don't want to explore as a python beginner
Whats __new__
it's the thing that returns an instance of your class before init gets called on it
This is the docs for it: https://docs.python.org/3/reference/datamodel.html#object.__new__
Hello
import math
i,j,r=int,math.dist,range(11)
print('\n'.join(''.join(' 0'[5==i(j(p:=(k,l),(5,5)))or i(j(p,(7,2)))==3]for k in r)for l in r))
What else could I shorten from this?
complex abs might be shorter idk
but it won't be circle anymore
''.join should be shortest
It looks so squarey now
i,j,r=int,abs,range(11)
print('\n'.join(''.join(' 0'[(j(k-5)+j(l-5)==5or j(k-7)+j(l-2)==3)]for k in r)for l in r))
what
that's not what I meant
!e
import math
k, l = 7, 4
print(math.dist((k,l),(5,5)))
print(abs(k+1j*l-5-5j))
those should be equivalent
@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 2.23606797749979
002 | 2.23606797749979
what does it do
it lets you work with complex numbers in python
abs calculates the modulus of a complex number
which is just its magnitude
which is the same as distance because of argand diagram
is % not modulus?
modulus has a different meaning here
does the complex number have a value?
yes
well complex numbers are just an extension of the real numbers
they have 2 parts the imaginary part and the real part
the numbers are you probably deal with are all technically complex numbers with no imaginary part
is it a constant like pi
that's modulo
Ohh
The basis of imaginary numbers is "i" (j in python) which is equivalent to the square root of -1
Complex numbers look like a + bi where a is a real number
and b is also a real number
^
is it actually a value of sqrt(-1) or is it just imaginary
the value of sqrt(-1) is i
its also -i :)
mhm
Why python errors
wdym
sqrt of -1 isn't allowed
In [3]: (-1) ** 0.5
Out[3]: (6.123233995736766e-17+1j)```i dont see any errors here
I mean math.sqrt(-1)
cause you need to use cmath for complex numbers
normal the normal math module only deals with real numbers
Hence "imaginary"
I don't know how complex numbers affect real numbers
!e
import cmath
print(cmath.sqrt(-1))
@languid night :white_check_mark: Your 3.11 eval job has completed with return code 0.
1j
Complex numbers are comprised of real numbers and imaginary numbers
Do imaginary numbers only ineract with each other?
a complex number is an imaginary number interacting with a real number
honestly for right now you can just think of complex numbers as two component vectors
so a+bj <-> (a, b)
and abs() is just the magnitude of (a, b)
and you can add them like (a, b) + (c, d) = (a+c, b+d)
is j*j = 1?
-1
Absolute is not just making numbers positive?
does cd also have an imaginary number?
think of them as real component vectors
you do not want to get into complex vector spaces before knowing what complex numbers are
do you know what a vector is?
I think it's a velocity?
not strictly, velocity can be represented as a vector
vectors are just something that encode dimensions into a neat little package
What is magnitude?
distance from your vector to the origin
say you had the vector (3, 4) and you plotted that on a graph youd have to go 3 on the x axis and 4 up on the y axis
single line and shorter
globals().update({'str':type('',(str,),{'__init__':lambda self,_o='':(self.__setattr__('_t',_:=0),[_:=_+1 for i in globals().values()if isinstance(i,str)and i._t==self._t],self.__setattr__('_t', _))[0]}),'cin':type('',(),{'__rshift__':lambda self,_:(self,globals().update({[i for i,_i in globals().items()if isinstance(_i,str)and _i._t==_._t][0]:str(input())}))[0]})(),'cout':type('',(),{'__lshift__':lambda self,_:(print(_,end=''),self)[-1]})(),'cerr':type('',(),{'__lshift__':lambda self,_:(self,print(_,end='',file=__import__('sys').stderr))[0]})(),'endl':'\n'})
the magnitude of the vector (3, 4) can be found by pythagoras's theorem and is 5
Does complex numbers bend spacetime in the graph or something
So pythagoreas' theorem is like absolute?
a = str()
b = str()
cin >> b;
print(repr(a), repr(b))```
(py311_venv) E:\co>py esoteric/cpp.py
blah
'' 'blah'
(py311_venv) E:\co>```
complex numbers are related to spacetime but that's irrelevant to this conversation rn
all you basically need to know is that complex numbers act like 2d vectors
to find the absolute value of a complex number (which can be represented on a graph with the real components on the x axis and the imaginary component on the y) you can use pythagoras to find the length of the hypotenuse ie the distance from the origin
!e
input = lambda: "test string"
import sys, dis
def get_load(code, lasti):
for i, (op, oparg) in enumerate(zip(
code.co_code[:lasti+1][::-2],
code.co_code[:lasti+2][::-2]
)):
op = dis.opname[op]
match op:
case "LOAD_NAME":
return ((op, code.co_names[oparg]),)
case "LOAD_GLOBAL":
return ((op, code.co_names[oparg>>1]),)
case "LOAD_FAST":
return ((op, code.co_varnames[oparg]),)
case "LOAD_CLOSURE":
return ((op, code.co_fastlocalnames[oparg]),)
case "LOAD_ATTR":
return code.co_names[oparg], *get_load(code, lasti - i*2 - 2)
@type.__call__
class cin:
def __rshift__(self, o, b=[]):
if b:
v = b.pop(0)
else:
v, *e = input().split()
b.extend(e)
f = sys._getframe(1)
*a, m = get_load(f.f_code, f.f_lasti)
match m[0]:
case "LOAD_GLOBAL":
d = f.f_globals
case "LOAD_FAST":
d = f.f_locals
case "LOAD_CLOSURE":
d = f.f_locals
case "LOAD_NAME":
if m[1] in f.f_locals:
d = f.f_locals
elif m[1] in f.f_globals:
d = f.f_globals
else:
d = f.f_builtins
if a:
_, l, *a = d[m[1]], *a
while a:
_ = getattr(_, a.pop())
setattr(_, l, v)
else:
d[m[1]] = v
return self
n = 1
cin >> n
print(n)
class T:
def __init__(s):
s.a = 1
t = T()
cin >> t.a
print(t.a)
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | test
002 | string
bytecode parsing is fun
good now example how get_load works
what I am doing is overwriting str class to have different ids on every init
get_load parses the bytecode to find the most recent LOAD_* instruction and then returns the name that was loaded and the type of load that happened
i skipped a few of the LOAD_* instructions that i thought probably wouldn't be relevant though
and I sucked up```
(py311_venv) E:\co>py esoteric/cpp.py
a
b
'b' ''
(py311_venv) E:\co>``````py
a = str()
b = str()
cin >> a >> b;
print(repr(a), repr(b))```
fails on 2 var store
im fairly sure that mine also fails
for 2 or more vars
but i haven't actually tested it
absolute number of complex number is a vector on graph, pythagoras to get distance from the origin
Absolute number = distance from origin
Pythagoras is a way to get distance from origin
cin >> b
cin >> a```this works
but not this```py
cin >> a
cin >> b```
You turned the coordinates into vectors?
yes in the form of complex numbers
Then did this?
guess this happens due to ids
Did you convert it back into real?
I used abs() to get the magnitude
using absolute?
using abs()
Are the complex numbers there because you converted the coordinates into a vector?
Oh wait you said that
if you assign 2 str() together it might be the same object
Okay
yeah tried printing their ids they become same
Thank you
you'd have to find the callers dict and look for the variable by name and not identity
callers dict?
yeah, like locals() or globals()
and How I am gonna get variable name from in cin.__rshift__
@dry mirage
hm
there are some ways I can think of
non fully works likely
for one there might be no variable at all
like if you did cin >> func()
well target is not about that
target is updating global values of vars in globals given as parameter to cin.__rshift__
I want to learn some cursed python
also have you tried to see if this works in function scopes
def func():
x = None
cin >> x
print(x)
ionite
does that work
not gonna I know
because I didn't made it to work on locals
doesn't seem so
I think function variable lookups don't actually go into a dict lookup if it wasn't materialized
things like exec() or locals() will materialize the function dict
wdym
I'm not even sure
trying to find out more
basically assigning to a variable in the caller when the caller is in a function
assigning to f_locals in functions seems to silently fail
aw
or rather, has no effect
!e
def func():
x = 5
locals()["x"] = 100
return x
print(func())
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
5
local vars skip dict lookup it seems
You can use a trace function to set variables in the locals dictionary

When the trace func ends it copies all the values from the locals dictionary into the actual frame locals array
Look into sys.settrace
is f_locals not the actual one?
weird
No prob
Later when I am home I'll send my set locals code that works transparently
can you settrace after the function already started
You can settrace on a frame selectively (frame.f_trace), as long as you do it from a trace function
Yea, you need to use a global trace to set your lower traces
I wrote an implementation a while ago, I'll send it later when I'm on my laptop
!e
import inspect
from sys import settrace, gettrace
def set_caller(name, value):
frame = inspect.stack()[2].frame
def _trace(frame, event, arg=None):
frame.f_locals[name] = value
if gettrace() is None:
settrace(lambda *args: None)
frame.f_trace = _trace
def modify():
set_caller("n", "hello")
def func():
n = 100
modify()
return n
print(func())
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello
the what
!e ```py
import inspect
print(inspect.stack()[0].frame.f_trace)
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
None
!e ```py
def make_locals():
import sys
to_update = {}
def locals():
frame = sys._getframe(1)
return to_update.setdefault(frame, {**frame.f_locals})
def tracefunc(frame, what, arg):
if frame in to_update:
for key in frame.f_locals.copy():
if key not in to_update[frame]:
del frame.f_locals[key]
for key, val in to_update[frame].items():
if key not in frame.f_locals or frame.f_locals[key] != val:
frame.f_locals[key] = val
del to_update[frame]
return tracefunc
sys.settrace(tracefunc)
return locals
(builtins if isinstance(builtins, dict) else builtins.dict)['locals'] = make_locals()
def foo():
a = 1
locals()['a'] = 2
print(a)
foo()``` @dry mirage this is the implementation I wrote a while ago
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
its not perfect tho, I might rewrite it so you can hold onto the mapping returned by locals() to perform further mutations (right now you cannot)
what's the del keys doing 
It makes it so del locals()['a'] works
why not just ctypes.pythonapi.PyFrame_LocalsToFast(frame, 0)
Doesn't quite work as expected when called from python code if I remember correctly
works for basic examples at least
!e ```py
import ctypes
import sys
ctypes.pythonapi.PyFrame_LocalsToFast.argtypes = ctypes.py_object,
def f():
frame = sys._getframe(0)
x = 0
frame.f_locals['x'] = 100
ctypes.pythonapi.PyFrame_LocalsToFast(frame, 0)
print(x)
f()```
@lunar marsh :white_check_mark: Your 3.11 eval job has completed with return code 0.
100
It probably changed a bit from 3.8 then which is the last time I tried to use it
Previously the f_locals would get refreshed between the update and the api call
Actually might have been 3.7 it's been a while
what the fuck
god i love python
hm strange, nonlocals still show up in frame.f_locals
You don't need to know the defining frame of a nonlocal, you can just grab the cell and change it there
it's not in frame.f_code.co_varnames though
the cell affects the upper variable?

Yea that's how nonlocal variables work
All frames hold a reference to the same cell
chilaxan is python god
you'd still have to know its a nonlocal to use the cell right?
or is it also valid for setting normal and globals
You'd need to know it was nonlocal I think?
seems hard to differentiate nonlocal and global though
I'll work on a way
i might be a bit late but you can do inline imports
__import__(module).function()
it's longer for code golf
import module;module.func()
import module as m;m.func()
__import__("module").func()
from module import*;func()
the first one scales doubly with the module name so it can be better for e.g. re
Ohh thanks
if you do one line you can't really do it any other way tho
unless you count semicolons
I genuinely think I can't shorten this anymore
k,i,a=0,int,abs;exec("print(' 0'[i(a((p:=k/11+1j*(k%11))-5-5j))==5or i(a(p-2-7j))==3],end='\\n'*(k%11<1));k+=1;"*121)```
from the 5or
also why are you doing two backslashes on \n
oh
i see
you could try a list comp but idk if it would be smaller
that's what i usually use for this sort of thing
idk maybe it's just me being paranoid about exec()
what are you trying to do anyway?
if it's just a rendering thing you could probably store the data using binary
I don't know how to store stuff in binary with even less code
Wait
think I can shorten this more
I used exec because it's smaller
k,a=0,abs;exec("print(' 0'[a((p:=k/11+1j*(k%11))-5-5j)//1==5or a(p-2-7j)//1==3],end='\\n'*(k%11<1));k+=1;"*121)```
Oh wait it's smaller if I don't use abs like that
k=0;exec("print(' 0'[abs((p:=k/11+1j*(k%11))-5-5j)//1==5or abs(p-2-7j)//1==3],end='\\n'*(k%11<1));k+=1;"*121)```
It's for a calculation
ah
store it as a character
Represent the image in binary using text and the print it?
basically yes
well
you convert the binary as a number into the corresponding character
Okay wait I could probably create a better image If I do that
i'd recommend generating the characters using another script and then putting them in
im trying it and converting unfortunately seems to mess up some stuff
aliasing a function is only viable when more than one call to it is made
everything else is shorter not to alias
Yeah,I counted with alias and with none
print.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__('Hello World')
repeat as much as you wish to
no limit
as long as you can make something more complicated than it already is, there's no limit
(you can always make things more complicated)
and how to do it without using print
the 11 is the return value of write()
that's why "longest way to do X" is usually not a good goal without other constraints
"most obfuscated" isn't well defined either, but at least it allows for some more interesting ideas to be put forth
one "more complicated" way to type print("hi"): getattr(__builtins__, "print")("hi")
you can expand this even further
there is no limit
fun thing about obfuscating is that you can basically pick any part of the code and obfuscate it further
tho that's more just surface level obfuscation
!epy __builtins__.__getattribute__('__import__').__call__('sys').__getattribute__.__call__('__stdout__').__getattribute__.__call__('write').__call__('Hello, world!')
@arctic skiff :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | __builtins__.__getattr__('__import__').__call__('sys').__getattr__.__call__('__stdout__').__getattr__.__call__('write').__call__('Hello, world!')
004 | ^^^^^^^^^^^^^^^^^^^^^^^^
005 | AttributeError: module 'builtins' has no attribute '__getattr__'
wait what?
!e __builtins__.__getattribute__("__import__")("sys").__getattribute__("stdout").write("hello chat\n")
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello chat
ohh its attribute
!epy __builtins__.__getattribute__('__import__').__call__('sys').__getattribute__.__call__('__stdout__').__getattribute__.__call__('write').__call__('Hello, world!')
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, world!
!e exec(type((lambda:0).__code__)(0, 0, 0, 0, 1, 0, b'\x97\x00t\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00d\x01\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00d\x00S\x00', ("hi chat",), ("print",), (), "", "", "", 0, b"", b""))
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
<K object at 0x7ff20d35fdf0>
interesting
co_consts index out of range
oh right
!e ```py
exec(type((lambda:0).code)(0, 0, 0, 0, 1, 0, b'\x97\x00t\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00d\x01\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00d\x00S\x00', (None, "hi chat"), ("print",), (), "", "", "", 0, b"", b""))
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
hi chat
although what's a K object? 🤔
no idea
sounds like an arbitrary thing
!e ```py
exec(type((lambda:0).code)(0, 0, 0, 0, 1, 0, b'\x97\x00t\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00d\x01\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00d\x00S\x00', ("hi chat",), ("print",), (), "", "", "", 0, b"", b""))
!e ```py
a=eval(type((lambda:0).code)(0, 0, 0, 0, 1, 0, b'\x97\x00d\x00S\x00', (), (), (), "", "", "", 0, b"", b""))
dir(a)
oof
!e ```py
a=eval(type((lambda:0).code)(0, 0, 0, 0, 1, 0, b'\x97\x00d\x01S\x00', ("hi chat",), ("print",), (), "", "", "", 0, b"", b""))
dir(a)
!e ```py
exec(type((lambda:0).code)(0, 0, 0, 0, 1, 0, b'\x97\x00t\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00d\x01\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00d\x01S\x00', ("hi chat",), ("print",), (), "", "", "", 0, b"", b""))
!e ```py
a=eval(type((lambda:0).code)(0, 0, 0, 0, 1, 0, b'\x97\x00t\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00d\x01\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00d\x01S\x00', ("hi chat",), ("print",), (), "", "", "", 0, b"", b""))
@quartz wave :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
can you like not
ye i'm going to #bot-commands
the number of characters written to stdout
!e
__builtins__.__getattribute__('__import__').__call__('sys').__getattribute__.__call__('__stdout__').__getattribute__.__call__('write').__call__(__builtins__.__getattribute__.__call__('int')("0110100001101001", 2).to_bytes((__builtins__.__getattribute__.__call__('int')("0110100001101001", 2).bit_length() + 7) // 8, 'big').decode())
@weak imp :white_check_mark: Your 3.11 eval job has completed with return code 0.
hi
Trying to make this looks more esoteric
!e
__builtins__.__getattribute__('__import__').__call__('sys').__getattribute__.__call__('__stdout__').__getattribute__.__call__('write').__call__(__builtins__.__getattribute__.__call__('int')("0110100001101001", 2).__getattribute__.__call__("to_bytes")((__builtins__.__getattribute__.__call__('int')("0110100001101001", 2).bit_length() + 7) // 8, 'big').decode())
@weak imp :white_check_mark: Your 3.11 eval job has completed with return code 0.
hi
!e
__builtins__.__getattribute__('__import__').__call__('sys').__getattribute__.__call__('__stdout__').__getattribute__.__call__('write').__call__(__builtins__.__getattribute__.__call__('int')("0110100001101001", 2).__getattribute__.__call__("to_bytes")((__builtins__.__getattribute__.__call__('int')("0110100001101001", 2).bit_length() + 7) // 8, 'big').__getattribute__.__call__('decode'))
Huh

Bot died
It's some arbitrary address rendered as a pyobject that happens to have a pointer at addr + 8 and that pointer happens to have a pointer to a char array where tp_name would be
Possibly a legitimate object that was deallocated and partially overwritten

