#esoteric-python

1 messages ยท Page 126 of 1

near gust
#

I'll take a shower then think about it

golden finch
#

note the difference

#

and... drumroll

#

!e

__import__('dis').dis('s=input()')
night quarryBOT
#

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

note how that's 10 bytes, not four

near gust
#

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

@near gust :white_check_mark: Your eval job has completed with return code 0.

2502
near gust
#

yeah... cin will be a lot weirder

floral meteor
#

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

near gust
#

Just use Java at this point

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

near gust
#

But what about cin.getline()

rugged sparrow
#
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']
>>> ```
near gust
#

cin.getline() is impossible due to parameters not being passed by reference, but by value

rugged sparrow
#

it works like cin.getline() by default

#

also nothing is impossible

vague cairn
#

Impressive!

near gust
#

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

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

floral meteor
#

nice

near gust
#

Time to port the entire c++ standard library into python

#

oh god

rugged sparrow
#

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

night quarryBOT
#

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

001 | static value
002 | static value
003 | ['static value']
rugged sparrow
#

@floral meteor ^ source

near gust
#

oh geez

#

lemme unpack this

floral meteor
#

noice

golden finch
golden finch
#

thank you for the music

floral meteor
#

yw

golden finch
#

nested bytecode modification is a beast

near gust
#

I can't seem to get it to work correctly

#

I'll try to make my own

#

I need to learn bytecode some way

golden finch
#

Slightly off-topic, but I've always wondered what the +8 means in the expression
ctypes.py_object.from_address(id(_)+8)

floral meteor
#

the __class__ of _

golden fjord
#

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

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__

golden fjord
potent comet
#

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

golden fjord
potent comet
#

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.

golden fjord
potent comet
#

Well probably not many given it's available as a global.

#

But in general you can't really.

golden fjord
potent comet
#

You can yes, you'd need to swap the pointer inside the print object.

golden fjord
#

oh okay, how does one do that then?

potent comet
#

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

golden fjord
potent comet
#

Yeah, there's probably an easier method.

golden fjord
#

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

potent comet
#

What's wrong with properties then?

#

I don't see why that needs overriding the class.

golden fjord
#

well, what's wrong is that I cannot override it's fget for predication

#

(or whichever function it calls for the matter)

potent comet
#

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.

golden fjord
#

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

sly root
#

wdym?

potent comet
#

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?

golden fjord
potent comet
#

It isn't, but you can just bind it yourself.

golden fjord
#

partialize it I guess?

golden fjord
potent comet
#

Yeah.

golden fjord
#
    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!

sly root
# sly root wdym?

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

potent comet
#

Use vars(cls), that gives back the class __dict__ - the dictionary holding all the attributes.

golden fjord
#

oh okay, so I can just loop through its items

potent comet
#

Yeah.

golden fjord
#

can i do the same with obj the instance?

potent comet
#

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.

potent comet
#

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.

golden fjord
#

so when we have properties the __get__ calls the getter or fget in this case

potent comet
#

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.

golden fjord
potent comet
#

Yeah, types.MethodType has the function and instance as attributes, then when called combines it.

golden fjord
#

Seems like there's no chance in overriding __get__ either, it's all read-only, making a new property does seem to work

golden fjord
#

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

!e

exec(type((lambda: 0).__code__)(0, 0, 0, 0, 0, 0, b'\x01', (), (), (), '', '', 0, b''))
night quarryBOT
#

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

[No output]
near gust
#

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

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

[No output]
near gust
#

!e

print( len(
"exec(type((lambda: 0).__code__)(*(0,)*6, b'\x01', *((),)*3, '', '', 0, b''))"
))
night quarryBOT
#

@near gust :white_check_mark: Your eval job has completed with return code 0.

73
near gust
#

73 chars

earnest wing
near gust
#

!e

from ctypes import *
p = pointer(c_int.from_address(5))
p[0]
night quarryBOT
#

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

[No output]
near gust
#

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

@near gust :white_check_mark: Your eval job has completed with return code 0.

63
near gust
#

Shorter somehow

earnest wing
#

ctypes.string_at

near gust
#

Wow it really is as simple as

#

!e

from ctypes import *
string_at(5)
night quarryBOT
#

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

[No output]
near gust
#

34 chars

#

And it's the same without the star import

sly root
#

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
#

alright i'm gonna do it

#

!e ```py
'' = ()
print('')

