#esoteric-python

1 messages · Page 29 of 1

night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello world!
unique heath
#

p.s: cheetsheet

>>> 81 // 34
2
>>> __builtins__.__dir__().__len__().__floordiv__(__import__.__dir__().__len__())
5
>>> __builtins__.__dir__().__len__().__floordiv__(__doc__.__dir__().__len__())
6
>>> __builtins__.__dir__().__len__().__floordiv__(__nam__.__dir__().__len__())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__nam__' is not defined. Did you mean: '__name__'?
>>> __builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())
1
>>> __builtins__.__dir__().__len__().__floordiv__(__spec__.__dir__().__len__())
6
>>> __builtins__.__dir__().__len__().__floordiv__(__debug__.__dir__().__len__())
2
>>> __doc__.__dir__().__len__()
25
>>> __builtins__.__dir__().__len__()
158
>>> __builtins__.__dir__().__len__().__floordiv__(15)
10
>>> __import__.__dir__().__len__()
30
#

mix and match stuff to make esoteric hell

sick hound
#

!e

T=int(input());r=i=1
while i<T:i+=1;r*=i
print(r)

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 1, in <module>
003 |     T=int(input());r=i=1
004 |           ^^^^^^^
005 | EOFError: EOF when reading a line
restive void
#

Oh, is that a new notice?

#

!e

import sys, io
sys.stdin = io.StringIO("foo")
print(input())
night quarryBOT
#

@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.

foo
vast wave
#

!e probably because of ```py
raise EOFError("EOF when reading a line")

night quarryBOT
#

@vast wave :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 1, in <module>
003 |     raise EOFError("EOF when reading a line")
004 | EOFError: EOF when reading a line
vast wave
#

yeah

last locust
fleet bridge
#

!e ```py
print('EOFError: EOF when reading a line')
import sys; sys.exit(1)

night quarryBOT
#

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

:warning: Note: input is not supported by the bot :warning:

EOFError: EOF when reading a line
last locust
versed eagle
#

!e

from posix import *
print(read(0, 11))
night quarryBOT
#

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

b''
versed eagle
#

huh

#

they should do something to prevent this then, no?

last locust
#

It's not a security thing or anything

versed eagle
#

right but the warnings are inconsistent

#

thats what i was trying to demonstrate

#

also, there is sys.stdin

#

!e

import sys
print(hasattr(sys, "stdin"))
night quarryBOT
#

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

True
versed eagle
#

it just returns EOF when read from

versed eagle
last locust
#

!e py import sys print(sys.stdin)

night quarryBOT
#

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

<_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>
last locust
#

Fair enough

versed eagle
#

so imo they should make it more consistent by making it so that all reads to that file descriptor result in that warning (unless the fd is replaced with something like dup2)

last locust
#

I mean the idea is just to let people who aren't familiar with the error know what's going on

#

If you use some other obscure method then you know what you're doing

versed eagle
#

thats true, and completely valid! but it still bothers me that the warnings are inconsistent

last locust
#

You can always raise it in #dev-contrib, but you'll probably just get the same response

versed eagle
#

mhm

#

the only way it would ever get implemented is probably if i implemented it myself

#

which is sad because i want to do that now but i dont have the time

#

one day, perhaps

sudden osprey
#

The warning is implemented without requiring adding any code at runtime

#

It's simple by design

#

Also still not sure what you mean by the warnings being inconsistent.

versed eagle
#

the warning is meant to tell people they can't read input from the user, right?

#

but it shows the warning in some cases where that wasnt attempted, and doesnt always show it in cases where it was attempted

#

inconsistent

#

hopefully that explanation makes sense? sorry if it doesnt, i dont have enough sleep so i have trouble forming coherent thoughts

sudden osprey
#

Yeah it makes sense

#

Although if the aim was to be precise as possible, EOFError already does that

versed eagle
#

its not that i want it to be more descriptive, i just want it to be shown in some situations and not shown in others

#

to be better aligned with what the goal of the warning is

fleet bridge
#

this warning is designed for users that dont realise that you cannot use input() in snekbox
if you are doing this: ```py
from posix import *
print(read(0, 11))

versed eagle
#

yep, that's right

night quarryBOT
#

@timber grotto :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello, world!
low lynx
#

what does it do?

serene stratus
#

Print Hello world I assume 😄

low lynx
#

also that definitely counts as esoteric

burnt pasture
#

i am also confused about "not esoteric" 😄

quartz wave
#

start deobfuscating here ```py
def (__, , ):
try:
(
)
except :
...
(lambda: ((
:= (lambda , __=builtins, =builtins.getattr: (, ))), ( := (lambda : (lambda : ('setitem', (('decode', ('fromhex', ('bytes'))('676c6f62616c73'))('ascii'))())(('decode', ('bytes')())('utf-16'), ('sum')()), ('UnicodeDecodeError'), ))), ( := (lambda : ('join', ('str')())(('map')(('chr'), )))), ( := ((((111, 114, 100)))((((115, 116, 114)))((
((115, 117, 112, 101, 114))))[9]) + (
((111, 114, 100)))(
(((115, 116, 114)))((((102, 111, 114, 109, 97, 116))))[7]) + (((111, 114, 100)))((((115, 116, 114)))((((111, 114, 100))))[9]) + (((84, 114, 117, 101))))), (((䨭, 㔽, Ũ, ὕ, 夌)), (((匠, 猁, 堌, Ů, 䌲, 椋)), (((ⰳ, 刍, ⴼ, 怍, 䠨, 弐, ⵅ, 欉, ᙉ, ࡗ)))(((严, 㝂, 㰷)))))(((㠐, 堍, 椃, ⴿ, 搋, ᘖ, ഓ, 昑, Ů, 氆, 朅, 怄, ᰅ, Ȉ))) if {((, __)) for _ in (((114, 97, 110, 103, 101)))(_____) for __ in (_((114, 97, 110, 103, 101)))(_____)} else ''))()

finite blaze
#
def main(arg1, arg2, someFunc):
    try:arg1(someFunc)
    except arg2:...
(
    lambda: (
        (strToFunc := (lambda arg2, arg1=__builtins__, someFunc=__builtins__.getattr: someFunc(arg1, arg2))),
        (
            someFunc := (
                lambda arg2: main(
                    lambda arg2: strToFunc(
                        "__setitem__",
                        strToFunc(strToFunc("decode",b'globals',)("ascii"))(),
                    )(bytes(arg2).decode("utf-16"), sum(arg2)),UnicodeDecodeError,arg2,
                )
            )
        ),
        (more := (lambda arg2: str.join(map(chr, arg2)))),
        (someInt := 255),
        strToFunc("write",strToFunc("stdout",__import__("sys"),),
        )("Hello, world!\n")
        if {
            someFunc((arg2, arg1))
            for arg2 in range(someInt)
            for arg1 in range(someInt)
        }
        else "",
    )
)()
#

some more cleaning

#
def main(arg1, arg2, someFunc):
    try:arg1(someFunc)
    except arg2:...
(lambda: (
        (someFunc := (lambda arg2: main(lambda arg2: globals().__setitem__(bytes(arg2).decode("utf-16"), sum(arg2)),UnicodeDecodeError,arg2,))),
        __import__("sys").stdout.write("Hello, world!\n")
        if {
            someFunc((arg2, arg1))
            for arg2 in range(255)
            for arg1 in range(255)
        }else ""))()
#

First time deobfuscating code, pretty fun

rough moat
#

i posted this in general, but for adding and subtracting 1 to an int, you can do val = -~val and val = ~-val

brittle cape
#

yeag sounds right

heady cosmos
#

I want to encode two esp32s that communicate over an nrf24, but it doesn't work no matter how hard I try. Can anyone send me a short sample micropython code?

sick hound
#

is this pyarmor

versed eagle
grave rover
gleaming linden
grave rover
#

I see

last locust
#

Does anyone here happen to know how to raise an error in cpython? I found PyErr_SetString(PyExc_ValueError, "the text of the value error"); but that doesn't seem to actually raise it.

fleet bridge
#

Does PyErr_SetRaisedException work?

#

Or any other PyErr_Set* function

fleet bridge
#

I think you also can do something like PyExecString("raise Exception") (i dont how this function is named exactly)

last locust
sick hound
#

bro how do y'all obfuscate at this level bro
It got me to question my existence. DO I EVEN KNOW PYTHON?

serene stratus
#

Did you manually do it or was it automated with a tool?

dusk basin
#

Ola

vast wave
#

there is always one more trick, one more standard library package, etc

unreal echo
#

Me saving hours just print("hello world")

sick hound
sick hound
#

is your name
uint64_t ?

#

also I think I saw someone

#

make that test

#

the more the code was obfuscated the faster it was

fleet bridge
#

Thats not true in almost all cases

#

Obfuscation usually needs redundant code, so obfuscated code os not faster

low lynx
#

if obfuscated code is faster it's probably not obfuscated for the sake of obfuscation

versed eagle
#

that could be true in some cases but in the vast majority of cases obfuscation will only make things slower

#

and even if it's faster at first, further obfuscation will make it slower eventually

fleet bridge
#

There are some microoptimization techniques that looks weird

versed eagle
#

i wouldn't call that obfuscation though

bitter jacinth
#

https://youtu.be/t863QfAOmlY this was fascinating, and hilariously esoteric

Python is a great language, with a few... cursed exploits. While a lot of implementation details make it easier to work with, they also lead to quirks - quirks which can be exploited for fun (and profit?). Whether it's variables, match statements, type hinting, imports, or even just trying to fit everything on one line, this talk has more than a...

▶ Play video
dreamy pier
versed eagle
#

lmao

errant slate
fleet bridge
#

(by making it slower)

errant slate
#

thank you for the help

