#esoteric-python
1 messages ยท Page 126 of 1
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (input)
002 | 2 CALL_FUNCTION 0
003 | 4 STORE_NAME 1 (s)
004 | 6 LOAD_CONST 0 (None)
005 | 8 RETURN_VALUE
note how that's 10 bytes, not four
without remembering the previous examples, here's what I did for cout
!e
c = lambda cls: cls()
@c
class std:
def __getitem__(self, name):
return name.step
@c
class cout:
def __lshift__(self, data):
print(data, end='')
return self
endl = '\n'
# include <iostream>
a = 2
b = 502
std[::cout] << a << b << std[::endl]
@near gust :white_check_mark: Your eval job has completed with return code 0.
2502
yeah... cin will be a lot weirder
globals modification
add missing to the dict of builtins such that a sentinal is returned
actually no
use c style type declarations
then an unassigned but declared variable can be a sentinal value to become a string when inputted to
Just use Java at this point
Python 3.9.6 (default, Jun 29 2021, 06:20:32)
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import enable_cin
>>> x = cin
abc
>>> x
'abc'
>>> cin >> y
foo
>>> y
'foo'
>>> print(cin)
bar
bar
>>> class a:pass
...
>>> cin >> a.b
test
>>> a.b
'test'
>>> ```
@floral meteor @near gust got it working
basically, cin by itself is now equal to input() and cin >> a stores the input into a
one sec imma make cin >> a[0] work
But what about cin.getline()
Python 3.9.6 (default, Jun 29 2021, 06:20:32)
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import enable_cin
>>> cin >> a
foo
>>> a
'foo'
>>> class b:pass
...
>>> cin >> b.b
bar
>>> b.b
'bar'
>>> x = []
>>> cin >> x[:]
chilaxan
>>> x
['c', 'h', 'i', 'l', 'a', 'x', 'a', 'n']
>>> ```
cin.getline() is impossible due to parameters not being passed by reference, but by value
Impressive!
cin.getline() has 2 parameters, the first one being the memory where the characters should be written to, and the second one being the number of characters to read
example in c++
using namespace std;
// Driver Code
int main()
{
char name[5];
// Reads stream of 3
// characters
cin.getline(name, 3);
// Print output
cout << name << endl;
return 0;
}
my code gets called into when LOAD_NAME occurs, so i can get the name i need to assign to from the bytecode before it fails
nice
!e ```py
from ctypes import py_object, c_char
import atexit, builtins, sys, dis
frame = sys.getframe()
while frame != None:
ob_base_p = py_object.from_address(id(frame.f_globals) + 8)
class cin_hook(dict):
slots = ()
def missing(self, key, ob_base_p=ob_base_p, builtins=builtins):
try:
ob_base_p.value = builtins.dict
if key == 'cin':
frame = sys.getframe(1)
f_code = frame.f_code
load_idx = shift_idx = frame.f_lasti + 2
while f_code.co_code[shift_idx] != dis.opmap['BINARY_RSHIFT']:
shift_idx += 2
if shift_idx >= len(f_code.co_code):
return input()
last_load = shift_idx - 2
instr = dis.opname[f_code.co_code[last_load]].replace('LOAD', 'STORE')
if instr == 'BINARY_SUBSCR':
instr = 'STORE_SUBSCR'
mem = (c_char * len(f_code.co_code)).from_address(id(f_code.co_code) + bytes.basicsize - 1)
mem[last_load] = dis.opmap[instr]
mem[shift_idx: shift_idx + 2] = bytes([
dis.opmap['LOAD_CONST'], f_code.co_consts.index(None)
])
return input()
return builtins.dict[key]
except KeyError as e:
raise NameError(f'name {e.args[0]!r} is not defined') from None
finally:
ob_base_p.value = class
ob_base_p.value = cin_hook
frame = frame.f_back
def input():
return 'static value'
print(cin)
cin >> x
print(x)
y = [0]
cin >> y[0]
print(y)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | static value
002 | static value
003 | ['static value']
@floral meteor ^ source
noice
this is literally identical to my code, wow!
this is... insane
thank you for the music
yw
nested bytecode modification is a beast
I can't seem to get it to work correctly
I'll try to make my own
I need to learn bytecode some way
Slightly off-topic, but I've always wondered what the +8 means in the expression
ctypes.py_object.from_address(id(_)+8)
the __class__ of _
What is the most simple way to use ctypes to swap IDs that references hold? (ping on reply please)
i.e.
def my_print():
sys.stdout.write("booya")
id(print) <- id(my_print)
print() calls my_print()
you cannot do that in a safe way
the first 8 bytes of an object are the reference count
the second 8 are a pointer to the objects __class__
How would I do it? and what are the possible issues
You can't do that in general, since there's no way to find all values pointing to another. You'd have to loop through the entire memory space, searching for matches, and then somehow guess if the match is actually the pointer, or simply a coincidence...
I'm not sure if I understand, would I only not need to get where the name print points to (the built-in print method) and change that pointer to a different method?
Something like this for example changes references;
print = my_print
how'd that work with ctypes?
That changes a single reference, in your module - not anywhere else people might have stored the print function.
You could set builtins.print, so regular lookup will get it - but that won't modify the object itself.
Yeah, I suppose, does print have different references in different modules?
Well probably not many given it's available as a global.
But in general you can't really.
So there's no way to modify a built-in or any function through modification of it's pointer?
You can yes, you'd need to swap the pointer inside the print object.
oh okay, how does one do that then?
Well, you'd need to look at the C struct defining builtin functions, create your own C-function that can be called with the same signature (there's several different ways arguments can be passed), and then overwrite the pointer...
Ah that seems quite tedious, can I tell you the usecase?
Yeah, there's probably an easier method.
So I've made a decorator that gives class* methods a marker, and that marker is checked during object creation with __new__, and then it predicates the method that has that marker, and the reason why I'm doing it on obj creation because It's required to be a bound method. The problem comes when we're dealing with properties, I tried to override fget and setting a getter but both of them are readonly
What's wrong with properties then?
I don't see why that needs overriding the class.
well, what's wrong is that I cannot override it's fget for predication
(or whichever function it calls for the matter)
You can just make a copy of the property with a new getter, then put that back in the class.
Or define your own descriptor class.
I'm confused as to how I would get the bound method for it's getter function
I can't really access them after instantiation because that gives me the return of the property
wdym?
Access via class, and you get the property, then you have the original function as the fget attribute.
Maybe post your code or portion thereof?
Right, but how would that be a bound method?
It isn't, but you can just bind it yourself.
partialize it I guess?
yep here
Yeah.
def __new__(cls, *args, **kwargs):
r"""
Check attributes on object creation to predicate asset caching function.
This must be done in order to resolve string names and cache dict occupation based
on instances and not type based.
If we don't do this, the calls from different instances of the same type will
be convoluted into a singular name space.
"""
obj = super().__new__(cls)
for item_name in dir(obj):
item = getattr(obj, item_name, None)
if callable(item):
is_liable = getattr(item, '__getliables__', False)
if is_liable is not False:
primer = item.__getliables__()
__getliables__ = lambda: [eval(src, {"self": obj}) if isinstance(src, str) else src for src in primer]
setattr(obj, item_name, AssetCached.__predicate__(item, __getliables__))
return obj``` so this is how im looping through the instance attributes, i suppose i can do the same by `dir(cls)`?
let me try that rq!
But this works:
class cin:
def init(self, text):
self.text = text
self.data = input(getattr(self, "text"))
def __rshift__(self, name):
self.name = name
globals()[getattr(self, "name")] = getattr(self, "data")
def __repr__(self):
return str(getattr(self, "value"))
cin("test: ") >> "a"
cout << a
$ python source.py
test: 1
1```
Use vars(cls), that gives back the class __dict__ - the dictionary holding all the attributes.
oh okay, so I can just loop through its items
Yeah.
can i do the same with obj the instance?
Yes (if it doesn't have __slots__ defined), but it'll give you just the raw object's attributes - you in both cases have to go up the class hierarchy yourself.
You do probably want to know how descriptors work BTW, since it's how functions get their self parameter and properties function - if you do this you'll likely want to call it to handle that manually.
Sure, i'll look it up!
Nice guide here: https://docs.python.org/3/howto/descriptor.html
The trick is that when an attr is defined on the class, whenever it's accessed __get__, __set__ or __delete__ is called to do what it wants instead.
So functions have __get__ defined to produce bound method objects when called on the object, classmethod produces a bound method always with the class instead, staticmethod disables this, and property calls your provided functions.
Oh, so would it be fair to say that it's just instance.func_name.__get__(instance)? and that function will have the first arg stitched
so when we have properties the __get__ calls the getter or fget in this case
The signature is __get__(self, instance, owner) - owner is the class, instance is the instance, or None if accessed via the class.
property just returns self if owner is None, so you can access the property object via MyClass.prop.
gotchu, so the instance is passed down to the returning function as some sort of a partialized method?
Yeah, types.MethodType has the function and instance as attributes, then when called combines it.
Seems like there's no chance in overriding __get__ either, it's all read-only, making a new property does seem to work
gotchu
for item_name, item in vars(cls).items():
if isinstance(item, property):
# __getliables__ is a marker that this function is decorated
is_liable = getattr(item.fget, '__getliables__', False)
if is_liable is not False:
primer = item.fget.__getliables__()
__getliables__ = lambda: [eval(src, {"self": obj}) if isinstance(src, str) else src for src in primer]
setattr(cls, item_name, property(AssetCached.__predicate__(item.fget, __getliables__)))
``` works great, tysm teamspen210
!e
exec(type((lambda: 0).__code__)(0, 0, 0, 0, 0, 0, b'\x01', (), (), (), '', '', 0, b''))
@near gust :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
Yep works
If you can't tell, this tries to evaluate the POP_TOP instruction when there's nothing on the stack and segfaults the interpreter. Or so I think. I'm still new to bytecode
Can't believe I got the number of zeroes right first try
I wonder what is the shortest code that can be used to segfault the interpreter
Because simplifying that to use unpacking there gives
!e
exec(type((lambda: 0).__code__)(*(0,)*6, b'\x01', *((),)*3, '', '', 0, b''))
@near gust :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
!e
print( len(
"exec(type((lambda: 0).__code__)(*(0,)*6, b'\x01', *((),)*3, '', '', 0, b''))"
))
@near gust :white_check_mark: Your eval job has completed with return code 0.
73
73 chars
ctypes can dereference null pointers easily
Oh wait...
!e
from ctypes import *
p = pointer(c_int.from_address(5))
p[0]
@near gust :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
!e
s =
"""
from ctypes import *
p = pointer(c_int.from_address(5))
p[0]
"""
print (len(s))
Oops
!e
s ="""
from ctypes import *
p = pointer(c_int.from_address(5))
p[0]
"""
print (len(s))
@near gust :white_check_mark: Your eval job has completed with return code 0.
63
Shorter somehow
ctypes.string_at
@near gust :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
Added json thingie
>>> dict() << "test" >> (var() == (json("dumps") >> {"a": 3}))
>>> cout << test << type(test)
{"a": 3}<class '__main__.var'>```
May be useful for obfuscation
@floral meteor :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | '' = ()
003 | ^
004 | SyntaxError: cannot assign to literal
@floral meteor :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | {} = ()
003 | ^
004 | SyntaxError: cannot assign to dict display
!e ```py
[] = ()
print([])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[]
!e ```py
() = [] = () = ''
print((),[])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
() []
!e ```py
() = [] = set()
print('why does this even exist?')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
why does this even exist?
!e
!e import('dis').dis("[] = ()")
@astral rover :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (())
002 | 2 UNPACK_SEQUENCE 0
003 | 4 LOAD_CONST 1 (None)
004 | 6 RETURN_VALUE
!e import dis;dis.dis('[] = ();a')
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (())
002 | 2 UNPACK_SEQUENCE 0
003 | 4 LOAD_NAME 0 (a)
004 | 6 POP_TOP
005 | 8 LOAD_CONST 1 (None)
006 | 10 RETURN_VALUE
you can see that [] = () generates 2 instructions, a LOAD_* for the right hand side, and an UNPACK_SEQUENCE. If there are names on the left hand side you will see the UNPACK_SEQUENCE will have an argument equal to the number of names, and an equal number of STORE_* after it
I'm learning how to actually write code using bytecode
So far the results have been
segfault
segfault
not enough positional args
I might want to try to make an entire module using bytecode. Anyone have tips or obscure docs I can have?
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
in class:```py
a = 1
homework:```py
[] = []
the test:```py
[*[[]]], *[[]] = [[], []], [[]]
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
!e
[*[[]]], *[[]] = [[], *[]], [*[]]
@dire yew :warning: Your eval job has completed with return code 0.
[No output]
>>> *[],
()
>>> type(*[],)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: type() takes 1 or 3 arguments
>>> type(())
<class 'tuple'>
!e
from ctypes import *
def foo(x):
print(id(x))
d = pointer(py_object.from_address(id(x)))
print(d[29])
a = ''
foo(a)
@near gust :white_check_mark: Your eval job has completed with return code 0.
001 | 140509237966448
002 | <class 'EncodingMap'>

!e
from ctypes import *
def foo(x):
print(id(x))
d = pointer(py_object.from_address(id(x)))
for _ in range(20,30):
print(d[_])
a = ''
foo(a)
@simple crystal :x: Your eval job has completed with return code 139 (SIGSEGV).
140353205614192
ah found it
Objects/unicodeobject.c lines 8422 to 8424
static PyTypeObject EncodingMapType = {
PyVarObject_HEAD_INIT(NULL, 0)
"EncodingMap", /*tp_name*/```
!e
from ctypes import *
def foo(x):
print(id(x))
d = pointer(py_object.from_address(id(x)))
print(d[83])
a = ''
foo(a)
@near gust :white_check_mark: Your eval job has completed with return code 0.
001 | 140359462016624
002 | <class 'member_descriptor'>