night quarryBOT
#

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

daaaaaam

#

!e ```py
{} = ()
print({})

#

wat

night quarryBOT
#

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

!e ```py
[] = ()
print([])

night quarryBOT
#

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

[]
floral meteor
#

!e ```py
() = [] = () = ''
print((),[])

night quarryBOT
#

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

() []
floral meteor
#

!e ```py
() = [] = set()
print('why does this even exist?')

night quarryBOT
#

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

why does this even exist?
chilly grail
#

!e

astral rover
#

!e import('dis').dis("[] = ()")

night quarryBOT
#

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

!e import dis;dis.dis('[] = ();a')

night quarryBOT
#

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

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

near gust
#

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?

sick hound
#

!code

night quarryBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

dire yew
#

in class:```py
a = 1

homework:```py
[] = []

the test:```py
[*[[]]], *[[]] = [[], []], [[]]

sick hound
#

!code

night quarryBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

dire yew
#

!e

[*[[]]], *[[]] = [[], *[]], [*[]]
night quarryBOT
#

@dire yew :warning: Your eval job has completed with return code 0.

[No output]
sick hound
#
>>> *[],
()
>>> type(*[],)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type() takes 1 or 3 arguments
#
>>> type(())
<class 'tuple'>
earnest wing
#

(x) == x

#

(*[],) is parsed the same as *[],

#

so type()

near gust
#

!e

from ctypes import *


def foo(x):
    print(id(x))
    d = pointer(py_object.from_address(id(x)))
    print(d[29])


a = ''
foo(a)
night quarryBOT
#

@near gust :white_check_mark: Your eval job has completed with return code 0.

001 | 140509237966448
002 | <class 'EncodingMap'>
near gust
simple crystal
#

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

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

140353205614192
simple crystal
#

ah found it

night quarryBOT
#

Objects/unicodeobject.c lines 8422 to 8424

static PyTypeObject EncodingMapType = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "EncodingMap",          /*tp_name*/```
near gust
#

!e

from ctypes import *


def foo(x):
    print(id(x))
    d = pointer(py_object.from_address(id(x)))
    print(d[83])


a = ''
foo(a)
night quarryBOT
#

@near gust :white_check_mark: Your eval job has completed with return code 0.

001 | 140359462016624
002 | <class 'member_descriptor'>
near gust
gritty mesa
#

unicodeobject.c

#

C code

thorny tapir
#

o i thought static n stuff like that was java

tribal moon
#

Java's definition of static is really different from C's definition of static, they're both completely different things with the same name

thorny tapir
#

okay

#

idk much about other langs

pastel ibex
#

doesnt static mean like non changing

tribal moon
#

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

near gust
#

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

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

001 | <class 'int'>
002 | 123
near gust
#

It's a good example of how you can just throw in subclasses sometimes when you're bored

vague cairn
#

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.

floral meteor
#

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

night quarryBOT
#

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

5
stark hinge
#

!e
print('hi')

near gust
#

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

rugged sparrow
#

@near gust explain?

near gust
rugged sparrow
#

Did you test it?

near gust
rugged sparrow
#

Well what were you trying to do

sick hound
carmine wren
#

Hii

floral meteor
#

hi

sly root
#
a = cin("test: ")
cin("test: ") >> "b"
cout << a << b```
#
str() << "a" >> (var() == cin("test: "))
cout << a```
sly root
#

ValueError: call stack is not deep enough

#

I'm using black python code formatter

#

So likely it's PEP

#

idk

distant wave
#

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

night quarryBOT
#

@distant wave :white_check_mark: Your eval job has completed with return code 0.

'test'
distant wave
#

Hm

#

Maybe not >.>

#

!e print(repr("test"))

sly root
night quarryBOT
#

@distant wave :white_check_mark: Your eval job has completed with return code 0.

'test'
distant wave
#

Nope, apparently it's ''

near gust
#

Can we just appreciate that the abbreviation for "Python Object-Oriented Programming" is POOP

rugged sparrow
#

That won't always work

sly root
#
#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"}
  }}
)```
wild relic
#

Contribute to this you demons

river idol
#

Making a custom list "literal" ๐Ÿ˜„

earnest wing
#

literals cannot be overridden, use your own type who
literals can't be overridden but you can emulate custom ones with operator overloads whom
literals can and should be overridden whomst

floral meteor
#

!e ```py
a = 1
b = 1
print(a is b is 1 is 1)