keen thicket
#
import os
timestep=1./60
gravity=-9.81
tg=timestep*gravity
s_x,s_y=10,20
u=v=[[.0 for A in range(s_y)]for A in range(s_x)]
pr=[[.0 for A in range(s_y)]for A in range(s_x)]
st=[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[0,1,1,1,1,0,.1,0,0,.1,.1,.1,.1,.1,.1,.1,0,0,0,0],[0,1,1,1,1,1,.1,.1,.1,.1,.1,.1,.1,.1,.1,0,0,0,0,0],[0,1,1,1,1,1,.1,.1,.1,.1,.1,.1,.1,.1,.1,0,0,0,0,0],[0,.1,0,1,1,1,.1,.1,.1,.1,.1,.1,.1,.1,.1,0,0,0,0,0],[0,.1,0,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,.1,0,0,0,0,0,0],[0,.1,0,.2,.1,.1,.1,0,.1,.1,.1,.1,0,0,0,0,0,0,0,0],[0,.1,0,0,.2,.1,.1,0,.1,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]
C=1e3/timestep
loop=[(A,B)for A in range(1,len(u)-1)for B in range(1,len(u[0])-1)]
cl=lambda x,size:0 if x<=0 else size-1 if x>=size else x
sf=lambda i,j,field:((A:=cl(int(i-.5),s_x-1)),(C:=i-.5-A),(E:=cl(A+1,s_x-1)),(B:=cl(int(j-.5),s_y-1)),(D:=j-.5-B),(F:=cl(B+1,s_y-1)),(G:=1.-C),(H:=1.-D),G*H*field[A][B]+C*H*field[E][B]+C*D*field[E][F]+G*D*field[A][F])[-1]
ses='.',':','!','*','o','e','&','#','%','@'
for _ in range(2**10):
    u=[[A+tg for A in A]for A in u];v=[[A+tg for A in A]for A in v]
    for(i,j)in loop:
        l,r,t,b=u[i][j],u[i+1][j],v[i][j],v[i][j+1];ls,rs,ts,bs=st[i-1][j],st[i+1][j],st[i][j-1],st[i][j+1]
        if st[i][j]==0:continue
        s=ls+rs+ts+bs;d=l-r+t-b;p=-d/s*1.9;pr[i][j]+=p*C;u[i][j],v[i+1][j],u[i][j],v[i][j+1]=l+d*ls,r+d*rs,t+d*ts,b+d*bs
    for i in range(len(u)):u[i][0],u[i][s_y-1],v[0][j],v[s_x-1][j]=u[i][1],u[i][s_y-2],v[1][j],v[s_x-2][j]
    new_u=new_v=[[.0 for A in range(s_y)]for A in range(s_x)]
    for(i,j)in loop:
        if st[i][j]!=0 and st[i-1][j]!=0:x,y=i,j+.5;nu,nv=u[i][j],sum((v[i][j],v[i+1][j],v[i][j],v[i][j+1]))/4;x-=timestep*nu;y-=timestep*nv;new_u[i][j]=sf(x//1,y//1,u)
        if st[i][j]!=0 and st[i][j-1]!=0:x,y=i+.5,j;nu,nv=sum((u[i][j],u[i+1][j],u[i][j],u[i][j+1]))/4,v[i][j];x-=timestep*nu;y-=timestep*nv;new_v[i][j]=sf(x//1,y//1,v)
    u,v=new_u,new_v;os.system('clear')
    for line in pr:print(''.join([ses[min(int(abs(A)/C)//10,9)]for A in line]),flush=True)

https://asciinema.org/a/592380

#

fluid simulation in less than 2kB

dusk basin
#

hi

fleet bridge
#

!e ```py
import itertools
for _ in map(print, itertools.count()):
...

night quarryBOT
#

@fleet bridge :x: Your 3.11 eval job has completed with return code 143 (SIGTERM).

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
011 | 10
... (truncated - too many lines)

Full output: too long to upload

fleet bridge
#

i just wanted to share it with you

strange basin
#

!e

@lambda _:_()
class print_:
    __getattr__ = lambda __,_:print(_.replace('_',' ').title()+'!')

print_.    hello_world
print_.    i_am_cursed
print_.    ᵃᵃᵃʳᵍʰ
night quarryBOT
#

@strange basin :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | Hello World!
002 | I Am Cursed!
003 | Aaargh!
strange basin
#

!e

def echo():
    print('Echo ...')
    return echo

echo()() ()  ()   ()    ()     ()      ()       ()
night quarryBOT
#

@strange basin :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | Echo ...
002 | Echo ...
003 | Echo ...
004 | Echo ...
005 | Echo ...
006 | Echo ...
007 | Echo ...
008 | Echo ...
009 | Echo ...
strange basin
#

!e

@lambda _:_()
def commented_out():
    print(f'Hello, cursed World!')

# commented_out()
night quarryBOT
#

@strange basin :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello, cursed World!
strange basin
#

!e

@lambda _:_()
def not_commented_out():
    print(f'Hello, cursed World!')

not_commented_out()
night quarryBOT
#

@strange basin :x: Your 3.11 eval job has completed with return code 1.

001 | Hello, cursed World!
002 | Traceback (most recent call last):
003 |   File "/home/main.py", line 5, in <module>
004 |     not_commented_out()
005 | TypeError: 'NoneType' object is not callable
dreamy pier
#

!e

@lambda _:_()
def it_is_not_true():
    print(f'Hello, cursed World!')
night quarryBOT
#

@dreamy pier :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello, cursed World!
unique heath
#

ok but unicode characters and binary strings is just cheating

#

!e

(___:=eval(__builtins__.__dir__().__getitem__((420).__floordiv__(__import__.__dir__().__len__().__sub__(20)))),_____:=lambda __: eval(__builtins__.__dir__().__getitem__(14))(__),eval(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__getitem__(__import__.__dir__().__len__().__sub__(__name__.__doc__.__len__().__floordiv__(__builtins__.__doc__.__len__()))).__len__()).__sub__(__name__.__dir__().__len__().__sub__(__import__.__dir__().__len__()).__sub__(__package__.__dir__().__len__()).__sub__(__package__.__dir__().__len__())).__add__(4)))(chr(__import__.__dir__().__len__().__add__(__builtins__.__dir__().__len__())), (eval(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__getitem__(__import__.__dir__().__len__().__sub__(__name__.__doc__.__len__().__floordiv__(__builtins__.__doc__.__len__()))).__len__()).__sub__(10))), ), {chr(__name__.__dir__().__len__()):(lambda _: ___(_____(72).__add__(_____(101)).__add__(_____(108)).__add__(_____(108)).__add__(_____(111)).__add__(_____(32)).__add__(_____(119)).__add__(_____(111)).__add__(_____(114)).__add__(_____(108)).__add__(_____(100)).__add__(_____(33))))})().Q())```
night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello world!
unique heath
#

!e

(___:=eval(__builtins__.__dir__().__getitem__((420).__floordiv__(__import__.__dir__().__len__().__sub__(20)))),_____:=lambda __: eval(__builtins__.__dir__().__getitem__(14))(__),eval(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__getitem__(__import__.__dir__().__len__().__sub__(__name__.__doc__.__len__().__floordiv__(__builtins__.__doc__.__len__()))).__len__()).__sub__(__name__.__dir__().__len__().__sub__(__import__.__dir__().__len__()).__sub__(__package__.__dir__().__len__()).__sub__(__package__.__dir__().__len__())).__add__(4)))(chr(__import__.__dir__().__len__().__add__(__builtins__.__dir__().__len__())), (eval(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__getitem__(__import__.__dir__().__len__().__sub__(__name__.__doc__.__len__().__floordiv__(__builtins__.__doc__.__len__()))).__len__()).__sub__(10))), ), {chr(__name__.__dir__().__len__()):(lambda _: ___(_____(72).__add__(_____(101)).__add__(_____(108)).__add__(_____(108)).__add__(_____(111)).__add__(_____(32)).__add__(_____(119)).__add__(_____(111)).__add__(_____(114)).__add__(_____(108)).__add__(_____(100)).__add__(_____(33))))})().Q())```
night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello world!
torn tulip
#

TypeError: BaseExceptionGroup.__new__() takes exactly 2 arguments (3 given)

dreamy pier
#

By me

TypeError: 'bool' object is not callable
dreamy pier
#

!e

(___ := print, _____ := lambda __: chr(__), eval('BaseExceptionGroup')(chr(__import__.__dir__().__len__().__add__(__builtins__.__dir__().__len__())), (object,), {chr(__name__.__dir__().__len__()): (lambda _: ___(_____(72).__add__(_____(101)).__add__(_____(108)).__add__(_____(108)).__add__(_____(111)).__add__(_____(32)).__add__(_____(119)).__add__(_____(111)).__add__(_____(114)).__add__(_____(108)).__add__(_____(100)).__add__(_____(33))))})().Q())

night quarryBOT
#

@dreamy pier :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 |     (___ := print, _____ := lambda __: chr(__), eval('BaseExceptionGroup')(chr(__import__.__dir__().__len__().__add__(__builtins__.__dir__().__len__())), (object,), {chr(__name__.__dir__().__len__()): (lambda _: ___(_____(72).__add__(_____(101)).__add__(_____(108)).__add__(_____(108)).__add__(_____(111)).__add__(_____(32)).__add__(_____(119)).__add__(_____(111)).__add__(_____(114)).__add__(_____(108)).__add__(_____(100)).__add__(_____(33))))})().Q())
004 |                                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
... (truncated - too long)

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

dreamy pier
#

!e

eval('BaseExceptionGroup')("¼", (object,), {"Q": (lambda _: print("Hello world!"))})().Q()
night quarryBOT
#

@dreamy pier :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 |     eval('BaseExceptionGroup')("¼", (object,), {"Q": (lambda _: print("Hello world!"))})().Q()
004 |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 | TypeError: BaseExceptionGroup.__new__() takes exactly 2 arguments (3 given)
dreamy pier
#

idk there should be type

#

but there is the baseexception

#

!e

type("¼", (object,), {"Q": (lambda _: print("Hello world!"))})().Q()
night quarryBOT
#

@dreamy pier :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello world!
fleet bridge
#

Do you know any algorithm with O(N^0.5) time complexity?

earnest wing
#

In quantum computing, Grover's algorithm, also known as the quantum search algorithm, refers to a quantum algorithm for unstructured search that finds with high probability the unique input to a black box function that produces a particular output value, using just

    O
    (
    
      
        N

...

#

as well as things derived from it

fleet bridge
#

I expected classic algorithm, not quantum algorithm...

earnest wing
#

well, something simple then

#
def is_prime(n):
  for i in range(1, round(n**0.5)):
    if n % i == 0:
      return False
  return True
fleet bridge
#

Amother example: N is the number of cells in the square. Iterating over square side if O(N^0.5)

#

If you think about it, it is the same as your is_prime example

vast wave
night quarryBOT
#

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

001 | Hello chat
002 | Hello chat
fleet bridge
#

!e ```py
@lambda :()
def what(
):
print("Hello chat")
return _

what(what)(what)

night quarryBOT
#

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

001 | Hello chat
002 | Hello chat
003 | Hello chat
keen thicket
#

!e

from collections import namedtuple
from itertools import takewhile
w_s,lhead_buf_sz=13,6
s_buf_sz,Token=w_s-lhead_buf_sz,namedtuple('Token',['offset','length','indicator'])
compress=lambda t,s_buf='':[((tok:=(lambda t,s_buf,l=0:Token(*[(0,0,t[0]),*([(len(s_buf)-i,(l:=fl),t[fl])for(i,ch)in enumerate(s_buf)if ch==t[0]and(fl:=(match_length:=lambda t,w,t_idx,w_idx:0 if t_idx+w_idx>=len(t)or not t or t[t_idx]!=w[w_idx]else 1+match_length(t,w+t[t_idx],t_idx+1,w_idx+1))(t,s_buf,0,i))>=l]if s_buf and len(t)>1 else[])][-1]))(t,s_buf)),(s_buf:=(s_buf+t[:tok.length+1])[-s_buf_sz:]),(t:=t[tok.length+1:]))[0]for _ in takewhile(lambda _:t,iter(int,1))]
decompress=lambda toks,o='':[([(o:=o+o[-tok.offset])for _ in range(tok.length)],(o:=o+tok.indicator))for tok in toks][-1][-1]
print(decompress(compress('"I will make no bargains with terrorist hardware."\n-- Peter da Silva')))
night quarryBOT
#

@keen thicket :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | "I will make no bargains with terrorist hardware."
002 | -- Peter da Silva
keen thicket
#

lz77 in like 800 bytes

#

also does anybody know if there's a more elegant way to put a while loop in a list comprehension besides takewhile(lambda _: a and b or whatever,iter(int,1))

versed eagle
#

[*iter((lambda:your_boolean_expression_here),0)]

keen thicket
versed eagle
#

you said you wanted it in a list

keen thicket
#

no haha, a list comprehension

#

as like the iterator for it

#

[something for _ in iter((lambda:your_boolean_expression_here),0)]

versed eagle
#

[_ for _ in iter((lambda:your_boolean_expression_here),0)]

keen thicket
#

but yeah I worded that confusingly

versed eagle
#

oh no i re-read it just now

#

i was misunderstanding

#

sorry

versed eagle
fringe oracle
#

!e

something = [5064, 5111, 5148, 5175, 5193, 5239, 5273, 5324, 5349, 5355, 5360, 5364, 5401, 5405, 5410, 5459, 5519, 5569, 5577, 5677, 5684, 5696, 5720];WHAT = ''; exec("""for i in something: __import__("random").seed(i); WHAT += __import__("random").choice((__import__("string").ascii_lowercase + " ")); print(WHAT)""");
night quarryBOT
#

@fringe oracle :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | n
002 | ne
003 | nev
004 | neve
005 | never
006 | never 
007 | never g
008 | never go
009 | never gon
010 | never gonn
011 | never gonna
... (truncated - too many lines)

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

vast wave
#

do we have numpy

#

!e print(import("numpy"))

night quarryBOT
#

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

<module 'numpy' from '/snekbox/user_base/lib/python3.11/site-packages/numpy/__init__.py'>
vast wave
#

nice

#

!e ```py
import numpy as n
print(n.random.default_rng(0).integers(low=0, high=10, size=10))

night quarryBOT
#

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

[8 6 5 2 3 0 0 0 1 8]
vast wave
#

!e ```py
import numpy as n
print(n.random.default_rng(0).random())

night quarryBOT
#

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

0.6369616873214543
vast wave
#

i will eat a shoe

night quarryBOT
#

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

lgbt eshek
vast wave
#

!e ```py
import numpy as n
n.random.seed(0);
print(n.random.rand())

night quarryBOT
#

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

0.5488135039273248
vast wave
#

!e ```py
import numpy as n
n.random.seed(0);
print(n.random.choice("abc", 5))

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "mtrand.pyx", line 940, in numpy.random.mtrand.RandomState.choice
003 | TypeError: 'str' object cannot be interpreted as an integer
004 | 
005 | During handling of the above exception, another exception occurred:
006 | 
007 | Traceback (most recent call last):
008 |   File "/home/main.py", line 3, in <module>
009 |     print(n.random.choice("abc", 5))
010 |           ^^^^^^^^^^^^^^^^^^^^^^^^^
011 |   File "mtrand.pyx", line 942, in numpy.random.mtrand.RandomState.choice
... (truncated - too many lines)

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

vast wave
#

guh

#

!e ```py
import numpy as n
n.random.seed(0);
print(n.random.choice(list("abc"), 5))

night quarryBOT
#

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

['a' 'b' 'a' 'b' 'b']
vast wave
night quarryBOT
#

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

hello world
gleaming linden
#

wrong channel, and selfbots are against tos

#

!rule 5

night quarryBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

gleaming linden
#

we can't help with it here

grand urchin
grand urchin
fleet bridge
#
>>> class X(type(None)): ...
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type 'NoneType' is not an acceptable base type
>>> class X(type(True)): ...
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type 'bool' is not an acceptable base type
>>> class X(type(...)): ...
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type 'ellipsis' is not an acceptable base type
>>> class X(type(print)): ...
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type 'builtin_function_or_method' is not an acceptable base type
>>> class X(type(lambda:...)): ...
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type 'function' is not an acceptable base type
>>> class X(type(object.__dict__['__class__'])): ...
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type 'getset_descriptor' is not an acceptable base type
#

i guess there are more C-classes that you cannot subclass, than classes that you can subclass

#

almost all "normal" classes (list, tuple, dict, object, type, int) are subclassable (except bool and NoneType)
everything else is kinda implementation detail (their API is described, but not classes itself), so they are not subclassable

#

their API is described, but not classes itself
i mean print and lambda:... are "things you can call", exact classes of these things are impl detail (strictly speaking it is not...)
object.__dict__['__class__'] (=<attribute '__class__' of 'object' objects>) is a thing with __get__ and __set__, exact class is not documented (and it is an impl detail)

#
>>> class X(slice(slice)): ...
...
>>> X
slice('X', (slice(None, <class 'slice'>, None),), {'__module__': '__main__', '__qualname__': 'X'})
``` this will always be funny
#
>> class X(map(print,"abc")): ...
...
>>> X
<map object at 0x0000025950463280>
>>> [*X]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
#
>>> class X(map): ...
...
>>> X
<class '__main__.X'>
>>> X.__bases__
(<class 'map'>,)
>>> X(print, "abc")
<__main__.X object at 0x000002595092C460>
>>> [*X(print, "abc")]
a
b
c
[None, None, None]
``` wow!
#

you can subclass filter too
upd: and enumerate/zip/reversed

#

and classmethod/staticmethod/property

#

and super...

#

!e ```py
import builtins
for k, v in builtins.dict.items():
try:
class X(v):
pass
except:
pass
else:
if issubclass(v, BaseException):
continue
print(v.qualname, end=', ')

night quarryBOT
#

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

BuiltinImporter, bytearray, bytes, classmethod, complex, dict, enumerate, filter, float, frozenset, property, int, list, map, object, reversed, set, staticmethod, str, super, tuple, type, zip, 
fleet bridge
#
# normal:
object
type

# kinda normal:
int
float
complex
dict
list
set
frozenset
tuple
str
bytes
bytearray

# cursed stuff:
classmethod
staticmethod
property

# ajsldjaslkdjaskd
super
enumerate
filter
map
reversed
zip
arctic skiff
fleet bridge
arctic skiff
restive void
coarse void
#

Quick question I was wondering about, but couldn't get it to work. Is there such a thing as "recursive decorators", where somehow a function or class decorates itself until some conditions happen or whatever...(?) It would be a hella esoteric piece of code

dreamy pier
night quarryBOT
#

@dreamy pier :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
kindred stone
#

!e

foo = lambda a: (print(a), foo(a+1)(lambda f: f) if a < 5 else lambda f: f)[1]

@foo(0)
def test(): ...
night quarryBOT
#

@kindred stone :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
calm loom
#

🛌

golden finch
#

What's the best way (in 3.11 bytecode) to increment the 3rd value on the stack?

potent comet
golden finch
golden finch
potent comet
#

I'm not sure if it's actually documented anywhere, which is a little problematic since it changes often.

#

opcode._cache_format defines the sizes, but that's not public...

vast wave
#

you can access it regardless

potent comet
#

You can, but that might go away/change at any time, breaking your code and annoying the core devs...

fleet bridge
quartz wave
#

opcode._inline_cache_entries

#

or dis._inline_cache_entries if you prefer that

golden finch
#

Thanks!

quartz wave
golden finch
#

cool

#

can't thank you enough

quartz wave
#

it can't easily make a jump

vast wave
quartz wave
# vast wave oh right i forgot to test jumps
import dis
from assembler import Assembler, Label

def func():
    a = Assembler()
    a.consts.extend([0] * 257 + [True]) # simulate EXTENDED_ARG
    a.insn("RESUME", 0)
    
    a.insn("LOAD_CONST", 257)
    a.insn("POP_JUMP_FORWARD_IF_FALSE", 2)
    
    a.insn("LOAD_CONST", 256)
    a.insn("COPY", 1)
    a.insn("POP_JUMP_BACKWARD_IF_TRUE", 5) # have to manually count jumps here
    
    a.insn("RETURN_VALUE", 0)
    
    return a.build()

dis.dis(func())
#

that's how i tested it

fleet bridge
languid hare
#

wait wtf

#

bits << x ???

low lynx
#

it's honestly a good idea

#

using an int for a dp table instead of a list

#

i'll borrow that

simple panther
#

how to make seive of erastothenes function using lambda?

#

i wish that i were exellent in lambda

fleet bridge
#

if you send here your "normal" code, i will try to turn it into lambda

low lynx
#

!e here's a quick one

test=lambda n:[[0,0,1,1][:n+1],(s:=[0,0]+[1]*~-n)and[s.__setitem__(k:=slice(p*p,n+1,p),[0]*len(s[k]))for p in range(2,int(n**.5)+1)if s[p]]and s][n>3]
print(test(100))
night quarryBOT
#

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

[0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
night quarryBOT
#

@half escarp :white_check_mark: Your 3.11 eval job has completed with return code 0.

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
night quarryBOT
#

@half escarp :white_check_mark: Your 3.11 eval job has completed with return code 0.

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
fleet bridge
#

That's cool

dry cave
#

20

sonic birch
#

Hi guys. I dynamicaly create a copy of function like new_f = FunctionType(f.__code__, f.__globals__, name=f.__name__ , argdef = inspect.getfullargspec(f).defaults, closure=f.__closure__). Is there any way for debugger to tell that the function is exactly the same so when I put a brackpoint into original f it will work?

restive void
sonic birch
cobalt mica
#

scary

languid hare
#

mapping over discard is really neat

night quarryBOT
#

@digital mesa :warning: Your 3.11 eval job has completed with return code 0.

[No output]
sick hound
#

!e

print([i for i in range(2, 100) if all(i % j != 0 for j in range(2, int(i ** 0.5) + 1))])
night quarryBOT
#

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

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
wheat river
#

!e

sieve=lambda n:[*[p:={*range(2,n)},[p:=p-{*range(i*i,n,i)}for i in[*p]],p][2]]
print(sieve(100))
night quarryBOT
#

@wheat river :white_check_mark: Your 3.11 eval job has completed with return code 0.

[2, 3, 67, 5, 7, 71, 73, 11, 13, 79, 17, 19, 83, 23, 89, 29, 31, 97, 37, 41, 43, 47, 53, 59, 61]
quartz wave
night quarryBOT
#

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

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
quartz wave
#

or ```py
sieve=lambda n:[*[p:={*range(2,n)},[p:=p-{range(ii,n,i)}for i in p],p][2]]

wheat river
#

oh yea, u can just iterate over p

quartz wave
#

now i wanted to see how it compares in ruby ```ruby
sieve=->(n){[t=2..n]-t.flat_map{[(_1*_1..n)%_1]}}

karmic pumice
#

!e

import sys;[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];
import random;[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];
[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[1];[1];
class App(object):#[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[
    @staticmethod #[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[1,]
    def main(args: list[str]) -> None:#[];[];[];[];[];[];[];[];[];[];[];[];[];[];[1,];
        if len(args)<=1:raise TypeError("Skill Issue");[];[];[];[];[];[];[];[];[];[1];
        buffer_hello:list[str]=[char for char in "hello"];[];[];[];[];[];[];[];[1];[];
        buffer_world:list[str]=[char for char in args[1]];[];[];[];[];[];[];[];[1];[];
        random.shuffle(buffer_hello);[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[1];
        random.shuffle(buffer_world);[];[];[];[];[];[];[];[];[];[];[];[];[];[];[];[1];
        while ''.join(buffer_hello)!="hello":random.shuffle(buffer_hello);[];[];[];[];
        while ''.join(buffer_world)!=args[1]:random.shuffle(buffer_world);[];[];[];[];
        sys.stdout.write(f"{''.join(buffer_hello)}, {''.join(buffer_world)}!");[];[1];
if __name__ == '__main__': App().main(['', 'shrek']);[];[];[];[];[];[];[];[];[];[];[];
night quarryBOT
#

@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.

hello, shrek!
jolly juniper
#

i need an interpreter for vs code python

#

any help? pls

versed eagle
#
  1. wrong channel
  2. just sudo apt install python3 [or whatever the equivalent is if you're using windows]
cursive portal
#

Ok not sure what's the best channel but the question seems esoteric enough: "\U0001f40d", which is a nice snake unicode character 🐍, doesn't display in Windows terminal/Powershell. I only see the charcode. Yet it can show other characters such as ⚛️. Is that because the snake one is not supported ? Where can I get started to get a precise answer on such matters (I am a tad confused between unicode, utf8, "emojis", and their behaviour accross platforms...)

vast wave
vast wave
#

works on gnome term

cursive portal
#

indeed I don't have the issue on Linux

#

I do print 🐍 directly, that's how I see it in the code editor

#

sad day for Python 😢

cursive portal
#

but it runs powershell so I guess it's expected to have the same limitations

versed eagle
#

it's an issue with windows stuff

cursive portal
#

well, it's about displaying a Python 🐍

#

more seriously I wondered if something could be off in the way I created/formatted the string but it doesn't seem so

sonic birch
#

Hi does anybody knows why ```
def foo():
locals()['f']=5
yield
print(locals())
yield

g = foo()
for s in g:
g.gi_frame.f_locals['f']=8
...


prints {'f': 8}

But ```
def foo():
  f=5
  yield
  print(locals())
  yield

g = foo()
for s in g:
  g.gi_frame.f_locals['f']=8
  ...

prints {'f': 5}

fleet bridge
#

Because locals()['f']=5 has no effect

#

Hmm

#

Im confused, i have no idea

sonic birch
faint vector
#
~/NAME$ pip install hppx
Looking in indexes: https://package-proxy.replit.com/pypi/simple/
ERROR: Could not find a version that satisfies the requirement hppx (from versions: none)
ERROR: No matching distribution found for hppx
~/NAME$ 
fleet bridge
faint vector
#

idk what this channel is

#

idk where the help is for this

fleet bridge
mighty parcel
#

!e

night quarryBOT
#
Missing required argument

code

sick hound
sick hound
vast wave
sick hound
#

Gnome terminal default looks like that?

vast wave
#

if you want to know the name of the prompt, powerlevel10k via zsh

#

but the terminal is gnome terminal, yes

sick hound
vast wave
#

yes

#

that’s pl10k

sick hound
#

Is that a zsh theme?

vast wave
#

yes

forest meadow
#

This is similar to how a font will be shown for a unicode char. It takes the 16 bit (2 byte) number, and applies a font style and renders it. So it's not very portable in that terminals don't even copy paste an emoji correctly sometimes.

magic wraith
fleet bridge
#

!e ```py
d = dict(a=1, b=2, c=3, d=4)
print(*map(list, zip(*d.items())))

night quarryBOT
#

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

['a', 'b', 'c', 'd'] [1, 2, 3, 4]
fleet bridge
#

!e ```py
d = dict(a=1, b=2, c=3, d=4)
print(*zip(*d.items()))

night quarryBOT
#

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

('a', 'b', 'c', 'd') (1, 2, 3, 4)
night quarryBOT
#

@mellow salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
fleet bridge
#

!e ```py
print(f'{any([]) = }')
print(f'{all([]) = }')

night quarryBOT
#

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

001 | any([]) = False
002 | all([]) = True
vast wave
#

if all() is true, any() should as well

low lynx
#

not really

#

that's not really a rule

#

any is asking "is there anything here that is True?" so it defaults to a negative if there is nothing there
all is asking "is everything here True?" so it defaults to a positive if there is nothing there
if you negate all you have that it's (not (anything here that is False?)), so you have
any: (anything here that is True?)
all: (not (anything here that is False?))
if you have at least one thing, then you will have that at least one of those (anything here) conditions are true, so you can eventually deduce that all => any
but if you have nothing, then both of those will be False, so you can't deduce that

serene garnet
#

how do you think about this code?

#
g=len;o=range;z=list;k=map;v=int;y=zip
exec('''w=?u,f,l,a:f([[a([k[j:j+l]!k@u[i:i+l]])!j@o(0,g(u),l)]!i@o(0,g(u),l)])
e=?u,r:[[l !k@j !l@k]!i@o(1<<r)!j@y(*u[i])];n,m=$;u=[z($)!_@o(1<<n)]
f=[d:=?x:x[::-1],?x:[d(i)!i@x],?x:z(k(z,y(*d(x)))),?x:d(z(k(z,y(*x))))]
!_@o(m):a,b=$;r=n-b;l=g(u)>>r;u=e(w(u,z,l,f[a-1]),r)if a<5 else e(w(u,f[a-5],l,z),r)
!i@u:print(*i)'''.replace('?','lambda ').replace('$','k(v,input().split())').replace('!','for ').replace('@',' in '))
fleet bridge
#

I like that

earnest wing
# vast wave if all() is true, any() should as well

you can also think of it this way: a contract with all() is that all(x) and all(y) is the same as all(x + y), but if x!=y==[] then this must mean all([])==True
this is different with any() because instead of and it uses or, you can probably figure out the logic there

royal sun
#

!e g=len;o=range;z=list;k=map;v=int;y=zip
exec('''w=?u,f,l,a:f([[a([k[j:j+l]!k@u[i:i+l]])!j@o(0,g(u),l)]!i@o(0,g(u),l)])
e=?u,r:[[l !k@j !l@k]!i@o(1<<r)!j@y(*u[i])];n,m=$;u=[z($)!@o(1<<n)]
f=[d:=?x:x[::-1],?x:[d(i)!i@x],?x:z(k(z,y(*d(x)))),?x:d(z(k(z,y(*x))))]
!
@o(m):a,b=$;r=n-b;l=g(u)>>r;u=e(w(u,z,l,f[a-1]),r)if a<5 else e(w(u,f[a-5],l,z),r)
!i@u:print(*i)'''.replace('?','lambda ').replace('$','k(v,input().split())').replace('!','for ').replace('@',' in '))

night quarryBOT
#

@royal sun :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 2, in <module>
003 |     exec('''w=?u,f,l,a:f([[a([k[j:j+l]!k@u[i:i+l]])!j@o(0,g(u),l)]!i@o(0,g(u),l)])
004 |   File "<string>", line 2, in <module>
005 | EOFError: EOF when reading a line
quartz wave
quartz wave
# quartz wave making a nodevisitor rn

it works ```py

print(unparse(tree))
w = lambda u, f, l, a: f([[a([map[j:j + l] for k in u[i:i + l]]) for j in range(0, len(u), l)] for i in range(0, len(u), l)])
e = lambda u, r: [[l for k in j for l in k] for i in range(1 << r) for j in zip(*u[i])]
n, m = map(int, input().split())
u = [list(map(int, input().split())) for _ in range(1 << n)]
f = [(d := (lambda x: x[::-1])), lambda x: [d(i) for i in x], lambda x: list(map(list, zip(*d(x)))), lambda x: d(list(map(list, zip(*x))))]
for _ in range(m):
a, b = map(int, input().split())
r = n - b
l = len(u) >> r
u = e(w(u, list, l, f[a - 1]), r) if a < 5 else e(w(u, f[a - 5], l, list), r)
for i in u:
print(*i)

sick hound
#

Calculating the area of ​​figures

(lambda formuls: (lambda a: [print("Selected non-existent item"), exit()] if a not in range(len(formuls)) else (lambda formula, args: [print("Enter formula arguments:"), [args.update({arg["code_name"]: arg['type'](input(f"\t{arg['human_name']}(type {arg['type'].__name__}): "))}) for arg in formula["args"]], print("\n"), [print("Formula result:"), print(f"\t{formula['formula'](**args)}")]])(formuls[a], {}))((lambda: [print("Choose what you want to calculate:"), [print(f"\t{i}. {name}") for i, name in zip(range(1, len(formuls)+1), (formula['name'] for formula in formuls))], int(input("> ")) - 1, print("\n")])()[-2]))([{"name": "Square area", "formula": lambda x: x**2, "args": [{"code_name": "x", "human_name": "Side length", "type": float}]}, {"name": "Rectangle area", "formula": lambda a, b: a*b, "args": [{"code_name": "a", "human_name": "Side length 'a'", "type": float}, {"code_name": "b", "human_name": "Side length 'b'", "type": float}]}, {"name": "Circle area", "formula": lambda r: 3.14 * r**2,"args": [{"code_name": "r", "human_name": "Circle radius", "type": float}]}])

1087 symbols

merry pasture
#

to all ye maesteros

#

any way I could rewrite this in a single line ?

#
from requests.utils import default_headers
headers = default_headers()```
static knoll
#

use __import__

quartz wave
merry pasture
#

like why is utils apperaing twice in the code ?

#

....

#

the repl shows once is enough, but twice also works

#

Thanks anyway !

quartz wave
fleet bridge
#

But if you import requests it is not necessarily have .utils attr

#

Import system should import submodule and set attr on parent module, so it is more reliable to import requests.utils

unique heath
#

!e cannot compare to the glory of

(___:=eval(__builtins__.__dir__().__getitem__((420).__floordiv__(__import__.__dir__().__len__().__sub__(20)))),_____:=lambda __: eval(__builtins__.__dir__().__getitem__(14))(__),eval(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__getitem__(__import__.__dir__().__len__().__sub__(__name__.__doc__.__len__().__floordiv__(__builtins__.__doc__.__len__()))).__len__()).__sub__(__name__.__dir__().__len__().__sub__(__import__.__dir__().__len__()).__sub__(__package__.__dir__().__len__()).__sub__(__package__.__dir__().__len__())).__add__(4)))(chr(__import__.__dir__().__len__().__add__(__builtins__.__dir__().__len__())), (eval(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__getitem__(__import__.__dir__().__len__().__sub__(__name__.__doc__.__len__().__floordiv__(__builtins__.__doc__.__len__()))).__len__()).__sub__(10))), ), {chr(__name__.__dir__().__len__()):(lambda _: ___(_____(72).__add__(_____(101)).__add__(_____(108)).__add__(_____(108)).__add__(_____(111)).__add__(_____(32)).__add__(_____(119)).__add__(_____(111)).__add__(_____(114)).__add__(_____(108)).__add__(_____(100)).__add__(_____(33))))})().Q())```
night quarryBOT
#

@unique heath :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 |     (___:=eval(__builtins__.__dir__().__getitem__((420).__floordiv__(__import__.__dir__().__len__().__sub__(20)))),_____:=lambda __: eval(__builtins__.__dir__().__getitem__(14))(__),eval(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__getitem__(__import__.__dir__().__len__().__sub__(__name__.__doc__.__len__().__floordiv__(__builtins__.__doc__.__len__()))).__len__()).__sub__(__name__.__dir__().__len__().__sub__(__import__.__dir__().__len__()).__sub__(__package__.__dir__().__len__()).__sub__(__package__.__dir__().__len__())).__add__(4)))(chr(__import__.__dir__().__len__().__add__(__builtins__.__dir__().__len__())), (eval(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__getitem__(__import__.__dir__().__len__().__sub__(__name__.__doc__.__len__().__floordiv__(__builtins__.__doc__.__
... (truncated - too long)

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

unique heath
#

damn it doesnt work now

#

rewrite time

unique heath
#

!e

eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__()))))(__name__, (eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__()))))), ), {chr(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())))): (lambda _: eval(__builtins__.__dir__().__getitem__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__add__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__()))).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__name__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())))))))("Hello, world!"))})().E()
night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello, world!
unique heath
arctic skiff
#

