#esoteric-python
1 messages · Page 29 of 1
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
!e
T=int(input());r=i=1
while i<T:i+=1;r*=i
print(r)
@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
Oh, is that a new notice?
!e
import sys, io
sys.stdin = io.StringIO("foo")
print(input())
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
foo
!e probably because of ```py
raise EOFError("EOF when reading a line")
@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
yeah
Apparently at least 3months old
!e ```py
print('EOFError: EOF when reading a line')
import sys; sys.exit(1)
@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
Committed March 1st & merged on March 3rd https://github.com/python-discord/bot/pull/2422
!e
from posix import *
print(read(0, 11))
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
b''
Why? The only reason input() doesn't work is because there's no sys.stdin.
It's not a security thing or anything
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"))
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
it just returns EOF when read from
(which is why the read call returned 0 bytes)
!e py import sys print(sys.stdin)
@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'>
Fair enough
No readable stdin then
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)
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
thats true, and completely valid! but it still bothers me that the warnings are inconsistent
You can always raise it in #dev-contrib, but you'll probably just get the same response
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
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.
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
Yeah it makes sense
Although if the aim was to be precise as possible, EOFError already does that
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
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))
yep, that's right
see above
@timber grotto :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, world!
what does it do?
Print Hello world I assume 😄
also that definitely counts as esoteric
i am also confused about "not esoteric" 😄
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 ''))()
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
i posted this in general, but for adding and subtracting 1 to an int, you can do val = -~val and val = ~-val
yeag sounds right
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?
is this pyarmor
wrong channel, see #❓|how-to-get-help or go to a [correct] topic-specific channel
Does this work on all platforms? I believe older systems don't necessarily use 2s complement which is what this relies on, no?
https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types
The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits.
All implementations of python have to use 2s complement for bitwise operations, so yes
I see
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.
I think you also can do something like PyExecString("raise Exception") (i dont how this function is named exactly)
I managed to get an answer in #internals-and-peps. I just needed to add an explicit return NULL;
bro how do y'all obfuscate at this level bro
It got me to question my existence. DO I EVEN KNOW PYTHON?
Did you manually do it or was it automated with a tool?
Ola
no one knows python
there is always one more trick, one more standard library package, etc
Me saving hours just print("hello world")
I also think the more you obfuscate your code the faster it will be
No not really
is your name
uint64_t ?
also I think I saw someone
make that test
the more the code was obfuscated the faster it was
Thats not true in almost all cases
Obfuscation usually needs redundant code, so obfuscated code os not faster
if obfuscated code is faster it's probably not obfuscated for the sake of obfuscation
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
There are some microoptimization techniques that looks weird
i wouldn't call that obfuscation though
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...
import time
with open("file.py") as file:
text = file.read()
time.sleep(1 / len(text))
exec(text)
: D
(here should be some better formula because it will be too close to zero, but just as an example)
lmao
whats the point of time.sleep() here? just a bit confused
It makes code faster 😄
(by making it slower)
thank you for the help
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)
fluid simulation in less than 2kB
hi
!e ```py
import itertools
for _ in map(print, itertools.count()):
...
@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
i just wanted to share it with you
!e
@lambda _:_()
class print_:
__getattr__ = lambda __,_:print(_.replace('_',' ').title()+'!')
print_. hello_world
print_. i_am_cursed
print_. ᵃᵃᵃʳᵍʰ
@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!
!e
def echo():
print('Echo ...')
return echo
echo()() () () () () () () ()
@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 ...
!e
@lambda _:_()
def commented_out():
print(f'Hello, cursed World!')
# commented_out()
@strange basin :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, cursed World!
!e
@lambda _:_()
def not_commented_out():
print(f'Hello, cursed World!')
not_commented_out()
@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
!e
@lambda _:_()
def it_is_not_true():
print(f'Hello, cursed World!')
@dreamy pier :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, cursed World!
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())```
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello world!
!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())```
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello world!
weird doesn't work on my system
TypeError: BaseExceptionGroup.__new__() takes exactly 2 arguments (3 given)
By me
TypeError: 'bool' object is not callable
yeah, and the same error on 3.11
!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())
@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
!e
eval('BaseExceptionGroup')("¼", (object,), {"Q": (lambda _: print("Hello world!"))})().Q()
@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)
idk there should be type
but there is the baseexception
!e
type("¼", (object,), {"Q": (lambda _: print("Hello world!"))})().Q()
@dreamy pier :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello world!
Do you know any algorithm with O(N^0.5) time complexity?
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
I expected classic algorithm, not quantum algorithm...
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
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
!e ```py
@lambda :((),_)[1]
def what():
print("Hello chat")
what()
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Hello chat
002 | Hello chat
!e ```py
@lambda :()
def what():
print("Hello chat")
return _
what(what)(what)
@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
!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')))
@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
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))
[*iter((lambda:your_boolean_expression_here),0)]
is the [*iter...] necessary?
you said you wanted it in a list
no haha, a list comprehension
as like the iterator for it
[something for _ in iter((lambda:your_boolean_expression_here),0)]
[_ for _ in iter((lambda:your_boolean_expression_here),0)]
but yeah I worded that confusingly
but yeah this is correct
!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)""");
@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 :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'>
nice
!e ```py
import numpy as n
print(n.random.default_rng(0).integers(low=0, high=10, size=10))
@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]
!e ```py
import numpy as n
print(n.random.default_rng(0).random())
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
0.6369616873214543
i will eat a shoe
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
lgbt eshek
!e ```py
import numpy as n
n.random.seed(0);
print(n.random.rand())
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
0.5488135039273248
!e ```py
import numpy as n
n.random.seed(0);
print(n.random.choice("abc", 5))
@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
guh
!e ```py
import numpy as n
n.random.seed(0);
print(n.random.choice(list("abc"), 5))
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
['a' 'b' 'a' 'b' 'b']
!e ```py
import random
random.seed(56756)
print("".join(random.choices("abo olghwellrnopqhstud",k=11)))
@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
we can't help with it here
I posted this #software-architecture message in https://discord.com/channels/267624335836053506/782713858615017503 but I worry that this approach may be considered “esoteric” given how rare I've seen pumped-coroutine approaches in the wild. I am very curious to hear from people with experiece working with similar designs.
(For how rare the approach seems to be, it's quite pedestrian. It's also extremely effective in practice.)
>>> 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 meanlambda:...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=', ')
@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,
# 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
how enumerate is ajsldjaslkdjaskd
Why would you subclass enumerate?
oh wait I didn't read full context its about subclass
To add support for step
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
!e
def foo(argument):
print(argument)
if argument < 5:
@foo(argument + 1)
def bar(function):
return function
else:
def bar(function):
return function
return bar
@foo(0)
def test(): ...
@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
!e
foo = lambda a: (print(a), foo(a+1)(lambda f: f) if a < 5 else lambda f: f)[1]
@foo(0)
def test(): ...
@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
🛌
What's the best way (in 3.11 bytecode) to increment the 3rd value on the stack?
You'd want to use SWAP(3), LOAD_CONST(...), BINARY_OP(0), CACHE(0), SWAP(3) I think? Technically BINARY_OP_ADD_INT would be better, but that's a specialised opcode that probably wouldn't work if put directly in the code object. It should specialise to that quickly though. Also unsure if you need to add the cache entries yourself.
Right, I got that far, minus CACHE 0. What does that do?
Looking at the docs I can see it's some optimisation thing, and that certain opcodes expect to be followed by some number of caches. Is there a table of opcodes and the number of caches they need anywhere?
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...
doesnt matter
you can access it regardless
https://github.com/0x3C50/pyasm if you dont want to manually write cache entries
You can, but that might go away/change at any time, breaking your code and annoying the core devs...
Weird behaviour of dicts (in #internals-and-peps):
#internals-and-peps message
yes there is
opcode._inline_cache_entries
or dis._inline_cache_entries if you prefer that
Thanks!
that has to be accessed with the integer opcode because it's a list though
there's a problem with jumps here
it can't easily make a jump
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
https://leetcode.com/problems/partition-equal-subset-sum/
#algos-and-data-structs message
def canPartition(self, nums: List[int]) -> bool:
sm = sum(nums)
if sm & 1: return False
bits = 1
for x in nums: bits |= bits << x
return bool(bits & (1<<sm//2))
it's honestly a good idea
using an int for a dp table instead of a list
i'll borrow that
how to make seive of erastothenes function using lambda?
i wish that i were exellent in lambda
if you send here your "normal" code, i will try to turn it into lambda
!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))
@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]
@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]
@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]
That's cool
20
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?
How do you put a breakpoint in? If you insert breakpoint(), that will also apply to the copied function (because you also copy the call to breakpoint()).
In PyCharm
Oh, indeed, it works! It was some mess in the code. Thank you a lot
scary
mapping over discard is really neat
@digital mesa :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!e
print([i for i in range(2, 100) if all(i % j != 0 for j in range(2, int(i ** 0.5) + 1))])
@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]
!e
sieve=lambda n:[*[p:={*range(2,n)},[p:=p-{*range(i*i,n,i)}for i in[*p]],p][2]]
print(sieve(100))
@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]
!e ```py
sieve=lambda n:[(p:={range(2,n)}).difference([range(ii,n,i)for i in p])]
print(sieve(100))
@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]
or ```py
sieve=lambda n:[*[p:={*range(2,n)},[p:=p-{range(ii,n,i)}for i in p],p][2]]
oh yea, u can just iterate over p
now i wanted to see how it compares in ruby ```ruby
sieve=->(n){[t=2..n]-t.flat_map{[(_1*_1..n)%_1]}}
!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']);[];[];[];[];[];[];[];[];[];[];[];
@karmic pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello, shrek!
- wrong channel
- just
sudo apt install python3[or whatever the equivalent is if you're using windows]
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...)
cmon spamming an empty array isn't that based
cmd and powershell are comically outdated when it comes to literally anything. try to literally print "\🐍"
works on gnome term
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 😢
I am using the new shiny terminal too
but it runs powershell so I guess it's expected to have the same limitations
has nothing to do with python
it's an issue with windows stuff
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
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}
BTW this is also strange
~/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$
How is this related to this channel?
!e
code
What terminal is this?
You probably meant httpx
To get it to show the blue folder path I mean
the name’s in the message
Gnome terminal default looks like that?
if you want to know the name of the prompt, powerlevel10k via zsh
but the terminal is gnome terminal, yes
To get the blue folder thingy?
Is that a zsh theme?
yes
@cursive portal not an expert on this but each terminal in windows and linux implements its version of the emoji. So you can't rely on any terminal showing the same emoji or even supporting one at all.
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.
regarding the outdatedness of them on windows 10 you can resize windows width infinitely (try on discord), but in cmd, when i want to see a long mysql query output for example, it doesnt want to resize further than 1080px idk how it was related but felt like i gotta write it
!e ```py
d = dict(a=1, b=2, c=3, d=4)
print(*map(list, zip(*d.items())))
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
['a', 'b', 'c', 'd'] [1, 2, 3, 4]
!e ```py
d = dict(a=1, b=2, c=3, d=4)
print(*zip(*d.items()))
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
('a', 'b', 'c', 'd') (1, 2, 3, 4)
@mellow salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
!e ```py
print(f'{any([]) = }')
print(f'{all([]) = }')
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | any([]) = False
002 | all([]) = True
doesnt this break the contract
if all() is true, any() should as well
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
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 '))
I like that
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
!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 '))
@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
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)
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
to all ye maesteros
any way I could rewrite this in a single line ?
from requests.utils import default_headers
headers = default_headers()```
use __import__
headers = __import__('requests.utils').utils.default_headers()
not familiar with _import_, so I ask - why do we use utils twice ?
like why is utils apperaing twice in the code ?
....
the repl shows once is enough, but twice also works
Thanks anyway !
__import__('requests.utils') returns the same thing as __import__('requests')
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
agree
meh code tbh
!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())```
@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
!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()
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, world!
good now explain its working
its just an obfuscated version of hello world duh
i know but what it does
print hello world?
unobfuscate it
: )
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.
type(
__name__, (object,), {
"E": (lambda _: print("Hello, world!"))
})().E()
Scroll upwards from that
Thank you!
just creates a class with method E, which prints out "Hello, world!"
oh ok thx
imma use it
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
Any concept/impl of comptime evalutation in python?
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("\\\\", "\\")
!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("\\", "\")
@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
you need to escape the single quotes
wdym by escape
!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("\\", "\")
@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
!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("\\", "\")
@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
what is "escape"
\'
@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("\\", "\")
@kindred path :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!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("\\", "\")
@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
there's some const-folding in cpython
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
url to that if anyone cares https://github.com/exaloop/codon
!e
import numpy as np
print([1, np.array([1,2])].count(1))
@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()
aw
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).
!e assert 'o' == 'о'
@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
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())
@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
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)
Good guesses!
No builtins have been patched at all, the REPL is normal.
These really are two strings of length 5, each of their elements is a normal ASCII o.
Correct. No cheap tricks
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
Perhaps a hint:
Both x[1:] == y[1:] and x[:-1] == y[:-1] are true
i thought there was some cpython bug with zip() there but ig not
you have some invisible unicode character in these strings?
hmm
no, that would trigger ValueError
No, as I said: exactly 5 characters, each of them an ASCII o
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
cpython always adjusts a new string that's created
so that it always uses the least possible size
Correct!
how did you do that? ctypes stuff or just normal python?
ctypes stuff
ok, then it is not a bug 😄
Yeah, not a bug. But interesting behaviour :)
And you could make a z as well.
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
I just did x = 'ooſoo'; ctypes.c_byte.from_address(id(x) + 77).value = 0; ctypes.c_byte.from_address(id(x) + 76).value = 111.
>>> 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
i think you could do it like ctypes.c_ushort.from_address(id(x) + 76).value = 111
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
This is cool I will use in production thanks :))
@quartz wave
get_string = efrem_utils.get_validated_input()
💀 0.0.7 patch going crazy
nice
now make msg a normal argument ```diff
- def get_validated_input(*, msg: str | None = None, validators: ...
- def get_validated_input(msg: str | None = None, *, validators: ...
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
you can still pass it as a kwarg, its just not kwonly then
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
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
anyone got a cool idea i can try to work out in python?
!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))
@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
experimenting with functional stuff
!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))))
@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
ah thats why that was there
@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
the feeling when no x:-=1
x:--

