#esoteric-python

1 messages · Page 23 of 1

meager zinc
#

its right

#

!e ```py
q=[-~x10**x9for x in range(20)]
def c(n):
i=0
while n>q[i]:n-=q[i];i+=1
return int(str(10i+~-n//-~i)[~-n%-~i])
f=lambda k,a=1:f(k-1,a*c(10
k))if k else a
for _ in range(1,7):
print(f(_))

night quarryBOT
#

@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | <string>:1: SyntaxWarning: invalid decimal literal
002 | 1
003 | 5
004 | 15
005 | 105
006 | 210
007 | 210
meager zinc
#

is not using divmod shorter

low lynx
#
q=[-~x*10**x*9for x in range(20)]
def c(n):
 i=0
 while n>q[i]:n-=q[i];i+=1
 return int(str(10**i+~-n//-~i)[~-n%-~i])
f=lambda k:0**k or c(10**k)*f(k-1)

152

meager zinc
#

what if you put it in variables

quartz wave
meager zinc
#
g=~-n;h=-~i;return int(str(10**i+g//h)[g%h])
return int(str(10**i+~-n//-~i)[~-n%-~i])
#

still longer

quartz wave
meager zinc
#

!e```py
def c(n):
i=0
while n>(t:=-~i10**i9):n-=t;i+=1
return int(str(10i+~-n//-~i)[~-n%-~i])
f=lambda k:0
k or c(10**k)*f(k-1)
for _ in range(1,7):
print(f(_))

night quarryBOT
#

@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 1
002 | 5
003 | 15
004 | 105
005 | 210
006 | 210
meager zinc
#

i=0 is necessary

#

so +4

low lynx
#

why not put the i=0 in the function argument

quartz wave
#

oh yeah

quartz wave
meager zinc
#

it's same length

#

,i=0
i=0

quartz wave
low lynx
#

yeah but newline

meager zinc
#

oh

#

the solution is f(7) on the official problem

low lynx
#

117

c=lambda n,i=0:c(k,i+1)if(k:=n+~i*10**i*9)>0else int(str(10**i+~-n//-~i)[~-n%-~i])
f=lambda k:0**k or c(10**k)*f(k-1)
pearl socket
#

!e

import ctypes
ctypes.cast(-1, ctypes.py_object)
low lynx
#

!e

from fishhook import hook
@hook(list)
def __hash__(self):
    return hash(tuple(self))
@hook(dict)
def __hash__(self):
    return hash(tuple(self.items()))

d = {[[1], 2, [3]]: 1, {1: 2, [3, {4: 5}]: 6}: 1}
print(d)
print([[1], 2, [3]] in d)
d[([1], 2, [3])] = 3
print(d) 
night quarryBOT
#

@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | {[[1], 2, [3]]: 1, {1: 2, [3, {4: 5}]: 6}: 1}
002 | True
003 | {[[1], 2, [3]]: 1, {1: 2, [3, {4: 5}]: 6}: 1, ([1], 2, [3]): 3}
#

@pearl socket :warning: Your 3.11 eval job has completed with return code 0.

[No output]
low lynx
#

this works surprisingly well

cloud fossil
#

JSON achieved

low lynx
#

ofc until you mutate the lists

#

which is why you can't hash them in the first place

cloud fossil
#

Mutation cares about hashability?

versed eagle
#

the idea of the hash is to return a unique integer for each thingy, right?

low lynx
#

!e

from fishhook import hook
@hook(list)
def __hash__(self):
    return hash(tuple(self))

a = [1]
b = [2]
s = {a, b}
print(s)
a[:] = b
print(s)
night quarryBOT
#

@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | {[1], [2]}
002 | {[2], [2]}
versed eagle
#

but i dont remember

low lynx
#

yeah

versed eagle
#

why not return id(self) then

cloud fossil
low lynx
versed eagle
#

why's that?

#

one is an int and one is a float

#

they're different objects

low lynx
#

it's how python implements hashing

cloud fossil
#

!e print(hash(1), hash(1.0))

night quarryBOT
#

@cloud fossil :white_check_mark: Your 3.11 eval job has completed with return code 0.

1 1
low lynx
#

probably because sets i would assume

#

for something like

d = {-1, 1j, 1, -1j}

you don't want

-1+0j in d

to be false

#

same with dicts

versed eagle
#

well. if you want it to be true then you could use complex numbers for all of them

#

rather than using ints for some and complex's for others

versed eagle
cloud fossil
#

Did you just answer yourself

versed eagle
#

no

#

i explained the reason for my question

#

and dismissed the line of questioning as non-important

cloud fossil
#

The line is blurry

#

With how that was phrased

low lynx
#

the idea is that hash and eq should behave in mostly the same way

#

i think at least

versed eagle
#

you mean, x == y iff hash(x) == hash(y)?

low lynx
#
The __hash__() method should return an integer. The only required property is that objects which compare equal have the same hash value; it is advised to mix together the hash values of the components of the object that also play a part in comparison of objects by packing them into a tuple and hashing the tuple.

from the docs

versed eagle
#

ah

low lynx
versed eagle
#

yeah

fair quartz
#

!e

from fishhook import hook

@hook(range)
def __contains__(self, item: int):
  return isinstance(item, int) and item >= self.start and item < self.stop and item % self.step == 0


print(2 in range(5))
night quarryBOT
#

@fair quartz :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
fair quartz
#

!e

from fishhook import hook

@hook(range)
def __contains__(self, item: int):
  return isinstance(item, int) and item >= self.start and item < self.stop and item % self.step == 0


print(2 in range(0, 4, 2))
night quarryBOT
#

@fair quartz :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
fair quartz
#

guys, how is fishook built into snekbox?
is it actually installed on the snekbox's venv or is snekbox installing dependencies dynamically then caching it?

versed eagle
fair quartz
#

ah i see

#

it is indeed built in

#

but why would such a small, yet such a good library be built-in

versed eagle
#

cause someone asked for it to be added

#

once upon a time

fair quartz
#

interesting

versed eagle
#

¯_(ツ)_/¯

#

chilaxan would know more about that than me though

low lynx
#

!e

print(5 in range(2, 10, 3))
night quarryBOT
#

@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
wide crow
sick hound
#

hey im back

fair quartz
#

i was just using it..

night quarryBOT
#

Hey @agile frigate!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

#
Missing required argument

code

rugged sparrow
dry mirage
#

snekbox itself (the server) doesn't have those dependencies

#

so security isn't a huge concern, since they're all in the isolated environment

old socket
low lynx
#

steps as well

#

but should be yeah

#

also doesn't include stop

old socket
#

Looks like it isn't?

#

I guess I can check with timeit

proper vault
#

I believe it is for int and possibly integer floats

old socket
#

I don't know if it's O(1)

#

I mean if it is, the time should be about the same

proper vault
#
In [3]: class A:
   ...:     def __eq__(s, o): return False
   ...:

In [4]: A() in range(1, 100000000000)
^C---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
Cell In [4], line 1
----> 1 A() in range(1, 100000000000)

Cell In [3], line 2, in A.__eq__(s, o)
----> 2 def __eq__(s, o): return False

KeyboardInterrupt:

In [5]: 10000000000000000000 in range(1, 100000000000)
Out[5]: False
#

it depends is the short of it

night quarryBOT
#

Objects/rangeobject.c lines 481 to 489

range_contains(rangeobject *r, PyObject *ob)
{
    if (PyLong_CheckExact(ob) || PyBool_Check(ob))
        return range_contains_long(r, ob);

    return (int)_PySequence_IterSearch((PyObject*)r, ob,
                                       PY_ITERSEARCH_CONTAINS);
}```
versed eagle
#

interesting

proper vault
#

what's funny is that this isn't telling the whole story

old socket
proper vault
#

nvm it is

old socket
#

I haven't read all of the LOC but I mean I see an iterator somewhere so I don't think it's O(1)

proper vault
#

I was testing the wrong example

old socket
#

I wonder why its iterating instead of just checking if its in the open interval though

#

Wouldn't it just be the same exact thing but less intensive

proper vault
#

a given class may only implement equality but not comparison

#
In [10]: %timeit 1e10 in range(1, 10000000)
431 ms ± 7.32 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [11]: %timeit 10 ** 10 in  range(1, 10000000)
191 ns ± 1.37 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

old socket
#

I see that would make sense

#

I would've thought there would be some optimisation for ints or something though

restive void
#

There is

proper vault
#

there is if (PyLong_CheckExact(ob) || PyBool_Check(ob)) return range_contains_long(r, ob); this thing

versed eagle
#

that's what the PyLong_CheckExact is

old socket
#

Oh lmao 😔 facepalming

proper vault
#

int is PyLong internally

old socket
#

I guess this is a TIL

rugged sparrow
#

I found a bug that lets me get into a state where I can execute python code with an exception set, anyone know any spots that I could use this to provoke even an weirder state?

versed eagle
#

wdym "with an exception set"?

#

as in, after an exception has been thrown but before its been handled?

rugged sparrow
#

results in this weird traceback py Traceback (most recent call last): File "bug.py", line 31, in <module> 1 in weird_range File "bug.py", line 22, in __gt__ print() # this is normal builtin print ^^^^^^^ File "bug.py", line 27, in __le__ raise self.E Exception: This exception is handled late

and __le__ is called directly before __gt__

#

so __le__ raises the exception, but __gt__ is called despite that

#

so the print() call happens to check for a set exception (haven't checked where yet) and finds one, so it returns NULL which triggers the interpreter to check for set exception

versed eagle
#

if you dont call print, does it just keep going?

rugged sparrow
#

yea

versed eagle
#

what happens if you raise another exception

rugged sparrow
#

until it hits something else that happens to check for an exception

versed eagle
#

while the first is in flight

rugged sparrow
#

it just overwrites the first one

versed eagle
#

ah

rugged sparrow
#

actually wait

#

my test for that was bugged

#

because i did raise Exception('second') but that call to create the exception is what was checking for an exception

#
  • yea it did just overwrite it
old socket
#

How many bugs in Cpython have you found now

#

That's gotta be at least 3 right

rugged sparrow
#

its more than that

#

i think closer to 12 or 13

old socket
#

Danmm

#

Whats the biggest vulnerability you've found so far?

rugged sparrow
#

none of them have been like critical vulns so far

#

mostly stuff that would require specific code to hit the bug so it is unlikely to see vulnerable code in the wild

fleet bridge
#

TIL: ```py

bool()
False

#

that is so cute...

meager zinc
#

what do you guys think of my anonymous recursion

#

!e

import sys, types, gc
print(
    (lambda fun,*args:fun(*args,fun))(lambda n,self_:1if n<2else self_(n-1,self_)*n,5)
)

print(
    (lambda n:1if n<2else types.LambdaType(sys._getframe().f_code,globals(),'',(n-1,),())()*n)(5)
)

print(
    (lambda n:1if n<2else[o for o in gc.get_referrers(sys._getframe().f_code)if isinstance(o,types.LambdaType)][0](n-1)*n)(5)
)
night quarryBOT
#

@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | <string>:3: SyntaxWarning: invalid decimal literal
002 | <string>:3: SyntaxWarning: invalid decimal literal
003 | <string>:7: SyntaxWarning: invalid decimal literal
004 | <string>:7: SyntaxWarning: invalid decimal literal
005 | <string>:11: SyntaxWarning: invalid decimal literal
006 | <string>:11: SyntaxWarning: invalid decimal literal
007 | 120
008 | 120
009 | 120
languid hare
#

the y combinator would like to have a word

meager zinc
#

here's a helper for anonymous recursion:

import sys, types

@lambda _:_()
class lambda_self:
    __call__=lambda _,*a,**k:types.LambdaType(sys._getframe().f_back.f_code,globals(),'',(),())(*a,**k)

print((lambda n:1if n<2else lambda_self(n-1)*n)(5))
quartz wave
rugged sparrow
#

!e ```py
import sys
import gc
def self(*args, **kwargs):
for o in gc.get_referrers(sys._getframe(1).f_code):
if isinstance(o, type(lambda:0)):
return o(*args, **kwargs)

print((lambda n:1 if n < 2 else self(n - 1) * n)(5))```

night quarryBOT
#

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

120
meager zinc
rugged sparrow
meager zinc
#

no reason in particular

#

I would guess that gc.get_referrers is slower though

#

but perhaps it's not

quartz wave
meager zinc
#

don't believe so

#

if there are multiple frames

rugged sparrow
#

technically, the order of gc.get_referrers(...) is not specified

meager zinc
#

it might work for CPython but I'm unsure about other implementations

rugged sparrow
#

sys._getframe is also a cpython implementation detail

meager zinc
#

you can replace it with inspect.getframe() which I presume is cross-impl

rugged sparrow
meager zinc
#

oh interesting

#

didn't know that

#

I'm curious if there's a shorter solution for CPython anyways because I couldn't figure out a solution with just using the sys._getframe().f_code.replace function but I feel like there should be...

#

would you have to use a Y combinator then?

#

for other non-Cpython versions?

rugged sparrow
#

yea

#

my personal rule of thumb is if an object uses attributes like prefix_attrname (f_code, gen_code, etc) that object is probably a cpython implementation detail and those attributes are not part of the spec

meager zinc
#

well _getframe is different - there are other functions that are not implementation specific that have a _name scheme

rugged sparrow
#

afaik all the functions with the _name scheme are either implementation specific or not guaranteed stable api

#

what other ones are there?

meager zinc
#

not stable

#

I am referring to the platform-specific modules

#

and also

#

non-stable apis

#

such as

#

pickle._Pickler

rugged sparrow
#

i would consider stuff like pickle._Pickler as implementation specific since they are defined in C

meager zinc
#

I suppose

#

Yeah RustPython gives:

Traceback (most recent call last):
  File "<wasm>", line 5, in <module>
  File "<wasm>", line 5, in <lambda>
  File "gc", line 113, in get_referrers
NotImplementedError

or (compiler panic!?)

RuntimeError: panicked at 'The symbol must be present in the symbol table, even when it is undefined in python.', compiler/src/compile.rs:436:48

or

Traceback (most recent call last):
  File "<wasm>", line 3, in <module>
  File "<wasm>", line 3, in <lambda>
TypeError: unexpected payload for __call__
rugged sparrow
#

interesting that RustPython is using the webassembly build

meager zinc
#

that's not local

#

Rust is a "first-class citizen" for WASM so practically all things that can be used on WASM have been.

rugged sparrow
#

ah makes sense

meager zinc
#

the panic is from this:

import sys, types

@lambda _:_()
class lambda_self:
    __call__=lambda _,*a,**k:types.FunctionType(sys._getframe().f_back.f_code,globals(),'',(),())(*a,**k)

print((lambda n:1if n<2else lambda_self(n-1)*n)(5))
#

I don't know what part makes it bad

#

might be the @lambda _:_()

#

because

#
import sys
import gc
self=lambda *a,**k:types.LambdaType(sys._getframe().f_back.f_code,globals(),'',(),())(*a,**k)

print((lambda n:1 if n < 2 else self(n - 1) * n)(5))

gives that "TypeError: unexpected payload for __call__"

#

I'm gonna look into the source for RustPython and see if I can construct a RustPython version

meager zinc
#

it's more tricky than I thought

#

it can't bind the FuncArgs to the &VirtualMachine and it seems that is because the RustPython actually prevents type coercion in that stage

proper vault
#

Esoteric challenge - probably impossible without C tricks like einspect. Get at the raw yielded value of an async generator - that is, the wrapped value object.

#

Hopefully it still exists in 3.11

proper vault
night quarryBOT
#

Python/ceval.c line 2637

PyObject *w = _PyAsyncGenValueWrapperNew(retval);```
proper vault
#

You normally can't access it, but it is a python object

#

It is unwrapped by AsyncGenASend

#

No idea where it is in 3.11 though

#

If it even still exists

quartz wave
quartz wave
#

!e @proper vault this? ```py
from opcode import opmap
async def g(): yield 2

g.code = g.code.replace(co_code=g.code.co_code.replace(opmap['YIELD_VALUE'].to_bytes(), opmap['RETURN_VALUE'].to_bytes()))

print(anext(g()))

night quarryBOT
#

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

<async_generator_asend object at 0x7f5215ecbb80>
fleet bridge
#

!e ```py

async def g(): yield 2
import dis
dis.dis(g)

night quarryBOT
#

@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 |   1           0 RETURN_GENERATOR
002 |               2 POP_TOP
003 |               4 RESUME                   0
004 |               6 LOAD_CONST               1 (2)
005 |               8 ASYNC_GEN_WRAP
006 |              10 YIELD_VALUE
007 |              12 RESUME                   1
008 |              14 POP_TOP
009 |              16 LOAD_CONST               0 (None)
010 |              18 RETURN_VALUE
proper vault
#

Huh, in 3.11 it's an instruction

#

In 3.10 it's just special behavior of YIELD_VALUE

fleet bridge
#

Is it true that between lines (= after one statement is completely executed) stack is always empty?

proper vault
#

Afaik no, for example a with statement leaves the context manager on the stack for its body

#

What should hold however is that the stack before and after a statement is the same

#

There could be exceptions though

fleet bridge
#

Indeed.
I am asking that because i am thinking about safety of goto inside of one function. I guess, it is safe to jump inside one "block" statement (with, for, try-except, ...)

proper vault
night quarryBOT
#

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

<async_generator_wrapped_value object at 0x7f58969f9120>
remote prawn
#

hi guys can you recommend any obfuscator?

fleet bridge
#

how to compile dis.get_instructions(codeobj) back to code object?
is it possible?

fleet bridge
#

how to get the exact number of CACHE entries every instruction needs?

#

seems like LOAD_GLOBAL uses 5, LOAD_ATTR - 4, POP_TOP - 0

rugged sparrow
#

dis.get_instructions(codeobj, show_caches=True) will include cache ops

fleet bridge
#

my code turned to mess again

#

so i am now using bytecode package for bytecode manipulations

#

it is a lot easier with this package

#
@goto
def gcd(a: int, b: int) -> int:
    label.start
    if a < b:
        goto.swap
    else:
        goto.main
    label.swap
    a, b = b, a
    label.main
    a, b = b, a % b
    if not a:
        goto.end
    if not b:
        goto.end
    goto.start
    label.end
    return a
``` now it works
rugged sparrow
#

nice

golden finch
#

Does anybody have a reference implementation of __build_class__? I'm looking to cook up something cursed

restive void
night quarryBOT
#

Python/bltinmodule.c line 88

/* AC: cannot convert yet, waiting for *args support */```
golden finch
#

I could have sworn someone posted one here before

golden finch
#

I've used that in the past, but there are some weird edge cases where it doesn't work and I'm not sure why

versed eagle
golden finch
#

(See #bot-commands message for traceback & code)

golden finch
#

Bug fixed, the line

newnamespace = func(namespace)

should be replaced with

import copy
newnamespace = copy.copy(namespace) # do I need to deepcopy this? not sure about impementation details
exec(func.__code__,func.__globals__,newnamespace)
quartz wave
golden finch
#

I can't think of anything that would ever trigger that

quartz wave
versed eagle
#

!e metaclasses can be used to create a forwards linked list

def tp_linked_list(data_to_encode):
    class end_link(type, metaclass = type):
        pass
    current_link = end_link
    for obj in tuple(data_to_encode)[::-1]:
        class link(type, metaclass = current_link):
            next = current_link
            data = obj
        current_link = link
    return current_link


ll = tp_linked_list((1, 2, 3))
print(ll.data)
print(type(ll).data)
print(type(type(ll)).data)
print(type(type(type(ll))).data) # errors, since it goes out of bounds of the list
night quarryBOT
#

@versed eagle :x: Your 3.11 eval job has completed with return code 1.

001 | 1
002 | 2
003 | 3
004 | Traceback (most recent call last):
005 |   File "<string>", line 17, in <module>
006 | AttributeError: type object 'end_link' has no attribute 'data'
languid hare
#

ive been told that in the lean language, type = type 1, type (type 1) = type 2, type (type 2) = type 3, etc

versed eagle
#

kinda reminds me of church encoding for numbers

languid hare
versed eagle
versed eagle
#

oh cool so

#

lean is based off of lambda calculus

#

no wonder i thought of church encoding lmao

pearl socket
#

!e

from ctypes import c_void_p
c_void_p.from_address(id(True)+8).value = id(False)
c_void_p.from_address(id(False)+8).value = id(True)
night quarryBOT
#

@pearl socket :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).

[No output]
rugged sparrow
#

That code is changing the type of True to False and vice versa, since True and False are not types it crashes

golden finch
#
class Namespace(dict):
    def __init__(self):
        self.times = {}
    def __setitem__(self,name,value):
        if isinstance(value,type(lambda:0)) and type(value.__doc__)is str and value.__doc__.isnumeric():
            if name not in self or name in self.times:
                if name in self.times:
                    if int(value.__doc__)>self.times[name]:
                        self.times[name]=int(value.__doc__)
                        dict.__setitem__(self,name,value)
                else:
                    self.times[name]=int(value.__doc__)
                    dict.__setitem__(self,name,value)
        else:
            dict.__setitem__(self,name,value)

@lambda f:setattr(__builtins__,"__build_class__",f)
def build_class(func, name, *bases, metaclass=None, **kwds):
    if metaclass is None:
        if not bases:
            metaclass = type
        else:
            metaclass = bases[0].__class__
    if hasattr(metaclass,"__prepare__") and metaclass is not type:
        namespace = metaclass.__prepare__(name, bases, **kwds)
    else:
        namespace = Namespace()
    exec(func.__code__,func.__globals__,namespace)
    return metaclass(name, bases, dict(namespace), **kwds)

demo:

#
class Foo: # it hooks the internal class creation process itself, no special syntax needed
    def A(): # later timestamps override newer ones
        '1678163895'
        print('New A')
    def A():
        '1678163878'
        print('Old A')
    
    def B():
        print('Old B')
    def B():
        print("Methods without a version docstring will override all others, including themselves if defined sequentially")
    def B():
        '1'
        print('Old B1')

    attr = 'Attributes are unaffected'
        

Foo.A() # New A

Foo.B() # Methods without a version docstring will override all others, including themselves if defined sequentially

print(Foo.attr) # Attributes are unaffected
quartz wave
golden finch
#

tysm

nimble mirage
unique heath
#

esopy starter pack:
ctypes
~
lambda
@ hook
;

fleet bridge
#

segfaults

#

implementation details

unique heath
low lynx
#

love it when i segfault in python

quartz wave
#

!e love it when ```py
from _testcapi import*;fatal_error(b"unspecified reason")

night quarryBOT
#

@quartz wave :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).

001 | Fatal Python error: test_fatal_error: unspecified reason
002 | Python runtime state: initialized
003 | 
004 | Current thread 0x00007f17f07da740 (most recent call first):
005 |   File "<string>", line 1 in <module>
006 | 
007 | Extension modules: _testcapi (total: 1)
unique heath
#

lmao

#

me when i segfault in py:

silent tartan
unique heath
#

i dont think you want to be here

low lynx
#

this is the forbidden lands

quartz wave
low lynx
#

tfw import discord as np

silent tartan
#

what is esoteric ?

#

whts this about

quartz wave
winter basin
#

Can you shortest this?

#

from collections import deque
t = int(input())
for _ in range(t):
s = input().rstrip()
n = int(input())
a = input().rstrip()[1:-1].split(',')
if a[0]=='':
a=deque()
else:
a=deque(a)
f = False
fa = False
for i in s:
if i=='R':
fa=not fa
elif i=='D':
if not a:
f=True
break
if fa:
a.pop()
else:
a.popleft()
if f:
print('error')
else:
if fa:
a.reverse()
print('[{}]'.format(','.join(a)))

gleaming linden
sick hound
#

is there a way i can obfuscate my code in python very good

gleaming linden
winter basin
#

thanks

versed eagle
#

this saves a char
a=a if a[0]else[] -> a=a[0]and a or[]

#

which gives us this

I=input;P=print
for _ in range(int(I())):
 s=I().rstrip();I();a=I().rstrip()[1:-1].split(',');a=a[0]and a or[];f=0
 for i in s:
  if i=='R':f=1-f
  if i=='D':
   if not a:P('error');break
   a.pop(-f)
 else:P(f'[{",".join(a[::1-2*f])}]')
versed eagle
#

does anyone happen to have an implementation of the cpp written in Python?

pure dew
#

the cpp?

sick hound
versed eagle
#

the program is called cpp on most Unix-based systems

night quarryBOT
#

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

Hello World.
quartz wave
#

!e ```py
print("".join(sum([[*_]for _ in zip("hlowrd", "el ol.")],[])).title())

night quarryBOT
#

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

Hello World.
upper helm
#

i was discussing the classic “how cursed can you make isOdd when you dont use mod 2” with some friends, and ended up with these two:

isOdd = lambda n:("{:n}".format(n/2)*2)[-2]=="."

isOdd = lambda l:l//2-l/2
using l for confusion with 1 is sorta cheating as far as I’m concerned so
isOdd = lambda v:v//2-v/2
probably looks nicer as it goes with the angle of the /

quartz wave
#

destroyed

upper helm
#

well i wasn’t golfing :P

versed eagle
#

if you dont care about length then a few longer options can be employed

#

such as,

from ctypes import *
is_odd = lambda n: bool(c_int8.from_address(id(n) + 24).value & 1)
old socket
#

!e print(2**8)

night quarryBOT
#

@old socket :white_check_mark: Your 3.11 eval job has completed with return code 0.

256
old socket
#

!e ```py
from ctypes import *
is_odd = lambda n: bool(c_int8.from_address(id(n) + 24).value & 1)

is_odd(257)

night quarryBOT
#

@old socket :warning: Your 3.11 eval job has completed with return code 0.

[No output]
old socket
#

Oh I guess not?

versed eagle
#

it does

#

but it doesn't matter

old socket
#

Past 8-bits?

versed eagle
#

because after 255

#

is 0

#

which is even

#

odd and even always alternate

#

so the overflow doesn't matter

old socket
#

Oh okay

sick hound
versed eagle
#

yeah. though ive started writing my own since i couldnt find one

#

its a lot harder than i thought it'd be

sick hound
#

doesn't have conditions yet though I should get back

#

also oops I missed your reply earlier

sly ibex
#

hey guys is a bad practice to use the all() method? or why i never see it?

quartz wave
sly ibex
low lynx
#

esopy doesn't have bad practices

quartz wave
sly ibex
#

forget it

low lynx
#

if you're talking about outside of esopy I use all pretty often
lambdas are more for esopy

sly ibex
#

i already ask you if you use all and you say "all? whats that"

#

hashtag stickie

low lynx
#

I didn't realize you meant the function all

fleet bridge
#
@goto
def test_loop(l: list[int], x: int) -> list[int]:
    res: list[int] = []
    for i in l:
        if i == x:
            goto.loop2
        res.append(i)
    for i in ():
        res.append(i)
        label.loop2
    return res

assert test_loop([1, 2, 3, 2, 4, 5], 2) == [1, 3, 2, 4, 5]
#

this code removes first occurrence of x in l

fleet bridge
#

i can commit it

#

wait a minute

fleet bridge
#

it requires only bytecode package

#

it works on this version: 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)]
i didn't test it on other versions

versed eagle
#

ty

versed eagle
dry mirage
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | True
002 | True
cloud fossil
#

Is it True because the answer is swapped or is it True because the boolean literals' values are swapped

#

It's like the paradox where you ask someone whether they lied to you and they answer yes, what would you make out of it pithink

fleet bridge
#

No, im wrong

#

bool.__repr__ works like this:
lambda self: "True" if id(self) == TRUE_ID else "False", where TRUE_ID is a pointer to True that is hardcoded in binary code.
When you swap True and False, their values are swapped, but reprs are still the same.
So repr(True) is "True" even after swap

#

And in this example == returns True, because 0 and True(that is swapped with False) are equal, so the output is True

#

!e __import__("dis").dis("True==1")

night quarryBOT
#

@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 |   0           0 RESUME                   0
002 | 
003 |   1           2 LOAD_CONST               0 (True)
004 |               4 LOAD_CONST               1 (1)
005 |               6 COMPARE_OP               2 (==)
006 |              12 RETURN_VALUE
dry mirage
#

technically both of those prints return the value of False, it just happens that bool repr uses object identity

#

despite swapping the memory of False and True, their reprs won't change

vast wave
#

this is real

#
from ctypes import c_void_p
tp = type("", (), {})
c_void_p.from_address(id(object)+8).value = id(tp)
object.<tab>
#

i really need to learn how the structure of all of this works

cursive moon
#

!e```py
def fib():
a, b = 0, 1
for i in range(20):
print(a)
a, b = (a ^ b) & ((1 << 32) - 1), ((a & b) << 1) & ((1 << 32) - 1)

fib()

night quarryBOT
cursive moon
#

Lmao

versed eagle
#

for starters, at least

dry mirage
vast wave
#

the [1] is from my shell btw

dry mirage
#

tab is invalid syntax, that shouldn't get pass compiling stage

vast wave
#

doing object.<tab here> segfaults for me at least

dry mirage
#

so I don't see how it can segfault

dry mirage
#

oh do you have the autosuggest on?

vast wave
#

pressing tab in the repl shows suggestions

#

that's what's happening here

#

i don't know why it crashes but its funny nontheless

versed eagle
#

the [1] is part of the shell message for the segfault on some machines

dry mirage
#

maybe the autocomplete fetching attributes crashes

vast wave
#

probably

dry mirage
#

but it's not too strange

versed eagle
#

well you set the type of object to an integer

#

so accessing any attributes of object would break, right?

dry mirage
#

well no it set the pointer to the address of tp

versed eagle
#

oh wait- i read it wrong

dry mirage
#

but object isn't supposed to have a type of that

vast wave
#

that's why it crashed

dry mirage
#

sometimes cpython makes assumptions to locate object

versed eagle
#

sorry! thought it said py_object not c_void_p
apparently im too tired to read lmao

dry mirage
#

also you might have to incref your new type so it doesn't get GC'd

versed eagle
#

from being assigned to tp

#

it'd be stored in the globals dict

dry mirage
#

well, not in the repl but

#

normally it would

#

!e

from einspect import view, unsafe

with unsafe():
    view(object).type = type("", (), {"a": 123})
    
print(object.a)
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

123
versed eagle
# dry mirage normally it would
~: $ cat gc_test.py 
import gc

tp = type("test", (), {})

gc.collect()

print("tp" in globals())
~: $ python3 gc_test.py 
True
#

the variable never goes out of scope so it never gets collected

dry mirage
versed eagle
#

well yeah

dry mirage
#

regardless it's not safe ref counting wise

#

object is supposed to "own" the reference to its type

versed eagle
dry mirage
#

since object will DecRef the type as it owns it

versed eagle
dry mirage
#

not with object, no, but other types yeah

versed eagle
#

ah. you meant, it's not safe in general
not that its not safe for this specific case

#

i misunderstood what you meant originally

dry mirage
#

!e

from ctypes import c_void_p

tp = type("", (), {})

def main():
    class Foo:
        pass
    c_void_p.from_address(id(Foo)+8).value = id(tp)

main()
print(tp)
night quarryBOT
#

@dry mirage :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).

<class '__main__.'>
fleet bridge
#
>>> res(1,x=2)
Traceback (most recent call last):
...
UnboundLocalError: cannot access local variable '_c' where it is not associated with a value
>>> res(1,x=2,_c=3)
Traceback (most recent call last):
...
TypeError: _test.<locals>.f() got an unexpected keyword argument '_c'
``` cursed
quartz wave
#

!e ```py
def f(a,*,x):_c=2;del _c;_c
f(1,x=2)

night quarryBOT
#

@quartz wave :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 |   File "<string>", line 1, in f
004 | UnboundLocalError: cannot access local variable '_c' where it is not associated with a value
quartz wave
#

!e ```py
def f(a,*,x):_c=2;del _c;_c
f(1,x=2,_c=3)

night quarryBOT
#

@quartz wave :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | TypeError: f() got an unexpected keyword argument '_c'
quartz wave
#

ok

fleet bridge
#

I removed arg _c but forgot to change LOAD_FAST _c

golden finch
#
# Create the hook
import ctypes

globals_type=ctypes.py_object.from_address(id(globals())+8) # extract the type of the globals() dict

class new_globals(dict):
    __slots__=()
    def __getitem__(self,name,bound1=dict,globals_type=globals_type):
        try:
            globals_type.value = bound1
            if name[0]=='λ' and len(name)>1:
                return 'λ'
            return self[name]
        finally:
            globals_type.value=__class__

globals_type.value = new_globals # so when methods are looked up they are looked up in the new globals

I've been digging through some of my old snippets I've been experimenting on that I saved from this channel, and I found this one, which I never understood how it worked.
Specifically
• Why does adding an except clause crash?
• Why do we need to bind dict and the globals type to the local scope?
• Why do we need __slots__?
• Why do we set the globals type's value to __class__ (which should be undefined, but isn't, apparently?)?
I presume what this is doing is modifying the class of globals so it has a modded __getitem__ method