i know but what it does

unique heath
#

print hello world?

arctic skiff
#

like mine does __import__('__hello__').main()

dreamy pier
restive void
#

A few months ago, there was a challenge here about arbitrary code execution from eval() without dunders or builtins. Can someone send me a link to that, especially the/a solution? It's for a talk about eval being unsalvageable.

dreamy pier
restive void
#

Thank you!

kindred path
#

hey vitnes

#

how does it work

#

@dreamy pier

dreamy pier
#

just creates a class with method E, which prints out "Hello, world!"

kindred path
#

what does this do again

#

what does this do

kindred path
#

imma use it

kindred path
#

oh so it runs the os.system command?

#

@half escarp

#

does it work like a normal function

#

can i put parentheses at the end and run an os command

nimble mirage
#

Any concept/impl of comptime evalutation in python?

kindred path
#

code to concatenate two strings with a space inbetween

#
x = (string1, string2).__repr__().replace("(\'","(\"")
  y = x.replace("\', \'","\", \"")
  z = y.replace("\')","\")")
  (tempList:=z.split("(")[1].split(")")[0].split("\""))[1]+tempList[2][1]+tempList[3].replace("\\\\", "\\")
ionic latch
#

Hello python

#

Hi

quartz wave
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 6, in <module>
003 |     (tempList:=z.split("(")[1].split(")")[0].split("\""))[1]+tempList[2][1]+tempList[3].replace("\\\\", "\\")
004 |                                                              ~~~~~~~~^^^
005 | IndexError: list index out of range
kindred path
#