night quarryBOT
#

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

that means...

#

!e ```py
a = 1
from ctypes import*
py_object.from_address(id(1)+8).value = float; print(1)

night quarryBOT
#

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

5e-324
floral meteor
#

behold, ye nerds, and despair, literals can and should be overridden

floral meteor
#

!e ```py
a = 69
from ctypes import*
py_object.from_address(id(69)+8).value = str; print(69 + 69)

night quarryBOT
#

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

001 | 138
002 | free(): invalid pointer
floral meteor
#

wat the

#

!e ```py
a = 69
from ctypes import*
py_object.from_address(id(69)+8).value = str; print(a + 69)

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | ValueError: character U+d41f4980 is not in range [U+0000; U+10ffff]
004 | free(): invalid pointer
floral meteor
#

wat theeeee

#

!e ```py
a = 69
from ctypes import*
py_object.from_address(id(69)+8).value = str; print(a + a)

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | ValueError: character U+7e778980 is not in range [U+0000; U+10ffff]
004 | free(): invalid pointer
floral meteor
#

to U+d41f4980 or to U+7e778980 that is the question

earnest wing
#

Heh.

def cast_to_float(n: int):
    ctypes.py_object.from_address(id(0)+8).value = float
    return n
rugged sparrow
#

you would need to allocate more memory and move it there

woven bridge
#

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

night quarryBOT
#

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

.h is a c header file

#

it's c code

#

\ lets you break code into multiple lines

floral meteor
#

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

near gust
#

It's sad that I've sent a rickroll .exe file to many friends and all of them fell for it

snow beacon
#

Was it written in Python?

near gust
#

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

shut trail
floral meteor
#

lol

#

@hexed tangle XD

night quarryBOT
#

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

huh

night quarryBOT
#

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

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

sly root
#

!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": {}
}
)```

night quarryBOT
#

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

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

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

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

@near gust :white_check_mark: Your eval job has completed with return code 0.

hello world!
near gust
#

Finally printed hello world

rugged sparrow
#

Why not just LOAD_CONST, PRINT_EXPR?

near gust
#

Also I accidentally built a tuple too

#

And PRINT_EXPR didn't work for me

#

Actually no, it's because it prints the repr

near gust
#

Is there a way to turn bytecode into a function that can be called and imported?

#

Lemme check that out

tacit cobalt
#

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

night quarryBOT
#

@tacit cobalt :white_check_mark: Your eval job has completed with return code 0.

Hello World!
near gust
#

Or you could do that I guess

sick hound
#
class A:
    def __init__(
        self,
    ):
        self.i = 10

    def u(
        self,
    ):
        print(
            "TRY"
        )
        assert (
            self.i
            == 11
        )
        print(
            "DONE"
        )


A().u()

esoteric python

near gust
#

Should I try to write a library, but all functions are written in bytecode?

cloud fossil
#

How do you do that?

earnest wing
sick hound
earnest wing
#

doesn't work

sick hound
#

not expected to work

dry briar
#

!e ```raise SystemExit("hello world")

night quarryBOT
#

@dry briar :x: Your eval job has completed with return code 1.

hello world
white verge
#

;)

#

Hey can anyone guide me how to write esoteric python code

sacred umbra
#

Go everything against what PEP-8 and the Zen of Python stand against for

white berry
#

Does anyone code in c++?

#

I need some help

snow beacon
snow beacon
white verge
#

@snow beaconig you are the master wth

dire galleon
sly root
#

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

night quarryBOT
#

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

[No output]
sly root
cosmic path
#

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"

loud ibex
#

for char in "name"

cosmic path
#

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

#

Traceback (most recent call last): File "script.py", line 19, in User1.What_Is_My_ID() File "script.py", line 16, in What_Is_My_ID print(f"[Name]{name}") NameError: name 'name' is not defined

earnest wing
cosmic path
#

Ok sorry. For using wrong channel

cloud fossil
#

Also add self to it as a parameter

cosmic path
#

ฮŸk. Sorry for the late reply! Thank you.

earnest wing
#

Idea: bytecode patching to disable and/or short circuiting

near gust
#

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

rugged sparrow
earnest wing
#

it would ideally be mixed with a hacky way to overload them, but that's a different topic altogether

rugged sparrow
#

so (expr) or (expr2) would call (expr).__or__((expr2))?

#