versed eagle
#

__slots__ is to prevent it from segfaulting

#

setting it to __class__ is to set it back to the same type

#

since it gets set to dict in the try block

#

binding the things to local scope is so it doesn't recurse

#

because if they're global, then accessing them leads to calling the __getitem__ method again

#

though there's a better way to do that imo

rugged sparrow
versed eagle
#

mhm

#

cause it prevents the creation of __dict__

#

and some reference stuff

rugged sparrow
#

(Along with other cache space)

golden finch
rugged sparrow
#

it is a magic variable, part of how argumentless super works

#

its added as a cell variable at compile time if __class__ or super is referenced

#

!e ```py
class A:
def foo():
super

print(A.foo.closure[0].cell_contents is A)```

night quarryBOT
#

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

True
golden finch
#

thanks

rugged sparrow
# golden finch thanks

yea back when I first wrote that hook strategy it seemed like the best/only way to get a safe stable reference to the class itself

versed eagle
#

chilaxan, i have a question

#

why is ob_refcnt signed?

night quarryBOT
#

Include/object.h lines 102 to 106

struct _object {
    _PyObject_HEAD_EXTRA
    Py_ssize_t ob_refcnt;
    PyTypeObject *ob_type;
};```
fleet bridge
#

To catch reference related errors

versed eagle
#

negative values are used to indicate errors then?

fleet bridge
#

If you do REF_DEC too often, ob_refcnt will eventually become negative

versed eagle
#

right

fleet bridge
#

Otherwise if ob_refcnt is unsigned, it would be difficult, because 0-1==2**32-1

versed eagle
#

2**32-1 > 0

fleet bridge
#

And i guess there is no if (ob_refcnt==0) then throw BadReferenceError; check in REF_DEC in release mode because it would be a bit slow

#

It is actually Py_DECREF, not a REF_DEC 🙃

versed eagle
#

dw, i understood what you meant

proud elbow
#

what happens if you define

#

a dunder method as a lambda?

vast wave
languid hare
#

as long as you can call it i see no reason to expect anything out of the ordinary

low lynx
#

that's how they're usually defined if you're using the type constructor

languid hare
#

!e

class EmptyString:
  __str__ = str

print(repr(str(EmptyString())))
rugged sparrow
# versed eagle why is `ob_refcnt` signed?

When compiled with debug mode there is an assert that is hit if any refcount hits a negative value, which acts like a rudimentary catch all for refcounting bugs. And it would be essentially impossible (on average current hardware) to produce enough references to a given object to need an unsigned 8byte value for the refcount

night quarryBOT
#

@languid hare :white_check_mark: Your 3.11 eval job has completed with return code 0.

''
rugged sparrow
languid hare
#

mm

fleet bridge
#

Also, today's 64-bit pointers are not actually containing 64 bit of data, there is a lot of unused values

#

!e print(object())

night quarryBOT
#

@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.

<object object at 0x7f5716524160>
dry mirage
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

1
dry mirage
#

though I guess it isn't really bound

fleet bridge
#

Yes, builtin_function_or_method class doesn't implement descriptor methods

#

!e ```py
def f():...
f.get # ok
print.get # should fail here