isnt that java?
o i thought static n stuff like that was java
Java's definition of static is really different from C's definition of static, they're both completely different things with the same name
doesnt static mean like non changing
I think that's what happens when you make a static variable in a function, usually as soon as the functions stops running, the stack frame of the function is erased, as with the variable, so it no longer exists, however if the variable is static, it doesn't get erased and it lives after the function stops running
This has to be one of the stupidest things I've done
!e
from ctypes import *
class g(int):
def __add__(self, x):
return g(x)
def foo(obj):
p = cast(c_void_p(id(obj)), POINTER(py_object))
print(p[1])
p[1] = g
a = 69
foo(a)
print(a+69420+123)
@near gust :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | <class 'int'>
002 | 123
It's a good example of how you can just throw in subclasses sometimes when you're bored
LOL!
try print(executable.b)?
the copy that is running has a __name__ of __main___ the copy that you imported and stole the vars from has a __name__ of executable
I was a little surprised that you can mod the vars() copy and it have an effect on the module's globals, thanks for teaching me.
They sort of are 'compiled' first, in the sense that the interpreter runs through them and saves all the defined classes and defs into the module, and then that module is saved in /pycache/ for later.
Hence why your executable.py prints 2 twice, then stops, rather than have an infinite recursion.
You could put ```py
if name=='main':
#some code here
else:
#some code here
#executable.py
import executable
a = vars(executable)
a['b'] = 2
print(__name__, executable.b)
the output I get is:
executable 2
__main__ 2```
I'm on python3.8.10 if that makes a difference...
cool!
Nope, I'm wrong, it doesn't compile the way I said, actually compiles the whole imported file to byte code. Saves it, to pycache, then runs it and links the module's stuff into sys.modules or wherever.
import __main__
that's how you get the mutable namespace
!e ```py
_0, _1, _2, _3 = vars, import('main'),'a',5;
a = 2 + 2;
_0(_1)[_2]=_3;
print (a);
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5
!e
print('hi')
You know how we were doing python with c++ syntax like a day ago and trying to get cin to work?
std[::cout] << 'help'
Well, I realized that you don't need to manipulate bytecode. Instead, you just need a python C function with 2 parameters. You can either swap the pointers to the 2 objects (recommended) or just set the pointer of one object to be the pointer of the other. I'm not sure if the second one would cause problems with the garbage collector
@near gust explain?
One sec. I'll test my theory when I get home in a few minutes
Did you test it?
Didn't work because I couldn't figure out how to do it correctly
Well what were you trying to do
!e
print('hi')```
Hii
hi
Isn't this enough?
class cin:
def __init__(self, text):
self.text = text
self.data = input(getattr(self, "text"))
def __rshift__(self, name):
self.name = name
globals()[getattr(self, "name")] = getattr(self, "data")
def __repr__(self):
return str(getattr(self, "data"))
a = cin("test: ")
cin("test: ") >> "b"
cout << a << b```
str() << "a" >> (var() == cin("test: "))
cout << a```
ValueError: call stack is not deep enough
I'm using black python code formatter
So likely it's PEP
idk
From pep8
In Python, single-quoted strings and double-quoted strings are the same. This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.
Most people use "" though
and I believe the default for stuff like repr() is ""
!e print(repr('test'))
@distant wave :white_check_mark: Your eval job has completed with return code 0.
'test'