@rigid knoll :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
!e ```py
print(1 in [1] == True)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
!e ```py
print(1 in [1]) # True
print(True == True) # True
print(1 in [1] == True) # False?
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | True
002 | True
003 | False
!e
code
!e
a=[],
try:
a[0]+=[42]
except Exception as e:
print(e)
print(a)
@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],)
It's even extra documented: https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works
!e [] = {}
@rigid knoll :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!e {} = []
@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 '='?
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
??
!e ```py
for _ in range(10):
{a, b} = 1, 2
print(a, b) # 1 2 or 2 1
@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 '='?
I know, i was just dreaming about this
The sad part here is that the variables within a dict have a defined order.
You can even use the dict as a stack with the popitem() function:
!e
print({1:1, 2:2}.popitem())
!e
() = [] = {}
@rigid knoll :warning: Your 3.11 eval job has completed with return code 0.
[No output]
Even the items in a set have a defined order, it's just not by insertion.
return requests.get(...).json()['key']doesnt work?
It returns the same as:
return requests.get(...).json()
I need to do this:
return x['key']```
Is there a more pythonic way of combining two different sequences into like a tuple than tuple(itertools.chain(first, second))?
You are in the wrong channel for this question, either #python-discussion or #1035199133436354600 would be better
(*a, *b)
is maybe more readable
can do the same with [*a, *b] for lists
(where a and b are arbitrary iterables)
Yeah I got this same thing on general and it blew my mind, when was this made possible?
python2?
damn, so it's just been something I never knew =D
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
Python Enhancement Proposals (PEPs)
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 😄
!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'))
@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')
!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'))
@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')
!e
chain = lambda *a: (*sum(([*x] for x in a),[]),)
print(chain())
print(chain([1,2],[3,4]))
print(chain('abcd','efg','h'))
@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')
!e ```py
f=lambda*a:sum(map(tuple,a),())
print(f())
print(f([1,2],[3,4]))
print(f('abcd','efg','h'))
@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')
!e
print(isinstance(True, bool))```
@wet fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | True
002 | True
float is misleading; True is not a float. It is an int, though, yes.
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=}")
@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
>>> 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))
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
123
it uses this character set: ().0123456789_abelostvy
it can execute arbitrary code
whats the lowest amount of characters to execute arbitrary code anyone has managed in python3? i've got 8
wdym with arbitrary code
any python program
py x
where x is file
or what
!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)
@lunar marsh :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
ah
then idk never did that
You likely found the minimum. There's a slightly different solution here: https://codegolf.stackexchange.com/a/250500
impressive
Hey, do you know any place (discord sever for example) where I can talk about C# golfing?
Or just golfing in general
There is esolangs server, maybe you also can talk about golfing there
I dont know if there is a server about golfing
Alright, thanks
This site has discord server
https://code.golf/
There is not a lot of talking but something
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='')))
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)
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)
instead of if(blah):break you can do while(blah):
that would save 2 lines
actually I don't need an else condition at all bc it breaks out of the loop
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)
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)
it would be !=
forgot about that
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)
only it i guess
f=open(0)
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(f.read(1)) while(s[i]): s '.split()['><+-.,['.find(o)]+'\n';i+=(92-ord(o))*(o in'][')
exec(c)
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)
stdout, sys.platform, sys.modules, sys.setrecursionlimit
and more
and sys.exit
oh
Pretty sure it was just used for stdin
open(0) should work, ye
i was confused a bit because the REPL didnt work with both
0 stdin
1 stdout
2 stderr
s=[0]*30000
while(p:=input()).lower()!='exit':
i,c=0,''
for o in p:c+=' '*i+'i+=1 i-=1 A=-~A%256 A=~-A%256 print(end=chrA) A=ord(open(0).read(1)) whileA: s '.split()['><+-.,['.find(o)]+'\n';i+=(92-ord(o))*(o in'][')
exec(c.replace('A','(s[i])'))
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
ah
i also have a version while trying to golf that reads per byte
@final iron?
huh
good good
takes up +2b though
Huh
Ye
it's actually +0b
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])'))
oh
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+=1 A-=1 print(end=chrA) A=f.read(1) whileA:# s '.split()[b'><+-.,['.find(o)]+';A%=256\n';i+=(92-o)*(o in b'][')
exec(c.replace('A','(s[i])'))
``` does this work?
not sure
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
huh that shouldn't happen
>>> open(0)
<_io.TextIOWrapper name=0 mode='r' encoding='utf-8'>
>>> ```
works in my machine
though what this code is?
¯_(ツ)_/¯
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.
your interpreter is having a stroke
Oh, you guys created brainfuck REPL? 😄
doesn't seems like it is a brainfuck repl
maybe it is
dunno
though why you are upside down? @fleet bridge
Idk. Some guy said me to change my avatar, so i turned it upside down
it is
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)
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)
im guessing food_related_values is your own file youre trying to import?
yeah, it's in the screenshot
Tried all kinds of data.processing.translate and processing.translate
sorry food_related_values
instead of translate
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?
that works
there ya go
what if I don't want it there 👀
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
When I try that I get attempted relative import with no known parent package
all those inits
for what
This is not a help channel, please continue discussion there, see #❓|how-to-get-help
all goods
ok sorry
no ideas either? 👀
try from server.config.data.food_related_values import FoodRelatedValues
idk