night quarryBOT
#

@fleet bridge :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | AttributeError: 'builtin_function_or_method' object has no attribute '__get__'. Did you mean: '__ge__'?
vast wave
#

!e ```py
print(hasattr(print, "code"))
print = lambda *x: print(x)
print(print.code)

night quarryBOT
#

@vast wave :x: Your 3.11 eval job has completed with return code 1.

001 | False
002 | Traceback (most recent call last):
003 |   File "<string>", line 3, in <module>
004 |   File "<string>", line 2, in <lambda>
005 |   File "<string>", line 2, in <lambda>
006 |   File "<string>", line 2, in <lambda>
007 |   [Previous line repeated 996 more times]
008 | RecursionError: maximum recursion depth exceeded
#

@vast wave :x: Your 3.11 eval job has completed with return code 1.

001 | False
002 | Traceback (most recent call last):
003 |   File "<string>", line 3, in <module>
004 |   File "<string>", line 2, in <lambda>
005 |   File "<string>", line 2, in <lambda>
006 |   File "<string>", line 2, in <lambda>
007 |   [Previous line repeated 996 more times]
008 | RecursionError: maximum recursion depth exceeded
vast wave
#

i forgor

#

!e ```py
orig_pr = builtins.print
print(hasattr(print, "code"))
print = lambda *x: orig_pr(*x)
print(print.code)

