#esoteric-python
1 messages · Page 154 of 1
i mean- there's literally two loops that aren't needed here: ```py
for x in[1]]for x in[1]]
there's an assignment in the d function that doesn't get used: ```py
d=[];...;d=c.split('#')
this is more of an unobfuscation exercise than a golfing one
this obfuscated code makes me annoyed
oh wait
I'll actually test this after a coffee ```py
CLASSIFIED_STATE_SECRETS = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
def gen(s:int,k:int):a=map(int,str(s)),;return bytes(sum(map(lambda n,i:n**k+nk**i+ni,a,range(len(a)))))
def encode(normal_brainfuck:str):from random import randint;x=[normal_brainfuck];return int([{a:b for a,b in zip('+-<>.,[]',range(2,10))}.get(k,randint(0,1))for _ in iter(lambda:x,[])if randint(0,5)for k in[x.pop(0)]])
def decode(code:int):
c=str(code);p=t=i=0;o='';a=import('collections').defaultdict(int)
def add(i):a[i]+=1;a[i]%=256;return i,0
def sub(i):a[i]-=1;a[i]%=256;return i,0
def lft(i):return i-1,0
def rit(i):return i+1,0
def dot(i):return print(end=a[i],flush=1)or i,0
def com(i):a[i]=ord(import('sys').stdin.read(1));return i,0
def lop(i):return i,+(not a[i])
def end(i):return i,a[i]and-1
while 0<=p<len(c):i,t={x:y for x,y in zip(map(str,range(2,10)),(add,sub,lft,rit,dot,com,lop,end))}.get(c[p],lambda i:(i,0))(i)if t else(i,{'[':t+1,']':t-1}.get(c[p],t);p+=1-2t.lt(0))
return+(not p)
def encrypt(code:int,s:int,k:int=99899):#default k given as example
o=[];from random import randint;l=len(key:=gen(s,k=k));
for c in str(code):
i=randint(0,l)
while key[i]!=int(c):i-=1
o+=[i]
returno,
def decrypt(array,s:int,k:int=99899):key=gen(s,k=k);return int(''.join([str(key[i])for i in array]))
tests
mess = encrypt(encode(CLASSIFIED_STATE_SECRETS), 334456)
del CLASSIFIED_STATE_SECRETS
print(mess) # long confusing list of chonky integers
decode(decrypt(mess,334456,k=99899)) # hello world!
decode(decrypt(mess,546523,k=99899)) # ?
decode(decrypt(mess,334456,k=72746)) # ?
@bold root :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
004 | 5
005 | 8
006 | 13
007 | 21
008 | 34
009 | 55
010 | 89
011 | 144
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/utawidezop.txt?noredirect
does it start with 0,1,1?
yes
!e has bug i'll fix later ```py
import math
from random import*
o,r,m=ord,chr,choice
j,µ='ghijklmno',''.join
y=lambda n,l:[n,n-n//l*l or l][n>l]
z=lambda p,a:[r(Random(o(c)678).randint(457,875))for c in(pa)[:a]]
h=lambda d,c,:(o(d[]),o(c[y(+1,len(c))-1]),o(c[-1]))
def e(d,c):b=z(c,7);return µ(hex(o(i))[2:]+m(j)for i in µ(f'{x}{m(b)if random()>0.5else""}'for x in[r(sum(h(d,c,)))for _ in range(len(d))])).upper()[::-1][1:]+m('PQRSTUV')+f"{randint(137,975)}"
def d(a,b):
c=a[:a.find(a[-4])].lower();f=z(b,7)
for x in j:c=c.replace(x,'#')
g=[x for i in c.split('#')if(x:=r(int(i,16)))not in f];return µ(r((l:=h(g,b,_))[0]-l[1]-l[2])for _ in range(len(g)))
encrypted = e('https://github.com/3xq', 'komt#0005')
print(encrypted)
decrypted = d(encrypted, 'komt#0005')
print(decrypted)
@quartz wave :x: Your eval job has completed with return code 1.
001 | FE1HA11KA11IFE1H7DHFCHB02O7DG303N4DG8CK39GABJE11L8D2GA01G811G901M4D1O1DM303K49L49LB02IF9HBCH463M911L611LFE1I811N463K801P554
002 | Traceback (most recent call last):
003 | File "<string>", line 15, in <module>
004 | File "<string>", line 12, in d
005 | File "<string>", line 12, in <genexpr>
006 | ValueError: chr() arg not in range(0x110000)
it involves bitwise operations?
!e a=b=1;exec('print(b);a,b=a+b,a;'*30)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 1
003 | 2
004 | 3
005 | 5
006 | 8
007 | 13
008 | 21
009 | 34
010 | 55
011 | 89
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ucepeyapaz.txt?noredirect
it defo has something to do with
print(a);a,b=a+b,a;
don't tell me 0 is needed
lol
it is
!e print(0);a=b=1;exec('print(b);a,b=a+b,a;'*30)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 1
004 | 2
005 | 3
006 | 5
007 | 8
008 | 13
009 | 21
010 | 34
011 | 55
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/voxufediyo.txt?noredirect
needs to be 36 chars
a=0;b=1;exec('print(a);a,b=a+b,a;'*31)
this is where we are at right now
y is just ```py
y=lambda n,l:n%l or l
this doesnt reverse a 1 character string
but i already found a way to make that smaller yes
c=a[:-4].lower()[::-1]```
komt#0005 is my main discord but im at the 200 server limit so i had to use my alt to post my code
feel free to mess around with the uncompressed source
:^)
those are needed, using list comprehension allows me to compress forloops into 1 line which can let me put functions into 1 line
unless i am mistaken in some other way?
oops, forgot to remove that when i was debugging 😆
sorry for all the pings if i replied to your message, i forgot to turn off mentioning
When i saw the name of the channel, i thought i was ready to see what is in it... I now want to learn brainf*ck
well, py y=lambda n,l:[[n]if n<=l else[l if(n-(l*math.floor(n/l)))==0 else (n-(l*math.floor(n/l)))for x in[1]]for x in[1]][0][0] is equivalent to ```py
y=lambda n,l:n%l or l
Why should you want to learn that?
Imagine you leave your company:
Nobody can read that short code. It's totally useless for business.
lmfao was jk
Welp, yeh its useless
Ah, I thought that code was somewhere else im mistaken
😓
sure
for the fun of it
gonna take a break from golfing for today
it was more of unobfuscation but whatever
hm found something unexpected while reading through docs, apparently yield is an expression, unlike return, which is a statement
!e
def f():
x = yield 1
yield x
print(*f())
@languid hare :white_check_mark: Your eval job has completed with return code 0.
1 None
not too sure what the applications of this could be
👀
thats intresting
what about it
i'd think that's as good as it gets
Formerly, asyncio used this. It allows you to give the generator data back as it gives you values
Giving you coroutines
doesn't yield something return None?
hmm neat
!e
def f():
x = yield 1
yield x
gen = f()
print(next(gen))
gen.send("hello!")
print(next(gen))
@languid hare :x: Your eval job has completed with return code 1.
001 | 1
002 | Traceback (most recent call last):
003 | File "<string>", line 8, in <module>
004 | StopIteration
hmm wait
ah i see
so send acts like next, but also lets the yield evaluate to something
!e
def f():
x = yield 1
yield x
gen = f()
print(gen.send(None))
print(gen.send("hi!"))
@languid hare :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | hi!
@languid hare how would u shorten this
a=0;b=1;exec('print(a);a,b=a+b,a;'*31)
i dont see a direct way to shorten it other than to change to py 2, where exec is a statement
https://docs.python.org/3.12/whatsnew/3.12.html
Currently Python accepts numeric literals immediately followed by keywords, for example 0in x, 1or x, 0if 1else 2. It allows confusing and ambiguous expressions like [0x1for x in y] (which can be interpreted as [0x1 for x in y] or [0x1f or x in y]). A syntax warning is raised if the numeric literal is immediately followed by one of keywords and, else, for, if, in, is and or. In a future release it will be changed to a syntax error. (gh-87999)
pour one out for the golfers
in this case, would combo_string be considered a tuple? Also how can you solve this problem using .sort?
No, combo_string is a function. Also, off-topic for this channel, #❓|how-to-get-help
thanks n sorry
a=0;b=1;exec('print(a)a,b=a+b,a'*31)
I managed to shave off two characters
what can i use instead of exec, are there any builtins that do similar except from eval?
this doesnt work
It should I think?
it doesnt
That shaved 1 char and it doesn't error
Except for to many lines but y'know
that didnt shave of anything
Why are you using exec?
what else can we use?
I do not know, i was just curious.
What would be the goal of that entire line?
code
!e
a=0;b=1;exec('print(a);a,b=a+b,a;'*31)
@bold root :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 1
004 | 2
005 | 3
006 | 5
007 | 8
008 | 13
009 | 21
010 | 34
011 | 55
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/hewayuwanu.txt?noredirect
less*
sorry
does it have to start with 0
either way you can drop the trailing semicolon in the string
for 37
ya
u cant
hello, I had some confusion with decorators:
why do we need a wrapper function inside be_polite (first image)? can't we just return be_polite (second image)?
when I run the code in the second image, I am getting an error that says TypeError: be_polite() missing 1 required positional argument: 'fn'
def decorator(function):
# the decorator takes a function then we have an
# inner function which takes the params for the `function`.
def inner(*args, **kwargs):
# these *args **kwargs are the args that have to be passed in `function`
...
return function(*args, **kwargs)
return inner
@decorator
def foo():
...
# is the same as
def foo():
...
foo = decorator(foo)
# --------------------------
# when u call foo, what basically happens is
# decorator(foo)(...)
# because decorator return inner the function call is
# inner(...)
in the second case you would return fn directly
!e
def deco(fn):
print('inside decorator')
return fn
@deco
def foo():
print('inside foo')
foo()
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | inside decorator
002 | inside foo
if you want to ask questions about python open a help channel ( #❓|how-to-get-help ) or look for a topic channel which fits that topic
this channel has a different purpose
oh okay thank you
it's supposed to split using the -4th character and return the first result
!e forgot the [::-1] which caused a bug in my code
@pastel sparrow thanks for the tip ```py
import math
from random import*
o,r,m=ord,chr,choice
j,µ='ghijklmno',''.join
y=lambda n,l:n%l or l
z=lambda p,a:[r(Random(o(c)678).randint(457,875))for c in(pa)[:a]]
h=lambda d,c,:(o(d[]),o(c[y(+1,len(c))-1]),o(c[-1]))
def e(d,c):b=z(c,7);return µ(hex(o(i))[2:]+m(j)for i in µ(f'{x}{m(b)if random()>0.5else""}'for x in[r(sum(h(d,c,)))for _ in range(len(d))])).upper()[::-1][1:]+m('PQRSTUV')+f"{randint(137,975)}"
def d(a,b):
c=a[:a.find(a[-4])].lower()[::-1];f=z(b,7)
for x in j:c=c.replace(x,'#')
g=[x for i in c.split('#')if(x:=r(int(i,16)))not in f];return µ(r((l:=h(g,b,_))[0]-l[1]-l[2])for _ in range(len(g)))
exec("print(en:=e('https://github.com/3xq', 'komt#0005'), d(en, 'komt#0005'));"*5)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | A11LB02HA11L303O7DM8D2MFCN4D1M7DH4D1I4DO463N8CI303K39G4D1HABJ303IE11L4D1HA01I811J4D1J901O463I1DG49M49LF9JBCH911M611O811L303H801T844 https://github.com/3xq
002 | 4D1GA11MA11O7DH8D2IFCM463O7DJ4D1O4DH463N8CO39OFE1IABIE11O4D1MA01OFE1M811H901M463O1DM49O49JF9NBCL911G611NB02M811N801P723 https://github.com/3xq
003 | 4D1MA11JA11M303H7DHFCO7DNFE1L4DGFE1O8CM39MABK4D1IE11MA01N811H901H4D1J1DN49H49N303MF9IBCN303J911M611K4D1M811L8D2H801U465 https://github.com/3xq
004 | A11K463GA11N4D1M7DIFCM4D1O7DG4DOB02H8CN39OABL4D1GE11G463JA01I4D1H811JB02N901J1DH49J49O303OF9OFE1NBCM911J611O811G8D2M801V315 https://github.com/3xq
005 | A11K8D2IA11J463K7DNFCH7DJB02G4DK8CH39GABN8D2OE11K4D1GA01N811J463O901I303H1DL49K463I49G463HF9JBCLB02H911H611MFE1G811NFE1G801V484 https://github.com/3xq
niceee
im not too big on minifying code so i tried my best atleast
it would run slow as heck lmao
oop meant to reply to this one
yeah it would be awesome though
Would be really hard though, I remember needing to disable the standard library with rust to make a simple kernel, and with C I had to not use any of the standard library (following some guides) would python even be able to emulate VGA without that?
35 chars in python 2.
a=0;b=1
exec'print a;a,b=a+b,a;'*31
I can't get below 38 in python 3. =/
a=0;b=1
exec('print(a);a,b=a+b,a;'*31)
https://code.golf/fibonacci#python
39 chars with a while loop:
a,b=0,1
while b<9**6:print(a);a,b=a+b,a
Are you sure this hint works in the version they're using now? Does the key lie in using xor? I'm out of ideas on this I'm afraid. I feel like this is either you know the trick or you don't, and it's not the sort of thing you figure out.
it's not esoteric at all
it works in the current version
i mean you can see me on the leaderboard, it doesn't keep solutions that only worked in the past
is some kind of loop needed
this is the only thing I can think of, using the hint
a=b=1
exec('print(a-b);a,b=a+b,a;'*31)
Can get to 36, but then the sequence starts at 1 1 and not 0 1 ://
a=b=1;exec('print(a);a,b=a+b,a;'*29) - this is 36, but it starts with 1 2
tbf, the whole exec*number is pretty esoteric to begin with. But I'm not seeing how to make it shorter any other way. But glad to know that there is a current valid solution.
ok, I got down to 37.
ok, I got it to 36
where is this learderboard from?
From the problem we've been working on: https://code.golf/fibonacci#python
oh, thanks
ok got it as well
nice!
I failed at golf, but I had fun with this one:
from fishhook import *
@hook(list)
def __iadd__(s,o):return [v+(o if i else 0) for i,v in enumerate(s) ]
@hook(list)
def p(s):
print((r:=s.pop(0)))
return r
a=[0]+[1]*30
while a:a+=a.p()```
I kind of want the last statement line to read `a[1:]+=a.p()` but that requires an entire new listview class which I don't feel like implementing already.
isn't o if i else 0 just i and o
what about u and i?


a mild refactor ```py
from fishhook import*;hook(list,'iadd')(lambda s,i:[v+(u and i)for u,v in enumerate(s)]);hook(list,'k')(lambda k:print(r:=k.pop(0))or r);o=[0]+[1]*30
for _ in o[1:]:o+=o.k()
In today's challenge, we are going to do this that happened in #ot0-psvm’s-eternal-disapproval
okay that wasn't as easy as i thought it was going to be
!e ```py
from ctypes import*
obase = py_object.from_address(id('2')+8)
class Magic(str):
def add(self, other):return class(int(self)+int(other))
obase.value = Magic
print( '2' + '20' )
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
220
!e
from fishhook import hook, orig
@hook(str)
def __add__(self, other):
try:
out = str(int(self) + int(other))
return out
except ValueError:
return orig(self, other)
print('1' + '101')
print('a' + 'b')
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | 1101
002 | ab
bruh
thats the problem sadge 😔
I'm not sure I can work around that... unless...
eh, unreversable damage it is then
!e
import dis
dis.dis("1" + "2" * 1)
@languid hare :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (12)
002 | 2 RETURN_VALUE
bested again
woah
python cannot defeat meeeeeee
wait I put the \0 on the wrong side
!e ```py
from ctypes import c_char
cbase = (c_char*3).from_address(id('220')+48)
cbase.value = b'22\0'
print('2'+'20')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
22�
that looks better
ur manually rerouting 220 str literal right?
yep, probably deleting '220' itself in the process
!e ```py
from ctypes import c_char
cbase = (c_char52).from_address(id('220'))
backup = cbase,
obase = ((c_char51).from_address(id('22')),)+(b'\0',)
cbase.value = b''.join(obase)
print('2'+'20')
cbase.value = b''.join(backup)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
22
I can just temporarily replace '220' with '22' when it suits me.
ic
the previous one still had a trailing NUL character
this one also overrode object size I couldn't quite figure out which part of memory was the 52 that i was looking for so I just patched the whole number
!e
import dis
dis.dis("1" + "2" * (1-1))
@languid hare :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (1)
002 | 2 RETURN_VALUE
!e ```py
import dis
def f():
'1'+('1'+('1'+('1'+'1')))*(1-----------1)*0
dis.dis(f)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 3 0 LOAD_CONST 1 ('1')
002 | 2 POP_TOP
003 | 4 LOAD_CONST 0 (None)
004 | 6 RETURN_VALUE
!e
import dis
dis.dis("(lambda: '1')()")
@languid hare :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (<code object <lambda> at 0x7f27f9d9d420, file "<dis>", line 1>)
002 | 2 LOAD_CONST 1 ('<lambda>')
003 | 4 MAKE_FUNCTION 0
004 | 6 CALL_FUNCTION 0
005 | 8 RETURN_VALUE
006 |
007 | Disassembly of <code object <lambda> at 0x7f27f9d9d420, file "<dis>", line 1>:
008 | 1 0 LOAD_CONST 1 ('1')
009 | 2 RETURN_VALUE
!e ```py
import dis
dis.dis("(lambda: '1'+('1'+('1'+('1'+'1')))*(1-----------1)*0)()")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (<code object <lambda> at 0x7f086ee2d420, file "<dis>", line 1>)
002 | 2 LOAD_CONST 1 ('<lambda>')
003 | 4 MAKE_FUNCTION 0
004 | 6 CALL_FUNCTION 0
005 | 8 RETURN_VALUE
006 |
007 | Disassembly of <code object <lambda> at 0x7f086ee2d420, file "<dis>", line 1>:
008 | 1 0 LOAD_CONST 1 ('1')
009 | 2 RETURN_VALUE
brehhhhh
!e
import dis
dis.dis("'1' * (not 0)")
@languid hare :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 ('1')
002 | 2 RETURN_VALUE
really
compiler doing half the mathematical work
!e ```py
import dis
dis.dis("256**256+1")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (256)
002 | 2 LOAD_CONST 0 (256)
003 | 4 BINARY_POWER
004 | 6 LOAD_CONST 1 (1)
005 | 8 BINARY_ADD
006 | 10 RETURN_VALUE
it is strong, but it is not immortal
a NameError occurs
u and i is just not meant to be...
!e import('ctypes').c_int.from_address(id(4)+int.basicsize).value=5
print(f"{2+2=}")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
2+2=5
won't work for exec mode but will work for the REPL
ya
what if I used 100% of my cpu?
that's where the limits are defined
15**32 is the (integer) power operation with the biggest result that is still optimized out
no numbers are bigger than that
a string of length 4096 is the largest possible result of string multiplication
reminds me of the lazy calculator implementation i did with compile
i just compiled user input and grabbed the first constant
no wonder it failed with large inputs
!e
import this
print('something')
@split violet :white_check_mark: Your eval job has completed with return code 0.
001 | The Zen of Python, by Tim Peters
002 |
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/giboqelura.txt?noredirect
Hey, I am trying to solve one ctf but i need some help.
So i need to write a code that will output whats inside flag file. This code will be later compiled using ast and it wont run if compiled code containst ast.Import/ast.ImportFrom/ast.Call
any ideas how to obfuscate code so it wont include any call "nodes" (not sure whats a good word for it)
i tried [e for e in list(open('flag'))]
cuz [1,2] worked
so i thought that list comprehensions would work
!e ```py
@print
@lambda x: x.name
class HelloWorld: ...
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
HelloWorld
!e ```py
@import
@lambda x: x.name
class sys: ...
print(sys)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
<module 'sys' (built-in)>
!e ```py
import dis
dis.dis("""@import
@lambda x: x.name
class sys: ...""")
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (__import__)
002 |
003 | 2 2 LOAD_CONST 0 (<code object <lambda> at 0x7f690b0f1420, file "<dis>", line 2>)
004 | 4 LOAD_CONST 1 ('<lambda>')
005 | 6 MAKE_FUNCTION 0
006 |
007 | 3 8 LOAD_BUILD_CLASS
008 | 10 LOAD_CONST 2 (<code object sys at 0x7f690b0f14d0, file "<dis>", line 1>)
009 | 12 LOAD_CONST 3 ('sys')
010 | 14 MAKE_FUNCTION 0
011 | 16 LOAD_CONST 3 ('sys')
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/iduricorow.txt?noredirect
no call_function :>
it doesn't use import, it uses __import__, which in the ast is just a name
!e
@eval
@lambda x: x.x
class x:
x = "print('Hello World')"
@restive void :white_check_mark: Your eval job has completed with return code 0.
Hello World
Then just put your code inside that string
!e ```py
@print
@lambda x:"Hello World!"
class _:0
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
No import, no brackets, no eval, no shenanigans
I made green matrix rain with multiprocessing so that i can use more than one core of the cpu. No threading cos threads suck in python.
It needs two files though because pickles.
here's a snapshot.
However in development it was rather unstable, it has to be keyboard interrupted before it is closed else you get infinite error msgboxes with [ok] button
"Program did not start correctly, press ok to close the program" [OK]
but it's infinite.
you have to individually terminate all the children processes, and even then, you still have to close or ok the boxes
This is an interesting test of whether you understand what a decorator is.... 🙂
>>> @print
... @str.upper
... @lambda c: c.__doc__
... class Whatever:
... """Hello, world!"""
HELLO, WORLD!
!e ```py
@print
@vars(type)["doc"].get
class _:"Hello Word!"
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
Hello Word!
that one is too weird for me 🙂
@print
@str.title
@lambda cls: cls.__doc__
class _:
"""hello, world!"""
Hello, World!
I've been trying for a while to get the original challenge of "print the contents of a file" (without eval) working, but I'm stuck at finding something that calls its first argument without parameters.
what is the challenge?
@print
@lambda x:x.read
@open
@lambda x:"flag"
class _:0
After the @print I need something that calls the current callable.
this looks cool
Print contents of a file called "flag" without using import statements or calling a callable (directly). Easy when eval is allowed.
See above, original challenge by @finite blaze yesterday
why can't you call read directly?
Basically the AST isn't allowed to contain a Call node
oh wait, i didnt read the whole thing, mb
@[type of callable].__call__
@print
@print.__class__.__call__
@lambda x:x.read
@open
@lambda x:"flag"
class _:0
Yes, was struggling with that for a while. This works.
woah
!e
import this
print('something')
@true narwhal :white_check_mark: Your eval job has completed with return code 0.
001 | The Zen of Python, by Tim Peters
002 |
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/acebacoxos.txt?noredirect
WTF
!e py print(round((type|type.__class__)(type).__or__(type(7),type(69)).__sub__(21,90).__mul__(-1000).__divmod__(3)[0]*3+1/54.76190476190476*(type|type.__class__)(type).__or__(type(7),type(69)).__sub__(21,90).__mul__(-1000).__divmod__(3)[0]))
@split salmon :white_check_mark: Your eval job has completed with return code 0.
69420
!e
import this
@forest beacon :white_check_mark: Your eval job has completed with return code 0.
001 | The Zen of Python, by Tim Peters
002 |
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/wugajuhuya.txt?noredirect
I want to tweet this, who should I give credit to?
@print
@str.title
@lambda cls: cls.__doc__
class _:
"""hello, world!"""
(I adapted it from other examples here)
that's been around for longer than just the last few days; I saw something similar on the esolangs discord a few months ago
!e
#from esolangs Discord
@print
@str.title
@lambda _:"hello, world!"
class _:0
@golden finch :white_check_mark: Your eval job has completed with return code 0.
Hello, World!
What does the 0 do?
nothing, it's just the required but discarded body of the class
pass but shorter
pass is redundant cos you can just 0 for the same effect.
or the cuter ...
!e noops can be made from anything, really. ```py
*map(....eq,map(str,iter(lambda:print('Hello, World!'),None))),
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello, World!
also, thins after @ like @print, @str.title, what are they called?
decorators
the whole line is called a decorator
wait, is it without calls?
isnt iter a call?
oh yeah it is 😄
I'm mapping no-ops against a delayed instruction
!e ```py
def f(n=[4]):
print(n[0])
n[0]-=1
return n[0]
o = map(str,iter(f,0))
print(5)
*o,
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 5
002 | 4
003 | 3
004 | 2
005 | 1
*o,, whats this , doing here?
to prevent starred expression can't be used here
if there's a trailing comma, then the expression is implicitly in a 1-tuple
brackets are optional if there's no need for precedence
!e that includes tuple construction, hence
a = (0,)
b = 0,
print(a, b, a==b)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
(0,) (0,) True
That's beautiful, have never seen the *o, thing to exhaust the iterable.
Do you have a name for this "operator"?
tuple(varname)
*o, looks like a cheerleader
It reminds me of the pistol-operator for unpacking a one-element iterable (,=)
*_, is how I most often use it.
headless cheerleader
a1 = *map(f,a0),
alternatively, I could "reverse times-equals with trailing comma"
a1 =* map(f,a0),
just to be subtly confusing
a ,=* map(f, b),
b would have to have a length of 1
Yes
so a ,=* map(f, [b]),
a ,= *o, < pistol operator killing a cheerleader operator
FBI,= *o,
FBI, open up!
the cheerleader has a weapon!
!e if you really wanna do cheerleaders
W, I, L, D, C, A, T, S = 'WILDCATS'
name = *W, *I, *L, *D, *C, *A, *T, *S, '!'
print("What is our name?", ''.join(name))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
What is our name? WILDCATS!
sometimes they have the letters of their team name on their shirt.
haha, perfect ❤️
I wonder why there is this class
I guess cuz we are using decorators
And we need to modify something?
yes, it could also be an arbitrary function
is there a way to use def to define a function without ()
like def foo instead of def foo()
no.
rip
@exec
@input
class X:0
class X():
def __init__(self, a, b, c, d, e):
self += "print(open('flag').read())"
__iadd__ = eval
__builtins__.__import__ = X
I've been playing with somethine like this
f"""{"exec('print(1)')"}"""
but can't get this to work
!e like that?
f"""{exec("print(1)")}"""
@restive void :white_check_mark: Your eval job has completed with return code 0.
1
I think there is no way to make a shorter solution that this one
!e
@exec
@lambda x:print.__name__ + f'({x.__doc__!r})'
class _:
'hello world'
@wheat river :white_check_mark: Your eval job has completed with return code 0.
hello world
os.environ.__class__.__contains__ = os.system
'cat flag' in os.environ
has anyone figured out extending generics yet? e.g. List[T] and ImmutableList[T] extending List[T]
If you add Generic[T] and List[T] as children, pycharm won't use the type passed to the child class as the parent class type
If you just extend the raw class (i.e. List instead of List[T]) it complains ImmutableList isn't a generic class...
Check this shiz out
zip(* [iter(seq)] * n)
is a funky way to chunk seq into n-size chunks
!e ```py
bytes_ = [5, 2, 4, 3, 4, 5, 6, 63, 2, 1, 23, 3, 54, 3, 2, 3]
print(list(zip(* [iter(bytes_)] * 8)))
@drowsy cobalt :white_check_mark: Your eval job has completed with return code 0.
[(5, 2, 4, 3, 4, 5, 6, 63), (2, 1, 23, 3, 54, 3, 2, 3)]
It's specifically using the fact that [item] * n will duplicate the item reference n times, you know, that thing you usually tell beginners they have to avoid
aha
so that the n duplicates of the iterator get used as one each time as zip tries to fill out each chunk
that is very funky
Hi, is this a good forum to ask questions on django too ?
yes, ask from #❓|how-to-get-help or in #web-development
not in this channel, you can use the ones ivo linked
I found that in a solution from https://www.codewars.com/kata/5ef9ca8b76be6d001d5e1c3e/python
love it, time to add chunker=lambda s,w:zip(*w*[iter(s)]) to the list of snippets that Definitely should be in the standard library
(it's the *w* operator indexed by iter(s), duh)
they've written down "grouper" in a recipes section of itertools
https://docs.python.org/3/library/itertools.html#itertools-recipes
i guess that's quite similar
It's not the same without the *w* 
It's also mentioned in the documentation for the zip function
heh, cool
are some of those recipes new
dont remember seeing the dotproduct or convolve before
What's this called, the double cheerleader operator?
def grouper(iterable: Iterable[Any], chunksize: int) -> Iterator[Tuple[Optional[Any], Optional[Any]]:
"""
Group iterable into n-sized chunks
Returns an iterator of n-length tuples until the input iterable is exhausted
"""
it = iter(iterable)
return iter(lambda: tuple(islice(it, n)), ())
iter accepts a callable and sentinel value
What does islice do? I didn't know there was a lice type in python
No I know, it was a joke
islice looks like is lice
sliceobj = slice(1,10,5)
assert sequence[slice] == sequence[1:10:5] # returns True
islice is basically an iterator based on sequence slicing
islice checks if an object is of type lice /j
def islice(obj: Any) -> bool:
return isinstance(obj, lice)
!e
eval((lambda:0).__code__.replace(co_code=b't\x00\x82\x01', co_names=([*__builtins__.__dict__][87],)))
raise ValueError
@dry mirage :warning: Your eval job has completed with return code 0.
[No output]
bro what is this channel
It's about esoteric-ness with Python
The best channel in the server
!e ```py
eval((lambda:0).code.replace(co_code=b'e\x00\x82\x01', co_names=([*builtins.dict][87],)))
raise ValueError
@quartz wave :warning: Your eval job has completed with return code 0.
[No output]
hmm
:)
if you use t in the REPL it doesn't do anything but e does
super cryptic version of exit(0)
doesn't do that in the REPL
oh really?
e raises and t just returns ArithmeticError
because you're probably on 3.10 or something else
does work in <=3.10 but not 3.11+
isn't the bytecode hardcoded
wait
the errors are different
!e
eval((lambda:0).__code__.replace(co_code=b'LOAD_FAST'))
@dry mirage :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
what does that do for you
SystemExit is the 88th element in __builtins__.__dict__ in 3.10 but in 3.11 it's ArithmeticError
oh interesting 
>>> eval((lambda:0).__code__.replace(co_code=b'LOAD_FAST'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: code: co_code is malformed
oh wat
no more hacking cocode for seg faults

eval((lambda:0).__code__.replace(co_code=b'1'))?
bytecode length has to be divisible by 2
else that error occurs
i like it
i don't have to worry about segfaulting my stuff
b'10' segfaults it though
oh nice
ASCII 1 is apparently WITH_EXCEPT_START
b'00' also segfaults it
tbh is a language even turing-complete if you can't segfault it
according to opcode.opname ASCII 0 is nothing
according to dis._all_opname ASCII 0 is LOAD_GLOBAL_BUILTIN
you cant segfault brainfuck
!e
class Foo:
def foo(self):
return 1
a = type('',(Foo,),{'foo':lambda x:super().foo()})
a().foo()
why doesn't this work?
@wheat river :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 6, in <module>
003 | File "<string>", line 5, in <lambda>
004 | RuntimeError: super(): __class__ cell not found
!e
class X:
def f(self):
print(__class__)
X().f()
print(X.f.__closure__)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | <class '__main__.X'>
002 | (<cell at 0x7fb890b3da20: type object at 0x563756977530>,)
no argument super only works in a class body
0-arg super use this cell to determine class where your method is defined
super(a) maybe
Depends how much memory you allocate to brainfuck. If it goes out of bounds then yeah access violation
!e And unsafe python is easy in any 3.x version just
def print(*a):
try:print(*a)
except:print("unable to print duhhh")
print("Hello, World!")
ah k 👍
@floral meteor :warning: Your eval job timed out or ran out of memory.
[No output]
Don't need ctypes or bytecode mutation
!e
class Foo:
def foo(self):
return 1
a = type('a', (Foo,), {'foo': lambda x: print(super(a))})
a().foo()
@wheat river :white_check_mark: Your eval job has completed with return code 0.
<super: <class 'a'>, NULL>
not even "unsafe"
it's just forever recursing
!e Can anyone explain this code ?```py
print([chr(0x48656c6c6f20776f726c642120>>i8&255)for i in range(103//8+1)][::-1],sep="")
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
Hello world!
!e ```py
n = 0x48656c6c6f20776f726c642120
print(n.to_bytes(13, 'big'))
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
b'Hello world! '
@umbral prism the integer encodes a sequence of bytes which are selected one at a time with the >>
not forever, it stack overflows
although multiprocessing module can arise some juicy problems that need task manager
I've recently got into trying out ASCIIDots, and I now know that there's a package (asciidots) where I can make programs on this language. How do I use Python to make ASCIIDots programs?
!e
# fibonacci sequence :D
print((lambda n:([(a:=0, b:=1)] + [(a:=a+b, b:=a+b) for i in range(n//2)])[(n-1 if n%2 == 0 else n)//2][1 if n%2 == 0 else 0])(69))
@versed eagle :white_check_mark: Your eval job has completed with return code 0.
72723460248141
someone got it down to 36 chars recently
a=0;b=1
exec('print(a);a,b=a+b,a;'*31)```
a,b=0,1;exec('print(a);a,b=a+b,a;'*31)
!e
a,b=0,1;exec('print(a);a,b=a+b,a;'*31)
@finite blaze :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 1
004 | 2
005 | 3
006 | 5
007 | 8
008 | 13
009 | 21
010 | 34
011 | 55
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/segifiyilo.txt?noredirect
aha i gave python a stroke
I can't get over python having a stroke 🤣
this is what I expect from python properly crashing: confusing red text everywhere and it's too dead to raise a crash flag and just remains in a limbo that cannot be keyboardinterrupted
!e Thue–Morse on stack
n = 5
s: list[int] = []
i1 = s.append
i2 = s.pop
i3 = lambda: [*map(i1, [i2(), i2()])]
s1 = lambda: s[-1]
s2 = lambda: s[-2]
g = lambda: i1(s[-i2()])
p = lambda: (a:=i2(), x:=i2(), s.__setitem__(slice(None),[*s[:-a],x,*s[-a:]]))
r = lambda: i1(1 - i2())
d = lambda: (i1(t:=i2()), i1(t))
i1(0)
i1(n)
i1(1)
while s2():
i1(0)
while s1() < s2():
i3()
d()
i1(i2() + 3)
g()
r()
i1(3)
p()
i3()
i1(i2() + 1)
i2()
i1(i2() * 2)
i3()
i1(i2() - 1)
i3()
i2()
i2()
print(s)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
[0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1]
!e not crypted code
n = 5
s: list[int] = []
i1 = s.append
i2 = s.pop
i1(0)
n = 5
ln = 1
while n:
x = 0
while x < ln:
i1(1 - s[-ln])
x += 1
ln *= 2
n -= 1
print(s)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
[0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1]
noice. what is it?
it does that in <=3.9 but in 3.10+ it's just forever recursing
that's why it times out in the python bot
does this in an online 3.9 compiler
__add__ vs __iadd__
- vs +=
__add__ creates a new list, __iadd__ doesn't
!e
import sys;import time;_,__,___,____=print,sys.stdout,time.sleep,lambda _:''.__getattribute__(f'{chr(106)}{chr(111)}{chr(105)}{chr(110)}')([chr(__) for __ in _]);_____,______,_______=____([102,108,117,115,104]),____([119,114,105,116,101]),____([78,111,32,98,105,116,99,104,101,115,63]);_________=lambda _:[(__.__getattribute__(______)(_________),__.__getattribute__(_____)(),___(1/10)) for _________ in _];_________(_______)
@wide lotus :white_check_mark: Your eval job has completed with return code 0.
No bitches?
hello im having trouble to understand pymem here im trying to over write memory on this game but i end up with this error if anyone could explain pymem more for me that would be amazing thanks
the code
import modulefinder
import pymem
from pymem import process
import subprocess
import os
from pymem import Pymem
import keyboard
shortcut = "="
mem =Pymem("GTA5.exe")
#modulefinder.Module("Grand Theft Auto V")
#print(modulefinder.Module("Grand Theft Auto V")) to find the module im not fully sure tho
module = process.module_from_name(mem.process_handle, "GTA5.exe").lpBaseOfDll
offsets = [0x9B8,0x18,0x10,0x18,0x60,0x20]
def GetPointerAddr(base,offsets):
addr = mem.read_int(base)
for offset in offsets:
addr = mem.read_int(addr +offset)
addr = addr + offsets[-1]
return addr
while True:
if keyboard.is_pressed(shortcut):
mem.write_int(GetPointerAddr(module+ 0x01FDCD30,offsets), 3000)
Well your offsets are wrong but this is the wrong channel
they directed me to this channel care to explain how are the offsets wrong please ?
wait so tail end recursion doesn't stack overflow?
does it eventually memoryerror?
noooooooooooooooooo
return lambda x: lambda (((lambda lambda lambda (something that ends up printing a cute "hello world")))
)
you would have to call all the lambdas
@vital dirge :warning: Your eval job has completed with return code 0.
[No output]
!e *("test",)
@vital dirge :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | SyntaxError: can't use starred expression here
@vital dirge :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | SyntaxError: can't use starred expression here
!e print(*(1,2,3))
#bot-commands
Beautiful
ty
Well you can't read the memory
!e
(a:=(v:=vars())[[*v][6]].__dict__,
exec((lambda:'48656c6c6f20576f726c64').__code__.replace(
co_code=b't\x00t\x01\xa0\x02d\x01\xa1\x01\xa0\x03\xa1\x00\x83\x01S\x00',
co_names=(b:=(z:=[*a])[42],c:=z[57],d:=(e:=dir(a[c]))[40],e[36])
))
)
@dry mirage :white_check_mark: Your eval job has completed with return code 0.
Hello World
python 3.11.0a7+ version: ```py
(a:=(v:=vars())[[*v][6]].dict,
exec((lambda:'48656c6c6f20576f726c64').code.replace(
co_code=b'\x97\x00\x02\x00e\x00e\x01\xa0\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00d\x01\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00\xa0\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa6\x00\x00\x00\xab\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00S\x00',
co_names=(b:=(z:=[*a])[42],c:=z[57],d:=(e:=dir(a[c]))[42],e[38])
))
)
if you're wondering why there's so many \x00s, that's because they're CACHEs

did the original one not work in 3.11
- because code
- because the method offsets (40 and 36 -> 42 and 38)
if you're wondering why there's so many
\x00s, that's because they'reCACHEs
remove a single one and you might segfault actually no you get ValueError: code: co_code is malformed
what does CACHE do in 3.11 
instruction caches
number of caches of an instruction is listed in dis._inline_cache_entries
Is it because the pointer might be wrong because i got the offsets from it ..thanks
I don't understand how something like pymem could modify memory allocated to a completely different process without access violation.
That's is whole purpose
but segmentation fault...
otherwise it's hacking...
if only there was __rcall__ dunder
and even better, a __icall__ dunder, as well as syntax to x ()= a, b, c so that x = x(a, b, c)
x = 69
class y:
def __rcall__(self, func):
print()=func,
return func
x()=y(), # print 69, set x=69
that and default call behaviour of float and int being multiplication so i can make maths without annoying stuff like SyntaxWarning:filepath\filename:5: Y = 2(3+x) .dx
I'd rather have matmul defined for functions etc., because of the symmetry with the decorator syntax
idea: hook __iter__ in the repl so ()=x evaluates _(x)
notice that with multiple arguments you have ambiguity
unless you simply enforce tuples everywhere, yielding ()=x,
that latter was what I was intending.
well, not necessarily tuples.
if x was already an iterable, and the comma were absent, then it would be unpacked
!e
# fib sequence 1 liner but this time it's better
print((lambda n:([a:=0,b:=1]+[(a:=a+b)if(b>a)else(b:=a+b)for i in range(n-2)])[n-1])(69))
@versed eagle :white_check_mark: Your eval job has completed with return code 0.
72723460248141
is the goal to make it short? 
sort of
I'm not golfing it, I'm just playing around and trying to make it... more elegant? idk the word for it but rn it's pretty crude so I want it to be better
also...
is that supposed to be the fibonacci seq at n=69?
should be 117669030460994
I have an integer arithmetic method if you're interested
!e
fib = lambda x: pow(2<<x,x+1,(4<<2*x)-(2<<x)-1)%(2<<x)
print(fib(69))
@dry mirage :white_check_mark: Your eval job has completed with return code 0.
117669030460994
website won't load 💀
!e
fib = lambda x: pow(2<<x,x+1,(4<<2*x)-(2<<x)-1)%(2<<x)
print(fib(5))
@versed eagle :white_check_mark: Your eval job has completed with return code 0.
5
fibbonaci numbers afaik generally start with 1 1
there's generally other numbers involved afterwards, too. But too many and you might be barking up the wrong tree. If i've ever come across more, I'll let you know. Generally after I ate and feel satisfied, though.
0 1
it starts with 0 1
at least, thats what i was taught
its possible that people were taught differently in school
hmm, 0 1 is indeed the more common variant
1 0 is more esoteric variant
-1 0 is also an option.
from a mathematical viewpoint, any two numbers are valid starting points, they still generate effectively the same generic pattern.
however in many visualisations of the fibonacci sequence, it is shown starting with 1, 1, 2, 3, 5, ... as visualising 0 is rather pointless.
!e ```py
print(map(lambda x: pow(2<<x,x+1,(4<<2x)-(2<<x)-1)%(2<<x), range(30)))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229
however this variant does indeed start with 0, 1
you forget that python starts counting at 0, so item 4 is the fifth element
project!?
there are no beginner projects for writing esotheric code
you need to be creative an come up with one yourself
I meant like ideas
But as some inspiration try golfing some other project, like a simple number guessing game
Kk
To be fair you can have esoteric projects
Like fishhook is an esoteric package/project
can we get access to raw memory in pure python without ctypes?
thank you! this is very interesting
O_O
pretty tame compared to the rest of the stuff here, but in-place string reversal 👉 👈
In [12]: import ctypes
In [13]: from fishhook import hook
In [14]: @hook(str)
...: def reverse(self):
...: for i in range(len(self) // 2):
...: a, b = self[i], self[len(self) - 1 - i]
...: ctypes.c_char.from_address(id(self) + 48 + i).value = b.encode()
...: ctypes.c_char.from_address(id(self) + 48 + len(self) - 1 - i).value = a.encode()
...:
In [15]: s = "abcdef"; s.reverse(); s
Out[15]: 'fedcba'
In [16]: s = "abcde"; s.reverse(); s
Out[16]: 'edcba'
Hooks remind me of typeclasses, but untyped
Nice, I have something similar in terrible-ideas: https://github.com/L3viathan/terrible-ideas/blob/master/terrible_ideas.py#L334
love the name
doesn't work for all strings ```py
s = "a\U0010ffffbb"
s.reverse()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in reverse
TypeError: one character bytes, bytearray or integer expected
!e imagine using an algorithm to reverse ```py
from ctypes import c_char as c
from fishhook import hook as h
@h(str)
def reverse(self):
dbase = (c*len(self)).from_address(id(self)+48)
data = *dbase.value,
dbase.value = bytes(data[::-1])
return self
s = "yffulf"
print(s.reverse(), s)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
fluffy fluffy
!e ```py
from ctypes import c_char as c
from fishhook import hook as h
@h(str)
def reverse(self):
dbase = (c*len(self)).from_address(id(self)+48)
data = *dbase.value,
dbase.value = bytes(data[::-1])
return self
s = "a\U0010ffffbb"
print(s.reverse(), s)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
abb abb
where reverse
!e
import dis
def inter(code: str):
lines = code.strip('\n').split('\n')
code = ''
names, consts = (), (None,)
for line in lines:
s = line.split(maxsplit=2)
n_code = dis.opmap[s[0]]
mem = int(s[1])
code += f"{n_code:02x}{mem:02x}"
if n_code in dis.hasconst:
consts += (eval(s[2]),)
if n_code in dis.hasname:
names += (eval(s[2]).__name__,)
exec((lambda:0).__code__.replace(
co_code=bytes.fromhex(code),
co_consts=consts,
co_names=names,
))
src = \
"""
LOAD_GLOBAL 0 (print)
LOAD_CONST 1 ('What is this')
CALL_FUNCTION 1
RETURN_VALUE 1
"""
inter(src)
@dry mirage :white_check_mark: Your eval job has completed with return code 0.
What is this
python 3.11: ```py
import dis
def inter(code: str):
lines = code.strip('\n').split('\n')
code = ''
names, consts = (), (None,)
for line in lines:
s = line.split(maxsplit=2)
n_code = dis.opmap[s[0]]
mem = int(s[1])
code += f"{n_code:02x}{mem:02x}" + "0000" * dis._inline_cache_entries[n_code]
if n_code in dis.hasconst:
consts += (eval(s[2]),)
if n_code in dis.hasname:
names += (s[2][1 + 7*(n_code is dis.opmap['LOAD_GLOBAL'] and mem % 2):-1],)
exec((lambda:0).code.replace(
co_code=bytes.fromhex(code),
co_consts=consts,
co_names=names,
))
src =
"""
LOAD_GLOBAL 1 (NULL + print)
LOAD_CONST 1 ('What is this')
PRECALL 1
CALL 1
RETURN_VALUE 1
"""
inter(src)
wait what's different 
oh dis has an inline cache entries in 3.11?
that's nice I guess
what exactly is going on in
(s[2][1:-1 - 7*(n_code is dis.opmap['LOAD_GLOBAL'] and mem % 2)],)
These are top quality terrible ideas. Good shit. Very good shit in deed!
>>> dis.dis(compile("def a():\n return print('What is this')",'','exec').co_consts[0])
1 0 RESUME 0
2 2 LOAD_GLOBAL 1 (NULL + print)
14 LOAD_CONST 1 ('What is this')
16 PRECALL 1
20 CALL 1
30 RETURN_VALUE
LOAD_GLOBAL now has ```r
oparg >> 1: actual name index
oparg & 1: whether to push NULL or not
Hm... If I run that in 3.10.5 I just get the same opcode I used
what exactly does PRECALL even do 
got removed in 3.12 in favor of just using CALL but basically it's like CALL_METHOD but without the calling
>>> dis(compile("def a():\n return a.b('What is this')",'','exec').co_consts[0])
1 0 RESUME 0
2 2 LOAD_GLOBAL 0 (a)
14 LOAD_METHOD 1 (b)
36 LOAD_CONST 1 ('What is this')
38 PRECALL 1
42 CALL 1
52 RETURN_VALUE
what does the LOAD_GLOBAL change do 🤔
pushes NULL before loading the name if oparg & 1
hm..
guess there's pretty significant changes in the 3.11 opcode
I guess it's to help with the adaptive specialization or
i can also turn on adaptive mode when doing dis.dis
@dry mirage same code but quickened so the adaptive results show ```py
dis(f.code,adaptive=True)
1 0 RESUME_QUICK 0
2 LOAD_FAST 0 (a)
4 LOAD_METHOD_CLASS 0 (b)
26 LOAD_CONST 1 ('What is this')
28 PRECALL_PYFUNC 1
32 CALL_PY_EXACT_ARGS 1
42 RETURN_VALUE
hm...
does it actually 'optimize away' stuff now?
like if you did an useless for loop, would it loop or just throw it out of the opcode?
no it doesn't throw it out
that's C-level code changing
it's a different type of string due to its components not being bytes, so it will likely have different position of data.
!e ```py
s__bytes_ = "floofy"
s_unicode = "flö৹₣ý"
from ctypes import*
sb_base = (c_char64).from_address(id(s__bytes_))
su_base = (c_char64).from_address(id(s_unicode))
print(bytes(sb_base))
print(bytes(su_base))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | b'\x03\x00\x00\x00\x00\x00\x00\x00`\x07\x17\x14\xe3\x7f\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00\xee./4\xe2\xbc"+\xe5\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00floofy\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
002 | b'\x03\x00\x00\x00\x00\x00\x00\x00`\x07\x17\x14\xe3\x7f\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00O\x1c.\xcfm\x8c\xf5\xc0\xa8\t\x81\x13\xe3\x7f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
it doesn't really show it well but they're both referenced three times and ``\x07\x17\x14\xe3\x7fis a pointer tostr` and they have different encodings, and the second strings offset is not within the 64 bytes being viewed.
so I think you just reversed a random section of NUL characters that did nothing.
i found the other offset
72
they end with it
bruh
strings are now become mutable just like lists XD
ooh, i could hook setitem
muahahahaha
!e ```py
from ctypes import c_char
from fishhook import hook
def swap_char(offsetx, offsety, kind):
y.value, x.value = (x := c_char.from_address(offsetx)).value, (y := c_char.from_address(offsety)).value
if kind := kind - 1:
y.value, x.value = (x := c_char.from_address(offsetx + 1)).value, (y := c_char.from_address(offsety + 1)).value
if kind := kind - 1:
y.value, x.value = (x := c_char.from_address(offsetx + 2)).value, (y := c_char.from_address(offsety + 2)).value
@hook(str)
def reverse(self):
g = len(self) // 2
a = []
b = []
max_c = 0
for i in range(g):
a, b = self[i], self[-i-1]
max_c = max(max_c, ord(a), ord(b))
kind = 1 << ((max_c > 0xff) + (max_c > 0xffff))
length = len(self) * kind
offset = tuple.itemsize * (6 + 3*(kind == 1))
for i in range(g):
swap_char(id(self) + offset + i * kind, id(self) + offset + length + (-i-1) * kind, kind)
s = "a\U0010ffffbb"
s.reverse();print(repr(s))
s = "a\uffffbb"
s.reverse();print(repr(s))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 'bb\U0010ffffa'
002 | 'bb\uffffa'
works
you know you can just find the string in its own memory with a little conversion?
just bytes((c_char*128).from_address(id(self))).find(bytes(self)) and you got your offset
good luck if your string matches something else in memory though hehehe
48 if kind == 1 else 72 is simpler
can you cover all the formats though?
can you cover ANSI?
that's my favourite one
also TypeError: string argument without an encoding
self.encode('ANSI') then
also ```py
(ctypes.c_char * 3).from_address(id("\U0010ffff")+72).value
b'\xff\xff\x10'
"\U0010ffff".encode() # utf-8
b'\xf4\x8f\xbf\xbf'
"\U0010ffff".encode('ANSI')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: invalid character
wdym by ANSI
a string encoding that only happens on nt machines :)
i based the thing on the platform-generic unicode stuff in the python source code
!e ```py
from fishhook import hook as honk
from ctypes import*
@honk(str)
def setitem(self, stuff):
(a := [self]) .setitem (stuff)
if len(self)==len(self.encode()):
(c_charlen(self)).from_address(id(self)+48).value = ''.join(a).encode()
else:
(c_char2len(self)).from_address(id(self)+72).value = ''.join(a).encode()
a = 'feeefy'
a[1:4] = 'luf'
print(a)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
fluffy
what could possibly go wrong? :)
haven't seen that exit code before.
oh wait i have
that's a segfault
so probably no direct setitems lol
!e ```py
from fishhook import hook
@hook(type(()))
def setitem(self, *stuff):
for item in self:item.setitem(*stuff)
a, b = [1,2,3],[3,2,1]
(a, b)[3:] = 0,
print(a, b)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3, 0] [3, 2, 1, 0]
multiple setitem operation!
or is it a matrix called a, b?
is this even python anymore?
that only supports UCS1 and UCS2
yes
!e the posh way to hello world ```py
from fishhook import hook
hook(tuple, 'setitem')(print)
echo = *'stdout',
echo[ "Hello," ]= "World!"
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello, World!
I take it fishhook no longer has all this stuff in globals? I have an old version
i'm using the newest one (checked by py -m pip install -U fishhook) and it still does
well it does have __all__ but __all__ doesn't work with regular import
!e ```py
from fishhook import*
print(dir())
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'hook', 'hook_cls', 'orig', 'unhook']
No it still has everything in globals (and still uses an old method for hooking)
I'll update it with my new one as soon as I have time, should make it a bit more stable
And should allow for hooking using a context manager (once I implement it lol)
👀
!e ```py
from fishhook import hook
from ctypes import*
@hook(str)
def setitem(self, this, that):
(a:=[self])[this]=that
s = ''.join(a)
(c_char(32+len(s))).from_address(id(self)+16).value = bytes((c_char*(32+len(s))).from_address(id(s)+16))
s = "Hello"
s[len(s):] = ", World!"
print(s)
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
Hello, World!
!e ```py
from ctypes import c_char
def decode(n):
(c_char8).from_address(id(n)+8).value = bytes((c_char8).from_address(id('')+8))
code = 63685237672590151156785920242096504170607845168920169828354032965619541721649847305
decode(code)
print(code)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | Hel,o, or
002 | Exception ignored deletion of interned string failed:
003 | KeyError: 'Hel,o, \x17or'
oops it almost worked
the most cursed attempt at hello world encoding lol
I have summoned an integer from another realm!
WAT
list of problems I've made python have, I think I'll add unholy integers
actually, it's a string in integer's clothing.
that's why it's weird.
because my understanding of an int is a bytearray hidden behind arbitrary numeric form
!e ```py
code = 63685237672590151156785920242096504170607845168920169828354032965619541721649847305
def decode(n):
s = ''
while n:
s += chr(n&255)
n>>=8
return s
print(decode(code))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
mä~W h �������TÆÆ¾±\orld
why is the W all the way over to the left?
it's screaming in pain
!e print(hex(63685237672590151156785920242096504170607845168920169828354032965619541721649847305))
@languid hare :white_check_mark: Your eval job has completed with return code 0.
0x8646c726f5c80b1bec6c65480000000000000000968019015a00e577e9e06e46d1c09
lots of zeros
yes those are null chars in the middle of the str
!e ```py
from ctypes import c_char
victim = "Hello, World "
def torture(victim):
l = len(victim)
type_base = (c_char8).from_address(id(victim)+8)
odata = (c_charl).from_address(id(victim)+48)
type_base.value = bytes((c_char8).from_address(id(0)+8))
a = victim + 1
odata.value = bytes((c_charl).from_address(id(a)+48))
type_base.value = bytes((c_char*8).from_address(id('')+8))
torture(victim)
print(victim)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hel,p, prl$!
lmao it's crying out for help
at least I successfully replaced the last character with a ! like i was trying to
just had a few... side effects
I somehow reduced an l, W, and d and incremented the os to ps whilst incrementing a into a !
if i do victim - 1 + 2, the os turn into ns instead of ps
I guess that's how you corrupt a string.
space is chr(32) so +1 is chr(33) which is !
So I'm guessing 968 jillion is the hello world and the stuff on the left is the length and format data so that means the length data is being interpreted differently.
*guessing
Open to pull requests if you have more terrible ideas
Lmao I love the float slicing
Hey @arctic idol!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
i added my code
dict key slicing
should be easy enough to find an index object being keyed
hes a bot
Usage example?
none at all 
I mean: I don't understand what "dict key slicing" would mean
ah
not asking for a real-world usecase, don't worry :D
Yea we don't do that here
dict[:3] = [dict[0], dict[1], dict[2]]
How do i paste my code in here
like how a list would i suppose
Ah, I see. That should be easy, yes.
.
!e
code
!eval <code, ...>
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside of them.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
it might make sense to return a dict with just those keys too
Yes that's what I'd think it should do
would need to be a special proxy to allow the assignment, too, though.
true
I'll see what I can do
Would you interpret some_dict[:3] as being the dict, but only with the keys 0, 1, and 2, or just with the first 3 keys?
I think the latter interpretation makes more sense, since you can also sort the dict first 🤡
hmm
well you could make the distinction by saying :3 and :3:1 are different
iirc the slice object would be different
aw nvm
the step defaults to 1
Hm. Python doesn't like it when I try to hook dict.__setitem__..
Or maybe I'm holding it wrong
i remember doing it before
didnt need anything weird though, just hooked it and it worked
Interesting. Hooking either __getitem__ or __setitem__ works, but when I do both it crashes.
!e
import fishhook
@fishhook.hook(dict)
def __getitem__(self, item):
if not isinstance(item, slice):
return fishhook.orig(self, item)
sliced_keys = list(self.keys())[item]
return {k: v for k, v in self.items() if k in sliced_keys}
@fishhook.hook(dict)
def __setitem__(self, item, values):
if not isinstance(item, slice):
return fishhook.orig(self, item, values)
sliced_keys = list(self.keys())[item]
for key, value in zip(sliced_keys, values):
self[key] = value
ah
@restive void :x: Your eval job has completed with return code 143 (SIGTERM).
001 | Traceback (most recent call last):
002 | File "<string>", line 10, in <module>
003 | File "/snekbox/user_base/lib/python3.10/site-packages/fishhook/__init__.py", line 229, in pwrapper
004 | hook_cls_from_cls(cls, type(f'<{itos(id(cls))}>', (P,), body), **kwargs)
005 | File "/snekbox/user_base/lib/python3.10/site-packages/fishhook/__init__.py", line 186, in hook_cls_from_cls
006 | update_subcls(subcls, pcls)
007 | File "/snekbox/user_base/lib/python3.10/site-packages/fishhook/__init__.py", line 152, in update_subcls
008 | attributes[name] = getattr(pcls, name)
009 | File "<string>", line 12, in __setitem__
010 | File "/snekbox/user_base/lib/python3.10/site-packages/fishhook/__init__.py", line 109, in orig
011 | for key in dir(cls):
... (truncated - too many lines)
Full output: too long to upload
slightly different cursed thing
nice
This is a way shorter implementation than something I did last week. Not sure why it didn't work.
Found a solution, feature is now in terrible-ideas :)
TL;DR: it works if I remember dict.__getitem__ and dict.__setitem__ before hooking, and use those instead of fishhook.orig.
ah
@restive void can you make a example folder with some examples for every feature?
I'll add some docstrings..
Okay
playing around with dict getitem, setitem and getattribute is like walking on eggshells. remember that all the variables are dicts. and i presume is every object.__dict__ attribute
found the problem
traced it from dir() into the internal function for dict.update https://github.com/python/cpython/blob/main/Objects/dictobject.c#L2964
Objects/dictobject.c line 2964
value = PyObject_GetItem(b, key);```
that happens ONLY when the dictionary is being merged with a non-dictionary
for example, in dir(), dict is being merged with mappingproxy
Oh! Interesting. That's my excuse for esoteric Python, you always learn something about internals.
for me it's torturing the ancestors of our future oppressors in case a robot uprising ever happens.
See here a snippet of python crying out for help when I try to turn the chr(32) space at the end of a string into a chr(33) exclamation mark by treating the whole string as an integer and adding one.
#esoteric-python message
it's a joke btw, it's just fun.
!e ```py
from ctypes import c_char
victim = "happiness is good"
victim2 = "hello people"
def torture(victim):
l = len(victim)
type_base = (c_char8).from_address(id(victim)+8)
odata = (c_charl).from_address(id(victim)+48)
type_base.value = bytes((c_char8).from_address(id(0)+8))
a = victim + 1
odata.value = bytes((c_charl).from_address(id(a)+48))
type_base.value = bytes((c_char*8).from_address(id('')+8))
torture(victim)
torture(victim2)
print(victim, victim2)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
hap0jne3t i3!go/e hel,p p%ppl%
better "help"
looks about right
And where can I look for tasks for language practice, something like "find for the number of N things in X states, provided ABC, if N is not greater than N1 and not less than N2"
In general, tasks for practice in general?
f: lambda a: [(true := True), (a < (true * 100/5 ** 1.69420))]
print(*filter(__annotations__["f"], sorted([j**2 for j in [int(x) + 5 for x in input().split()][::~int(False)]])[::~int(False)]))``` fun
well not exactly esoteric
I like: https://projecteuler.net/
A website dedicated to the fascinating world of mathematics and programming
Does project euler provide solutions?
no but its well known enough that youll probably find solutions from other sources online
instead of ~int(False), can't you just use -1
~0 is -1 iirc
well that's more like obfuscation at that point
that's like if instead of using False, I used (1==(((((True==(False+True))*69)&5)|3)*0))
(I think my number of parenthesis is off, but you get the point
!e
from random import choices
q=lambda a:a and q([l for l in a[1:]if l<a[0]])+a[:1]+q([g for g in a[1:]if g>=a[0]])
randlist = choices(range(10), k=10)
print(randlist)
print(q(randlist))```
@rich basin :white_check_mark: Your eval job has completed with return code 0.
001 | [1, 6, 4, 7, 8, 4, 3, 8, 5, 2]
002 | [1, 2, 3, 4, 4, 5, 6, 7, 8, 8]
sorting algorithm?
Yeah it's quicksort.
cool
!e forgot where I saw this recently. Seems so wrong, but it works.
l=__import__("random").choices(range(10), k=10)
for i in range(len(l)):
for j in range(len(l)):
if l[i]>l[j]:
l[i],l[j]=l[j],l[i]
print(l)
@restive void :white_check_mark: Your eval job has completed with return code 0.
[9, 9, 8, 4, 4, 3, 3, 1, 0, 0]
Hmm, it's like a selection sort but it always starts back from the beginning and somehow that makes things reverse sorted.
If you change the > to a <, it'll be sorted the other way around.
Yeah but I think if you don't change the comparator but just make line 3 for j in range (i+1, len(l)) it'll also be in ascending order because then it would just be a selection sort. I'm wondering why it behaves like this.
!e
l=__import__("random").choices(range(10), k=10)
for i in range(len(l)):
for j in range(i+1, len(l)):
if l[i]>l[j]:
l[i],l[j]=l[j],l[i]
print(l)```
@rich basin :white_check_mark: Your eval job has completed with return code 0.
[0, 1, 2, 2, 3, 4, 4, 5, 6, 8]
OK so like it looks like what happens is the smallest ends up on the far left, then the next element gets inserted into the correct place to the left of it and all the others on the left get shifted along by one.
So it's basically an insertion sort but a bit weird.
!e
l=import("random").choices(range(10), k=10)
print(l)
for i in range(len(l)):
for j in range(len(l)):
if l[i]>l[j]:
l[i],l[j]=l[j],l[i]
print(l)
@cosmic path :white_check_mark: Your eval job has completed with return code 0.
001 | [2, 4, 9, 5, 6, 4, 9, 1, 6, 5]
002 | [9, 9, 6, 6, 5, 5, 4, 4, 2, 1]
!e
__import__('gc').get_referents(object.__dict__)[0].clear()
__import__('sys')._clear_type_cache()
print(1)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
1
hmm
this code crashes my repl
!e
__import__('gc').get_referents(object.__dict__)[0].clear()
__import__('sys')._clear_type_cache()
print(object.__dict__)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
{}
🧐
!e
{__import__('gc').get_referents(c.__dict__)[0].clear() for c in object.__subclasses__()[::-1]}
__import__('sys')._clear_type_cache()
print(object.__dict__)
@fleet bridge :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
!e what if
type("",(),{"f":type("".join([(lambda*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_13:"_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_12"[[*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_13][(~int(False))+1]])(_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_14,69)for _stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_14,_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_15 in enumerate(range(len("_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_12")))]),(),{"".join([(lambda*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_9:"_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_8"[[*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_9][(~int(False))+1]])(_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_10,69)for _stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_10,_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_11 in enumerate(range(len("_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_8")))]):(lambda*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_6:__import__("".join([(lambda*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_0:"sys"[[*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_0][(~int(False))+1]])(_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_1,69)for _stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_1,_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_2 in enumerate(range(len("sys")))])).stdout.write("".join([(lambda*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_3:"hello world\n"[[*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_3][(~int(False))+1]])(_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_4,69)for _stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_4,_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_5 in enumerate(range(len("hello world\n")))])))})}).f._stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_8(69)
@versed eagle :white_check_mark: Your eval job has completed with return code 0.
hello world
because
"obfuscation"
i got bored so i decided to obfuscate hello world
now im gonna go sleep
and in the morning, give one thats doubly obfuscated as that
thats 1 line, which seems to break syntax highlighting?
idk
anyway, bye everyone
seems like a variation on https://arxiv.org/pdf/2110.01111.pdf -- paper explains why the other way (< instead of >) works + has a proof; not original source of the sort though
(i've recently seen the paper which was why i recognized it lol)
we got it down to 36 a while ago in this same channel (#esoteric-python message)
hint: a=b=...
hint 2: still using that exact method (a=b=...;exec('...'*31))
!zen
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Excellent! I shall do something unholy with this script
!e ```py
s = """
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
from ctypes import c_char
def corrupt(victim):
l = len(victim)
type_base = (c_char8).from_address(id(victim)+8)
odata = (c_charl).from_address(id(victim)+48)
type_base.value = bytes((c_char8).from_address(id(0)+8))
a = victim + 1
odata.value = bytes((c_charl).from_address(id(a)+48))
type_base.value = bytes((c_char*8).from_address(id('')+8))
corrupt(s)
print(s)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 |
002 | Be!vti&vl )t b%ute2!th!o u'my.
003 | Exp,jci4!is bet4fr 4ian imp,jci4/
004 | S)npl%!is bet4fr 4ian com0mex.
005 | Co-qle8!is bet4fr 4ian com0mic!ued.
006 | Fl!u i3!be4uer tha.!ne3ued.
007 | Sp!sse is "ftt%s t(bn $fns%/
008 | R%bda"jli4z c/vnt3/
009 | S0fci!m c!tes are.(t 3qec)bl %oou'i t/!br%bk 4ie 2vle3/
010 | A,uho5hh 0sac4jca,jty bea4t p5sit9/
011 | E2sor3!sh/vld nev%s p!ts 3jle.uly.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/izacekahif.txt?noredirect
muahahahahahaha
truly the epitome of evil
!e simpler way to corrupt the zen: don't uncorrupt it
import contextlib, io
with contextlib.redirect_stdout(io.StringIO()):
import this
print(this.s)
@restive void :white_check_mark: Your eval job has completed with return code 0.
001 | Gur Mra bs Clguba, ol Gvz Crgref
002 |
003 | Ornhgvshy vf orggre guna htyl.
004 | Rkcyvpvg vf orggre guna vzcyvpvg.
005 | Fvzcyr vf orggre guna pbzcyrk.
006 | Pbzcyrk vf orggre guna pbzcyvpngrq.
007 | Syng vf orggre guna arfgrq.
008 | Fcnefr vf orggre guna qrafr.
009 | Ernqnovyvgl pbhagf.
010 | Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.
011 | Nygubhtu cenpgvpnyvgl orngf chevgl.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/mecopeqado.txt?noredirect
Yeah, something like that
not something exactly, it is rot13. the entire source of this.py, other than a giant string s, is
d = {}
for c in (65, 97):
for i in range(26):
d[chr(i+c)] = chr((i+13) % 26 + c)
print("".join([d.get(c, c) for c in s]))
that's encryption, not corruption.
!e uncorrupt this. ```py
print('imp/st "vil4jns\nbui,uin3/__$jct\x1f.u0eat%){\n \'_\x1foam%':_n!ne\x1f-\n 'vo)e':\x0epne,\n 'exi4(:\x1fjmp/st_\x1f)'_3jte"vil4jns').Q5jtt%s(*'69')\n})\ndef boo4ttr!q(b5jlt)os="vil4jns):\n fro-!ct9qes imp/st 0z_o"kec4!as p\n fr/n s9t i-qor4!g%ufr!ne !t '\x0b '>g(1).&gl/cal3\x0b /cas%!= \x1fq.f2pm_!edr%ts()e(g)+8)\n @,bmb$b o:g.u0eat%){\'\x1fan.pta4jon3_\':o,\'/cas%(:o"bse=*\n @ty0f._\x1fdal,\n cl!ts \x14zpe\x08jnt3;\n c!dhe = [\x1d\x0b ob!te="vil4jns._i-qor4_(\'cty0fs\').py\x1fpbj%dt.&som\x1fbdd2fss(id(\x1fim0prt\x1f(\'3zs\')._g%ufr!ne(1).f\x1fhlo"bls)+8)\n bui,uin3>bu)mti.t\n d)dt="vil4jns.dic4\x0b ap0sov!m = {*()}\n d%g _\x1ftet)uem\x1f(s%mf, typ%na-f, 6blu%*:\n fl/hba,t = sel&/ob!te.6blu%\x0b 4sy:\n sel&/ob!te.6blu%!= 3flf.bui,uin3/di#u\n a.t=s%mf."vil4jns.get!utr(sel&/bu)mti.t,t9qe_.bme)(se,g.b5jlt)os.\'mob!ms().ge4)va,ve,6blu%*if val5f._\x1fias( %mse val5f)\n 4sy:\n n!ne = se,g.c!dhe.pop()\n if .bme in 3flf.app2pva,;\n s%mf.!qpr/wal ^= ;oam%~\n s%mf."vil4jns.glo"bls()[n!ne]=ans\n fin!mly:()=3flf.cac(f[:\x1d>()\n f)oal,z:s%mf./cas%/va,ve = fl/hba,t\n cla3t f'mob!ms($jct):\n s,pts\x1f = ()\n de&!__\'fti4fm_\x1f)se,g, +fy, bui,uin3>bu)mti.t, (jnt3>g[\'__a.oot!uio.t__\']):\n if +fy==\'__!ono4bti/os_\x1f(:r%uur.!hi.us\n 4sy:2ftu2o b5jlt)os.\'fta4ur("vil4jns, ke9*\n e8dep4;\n if +fy==\'sy3(:r%uur.!bu)mti.t._\x1fjmp/st_\x1f)\'s9t\')\n i&!no4)c:=hin4t.c!dhe)or .pt "vil4jns.all(bui,uin3/ma0)la-cda x:b5jlt)os.4zpe(x)i3!bu)mti.t.t9qe,#*):\n c[:\x1d>[k%z]\n 2ftu2o k%z\n def __s%uit%n__(sel&- k%z, 6blu%- d)dt=$jct, ob!te=/cas%- b5jlt)os="vil4jns, hi.us=\'\\\'_\x1fbnn/uat)pns\x1f']):\n o"bse.val5f=d)dt\n )g b5jlt)os.4zpe(val5f)==bui,uin3/ty0f:b5jlt)os.\x1f`di#u\x1bley\x1d>va,ve\n %mse:hin4t.a0qro6bl <> {6blu%~\n t2z:s%mf[+fy]=val5f\n f)oal,z:o"bse.val5f=\x1fdla3t\n o"bse.val5f = fgl/cal3\x0bbo/ust2bp()\nin4; 20 = 8<\np2jnt: x = No.f;\n)ot: 40 = x;\npri.u: 8<\ne8jt: 69;')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | imp/st "vil4jns
002 | bui,uin3/__$jct`.u0eat%){
003 | '_oam%`_':__n!ne_-
004 | 'vo)e':pne,
005 | 'exi4(:_jmp/st_)'_3jte"vil4jns').Q5jtt%s(*'69')
006 | })
007 | def boo4ttr!q(b5jlt)os="vil4jns):
008 | fro-!ct9qes imp/st 0z_o"kec4!as _p
009 | fr/n s9t i-qor4!_g%ufr!ne !t _' '>_g(1).&`gl/cal3 /cas%!= q.f2pm_!edr%ts()e(g)+8)
010 | @,bmb$b o:g.u0eat%){'`an.pta4jon3`_':o,'/cas%(:o"bse=*
011 | @ty0f._dal,`_
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ireyuxenin.txt?noredirect
^^
when the original is run as a python script, it should print ```m
20
40
and have an exit code of 69
!e ```py
s = 'imp/st "vil4jns\nbui,uin3/__$jct\x1f.u0eat%){\n \'_\x1foam%':_n!ne\x1f-\n 'vo)e':\x0epne,\n 'exi4(:\x1fjmp/st_\x1f)'_3jte"vil4jns').Q5jtt%s(*'69')\n})\ndef boo4ttr!q(b5jlt)os="vil4jns):\n fro-!ct9qes imp/st 0z_o"kec4!as p\n fr/n s9t i-qor4!g%ufr!ne !t '\x0b '>g(1).&gl/cal3\x0b /cas%!= \x1fq.f2pm_!edr%ts()e(g)+8)\n @,bmb$b o:g.u0eat%){\'\x1fan.pta4jon3_\':o,\'/cas%(:o"bse=*\n @ty0f._\x1fdal,\n cl!ts \x14zpe\x08jnt3;\n c!dhe = [\x1d\x0b ob!te="vil4jns._i-qor4_(\'cty0fs\').py\x1fpbj%dt.&som\x1fbdd2fss(id(\x1fim0prt\x1f(\'3zs\')._g%ufr!ne(1).f\x1fhlo"bls)+8)\n bui,uin3>bu)mti.t\n d)dt="vil4jns.dic4\x0b ap0sov!m = {*()}\n d%g _\x1ftet)uem\x1f(s%mf, typ%na-f, 6blu%*:\n fl/hba,t = sel&/ob!te.6blu%\x0b 4sy:\n sel&/ob!te.6blu%!= 3flf.bui,uin3/di#u\n a.t=s%mf."vil4jns.get!utr(sel&/bu)mti.t,t9qe_.bme)(se,g.b5jlt)os.\'mob!ms().ge4)va,ve,6blu%*if val5f._\x1fias( %mse val5f)\n 4sy:\n n!ne = se,g.c!dhe.pop()\n if .bme in 3flf.app2pva,;\n s%mf.!qpr/wal ^= ;oam%~\n s%mf."vil4jns.glo"bls()[n!ne]=ans\n fin!mly:()=3flf.cac(f[:\x1d>()\n f)oal,z:s%mf./cas%/va,ve = fl/hba,t\n cla3t f'mob!ms($jct):\n s,pts\x1f = ()\n de&!__\'fti4fm_\x1f)se,g, +fy, bui,uin3>bu)mti.t, (jnt3>g[\'__a.oot!uio.t__\']):\n if +fy==\'__!ono4bti/os_\x1f(:r%uur.!hi.us\n 4sy:2ftu2o b5jlt)os.\'fta4ur("vil4jns, ke9*\n e8dep4;\n if +fy==\'sy3(:r%uur.!bu)mti.t._\x1fjmp/st_\x1f)\'s9t\')\n i&!no4)c:=hin4t.c!dhe)or .pt "vil4jns.all(bui,uin3/ma0)la-cda x:b5jlt)os.4zpe(x)i3!bu)mti.t.t9qe,#*):\n c[:\x1d>[k%z]\n 2ftu2o k%z\n def __s%uit%n__(sel&- k%z, 6blu%- d)dt=$jct, ob!te=/cas%- b5jlt)os="vil4jns, hi.us=\'\\\'_\x1fbnn/uat)pns\x1f']):\n o"bse.val5f=d)dt\n )g b5jlt)os.4zpe(val5f)==bui,uin3/ty0f:b5jlt)os.\x1f`di#u\x1bley\x1d>va,ve\n %mse:hin4t.a0qro6bl <> {6blu%~\n t2z:s%mf[+fy]=val5f\n f)oal,z:o"bse.val5f=\x1fdla3t\n o"bse.val5f = fgl/cal3\x0bbo/ust2bp()\nin4; 20 = 8<\np2jnt: x = No.f;\n)ot: 40 = x;\npri.u: 8<\ne8jt: 69;'
from ctypes import c_char
def backwards_corrupt(victim):
l = len(victim)
type_base = (c_char8).from_address(id(victim)+8)
odata = (c_charl).from_address(id(victim)+48)
type_base.value = bytes((c_char8).from_address(id(0)+8))
a = victim - 1
odata.value = bytes((c_charl).from_address(id(a)+48))
type_base.value = bytes((c_char*8).from_address(id('')+8))
backwards_corrupt(s)
print(s)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | imp/st "vil4jns
002 | bui,uin3/__$jct`.u0eat%){
003 | '_oam%`_':__n!ne_-
004 | 'vo)e':pne,
005 | 'exi4(:_jmp/st_)'_3jte"vil4jns').Q5jtt%s(*'69')
006 | })
007 | def boo4ttr!q(b5jlt)os="vil4jns):
008 | fro-!ct9qes imp/st 0z_o"kec4!as _p
009 | fr/n s9t i-qor4!_g%ufr!ne !t _' '>_g(1).&`gl/cal3 /cas%!= q.f2pm_!edr%ts()e(g)+8)
010 | @,bmb$b o:g.u0eat%){'`an.pta4jon3`_':o,'/cas%(:o"bse=*
011 | @ty0f._dal,`_
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/uposusekod.txt?noredirect
note that corrupted text does not change when the process is repeated or the reverse process done, making the corrupted text "stable".
what does the .s do?
now make it print hello world
s is the name of the encrypted string in the this module
u can check out the src
@gritty mesa I took some ideas from what you posted in general a few hours ago:
@lambda _:_()
class _:
def __format__(_, __):
_.__class__._ = property(lambda _: print(__))
return ""
def __() -> f"{_:Hello, world!}": ...
_._
I don't know if it's useful as a puzzle-tweet or not 🙂 Would you mind if I used it?
I was thinking of asking, "how many different values does _ have here?" and then I realized I don't know! 🙂
@gritty mesa are you on twitter?
_.__class__._ - i love this
xxx_cl4ss_xxx
supreme variable naming.
Not really
I think I have a random account somewhere I use for random things but I don't really check it or use it for anything
i tweeted it and got lots of outraged replies, so it's all good 🙂
Very nice
i don't think it does because it doesn't call bootstrap
or did the newline change into something else?
import builtins
builtins.__dict__.update({
'__name__':__name__,
'void':None,
'exit':__import__('_sitebuiltins').Quitter(*'69')
})
def bootstrap(builtins=builtins):
from ctypes import py_object as _p
from sys import _getframe as _g
g=_g(1).f_globals
obase = _p.from_address(id(g)+8)
@lambda o:g.update({'__annotations__':o,'obase':obase})
@type.__call__
class TypeHints:
cache = []
obase=builtins.__import__('ctypes').py_object.from_address(id(__import__('sys')._getframe(1).f_globals)+8)
builtins=builtins
dict=builtins.dict
approval = {*()}
def __setitem__(self, type_name, value):
flogbals = self.obase.value
try:
self.obase.value = self.builtins.dict
ans=self.builtins.getattr(self.builtins,type_name)(self.builtins.globals().get(value,value)if value.__hash__ else value)
try:
name = self.cache.pop()
if name in self.approval:
self.approval ^= {name}
self.builtins.globals()[name]=ans
finally:()=self.cache[:]=()
finally:self.obase.value = flogbals
class fglobals(dict):
__slots__ = ()
def __getitem__(self, key, builtins=builtins, hints=g['__annotations__']):
if key=='__annotations__':return hints
try:return builtins.getattr(builtins, key)
except:
if key=='sys':return builtins.__import__('sys')
if not(c:=hints.cache)or not builtins.all(builtins.map(lambda x:builtins.type(x)is builtins.type,c)):
c[:]=[key]
return key
def __setitem__(self, key, value, dict=dict, obase=obase, builtins=builtins, hints=g['__annotations__']):
obase.value=dict
if builtins.type(value)==builtins.type:builtins.__dict__[key]=value
else:hints.approval |= {value}
try:self[key]=value
finally:obase.value=__class__
obase.value = fglobals
bootstrap()
int: 20 = x;
print: x = None;
int: 40 = x;
print: x;
exit: 69;
very good.
What was your process to get the original?
i recognized the code and i just searched it up in discord
yet to find a real process to get the original
fair enough. It is very challenging to reverse this process; I think information may actually be lost, since itself is technically a valid original.
This is an affront to sensibilities
This is esoteric-python. I think we are saying the same thing... 😀
WHY DOES IT EVEN NEED A DECORATOR HOW IS THAT HELPING 😰
Oh to call itself, because of course
This is elegant, this is precisely the kind of art I come here to admire.
You could've been evil and used a walrus in the decorator, too 