!e py import dis dis.dis('x or y') dis.dis('x and y')

night quarryBOT
#

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

001 |   1           0 LOAD_NAME                0 (x)
002 |               2 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
#

why my data frame is showing none type

#

i need to convert it into dataframe obj

rugged sparrow
#

@gaunt ferry wrong channel, but i assume that you shouldnt call .show(...) it probably returns None

floral meteor
#

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

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

Classes Without Boilerplate <https://www.attrs.org/>
simple crystal
#

I am sick of mutating objects in place

sick hound
#

Hey guysss

simple crystal
#

HI <UNICODE PERSON>

sick hound
#

Does any of you know selenium

simple crystal
#

whya re so many ppl

#

asking for help

#

in thsi channel

sick hound
#

Cus

simple crystal
#

???

sick hound
#

I WANT help

#

And

#

Everyones afk in help

simple crystal
#

all we know is how to break python

#

!e

@__import__
@lambda a:a.__name__
class __hello__:...```
night quarryBOT
#

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

Hello world!
earnest wing
#

!e ```py
from future import annotations
hello: world
for future in annotations:
import(future)

night quarryBOT
#

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

Hello world!
simple crystal
#

!e

__hello__ = '__world__'
__import__([*vars()][-1])
night quarryBOT
#

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

Hello world!
earnest wing
#

!e ```py
@import
@lambda hello: hello.hello
@type.call
class hello: getattr = lambda hello, world: world

night quarryBOT
#

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

Hello world!
crystal marsh
#

Can anyone help me understand an enviorment digram of python ?

floral meteor
floral meteor
opaque belfry
#

hi

#

how can i print something in stdout
but
im not allowed to use print or eval or open or import sys

snow beacon
floral meteor
#

*in this channel

snow beacon
#

That prints Hello, world! to the console.

floral meteor
earnest wing
#

You can even just raise SyntaxError

#

consider exit("Hello, world!")

snow beacon
earnest wing
#

what about input("Hello, world!")?

opaque belfry
#

i should print this #pythoniscool

#

just stdout

tribal moon
#

Can't you just overwrite the printer data in copyright and then reference it to print your message

lunar moon
#

!e

__import__('__hello__')
night quarryBOT
#

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

Hello world!
opaque belfry
#

i found this

#

__builtins__.__dict__['p,r,i,n,t'.replace(',', '')]('#pythoniscool')

snow beacon
#

!e ```py
input ("#pythoniscool")

night quarryBOT
#

@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
snow beacon
opaque belfry
#

but it passed the tests

#

XD

snow beacon
#

Oh, you're trying to pass automated tests.

opaque belfry
#

yea

tribal moon
#

!e py (lambda message: copyright if not setattr(copyright, "_Printer__lines", [message]) else None)("Hello, World!")

night quarryBOT
#

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

!e

print(__builtins__.__dict__['p,r,i,n,t'.replace(',', '')] is print)
night quarryBOT
#

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

True
tribal moon
#

ยฏ_(ใƒ„)_/ยฏ

opaque belfry
#

xD

#

what can i say

opaque belfry
#

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
dire galleon
#

crap?

opaque belfry
#

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

rapid sparrow
opaque belfry
#

im still doing it manually

#

xD

#

any i guess i have to anyway

rapid sparrow
#

trying to install a package and finding out it's for python 2 = โšฐ๏ธ

opaque belfry
#

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

earnest wing
#

"p,r,i,n,t".replace(",","") no
"p"'r'"i"'n'"t" yes

opaque belfry
#

that is a string literal

#

i found this

#

import string
print(string.ascii_uppercase)

#

XD

earnest wing
#

of course it is?

opaque belfry
#

its not allowed

earnest wing
#

what?'

#

oh are you talking about your challenge?

opaque belfry
#

yea

opaque belfry
#

ha!

next flame
next flame
#

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

night quarryBOT
#

@next flame :white_check_mark: Your eval job has completed with return code 0.

ABCDEFGHIJKLMNOPQRSTUVWXYZ
next flame
#

or just do print(chr(65) +chr(66) ... + chr(90)) lol

gaunt ferry
#

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

last locust
real brook
#

Evaluate a string made up of Unicode values individually converted to characters

snow beacon
floral meteor
#

Umm

#

Wat

#

What ifcoltransg said

#

But with an extra side of "huh?"

rugged sparrow
#

anyone have any fun esoteric challenges