night quarryBOT
#

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

001 | False
002 | (<code object <lambda> at 0x7fcc123258b0, file "<string>", line 3>,)
vast wave
#

funny way to detect if a builtin has been overwritten btw

#

check if it has a __code__

dry mirage
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | False
002 | 50
low lynx
#

ah yes ml_meth

#

my favourite drug

sick hound
#

anyone knows how to get the pytransform runtime files from pyinstxtractor

#

i extracted all files of an exe with pyinstxtractor and then decompiled the main file with uncompyle6 the code is protected with pyarmor and i cant seem to find its runtime files in the folder which pyinstxtractor made

low lynx
#

!e

stuff = iter([2, 4, 0, 1, 7, 3, 5])
input = lambda _: print(_) or next(stuff)

*I,r=7,0,5,2,4,6,3,8,1,range
d=lambda:"\n".join(' '.join(map(str,x))for*x,in zip(*[iter([i,*"xo"][b[i]]for i in I)]*3))
b=[p:=0]*9
while(e:=next((b[x]for x in r(9)for y in r(x)for z in r(y)if x+y+z==12and b[x]&b[y]&b[z]>0),69))>13>sum(b):
 if b[o:=int(input(f'Player {p+1}, enter a cell:\n{d()}\n'))]<1:b[o],p=1+p,1-p