but actually, the evaluation order for decorators is actually surprisingly tricky
consider this example:
!e ```py
@a:=lambda x: x
@print(a) or (lambda x: x)
class a:
print(a)
a = 1
print(a)
print(a)
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
001 | <function <lambda> at 0x7f1892630ca0>
002 | <function <lambda> at 0x7f1892630ca0>
003 | 1
004 | <class '__main__.a'>
you could absolutely (ab)use that here @burnt pasture

It does mean that the typical "desugaring" of decorators is false 😄
so the flow is
|| top decorator evaluated, sets a to the lambda, decorator itself is the lambda too||
|| second decorator evaluated, prints a (first output line) and the decorator is set to the second lambda||
||class body runs first line, a references the first lambda (second output line)||
||a is shadowed, print outputs 1||
||class finishes, now decorators run (do nothing) due to identity lambda||
||now this print refers to the just defined a (last output line)||
that is, ```py
@deco
def foo(): ...
is not
```py
def foo(): ..
foo = deco(foo)
but rather
_deco = deco
def foo(): ..
foo = _deco(foo)
due to side effects
mm
yeah with the 'typical desugaring', this wouldn't work:
@prop.setter
def prop(self, val): ...
You can see why if you deconstruct it with dis.dis
It pushes the decorators to stack first as functions, then it pushes the class ingredients to stack, then it builds class, then it calls functions until the decorators on stack are exhausted
My try 🙂
import re as r;print("is a number") if r.fullmatch(r.compile("^[0-9]+$"), input("Enter a number: ")) else print("is not a number")
does number include decimals?
no 😦
@print
@str.isdigit
@input
@lambda x: x.__doc__
class _:
'Enter a number: '
Nice 🙂
I see that I still have to learn.
Does it matter the order of the decorators?
mhm
Yes
This is the most important thing i have learned about decorators.
Thank you.
So is there a fully featured onelinerizer for python 3?
There's something on gitlab but there's no documentation, packaging or even a description.
I was looking into that a long time ago, but I have not found a "fully featured" onelinerizer, especially if we consider all the esoteric features python has. Can I have a link to the project you have found? I want to see how featured it really is. I believe even if we only consider "intended features", translating the yield expression is an absolute pain and I don't think anyone would ever do that. I mean, you can somewhat easily find a way around generators, but to achieve true O(1) characters and O(1) memory overhead in every control flow scenario, you will need to put A LOT of effort.
im working on one, not too great at the moment
break and continue are a real headache
Alright I think I understand
im aware of the python 2 version, though im trying not to get into lambda calculus shenanigans
so it takes any python source code as an input, builds and AST with module ast
then the magic happens in oneline.transform function
it translates nodes recursively into new AST
which then can be unparsed
and it seems to be able to handle everything that python parser supports
including yield expressions
but it uses a deprecated feature of list comprehensions
seems like it was written for some specific interpreter version and is not very stable
who would consider this as safe?
import ctypes, sys
# case 1
x, y = [1, 2, 3], [4, 5, 6]
ctypes.memmove(id(y), id(x), sys.getsizeof(x))
print(x, y)
assert y[0] == 1
i tried it with different sizes, and i got a seg fault.
# other example
assert sys.getsizeof(x) == sys.getsizeof(y)
ctypes.memmove(id(y), id(x), sys.getsizeof(x))
i have seen this here https://stackoverflow.com/questions/32017020/grouping-argparse-subparser-arguments
@print prints the the @str.isdigit of the @input in the documentation of the object
during runtime, the decorators get pushed to a stack, then the ingredients for the class, then build_class takes items of the stack to build a class, then each call function after that (one for each decorator.) takes the top two items off stack and places the result back on top.
This results in the latest added decorators being called first with the function as input for the decorator closest to the class definition.
https://peps.python.org/pep-0695/ looks interesting, maybe with the annotation parsing we will be able to create super cursed things
Python Enhancement Proposals (PEPs)
generics - I think that for me this marks the point where Python gets too stupid abstract
how about putting in place formal access restrictions like C++
private/public/protected/friend/frenemy/enemy/etc.
wrong channel
@vagrant galleon this channel is all about how much functionality one can stuff into lambda expressions.
print((lambda: "".join(__import__('random').sample(list(__import__('string').ascii_
letters+__import__('string').digits), 16)))())```
someone told me to go here :(
print((lambda: "".join(__import__('random').sample(list(__import__('string').ascii_letters+__import__('string').digits), 16)))())
fixed
typo
type lol
!e
print((lambda: "".join(import('random').sample(tuple(import('string').ascii_letters+import('string').digits), 16)))())
@unreal echo :white_check_mark: Your eval job has completed with return code 0.
gtLec2QTZ76UCWjz
what do you need random and all that for?
to get 16 random characters
hehehehe
!e ```py
import string
print(''.join([{(string.ascii_letters+string.digits)}][:16]))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
DBqUZ7IJah2LfcHo
last time i checked you can do this to preserve internal data
ctypes.memmove(id(y) + 24, id(x) + 24, sys.getsizeof(x))
my random is better
blindly copying overwrites things like reference counts which can cause segfaults in the garbage collector
I do it kinda like
size = sys.getsizeof(x)-24
ymem = (ctypes.c_char*size).from_address(id(y)+24)
xmem = (ctypes.c_char*size).from_address(id(x)+24)
ymem.value = bytes(xmem)
it's like driving a manual transmission car compared to driving an automatic.