snow beacon
rugged sparrow
#

!e py @print @lambda c:c.__name__ class hello_world:pass

night quarryBOT
#

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

hello_world
rugged sparrow
#

@snow beacon ^

#

originally wanted to overwrite exit.__getattr__ but exit doesnt seem to be available

snow beacon
rugged sparrow
#

oo bet

#

never written a parser before so i might just write the parser first then golf it

rugged sparrow
#

im gonna write a proper parser, but wouldnt eval(inp,{'true':True,'false':False,'null': None}) work? @snow beacon

floral meteor
#

!e ```py
from _sitebuiltins import*
exit = Quitter('ctrl-z','exit')
exit(69)

night quarryBOT
#

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

[No output]
floral meteor
#

almost got the module name wrong lmao

floral meteor
night quarryBOT
rugged sparrow
#

lmk if you find any bugs (there are prob a lot)

snow beacon
rugged sparrow
snow beacon
rugged sparrow
#

leftover code from my first impl of read_str

snow beacon
#

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.

rugged sparrow
#

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

snow beacon
#

I can't see any other bugs from sight alone.

brisk gorge
#

!e

def reallycoolfunctionwithgoodname(arg):
    x = 0

    while x < 10000:
        if x == 9999:
            print(arg)
        x += 1
night quarryBOT
#

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

[No output]
brisk gorge
#

oh yeah...

#

!e

def reallycoolfunctionwithgoodname(arg):
    x = 0

    while x < 10000:
        if x == 9999:
            print(arg)
        x += 1

reallycoolfunctionwithgoodname("Dog")
night quarryBOT
#

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

Dog
snow beacon
#

You can use #bot-commands to test non-esoteric things if you want to.

brisk gorge
#

This was the only channel I have seen it used in

rugged sparrow
#

@snow beacon new version, has some more checks and doesnt use idx anymore

sly root
#

Guys, can someone help me in #help-dumpling please? My problem is related to bytecode and code object

#

I'm getting SIGSEGV

coral kernel
#

why does discord say my name was mentioned in channels like this one but can't find any messages when i look for myself?

proper vault
#

there was a raid where a bunch of selfbots spammed mentions

floral meteor
#

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

sly root
#

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

floral meteor
#

You gotta look out for any error as it generally segfaults when it tries to raise an exception

sly root
#

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([]),(),()))```
sly root
floral meteor
#

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