print(d()+("\nIt's a tie.",f'\nPlayer {e} wins!')[e<3])
night quarryBOT
#

@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | <string>:7: SyntaxWarning: invalid decimal literal
002 | Player 1, enter a cell:
003 | 7 0 5
004 | 2 4 6
005 | 3 8 1
006 | 
007 | Player 2, enter a cell:
008 | 7 0 5
009 | x 4 6
010 | 3 8 1
011 | 
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/acobiwijuz.txt?noredirect

low lynx
#

kinda golfed tic tac toe

#

uses the magic square method

#

i think it should work

kindred stone
#

trying to make this the most unnecessarily complicated as possible

console = (lambda o:(setattr(o,"log",print))or o)(type("",(),{}))
console.log("i hate js")
noble locust
#

I've re-framed the problem.
I now have a 2D numpy array, and an equivalent 2D mask.
However, if I try to use boolean indexing I get a 1D array.
Is there a way to keep the shape of the original array and mask and fill the "false" values with something?

vapid finch
noble locust
#

I want a[mask] to somehow return a 3x3 matrix that would look like this:

0, -1, 3,
-1, 5, -1,
7, -1, 9
#

Hmmm, actually it's not even that

#

Now that I think about it, it's that my mask has at most 10 elements == True in each row

vapid finch
#
a2 = a.copy()
a2[mask] = -1

?

#

Or a2[~mask]?

noble locust
#

Sort of

#

My mask has at most 10 elements true, some rows have less.
I somehow want the output to have shape (n, 10), filled with invalid values when not

vapid finch
#

np.nonzero will help with this somewhat. But I don't know a good way to pad things like you want.

vapid finch
#

@noble locust The best way I can think of to do this is:

import operator

import numpy as np

a = np.arange(9).reshape(3, 3)
mask = np.array([[True, False, True], [False, True, False], [True, False, True]])

b = np.full((3, 2), -1)

for src_row, dst_row, nzs in zip(a, b, map(operator.methodcaller('nonzero'), mask)):
    dst_row[:nzs[0].size] = src_row[nzs]
versed eagle
versed eagle
#

i think you have the wrong channel

#

this still isn't the right channel

#

what you're looking for is #bot-commands

#

ah

#

yeah, this channel is for esoteric python

#

#bot-commands is for general bot stuff
or running commands that aren't specifically related to a channel

sly ibex
#

@low lynx

sly ibex
low lynx
#

yeah syrulol had that issue as well

#

it's a python version issue

#

i think

#

something along those lines

arctic skiff
night quarryBOT
#

@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.

...
arctic skiff
#

!e```py
globals().update({'cout':type('cout',(),{'lshift':lambda self,:(print(,end=''),self)[-1]})()})

cout << 'hello ' << 'world';
cout << '...';```

night quarryBOT
#

@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.

hello world...
sick hound
#

That's actually amazing.

#

!e```
class cin:
def rshift(self, _):
global x

    j = input()
    
    x = j

globals().update({"cin" : cin()})

x = None
cin >> x;

print(x)

night quarryBOT
#

@sick hound :x: Your 3.11 eval job has completed with return code 1.
:warning: Note: input is not supported by the bot :warning:

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 11, in <module>
003 |     cin >> x;
004 |     ~~~~^^~~
005 |   File "/home/main.py", line 5, in __rshift__
006 |     j = input()
007 |         ^^^^^^^
008 | EOFError: EOF when reading a line
sick hound
#

oh forgot

dry mirage
#

!e so this is fixed now with snekbox updating to einspect 0.5.12

from einspect import impl

@impl(int)
def __getitem__(self, item):
    return self * item

x = 5
print(x[2])
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

10
low lynx
#

FubukiYay what was the issue before?

dry mirage
#

the PyMethods allocation was just for subclasses and not all subclasses of subclasses

#

like adding __getitem__ here requires allocating tp_as_sequence / tp_as_mapping for int

#

since those fields previously were null

#

!e also TpFlags is a enum.IntFlag now

from einspect import view

print(repr(view(list).tp_flags))
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

<TpFlags.SEQUENCE|IMMUTABLETYPE|BASETYPE|READY|HAVE_GC|VALID_VERSION_TAG|MATCH_SELF|LIST_SUBCLASS: 38294816>
dry mirage
#

!e and the NULL singleton can now be used in more places, auto converting to the appropriately typed null value

from einspect import view, NULL

view(int).tp_as_number[0].nb_power = NULL

print(3 ** 85)
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 5, in <module>
003 |     print(3 ** 85)
004 |           ~~^^~~~
005 | TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'int'
versed eagle
#

exciting

dry mirage
#

TypeView.__delitem__ will also remove existing methods with null and with the ability to restore them later

#

!e

from einspect import view

del view(int)["__pow__"]

print(3 ** 85)
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 5, in <module>
003 |     print(3 ** 85)
004 |           ~~^^~~~
005 | TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'int'
dry mirage
#

!e

from einspect import view

del view(int)["__pow__"]

view(int).restore("__pow__")

print(3 ** 85)
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

35917545547686059365808220080151141317043
versed eagle
#

can you use orig on view(sometype)["some_method"]?

dry mirage
#

hm? like how

versed eagle
#

orig(view(sometype)["some_method"])(args_to_some_method...)

#

something like that?

#

idk

dry mirage
#

like for non builtin types?

versed eagle
#

at all

dry mirage
#

yeah it works the same way

#

!e

from einspect import view, orig

class Foo:
    def abc(self):
        return 5

view(Foo)["abc"] = lambda s: 100

print(Foo().abc())
print(orig(Foo).abc(Foo()))
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 100
002 | 5
dry mirage
#

orig(<type>) gives you a view of that type before any modifications

versed eagle
#

mhm

#

oh hey i have an idea

#

you could store all changes to a type on a stack
and then the type can be accessed as any of its past states

#

well, maybe not all changes

#

but "high level" changes

#

such as using impl on it
or stuff like that

#

sorry for my stupid ideas. its well past when i should have gone to bed so my brain isn't functioning quite properly anymore

dry mirage
#

hm, how would you specify which past state though

versed eagle
#

good question
i hadnt thought that far ahead yet

#

i assume you'd want to support two separate ways though

#

index based and key based
since it'd be nice to do something like "i want the 4th state of this class" or "i want the -1th state (the most recent state) of this class"
and also "i want the state of this class right after X change was made to it"

#

both would be super useful to be able to do

dry mirage
#

might be interesting yeah firT

low lynx
#

!e

from einspect import view, orig
class Foo:
    def abc(self):
        return 5

view(Foo)["abc"] = lambda s: 100

print(Foo().abc())
print(orig(Foo)().abc())
print(orig(Foo).abc(Foo()))
night quarryBOT
#

@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 100
002 | 100
003 | 5
dry mirage
#

only attribute calls are forwarded

#

__call__ is like running Foo() with the current one

low lynx
#

ah

#

is there any way to get like

#

a copy of a class?

#

something like

class Bar(orig(Foo)):
dry mirage
#

that should be possible? haven't really thought of that use case

low lynx
#

well i was thinking if you were to implement Herald's idea

#

would be nice to make copies of a base type to modify each copy to make new states

#

i have no clue how this stuff works tho so

dry mirage
#

I thought this would work but

#

seems like deepcopying a class does nothing lol

#

!e

from copy import deepcopy

class Foo:
    pass

print(deepcopy(Foo) is Foo)
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
versed eagle
#

!e

from einspect import view, orig
o = orig(int)
class thing(o):
    pass
night quarryBOT
#

@versed eagle :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 3, in <module>
003 |     class thing(o):
004 | TypeError: orig.__new__() takes 2 positional arguments but 4 were given
versed eagle
#

over this weekend im going to try to implement the stack thingy

#

if i get it working i'll make a PR

dry mirage
versed eagle
#

ah

#

i'll work on that too then

dry mirage
#

maybe you can override __init_subclass__

versed eagle
#

i'll look into it 👍

arctic skiff
# sick hound !e``` class cin: def __rshift__(self, _): global x ...
globals().update({'cin':type('cin',(),{'__rshift__':lambda self,inp:(globals().update({[i for i in __import__('inspect').stack()[-2][0].f_globals if id(inp)==id(__import__('inspect').stack()[-2][0].f_globals[i])][0]:input()}),self)[-1]})(),'cout':type('cout',(),{'__lshift__':lambda self,inp:(print(inp,end=''),self)[-1]})(),'cerr':type('cerr',(),{'__lshift__':lambda self,inp:(print(inp,end='',file=__import__('sys').stderr),self)[-1]})(),'endl':'\n'})