@distant wave :white_check_mark: Your eval job has completed with return code 0.
'test'
Can we just appreciate that the abbreviation for "Python Object-Oriented Programming" is POOP
That won't always work
#procedure name
proc("test") << (
{"test": "a"}, #procedure local variables
{"a": lambda locals, globals, args, **self: (locals, globals, args, self)} #procedure local functions
) >> (
{"a": { #arguments for each procedure function
"d": {"value": 40},
"g": {"value": "h"}
}}
)```
Contribute to this you demons
I think you guys might like the second part of this SO answer: https://stackoverflow.com/a/19083442/2846495
Making a custom list "literal" ๐
literals cannot be overridden, use your own type 
literals can't be overridden but you can emulate custom ones with operator overloads 
literals can and should be overridden 
!e ```py
a = 1
b = 1
print(a is b is 1 is 1)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:3: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | True
that means...
!e ```py
a = 1
from ctypes import*
py_object.from_address(id(1)+8).value = float; print(1)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5e-324
behold, ye nerds, and despair, literals can and should be overridden
In this server, everyone calls me Fatal.
cos I'm fatal to python ;)
!e ```py
a = 69
from ctypes import*
py_object.from_address(id(69)+8).value = str; print(69 + 69)
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | 138
002 | free(): invalid pointer
wat the
!e ```py
a = 69
from ctypes import*
py_object.from_address(id(69)+8).value = str; print(a + 69)
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | ValueError: character U+d41f4980 is not in range [U+0000; U+10ffff]
004 | free(): invalid pointer
wat theeeee
!e ```py
a = 69
from ctypes import*
py_object.from_address(id(69)+8).value = str; print(a + a)
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | ValueError: character U+7e778980 is not in range [U+0000; U+10ffff]
004 | free(): invalid pointer
to U+d41f4980 or to U+7e778980 that is the question
Heh.
def cast_to_float(n: int):
ctypes.py_object.from_address(id(0)+8).value = float
return n
you would need to allocate more memory and move it there
it's a macro
so not a function that gets exported, just something that gets replaced with other code
you could look at the source to see what the macro does and recreate that with ctypes
Include/pymem.h lines 77 to 79
#define PyMem_Resize(p, type, n) \
( (p) = ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \
(type *) PyMem_Realloc((p), (n) * sizeof(type)) )```
NTSTATUS_MEMORY_ACCESS_VIOLATION
you've violated it
if you open
control panel > System > security and maintenance > view reliability history
you will find that this has impacted the reliablity of your pc
It is a critical application failure
yes
red x on python.exe
exception code 0xc0000005
some exception offset
a few more details about python and how you violated it
most of it is numbers
It's sad that I've sent a rickroll .exe file to many friends and all of them fell for it
Was it written in Python?
yes
I think I'm gonna make a virus that scrapes your email and emails you a bunch of resources about internet safety
Because my friends are idiots
Python objects (known as PyObject in C) are only made of 2 elements, a reference count and a type object, which is also a python object
The type object can be found with id(obj) + 8
This only applies to the CPython implementation
#internals-and-peps message
figured I'd link it here since it could constitute under esoteric ness
yes
.bm
noice
@sick hound :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | Fatal Python error: death.py activated
002 | Python runtime state: initialized
003 |
004 | Current thread 0x00007f2f6b3b7740 (most recent call first):
005 | File "<string>", line 16 in <module>
@sick hound :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | <class 'int'>
002 | (<class 'type'>, <class 'int'>)
003 | (<class 'int'>, <class 'int'>)
004 | (<class 'int'>,)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
(<class 'object'>,)
huh
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'enhanced'
I'm gonna leave this challenge here again since it went ignored last time but make it so that when you create a variable if you use the variable name backwards it'll use the reverse of the value python abc = "hello" de = 12 cba # olleh ed # 21
!e ```py
import gc
class proc:
def init(self,name):self.=name;self.__=getattr(self,"");del self.;self.=getattr(self,"");del self.;self.=getattr(self,"");del self.;self.name=getattr(self,"");del self.
def lshift(self,main):self.=main;self.__=getattr(self,"");del self.;self.=getattr(self,"");del self.;self.=getattr(self,"");del self.;self.main=getattr(self,"");del self.;self.=getattr(self,"main")[0];self.__=getattr(self,"");del self.;self.=getattr(self,"");del self.;self.=getattr(self,"");del self.;self.locals=getattr(self,"");del self.;self.=globals();self.__=getattr(self,"");del self.;self.=getattr(self,"");del self.;self.=getattr(self,"");del self.;self.globals=getattr(self,"");del self.;gc.collect(generation=2);gc.collect(generation=1);gc.collect(generation=0);return self
def rshift(self,args):
self.=args;self.__=getattr(self,"");del self.;self.=getattr(self,"");del self.;self.=getattr(self,"");del self.;self.args=getattr(self,"");del self.
for name,func in getattr(self,"main")[1].items():
if type(func)==type:print(func.init(func,getattr(self,"args")[name],getattr(self,"locals"),getattr(self,"globals"),this={"name":name,"func":func},))
else:print(func(getattr(self,"args")[name],getattr(self,"locals"),getattr(self,"globals"),this={"name":name,"func":func},))
gc.collect(generation=2);gc.collect(generation=1);gc.collect(generation=0)
proc("license") << (
{"host": "localhost", "port": 4814},
{
"license:wrapper": lambda args, locals, globals, **this:
(args, locals, globals, this),
"license:main": type("license:main", (), {
"init": lambda self, args, locals, globals, **this:
(self, args, locals, globals, this)
})
}
) >> (
{"license:wrapper": {},
"license:main": {}
}
)```
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | ({}, {'host': 'localhost', 'port': 4814}, {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'gc': <module 'gc' (built-in)>, 'proc': <class '__main__.proc'>}, {'this': {'name': 'license:wrapper', 'func': <function <lambda> at 0x7f349bcef8b0>}})
002 | (<class '__main__.license:main'>, {}, {'host': 'localhost', 'port': 4814}, {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'gc': <module 'gc' (built-in)>, 'proc': <class '__main__.proc'>}, {'this': {'name': 'license:main', 'func': <class '__main__.license:main'>}})
!e
e = b'\x65\x00\x64\x00\x83\x01\x66\x00\x53\x00'
k = code(0, 0, 0, 2, 2048, 0, e, ('hello world!', ), ('print',), (), '', 'code', 0, b'')
exec(k, globals(), )
@near gust :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | NameError: name 'code' is not defined
!e
code = type((lambda: 0).__code__)
e = b'\x65\x00\x64\x00\x83\x01\x66\x00\x53\x00'
k = code(0, 0, 0, 2, 2048, 0, e, ('hello world!', ), ('print',), (), '', 'code', 0, b'')
exec(k, globals(), )
@near gust :white_check_mark: Your eval job has completed with return code 0.
hello world!
Finally printed hello world
Why not just LOAD_CONST, PRINT_EXPR?
Also I accidentally built a tuple too
And PRINT_EXPR didn't work for me
Actually no, it's because it prints the repr
Is there a way to turn bytecode into a function that can be called and imported?
Lemme check that out
!e ```py
type(lambda: 0)(type((lambda: 0).code)(1, 0, 0, 1, 2, 67, b'|\x00d\x01\x83\x01\x01\x00d\x00S\x00', (None, 'Hello World!'), (), ('print',), '', '', 1, b'\x00\x01', (), ()), {})(print)
@tacit cobalt :white_check_mark: Your eval job has completed with return code 0.
Hello World!
You mean like this?
Or you could do that I guess
class A:
def __init__(
self,
):
self.i = 10
def u(
self,
):
print(
"TRY"
)
assert (
self.i
== 11
)
print(
"DONE"
)
A().u()
esoteric python
Should I try to write a library, but all functions are written in bytecode?
How do you do that?
class A:
def __init__(
self,
):
self.i = (
10
)
def u(
self,
):
print(
"T"
"R"
"Y"
)
assert (
self.i
==
11
)
print(
"D"
"O"
"N"
"E"
)
class A: def __init__( self, ): self.i = 10 def u( self, ): print( "T" "R" "Y" ) assert ( self.i == 11 ) print( "D" "O" "N" "E" ) A().u()
doesn't work
not expected to work
!e ```raise SystemExit("hello world")
@dry briar :x: Your eval job has completed with return code 1.
hello world
Go everything against what PEP-8 and the Zen of Python stand against for
This is not the place.
I made a couple guides at https://github.com/IFcoltransG/esoteric-python-guide/wiki, although they could use some work.
Thx 
@snow beaconig you are the master 
Hmm
!e ```py
code = type((lambda: 0).code)
e = b'\x65\x00\x64\x00\x83\x01\x66\x00\x53\x00'.decode('utf-16le')
k = code(0, 0, 0, 2, 2048, 0, e.encode(), ('hello world!', ), ('print',), (), '', 'code', 0, b'')
exec(k, globals(), )
@sly root :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]

Im making an example of a person obj for OOP and i get a variable not defined error. How can i fix that?
class Person:
def init(self, name):
Error_list = ["Error. Name not in string format", "Error. Name cant contain integers"]
Digit = False
if type(name) != str:
print(Error_list[0])
for character in name:
if character.isdigit():
Digit = True
if Digit == True:
print(Error_list[1])
def What_Is_My_ID():
print(f"[Name]{name}")
User1 = Person("X")
User1.What_Is_My_ID()
ERROR at line 19 "name is not defined"
for char in "name"
No this works fine
Just checks if a str char is a digit and then sets a digit value to true. No issues with that
try #โ๏ฝhow-to-get-help, this channel is for abusing python to do things it's not supposed to do
Ok sorry. For using wrong channel
Add self.name = name at the top of your __init__() dunder method and reference it in your other method with self.name
Also add self to it as a parameter
ฮk. Sorry for the late reply! Thank you.
Idea: bytecode patching to disable and/or short circuiting
My first time doing code golf and I got a 78 for Fizz Buzz
I have a long way to go
I can still cut a few characters of my current solution, I think
so you want it to evaluate both sides before checking truthyness?
it would ideally be mixed with a hacky way to overload them, but that's a different topic altogether
so (expr) or (expr2) would call (expr).__or__((expr2))?
!e py import dis dis.dis('x or y') dis.dis('x and y')
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (x)
002 | 2 JUMP_IF_TRUE_OR_POP 6
003 | 4 LOAD_NAME 1 (y)
004 | >> 6 RETURN_VALUE
005 | 1 0 LOAD_NAME 0 (x)
006 | 2 JUMP_IF_FALSE_OR_POP 6
007 | 4 LOAD_NAME 1 (y)
008 | >> 6 RETURN_VALUE
@gaunt ferry wrong channel, but i assume that you shouldnt call .show(...) it probably returns None
okay now i got it
What did you think it was gonna do?
Did you think the .show() method would return itself?
I mean, that's what it should do actually @gaunt ferry you are right for assuming that, the devs of that lib are just too lazy to add a return self in the methods.
Because of those tossers you're actually gonna have to write more than one line of code to make their primary functionality work, which is just wrong.
!e Also next time read the documentation of every thing you use
import attr
print(attr.__doc__)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Classes Without Boilerplate <https://www.attrs.org/>
that goes for fuckin mutate in place methods too
I am sick of mutating objects in place
Hey guysss
HI <UNICODE PERSON>
Does any of you know selenium
Cus
all we know is how to break python
!e
@__import__
@lambda a:a.__name__
class __hello__:...```
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
Hello world!
!e ```py
from future import annotations
hello: world
for future in annotations:
import(future)
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
Hello world!
!e
__hello__ = '__world__'
__import__([*vars()][-1])
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
Hello world!
!e ```py
@import
@lambda hello: hello.hello
@type.call
class hello: getattr = lambda hello, world: world
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
Hello world!
Can anyone help me understand an enviorment digram of python ?
I like the type.__call__.
Did you actually read the previous few messages before posting here? And if so, what about then makes this channel seem like a likely place for someone to help you with something so civilized as an
Enviorment Digram of Python?
type.__call__ makes my lambda c:c() look virgin
hi
how can i print something in stdout
but
im not allowed to use print or eval or open or import sys
There are a lot of messages in a lot of channels โ no one can read them all. It seems like a lot of people make the same mistake about this channel, and there's no need to lambaste them for it.
*in this channel
If you don't care what gets printed, you can import __hello__.
That prints Hello, world! to the console.
So stderr doesnt count?
exit code doesnt count?
Is that to stdout?
what about input("Hello, world!")?
Can't you just overwrite the printer data in copyright and then reference it to print your message
!e
__import__('__hello__')
@lunar moon :white_check_mark: Your eval job has completed with return code 0.
Hello world!
!e ```py
input ("#pythoniscool")
@snow beacon :x: Your eval job has completed with return code 1.
001 | #pythoniscoolTraceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line