you need to escape the single quotes

quartz wave
quartz wave
# kindred path you need to escape the single quotes

!e ```py
string1 = "The World Wide Web (aka \'WWW\')"
string2 = "(\'They\' made) something"
x = (string1, string2).repr().replace("('","("")
y = x.replace("', '","", "")
z = y.replace("')","")")
(tempList:=z.split("(")[1].split(")")[0].split("""))[1]+tempList[2][1]+tempList[3].replace("\\", "\")

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 6, in <module>
003 |     (tempList:=z.split("(")[1].split(")")[0].split("\""))[1]+tempList[2][1]+tempList[3].replace("\\\\", "\\")
004 |                                                              ~~~~~~~~^^^
005 | IndexError: list index out of range
quartz wave
# kindred path you need to escape the single quotes

!e ```py
string1 = "The World Wide Web (aka 'WWW')"
string2 = "('They' made) something"
x = (string1, string2).repr().replace("('","("")
y = x.replace("', '","", "")
z = y.replace("')","")")
(tempList:=z.split("(")[1].split(")")[0].split("""))[1]+tempList[2][1]+tempList[3].replace("\\", "\")

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 6, in <module>
003 |     (tempList:=z.split("(")[1].split(")")[0].split("\""))[1]+tempList[2][1]+tempList[3].replace("\\\\", "\\")
004 |                                                              ~~~~~~~~^^^
005 | IndexError: list index out of range
quartz wave
#

what is "escape"

kindred path
#

\'

kindred path
#

Why

#

Doesn’t it work

#

Well I don’t rly care

#

It’s fine

#

U can try to fix it if you want

#

!e ```py
string1 = "The World Wide Web aka WWW"
string2 = "They made something"
x = (string1, string2).repr().replace("('","("")
y = x.replace("', '","", "")
z = y.replace("')","")")
(tempList:=z.split("(")[1].split(")")[0].split("""))[1]+tempList[2][1]+tempList[3].replace("\\", "\")

#

!e ```py
string1 = "The World Wide Web aka WWW"
string2 = "They made something"
x = (string1, string2).repr().replace("('","("")
y = x.replace("', '","", "")
z = y.replace("')","")")
print(tempList:=z.split("(")[1].split(")")[0].split("""))[1]+tempList[2][1]+tempList[3].replace("\\", "\")

night quarryBOT
#

@kindred path :warning: Your 3.11 eval job has completed with return code 0.

[No output]
kindred path
#

!e ```py
string1 = "The World Wide Web aka WWW"
string2 = "They made something"
x = (string1, string2).repr().replace("('","("")
y = x.replace("', '","", "")
z = y.replace("')","")")
print(tempList:=z.split("(")[1].split(")")[0].split("""))[1]+tempList[2][1]+tempList[3].replace("\\", "\")

night quarryBOT
#

@kindred path :x: Your 3.11 eval job has completed with return code 1.

001 | ['', 'The World Wide Web aka WWW', ', ', 'They made something', '']
002 | Traceback (most recent call last):
003 |   File "/home/main.py", line 6, in <module>
004 |     print(tempList:=z.split("(")[1].split(")")[0].split("\""))[1]+tempList[2][1]+tempList[3].replace("\\\\", "\\")
005 |     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^
006 | TypeError: 'NoneType' object is not subscriptable
versed eagle
#

theres also that one almost-python thing that compiles into llvm stuff
which would have a lot more optimisations done to it

#

but no way to explicitly do anything at compile-time with that, its all up to the compiler

languid hare
#

!e

import numpy as np
print([1, np.array([1,2])].count(1))
night quarryBOT
#

@languid hare :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 2, in <module>
003 |     print([1, np.array([1,2])].count(1))
004 |           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 | ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
languid hare
#

aw

restive void
#
In [88]: for a, b in zip(x, y, strict=True):
    ...:     if a != b:
    ...:         raise ValueError
    ...:

In [89]: x
Out[89]: 'ooooo'

In [90]: y
Out[90]: 'ooooo'

In [91]: x == y
Out[91]: False

What did I do? x and y really are strings, and I didn't mess with the str class (patching __eq__ or something like that).

fleet bridge
#

!e assert 'o' == 'о'

night quarryBOT
#

@fleet bridge :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 |     assert 'o' == 'о'
004 |            ^^^^^^^^^^
005 | AssertionError
fleet bridge
#
import sys

def hook(obj: object) -> None:
  if isinstance(obj, bool):
    print(not obj)
  else:
    print(repr(obj))

sys.displayhook = hook

###
x = 'ooooo'
y = 'ooooo'

for a, b in zip(x, y, strict=True):
  if a != b:
    raise ValueError

# then in REPL do this
>>> x
'ooooo'
>>> y
'ooooo'
>>> x == y
False
>>>
#

!e maybe you did this 🤔 ```py
print('''
In [88]: for a, b in zip(x, y, strict=True):
...: if a != b:
...: raise ValueError
...:

In [89]: x
Out[89]: 'ooooo'

In [90]: y
Out[90]: 'ooooo'

In [91]: x == y
Out[91]: False
'''.strip())

night quarryBOT
#

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

001 | In [88]: for a, b in zip(x, y, strict=True):
002 |     ...:     if a != b:
003 |     ...:         raise ValueError
004 |     ...:
005 | 
006 | In [89]: x
007 | Out[89]: 'ooooo'
008 | 
009 | In [90]: y
010 | Out[90]: 'ooooo'
011 | 
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/U3AMCIJ4SKLS7R4XVLCCEWQZZE

fleet bridge
#

another possibility (you should replace a with something that looks like an o, for example russian o: о)

#
>>> zip = lambda *_, **__: ()
>>>
>>> x = 'ooooo'
>>> y = 'aaaaa'
>>>
>>> for a, b in zip(x, y, strict=True):
...   if a != b:
...     raise ValueError
...
>>>
>>> x
'ooooo'
>>> y
'aaaaa'
>>> x == y
False
#

did i guess?

#

i copy-pasted your symbols and they are in fact equal: ```py

'ooooo' == 'ooooo'
True

so i see two options:
1) `sys.excepthook` does nothing
2) `zip` is shadowed
#

it is also possible that you patched REPL itself too much (it ignores some predefined strings, or compiles them differently)

restive void
#

These really are two strings of length 5, each of their elements is a normal ASCII o.

fleet bridge
#
>>> 'x' == 'x'
True
>>> 'y' == 'y'
True
``` 🤔
#

no weird name trickery too

restive void
#

Correct. No cheap tricks

quartz wave
#

oh

#
>>> x = 'ooooo'
>>> y = 'ooooo'
>>> for a, b in zip(x, y, strict=True):
...     if a != b:
...             raise ValueError
...
>>>
#

wait nvm why am i looking at that

restive void
#

Perhaps a hint:
Both x[1:] == y[1:] and x[:-1] == y[:-1] are true

quartz wave
#

i thought there was some cpython bug with zip() there but ig not

fleet bridge
#

hmm

#

no, that would trigger ValueError

restive void
fleet bridge
#

you somehow forced x to be 2-byte kind, so _PyUnicode_Equal returns False

#
>>> x = 'oooooж'
>>> x = x[:-1]
>>> y = 'ooooo'
>>> x
'ooooo'
>>> y
'ooooo'
>>> x == y
True
``` that didnt work
quartz wave
fleet bridge
#

:(

#

that makes sense

quartz wave
#

so that it always uses the least possible size

fleet bridge
#

how did you do that? ctypes stuff or just normal python?

restive void
#

ctypes stuff

fleet bridge
#

ok, then it is not a bug 😄

restive void
#

Yeah, not a bug. But interesting behaviour :)
And you could make a z as well.

quartz wave
# restive void ctypes stuff

i thought this was gonna be easy ```pycon

import ctypes
p = ctypes.pythonapi.PyUnicode_FromKindAndData
p.argtypes = ctypes.c_int, ctypes.c_char_p, ctypes.c_ssize_t
p.restype = ctypes.py_object
x = p(2, b'o\0o\0o\0o\0o\0', 5)
y = 'ooooo'
for a, b in zip(x, y, strict=True):
... if a != b:
... raise ValueError
...
x
'ooooo'
y
'ooooo'
x == y
True

#

oh nvm it is ```pycon

p = ctypes.pythonapi.PyUnicode_New
p.argtypes = ctypes.c_ssize_t, ctypes.c_uint
p.restype = ctypes.py_object
x = p(5, 65535)
ctypes.memmove(id(x) + 72, b'o\0o\0o\0o\0o\0', 10)
2236930728024
x
'ooooo'
y
'ooooo'
for a, b in zip(x, y, strict=True):
... if a != b:
... raise ValueError
...
x
'ooooo'
y
'ooooo'
x == y
False
x[1:] == y[1:]
True
x[:-1] == y[:-1]
True

restive void
fleet bridge
#
>>> import ctypes
>>> (ctypes.c_uint8 * 64).from_address()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: c_ubyte_Array_64.from_address() takes exactly one argument (0 given)
>>>
>>> x = 'ooooж'
>>> bytes((ctypes.c_uint8 * 64).from_address(id(x))).hex(' ', -8)
'0100000000000000 7094559ff97f0000 0500000000000000 0c65ac0d59249158 a8006e005c003300 f8d08d6556010000 0000000000000000 0000000000000000'
>>> hex(id(x))
'0x156658dd0b0'
>>> bytes.fromhex('f8d08d6556010000')
b'\xf8\xd0\x8deV\x01\x00\x00'
>>> bytes.fromhex('f8d08d6556010000')[::-1]
b'\x00\x00\x01Ve\x8d\xd0\xf8'
>>> bytes.fromhex('f8d08d6556010000')[::-1].hex()
'00000156658dd0f8'
>>> eval('0x'+bytes.fromhex('f8d08d6556010000')[::-1].hex())
1_470_582_608_120
>>> bytes((ctypes.c_uint8 * 64).from_address(1_470_582_608_120)).hex(' ', -8)
'6f006f006f006f00 3604000000006f00 6f00360427000000 0400000000000000 7094559ff97f0000 2800000000000000 88fa97a82d86ae21 e4006e005c003300'
>>> ord('o')
111
>>> hex(ord('o'))
'0x6f'
>>> bytes((ctypes.c_uint8 * 2).from_address(1_470_582_608_120 + 8)).hex(' ', -8)
'3604'
>>> (ctypes.c_uint8 * 2).from_address(1_470_582_608_120 + 8) = [0x6f, 0]
  File "<stdin>", line 1
    (ctypes.c_uint8 * 2).from_address(1_470_582_608_120 + 8) = [0x6f, 0]
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
>>> (ctypes.c_uint8 * 2).from_address(1_470_582_608_120 + 8)[:] = [0x6f, 0]
>>>
>>> x
'ooooo'
``` i figured this out
quartz wave
fleet bridge
#
x = 'жoooo'
index = 0
kind = 2
change_to = 'o'

import ctypes
ctypes.c_uint16.from_address(ctypes.c_void_p.from_address(id(x) + 5 * ctypes.sizeof(ctypes.c_void_p)).value + index * kind).value = ord(change_to)
#

for some reason there is a pointer to begginning of data in str object

#

so i used that

languid night
karmic pumice
#

@quartz wave

get_string = efrem_utils.get_validated_input()

💀 0.0.7 patch going crazy

quartz wave
#

nice

quartz wave
karmic pumice
#

why 😢 kwargs gaming

#

ok imma add this because i just noticed i need to fix a typehint 💀:
hopefully the typehints make sense now and msg is now a normal argument

versed eagle
mental vector
#

Does anyone have any interesting articles they'd recommend on some obscure or bizarre python metaprogramming/black-magic techniques? Not looking to learn anything practical necessarily, I just enjoy reading about the crazy stuff people come up with and understanding the inner workings of python

karmic pumice
#

looks like .pyc to me

#

you can manually generate it with something like:

py -m compileall <file1.py> [<file2.py> <fileN.py>]
#

and its not really obfuscation, its.. compilation

fickle stratus
#

anyone got a cool idea i can try to work out in python?

karmic pumice
#

!e

(_while:=lambda cond, fn, args:((fn(args()if(callable(args))else(args))),_while(cond, fn, args)if(cond())else(None)),x:=10,_while(lambda: x>0, lambda _:(globals().__setitem__("x",x-1),print(x)),None))
night quarryBOT
#

@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 9
002 | 8
003 | 7
004 | 6
005 | 5
006 | 4
007 | 3
008 | 2
009 | 1
010 | 0
karmic pumice
#

experimenting with functional stuff

vast wave
#

!e (w:=lambda c,f:(f(),w(c,f)if c()else 0),x:=10,w(lambda:x>0,lambda:(x:=x-1,print(x))))

night quarryBOT
#

@vast wave :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 |     (w:=lambda c,f:(f(),w(c,f)if c()else 0),x:=10,w(lambda:x>0,lambda:(x:=x-1,print(x))))
004 |                                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 |   File "/home/main.py", line 1, in <lambda>
006 |     (w:=lambda c,f:(f(),w(c,f)if c()else 0),x:=10,w(lambda:x>0,lambda:(x:=x-1,print(x))))
007 |                     ^^^
008 |   File "/home/main.py", line 1, in <lambda>
009 |     (w:=lambda c,f:(f(),w(c,f)if c()else 0),x:=10,w(lambda:x>0,lambda:(x:=x-1,print(x))))
010 |                                                                           ^
011 | UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/DRFT6ZOPLTNNMV7X6H3GVSCZBU

vast wave
#

ah thats why that was there

night quarryBOT
#

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

001 | 9
002 | 8
003 | 7
004 | 6
005 | 5
006 | 4
007 | 3
008 | 2
009 | 1
010 | 0
dreamy pier
#

x:--
pithink

rigid knoll
#

!e False == False in [ False ]

#

!e print(False == False in [ False ])

night quarryBOT
#

@rigid knoll :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
fleet bridge
#

!e ```py
print(1 in [1] == True)

night quarryBOT
#

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

False
rigid knoll
#

Yes Same pattern and Same Reason

#

Reason

fleet bridge
#

!e ```py
print(1 in [1]) # True
print(True == True) # True

print(1 in [1] == True) # False?

night quarryBOT
#

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

001 | True
002 | True
003 | False
rigid knoll
#

!e

night quarryBOT
#
Missing required argument

code

rigid knoll
#

!e
a=[],
try:
a[0]+=[42]
except Exception as e:
print(e)
print(a)

night quarryBOT
#

@rigid knoll :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 'tuple' object does not support item assignment
002 | ([42],)
languid hare
#

neat

#

i suppose it makes sense, no matter how unexpected

rigid knoll
rigid knoll
#

!e [] = {}

night quarryBOT
#

@rigid knoll :warning: Your 3.11 eval job has completed with return code 0.

[No output]
rigid knoll
#

!e {} = []

night quarryBOT
#

@rigid knoll :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     {} = []
003 |     ^^
004 | SyntaxError: cannot assign to dict literal here. Maybe you meant '==' instead of '='?
fleet bridge
#

Imagine assigning to set literal

#

Variables are assigned to values in random order

#
{a, b} = 1, 2
print(a, b) # 1 2 or 2 1
vast wave
#

!e ```py
for _ in range(10):
{a, b} = 1, 2
print(a, b) # 1 2 or 2 1

night quarryBOT
#

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

001 |   File "/home/main.py", line 2
002 |     {a, b} = 1, 2
003 |     ^^^^^^
004 | SyntaxError: cannot assign to set display here. Maybe you meant '==' instead of '='?
fleet bridge
#

I know, i was just dreaming about this

rigid knoll
#

!e
() = [] = {}

night quarryBOT
#

@rigid knoll :warning: Your 3.11 eval job has completed with return code 0.

[No output]
restive void
#

Even the items in a set have a defined order, it's just not by insertion.

ember flower
#

return requests.get(...).json()['key']doesnt work?
It returns the same as:
return requests.get(...).json()

#

I need to do this:

return x['key']```
nova barn
#

Is there a more pythonic way of combining two different sequences into like a tuple than tuple(itertools.chain(first, second))?

rugged owl
digital mesa
#

can do the same with [*a, *b] for lists

#

(where a and b are arbitrary iterables)

nova barn
#

Yeah I got this same thing on general and it blew my mind, when was this made possible?

fleet bridge
#

python2?

nova barn
#

damn, so it's just been something I never knew =D

fleet bridge
# fleet bridge python2?

apparently not ```py

python.exe -c "x = (1,2); y = (3, 4); print (*x,*y)"
File "<string>", line 1
x = (1,2); y = (3, 4); print (*x,*y)
^
SyntaxError: invalid syntax

nova barn
fleet bridge
#

yeah

#

2013

nova barn
#

10 years xD

#

It was like 3.5 or 3.6 when I started using pure 3 over hybrid 2 and 3.

#

And I internalized the {**sth, **other} but completely missed that well obviously (*sth, *other) should also work

#

I guess in retrospect this is the antithesis of the channel to ask this type of question in 😄

fleet bridge
#

!e ```py
chain = lambda *a: tuple((x:=[],[x.extend(_)for _ in a])[0])

print(chain())
print(chain([1,2],[3,4]))
print(chain('abcd','efg','h'))

night quarryBOT
#

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

001 | ()
002 | (1, 2, 3, 4)
003 | ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
fleet bridge
#

!e ```py
chain = lambda *a: tuple((x:=[],[*map(x.extend,a)])[0])

print(chain())
print(chain([1,2],[3,4]))
print(chain('abcd','efg','h'))

night quarryBOT
#

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

001 | ()
002 | (1, 2, 3, 4)
003 | ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
dreamy pier
#

!e

chain = lambda *a: (*sum(([*x] for x in a),[]),)

print(chain())
print(chain([1,2],[3,4]))
print(chain('abcd','efg','h'))
night quarryBOT
#

@dreamy pier :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | ()
002 | (1, 2, 3, 4)
003 | ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
quartz wave
#

!e ```py
f=lambda*a:sum(map(tuple,a),())
print(f())
print(f([1,2],[3,4]))
print(f('abcd','efg','h'))

night quarryBOT
#

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

001 | ()
002 | (1, 2, 3, 4)
003 | ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
wet fulcrum
#

!e

print(isinstance(True, bool))```
night quarryBOT
#

@wet fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | True
002 | True
restive void
#

float is misleading; True is not a float. It is an int, though, yes.

restive void
# wet fulcrum interesting

!e Can be seen as a historical artifact. In early versions of Python bools didn't exist, and the ints 1 and 0 where used instead. When it was added, bool was made a subclass of int.

print(f"{issubclass(bool, int)=}")
print(f"{1 == True=}")
print(f"{0 == False=}")
night quarryBOT
#

@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | issubclass(bool, int)=True
002 | 1 == True=True
003 | 0 == False=True
fleet bridge
#
>>> s = 'print(123)'
>>> n = int.from_bytes(s.encode()); print(f'eval(({n}).to_bytes({(n.bit_length()+7)//8}))')
eval((531015572043140546310953).to_bytes(10))
#

!e eval((531015572043140546310953).to_bytes(10))

night quarryBOT
#

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

123
fleet bridge
#

it uses this character set: ().0123456789_abelostvy
it can execute arbitrary code

lunar marsh
#

whats the lowest amount of characters to execute arbitrary code anyone has managed in python3? i've got 8

serene stratus
#

wdym with arbitrary code

lunar marsh
#

any python program

dreamy pier
#

py x
where x is file
or what

lunar marsh
#

!e ```e
exec('x=%x'%('e'==''))==exec('e=%x'%(''==''))==exec('c=%x%%x'%e%e)==exec('c=%x%%x%%%%x%%%%%%%%x'%x%c%e%e)==exec('ee=%x%%x%%%%x'%e%x%c)==exec('ee=%x'%ee)==exec('ee=%x'%ee)==exec('xe=ee%ce%%ce'%ee%ee)==exec('xx=ee%cc'%xe)==exec('xc=xx%ce'%ee)==exec('ce=xc%ce'%ee)==exec('cx=ce%cc'%xe)==exec('cc=cx%ccx'%ee)==exec('eee=cc%cxc'%ee)==exec('eex=eee%cc'%xe)==exec('eec=eex%cxc'%xe)==exec('exe=eec%cee'%xe)==exec('exx=exe%ccc'%ee)==exec('exc=exx%ce'%ee)==exec('ece=exc%cc'%xe)==exec('ecx=ece%cc'%xe)==exec('ecc=ecx%ce'%xe)==exec('xee=ecc%cc'%xe)==exec('xex=xee%ce'%xe)==exec('xec=exx%cxex'%xe)==exec('xxe=xec%cecc'%ee)==exec('xxx=xxe%ce'%ee)==exec('xxc=xxx%cc'%xe)==exec('''ex=('%c%%c%%%%c%%%%%%%%c')''')==exec('''ec=('')''')==exec('ec%c=ex%%xxc%%xxe%%ecx%%exx'%ee)==exec('ec%c=ex%%eex%%xx%%cx%%ecc'%ee)==exec('ec%c=ex%%xee%%ece%%ece%%exc'%ee)==exec('ec%c=ex%%exe%%eee%%exc%%xxe'%ee)==exec('ec%c=ex%%ece%%xex%%cx%%xc'%ee)==exec(ec)

night quarryBOT
#

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

hello world
lunar marsh
#

like this

#

here using only exc()'%=

dreamy pier
#

ah
then idk never did that

restive void
serene stratus
finite blaze
#

Hey, do you know any place (discord sever for example) where I can talk about C# golfing?

#

Or just golfing in general

fleet bridge
#

There is esolangs server, maybe you also can talk about golfing there

#

I dont know if there is a server about golfing

finite blaze
#

Alright, thanks

dreamy pier
#

This site has discord server
https://code.golf/

#

There is not a lot of talking but something

meager zinc
#

im wondering if there's a better solution for https://leetcode.com/problems/merge-strings-alternately/
I have this:

from itertools import*
class Solution:mergeAlternately=lambda s,*w:''.join(chain(*zip_longest(*w,fillvalue='')))

(which ignoring the leetcode stuff becomes)

from itertools import*
lambda *w:''.join(chain(*zip_longest(*w,fillvalue='')))
sick hound
#
M,P,O,S,Z=3e4,0,'',[]
while 1:
 I=input();A='><+-.,[]'
 if I.lower()=='exit':print('Quitting... thanks for using!');break
 I=''.join(c for c in I if c in A)
 L=len(I)
 for i in range(L):
  c=I[i]
  if c in"><":P+=1if c=='>'else-1
  if c in"+-":Z[P]=(Z[P]+1)%256if c=='+'else(Z[P]-1)%256
  if c==".":O+=chr(Z[P])
  if c==",":Z[P]=ord(input("Enter a single character: ")[0])
  if c=="[":
   if Z[P]==0:C=1;R=0
   while C>0:
    i+=1
    C+=1if I[i]=='['else-1if I[i]==']'else 0
  if c=="]":i=S.pop()-1if Z[P]!=0else i
print(O)
meager zinc
# sick hound ```py M,P,O,S,Z=3e4,0,'',[] while 1: I=input();A='><+-.,[]' if I.lower()=='exi...

uhh

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    M,P,O,S,Z=3e4,0,'',[]
ValueError: not enough values to unpack (expected 5, got 4)

this might be similar to what you're trying to do (this isn't perfect however, and could likely be more optimized):

from sys import*
s=[i:=0]*30000
while 1:
 if(p:=input()).lower()=='exit':break
 else:
  i,c=0,''
  for o in p:c+=' '*i+[f'i+=1','i-=1','s[i]=-~s[i]%256','s[i]=~-s[i]%256','print(end=chr(s[i]))','s[i]=ord(stdin.read(1))','while s[i]:','s','']['><+-.,['.find(o)]+'\n';i+=(92-ord(o))*(o in'][')
  exec(c)
arctic skiff
#

that would save 2 lines

meager zinc
#
from sys import*
s=[i:=0]*30000
while 1:
 if(p:=input()).lower()=='exit':break
 i,c=0,''
 for o in p:c+=' '*i+[f'i+=1','i-=1','s[i]=-~s[i]%256','s[i]=~-s[i]%256','print(end=chr(s[i]))','s[i]=ord(stdin.read(1))','while s[i]:','s','']['><+-.,['.find(o)]+'\n';i+=(92-ord(o))*(o in'][')
 exec(c)
arctic skiff
#

you don't even need if

#
from sys import*
s=[i:=0]*30000
while(p:=input()).lower()!='exit':
 i,c=0,''
 for o in p:c+=' '*i+[f'i+=1','i-=1','s[i]=-~s[i]%256','s[i]=~-s[i]%256','print(end=chr(s[i]))','s[i]=ord(stdin.read(1))','while s[i]:','s','']['><+-.,['.find(o)]+'\n';i+=(92-ord(o))*(o in'][')
 exec(c)
meager zinc
#

it would be !=

arctic skiff
#

forgot about that

meager zinc
#

this is better

from sys import*
s=[0]*30000
while(p:=input()).lower()!='exit':
 i,c=0,''
 for o in p:c+=' '*i+'i+=1 i-=1 s[i]=-~s[i]%256 s[i]=~-s[i]%256 print(end=chr(s[i])) s[i]=ord(stdin.read(1)) while(s[i]): s '.split()['><+-.,['.find(o)]+'\n';i+=(92-ord(o))*(o in'][')
 exec(c)
static knoll
#

whats the sys import for

#

apart from stdin

dreamy pier
#

only it i guess

dreamy pier
#

even so

s=[0]*30000
while(p:=input()).lower()!='exit':
 i,c=0,''
 for o in p:c+=' '*i+'i+=1 i-=1 s[i]=-~s[i]%256 s[i]=~-s[i]%256 print(end=chr(s[i])) s[i]=ord(open(0).read(1)) while(s[i]): s '.split()['><+-.,['.find(o)]+'\n';i+=(92-ord(o))*(o in'][')
 exec(c)
tough willow
#

and more

#

and sys.exit

static knoll
#

i meant in the context of the golf

#

🥴

tough willow
#

oh

rugged owl
tough willow
#

but cant you just open(0) instead of sys.stdin

#

no wiait it was 1

#

oridk

proper vault
#

open(0) should work, ye

tough willow
#

i was confused a bit because the REPL didnt work with both

dreamy pier
#

0 stdin
1 stdout
2 stderr

quartz wave
versed eagle
#

brainfuck interpreter?

#

im pretty sure you have a bug
open(0).read(1) returns one character, not one byte
1 character can be multibyte sequences, meaning ordinals that cant fit in a single byte

quartz wave
#

just golfed here

#

maybe ask the source

versed eagle
#

ah

quartz wave
quartz wave
#

huh

versed eagle
#

oops wrong ping

#

skfnhfh sorry

#

@sick hound

#

there

quartz wave
#

takes up +2b though

sick hound
#

Huh

sick hound
versed eagle
#

,'rb' is 5

quartz wave
#

i'm gonna have to do it again i lost it

quartz wave
#
s=[0]*30000
while(p:=next(f:=open(i:=0,'rb'))).lower()!=b'exit':
 c=''
 for o in p:c+=' '*i+'i+=1 i-=1 A=-~A%256 A=~-A%256 print(end=chrA) A=f.read(1) whileA: s '.split()[b'><+-.,['.find(o)]+'\n';i+=(92-o)*(o in b'][')
 exec(c.replace('A','(s[i])'))
versed eagle
#

oh

quartz wave
#

nvm

#

it should be +1b

#

since b'exit'!='exit'

gleaming linden
dreamy pier
#

Last two codes can't execute more than one line by me

    while(p:=next(f:=open(i:=0,'rb'))).lower()!=b'exit':
OSError: [Errno 9] Bad file descriptor
arctic skiff
#
>>> open(0)
<_io.TextIOWrapper name=0 mode='r' encoding='utf-8'>
>>>  ```
arctic skiff
#

though what this code is?

dreamy pier
#
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.
arctic skiff
fleet bridge
#

Oh, you guys created brainfuck REPL? 😄

arctic skiff
#

doesn't seems like it is a brainfuck repl

#

maybe it is

#

dunno

#

though why you are upside down? @fleet bridge

fleet bridge
#

Idk. Some guy said me to change my avatar, so i turned it upside down

dreamy pier
weak garden
#

Anyone able to help with import hell?

root@1188a87ba730:/server# python data/processing/experiments/experiment_1/experiment.py
Traceback (most recent call last):
  File "/server/data/processing/experiments/experiment_1/experiment.py", line 1, in <module>
    from food_related_values import FoodRelatedValues
ModuleNotFoundError: No module named 'food_related_values'

Contents of file:

from food_related_values import FoodRelatedValues
from gpt_nlp_engine import GPTNLPEngine


def run_experiment(test_var):
    print('RUNNED', test_var)
restive void
#

I did a thing: https://gist.github.com/L3viathan/8bc92404f7084342175b95970a086b04
Usage:

from sumtypes import ST

class Result(ST):
    Ok[T]
    Err[E]


class Maybe(ST):
    Some[T]
    Not

res = Result.Err("hello")
nah = Maybe.Not

match res:
    case Result.Ok(value):
        print("got a result:", value)
    case Result.Err():
        print("got an error")

match nah:
    case Maybe.Not:
        print("not good")
    case Maybe.Some(value):
        print("some value:", value)
floral spoke
weak garden
#

yeah, it's in the screenshot

floral spoke
#

yeah righto let me have a look

#

ok

weak garden
#

Tried all kinds of data.processing.translate and processing.translate

#

sorry food_related_values

#

instead of translate

floral spoke
#

yeah look my only idea is that it might be something to do with the file path and trying to reference python files multiple folders outside of the root program's folder? usually that isnt a problem but yknow hail maries and such

#

have you tried moving food_related_values into the root folder of experiment.py?

weak garden
#

that works

floral spoke
#

there ya go

weak garden
#

what if I don't want it there 👀

floral spoke
#

weird that that was the problem usually python can call to outside programs

#

erm usually when i reference outside files its in webdev and in that to escape the root folder you just go "../" before the filepath to go to the previous folder of the one that youre currently in

weak garden
#

When I try that I get attempted relative import with no known parent package

#

all those inits

#

for what

restive void
floral spoke
#

all goods

weak garden
#

ok sorry

zenith geode
#

idk

#

oh sht its kinda necropost xd

meager zinc
# quartz wave works in my machine

iirc on windows each process is only allowed to have one file descriptor for each of stdout, stderr, and stdin but I might be misremembering

fleet bridge
#
import types
import fishhook

@fishhook.hook(types.FunctionType)
def __repr__(self: types.FunctionType) -> str:
    """
    def f():...
    lambda: ...
    """
    varnames = self.__code__.co_freevars
    varvalues = self.__closure__ or ()
    qualname = self.__qualname__

    if self.__module__ not in {'builtins', '__main__'}:
        qualname = f'{self.__module__}.{qualname}'

    if not varnames:
        return qualname

    return (
        '<'
        + ' '.join(
            [qualname] + [f'{n}={v.cell_contents}' for n, v in zip(varnames, varvalues)]
        )
        + '>'
    )

@fishhook.hook(types.BuiltinFunctionType)
@fishhook.hook(types.MethodWrapperType)
def __repr__(self: types.BuiltinFunctionType) -> str:
    """
    print # builtin function
    sys.exit # builtin function
    [].append # builtin method
    """
    obj = self.__self__
    if isinstance(obj, types.ModuleType):
        if obj.__name__ in {'builtins', '__main__'}:
            return self.__qualname__
        obj = obj.__name__
    else:
        obj = repr(obj)
    return f'{obj}.{self.__name__}'

@fishhook.hook(types.ModuleType)
def __repr__(self: types.ModuleType) -> str:
    """
    __main__ builtins
    sys
    """
    return self.__name__

@fishhook.hook(type)
def __repr__(self: type) -> str:
    """
    int enum.Enum X
    """
    if self.__module__ in {'builtins', '__main__'}:
        return self.__qualname__
    return f'{self.__module__}.{self.__qualname__}'

@fishhook.hook(types.MethodDescriptorType)
@fishhook.hook(types.WrapperDescriptorType)
def __repr__(self: types.MethodDescriptorType) -> str:
    """
    list.append # method descriptor
    object.__init__ # wrapper descriptor (slot wrapper)
    """
    mod = getattr(getattr(self, '__objclass__', None), '__module__', None)
    if mod in {None, 'builtins', '__main__'}:
        return self.__qualname__
    return f'{mod}.{self.__qualname__}'

``` UPD: added more overwrites
#
    varnames = self.__code__.co_freevars
    varvalues = self.__closure__ or ()

im not sure with this part
will this always be correct? i mean will these two sequences correspond to each other 1-to-1?

#

it seems to be working in my little tests, but i am not sure if this will work even in weird cases

arctic skiff
fleet bridge
#
>>> {1:2,object:object(),(lambda:...):print}.keys.__call__
{1: 2, object: <object at 0x00199BCD250C0>, <lambda>: print}.keys.__call__
``` isn't this beautiful?
#
>>> class X(type): ...
...
>>> class X(X): ...
...
>>> class X(X, metaclass=X): ...
...
>>> X.__class__ = X
>>> assert X is type(X) is X.__class__
>>> X
Traceback (most recent call last):
  ...
RecursionError: maximum recursion depth exceeded while getting the str of an object
>>> 
``` 😭
#
>>> class X(type): ...
...
>>> X
X
>>> class X(X): ...
...
>>> X
X
>>> class X(X, metaclass=X): ...
...
>>> X
<X 'X'>
``` recursive repr :(
narrow hound
ember vessel
#

Code Golfed Snake

from pygame import*
from random import*
r=randrange
d=display.set_mode((z:=500,z))
m=Vector2
s=[m(0,0)]
v=1,0
f=m(1,1)
u=-1
j=50
while not event.get(256):
 h=s[u];d.fill(0)
 if(k:=key.get_pressed())[K_w]:v=0,u
 if k[K_s]:v=0,1
 if k[K_a]:v=u,0
 if k[K_d]:v=1,0
 for b in s+[f]:draw.circle(d,"red",b*10+(4,4),4)
 s+=[h+v];display.flip();time.wait(99)
 if h==f:f.xy=r(j),r(j)
 else:s.pop(0)

387 characters (including spaces and newlines)

#

(no u cant die)

#

(but i have a version that has that)

restive void
restive void
#

Oh, right

ember vessel
#

?

restive void
#

Nevermind, I somehow read the first r as a different letter

ember vessel
#

lol

quartz wave
ember vessel
#

what did u change?

#

oh

#

the last line

#

huh

#

what does the do

#

it look invalid...but it works

quartz wave
ember vessel
#

else:_,*s=s

#

under scroe if for var assignment...

#

ohhhh

#

i get it

#

ur splitting s into two parts

#

why?

#

oh

restive void
#

It's just doing s.pop(0)

ember vessel
#

is that a way to pop the first element

ember vessel
quartz wave
#

can it just be d.flip()?

ember vessel
#

wdym

restive void
#

!e

x = [1, 2, 3, 4]
_, *x = x
print(x)
night quarryBOT
#

@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.

[2, 3, 4]
quartz wave
ember vessel
#

on the pygame discord server, we had a long line of versions

#

i wrote the above one

#

i think imma try to make one from scratch using the sketchiest techniques possible

restive void
#

You should be able to do something like

v={K_w:(0,u),K_s:(0,1),K_a:(u,0),K_d:(1,0)}[k.index(1)]

instead of all the ifs

ember vessel
#
from pygame import*
d=display
s=d.set_mode()
while not event.get(256):
    s.fill(0)
    d.flip()

Shortest start code possible (i think)

#

its even shorter than before

restive void
#

And depending on the actual value of K_*, using the int directly might be shorter

ember vessel
restive void
ember vessel
#

oh, i get it now, i think

#

they are

#

but why k.index(1)

restive void
ember vessel
#

ah

restive void
ember vessel
#

yeah

#

i just tested

#

i think i have a better idea

restive void
#

Can add [1] to the list

ember vessel
#

ye, cuz the index isnt in the tuple

quartz wave
quartz wave
#

handling the cases where no key is pressed

restive void
quartz wave
#

i think

ember vessel
#
from pygame import*
d=display
s=d.set_mode()
u=-1
f=1,0
v=f
e=event.get
while not e(256):
    s.fill(0)
    k=e(768)
    if k:v=f if(k:=k[0].key)==K_d else(u,0)if k==K_a else(0,1)if k==K_w else(0,u)
    d.flip()
```?
#

it handles controls now

#

oh

#

forgot to code golf

#

there

quartz wave
ember vessel
#

Did you guys get the controls script to work? @restive void @quartz wave

#

mine is way to long

#

nope

#

still to long :(

#

hows this real?

from pygame import*
from random import*
r=randrange
q=display
d=q.set_mode()
m=Vector2
s=[m()]
v=1,0
f=m(v)
u=-1
j=50
while not event.get(256):
 h=s[u];d.fill(0);k=key.get_pressed()
 if k[K_w]:v=0,u
 if k[K_s]:v=0,1
 if k[K_a]:v=u,0
 if k[K_d]:v=1,0
 for b in s+[f]:draw.circle(d,"red",b*10+(4,4),4)
 s+=h+v,;q.flip();time.wait(99)
 if h==f:f.xy=r(j),r(j)
 else:_,*s=s

368 chars

quartz wave
ember vessel
#

why did u remove u=-1?

quartz wave
ember vessel
#

yes

#

there is

#

the u= is two chars

quartz wave
#
u=-1;uuu
-1-1-1
#

no benefit

#

semicolon is supposed to represent a newline

ember vessel
#

hmmmm

#

ur right

#

did u add any other changes?

quartz wave
ember vessel
#

?

quartz wave
#

removed j ```
j=50;jj
5050

ember vessel
#

ah

quartz wave
#

these ```diff

  • s=[m()]
  • s=m(),
  • ...for b in s+[f]...
  • ...for b in*s,f:...
ember vessel
#

357 chars!

from pygame import*
from random import*
r=randrange
t=display
d=t.set_mode()
m=Vector2
s=m(),
v=1,0
f=m(v)
while not event.get(256):
 h=s[-1];d.fill(0);k=key.get_pressed()
 if k[K_w]:v=0,-1
 if k[K_s]:v=0,1
 if k[K_a]:v=-1,0
 if k[K_d]:v=1,0
 for b in*s,f:draw.circle(d,99,b*10+(4,4),4)
 s+=h+v,;t.flip();time.wait(99)
 if h==f:f.xy=r(50),r(50)
 else:_,*s=s

#

this is low contrast mode

#

higher contrast takes one more character

#

use this to count chars

#

and click "include spaces"

finite blaze
quartz wave
finite blaze
#

thanks 👍

ember vessel
#

@quartz wave , i added some int he og version to make it look like nicer

#

but i can remove those

#

351 chars

from pygame import*
from random import*
r=randrange
t=display
d=t.set_mode()
m=Vector2
s=m(),
v=1,0
f=m(v)
while not event.get(256):
 h=s[-1];d.fill(0);k=key.get_pressed()
 if k[K_w]:v=0,-1
 if k[K_s]:v=0,1
 if k[K_a]:v=-1,0
 if k[K_d]:v=1,0
 for b in*s,f:draw.circle(d,255,b*9,4)
 s+=h+v,;t.flip();time.wait(99)
 if h==f:f.xy=r(50),r(50)
 else:_,*s=s
#

and this is high contrast

#

i can do 350

dreamy pier
#

changing key to integer -1

ember vessel
#

?

quartz wave
ember vessel
#

well

dreamy pier
#
from pygame import *
print(K_w, K_s, K_a, K_d)
119 115 97 100
ember vessel
#

low-contrast is pretty hard to see

dreamy pier
#

K_a can be 97

ember vessel
#

but ultra-low is impossible

ember vessel
ember vessel
quartz wave
#

playable and as low as possible

ember vessel
#

can you do that?

dreamy pier
#

sure

ember vessel
#

OMG

#

i can do white

#

and its high contrast

dreamy pier
ember vessel
#

@dreamy pier , i got it

ember vessel
#

it should still be snake

dreamy pier
#

Like i can make it shorter, but it will move only when pressed and can move diagonally 😄

ember vessel
#
from pygame import*
from random import*
r=randrange
t=display
d=t.set_mode()
m=Vector2
s=m(),
v=1,0
f=m(v)
while not event.get(256):
 h=s[-1];d.fill(0);k=key.get_pressed()
 if k[K_w]:v=0,-1
 if k[K_s]:v=0,1
 if k[97]:v=-1,0
 if k[K_d]:v=1,0
 for b in*s,f:draw.circle(d,-1,b*9,4)
 s+=h+v,;t.flip();time.wait(99)
 if h==f:f.xy=r(50),r(50)
 else:_,*s=s
#

349

#

my first draft was like 530

#

then on the pygame server, a bunch of ppl helped make it lower

ember vessel
#

thats not rlly snake

dreamy pier
#

actually diagonal moving looks very cool

#

but yeah

ember vessel
#

i can make the apple spawn in just a 9x9 grid for 2 less chars

#

but that's not fun

dreamy pier
#

choices -1

#
from pygame import*
from random import*
t=display
d=t.set_mode()
m=Vector2
s=m(),
v=1,0
f=m(v)
while not event.get(256):
 h=s[-1];d.fill(0);k=key.get_pressed()
 if k[K_w]:v=0,-1
 if k[K_s]:v=0,1
 if k[97]:v=-1,0
 if k[K_d]:v=1,0
 for b in*s,f:draw.circle(d,-1,b*9,4)
 s+=h+v,;t.flip();time.wait(99)
 if h==f:f.xy=choices(range(50),k=2)
 else:_,*s=s
ember vessel
#

isn't that longer

#

oh

dreamy pier
#

348

ember vessel
#

i see

#

yesss

#

now that its in full screen

#

lets up 50 to 99

#
from pygame import*
from random import*
t=display
d=t.set_mode()
m=Vector2
s=m(),
v=1,0
f=m(v)
while not event.get(256):
 h=s[-1];d.fill(0);k=key.get_pressed()
 if k[K_w]:v=0,-1
 if k[K_s]:v=0,1
 if k[97]:v=-1,0
 if k[K_d]:v=1,0
 for b in*s,f:draw.circle(d,-1,b*9,4)
 s+=h+v,;t.flip();time.wait(99)
 if h==f:f.xy=choices(range(99),k=2)
 else:_,*s=s
#

same chars

dreamy pier
#
from pygame import*
from random import*
t=display
d=t.set_mode()
m=Vector2
s=m(),
v=1,0
f=m(v)
while not event.get(256):
 h=s[-1];d.fill(0);k=key.get_pressed()
 if k[K_w]:v=0,-1
 if k[K_s]:v=0,1
 if k[97]:v=-1,0
 if k[K_d]:v=1,0
 for b in*s,f:draw.circle(d,-1,b*9,4)
 s+=h+v,;t.flip();time.wait(99)
 if h-f:_,*s=s
 else:f.xy=choices(range(99),k=2)

347

ember vessel
#

thats clever

#

the diff

quartz wave
ember vessel
#

WHAT

quartz wave
#

those question mark boxes are control characters

ember vessel
#

huh

quartz wave
#

technically valid as 1 byte since they're part of ASCII

ember vessel
#

explain what the exec is doing plz

#

and whered the keys go

quartz wave
ember vessel
#

but weird...

quartz wave
#

yeah

ember vessel
#

howd you do it

quartz wave
#

[K_s, K_w, K_a, K_d] is technically [*b'swad']

ember vessel
#

the k?

quartz wave
#

because there's a newline escape in there

dreamy pier
#

ah, ye, 331

ember vessel
#

if you want

#

cuz its rlly easy

quartz wave
ember vessel
#

oh, ok...

quartz wave
#

and a quick n easy way to get those is by doing b'swad'

#

if that is iterated over, it'll return the value of those keys

ember vessel
#

did u write that by hand?

quartz wave
#

yeah

#

well i had to do print('\2\2\1\3') n stuff but other than that yeah

ember vessel
#

k, thats rlly cool

#

(im posting all the codes that are being sent in the pygame discord, if you don't mind)

dreamy pier
#

191 then

exec(bytes('牦浯瀠杹浡⁥浩潰瑲ਪ牦浯爠湡潤浩潰瑲ਪ㵴楤灳慬੹㵤⹴敳彴潭敤⤨洊嘽捥潴㉲猊洽⤨ਬ㵶ⰱਰ㵦⡭⥶眊楨敬渠瑯攠敶瑮朮瑥㈨㘵㨩 㵨孳ㄭ㭝⹤楦汬〨㬩㵫敫⹹敧彴牰獥敳⡤㬩硥捥✨晩欠╛嵤瘺┽ⵤⰲ搥㈭湜⨧┴⨨❢ɳ眃Ăš搂ȃⰧ⤩ 潦⁲⁢湩猪昬携慲⹷楣捲敬搨⴬ⰱ⩢ⰹ⤴ ⭳栽瘫㬬⹴汦灩⤨琻浩⹥慷瑩㤨⤹ 晩栠昭强⨬㵳ੳ攠獬㩥⹦祸挽潨捩獥爨湡敧㤨⤹欬㈽
','u16')[2:])
quartz wave
#

191c

ember vessel
#

HUH

quartz wave
#

519b

dreamy pier
#

depends on what we do

ember vessel
#

you definetly generated that

dreamy pier
#

sure

ember vessel
#

ok, whoa

#

@quartz wave , is that where you leanred it?

quartz wave
ember vessel
#

this technique

quartz wave
#

from where?

ember vessel
quartz wave
#

no

#

the chinese character thingy is a common tool

ember vessel
#

i don't feel like these two should be counted though

#

cuz its not even python

quartz wave
#

used to generate the shortest character solutions

#

but they're very expensive in terms of bytes

ember vessel
quartz wave
#

so generating that results in a 519b, 191c solution

ember vessel
#

ok

quartz wave
# ember vessel its binary

341b, 341c using escapes only ```py
from pygame import*
from random import*
r=randrange
t=display
d=t.set_mode()
m=Vector2
s=m(),
v=1,0
f=m(v)
while not event.get(256):
h=s[-1];d.fill(0);k=key.get_pressed();exec('if k[%d]:v=%d-2,%d-2\n'4%(b's\2\3w\2\1a\1\2d\3\2',))
for b in
s,f:draw.circle(d,-1,b
9,4)
s+=h+v,;t.flip();time.wait(99)
if h==f:f.xy=r(50),r(50)
else:_,*s=s

ember vessel
#

still, its not even python

quartz wave
#

it is python

ember vessel
#

fine

#

but this is way to hacky

#

even for my standards

dreamy pier
#

xd

quartz wave
#

that's code golfing for you

ember vessel
#

lol, yeah i just started

#

so all those code golfing jams, does everyone just use the shortest-char thing

quartz wave
#

so usually bytes is counted

ember vessel
#

ok, yeah, same

quartz wave
#

turns out i didn't use the latest golfed version before the exec()
here's the 339b, 339c from the 347 ```py
from pygame import*
from random import*
t=display
d=t.set_mode()
m=Vector2
s=m(),
v=1,0
f=m(v)
while not event.get(256):
h=s[-1];d.fill(0);k=key.get_pressed();exec('if k[%d]:v=%d-2,%d-2\n'4%(b's\2\3w\2\1a\1\2d\3\2',))
for b in
s,f:draw.circle(d,-1,b
9,4)
s+=h+v,;t.flip();time.wait(99)
if h-f:_,*s=s
else:f.xy=choices(range(99),k=2)

#

338b, 338c py from pygame import* from random import* t=display d=t.set_mode() m=Vector2 s=m(), v=1,0 f=m(v) while[1]>event.get(256): h=s[-1];d.fill(0);k=key.get_pressed();exec('if k[%d]:v=%d-2,%d-2\n'*4%(*b's\2\3w\2\1a\1\2d\3\2',)) for b in*s,f:draw.circle(d,-1,b*9,4) s+=h+v,;t.flip();time.wait(99) if h-f:_,*s=s else:f.xy=choices(range(99),k=2) 330b, 330c ```py
from pygame import*
from random import*
t=display
d=t.set_mode()
m=Vector2
s=m(),
v=1,0
f=m(v)
while[1]>event.get(256):
h=s[-1];d.fill(0);k=key.get_pressed();exec('if k[%d]:v=%d-2,%d-2\n'4%(b'swad',))
for b in
s,f:draw.circle(d,-1,b
9,4)
s+=h+v,;t.flip();time.wait(99)
if h-f:_,*s=s
else:f.xy=choices(range(99),k=2)

#
- while not event.get(256):
+ while[1]>event.get(256):
ember vessel
#

i still kinda don't like this thing. Your right that it is python, but still

quartz wave
# ember vessel i still kinda don't like this thing. Your right that it is python, but still

picked up from the 347 n made it a 346 ```py
from pygame import*
from random import*
t=display
d=t.set_mode()
m=Vector2
s=m(),
v=1,0
f=m(v)
while[1]>event.get(256):
h=s[-1];d.fill(0);k=key.get_pressed()
if k[K_w]:v=0,-1
if k[K_s]:v=0,1
if k[97]:v=-1,0
if k[K_d]:v=1,0
for b ins,f:draw.circle(d,-1,b9,4)
s+=h+v,;t.flip();time.wait(99)
if h-f:_,*s=s
else:f.xy=choices(range(99),k=2)

#

if that's what you like

ember vessel
#

yes, good

#

i think that is where the challenge is

#

oh, thats good

proper vault
#

~~```py
from pygame import*
from random import*
t=display
d=t.set_mode()
m=Vector2
s=m(),
v=1,0
f=m(v)
while[1]>event.get(256):
h=s[-1];d.fill(0)
for u in key.get_pressed().values():v=dict(w=(0,-1),s=(0,1),a=(-1,0),d=(1,0)).get(u,v)
for b ins,f:draw.circle(d,-1,b9,4)
s+=h+v,;t.flip();time.wait(99)
if h-f:_,*s=s
else:f.xy=choices(range(99),k=2)

#

ah nvm, doesn't work

unreal echo
#

how do i make @night quarry execute a code that is too big to send here, when i paste it it just comes up at message.txt

#

whoops recursion error

#

didnt know cache could do that

fleet bridge
night quarryBOT
#

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

hello world
unreal echo
#

no i will not golf it

#

someone else can try that, but not me

fleet bridge
#

i am not talking about golfing

#

just compress your code

unreal echo
#

hm

#

maybe

#

hm still too big

fleet bridge
unreal echo
#

what

fleet bridge
#

you know this does literally nothing?

#

global x has no runtime effect

#

so it cannot raise exception

#
try:
    pass
except WtfError:
    ...
``` this is your code
unreal echo
#

whoops

#

its supposed to be try:__overloads__except:

fleet bridge
#

still does nothing, because __overloads__ is always defined

unreal echo
#

its supposed to be a failsafe in case a user tries to delete the overloads

#

so that it doesnt completely break

#

just removes previous overloads

fleet bridge
#

you shouldnt worry about that case

unreal echo
unreal echo
unreal echo
fleet bridge
calm elk
dreamy stone
#
from functools import partial
from typing import Iterable, Callable
class Seq:
    _seq = []
    chained = []
    def __init__(self, i: Iterable) -> None:
        self._seq = i
    def filter(self, func: Callable):
        self.chained.append(partial(filter, func))
        return self
    def map(self, func: Callable):
        self.chained.append(partial(map, func))
        return self
    def to_list(self):
        for func in self.chained:
            self._seq = func(self._seq)
        return list(self._seq)
def seq(i: Iterable):
    return Seq(i)
l = [1, 2, 3, "4", "a", "b", 7, "8"]
r = seq(l).map(lambda x: str(x)).filter(lambda x: x.isdigit()).to_list()
print(r)
#

I wish Python had something like this built in, or at least a way to chain generator functions without hurting your eyes.

dreamy stone
#

mutable defaults not even once

fleet bridge
dreamy stone
#

d'oh

wide crow
fleet bridge
wide crow
night quarryBOT
low lynx
#

there we go

wide crow
low lynx
#

yeah but I thought they might be interested regardless

wide crow
dreamy stone
#

that's a tight solution

#

the str functions are not important. they're just what I used for an example. yeah I could have just named the class lowercase, I was being specific about style guidelines.

dreamy stone
gleaming linden
restive void
rugged sparrow
#

!e ```py
from fishhook import hook

@hook.cls(list)
class list_hooks:
def map(self, func):
return list(map(func, self))

def filter(self, func):
return list(filter(func, self))

data = [1, 2, 3, '4', 'a', 'b', 7, '8']
f = lambda x: str(x)
g = lambda x: x.isdigit()
r = data.map(f).filter(g)
print(r)```

night quarryBOT
#

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

['1', '2', '3', '4', '7', '8']
pearl socket
#

!e

from fishhook import hook

@hook.cls(list)
class list_hooks:
  def map(self, func):
    return list(map(func, self))

  def filter(self, func):
    return list(filter(func, self))

data = [1, 2, 3, '4', 'a', 'b', 7, '8']
print(data.map(str).filter(str.isdigit))
night quarryBOT
#

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

['1', '2', '3', '4', '7', '8']
sonic birch
#

I see more and more fishhook used in this chat. The previous superhero here was einspect. Also somebody using ctypes directly to hook some system behaviour. Which way is better?

languid hare
#

the previous previous superhero was fishhook :p

#

i never learnt how to use einspect fully (sorry ionite)

fleet bridge
#

When type annotations and py.typed marker in fishhook?

restive void
#
from fishhook import hook

@hook
def map(self: list, func):
    ...

like that?

proper vault
#

The real og is forbidden fruit.

rugged sparrow
#

but fishhook and einspect are slightly different in how they work

#

(at least in regards to hooking, einspect has a ton of introspection features that i didnt add to fishhook)

#

and fishhook has fishhook.asm for hooking C functions that einspect doesnt (i think?) have

#

!e fishhook.asm lets you do stuff like this to leak internal values and other way more in-depth control flow modification (this code grabs a reference to the interned strings dict)```py
from fishhook.asm import hook
from ctypes import *

@hook(pythonapi.PyDict_SetDefault, restype=py_object, argtypes=[py_object]*3)
def setdefault(self, key, value):
if key == 'MAGICVAL':
return self
return pythonapi.PyDict_SetDefault(self, key, value)

pythonapi.PyUnicode_InternFromString.restype = py_object
interned = pythonapi.PyUnicode_InternFromString(b'MAGICVAL')
setdefault.unhook()
print(interned)

night quarryBOT
#

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

{'type': 'type', 'AttributeError': 'AttributeError', '__qualname__': '__qualname__', 'obj': 'obj', 'update': 'update', '__dict__': '__dict__', 'getattr': 'getattr', 'setattr': 'setattr', 'hasattr': 'hasattr', '__doc__': '__doc__', '__name__': '__name__', '__module__': '__module__', 'replace': 'replace', 'old': 'old', 'new': 'new', 'sys': 'sys', 'name': 'name', '_DeadlockError': '_DeadlockError', 'waiters': 'waiters', 'count': 'count', 'owner': 'owner', 'wakeup': 'wakeup', 'lock': 'lock', 'allocate_lock': 'allocate_lock', '_thread': '_thread', 'self': 'self', 'add': 'add', 'get': 'get', '_blocking_on': '_blocking_on', 'set': 'set', 'get_ident': 'get_ident', 'seen': 'seen', 'tid': 'tid', 'me': 'me', 'release': 'release', 'acquire': 'acquire', 'has_deadlock': 'has_deadlock', 'RuntimeError': 'RuntimeError', 'id': 'id', 'format': 'format', '__repr__': '__repr__', '__init__': '__init__', '_ModuleLock': '_ModuleLock', '_DummyModuleLock': '_DummyModuleLock', '_lock': '_lock', '_name': '_name',
... (truncated - too long)

Full output: https://paste.pythondiscord.com/T375LWEFNTIRUGVFC5BPRPNYIM

rugged sparrow
#

!e ```py
from fishhook.asm import hook
from ctypes import *

@hook(pythonapi.PyDict_SetDefault, restype=py_object, argtypes=[py_object]*3)
def setdefault(self, key, value):
if key == 'MAGICVAL':
return self
return pythonapi.PyDict_SetDefault(self, key, value)

pythonapi.PyUnicode_InternFromString.restype = py_object
interned = pythonapi.PyUnicode_InternFromString(b'MAGICVAL')
setdefault.unhook()
interned['chilaxan'] = 'foo'
print(eval("'chilaxan'"))```

night quarryBOT
#

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

foo
rugged sparrow
#

interned dict lets you muck around with some odd stuff

fleet bridge
rugged sparrow
#

but i also want to rewrite fishhook.asm to be able to give access to different registers and do stuff like instruction injection point matching

#

like ```py
@hook(pythonapi.Some_C_Function, before='pop rax;')
def injected(rax: py_object):
...
return Before('pop rax;', rax=rax) # this would be the default to make hooks happen inline, but having it dynamic like this would allow for really cool tricks

sonic birch
# wide crow Perhaps this is the kind of thing that you were trying to do. ```py class compos...

What about this?
!e

import sys
import builtins
from functools import partial as part
from collections import ChainMap

class arg:

  def __init__(self, data):
    self.data = data

  def __getattr__(self, key):
    f = ChainMap(builtins.__dict__, sys._getframe(1).f_globals)[key]
    return lambda *args, **kwargs: arg(part(f, *args, **kwargs)(self.data))

(
  arg([1,2,'3','4','b',5])
  .map(str)
  .filter(str.isdigit)
  .map(int)
  .list()
  .data
)

cc: @dreamy stone

astral rover
#

you need to put !e first

night quarryBOT
#

@astral rover :white_check_mark: Your 3.11 eval job has completed with return code 0.

[1, 2, 3, 4, 5]
dreamy stone
#

too readable

tough willow
#

Thats actually pretty useful

burnt gust
#

look at what i made 8 years ago when i was still sorta new to python

stats = '**-Stats for {} members-**\n'.format(message.server.member_count)+'\n'.join(['`{:.<6}{:.>17}`'.format(len([m for m in message.server.members if r in m.roles]), r.name) for r in sorted(message.server.roles, key=lambda role: role.position, reverse=True) if r != message.server.default_role])
wide crow
#

!e

from functools import partial

class arg(list):
    def __getattr__(self, key):
        f = vars(__builtins__)[key]
        return lambda *args: arg(partial(f, *args)(self))

a = [1,2,'3','4','b',5]
r = (
    arg(a)
    .map(str)
    .filter(str.isdigit)
    .map(int)
    )
print(r)
night quarryBOT
#

@wide crow :white_check_mark: Your 3.11 eval job has completed with return code 0.

[1, 2, 3, 4, 5]
sonic birch
#

Looks elegant! But it will not work with custom functions defined in the global scope. Also it will not be able to work with data other than sequences. But, yeah - it depends on use-case

UDP: I meant this will not be possible with your approach


def add_one(x): return x+1

arg('5.76').float().round().add_one().data
golden finch
#

I've been trying to teach myself a little bit of "functional" (or at least, as functions-as-objects as Python allows) stuff here and there, explicitly for the purposes of obfuscation, and I've hit what seems to me to be something vaguely interesting. It's certainly given me one hell of a headache - and I hope whoever tries to deobfuscate it gets one of a similar magnitude.

So I had the following:

def a(x):
    return lambda y:x

Straightforward enough...

So I was toying around, and I thought that the following would behave the same:

@lambda _b:lambda x:lambda y:_b(y)
def b(y):
    return x

That throws a NameError, for reasons I don't understand.
I then looked at the lambda y:_b(y) part, and realised that's redundant (it's just _b, obviously), so I rewrote it to be a bit more palatable, like so:

@lambda _b:lambda x:_b
def b(y):
    return x

However, that still throws a NameError (x is not defined). By my understanding, when the final version of b(n) is called, x=n, and in the scope of the "original" version, x should be defined. Evidently not, though.

Where's the mistake in my logic here, and any ideas on how I can fix it?

(the goal is to produce a decorator for the function b that makes it behave just like a)

fleet bridge
#

x in lambda args and x in finction are two independent variables.
So first x is unused, and second is used but never assigned, so it raises NameError

golden finch
#

tysm mate

mental vector
#

Does anyone have any interesting resources or articles/blog posts on writing polyglots for other languages in Python that you could share? The other language I'm targeting is C++, but any language would be interesting to read about. I'm just looking for interesting tricks you can use to twist the python syntax to work with other stuff. While anything would be useful, I want to try something other than the usual c/c++ polyglot method of just spamming #defines everywhere to make C++ syntax Pythonic, because I think it's a lot more challenging to make Python C++-like.

finite blaze
#

Hey, how would you return value in a custom language without using "return"?

#

I'm creating a small interpreted language

#

and i thought u might have some cool ideas

mental vector
#

Rust has it so that if a function ends in an expression instead of a statement (so, no semicolon), the expression is returned

finite blaze
#

thats boring ;p

fleet bridge