a = ''
b = ''
cout << "hello ";
cin >> a >> b;
cerr << a << b << endl; 
vast wave
#

!e ```py
input = lambda *_: "hello chat"

globals().update({'cin':type('cin',(),{'rshift':lambda self,inp:(globals().update({[i for i in import('inspect').stack()[-2][0].f_globals if id(inp)==id(import('inspect').stack()[-2][0].f_globals[i])][0]:input()}),self)[-1]})(),'cout':type('cout',(),{'lshift':lambda self,inp:(print(inp,end=''),self)[-1]})(),'cerr':type('cerr',(),{'lshift':lambda self,inp:(print(inp,end='',file=import('sys').stderr),self)[-1]})(),'endl':'\n'})

a = None
b = None
cin >> b
print(b)

night quarryBOT
#

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

None
vast wave
#

huh

arctic skiff
#

Huh?

arctic skiff
vast wave
#

which will break if you have 2 variables with the same content and pass one of them in

#

then the wrong var will be set in some cases

arctic skiff
#

Will fix that

#

I actually copied borrowed The varname extracting part of code from stackoverflow and then rewrote the code in single line

placid hemlock
#

is this entry level for python coding

sick hound
#

yes

placid hemlock
#

cool help me install pygame cuz i installed it now i cant find it

#

i installed visual studio code

#

i installed python

#

i installed pygame snippets

#

whats next

#

im in kubuntu

#

so this is gona be annoying but ill learn eventually

#

tutorials on you tube dont clarify enough stuff and it mostly how to do it on windows

#

everything i found is based on outdated information so it never works the way it should

terse dagger
#

ok my concise is killing me

#

this is the weirdest channel here

#

just ask your question in general chat

versed eagle
versed eagle
versed eagle
fleet bridge
#
def add(x: int, y: int) -> int:
    return x + y

@inline(funcs=True)
def sum(l: list[int]) -> int:
    res = 0
    for i in l:
        res = add(res, i)
    return res

assert sum([1,2,3]) == 6
dis(sum)

``` ```py
431           0 RESUME                   0

433           2 LOAD_CONST               1 (0)
              4 STORE_FAST               1 (res)

434           6 LOAD_FAST                0 (l)
              8 GET_ITER
        >>   10 FOR_ITER                11 (to 34)
             12 STORE_FAST               2 (i)

435          14 LOAD_FAST                1 (res)
             16 STORE_FAST               3 (_inline_x)
             18 LOAD_FAST                2 (i)
             20 STORE_FAST               4 (_inline_y)
             22 LOAD_FAST                3 (_inline_x)
             24 LOAD_FAST                4 (_inline_y)

429          26 BINARY_OP                0 (+)

435          30 STORE_FAST               1 (res)
             32 JUMP_BACKWARD           12 (to 10)

436     >>   34 LOAD_FAST                1 (res)
             36 RETURN_VALUE
#
def add(x: int, y: int) -> int:
    return x + y

@inline(funcs=True)
def sum(l: list[int]) -> int:
    res = {0: 0}
    for i in l:
        res[0] = add(res[0], (i + i) // 2)
    return res[0]
``` this also works
#

currently it works only for functions with positional arguments, all of them must be provided in call
i am very happy

low lynx
#

what's @inline?

rugged sparrow
#

from context clues I would assume its a function they wrote that looks for function calls in a wrapped function and attempts to inline the bytecode

low lynx
#

ah

#

that's pretty cool

arctic skiff
#
class str(str):
    def __init__(self, _o=''):
        super().__init__()
        self._t = 0
        for i in globals().values():
            if isinstance(i, str) and i._t == self._t:
                self._t += 1

globals().update({'cin':type('cin',(),{'__rshift__':lambda self,inp:(globals().update({[_ for _ in [(i if isinstance(_i,str) and _i._t==inp._t else ...) for i,_i in globals().items()] if _!=...][0]:str(input())}),self)[-1]})(),'cout':type('cout',(),{'__lshift__':lambda self,inp:(print(inp,end=''),self)[-1]})(),'cerr':type('cerr',(),{'__lshift__':lambda self,inp:(print(inp,end='',file=__import__(name='sys',fromlist=['stderr']).stderr),self)[-1]})(),'endl':'\n'})```
#

by overwriting str

#
a = str()
b = str()
cin >> b
print(repr(a), repr(b))```

(py311_venv) E:\co>py esoteric/cpp.py
fef
'' 'fef'

(py311_venv) E:\co>```

#

tho it still have point where it can break but fixed that one

#
[_ for _ in [(i if isinstance(_i,str) and _i._t==inp._t else ...) for i,_i in globals().items()] if _!=...]```now it looks for str._t which is different for every str init
#

made it shorter py globals().update({'cin':type('cin',(),{'__rshift__':lambda self,inp:(globals().update({[i for i,_i in globals().items()if isinstance(_i,str)and _i._t==inp._t][0]:str(input())}),self)[-1]})(),'cout':type('cout',(),{'__lshift__':lambda self,inp:(print(inp,end=''),self)[-1]})(),'cerr':type('cerr',(),{'__lshift__':lambda self,inp:(print(inp,end='',file=__import__(name='sys',fromlist=['stderr']).stderr),self)[-1]})(),'endl':'\n'})

arctic skiff
arctic skiff
fleet bridge
#

why?

arctic skiff
fleet bridge
#

there is no str.__init__ and object.__init__ does nothing

arctic skiff
#

!epy print(dir(str))

night quarryBOT
#

@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
fleet bridge
#

!e print(str.__init__)

night quarryBOT
#

@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.

<slot wrapper '__init__' of 'object' objects>
fleet bridge
#

<slot wrapper 'init' of 'object' objects>

arctic skiff
#

Ok

dry mirage
sick hound
quartz wave
arctic skiff
low lynx
#

it's the thing that returns an instance of your class before init gets called on it

sick hound
#

Hello

#
import math
i,j,r=int,math.dist,range(11)
print('\n'.join(''.join(' 0'[5==i(j(p:=(k,l),(5,5)))or i(j(p,(7,2)))==3]for k in r)for l in r))

What else could I shorten from this?

low lynx
#

complex abs might be shorter idk

sick hound
#

but it won't be circle anymore

low lynx
#

to replace math.dist

#

they should work the same

sick hound
#

I'll try

#

also is there another way to connect strings?

low lynx
#

''.join should be shortest

sick hound
#

It looks so squarey now

i,j,r=int,abs,range(11)
print('\n'.join(''.join(' 0'[(j(k-5)+j(l-5)==5or j(k-7)+j(l-2)==3)]for k in r)for l in r))
low lynx
#

what

#

that's not what I meant

#

!e

import math
k, l = 7, 4
print(math.dist((k,l),(5,5)))
print(abs(k+1j*l-5-5j))

those should be equivalent

night quarryBOT
#

@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 2.23606797749979
002 | 2.23606797749979
sick hound
#

Why does that work

#

Where does j come from

versed eagle
#

its a complex literal

#

python uses j instead of i to signify imaginary numbers

sick hound
#

what does it do

low lynx
#

it lets you work with complex numbers in python

#

abs calculates the modulus of a complex number

#

which is just its magnitude

#

which is the same as distance because of argand diagram

sick hound
#

is % not modulus?

astral rover
#

modulus has a different meaning here

sick hound
#

does the complex number have a value?

astral rover
#

yes

#

well complex numbers are just an extension of the real numbers

#

they have 2 parts the imaginary part and the real part

#

the numbers are you probably deal with are all technically complex numbers with no imaginary part

sick hound
#

is it a constant like pi

languid hare
sick hound
#

Ohh

languid night
#

The basis of imaginary numbers is "i" (j in python) which is equivalent to the square root of -1

#

Complex numbers look like a + bi where a is a real number

astral rover
#

and b is also a real number

languid night
#

^

sick hound
#

is it actually a value of sqrt(-1) or is it just imaginary

versed eagle
#

the value of sqrt(-1) is i

astral rover
#

its also -i :)

versed eagle
#

mhm

sick hound
#

Why python errors

versed eagle
sick hound
#

sqrt of -1 isn't allowed