sly root
#

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}
))
""")
shy remnant
#

ghost ping lemon_ping

simple crystal
#

ah that too

snow beacon
#

It seems like my challenge has a substantial flaw in it.

rugged sparrow
snow beacon
#

That would help, yes.

astral rover
#
import orjson
```:^)
next flame
#

*only using stdlib, I assume

rugged sparrow
#

Explicit or otherwise

gritty mesa
#

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

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

001 | 3
002 | 6
003 | 9
gritty mesa
#

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

@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

gritty mesa
#

They said Python didn't have C-style loops

hollow kiln
#

abusing annotations ๐Ÿ› supremacy

pastel ibex
#

what's a good way to index a number without making it look like py list[0]

#

or any obvious variant of it

snow beacon
pastel ibex
#

sorry i meant index an element from a list

#

!e py li = [1, 2, 3] print(li[0])

night quarryBOT
#

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

1
pastel ibex
#

something like that but without making it obvious that the list is getting indexed

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

pastel ibex
#

i was hoping for something more abstract

snow beacon
#

As in can work with indices that aren't integers?

#
dict(enumerate(lst)).get(index)
```This works for integers.
pastel ibex
#

no like something more complex looking cause you can tell by looking at it that its still doing something with the list

snow beacon
#

What do you want it to look like it's doing?

pastel ibex
#

something that looks very esoteric

snow beacon
#

~~```py
(lambda f, args: f(*args))(lambda f, i, j, *args: (i or f(f, i, *args)) and j, lst)

pastel ibex
#

prefect

snow beacon
#

I can fuzz it a bit more, because the first lambda is a bit suspect.

pastel ibex
#

if youd like to

snow beacon
#

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

pastel ibex
#

wait does that work

snow beacon
#

It should do.

#

Wait, where's index?

#

Oh, right.

pastel ibex
#

wait where do you pass the index atXD?

#

im pretty sure lst is the list right

snow beacon
#

Oops, I've done something weird.

#

It's clearly confusing me, so hopefully it confuses others.

pastel ibex
#

id hope so XD

snow beacon
#
(lambda f, args: f(f, index, *args))(lambda f, i, j, *args: f(f, i - 1, *args) if i else j, lst)
rugged sparrow
#

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

night quarryBOT
#

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

[1, {'a': 0.1}, None]
rugged sparrow
#

@snow beacon im pretty sure thats a compliant json parser

#

still golfing further now

snow beacon
#

If you need another challenge I have one (smaller) in mind.

pastel ibex
#

these challenges are rather interesting

floral meteor
#

ooh we challenging each other now?

floral meteor
#

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

rugged sparrow
#

I'll try my hand later tonight

snow beacon
rugged sparrow
#
from ctypes import *
index=lambda l, i:py_object.from_address(c_void_p.from_address(id(l)+24).value + i * 8).value```
snow beacon
thorny tapir
#

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 ๐Ÿค”

proper vault
#

!e

with open(1, 'w') as f:
    f.write('Hello, world!')
```works on both windows and *nix
night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

Hello, world!
proper vault
#

and well, there is no peak on length, since you can always just eval the same code encoded further

thorny tapir
#

thats funny

#

what is 1 tho

proper vault
#

the 1 file descriptor, which is stdout

thorny tapir
#

o cool

rapid sparrow
thorny tapir
#

lol what does that do

rapid sparrow
thorny tapir
#

yea but how does it work

#

xD

rapid sparrow
night quarryBOT
#

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

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

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

wtf nvm

#

but that specific line

#

what does it do

#

(idk anything about esoteric python xD)

snow beacon
#

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.

lime bane
#

!e ```py
a, b = a[b:] = [4,1,2,4] , 2
print(a, b)

night quarryBOT
#

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

[4, 1, [...], 2] 2
lime bane
#

!e
a = not 1 if 5 else not 0
print(a)
a = not 1 if 1==0 else not 0
print(a)

night quarryBOT
#

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

001 | False
002 | True
pine mural
#

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

@pine mural :white_check_mark: Your eval job has completed with return code 0.

105024
loud nest
#

!e print("1")

night quarryBOT
#

@loud nest :white_check_mark: Your eval job has completed with return code 0.

1
snow beacon
floral meteor
#

what was doings?

floral meteor
floral meteor
#

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

floral meteor
#

Hi spoony!

simple crystal
#

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

golden finch
#

I return

golden finch
floral meteor
simple crystal
#

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

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

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

night quarryBOT
#

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

it already looks like less code ;)

simple crystal
#

and can't imagine I ever will

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

dire galleon
#

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

golden finch
#

So there's absolutely no way to modify it?

dire galleon
#

depends on what you want

golden finch
#

within python, somehow

earnest wing
golden finch
#

So is there a difference between type(type_object) and type.__call__(type_object)

#

That's impressively cursed.

earnest wing
#

yes, type.__call__ is an unbound method

golden finch
#

Wow.

golden finch
#
list.append(element)

vs

list+=[element]
floral meteor
#

You don't need to golf to be concise, and neither do you need to waste space wrapping the ellipsis with space

floral meteor
golden finch
#

Oh - is it equivalent?

golden finch
earnest wing
#

the convention is f.__call__(*args) => type(f).__call__(f, *args)

#

when f is not a type, your example holds

floral meteor
#

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

golden finch
#

mhm

golden finch
#

What's the longest/most interesting error message you guys have ever seen?

floral meteor
#

That would be the stack overflow from the "intuitive print" I made a long time ago

golden finch
#

mhm?

floral meteor
#

This guy commenting on one of my snippets

#

Although the specific snippet I made a wrapper that neutralized it

golden finch
#

segfaults for me

floral meteor
#

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

golden finch
#

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']
night quarryBOT
#

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

[No output]
golden finch
#

strange

#

idle-specific

floral meteor
#

Alright here's an actually challenging challenge: make an AI that generates original roasts and insults

floral meteor
night quarryBOT
#

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

001 | Fatal Python error: _Py_CheckRecursiveCall: Cannot recover from stack overflow.
002 | Python runtime state: initialized
003 | 
004 | Current thread 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

floral meteor
#

oh it works here too

#

It prints it a hundred times then adds an ellipsis after a pause, then crashes

proud kiln
#
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

rich hound
#

evil

floral meteor
#

you wanna see evil?

floral meteor
rich hound
#

I'd love to

#

but i cant

#

reply to the original message

floral meteor
#

!e ```py
a=4
from ctypes import*
(c_longlong*4).from_address(id(4))[3]=5
print(2 + 2)

night quarryBOT
#

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

what does it do

floral meteor
#

well it still printed 5 i guess

rich hound
#

wait

#

wtf

floral meteor
#

wanna see more evil?

rich hound
#

yes.

floral meteor
#

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

night quarryBOT
#

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

Hello World!
rich hound
#

what the fuck

floral meteor
#

it's a bit crude, I didn't clean up afterwards hence the segfault

#

but it works

rich hound
#

how

#

how does it work

floral meteor
#

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

night quarryBOT
#

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

?!

floral meteor
#

i swapped globals with the type hints

#

i was literally that bored that day

rugged sparrow
#

@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}]'))

night quarryBOT
#

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

i did have to sacrifice int so i just parse every number to a float

floral meteor
#

oof

rugged sparrow
#

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

floral meteor
#

lol

earnest wing
#

raise SyntaxError("Keys must be Strings") who
{}["Keys must be Strings"] whom
Keys_must_be_Strings whomst
E01 whomstd

rugged sparrow
#

Nah biggest brain is just ignoring the errors

rich hound
#

yes

clever rain
#

i made a search engine for drugs using purely python

golden finch
#

how does _sitebuiltins work?

golden finch
#

(more specifically, what can I break)

golden finch
#

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

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

@sick hound

night quarryBOT
#

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

that makes sense

#

so it's __repr__ called - but it looks like it inherits from BaseException

night quarryBOT
#

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

:o

#

now make it have a custom name

#

idk

#

u expect me to know

#

no

#

but u know more

#

what

#

??? ok

#

neither

golden finch
#

so you overrode type to make it into BaseException?

golden finch
#

wait no... +24?

#

segfault for me

clever rain
#

moving astrology upstream.

golden finch
#

the filenames
kek

clever rain
#

LMAO

slim sonnet
#

Did anyone else see the post in r/python with the ++/-- operators?

clever rain
#

Yes. Drug search engine with astrology mixed in.

golden finch
slim sonnet
slim sonnet
#

But the bytecode approach was interesting

golden finch
#

!e

__import__('dis').dis('++2')
night quarryBOT
#

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

trying to remember how ++ works

#

-- is simplier, iirc

clever rain
# slim sonnet Sounds like erowid hahaha

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

GitHub

grungegirl aims to make available a massive amount of information about different drugs offline. This tool is for the hacker that just got some new shit. grungegirl is coded in python, making it ex...

golden finch
#

!e

__import__('dis').dis('--2')
night quarryBOT
#

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

huh

#

damn compiler

#

anyhow

#

!e

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

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

001 |   1           0 LOAD_NAME                0 (x)
002 |               2 UNARY_NEGATIVE
003 |               4 UNARY_NEGATIVE
004 |               6 RETURN_VALUE
golden finch
#

there we go

#

variables only

slim sonnet
golden finch
#

!e

__import__('dis').dis('x+=1')
night quarryBOT
#

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

001 |   1           0 LOAD_NAME                0 (x)
002 |               2 LOAD_CONST               0 (1)
003 |               4 INPLACE_ADD
004 |               6 STORE_NAME               0 (x)
005 |               8 LOAD_CONST               1 (None)
006 |              10 RETURN_VALUE
clever rain
#

i'm going to do the same thing with the psychonaut wiki people.

slim sonnet
#

That's a good idea

#

Using an api is always better

golden finch
#

!e

__import__('dis').dis('x=x+1')
night quarryBOT
#

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

001 |   1           0 LOAD_NAME                0 (x)
002 |               2 LOAD_CONST               0 (1)
003 |               4 BINARY_ADD
004 |               6 STORE_NAME               0 (x)
005 |               8 LOAD_CONST               1 (None)
006 |              10 RETURN_VALUE
clever rain
#

This is going to be the best drug culture contribution.

slim sonnet
#

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

golden finch
#

!e

__import__('dis').dis('f()')
night quarryBOT
#

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

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

tepid otter
#

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

@tepid otter :white_check_mark: Your eval job has completed with return code 0.

001 | 2
002 | 0
003 | 1
tepid otter
#

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

@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

tepid otter
#

!e

print(b'd\x01S\x00'.decode('utf-8'))
night quarryBOT
#

@tepid otter :white_check_mark: Your eval job has completed with return code 0.

dS๏ฟฝ
tepid otter
#

what even

#

thats what i was thinking

tepid otter
#

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

@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

tepid otter
#

@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

night quarryBOT
#

@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
signal herald
tepid otter
#

yes and im saying thats the implementation

night quarryBOT
#

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

lnotab is bloat

tepid otter
#

people in this channel too smart for me T^T

golden finch
#

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

walrus: x:=2
wal: x:2
rus: x=2

potent cliff
#

I will now call all normal assignment operations Russian assignments

#

Thank you

earnest wing
#

lol, that actually makes sense in multiple ways

snow beacon
night quarryBOT
#

Python/compile.c lines 3501 to 3502

return compiler_error(c, "from __future__ imports must occur "
                      "at the beginning of the file");```
snow beacon
#

I searched the repo for "beginning of the file".

#

I reasoned that the verbatim string has to be in there somewhere.

snow beacon
#

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.

vague cairn
#

this is esoteric-python, there's a mechanism for everything and we will find it...

sick hound
#

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

night quarryBOT
#

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

lol
sick hound
#

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

night quarryBOT
#

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

Hello World
sick hound
#

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

night quarryBOT
#

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

Hello World
sick hound
#

same thing

night quarryBOT
#

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

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

night quarryBOT
#

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

woah

rugged sparrow
#

an old version

autumn saffron
#

o

rugged sparrow
#

i need to push my local changes gimme a sec

autumn saffron
#

this could be the stuff i need to make True/False each have a 50% chance of being the other bool

rugged sparrow
#

pushed the update

#

True and False are constants so that may be tricky

autumn saffron
#

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

rugged sparrow
#

yea that doesnt sound like it would work

autumn saffron
#

do you have any ideas

rugged sparrow
#

source preprocessing should work

autumn saffron
rugged sparrow
#

ideas lets you do source preprocessing

floral meteor
#

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.

pastel ibex
#

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

night quarryBOT
#

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

Hello
pastel ibex
#

i love how you can just infinitely spam .__call__s

night quarryBOT
#

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

dir() inside the function isn't returning the globals dict, it's returning locals

night quarryBOT
#

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

yes

#

many ways

night quarryBOT
#

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

Hello
pastel ibex
#

yeah cause you can multiple lists

#

well yeah cause py number *= list_thing is the same as py number = number * list_thing

golden finch
#

:cursed:

snow beacon
#

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?

earnest wing
#

without expression statements you mean?

#

just about everything is an expression so

golden finch
#

my guess is no

snow beacon
snow beacon
earnest wing
#

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)

clever rain
#

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

simple crystal
#

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
#

ah

#

and I forgot pass is a statement >_>

proper vault
#

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

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

proper vault
#

would you consider a in del a an expression?

#

it doesn't really get evaluated

earnest wing
#

I'd say if something parses using expression rules, it's an expression.

proper vault
#

so del is ok

#

interesting

earnest wing
#

yep

#

!e

import ast
print(ast.parse("del a").body[0].targets[0])
night quarryBOT
#

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

<ast.Name object at 0x7fd33fb21f10>
proper vault
#

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

@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'
proper vault
#

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

snow beacon
#

You might be able to call the __del__ method of something.

proper vault
#

oh, interesting

snow beacon
#

It might need an instantiated type in order to do anything.

proper vault
#

oh wait, del a.b is not acceptable

#

since a is an expression

earnest wing
#

!e ```py
import ast
print(ast.parse("del a.b").body[0].targets)

night quarryBOT
#

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

[<ast.Attribute object at 0x7f4ad9045f10>]
earnest wing
#

aha yes

proper vault
#

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

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

earnest wing
#

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

snow beacon
#

Whether it's Turing complete or not, this is impressive beyond my expectations.

proper vault
#

hmm, I don't think you need infinite data, just unbounded data

#

which you could do here just by naming more variables

snow beacon
#

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.

proper vault
#

yeah, you are right

floral meteor
#

And that's why you don't hard code your variables

#

Cos you lose Turing completeness in this one specific case XD

floral meteor
#

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

gilded spoke
floral meteor
#

a real challenge is to make a transpiler or other brainfuck writer

#

let alone writing it yourself

proper vault
#

@floral meteorit wouldn't be dead easy due to way imports work