oh sht its kinda necropost xd
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
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
@narrow hound
>>> {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 :(
Damn
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)
Anything you only use once is not worth re-assigning (e.g. randrange)
example used 2 times
Oh, right
?
Nevermind, I somehow read the first r as a different letter
lol
381 ```py
from pygame import*
from random import*
r=randrange
d=display.set_mode((500,500))
m=Vector2
s=[m()]
v=1,0
f=m(1,1)
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,;display.flip();time.wait(99)
if h==f:f.xy=r(j),r(j)
else:_,*s=s
what did u change?
oh
the last line
huh
what does the do
it look invalid...but it works
the what?
else:_,*s=s
under scroe if for var assignment...
ohhhh
i get it
ur splitting s into two parts
why?
oh
It's just doing s.pop(0)
is that a way to pop the first element
yeah, got it
can it just be d.flip()?
wdym
!e
x = [1, 2, 3, 4]
_, *x = x
print(x)
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
[2, 3, 4]
nvm
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
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
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
And depending on the actual value of K_*, using the int directly might be shorter
wait, give me an example with the keypresses
I'm pretty sure K_w etc. are just ints
k is a sequence of bools, stating whether the key at that index is pressed. k.index(1) finds the first index where it's True.
ah
what if b is pressed
Undefined behavior? More critical would be the case where nothing is pressed :D
hmm true
Can add [1] to the list
ye, cuz the index isnt in the tuple
371 ```py
from pygame import*
from random import*
r=randrange
t=display
d=t.set_mode((500,500))
m=Vector2
s=m(),
v=1,0
f=m(1,1)
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 ins,f:draw.circle(d,"red",b10+(4,4),4)
s+=h+v,;t.flip();time.wait(99)
if h==f:f.xy=r(50),r(50)
else:_,*s=s
this does not work for whatever reason
handling the cases where no key is pressed
You'd need to do ...[(k+[1]).index(1)], plus add another case in the dict, but then it won't save any bytes anymore
you see i found a way to still get -3b
i think
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
even if that is done it still doesn't work
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
360 ```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()
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 ins,f:draw.circle(d,"red",b10+(4,4),4)
s+=h+v,;t.flip();time.wait(99)
if h==f:f.xy=r(50),r(50)
else:_,*s=s
why did u remove u=-1?
no benefit
sort of merged the 371 with the 368
?
removed j ```
j=50;jj
5050
ah
these ```diff
- s=[m()]
- s=m(),
- ...for b in s+[f]...
- ...for b in*s,f:...
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"
how did u color the text like that?
these ```diff
- s=[m()]
- s=m(),
- ...for b in s+[f]...- ...for b in*s,f:...
```
thanks 👍
@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
changing key to integer -1
?
ok get as low as you can
well
from pygame import *
print(K_w, K_s, K_a, K_d)
119 115 97 100
low-contrast is pretty hard to see
K_a can be 97
but ultra-low is impossible
so which one?
ahh
playable and as low as possible
can you do that?
sure
What are rules of moving? Keep them the same as they are here?
@dreamy pier , i got it
this is normal snake
it should still be snake
Like i can make it shorter, but it will move only when pressed and can move diagonally 😄
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
nah, don't do it
thats not rlly snake
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
348
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
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
331 ```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'swad',))
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)
WHAT
those question mark boxes are control characters
huh
technically valid as 1 byte since they're part of ASCII
just like this```py
if k[K_s]:v=0,1
if k[K_w]:v=0,-1
if k[97]:v=-1,0
if k[K_d]:v=1,0
but weird...
yeah
howd you do it
isn't that 330?
[K_s, K_w, K_a, K_d] is technically [*b'swad']
the k?
did you do len("""...""")
because there's a newline escape in there
ah, ye, 331
if you want
cuz its rlly easy
the keys correspond to their ascii equivalents
oh, ok...
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
did u write that by hand?
k, thats rlly cool
(im posting all the codes that are being sent in the pygame discord, if you don't mind)
191 then
exec(bytes('牦浯瀠杹浡浩潰瑲ਪ牦浯爠湡潤浩潰瑲ਪ㵴楤灳慬㵤敳彴潭敤⤨洊嘽捥潴㉲猊洽⤨ਬ㵶ⰱਰ㵦⡭⥶眊楨敬渠瑯攠敶瑮朮瑥㈨㘵㨩 㵨孳ㄭ㭝楦汬〨㬩㵫敫敧彴牰獥敳⡤㬩硥捥✨晩欠╛嵤瘺┽ⵤⰲ搥㈭湜⨧┴⨨❢ɳ眃Ăš搂ȃⰧ⤩ 潦湩猪昬携慲楣捲敬搨ⰱ⩢ⰹ⤴ ⭳栽瘫㬬汦灩⤨琻浩慷瑩㤨⤹ 晩栠昭强⨬㵳ੳ攠獬㩥祸挽潨捩獥爨湡敧㤨⤹欬㈽
','u16')[2:])
191c
HUH
519b
depends on what we do
you definetly generated that
learned what?
this technique
from where?
here
used to generate the shortest character solutions
but they're very expensive in terms of bytes
its binary
so generating that results in a 519b, 191c solution
ok
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 ins,f:draw.circle(d,-1,b9,4)
s+=h+v,;t.flip();time.wait(99)
if h==f:f.xy=r(50),r(50)
else:_,*s=s
still, its not even python
it is python
xd
that's code golfing for you
lol, yeah i just started
so all those code golfing jams, does everyone just use the shortest-char thing
no there are people who consider that cheating
so usually bytes is counted
ok, yeah, same
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 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)
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 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)
- while not event.get(256):
+ while[1]>event.get(256):
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
~~```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
overload decorator
https://paste.pythondiscord.com/TTBA
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
!e ```py
data = '789c2b28cacc2bd150cf48cdc9c95728cf2fca4951d704004ee30729'
import zlib
exec(zlib.decompress(bytes.fromhex(data)))
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
lmao
what
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
still does nothing, because __overloads__ is always defined
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
you shouldnt worry about that case
i did anyway
to be fair this could possibly run into a MemoryError if a gamma particle hits a bit in my memory at a specific time
KeyboardInterrupt is far more frequent than gamma particles
You must have heard the saying that “In Python everything is an object”. Let’s take that statement literally and test it.
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.
mutable defaults not even once
lambda x: str(x) is just str
lambda x: x.is_digit() is just str.is_digit
d'oh
What about this?
l = [1, 2, 3, "4", "a", "b", 7, "8"]
r = [*filter(str.isdigit, map(str, l))]
print(r)
Why do you have seq function that just instantiates Seq class? Just remove fjnction and rename class to seq
Or even this?
l = [1, 2, 3, "4", "a", "b", 7, "8"]
r = [s for x in l if (s := str(x)).isdigit()]
print(r)
!d iters
oh wait
!pypi iters
there we go
This fails on the "built-in" requirement.
yeah but I thought they might be interested regardless
Perhaps this is the kind of thing that you were trying to do.
class compose(list):
def map(self, func):
return compose(map(func, self))
def filter(self, func):
return compose(filter(func, self))
data = [1, 2, 3, '4', 'a', 'b', 7, '8']
f = lambda x: str(x)
g = lambda x: x.isdigit()
r = compose(data).map(f).filter(g)
print(r)
And then you can easily extend the class to include other features.
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.
Thanks!
I'm pretty sure there's something like using snake_case if the intended usecase is similar to a function in pep8
Yes:
However, know when to be inconsistent – sometimes style guide recommendations just aren’t applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best.
!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)```
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
['1', '2', '3', '4', '7', '8']
!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))
@pearl socket :white_check_mark: Your 3.11 eval job has completed with return code 0.
['1', '2', '3', '4', '7', '8']
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?
the previous previous superhero was fishhook :p
i never learnt how to use einspect fully (sorry ionite)
When type annotations and py.typed marker in fishhook?
from fishhook import hook
@hook
def map(self: list, func):
...
like that?
The real og is forbidden fruit.
i think the order was forbidden fruit, using ctypes directly, then fishhook, then einspect
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)
@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
!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'"))```
@rugged sparrow :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
foo
interned dict lets you muck around with some odd stuff
I am talking sbout type annotations in fishhook itself
when i have time to revamp it for 3.12 probably
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
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
Why it is not running?
you need to put !e first
@astral rover :white_check_mark: Your 3.11 eval job has completed with return code 0.
[1, 2, 3, 4, 5]
too readable
Thats actually pretty useful
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])
And after a little tidying up it becomes:
!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)
@wide crow :white_check_mark: Your 3.11 eval job has completed with return code 0.
[1, 2, 3, 4, 5]
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
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)
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
tysm mate
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.
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
Rust has it so that if a function ends in an expression instead of a statement (so, no semicolon), the expression is returned
thats boring ;p
A lot of other languages do the same