astral rover
#
In [3]: (-1) ** 0.5
Out[3]: (6.123233995736766e-17+1j)```i dont see any errors here
sick hound
#

I mean math.sqrt(-1)

astral rover
#

cause you need to use cmath for complex numbers

#

normal the normal math module only deals with real numbers

languid night
sick hound
#

I don't know how complex numbers affect real numbers

languid night
#

!e

import cmath
print(cmath.sqrt(-1))

night quarryBOT
#

@languid night :white_check_mark: Your 3.11 eval job has completed with return code 0.

1j
languid night
sick hound
#

Do imaginary numbers only ineract with each other?

versed eagle
low lynx
#

honestly for right now you can just think of complex numbers as two component vectors

#

so a+bj <-> (a, b)

#

and abs() is just the magnitude of (a, b)

#

and you can add them like (a, b) + (c, d) = (a+c, b+d)

sick hound
#

is j*j = 1?

astral rover
#

-1

sick hound
#

Absolute is not just making numbers positive?

astral rover
#

you didnt take the abs of that

#

but the absolute value is always positive yeah

sick hound
low lynx
#

think of them as real component vectors

#

you do not want to get into complex vector spaces before knowing what complex numbers are

astral rover
#

do you know what a vector is?

sick hound
#

I think it's a velocity?

astral rover
#

not strictly, velocity can be represented as a vector

#

vectors are just something that encode dimensions into a neat little package

sick hound
low lynx
#

distance from your vector to the origin

astral rover
#

say you had the vector (3, 4) and you plotted that on a graph youd have to go 3 on the x axis and 4 up on the y axis

arctic skiff
#
globals().update({'str':type('',(str,),{'__init__':lambda self,_o='':(self.__setattr__('_t',_:=0),[_:=_+1 for i in globals().values()if isinstance(i,str)and i._t==self._t],self.__setattr__('_t', _))[0]}),'cin':type('',(),{'__rshift__':lambda self,_:(self,globals().update({[i for i,_i in globals().items()if isinstance(_i,str)and _i._t==_._t][0]:str(input())}))[0]})(),'cout':type('',(),{'__lshift__':lambda self,_:(print(_,end=''),self)[-1]})(),'cerr':type('',(),{'__lshift__':lambda self,_:(self,print(_,end='',file=__import__('sys').stderr))[0]})(),'endl':'\n'})
astral rover
#

the magnitude of the vector (3, 4) can be found by pythagoras's theorem and is 5

sick hound
#

Does complex numbers bend spacetime in the graph or something

sick hound
arctic skiff
#

a = str()
b = str()
cin >> b;
print(repr(a), repr(b))```
#
(py311_venv) E:\co>py esoteric/cpp.py
blah
'' 'blah'

(py311_venv) E:\co>```
low lynx
astral rover
# sick hound So pythagoreas' theorem is like absolute?

to find the absolute value of a complex number (which can be represented on a graph with the real components on the x axis and the imaginary component on the y) you can use pythagoras to find the length of the hypotenuse ie the distance from the origin

versed eagle
# arctic skiff ```py a = str() b = str() cin >> b; print(repr(a), repr(b))```

!e

input = lambda: "test string"
import sys, dis
def get_load(code, lasti):
    for i, (op, oparg) in enumerate(zip(
        code.co_code[:lasti+1][::-2],
        code.co_code[:lasti+2][::-2]
    )):
        op = dis.opname[op]
        match op:
            case "LOAD_NAME":
                return ((op, code.co_names[oparg]),)
            case "LOAD_GLOBAL":
                return ((op, code.co_names[oparg>>1]),)
            case "LOAD_FAST":
                return ((op, code.co_varnames[oparg]),)
            case "LOAD_CLOSURE":
                return ((op, code.co_fastlocalnames[oparg]),)
            case "LOAD_ATTR":
                return code.co_names[oparg], *get_load(code, lasti - i*2 - 2)
@type.__call__
class cin:
    def __rshift__(self, o, b=[]):
        if b:
            v = b.pop(0)
        else:
            v, *e = input().split()
            b.extend(e)
        f = sys._getframe(1)
        *a, m = get_load(f.f_code, f.f_lasti)
        match m[0]:
            case "LOAD_GLOBAL":
                d = f.f_globals
            case "LOAD_FAST":
                d = f.f_locals
            case "LOAD_CLOSURE":
                d = f.f_locals
            case "LOAD_NAME":
                if m[1] in f.f_locals:
                    d = f.f_locals
                elif m[1] in f.f_globals:
                    d = f.f_globals
                else:
                    d = f.f_builtins
        if a:
            _, l, *a = d[m[1]], *a
            while a:
                _ = getattr(_, a.pop())
            setattr(_, l, v)
        else:
            d[m[1]] = v
        return self
n = 1
cin >> n
print(n)
class T:
    def __init__(s):
        s.a = 1
t = T()
cin >> t.a
print(t.a)
night quarryBOT
#

@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | test
002 | string
versed eagle
#

bytecode parsing is fun

arctic skiff
#

what I am doing is overwriting str class to have different ids on every init

versed eagle
# arctic skiff good now example how get_load works

get_load parses the bytecode to find the most recent LOAD_* instruction and then returns the name that was loaded and the type of load that happened
i skipped a few of the LOAD_* instructions that i thought probably wouldn't be relevant though

arctic skiff
#

and I sucked up```
(py311_venv) E:\co>py esoteric/cpp.py
a
b
'b' ''

(py311_venv) E:\co>``````py
a = str()
b = str()

cin >> a >> b;
print(repr(a), repr(b))```

#

fails on 2 var store

versed eagle
#

im fairly sure that mine also fails

#

for 2 or more vars

#

but i haven't actually tested it

sick hound
#

Absolute number = distance from origin

#

Pythagoras is a way to get distance from origin

arctic skiff
#
cin >> b
cin >> a```this works
but not this```py
cin >> a
cin >> b```
sick hound
low lynx
sick hound
low lynx
#

yes

#

to be precise I subtracted 5+5j from it

arctic skiff
sick hound
#

Did you convert it back into real?

low lynx
#

I used abs() to get the magnitude

sick hound
#

using absolute?

low lynx
#

using abs()

sick hound
#

Are the complex numbers there because you converted the coordinates into a vector?

dry mirage
low lynx
#

you'll have to continue this with someone else btw

#

it's like 4am over here

sick hound
#

Okay

arctic skiff
sick hound
arctic skiff
dry mirage
dry mirage
#

yeah, like locals() or globals()

arctic skiff
#

and How I am gonna get variable name from in cin.__rshift__

arctic skiff
#

@dry mirage

dry mirage
#

hm

#

there are some ways I can think of

#

non fully works likely

#

for one there might be no variable at all

#

like if you did cin >> func()

arctic skiff
#

target is updating global values of vars in globals given as parameter to cin.__rshift__

fluid pumice
#

I want to learn some cursed python

dry mirage
#
def func():
  x = None
  cin >> x
  print(x)
arctic skiff
#

because I didn't made it to work on locals

dry mirage
#

I think function variable lookups don't actually go into a dict lookup if it wasn't materialized

#

things like exec() or locals() will materialize the function dict

dry mirage
#

I'm not even sure

#

trying to find out more

#

basically assigning to a variable in the caller when the caller is in a function

#

assigning to f_locals in functions seems to silently fail

versed eagle
#

aw

dry mirage
#

or rather, has no effect

versed eagle
#

huh

#

why is that?

dry mirage
#

!e

def func():
  x = 5
  locals()["x"] = 100
  return x

print(func())
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

5
dry mirage
#

local vars skip dict lookup it seems

versed eagle
#

huh

#

thats annoying

rugged sparrow
dry mirage
rugged sparrow
#

When the trace func ends it copies all the values from the locals dictionary into the actual frame locals array

rugged sparrow
versed eagle
#

weird

versed eagle
#

ty chilaxan

rugged sparrow
#

No prob

#

Later when I am home I'll send my set locals code that works transparently

dry mirage
#

can you settrace after the function already started

rugged sparrow
#

You can settrace on a frame selectively (frame.f_trace), as long as you do it from a trace function

dry mirage
#

yeah that's not working for some reason firT

#

oh it still needs a global trace to be set?

rugged sparrow
#

Yea, you need to use a global trace to set your lower traces

#

I wrote an implementation a while ago, I'll send it later when I'm on my laptop

dry mirage
#

!e

import inspect
from sys import settrace, gettrace

def set_caller(name, value):
    frame = inspect.stack()[2].frame
    def _trace(frame, event, arg=None):
        frame.f_locals[name] = value
        
    if gettrace() is None:
        settrace(lambda *args: None)
        
    frame.f_trace = _trace

def modify():
    set_caller("n", "hello")

def func():
    n = 100
    modify()
    return n
    
print(func())
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

hello
sick hound
#

the what

vast wave
#

!e ```py
import inspect
print(inspect.stack()[0].frame.f_trace)

night quarryBOT
#

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

None
rugged sparrow
#

!e ```py
def make_locals():
import sys
to_update = {}
def locals():
frame = sys._getframe(1)
return to_update.setdefault(frame, {**frame.f_locals})

def tracefunc(frame, what, arg):
    if frame in to_update:
        for key in frame.f_locals.copy():
            if key not in to_update[frame]:
                del frame.f_locals[key]
        for key, val in to_update[frame].items():
            if key not in frame.f_locals or frame.f_locals[key] != val:
                frame.f_locals[key] = val
        del to_update[frame]
    return tracefunc
sys.settrace(tracefunc)
return locals