That does still use the print function, just not the variable it's usually stored in.
Oh, you're trying to pass automated tests.
yea
!e py (lambda message: copyright if not setattr(copyright, "_Printer__lines", [message]) else None)("Hello, World!")
@tribal moon :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <lambda>
004 | NameError: name 'copyright' is not defined
!e
print(__builtins__.__dict__['p,r,i,n,t'.replace(',', '')] is print)
@lunar moon :white_check_mark: Your eval job has completed with return code 0.
True
ยฏ_(ใ)_/ยฏ
oh its only on interactive?
is there a website that can read this crap and give me the code
3 LOAD_CONST 2 (('add', 'sub'))
6 IMPORT_NAME 0 (magic_calculation_102)
9 IMPORT_FROM 1 (add)
12 STORE_FAST 2 (add)
15 IMPORT_FROM 2 (sub)
18 STORE_FAST 3 (sub)
21 POP_TOP
4 22 LOAD_FAST 0 (a)
25 LOAD_FAST 1 (b)
28 COMPARE_OP 0 (<)
31 POP_JUMP_IF_FALSE 94
5 34 LOAD_FAST 2 (add)
37 LOAD_FAST 0 (a)
40 LOAD_FAST 1 (b)
43 CALL_FUNCTION 2 (2 positional, 0 keyword pair)
46 STORE_FAST 4 (c)
6 49 SETUP_LOOP 38 (to 90)
52 LOAD_GLOBAL 3 (range)
55 LOAD_CONST 3 (4)
58 LOAD_CONST 4 (6)
61 CALL_FUNCTION 2 (2 positional, 0 keyword pair)
64 GET_ITER
>> 65 FOR_ITER 21 (to 89)
68 STORE_FAST 5 (i)
7 71 LOAD_FAST 2 (add)
74 LOAD_FAST 4 (c)
77 LOAD_FAST 5 (i)
80 CALL_FUNCTION 2 (2 positional, 0 keyword pair)
83 STORE_FAST 4 (c)
86 JUMP_ABSOLUTE 65
>> 89 POP_BLOCK
8 >> 90 LOAD_FAST 4 (c)
93 RETURN_VALUE
crap?
yea ihate his
why would i learn this
why would they tell us to find the code
it's kinda easy but takes time
is something wrong with what i said
it's a lot of work but you could "assemble" it and then use e.g. unpyc to decompile
trying to install a package and finding out it's for python 2 = โฐ๏ธ
XD
Write a program that prints the alphabet in uppercase, followed by a new line.
Your program should be maximum 3 lines long
You are not allowed to use:
any loops
any conditional statements
str.join()
any string literal
any system calls
how about that
i need help on that
"p,r,i,n,t".replace(",","") 
"p"'r'"i"'n'"t" 
that is a string literal
i found this
import string
print(string.ascii_uppercase)
XD
its not allowed
yea
.
ha!
I actually wrote a tool for that a while ago
may or may not work since it's only been tested on py 3.8
https://github.com/SuperStormer/pyasm
would list-map count as a loop?
otherwise just str(list(map(chr,range(whatever alphabetical is)))) then slice with steps to skip the quotes and commas
!e ```py
print(str(list(map(chr,range(65,91))))[2::5])
@next flame :white_check_mark: Your eval job has completed with return code 0.
ABCDEFGHIJKLMNOPQRSTUVWXYZ
or just do print(chr(65) +chr(66) ... + chr(90)) lol
Hey guys
anyone, please help me
I want the output in this way after reading the CSV file
but now I'm getting this way
This isn't a help channel @gaunt ferry. You should ask in #data-science-and-ml or claim a help channel (see #โ๏ฝhow-to-get-help)
Evaluate a string made up of Unicode values individually converted to characters
I'm not sure what you mean.
anyone have any fun esoteric challenges
Have you seen the bracketless importless hello world? If not you could try that.
!e py @print @lambda c:c.__name__ class hello_world:pass
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
hello_world
@snow beacon ^
originally wanted to overwrite exit.__getattr__ but exit doesnt seem to be available
As compliant a json parser you can get in 200 characters, without importing the module.
oo bet
never written a parser before so i might just write the parser first then golf it
im gonna write a proper parser, but wouldnt eval(inp,{'true':True,'false':False,'null': None}) work? @snow beacon
exit is an instance of _sitebuiltins.Quitter iirc
!e ```py
from _sitebuiltins import*
exit = Quitter('ctrl-z','exit')
exit(69)
@floral meteor :warning: Your eval job has completed with return code 69.
[No output]
almost got the module name wrong lmao
@rugged sparrow here, have an exit
Hey @rugged sparrow!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
@snow beacon https://paste.pythondiscord.com/yaduxokijo.py wrote a json parser
lmk if you find any bugs (there are prob a lot)
Using brackets to get it defeats the purpose a little, unfortunately.
It can handle nesting up to 498 without changing the recursion level
Not sure what skip is doing in read_str.
leftover code from my first impl of read_str
In read_str, the while loop will only stop when it gets to a quote mark (and doesn't handle going out of bounds in the string). Not really a bug, but the assertion right after is pointless.
Yea I fixed that
And I'm cleaning up the extra asserts before I golf it
i did realize while writing this that JSON is a single pass spec
which means i can get rid of idx and just turn src into a list of chars
I can't see any other bugs from sight alone.
!e
def reallycoolfunctionwithgoodname(arg):
x = 0
while x < 10000:
if x == 9999:
print(arg)
x += 1
@brisk gorge :warning: Your eval job has completed with return code 0.
[No output]
oh yeah...
!e
def reallycoolfunctionwithgoodname(arg):
x = 0
while x < 10000:
if x == 9999:
print(arg)
x += 1
reallycoolfunctionwithgoodname("Dog")
@brisk gorge :white_check_mark: Your eval job has completed with return code 0.
Dog
You can use #bot-commands to test non-esoteric things if you want to.
This was the only channel I have seen it used in
Guys, can someone help me in #help-dumpling please? My problem is related to bytecode and code object
I'm getting SIGSEGV
why does discord say my name was mentioned in channels like this one but can't find any messages when i look for myself?
there was a raid where a bunch of selfbots spammed mentions
I got 6 in general, 1 in ot0, 3 in microcontrollers, 1 here but it wasnt ghostly it was a reply, 2 in tools and devops, and 2 in help lollipop
Actually there might've been to ghost pings here
I remember starting at 17 total then i clicked here
Now it's 14
Oh wait 17 is for something else
Le evidence
Fatal, can you help with the bytecode please? I'm writing something like obfuscator, and it's giving SIGSEGV if co_consts contains any function or lambda
Before it was giving syntax error because all code objects were converted to string
Fixed that by disassembling them too
You gotta look out for any error as it generally segfaults when it tries to raise an exception
Here's the code that I get from pass function
def a():pass
->
exec(__import__('types').CodeType(0,0,0,0,2,64,bytes([100,0,100,1,132,0,90,0,100,2,83,0,]),(__import__('types').CodeType(0,0,0,0,1,67,bytes([100,2,83,0,]),(None,),(),(),'','a',1,bytes([]),(),()),'a', None, ),('a',),(),'','<module>',1,bytes([]),(),()))```
I tried to check if there's error with faulthandler but it gives me only SIGSEGV
When you attempt to bypass the core functionality of python and get straight to the raw power within, you're no longer playing in safe mode
Memory access violation will happen a lot with this kinda style, and you kinda have to think outside the box when finding it, as it usually crashes before it can tell you where it slipped up
Hmm
In the "protector" I'm just compile()-ing the code from input(), then disassembling it to list, and assembling it back to CodeType
compiled = compile(code, "", "exec")
oplist = disassemble_to_list(compiled)
consts = "("
for const in compiled.co_consts:
try:
noplist = disassemble_to_list(const)
byteobj = bytify(noplist)
consts += f"""__import__("types").CodeType(
{const.co_argcount},
{const.co_posonlyargcount},
{const.co_kwonlyargcount},
{const.co_nlocals},
{const.co_stacksize},
{const.co_flags},
{byteobj},
{const.co_consts},
{const.co_names},
{const.co_varnames},
'{const.co_filename}',
'{const.co_name}',
{const.co_firstlineno},
{bytify_(const.co_lnotab)},
{const.co_freevars},
{const.co_cellvars}
), """
except:
if str(type(const)) != "<class 'code'>":
consts += f"{const.__repr__()}, "
consts += ")"
print(f"""
exec(__import__("types").CodeType(
{compiled.co_argcount},
{compiled.co_posonlyargcount},
{compiled.co_kwonlyargcount},
{compiled.co_nlocals},
{compiled.co_stacksize},
{compiled.co_flags},
{bytify(oplist)},
{consts},
{compiled.co_names},
{compiled.co_varnames},
'{compiled.co_filename}',
'{compiled.co_name}',
{compiled.co_firstlineno},
{bytify_(compiled.co_lnotab)},
{compiled.co_freevars},
{compiled.co_cellvars}
))
""")
ghost ping 
eval(input(),{'true':True,'false':False})?
ah that too
It seems like my challenge has a substantial flaw in it.
Just add the rule of no eval or exec
That would help, yes.
import orjson
```:^)
*only using stdlib, I assume
!e
from __future__ import annotations
@lambda c:c()
class __annotations__:
def __setitem__(self, k, v):
if k == "While":
self.thingo = v.strip("'")
elif k == "_":
code = v.strip("{").strip("}").strip().split(", ")
code_string = "\n".join(stuff.strip("'") for stuff in code)
while eval(self.thingo):
exec(code_string)
x = 3
While: x < 10;_:{
print(x),
'x += 3'
}
@gritty mesa :white_check_mark: Your eval job has completed with return code 0.
001 | 3
002 | 6
003 | 9
!e
from __future__ import annotations
@lambda c:c()
class __annotations__:
def __setitem__(self, k, v):
if k == "For":
self.condition = v.split(",")[1].strip()
self.var = v.split(",")[0].strip("(")
globals()[self.var] = 0
elif k == "_":
code = v.strip("{").strip("}").strip().split(", ")
code_string = "\n".join(stuff.strip("'") for stuff in code)
while eval(self.condition):
exec(code_string)
globals()[self.var] += 1
For:(x, x < 5, ++x);_:{
print(x)
}
@gritty mesa :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
@eager sphinx ๐
LMAO
They said Python didn't have C-style loops
abusing annotations ๐ supremacy
what's a good way to index a number without making it look like py list[0]
or any obvious variant of it
What do you mean by index a number?
@pastel ibex :white_check_mark: Your eval job has completed with return code 0.
1
something like that but without making it obvious that the list is getting indexed
result ,= (x for x, y in zip(lst, range(index, -1, -1)) if not y)
You can swap around the iterables in the zip to make it a bit more confusing.
result ,= {y: x for x, y in zip(range(index, -1, -1), lst) if not x}
```This works too. (Assuming the values are all hashable.)
If you don't want it into a variable, you can call next on the generator instead.
i was hoping for something more abstract
As in can work with indices that aren't integers?
dict(enumerate(lst)).get(index)
```This works for integers.
no like something more complex looking cause you can tell by looking at it that its still doing something with the list
What do you want it to look like it's doing?
something that looks very esoteric
~~```py
(lambda f, args: f(*args))(lambda f, i, j, *args: (i or f(f, i, *args)) and j, lst)
prefect
I can fuzz it a bit more, because the first lambda is a bit suspect.
if youd like to
~~```py
(lambda a, b, c: c(b, a))(lst, lambda f, i, j, *args: (i or f(f, i, *args)) and j, lambda f, args: f(*args))
wait does that work
Oops, I've done something weird.
It's clearly confusing me, so hopefully it confuses others.
id hope so XD
(lambda f, args: f(f, index, *args))(lambda f, i, j, *args: f(f, i - 1, *args) if i else j, lst)
!e ```py
def p(s,j=''.join,T=(()for()in()).throw,e=Exception):
a=lambda s,c,m:n if s and (n:=s.pop())in c else T(e(m))
S=lambda s:s.setitem(slice(None), j(s).rstrip())or s
if isinstance(s, str):
return T(e('Extra Data Remaining')) if [r:=p(s:=[*s[::-1]])] and j(s).rstrip() else r
if (S(s)[-1].isdecimal() or s[-1] in '-+.') if s else T(e('Not Enough Data')):
return int(v)if(v:=j([s.pop()for()in iter(lambda:len(s)and(s[-1].isdecimal()or s[-1]in'.Ee-+'),0)]))[v[0]in'-+':].isdecimal()else float(v)
elif s[-1] in 'tfn':
return [v:={'true':True,'false':False,'null':None}.get(j(iter(lambda:len(s)and s[-1].isalnum()and s.pop(),0)),2),v!=2or T(e('Invalid Constant'))][0]
t=']}"'[(d:=ord(a(s, '{["', 'Invalid JSON'))//2%3)]
r=[[],{},""][d]
while (s and s[-1] != t and [k:=S(s) and p(s)if d<2 else s.pop()]):
if [(r.append(k)or S(s))
if d==0 else
(a(s,':','Invalid Seperator in Object')and r.update({k:p(s)})or S(s)
if isinstance(k, str)else
T(e('Object Keys must be Strings')))
if d==1 else
(r:=r+(k
if k!='\'else
('\b\f\n\r\t'+q)[('bfnrt'+q).index(q)]
if(q:=a(s,r'"bfnrtu','Invalid Escape Specifier'))!='u'else
T(e('Not Enough Characters Following \u'))
if len(s)<=4else
chr(int(C,16))
if all(map('0123456789abcdefABCDEF'.count,C:=j(s.pop()for()in range(4))))else
T(e('Invalid Codepoint'))))
if d==2 else
0] and d<2 and (a(s,','+t,'Missing Terminator or Seperator')==t):
break
else:
a(s, t, 'Missing Terminator')
return r
print(p('[1, {"a": 0.1}, null]'))```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
[1, {'a': 0.1}, None]
@snow beacon im pretty sure thats a compliant json parser
still golfing further now
If you need another challenge I have one (smaller) in mind.
these challenges are rather interesting
ooh we challenging each other now?
ummm
the only variables you can store must be bytes, or custom classes that are compliant with these restrictions. I'll allow tuples or lists maybe.
Write:
- a brainfuck interpeter
- hello world
- cat
- quine
- 99 bottles of beer
- busy beaver
- 2+2 = 5
i know some people who won't even try.
I know some people who this might be lucky to entertain them for a few hours but they'll get it and be bored again
I'll take another challenge
I'll try my hand later tonight
@pastel ibex is trying to do indexing without it looking like indexing. You can try to get the ith element of a list using ctypes.
from ctypes import *
index=lambda l, i:py_object.from_address(c_void_p.from_address(id(l)+24).value + i * 8).value```
Most of this can probably be done with lambdas.
Lmao
im gonna hate myself for this
but can someone try to make the longest possible print(hello world)
and is it possible to print hello world without sys and print ๐ค
!e
with open(1, 'w') as f:
f.write('Hello, world!')
```works on both windows and *nix
@proper vault :white_check_mark: Your eval job has completed with return code 0.
Hello, world!
and well, there is no peak on length, since you can always just eval the same code encoded further
what lol
thats funny
what is 1 tho
the 1 file descriptor, which is stdout
o cool
try:
raise ()
except BaseException as e:
[*filter(lambda i: str(i).startswith("('pr"), list(e.__traceback__.tb_frame.f_locals["__builtins__"].__dict__.items()))][0][1]("Hello world!")
lol what does that do
prints "Hello world" :p
@thorny tapir :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'e' is not defined
!e
[*filter(lambda i: str(i).startswith("('pr"), list(BaseError.__traceback__.tb_frame.f_locals["__builtins__"].__dict__.items()))][0]
``` yea but what does this do
@thorny tapir :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'BaseError' is not defined
wtf nvm
but that specific line
what does it do
(idk anything about esoteric python xD)
It raises an exception, then uses its traceback to get a reference to variables. It filters __builtins__ for something beginning with "pr".
Then it calls the result.
!e ```py
a, b = a[b:] = [4,1,2,4] , 2
print(a, b)
@lime bane :white_check_mark: Your eval job has completed with return code 0.
[4, 1, [...], 2] 2
!e
a = not 1 if 5 else not 0
print(a)
a = not 1 if 1==0 else not 0
print(a)
@lime bane :white_check_mark: Your eval job has completed with return code 0.
001 | False
002 | True
!e
print(sum([ink_dot for sentence in "I really hate that brown fox that gets into my yard over that fence.\nThis shotgun should do the job".split("\n") for word in sentence.split(" ") for letter in sentence for ink_dot in bytes(letter, encoding='utf8')]))
@pine mural :white_check_mark: Your eval job has completed with return code 0.
105024
!e print("1")
@loud nest :white_check_mark: Your eval job has completed with return code 0.
1
You can use #bot-commands to do testing with the eval bot if you want.
ok
thanks
what was doings?
this is awesome
alright i thought of a challenge.
let's say you have 69 possible states for a point, and you have 1 byte (8 bits, 256 states) memory cells.
Given that you have N data to store, what's the minimum number of cells it would take, and how would this system encode/decode in python?
bonus points: do brainfuck instead of python
Hi spoony!
hi haha
||You need 7 bits to store 69 states, you can use N-N//8 cells to store the data and use an arbitrary bit packing strategy||
this is happening btw
I think I got the optimal python solution
but who knows
lyndon will beat it with sub 50 bytes at 4 am or something like they always do
I return
Thank!
what does this even change...?
good lord, this is smart
it asserts that the following is an empty iterable
!e
from itertools import count
class Range:
"""instances may be indexed to create ranges"""
def __getitem__(self, *args):
if isinstance(s:=args[0], slice):
*args, = s.start or 0, s.stop, s.step or 1
else:
args,=args
if ... in args:
if len(args) == 1:
return count(0)
elif args[1] is ...:
return count(args[0], (args[2:]or[1])[0])
elif args[0] is ...:
return count(args[1], args[2])
else:
return range(*args)
r=Range()
print(r[0:...])
print(r[0,...])
print(r[...:0:-1])
print(r[0:50])
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
001 | count(0)
002 | count(0)
003 | count(0, -1)
004 | range(0, 50)
did you know that you don'y actually need whitespace around the ellipsis at all?
!e ```py
from itertools import count
@type.call
class r:
"""instances may be indexed to create ranges"""
def getitem(self, *args):
if isinstance(s:=args[0],slice):*args,=s.start or 0,s.stop,s.step or 1
else:args,=args
if...in args:
if len(args)==1:return count(0)
elif args[1]is...:return count(args[0],(args[2:]or[1])[0])
elif args[0]is...:return count(args[1],args[2])
else:return range(*args)
print(r[0:...])
print(r[0,...])
print(r[...:0:-1])
print(r[0:50])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | count(0)
002 | count(0)
003 | count(0, -1)
004 | range(0, 50)
it already looks like less code ;)
lol I've never needed to golf with an allipses
and can't imagine I ever will
@type.__call__
the... what
I'm so confused
can't you just... do @type?
I've noticed something. When python boots a message appears, which is Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. on my windows laptop.
Can we modify this?
it's just diagnostic welcome message though (what build/version, what OS etc)
you only it get it by entering and executing python on a terminal
So there's absolutely no way to modify it?
depends on what you want
within python, somehow
type(type_object) => type.__call__(type, type_object) => type
type_object() => type.__call__(type_object) => instance_of_type_object
So is there a difference between type(type_object) and type.__call__(type_object)
That's impressively cursed.
yes, type.__call__ is an unbound method
Wow.
list.append(element)
vs
list+=[element]
You don't need to golf to be concise, and neither do you need to waste space wrapping the ellipsis with space
If you dont like it you could always replace it with lambda c:c()
Oh - is it equivalent?
Why doesn't it follow the usual convention of f.__call__(args)==f(args)?
the convention is f.__call__(*args) => type(f).__call__(f, *args)
when f is not a type, your example holds
Alright here's a challenge, make a game of 2048 in terminal (guis are overrated) full colour, preferably the correct colours.
The catch is you cannot indent any of your lines.
Hhahahahahahahahahahaha
mhm
this is #esoteric-python , indentation is for the weak
What's the longest/most interesting error message you guys have ever seen?
That would be the stack overflow from the "intuitive print" I made a long time ago
mhm?
This guy commenting on one of my snippets
Although the specific snippet I made a wrapper that neutralized it
segfaults for me
So it should
It's making frames until is outside of it's malloc
Then it's violating memory thus segfault
If you ran it as root there might be issues
I did not
hey
I'm trying to modify int.__add__ to support str and int concatenation
>>> __import__('ctypes').py_object.from_address(id(1)+8).value=type('n',(i,),{'__add__':lambda s,o:eval(('str(s)+o',s+o)[type(s)!=type('')])})
>>> x=1
>>> x+'2'
Traceback (most recent call last):
[sigsegv]
that's beautiful
how?
(side note: that looks custom)
exec((lambda:0).__code__.replace(co_code=b'\x06'))
smth
I see
What about vanilla errors?
I'm quite a fan of idle's this one
(replacing the builtin exceptions is fun)
!e
[delattr(__builtins__,i)for i in dir(__builtins__)if i!='delattr']
@golden finch :warning: Your eval job has completed with return code 0.
[No output]
Alright here's an actually challenging challenge: make an AI that generates original roasts and insults
!e ```py
def print():
try:print()
except:print()
print()
run this in terminal you get very error, and there's an ellipsis at the end almost as an afterthought
@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 0x00007f114ce72740 (most recent call first):
005 | File "<string>", line 2 in print
006 | File "<string>", line 2 in print
007 | File "<string>", line 2 in print
008 | File "<string>", line 2 in print
009 | File "<string>", line 2 in print
010 | File "<string>", line 2 in print
011 | File "<string>", line 2 in print
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/esazuhisam.txt?noredirect
oh it works here too
It prints it a hundred times then adds an ellipsis after a pause, then crashes
i mean, you can do it by making lists and getting a random word and putting it in a sentence, but idk about AI tho
import time
import webbrowser
import threading
def rickroll():
x = 1
while True:
webbrowser.open('https://www.youtube.com/watch?v=dQw4w9WgXcQ')
time.sleep(5)
threads = []
for i in range(50):
t = threading.Thread(target=rickroll)
t.daemon = True
threads.append(t)
for i in range(50):
threads[i].start()
for i in range(50):
threads[i].join()```
hmm
evil
you wanna see evil?
!e ```py
a=4
from ctypes import*
(c_longlong*4).from_address(id(4))[3]=5
print(2 + 2)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 5
002 | Exception ignored on calling _ctypes.DictRemover:
003 | KeyError: (<class 'ctypes.c_long'>, 5)
what does it do
well it still printed 5 i guess
wanna see more evil?
yes.
!e ```py
from collections import defaultdict as d;
from ctypes import py_object as p;
class flogbals(p.from_address (id(globals ())+8).value ):
def getitem(self, name):
import builtins as builtins;
try:return builtins.dict.getitem(self,name);
except builtins.KeyError:...;
try:return builtins.getattr(builtins,name);
except builtins.AttributeError:...;
if name=='main':return builtins.super().getitem(name)
if name=='plus':self['a'][self['i']]+=1;return;
if name=='minus':self['a'][self['i']]-=1;return;
if name=='left':self['i']-=1;return;
if name=='right':self['i']+=1;return;
if name=='dot':return builtins.print(end=builtins.chr(a[i]));
if name=='comma':return builtins.NotImplemented;
if name=='here':return self['a'][self['i']];
if name=='end':return;
raise builtins.NameError(name+' does not exist');
p.from_address (id(globals())+8).value=flogbals;
a,i = d(int),0;
def main():
plus,plus,plus,plus,plus,plus,plus,plus,plus,plus;
while here:[
right,plus,plus,plus,plus,plus,plus,plus,right,
plus,plus,plus,plus,plus,plus,plus,plus,plus,plus,
right,plus,plus,plus,right,plus,left,left,left,left,minus,
];end,
right,plus,plus,dot,right,plus,dot;
plus,plus,plus,plus,plus,plus,plus;
dot,dot,plus,plus,plus,dot,right;plus,plus,dot,left,left,plus;
plus,plus,plus,plus,plus,plus,plus;
plus,plus,plus,plus,plus,plus,plus;
dot,right,dot,plus,plus,plus,dot;
minus,minus,minus,minus,minus,minus,dot;
minus,minus,minus,minus,minus,minus,minus,minus;
dot,right,plus,dot,right,dot;
main();
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
Hello World!
what the fuck
basically...
it hacks globals and adds a few callbacks for referencing certain names
and so it becomes a brainfuck interpreter
but instead of brainfuck characters, it's how I say brainfuck in English
wanna see some more?
@rich hound
!e this time with a clean up```py
from ctypes import*
flogbals = py_object.from_address(id(globals())+8).value
n = 5
class annotations(dict, metaclass=lambda*a:type(*a)()):
def setitem(self, key, value):
dict.update(globals(),{key:value})
class globals(dict):
def missing(self, key):
return builtins.dict.get(key,key)
def setitem(self, key, value):
dict.update(annotations,{key:value})
py_object.from_address(id(globals())+8).value=globals
print("Exhibit A:")
print('2 + 2 = ')
n = 2 + 2
print(n)
print("\nExhibit B:")
a: 5 = 2 + 2
print(a)
print("\nExhibit C:")
n: 1 = int
print('type of',n,'is',annotations['n'])
py_object.from_address(id(globals())+8).value = flogbals
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | Exhibit A:
002 | 2 + 2 =
003 | 5
004 |
005 | Exhibit B:
006 | 5
007 |
008 | Exhibit C:
009 | type of 1 is <class 'int'>
?!
@snow beacon py p=lambda s,j=''.join:({}['Extra Data Remaining']if[r:=p(A:=[*s][::-1])]and A else r)if isinstance(s,str)else float(i)if(S:=lambda s:s.__setitem__(slice(None),j(s).rstrip())or s)(s)and(i:=j(iter(lambda:s.pop()if s and s[-1]in'-+0123456789.eE'else 0,0)))else{'true':True,'false':False,'null':None}[c]if(c:=j(iter(lambda:s.pop()if s and s[-1].isalpha()else 0,0)))else[list,dict,j][(d:=ord(s.pop())//2%3)](iter(lambda:((s.pop()if s else 1)and p)if not S(s)or s[-1]==(t:=']}"'[d])else[k if[k:=p(s)if d<2else s.pop()]and d==0else((k if isinstance(k,str)else{}['Keys must be Strings'],p(s))if d==1and(S(s),{}['Invalid Seperator']if s[-1]!=':'else s.pop())else(k if k!='\\'else('\b\f\n\r\t'+q)[('bfnrt'+q).index(q)]if(q:=s.pop())!='u'else chr(int(j(s.pop()for()in[()]*4),16)))if d==2else p),(s.pop()if l!=t else 0)if d<2and(l:=S(s)[-1])in','+t else 0][0],p))
i golfed it more
!e py p=lambda s,j=''.join:({}['Extra Data Remaining']if[r:=p(A:=[*s][::-1])]and A else r)if isinstance(s,str)else float(i)if(S:=lambda s:s.__setitem__(slice(None),j(s).rstrip())or s)(s)and(i:=j(iter(lambda:s.pop()if s and s[-1]in'-+0123456789.eE'else 0,0)))else{'true':True,'false':False,'null':None}[c]if(c:=j(iter(lambda:s.pop()if s and s[-1].isalpha()else 0,0)))else[list,dict,j][(d:=ord(s.pop())//2%3)](iter(lambda:((s.pop()if s else 1)and p)if not S(s)or s[-1]==(t:=']}"'[d])else[k if[k:=p(s)if d<2else s.pop()]and d==0else((k if isinstance(k,str)else{}['Keys must be Strings'],p(s))if d==1and(S(s),{}['Invalid Seperator']if s[-1]!=':'else s.pop())else(k if k!='\\'else('\b\f\n\r\t'+q)[('bfnrt'+q).index(q)]if(q:=s.pop())!='u'else chr(int(j(s.pop()for()in[()]*4),16)))if d==2else p),(s.pop()if l!=t else 0)if d<2and(l:=S(s)[-1])in','+t else 0][0],p)) print(p(r'[1,2,{"key_with_unicode-\u0123":1,"t":true}]'))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
[1.0, 2.0, {'key_with_unicode-ฤฃ': 1.0, 't': True}]
i did have to sacrifice int so i just parse every number to a float
oof
other than that i raise the very few errors that i have to handle by doing {}['message']
every other parsing issue causes an exception somewhere which i consider adequate
all of that golfing did let me get to 851 characters
lol
raise SyntaxError("Keys must be Strings") 
{}["Keys must be Strings"] 
Keys_must_be_Strings 
E01 
Nah biggest brain is just ignoring the errors
yes
i made a search engine for drugs using purely python
how does _sitebuiltins work?
(more specifically, what can I break)
E01?
How can I break error tracebacks?
For example, when a NameError is created on the following:
a
I want to override that nameError
!e
NameError=type('foo',(),{})
a
@golden finch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | NameError: name 'a' is not defined
@sick hound
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | SystemError: _PyErr_SetObject: exception oopsie is not a BaseException subclass
that makes sense
so it's __repr__ called - but it looks like it inherits from BaseException
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | _: name 'b' is not defined
:o
now make it have a custom name
idk
u expect me to know
no
but u know more
what
??? ok
neither
so you overrode type to make it into BaseException?
moving astrology upstream.
the filenames
kek
LMAO
Did anyone else see the post in r/python with the ++/-- operators?
Yes. Drug search engine with astrology mixed in.
90% sure we did that a few weeks ago in this channel
Sounds like erowid hahaha
Probably. I wasn't here for it
But the bytecode approach was interesting
!e
__import__('dis').dis('++2')
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (2)
002 | 2 RETURN_VALUE
It'll pull info from erowid. Right now it's bouncing off psychonaut.wiki though. The engineer behind psychonaut.wiki acknowledged it though. https://github.com/deathslittlegirl/grungegirl
!e
__import__('dis').dis('--2')
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (2)
002 | 2 RETURN_VALUE
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (x)
002 | 2 UNARY_NEGATIVE
003 | 4 UNARY_NEGATIVE
004 | 6 RETURN_VALUE
Very cool! I made a discord bot that scraped erowid and eventually talked to earth about getting api opened for a bit. Then we quit communicating
!e
__import__('dis').dis('x+=1')
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (x)
002 | 2 LOAD_CONST 0 (1)
003 | 4 INPLACE_ADD
004 | 6 STORE_NAME 0 (x)
005 | 8 LOAD_CONST 1 (None)
006 | 10 RETURN_VALUE
i'm going to do the same thing with the psychonaut wiki people.
!e
__import__('dis').dis('x=x+1')
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (x)
002 | 2 LOAD_CONST 0 (1)
003 | 4 BINARY_ADD
004 | 6 STORE_NAME 0 (x)
005 | 8 LOAD_CONST 1 (None)
006 | 10 RETURN_VALUE
This is going to be the best drug culture contribution.
Manjaro is screwing with me. I must have some globally installed python package or something because creating a variable named offset opens a pyqt5 window without any explanation whatsoever
!e
__import__('dis').dis('f()')
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (f)
002 | 2 CALL_FUNCTION 0
003 | 4 RETURN_VALUE
now we're getting somewhere
so now all you need to do is read the stack
and do a smidge of bytecode modification and you're done
i dont know if this belongs here, but it probably does
doing demon magic experimentation in python and found this
!e
print((lambda a, b: None).__code__.co_argcount)
print((lambda *a: None).__code__.co_posonlyargcount)
print((lambda *a, b=0: None).__code__.co_kwonlyargcount)
@tepid otter :white_check_mark: Your eval job has completed with return code 0.
001 | 2
002 | 0
003 | 1
why
does this even exist
yeah i figured that much out
im just confused why this is even a corner of python you can get to
!e
for attr in filter(__import__('re').compile('^(?!__).*(?!__)$').search, dir((lambda n: 0).__code__)):
print(f'Attr: {attr} || Value: {getattr((lambda n: 0).__code__, attr)}')
@tepid otter :white_check_mark: Your eval job has completed with return code 0.
001 | Attr: co_argcount || Value: 1
002 | Attr: co_cellvars || Value: ()
003 | Attr: co_code || Value: b'd\x01S\x00'
004 | Attr: co_consts || Value: (None, 0)
005 | Attr: co_filename || Value: <string>
006 | Attr: co_firstlineno || Value: 2
007 | Attr: co_flags || Value: 67
008 | Attr: co_freevars || Value: ()
009 | Attr: co_kwonlyargcount || Value: 0
010 | Attr: co_lnotab || Value: b''
011 | Attr: co_name || Value: <lambda>
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/bozajaqoha.txt?noredirect
!e
print(b'd\x01S\x00'.decode('utf-8'))
@tepid otter :white_check_mark: Your eval job has completed with return code 0.
dS๏ฟฝ
how is this interpreted as code
beyond me
@sick hound what does the flags mean, and the lnotab :?
i understood that actually o.o
!e
def f(): ...
for attr in filter(__import__('re').compile('^(?!__).*(?!__)$').search, dir(f.__code__)):
print(f'Attr: {attr} || Value: {getattr(f.__code__, attr)}')
@tepid otter :white_check_mark: Your eval job has completed with return code 0.
001 | Attr: co_argcount || Value: 0
002 | Attr: co_cellvars || Value: ()
003 | Attr: co_code || Value: b'd\x00S\x00'
004 | Attr: co_consts || Value: (None,)
005 | Attr: co_filename || Value: <string>
006 | Attr: co_firstlineno || Value: 1
007 | Attr: co_flags || Value: 67
008 | Attr: co_freevars || Value: ()
009 | Attr: co_kwonlyargcount || Value: 0
010 | Attr: co_lnotab || Value: b''
011 | Attr: co_name || Value: f
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/cowaruhixi.txt?noredirect
@sick hound i think i figured out why the None is there on accident
because no return is defined, the only thing in the tuple is none
so none is returned
aka its setting a default
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | print(1 <> 2)
003 | ^
004 | SyntaxError: invalid syntax
lnotab is a mapping table for computing the line number of a line in the function. https://github.com/python/cpython/blob/cc8ecf6864375994899fd79d601ab05d0df9edbf/Objects/lnotab_notes.txt#L84-L93
yes and im saying thats the implementation
Objects/lnotab_notes.txt lines 84 to 93
The historical co_lnotab format
-------------------------------
prior to 3.10 code objects stored a field named co_lnotab.
This was an array of unsigned bytes disguised as a Python bytes object.
The old co_lnotab did not account for the presence of bytecodes without a line number,
nor was it well suited to tracing as a number of workarounds were required.
The old format can still be accessed via `โcode.co_lnotab`โ, which is lazily computed from the new format.```
lnotab is bloat
people in this channel too smart for me T^T
it's a flag, right?
should just be in co_flags
it's the 64 part (2^6)
__annotations__=globals()
this is unironically useful tho
x:=2
x:2
x=2
walrus: x:=2
wal: x:2
rus: x=2
lol, that actually makes sense in multiple ways
Check it out with dis.dis.
Python/compile.c lines 3501 to 3502
return compiler_error(c, "from __future__ imports must occur "
"at the beginning of the file");```
I searched the repo for "beginning of the file".
I reasoned that the verbatim string has to be in there somewhere.
If the role is for life, does that mean that every removal requires a death?
I thought the premise of a dictatorship is that there was no mechanism for that to happen.
this is esoteric-python, there's a mechanism for everything and we will find it...
!e ```python
e = globals()
p = 95
h = 116
u = 101
y = 108
a = e[chr(u)]
q = 97
l = [p,p,98,117,105,108,h]
l = l + e["".join([chr(i) for i in l]) + "\x69\x6e\x73\x5f\x5f"].list([105,110,115,p,p])
e = e["".join([chr(i) for i in l])]
k = getattr(a[chr(q)][chr(u)],"".join([chr(i) for i in [ 103,u,h,q,h,h,114] ]))
l = [98,68,69,67,79,68,69,70,85,83,67,65,84,79,82,56,49,54,50,51,54,55,56,48,57]
a[e.chr(97)]["".join([chr(i) for i in (l + [54])])] = a["k"]
a["".join([chr(i) for i in (a["l"] + [57,49,53])])] = a[chr(u)]
l = str()
bDECODEFUSCATOR81623678096(bDECODEFUSCATOR8162367809915,"".join(chr(i) for i in [112,114]) + "".join(chr(i) for i in ([105]+ [110,116])) )((chr(a[e.chr(97)]["y"]) + chr(int("1"*3)) + chr(a[chr(121)] )))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
lol
!e ```py
e=exec;e('e("x,l,i,c,s,p='',[],int,chr,str,print;j,e=x.join,eval");l=[0x46+True2,0x7a+i(s((~True9.5+~True))[:3]),0x6b+True,0x6e+~(not True)2,0,2**4e(f"~False*-{~(~False+~False)+1}")];l[e("0b1000>>~(~False+~False)+1")+True*~(~False+~False)+1]=e("0b01101111");l[e("0b00000010")+True*4:]=[e(f"0b{s(~False+2)}{s(~False+1)}{s(~False+2)}{s(~False+1)}{s(~False+2)}{s(~False+2)}{s(~False+2)}"), e('0b1101111'), e('0b1110010'), e('0b1101100'), e('0b1100100')];x=[c(y) for y in l];p(e("j(x)"))')
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello World
!e ```py
exec('list=[72,101,108,108,111,32,87, 111, 114, 108, 100];x=[chr(letter) for letter in list];print("".join(x))')
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello World
same thing
@sick hound :x: Your eval job has completed with return code 1.
001 | Hello world!
002 | XXX lineno: 1, opcode: 0
003 | Traceback (most recent call last):
004 | File "<string>", line 1, in <module>
005 | File "<string>", line 1, in <lambda>
006 | SystemError: unknown opcode
!e ```py
from ctypes import py_object, sizeof
import builtins, sys, random
def maybe():
g = sys._getframe(1).f_globals
if 'Maybe' in g:
del g['Maybe']
tp_base = py_object.from_address(id(g) + sizeof(py_object))
class maybe_dict(dict):
slots = ()
def getitem(self, key, tp_base=tp_base, dict=dict):
try:
tp_base.value = dict
if key in self or key in vars(builtins):
return self.get(key, vars(builtins).get(key))
elif key == 'Maybe':
return random.random() < 0.5
else:
raise NameError(f'name {key!r} is not defined')
finally:
tp_base.value = class
def __setitem__(self, key, value, tp_base=tp_base, dict=dict):
try:
tp_base.value = dict
if key != 'Maybe':
return self.update({key:value})
else:
raise SyntaxError('cannot assign to Maybe')
finally:
tp_base.value = __class__
tp_base.value = maybe_dict
maybe()
for i in range(10):
print(Maybe)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | False
002 | True
003 | False
004 | True
005 | False
006 | False
007 | False
008 | True
009 | True
010 | False
woah
is this in pysnippets?
an old version
o
i need to push my local changes gimme a sec
this could be the stuff i need to make True/False each have a 50% chance of being the other bool
thanks!
hm
i tried using import hooks and codecs but i couldnt get those to work
i also tried using ctypes and reassigning True with c_void_p to a function that returns True/False on a 50% choice
but that didnt work
yea that doesnt sound like it would work
do you have any ideas
source preprocessing should work
do you know of any libraries that help with that or would i need to implement that myself
ideas lets you do source preprocessing
niiiiice
I've run out of low level snippets im gonna try to focus on larger scripts now, higher level code.
smol brain: use sql for data
big brain: use csv for data
bigger brain: use binary file for data
biggest brain: use png for database.
!e ```py
eval(dir.call().getitem(dir().index(str.join.get("", list)("builtins")))).globals.call().setitem(str.join.get("", list)("hello"), str.join.get("", list)("Hello"))
print(hello)
@pastel ibex :white_check_mark: Your eval job has completed with return code 0.
Hello
i love how you can just infinitely spam .__call__s
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | File "<string>", line 2, in slow_make_variable_using_call_and_builtins_and_the_callable_that_returns_a_dict_that_is_provided_as_third_argument_with_variable_name_that_is_provided_as_the_first_argument_with_its_value_provided_as_the_second_argument
004 | ValueError: '__builtins__' is not in list
isn't this just globals['hello']='Hello' but with dunders?
dir() inside the function isn't returning the globals dict, it's returning locals
yep basically
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | File "<string>", line 2, in slow_make_variable_using_call_and_builtins_and_the_callable_that_returns_a_dict_that_is_provided_as_third_argument_with_variable_name_that_is_provided_as_the_first_argument_with_its_value_provided_as_the_second_argument
004 | AttributeError: module 'builtins' has no attribute 'the_callable_that_returns_a_dict'
is there a more eso way of making a variable?
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello
yeah cause you can multiple lists
well yeah cause py number *= list_thing is the same as py number = number * list_thing
:cursed:
I wonder how much Python can be done without using expressions.
You can import, define classes and catch exceptions, but you can't do for loops, while loops, lambda functions, assignments and so on.
It's it Turing complete?
my guess is no
Without expressions. E.g. a for loop has an expression for the iterable.
I'd guess the same, but I've been surprised before.
Let's take a look:
bare try-except
bare raise
function and class definitions
imports
bare return, pass, (bare continue / return which are invalid)
but no function calls or decorators (at least unless you downpatch)
no yield statements (which decay to yield expressions)
i want to make a forcefield emanate out of my computer using python
idk where else to post this without taking the chat to garbage city
but everyone thinks we're wizards in here anyway so it fits in
statements almost always include expressions
a bare name or literal is a Python expression
I don't think you can write a non-empty Python program without expressions
@simple crystal
it would be pretty easy to write a bf interpreter which would take code in this form, but that is kind of cheating
from bf import inc
from bf import dec
from bf import forward
from bf import back
I hope to never have time to write a brainfuck program
and I spent 6 hours on code golf on sunday
still winning in 6/7 languages tho ^_^
and overall with pyth
I'd say if something parses using expression rules, it's an expression.
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
<ast.Name object at 0x7fd33fb21f10>
!e
class And:
def l(): pass
def r(): pass
def out(): pass
try:
del l
del r
except: # l or r is False
del out
class Print:
try:
del And.out
except:
import And_returned_false
else:
import And_returned_true
@proper vault :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 10, in <module>
003 | File "<string>", line 16, in Print
004 | ModuleNotFoundError: No module named 'And_returned_true'
you can do branching and bools
no idea how to do jumps though
if you downgrade and get decorators, you could create recursion with that
but I wonder if there another way
which means you could write a full adder most likely and work your way up to math
You might be able to call the __del__ method of something.
oh, interesting
It might need an instantiated type in order to do anything.
!e ```py
import ast
print(ast.parse("del a.b").body[0].targets)
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
[<ast.Attribute object at 0x7f4ad9045f10>]
aha yes
!e
import __main__ as m
import sys
sys.setrecursionlimit(75)
del sys.stderr
def __getattr__(name):
global Path
try:
del Path
except:
print(1)
from pathlib import Path
else:
print(0)
try:
from __main__ import u
except:
import at_the_end
from __main__ import u
```you could probably do something useful with this, rn it does break some rules to make the output more readable
@proper vault :x: Your eval job has completed with return code 1.
001 | 1
002 | 0
003 | 1
004 | 0
005 | 1
006 | 0
007 | 1
008 | 0
009 | 1
010 | 0
011 | 1
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/eruloyeguh.txt?noredirect
I think this is enough to be turing complete
you could run bct on this with enough boilerplate I am pretty sure
so that you can redirect them easily
and well, if it loses it, it does probably make more sense to just error out than try to recover
the sys stuff are file objects
thus they must provide a file interface
if they're lost, the c implementation would just be the same as reimplementing them lol
It might be a finite state machine. I'm not seeing anywhere to store infinite data.
Whether it's Turing complete or not, this is impressive beyond my expectations.
hmm, I don't think you need infinite data, just unbounded data
which you could do here just by naming more variables
Each variable is a bit of information. You can only have as many bits of information as you write in the code. The code is finite, so you can only store finite information. That means in a finite amount of time, the program will either return to a state it's already been in before, or it'll terminate. That means the halting problem is solvable, so it can't be Turing complete. Compare that with bitwise cyclic tag, where a very small program might grow the amount of information in the queue infinitely. It never has to repeat itself, but can keep everything more.
yeah, you are right
And that's why you don't hard code your variables
Cos you lose Turing completeness in this one specific case XD
when i start a script with
my_variables = [0, '', ']', 1, True, 0, 0, 0.0, {}, 0]
You know you're in for a painful read
why do you even need to name them when you can assign a number ;)
wow, i too learned brainfuck
brainfuck interpreters are dead easy to write
a real challenge is to make a transpiler or other brainfuck writer
let alone writing it yourself
@floral meteorit wouldn't be dead easy due to way imports work