(builtins if isinstance(builtins, dict) else builtins.dict)['locals'] = make_locals()

def foo():
a = 1
locals()['a'] = 2
print(a)

foo()``` @dry mirage this is the implementation I wrote a while ago

night quarryBOT
#

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

2
rugged sparrow
#

its not perfect tho, I might rewrite it so you can hold onto the mapping returned by locals() to perform further mutations (right now you cannot)

dry mirage
rugged sparrow
#

It makes it so del locals()['a'] works

lunar marsh
#

why not just ctypes.pythonapi.PyFrame_LocalsToFast(frame, 0)

rugged sparrow
#

Doesn't quite work as expected when called from python code if I remember correctly

lunar marsh
#

works for basic examples at least

#

!e ```py
import ctypes
import sys
ctypes.pythonapi.PyFrame_LocalsToFast.argtypes = ctypes.py_object,

def f():
frame = sys._getframe(0)
x = 0
frame.f_locals['x'] = 100
ctypes.pythonapi.PyFrame_LocalsToFast(frame, 0)
print(x)
f()```

night quarryBOT
#

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

100
rugged sparrow
#

It probably changed a bit from 3.8 then which is the last time I tried to use it

#

Previously the f_locals would get refreshed between the update and the api call

#

Actually might have been 3.7 it's been a while

dry mirage
#

hm

#

how do you find the defining frame of a nonlocal variable

dry mirage
#

hm strange, nonlocals still show up in frame.f_locals

rugged sparrow
#

You don't need to know the defining frame of a nonlocal, you can just grab the cell and change it there

dry mirage
#

it's not in frame.f_code.co_varnames though

dry mirage
rugged sparrow
#

Yea that's how nonlocal variables work

#

All frames hold a reference to the same cell

fair quartz
#

chilaxan is python god

dry mirage
#

or is it also valid for setting normal and globals

rugged sparrow
#

You'd need to know it was nonlocal I think?

dry mirage
#

seems hard to differentiate nonlocal and global though

rugged sparrow
#

I'll work on a way

dry mirage
#

oh

#

code.co_cellvars maybe

rough moat
#

__import__(module).function()

earnest wing
#

it's longer for code golf

#
import module;module.func()
import module as m;m.func()
__import__("module").func()
from module import*;func()
#

the first one scales doubly with the module name so it can be better for e.g. re

sick hound
rough moat
#

unless you count semicolons

sick hound
#

I genuinely think I can't shorten this anymore

#
k,i,a=0,int,abs;exec("print(' 0'[i(a((p:=k/11+1j*(k%11))-5-5j))==5or i(a(p-2-7j))==3],end='\\n'*(k%11<1));k+=1;"*121)```
rough moat
#

hm

#

why is there just an 'int' in there

#

and a 'abs'

versed eagle
#

from the 5or

rough moat
#

also why are you doing two backslashes on \n

#

oh

#

i see

#

you could try a list comp but idk if it would be smaller

#

that's what i usually use for this sort of thing

#

idk maybe it's just me being paranoid about exec()

#

what are you trying to do anyway?

#

if it's just a rendering thing you could probably store the data using binary

sick hound
#

I don't know how to store stuff in binary with even less code

#

Wait

#

think I can shorten this more

#

I used exec because it's smaller

#
k,a=0,abs;exec("print(' 0'[a((p:=k/11+1j*(k%11))-5-5j)//1==5or a(p-2-7j)//1==3],end='\\n'*(k%11<1));k+=1;"*121)```
#

Oh wait it's smaller if I don't use abs like that

#
k=0;exec("print(' 0'[abs((p:=k/11+1j*(k%11))-5-5j)//1==5or abs(p-2-7j)//1==3],end='\\n'*(k%11<1));k+=1;"*121)```
sick hound
rough moat
#

ah

rough moat
sick hound
#

Represent the image in binary using text and the print it?

rough moat
#

basically yes

#

well

#

you convert the binary as a number into the corresponding character

sick hound
#

Okay wait I could probably create a better image If I do that

rough moat
#

i'd recommend generating the characters using another script and then putting them in

rough moat
#

im trying it and converting unfortunately seems to mess up some stuff

vast wave
#

everything else is shorter not to alias

sick hound
weak imp
#

What is the longest way to print hello world in one line?

low lynx
#
print.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__.__call__('Hello World')

repeat as much as you wish to

vast wave
#

as long as you can make something more complicated than it already is, there's no limit

#

(you can always make things more complicated)

weak imp
#

pithink and how to do it without using print

vast wave
#

the 11 is the return value of write()

low lynx
#

"most obfuscated" isn't well defined either, but at least it allows for some more interesting ideas to be put forth

vast wave
#

you can expand this even further

#

there is no limit

low lynx
#

fun thing about obfuscating is that you can basically pick any part of the code and obfuscate it further

#

tho that's more just surface level obfuscation

arctic skiff
night quarryBOT
#

@arctic skiff :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     __builtins__.__getattr__('__import__').__call__('sys').__getattr__.__call__('__stdout__').__getattr__.__call__('write').__call__('Hello, world!')
004 |     ^^^^^^^^^^^^^^^^^^^^^^^^
005 | AttributeError: module 'builtins' has no attribute '__getattr__'
arctic skiff
#

wait what?

vast wave
night quarryBOT
#

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

hello chat
arctic skiff
#

ohh its attribute

#

!epy __builtins__.__getattribute__('__import__').__call__('sys').__getattribute__.__call__('__stdout__').__getattribute__.__call__('write').__call__('Hello, world!')

night quarryBOT
#

@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello, world!
vast wave
#

!e exec(type((lambda:0).__code__)(0, 0, 0, 0, 1, 0, b'\x97\x00t\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00d\x01\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00d\x00S\x00', ("hi chat",), ("print",), (), "", "", "", 0, b"", b""))

night quarryBOT
#

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

<K object at 0x7ff20d35fdf0>
quartz wave
vast wave
#

oh right

quartz wave
# vast wave interesting

!e ```py
exec(type((lambda:0).code)(0, 0, 0, 0, 1, 0, b'\x97\x00t\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00d\x01\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00d\x00S\x00', (None, "hi chat"), ("print",), (), "", "", "", 0, b"", b""))

night quarryBOT
#

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

hi chat
vast wave
#

it has None

#

i always forget that

quartz wave
#

although what's a K object? 🤔

vast wave
#

no idea

quartz wave
#

sounds like an arbitrary thing

#

!e ```py
exec(type((lambda:0).code)(0, 0, 0, 0, 1, 0, b'\x97\x00t\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00d\x01\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00d\x00S\x00', ("hi chat",), ("print",), (), "", "", "", 0, b"", b""))

#

!e ```py
a=eval(type((lambda:0).code)(0, 0, 0, 0, 1, 0, b'\x97\x00d\x00S\x00', (), (), (), "", "", "", 0, b"", b""))
dir(a)

#

oof

#

!e ```py
a=eval(type((lambda:0).code)(0, 0, 0, 0, 1, 0, b'\x97\x00d\x01S\x00', ("hi chat",), ("print",), (), "", "", "", 0, b"", b""))
dir(a)

#

!e ```py
exec(type((lambda:0).code)(0, 0, 0, 0, 1, 0, b'\x97\x00t\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00d\x01\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00d\x01S\x00', ("hi chat",), ("print",), (), "", "", "", 0, b"", b""))

#

!e ```py
a=eval(type((lambda:0).code)(0, 0, 0, 0, 1, 0, b'\x97\x00t\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00d\x01\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00d\x01S\x00', ("hi chat",), ("print",), (), "", "", "", 0, b"", b""))

night quarryBOT
#

@quartz wave :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).

[No output]
vast wave
#

can you like not

quartz wave
#

ye i'm going to #bot-commands

sick hound
vast wave
#

yes

#

i know

weak imp
#

!e

__builtins__.__getattribute__('__import__').__call__('sys').__getattribute__.__call__('__stdout__').__getattribute__.__call__('write').__call__(__builtins__.__getattribute__.__call__('int')("0110100001101001", 2).to_bytes((__builtins__.__getattribute__.__call__('int')("0110100001101001", 2).bit_length() + 7) // 8, 'big').decode())
night quarryBOT
#

@weak imp :white_check_mark: Your 3.11 eval job has completed with return code 0.

hi
weak imp
#

Trying to make this looks more esoteric

#

!e

__builtins__.__getattribute__('__import__').__call__('sys').__getattribute__.__call__('__stdout__').__getattribute__.__call__('write').__call__(__builtins__.__getattribute__.__call__('int')("0110100001101001", 2).__getattribute__.__call__("to_bytes")((__builtins__.__getattribute__.__call__('int')("0110100001101001", 2).bit_length() + 7) // 8, 'big').decode())
night quarryBOT
#

@weak imp :white_check_mark: Your 3.11 eval job has completed with return code 0.

hi
weak imp
#

!e

__builtins__.__getattribute__('__import__').__call__('sys').__getattribute__.__call__('__stdout__').__getattribute__.__call__('write').__call__(__builtins__.__getattribute__.__call__('int')("0110100001101001", 2).__getattribute__.__call__("to_bytes")((__builtins__.__getattribute__.__call__('int')("0110100001101001", 2).bit_length() + 7) // 8, 'big').__getattribute__.__call__('decode'))
#

Huh

#

Bot died

rugged sparrow
#

Possibly a legitimate object that was deallocated and partially overwritten