#esoteric-python
1 messages · Page 38 of 1
__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()) is 1
int.__add__ is redundant
i wanna see how it deals with viruses
i think it might have a problem with evaluating function calls
like a safety problem
but it works
hopefully fixed the flaws
my brain did a wrong :3
it's very questionable code, when I wrote that code I was more interested in just writing a dumb thing rather than worrying about the legality of it 😛
i love seeing recursive main
when programming microcontrollers you usually have two "main" functions: setup() and loop()
they work basically like this: ```py
def main():
setup()
while True:
loop()
i wonder what will happen if you call `loop()` inside a `loop()`? will microcontroller ran out call stack space? what will happen then?
it should run out of memory and crash, i assume
more elaborate MCUs will error out due to failing memory protection, less elaborate ones will just kind of keep going, breaking everything in the process.
crash
how would that look like? will it just reset itself? or stack pointer will wrap around? what will happen if you execute random garbage? will cpu halt ot reset?
the ESP32 just restarts when memory protection fails, for example
would u have to recompile and flash the code to the board again?
Nope, it will just the same code again, likely crashing again
oh
now that i think about it, it makes sense for a board of that size to do that instead of just getting rid of the faulty code
If only some branch of the code will hit the crash, which is the more common case, you don't want to break the entire thing
yea
!e
a:str="++-+---.++--+-+.++-++--.++-++--.++-++++.+-----".replace('+', '1').replace('-','0').split('.');b:str="+++-+++.++-++++.+++--+-.++-++--.++--+--".replace('+', '1').replace('-','0').split('.')
for i in a: print("{}".format(chr(int(i,++len([200,300])))), end='')
for k in b: print("{}".format(chr(int(k,++len([3,1,2])++--++---1))),end='')
@fluid pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
ascii is cool :3
.replace('a', 'b') -> .replace(*'ab')
!e ```py
a:str="++-+---.++--+-+.++-++--.++-++--.++-++++.+-----".replace('+1').replace('-0').split('.');b:str="+++-+++.++-++++.+++--+-.++-++--.++--+--".replace('+1').replace('-0').split('.')
for i in a: print("{}".format(chr(int(i,++len([200,300])))), end='')
for k in b: print("{}".format(chr(int(k,++len([3,1,2])++--++---1))),end='')
@quartz wave :white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
"{}".format(...) -> ...
a="++-+---.++--+-+.++-++--.++-++--.++-++++.+-----".replace(*'+1').replace(*'-0').split('.');b="+++-+++.++-++++.+++--+-.++-++--.++--+--".replace(*'+1').replace(*'-0').split('.')
for i in a:print(chr(int(i,2)),end='')
for k in b:print(chr(int(k,2)),end='')
a="...";b="..." -> a="..."
a="++-+---.++--+-+.++-++--.++-++--.++-++++.+-----.+++-+++.++-++++.+++--+-.++-++--.++--+--".replace(*'+1').replace(*'-0').split('.')
for i in a:print(chr(int(i,2)),end='')
!e
a="++-+---.++--+-+.++-++--.++-++--.++-++++.+-----.+++-+++.++-++++.+++--+-.++-++--.++--+--".replace(*'+1').replace(*'-0').split('.')
for i in a:print(chr(int(i,2)),end='')
@fluid pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
I made my code long and full of garbage on purpose lol
My code isn't bad, I'm just protecting my intellectual property through obfuscation.
✨
How come this task is able to complete, even though it should be free'd first?
import asyncio
import gc
async def print_after_time(text, time):
await asyncio.sleep(time)
print(text)
async def task_test():
asyncio.create_task(print_after_time("task_complete", 2))
gc.collect()
await asyncio.sleep(1)
gc.collect()
await asyncio.sleep(1)
gc.collect()
await asyncio.sleep(1)
asyncio.run(task_test())
According to the create_task docs you need to save a reference to the task: https://docs.python.org/3/library/asyncio-task.html#creating-tasks
Important Save a reference to the result of this function, to avoid a task disappearing mid-execution. The event loop only keeps weak references to tasks. A task that isn’t referenced elsewhere may get garbage collected at any time, even before it’s done. For reliable “fire-and-forget” background tasks, gather them in a collection:
Surely, gc.collect() should be freeing the task then, and we should never get to see the text?
is there something wrong with my code to test this, or does this mean that it's actually safe to fire and forget tasks without saving my own references to them?
!e print("hello world")
@sick hound :white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
very esoteric 👍
simple Hello, world! https://paste.pythondiscord.com/PR5Q
code
getting the exclamation mark is like 90% of this code
im pretty sure ur borrowing from jsfuck
have you seen my hello world?
!e print( __import__('math').factorial.__doc__[6])
@craggy ruin :white_check_mark: Your 3.12 eval job has completed with return code 0.
!
no
ehehehehe
!e
__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),____:=_.__add__(_),___:=____.__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__add__(_).__lshift__(___.__add__(_)).__sub__(___.__add__(_).__add__(_))))().__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(____))),[__.__sub__(____.__lshift__(___).__add__(____.__lshift__(____))), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(___),_______,_______.__sub__(___.__lshift__(_)), __.__sub__(___.__add__(_).__mul__(___.__add__(___).__add__(_)))]))).__getitem__(_.__sub__(____)))```
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
very beautiful
you need to have a capital h, comma, and exclamation mark for it to be legit
i ran out of chars
i cant add it without going past the discord limit
and if i do
it makes it worse
instantly
damages my reputation
!e ```py
(:=builtins.dir().len(),builtins.getattribute(builtins.dir().getitem(.floordiv(.floordiv(name.dir().len()).add(.floordiv(name.dir().len()).add(.floordiv(name.dir().len()).add(.floordiv(name.dir().len()))))).add(.floordiv(name.dir().len())).add(.floordiv(name.dir().len())).add(.floordiv(name.dir().len()))))).getitem(builtins.dir().len().floordiv(name.dir().len()))((:=.floordiv(name.dir().len()),__:=.add().lshift(.add().add().lshift()),:=.add(),:=.add(),:=.sub(.add().add().lshift(.add())),:=__.sub(.add().lshift().sub(.add())),builtins.getattribute(builtins.dir().getitem(.add().add().lshift(.add()).sub(.add().add())))().getattribute(name.dir().getitem(.lshift()))(builtins.getattribute(builtins.dir().getitem(.add().lshift(.add()).add(.add())))(builtins.getattribute(builtins.dir().getitem(.floordiv(name.dir().len()).lshift(.lshift(.add())).sub())),[.lshift(.lshift()).add(.lshift()), .sub(.add().lshift()).add(), _____, _____,.sub(),.lshift(.add().add()).add(.lshift(.add())),.add().lshift(),.sub(.lshift()).sub(), .sub(),,.sub(.lshift()), .sub(.add().mul(.add().add())),.lshift(.add().add()).add()]))).getitem(.sub(___)))
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, world!
good
`import random
blocklist = ["left", "not left"]
number_of_blocks = int(input("How many swipes? "))for _ in range(number_of_blocks):
print(random.choice(blocklist))`
do you like my code
#python-discussion not here
how do you come up with these?
Wrong channel, that's not esoteric
What
random.choices exists
also, wrong channel
@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
if u know how it works then ping me and ill give u a cookie :3
(but say it in spoilers so other people also get to try to figure it out)
|| it digs into the stack frame and accesses the co_consts tuple to read "hello world", provable by using +8 instead of +32 to read the object class (<class 'tuple'>), and +16 used there returns the 0 which is also present in the consts tuple ||
||yep! i expected either you or <class 'cereal'> to get this very quickly, and you did not disappoint lol||
here's a cookie 🍪
haha, yea frame trickery is fun, i've used it for some really cursed stuff. Thanks for the cookie
i dont get frames
Yeah i wish there was a way to learn things. too bad there isn't
!e py (_______:=__builtins__.__dir__().__len__(),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(_______.__floordiv__(_______.__floordiv__(__name__.__dir__().__len__()).__add__(_______.__floordiv__(__name__.__dir__().__len__()).__add__(_______.__floordiv__(__name__.__dir__().__len__()).__add__(_______.__floordiv__(__name__.__dir__().__len__()))))).__add__(_______.__floordiv__(__name__.__dir__().__len__())).__add__(_______.__floordiv__(__name__.__dir__().__len__())).__add__(_______.__floordiv__(__name__.__dir__().__len__()))))).__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))((_:=_______.__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),____:=_.__add__(_),___:=____.__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__add__(_).__lshift__(___.__add__(_)).__sub__(___.__add__(_).__add__(_))))().__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(_______.__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(____))),[_.__lshift__(___.__lshift__(_)).__add__(_.__lshift__(___)), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__lshift__(___.__add__(_).__add__(_)).__add__(___.__lshift__(_.__add__(_))),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(___),_______,_______.__sub__(___.__lshift__(_)), __.__sub__(___.__add__(_).__mul__(___.__add__(___).__add__(_))),_.__lshift__(___.__add__(_).__add__(_)).__add__(_)]))).__getitem__(_.__sub__(____)))
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, world!
@brittle olive
nice
can u make a cross compiler that converts brainfuck code into this mess?
no
actually
pretty weak to say no as an intermediate person
there was a reason i said actually
whats that?
new side project acquired
ill work on it later
!remind 1h 45m
Sorry, you can only do that in #bot-commands!
fuc-
!remindme 35h finish the deobfuscator and stop worrying about the performance impact
Sorry, you can only do that in #bot-commands!
SyntaxError: invalid syntax. Perhaps you forgot a comma?
uwhguurwghuirhhrituwghuiwgrh
upeosiufgoawgbouaygefougaeoufgvawoei
i have the necessity to learn how this works
maths, and __builtins__.__getattribute__
naming stuff _ is just to make things worse right?
oh shit
only works with +, >, <, and -
stupy lol
how to use:
1: copy paste that in
2: before the code, add your brainfuck code with a variable bf
and , and .
so everything except for loops basically
what about stupy to brainfuck
haha
Does anyone know how to fishook the elipsis?
!e
import fishhook
@fishhook.cls(...)
def __add__(a, b):
return b
print(... + 2)
@turbid dragon :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | @fishhook.cls(...)
004 | ^^^^^^^^^^^^
005 | AttributeError: module 'fishhook' has no attribute 'cls'
!e
import fishhook
@fishhook.hook(...)
def __add__(a, b):
return b
print(... + 2)
@turbid dragon :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | @fishhook.hook(...)
004 | ^^^^^^^^^^^^^^^^^^
005 | File "/snekbox/user_base/lib/python3.12/site-packages/fishhook/fishhook.py", line 322, in wrapper
006 | orig_val = vars(cls).get(name, NULL)
007 | ^^^^^^^^^
008 | TypeError: vars() argument must have __dict__ attribute
!e ```py
import fishhook
@fishhook.hook(type(...))
def add(a, b):
return b
print(... + 2)```
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
2
... is an instance of the Ellipsis type (so is Ellipsis) so you need to make sure to hook the type of it
... why not?
both are turing complete and both languages are machine-parseable
because reasons
what are the reasons
theres a lot more stuff done with pyton
wdym
i cant just translate any phyton code into brainfuck
python has like 1490823408139081 functions/operators adn siht
you dont have to though
brainfuk has like 6
you have that backwards
the goal was to make a converter of bf to python
not the other way around
silly goose
im a bit (almost 5 months) late but i have an idea for cpython
a switch/case for integers which compiles to a jump table in the bytecode
basically, switch/case from c but in python :3
idk how much work that would be so feel free to ignore me if it would be a lot of work
but it would be cool if implemented
you were 5 months late
5 months from then is in 15 days
you were 4 and a half months late
(almost 5 months)
yes, im aware lol
!e not space-optimized at all ```py
def bf2py(s: str, memsize: int = 2**15) -> str:
i = 0
r = []
a = lambda s:r.extend([i*' '+s])
a('i=0')
a(f'm=[0]*{memsize}')
for c in s:
match c:
case'>':a('i+=1')
case'<':a('i-=1')
case'+':a('m[i]+=1')
case'-':a('m[i]-=1')
case'.':a('print(end=chr(m[i]))')
case',':a('m[i]=ord(import("sys").stdin.read(1))')
case'[':a('while m[i]:');i+=1
case']':i-=1
case _:...
return '\n'.join(r)
helloworld = '''
from wikipedia
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++
.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.
------.--------.>+.>.
'''
exec(bf2py(helloworld))
@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello World!
!e this one supports cell wrapping, so it can successfully run all hello-worlds from esolangs: ```py
def bf2py(
s: str,
memsize: int = 2**15,
# if not zero, allows wrapping: (maxval-1)+1 will wrap back to 0
# otherwise cell will contain integers of any sign and size
maxval: int = 0,
) -> str:
i = 0
r = []
a = lambda s:r.extend([i*' '4+s])
a('i=0')
a(f'm=[0]{memsize}')
for c in s:
match c:
case'>':a('i+=1')
case'<':a('i-=1')
case'+':a('m[i]+=1'+f';m[i]%={maxval}'(maxval!=0))
case'-':a('m[i]-=1'+f';m[i]%={maxval}'(maxval!=0))
case'.':a('print(end=chr(m[i]))')
case',':a('m[i]=ord(import("sys").stdin.read(1))')
case'[':a('while m[i]:');i+=1
case']':i-=1
case _:...
return '\n'.join(r)
helloworld = '''
+[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++[.>]<<<<.+++.------.<<-.>>>>+.
'''
print(bf2py(helloworld, maxval=256))
exec(bf2py(helloworld, maxval=256))
@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | i=0
002 | m=[0]*32768
003 | m[i]+=1;m[i]%=256
004 | while m[i]:
005 | m[i]-=1;m[i]%=256
006 | m[i]-=1;m[i]%=256
007 | i+=1
008 | m[i]-=1;m[i]%=256
009 | while m[i]:
010 | i+=1
011 | i+=1
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/E3H4EMKAP7GLN2OCFXCZYZA4GQ
it is funny, but if cells are bounded, it doesnt really matter if they can hold negative numbers or not, because the only check that bf can do is to check if number is a zero, and in all situations signed and unsigned cells behave exactly the same (the only exception is . which will fail on negative inputs)
also, memory pointer wrapping is available for free, python does it on lists by default
you can hoist f';m[i]%={maxval}'*(maxval!=0) out of the loop :3
also __import__("sys").stdin
yeah, there is a lot
minor nitpicky optimisations that are negligible except for with very large programs
def bf2py(
s: str,
memsize: int = 2**15,
# if not zero, allows wrapping: (maxval-1)+1 will wrap back to 0
# otherwise cell will contain integers of any sign and size
maxval: int = 0,
) -> str:
i = 0
r = [
'i=0',
f'm=[0]*{memsize}',
'C=__import__("sys").stdin.read' # precomputed
]
a = lambda s:r.extend([i*' '*4+s])
f = f';m[i]%={maxval}' * (maxval != 0)
P = f'm[i]+=1{f}' # these are precomputed now
M = f'm[i]-=1{f}' # these are precomputed now
for c in s:
match c:
case'>':a('i+=1')
case'<':a('i-=1')
case'+':a(P)
case'-':a(M)
case'.':a('print(end=chr(m[i]))')
case',':a('m[i]=ord(C(1))')
case'[':a('while m[i]:');i+=1
case']':i-=1
case _:...
return '\n'.join(r)
next goal is to make optimizer for this
sequences of + and - can be folded
so can sequences of > and <
sequences of , can be slightly optimised by only ever storing the last input
actially there is a lot more things you can do
and ofc everything up to the first input can be precalculated
i wasn't done listing stuff lol
im just writing what appears in my mind as it appears
[+] or [-] is a common way to do m[i]=0
[A][B] is just [A], it is used to make a comment that uses brainfuck special characters
[->+<] can be turned into m[i+1]=m[i];m[i]=0;
you could also do similar for a copier
sequences of ,> to read input can be optimised into a larger read call
the issue is with the while thing
how do you obfuscate that
wdym
hwo doy ou obfuscate the while
also case']':i-=1 ] doesnt actually subrtact anything
wahts the i-=1 tehen
that function is not executing bf
it is generating python from bf
(hence the name bf2py)
im guessing the i stands for indentation level (since that's how it's used), but you'd have to ask @fleet bridge since they're the one who made it
correct
well, there you go then glasstile
i might try to do that
since match/case doesn't make a jump table i figured it'd be an interesting idea
also make python compiled pls uwu ty (/j)
is compiled alweady though??
pls make python compile into machine code pls uwu ty
and add simd instructions
thats already a thing
without using Python.h
?
thats for the python api
which is a different thing
you silly goose
im talking about codon :3
no
Codon is not a drop-in replacement for CPython. There are some aspects of Python that are not suitable for static compilation — we don't support these in Codon.
I mean, that's not really python, that's more a language that looks like python
its a subset of python
Kinda like numba
it's python in the same way that rpython is python -- it's a strict subset of python
big saf
It's not even a subset, it has new syntax for parallelism etc, says so in the readme
a supersubset
Calling C/C++ from Codon is quite easy with from C import, but Codon can also be called from C/C++ code. To make a Codon function externally visible, simply annotate it with @export:
okay um this is isck
shhhh
i need this in cpython
what i meant was that if you just use it in the same way that you'd use python, it's a strict subset
there are also features to take advantage of hardware parallelism and other such things
a few typing differences
etc.
should i allow putting variables as cases
i dont think you would be able to make a jump table at compile time then?
or at the very least, it gets more complicated
it'd be cool if you could without significant runtime overhead
There is a great thread in #1051603408597024828 about SIMD-like operations using long integers:
https://discord.com/channels/267624335836053506/1192626715307020359
I believe someone in this channel might find it interesting
Not sure if this is exactly the right channel for it, but...
Is there anywhere in the official python docs where I can find information about how instantiating an object involves calling its type?
Basically I'm trying to show that:
from functools import partial
class Foo:
def __init__(self, data: str):
self.data = data
FooBar = partial(Foo, data="bar")
my_foobar = FooBar()
assert my_foobar.data == "bar"
I can obviously experimentally show that this works! And intuitively/experimentally, I know that running Foo(data="bar") is itself equivalent to Foo.__call__(data="bar")... but I'd love something in the docs to point to when I talk about it.
Maybe it's a pure grammar thing?
Foo(x) = Foo.__call__(x) = (if Foo.__call__ is not defined) Foo.__new__(x) = Foo.__init__(super().__new__(Foo), x)
Foo(x) is not equivalent to Foo.__call__(x), but to type(Foo).__call__(Foo, x)
Are you looking for this? https://docs.python.org/3/reference/datamodel.html#classes
I looked though that page (admittedly, I could've missed something), and I didn't see anything explicit about the exact thing in your other message: #esoteric-python message
All special methods are looked up through their class: https://docs.python.org/3/reference/datamodel.html#special-method-names
cpython compiles python code to machine code already, thats how it runs, it just does a lot of this work at the moment that you run the code and not before this.
If you want python code which compiles ahead of time then cython might be worth checking out, there is also ongoing work to make cpython ( important destinction, not to be confused with cython) analyse code during runtime to speed up future execution, known as just in time compilation.
you are mistaken
cpython is not compiling code to machine code: it compiles code to bytecode and then executes it in VM
technically all code is interpreted
okay i meant that it reaches it eventually, what is the vm doing then?
and is that part of the cpython project?
everything eventually is executed by machine code, so saying that doesnt really give a lot of useful information
it was in response to a request that python be made to be converted to machine code
i know about bytecode
so in response to that, it does already compile into machine code, see the original comment on how to compile ahead of time
it does already compile into machine code
cpython itself is compiled to machine code, but it is not compiling python code to machine code
if you consider the vm as not a part of cpython then yes
i dont know where the bounds lie on that, do you?
cpython is a VM for python, wdym
it compiles python code to bytecode, then executes bytecode
there is no compilation to machine code happening
the instructions must be fed to the cpu at some point, when does this occur?, am i mistaken that machine code is a nescessary step to feed instructions to the cpu. What is generating the op code sequence for the cpu?
interpretation != compilation
cpython is an interpreter, it interprets bytecode instructions, not compiles them
ok but how do these insturctions reach the cpu?
cpu it only executing cpython's code, it never gets a chance to execute pure python in any form
cpu runs cpython, cpython runs python
looks like you have no idea what "interpreter" means
so the python code is translated into instructions for the cpu
it is not
yes by cpython like you just said
it is not translating nor compiling bytecode to machine code
it interprets them by itself
cpython runs, cpython observes python code, cpython sends instructions to cpu
translation
words are not so rigid
cpython sends instructions to cpu
nope, cpython is already running on cpu, there is no machine code generation happening at all
ok but it is the same thing by a different mechanism, the op code sequence is still sent to the cpu as per the instructions of the python code
every bytecode instruction is already implemented in cpython
cpython just performs them in different order for different python code
cpu executes already compiled machine code that is stored in executable on your hard drive, it just happens that this code contains implementation of bytecode instructions
there is nothing that decides which instructions to "send" to cpu
cpu executed code as usual
so the bytecode instruction is associated with a piece of c code?
as usual, in other words a process which could be described as sending
the myriad of different ways to get a cpu to do things
there is only one way to get a cpu to do something: point it to some machine code
there is no JIT happening in cpython (yet), so the only source of machine code is compiled executable binary
you are picking me up on the definition of compile, words are loose and there is nothing more to be said on this
i saw a video of someone demonstrating a cpython jit using llvm
any jit is not a part of cpython (yet), so it is not really related to the dicsussion
you are being un nice, i appreciate discussion about how cpython works
he’s telling you what is and what isnt part of cpython
cpython does not translate python code into executable code for the cpu, it does things itself based on what the python code looks like
an analogy: the python code is the ikea manual for building something. the cpython interpreter doesnt make the manual build it itself, it builds the thing based on the manual
not sure if this is the right place to ask. how do i access a class through the class's methods? something like this
def decorator(f):
print(f.__class__.bar)
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
return wrapper
class Foo:
bar = "baz"
@staticmethod
@decorator
def asd():
pass
At the point that decorator is called, the class doesn't exist
so you really don't get to
You can get at it in the wrapper if it were a (class)method
but the class is only created after the class block exits
A perhaps more useful option may be returning a descriptor, which lets you run code right after the class is crafted via __set_name__
!e
[(_x_B:=lambda A____,_B:(z:=(complex.__call__(*[9,2])-3j)).real%4),(AAAAA:=lambda __,_:(~int(_x_B(__,_)))),(GGENN:=lambda *a:-1)]
@eval('__import__((CC:="fishhook")).hook.cls(type(eval("[None,...][1]")))')
class ZZZ_:__sub__ = AAAAA;__mod__=lambda *a:-1;__add__ = _x_B;__mul__ = _x_B;__truediv__ = lambda *A:1j;__gt__=lambda *_:0;imag=None;__matmul__=lambda xX,Xx:3+3-3;__xor__=lambda Zz,zZ:int(False)>True;__ge__=GGENN;
def p(*x:__import__("typing").Any,_={}):
[*(__UU9:=list(),f:=lambda m:[a is Ellipsis or a>=1 for a in m])]
for e,z in (ne:=enumerate)(x):
if(z.imag or z>2):__UU9=[*__UU9,f(list(x[(tt:=len(sum(__UU9,start=[])))+len(list(filter(bool,__UU9))) if(__UU9)else 0:e])),*list(filter(lambda m:isinstance(m,list),[None if not(not z.imag and z>2)else[]]))]
[(YZ_A:=[[]]),(CC_:="ETIANMSURWDKGOHVF L PJBXCYZQ")]
for LLZZ_ in __UU9:
YZ_A.append([])
if(LLZZ_ ==[]):continue
[(p:=0),YZ_A.pop()]
for zxb in(LLZZ_ ):p=2*p+(1 if zxb is False else 0)
YZ_A[-1].append(CC_[(2**(len(LLZZ_ ))-1+p)-1])
return(' ' .join([''.join(__) for __ in YZ_A]))
print(p(...,...,...*...,...==...,.../...,...,.../...,...,...-...,...+...,...+...,.../...,...,...-...,...+...,...+...,.../...,...-...,...-...,...-...,...@...,...*...,...-...,...-...,.../...,...!=...,...<=...,...%...,.../...,...,...-...,...,.../...,...,...-...,...+...,...+...,.../...,...-...,...,...*...,.../...))
@turbid dragon :white_check_mark: Your 3.12 eval job has completed with return code 0.
HELLO WORLD
Would you guys have any ideas on how I can obfuscate the constant ETIANMSURWDKGOHVF L PJBXCYZQ?
So far I've managed to make the first 9 chars 3 quadratic sequences lol
Does anyone recognise ETIANMSURWDKGOHVF L PJBXCYZQ?
my point was that this is not opposed to what i was saying, in doing the latter it has effectively done the former
not really, no
it has "executed" the python code, yes
it didnt transpile it to code the cpu can understand
both have the same outcome, but they arrive there in different ways
ok that is now where i started stating about how it is more of a linguistic difference
its... not
i understand that there isnt a singular data representation of the python code as a sequence of instructions
it.... is
transpiling to cpu code != interpreting the code yourself
👆
*direct cpu instructions
good now rewrite this with proper format and following all rules
nuh
OPEN CHALLENGE FOR PYCORD:
what does False == False in [False] evaluate to
||False == False and False in [False], so True overall||
||picked up on that surprisingly fast, i assume you know about the absolute fuckshittery that is that syntax||
Yup
nuh
no lol
this is a well known feature, everybody here knows that
at least i hope so
morse code
you are mistaken
the linguistic difference here is that the words you're using have different definitions than the ones others are using, which causes what you're saying to be semantically different. what you're saying about cpython is incorrect
i didnt
and i wrote a whole ass assembler for this language
also, "feature"
it for sure is not a good one
Is there a way to create a class of fishhook.hook.cls without having to use the decorator
!e
[(_x_B:=lambda A____,_B:(z:=(complex.__call__(*[9,2])-3j)).real%4),(AAAAA:=lambda __,_:(~int(_x_B(__,_)))),(GGENN:=lambda *a:-1)]
@eval('__import__((CC:="fishhook")).hook.cls(type(eval("[None,...][1]")))')
class ZZZ_:__sub__ = AAAAA;__mod__=lambda *a:-1;__add__ = _x_B;__mul__ = _x_B;__truediv__ = lambda *A:1j;__gt__=lambda *_:0;imag=None;__matmul__=lambda xX,Xx:3+3-3;__xor__=lambda Zz,zZ:int(False)>True;__ge__=GGENN;
def p(*x:__import__("typing").Any,_={}):
[*(__UU9:=list(),f:=lambda m:[a is Ellipsis or a>=1 for a in m])]
for e,z in (ne:=enumerate)(x):
if(z.imag or z>2):__UU9=[*__UU9,f(list(x[(tt:=len(sum(__UU9,start=[])))+len(list(filter(bool,__UU9))) if(__UU9)else 0:e])),*list(filter(lambda m:isinstance(m,list),[None if not(not z.imag and z>2)else[]]))]
[(YZ_A:=[[]]),(CC_:="ETIANMSURWDKGOHVF L PJBXCYZQ")]
for LLZZ_ in __UU9:
YZ_A.append([])
if(LLZZ_ ==[]):continue
[(p:=0),YZ_A.pop()]
for zxb in(LLZZ_ ):p=2*p+(1 if zxb is False else 0)
YZ_A[-1].append(CC_[(2**(len(LLZZ_ ))-1+p)-1])
return(' ' .join([''.join(__) for __ in YZ_A]))
print(p(...,...,...*...,...==...,.../...,...,.../...,...,...-...,...+...,...+...,.../...,...,...-...,...+...,...+...,.../...,...-...,...-...,...-...,...@...,...*...,...-...,...-...,.../...,...!=...,...<=...,...%...,.../...,...,...-...,...,.../...,...,...-...,...+...,...+...,.../...,...-...,...,...*...,.../...))
@turbid dragon :white_check_mark: Your 3.12 eval job has completed with return code 0.
HELLO WORLD
I don't want @eval('__import__((CC:="fishhook")).hook.cls(type(eval("[None,...][1]")))') so obvious
Some sort of x = type(...) perhaps
class type(object)``````py
class type(name, bases, dict, **kwds)```
With one argument, return the type of an *object*. The return value is a type object and generally the same object as returned by [`object.__class__`](https://docs.python.org/3/library/stdtypes.html#instance.__class__).
The [`isinstance()`](https://docs.python.org/3/library/functions.html#isinstance) built-in function is recommended for testing the type of an object, because it takes subclasses into account.
Awesome, thanks
!e
import fishhook
class ABC:
def __add__(self, z): return 10
fishhook.hook.cls(ABC, type(...))
print(... + ...)
@turbid dragon :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 7, in <module>
003 | print(... + ...)
004 | ~~~~^~~~~
005 | TypeError: unsupported operand type(s) for +: 'ellipsis' and 'ellipsis'
!e
import fishhook
@fishhook.hook.cls(type(...))
class ABC:
def __add__(self, z): return 10
print(... + ...)
@turbid dragon :white_check_mark: Your 3.12 eval job has completed with return code 0.
10
oh in this case i think it'd be fishhook.hook.cls(type(...))(ABC)
the method you call in the decorator returns a method python invokes with the class
!e ```py
import fishhook
class ABC:
def add(self, z): return 10
fishhook.hook.cls(type(...))(ABC)
print(... + ...)
@vast wave :white_check_mark: Your 3.12 eval job has completed with return code 0.
10
what is the truth?
cpython is run by the cpu
python is run by cpython
it doesn't convert python to machine code (yet)
What better place to check if a syntax highlighter works than at #esoteric-python
discord's definitely doesnt
✅
It feels immaculate
using the same color for keywords, functions, and the decorator at (@...) symbol is a bit unsettling
although i thought classes were supposed to have a color
same color for keywords and functions?
if, return
ellipses is a bultin so its overriden but i gave yellow
in too
well those are keywords, no?
yep
so they have the same color
how come they're not purple
wait where
is it because the \w+\( match does a false positive
all the red-underlined here
cool
as for @ usually vsc highlights that too, but in a different color imo it looks cool to have the same color
but logically it is indeed kinda wrong
i understand that already, although i think explaining this multiple times is a waste of peoples time
wtf is this madness
I think its quite beautiful if you ask me
I havent finished it yet
if you understood it already, then why did you say something that contradicts it
For real obfuscation, define aliases for all builtin identifiers and string literals with sequences of "_" and "{MIDDLE DOT}" (Unicode MIDDLE DOT is a legitimate identifier body character). Like:
>>> _·, _··, _··· = list, range, enumerate
>>> _·(_···(_··(5),1))
[(1, 0), (2, 1), (3, 2), (4, 3), (5, 4)]
Can only do identifiers though, not keywords.
there’s so much more trolling one can do with unicode
It turns out that MIDDLE DOT is a low number, 00b7, so you are barely pushing the Unicode envelope. But yes, adding Unicode to the mix, 𝐭𝕙𝕖 𝒔ₖ𝖞 is 𝙩𝗵𝚎 𝖑iⅿ𝖎𝗍.
i dont even mean just unicode identifiers, i mean the fact that the python parser expands certain unicode characters into their ascii equivalent, which means you can reference “wxy” with “(certain wonky character for w)xy” without there being errors at runtime, and without defining “(certain wonky character for w)xy”
i forgot the exact characters but they exist
most tooling has no idea this works, and pycharm for example will scream and shit and piss about (certain wonky character for w)xy not existing
Yeah, I wrote a website to do that: https://ptmcg.pythonanywhere.com/font_mixer
i'll tell you a little cursed secret 
since middle dot (among some other chars like ó and μ and ñ etc) is part of the latin-1 alphabet,
and since these chars are valid identifier continuation letters,
and since most file browsers expect python source files to be utf-8,
and since using the # coding: unicode-escape defaults to latin-1 with extra escapes for unicode characters,
and since python can introspect variable names,
you can write a python source file that looks like it executes a certain program when rendered in utf-8, but actually executes a different program that you can only see in latin-1
:3
as an example:
# coding: unicode-escape
class 鷵: pass
print(鷵) # <class '__main__.é·μ'>
# now what's that class name?!
you can do a lot of very sneaky business, although it all falls apart by looking at the coding declaration
this is pretty cool
the underscore gives it away a bit shame it cant just be the unicode sym
i tried it on my code and checked if tools still work, here are results:
pyright works well, even does LSP stuff correctly (and it normalizes names internally)
mypy works
black works
ruff freaks out
- ruff error message
- pyright on-hover information window
Hi, what's esoteric pythonb
thats cool
python but funny
possible to make this any shorter?
o=[]
x=5000**2
s=[1]*x```
x=5000**2;*o,*s=[1]*x
o=[];x=5000**2;s=[1]*x
nvm wait
i don't think you can
x=5000**2;*o,s=[1]*x,
``` this maybe
why do 1 and 2 produce the same output but 3 fucks up
if all(i<j for i,j in zip(str(p),str(p)[1:])):print(p)
all(i<j for i,j in zip(str(p),str(p)[1:]))and 1 and print(p)
1*all(i<j for i,j in zip(str(p),str(p)[1:]))or print(p)```
these are the conditions ik they have to meet for 2 and 3 to work but i cant see any side effects that are caused by 3
why not all(...)and print(p)?
all(...)or print(p) would be if not all(...): print(p)
didnt even think of it
what would be the best way to hide
__builtins__.__dict__["getattr"](
__builtins__,
"eval"
)
this should do the same thing
exec(bytes('彟畢汩楴獮彟弮摟捩彴孟朢瑥瑡牴崢弨扟極瑬湩彳ⱟ∠癥污⤢','u16')[2:])```
not efficient but
¯_(ツ)_/¯
althought I forgot to hide print and the string lol
Why does this return True, True
a, b = (lambda x: (x, x))(all(i for i in range(-int(),int(int().__sub__(~int())**(~int())*-~int()), ~-int())))
and this False, False
a, b = (lambda x: (x, x))(all(i for i in range(-int(),int(int().__sub__(~int())**(~int())*-~int()), -~int())))
all(i for i in range(-int(),int(int().__sub__(~int())**(~int())*-~int()), ~-int()))
all(i for i in range(0,int(0 .__sub__(~0)**(~0)*-~0), ~-0))
all(i for i in range(0,int(0 .__sub__(-1)**(-1)*1), -1))
all(i for i in range(0,int(1**(-1)), -1))
all(i for i in range(0,1,-1))
all([])
True
and then the lambda x: (x, x) just turns that into (True, True)
for the False, False one, it has -~int() instead of ~-int() for the step size, which is 1 and not -1, so we get all([0]) instead of all(), which is False
Thank you Stickie
1+1 or -~1? 😶🌫️
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~True Brrr 🤣
But Srsly Performence Wise Which Is Better? 1+1 -> 1 Opration And -~1 -> 2? 😶🌫️
1+1
@muted scaffold Do You Play CTFs? Python Jail Escapes Specifically
they both optimize to the same thing anyway since they're both constants
So Like n % 2 And n & 1?
nope.
why?
did you publish the dundeobfuscator somewhere.
I actually just started with python recently, I have never heard of python jail escapes sorry.
Then I Guess You Actually Write For Fun 
Yes.
thank you.
@quartz wave
hello i made a thing with ipython and pygame that idk if makes sense
?
I reported you.
huh
Sorry
to where
to ur mom
I have no reason
i see
!e py __builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),____:=_.__add__(_),___:=____.__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__add__(_).__lshift__(___.__add__(_)).__sub__(___.__add__(_).__add__(_))))().__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(____))),[__.__sub__(____.__lshift__(___).__add__(____.__lshift__(____))), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(___),_______,_______.__sub__(___.__lshift__(_)), __.__sub__(___.__add__(_).__mul__(___.__add__(___).__add__(_)))]))).__getitem__(_.__sub__(____)))
@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
hello world
I like you and your projects.
thanks
why only dunder methods
love you bro ❤️
u too /p
reasons beyond your (and my) understanding
I also use alot of dunder methods, althought not everything is dunder methods
🥺
everything is dunder
No I mean
Everything here is dunder methods
wtf is /p
e v e r y t h i n g
And exec -> print results in seeing the content
!e py print(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),____:=_.__add__(_),___:=____.__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__add__(_).__lshift__(___.__add__(_)).__sub__(___.__add__(_).__add__(_))))().__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(____))),[__.__sub__(____.__lshift__(___).__add__(____.__lshift__(____))), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(___),_______,_______.__sub__(___.__lshift__(_)), __.__sub__(___.__add__(_).__mul__(___.__add__(___).__add__(_)))]))).__getitem__(_.__sub__(____))))
@muted scaffold :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | hello world
002 | None
what
🙂✌🏻
platonic tone tag
what's platonic tone tag
equivalent of "as a friend"
🥺
that means he loves you platonically
Awesome
internetters discovering the randomest words ever and making it a tone indicator
Well
oh
it's the same piece i deobfuscated before
Yes
Can you try to deobfuscate mine later.
deobfsucate hwat
My code
send
my deobfuscator can't deobfuscate my creation well :(
;o
hi
show your creation
This is extremely unperformative
!timeit
print(builtins.getattribute(builtins.dir().getitem(builtins.dir().len().floordiv(builtins.dir().len().floordiv(name.dir().len()).add(builtins.dir().len().floordiv(name.dir().len()).add(builtins.dir().len().floordiv(name.dir().len()).add(builtins.dir().len().floordiv(name.dir().len()))))).add(builtins.dir().len().floordiv(name.dir().len())).add(builtins.dir().len().floordiv(name.dir().len())).add(builtins.dir().len().floordiv(name.dir().len()))))((:=builtins.dir().len().floordiv(name.dir().len()),__:=.add().lshift(.add().add().lshift()),:=.add(),:=.add(),:=.sub(.add().add().lshift(.add())),:=__.sub(.add().lshift().sub(.add())),builtins.getattribute(builtins.dir().getitem(.add().add().lshift(.add()).sub(.add().add())))().getattribute(name.dir().getitem(.lshift()))(builtins.getattribute(builtins.dir().getitem(.add().lshift(.add()).add(.add())))(builtins.getattribute(builtins.dir().getitem(builtins.dir().len().floordiv(name.dir().len()).lshift(.lshift(.add())).sub())),[__.sub(.lshift().add(.lshift())), .sub(.add().lshift()).add(), _____, _____,.sub(),.add().lshift(),.sub(.lshift()).sub(), .sub(),,.sub(.lshift()), .sub(.add().mul(.add().add()))]))).getitem(.sub(____))))
@unreal echo :white_check_mark: Your 3.12 timeit job has completed with return code 0.
2000 loops, best of 5: 176 usec per loop
!timeit
print('hello world')
print(None)
@unreal echo :white_check_mark: Your 3.12 timeit job has completed with return code 0.
200000 loops, best of 5: 1.78 usec per loop
of course obfuscations slows the code down lol.
Make a fast obfuscation of anything, not necessarily an output on console, but maybe an algorithm or computing script.
And the obfuscated version should be faster
Where is the benchmarks for this? Honestly dont see how it would make it faster
what
GG ez, transpile to C. I can’t read C code, so it’s obfuscated, and probably faster.
is there a way to make this shorter
r=str(p)
zip(r,r[1:])```
Walrus in the first argument should save the newline
unfortunately i get this: assignment expression cannot be used in a comprehension iterable expression
its in an all()
does this work? ```py
zip(str(p),f"/{p}")
or maybe : instead of /
what does all the code look like?
nope but this does:
zip(f"/{p}",str(p)))```
x=70**4
s=[1]*x
for p in range(2,x):
if s[p]&1:s[p:x:p]=~-x//p*[0];all(i<j for i,j in zip(f"/{p}",str(p)))and print(p)```
nice, close enough
1&s[p]and ...?
oh yeah its an assignment
i dont think ive ever seen that error before i tried working on this problem
It's like doing 1 + x = 2
because expressions can be calculated but not assigned to
Couldn't you do some kinda sorted(r)==[*r] instead of the all()?
i think thats what i originally tried and then code golfing enthusiast gave me that snippet and it was shorter than i could get with sorted
Fairs
Note that if you also want uniqueness that requires a separate condition
Which may be what took so many chars
what do you mean by uniqueness?
oh yeah if you mean should 112345 work it shouldnt
wait what if i use a set instead of a list
ah
it fails then for 31
it doesnt differentiate between ascending and descending
crazy thing is the questions possible in 68
im on 119
and that already seems really low
characters or bytes?
bytes
Assuming I have an array of substrings that that can be found in a larger string, but do not compose the entirety of the larger string i.e. there are parts of the larger string that cannot be found in the array of substrings, is there a way to split my larger string by using the array of substrings so that instead of having a partial array of substrings, I have an array of all the unique substrings that compose the larger string including the substrings
i think an example might help
#ifndef __cplusplus
#include<stdio.h>
#else
#include<iostream>
#endif
#define def int
#define main() main() { a
#define return}
#define print puts
def main():
print("Hello, world!");
return
#if 0
main()
#endif``` (golfed) hello world that works in py, c, cpp
Oh wow
!e ```py
print((((:=(:=().class.base.subclasses().getitem(((____:=(:=().class.itemsize)).add()).mul(_______:=(:=.sub(:=((),).len().invert().neg()))).add(.add()))).dict).getitem((:=().class(builtins.dict).getitem)(.mul(.add())).add((:=loader.module.getitem(:=().len())).add(builtins.repr().getitem(builtins.dict.getitem((.pow().add(.add(:=.invert().neg()))))(_____,.add(_____))))))(:=__.getitem(().class(loader.dict).getitem(:=.invert().neg().invert())).wrapped(,(_____:=loader.doc.getitem)().add(()).add((:=(:=__.mul(:=.neg()))).add()).add((.sub().mul().add())).getattribute((:=().class(loader.name.class.dict).getitem)())(((:=.add()),)))),).mul((.sub())).add((.getattribute(name.getattribute((.add(.add(.add()))))()),))).getitem(.sub())())
@muted scaffold :x: Your 3.12 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((((__:=(________:=().__class__.__base__.__subclasses__().__getitem__(((____:=(__:=().__class__.__itemsize__)).__add__(__)).__mul__(_______:=(__:=__.__sub__(___:=((),).__len__().__invert__().__neg__()))).__add__(__.__add__(__)))).__dict__).__getitem__((______:=().__class__(__builtins__.__dict__).__getitem__)(___.__mul__(____.__add__(___))).__add__((_________:=__loader__.__module__.__getitem__(_____:=().__len__())).__add__(__builtins__.__repr__().__getitem__(__builtins__.__dict__.__getitem__(______(____.__pow__(___).__add__(____.__add__(_____:=_____.__invert__().__neg__()))))(_____,_______.__add__(_____))))))(__________:=__.__getitem__(().__class__(__loader__.__dict__).__getitem__(_:=_____.__invert__().__neg__().__invert__())).__wrapped__(________,(________:=__loader__.__doc__.__getitem__)(____).__add__(________(_____)).__add__((__:=________(______:=____.__mul__(_:=_.__neg__()))).__
... (truncated - too long)
Full output: https://paste.pythondiscord.com/RNAJZHJAKYWLHQ2BFEOT53ZU5E
it kinda only works for 3.11
sure!
heres the original string:
heres the array of substrings
stdio.h is a C++ header also
odam
#import<stdio.h>
#define def int
#define main() main(){a
#define return}
#define print puts
def main():print("Hello, world!");return
#if 0
main()
#endif```
more golf
( section [support.c.headers] of the standard :3 )
if we're golfing here wouldnt main(){a work?
or at least the ) and { together
yes
the spacing in the define can be removed
and I guess #import in place of #include might also work
ok fixed
i dont think this is a thing in C
its not a thing in any of the languages
C++ might get import in the future, but not #import
in python it's a comment, in C and C++ it's an invalid preprocessor directive
last time I tried it could work in C++, just that there's a compiler warning
well uh, that was g++
actually no, im wrong
there's also a version that's a preprocessor directive
ah I see
is a return really necessary there? could even just be a single letter that is expanded to } in C/C++ if I'm not wrong
hang on, we do have python
actually no again
#import is a microsoft extension
import directives are preprocessing directives according to the grammar but they don't start with #
yeah
is it possible to use define on a number?
#bot-commands message
then we can shorten return to a number literal
for future reference, this resolved my problem
i dont think so
answer: no
are there any 2-char names?
we could just use like, abs
saves another byte
#import<stdio.h>
#define def int
#define main() main(){a
#define abs}
#define print puts
def main():print("Hello, world!");abs
#if 0
main()
#endif``` shaving off a few more bytes
i dont really see how more bytes could be shaved
#import<stdio.h>
#define def int
#define main() main(){a
#define abs}
def main():puts("Hello, world!");abs
#if 0
puts=print
main()
#endif```less bytes
but
id
#import<stdio.h>
#define def int
#define main() main(){a
#define print(x) puts(x);}
def main():print("Hello, world!")
if you only care about printing
actually, forgot to call main
#import<stdio.h>
#define def int
#define main()main(){a
#define id}
def main():puts("Hello, world!");id
#if 0
puts=print
main()
#endif
nice!
does this work?```py
#import<stdio.h>
#define def int
#define main() main(){a
#define id}
#define abs
def main():puts("Hello, world!");id
abs//((puts:=print)and main())
#import<stdio.h>
#define def int
#define main() main(){a
#define id}
def main():puts("Hello, world!");id
#define id
id//((puts:=print)and main())
shaved 1 byte
actually 2
there's also a space between main() and main() which I missed
#import<stdio.h>
#define def int
#define main()main(){a
#define id}
def main():puts("Hello, world!");id
#define id
id//(puts:=print,main())
105```py
#import<stdio.h>
#define id
id//print("Hello, world!")
id//"""
int main(){puts("Hello, world!");}
id//"""
nice
we can probably get rid of return type of main but it will only work in older versions of C
hi! i want to try and code in the Shakespeare Programming Language, but i'm having some trouble just figuring out the basic setup. if anyone knows how to get shakespearelang working with pycharm, i'd really appreciate the help
!e ```py
#import<stdio.h>
#define id
id//print("Hello, world!")
id//"""
int main(){puts("Hello, world!");}
id//"""
@fleet bridge :x: Your 3.12 eval job has completed with return code 1.
001 | Hello, world!
002 | Traceback (most recent call last):
003 | File "/home/main.py", line 3, in <module>
004 | id//print("Hello, world!")
005 | ~~^^~~~~~~~~~~~~~~~~~~~~~~
006 | TypeError: unsupported operand type(s) for //: 'builtin_function_or_method' and 'NoneType'
what was supposed to happen
oh wait, it did print hello world
since hello world specification is not standard, i can accept failing program as correct hello world program
does this work? ```py
#import<stdio.h>
#define id
id//print("Hello, world!")//"""
int main(){puts("Hello, world!");}//"""
108 but no error
#import<stdio.h>
#if 0
print("Hello, world!")
"""
#endif
int main(){puts("Hello, world!");}
#if 0
"""
#endif
this looks like 99
this is 108, not 100
make sure to count newlines
!e ```py
print(len(open(file,'rb').read().rpartition(b'#####')[-1].strip()))
import os; os._exit(0)
#import<stdio.h>
#if 0
print("Hello, world!")
"""
#endif
int main(){puts("Hello, world!");}
#if 0
"""
#endif
@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.
108
you might use this :)
put your code after ##### and run it (it has to be valid python code, otherwise it wont work)
yes it should
you could also use + instead of // after the print
84 (with error in python)
#import<stdio.h>
int//print("Hello, world!")+"""
main(){puts("Hello, world!");}//"""
thats cool
i have this, but cant make it work in C, i dont see a way to escape )
this is 106 right now, it uses string "Hello, world!" only once ```py
#include<stdio.h>
#define id
id//print(
#define h
"Hello, world!"
)
#define x int main(){puts(h);}//"""
x
well, solution was pretty easy: ```py
#include<stdio.h>
#define id
id//print(
#define h
"Hello, world!"
)
#define x int main(){puts(h;}//"""
x
still 106
haha that (h;} looks so cursed
yeah
85, no error```py
#include<stdio.h>
#define id(y)int main(){y;}//
puts=print
id(puts("Hello, world!"))
nice
oh wait, im counting #include, not #import
so it is 85-1=84, same as #esoteric-python message, but without error
76, no error```py
#import<stdio.h>
#define print(y)int main(){puts(y);}
print("Hello, world!")
this feels so obvious when i look at it
lmao
Why'd you say ':3'
:3c
#import<stdio.h>
#define print(y)int main(){puts(y);}
#define g<script>alert("Hello, world!")</script>
print("Hello, world!")
mega scuffed html
is <stdio.h> a some sort of weird html tag?
i wonder how browser would respond to tags with . in them
as usual
a dot is a valid tag element
at least firefox didnt instantly complain
how did we not think of that
I know right!
72 ```py
#import<stdio.h>
#define print(y)main(){puts(y);}
print("Hello, world!")
no error in gcc
we're using import so why the fuck not
what doues the define print(y)main(){puts(y);} do?
define a macro print(y) that makes main(){puts(y);} appear in its place (with y substituted) in the code
cool
i was confused at first because there wasnt a space between print(y) and main()...
the wonders of unambiguous syntax elements
it would be illformed C++
why not
#import is neither C nor C++
it's either a GCC extension (and a deprecated one at that) or a microsoft extension, depending on what compiler you use
i dont know about clang since ive never used it, but it's probably there also
they like to be compatible with gcc
not sure if the type hints are correct but the assertions work xD```py
from typing import Type
TYPE: type = type('TYPE', (type,), {'type': type})
type TYPETYPE = Type[TYPE]
type_: TYPETYPE = TYPE.type
assert TYPE.type == type(TYPE)
assert issubclass(type_, type)
hi
Type type type type type type
is there a way to do something like this
class BaseClass:
val = None
def __eq__(self, other: object) -> bool:
return self.val == other
class Test(BaseClass):
val = 123
if Test == 123:
print("asd")
Now the snippet above will not work since i'm not initializing anything, but that's the thing i do not want to initialize them...
maybe a decorator initializing them?
metaclasses!
go on...
!e ```py
class Meta(type):
val = None
def eq(self, other: object) -> bool:
return self.val == other
class Test(metaclass=Meta):
val = 123
if Test == 123:
print("asd")
@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.
asd
:3
danke
that's really intresting though
didn't know such a thing existed
yet another part of python uncovered
@sick hound IIRC there's a great pycon talk by dave beazley (unsurprisingly) about metaclasses
or, yk, dataclasses
how do you not know what a dataclass is
wait no thats not a dataclass
:incoming_envelope: :ok_hand: applied timeout to @sick hound until <t:1705106214:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
from dataclasses import dataclass
@dataclass
class Test:
val: int
def hi(self):
print(self.val)
Test(3).hi() # 3``` its an easier way of making a class with basic `__init__`
its also in stdlib
@sick hound I don't know what you were doing, but spamming is going to get you muted. I'm letting that stick, don't continue once the mute is up.
that doesnt do what they wanted
also, what's the point
.
you can use it to initialize a whole bunch of stuff quickly, like __repr__, __hash__, __eq__, __slots__ and a whole bunch of others tuff
quickly remove a hecck ton of boilerplate
mcoding has a great video on it
I have another interesting problem. Say i have a class that is a event dispatcher. I want to both have a decorator function that registers the function below. And i also want a normal function that takes the function as an argument and registers it.
And last of all i want the both register functions to have same names.
How would i solve this?
i know that there is some overload function
but i don't know about it
can you give an exmaple?
sure
like, what you roughly want to do
yeah i know i just gotta compilie it in my head
clang head.c
class DeviceEventDispatcher:
def __init__(self, device_path: str) -> None:
self._device_path = device_path
self.events = {}
def register_event(self, event: _types._EventType, callback: Callable[[Event], None]) -> None:
self.events[event] = callback
@overload
def register_event(self, event) -> Callable[[], None]:
def decorator(func: Callable[[Event], None]) -> None:
self.events[event] = func
that is how the event dispatcher class looks like
sorry if it's a little messy
but i hope it gets the point across
why not just use *args?
i think i'm cooking, i'll reach out again in a min
i just imported from typing import overload
With this snippet i got the decorator function to work properly and register the function but the other function that is overloaded gives me an error that it needs less arguments
class DeviceEventDispatcher:
def __init__(self, device_path: str) -> None:
self._device_path = device_path
self.events = {}
@overload
def register_event(self, event: _types._EventType, callback: Callable[[Event], None]) -> None:
self.events[event] = callback
def register_event(self, event: _types._EventType) -> Callable[[], None]:
def decorator(func: Callable[[Event], None]) -> None:
self.events[event] = func
return decorator
but then yeah i might need to use *args
though i might need to to key args then
and something with a union too right?
thats not how overload works
here's how you use overload
@overload
def my_function(x: int):
...
@overload
def my_function(x: str):
...
def my_function(x: int | str):
if isinstance(x, str):
do_stuff
else if isinstance(x, int):
do more stuff```
well then i might just be better of doing something with keyword arguments
or what you think?
or wait
i think i undestand
btw does this fit in this channel, is this esoteric enough?
alright i got it working with a union instead
but thanks for helping
!e
class MyClass:
def __init__(self, value):
self.value = value
def __is__(self, other):
return True
obj1 = MyClass(42)
obj2 = MyClass(42)
obj3 = MyClass(99)
print(obj1 is obj2)
print(obj1 is obj3)
@sick hound :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | False
002 | False
What?
my brain has been stuck, why is that not working?
everything should be True, right?
is isnt an operator you can override
not without a lot more work anyway
but lets say that i would like is to work how would you do that, since the two objects i'm comparing are the same class?
it's just that i'm comparing a attribute of the classes
might be a stupid question
You could make a Singleton class, but that's kinda cheating
imma look into it
from typing import Callable, Never
def try_(
try_: Callable[[], None],
except_: BaseException | tuple[BaseException],
except_callback: Callable[[BaseException], None],
else_callback: Callable[[], None] = lambda: None,
finally_callback: Callable[[], None] = lambda: None,
) -> None:
try:
try_()
except except_ as exc:
except_callback(exc)
else:
else_callback()
finally:
finally_callback()
def raise_exc(exc: BaseException | None, context: Never | None | BaseException = Never) -> None:
if exc is not None:
if context is Never:
raise exc
else:
raise exc from context
else:
if context is not Never:
raise TypeError("caller is drunk")
raise
def while_loop(condition: Callable[[], bool], callback: Callable[[], None]) -> None:
while condition():
callback()
# all of those functions were helpers for this thing; i did try to make into a generator, but i dont think you can really yield from a subsubsublambda which is called from 2 functions deep into a very top level function without insane amount of fuckery (like passing into top lambda a generator and than making that generator yield what it is sent in a while loop with a condition callback and yield from *that* generator)
def zip_madness[*I](*iterables: Iterable[I], strict: bool = False) -> list[tuple[*I]]: return (lambda iters, next_, looping_, accum: (while_loop(lambda: looping_[0], lambda: try_(lambda: (next_.__setitem__(0, tuple(next(iter_) for iter_ in iters)), None)[-1], RuntimeError, lambda _: raise_exc(ValueError("some iterators have exhausted before the others"), None) if strict and len(iters) != len(next_) else looping_.__setitem__(0, False), lambda: (accum.append(next_[0]), next_.__setitem__(0, ())))), accum)[-1])([iter(iterable) for iterable in iterables], [()], [True], [])
what am i looking at
"one line"
well the zip_madness is one line
and try_, raise_exc, while_loop are helpers cuz syntax wouldnt allow truly one line otherwise
not an iterator, cuz to return an iterator i would prob need to rewrite entirity of it and i do not want to do that
look, it is one line
exec()
...today at #esoteric-python we're gonna try to turn this horrible multiliner code into one statement
🤮
i mean zip_madness is typed
yeah just one note
it literally crashes type checker
at least pycharm's
like if paste that function into some file
and then do
a = 1
print(a)
after function's definition
it will yell a reference is not defined
btw can you do with statement in a lambda?
btw the code is based on
def zip_[*I](*iterables: Iterable[I], strict: bool = False) -> Generator[tuple[*I], None, None]:
iters = [iter(iterable) for iterable in iterables]
next_: tuple[*I] | tuple[()] = ()
while True:
try:
next_ = tuple(next(iter_) for iter_ in iters)
except RuntimeError:
if strict and len(iters) != len(next_):
raise ValueError("some iterators have exhausted before the others") from None
else:
break
else:
yield next_
next_ = ()
alright we just need a mechanism to raise
are code objects allowed
what code objects?
the use of code objects to do a little trolling
btw i was able to make a oneliner -ish zip, which is also a generator... but wihout strict support
def almost_zip_madness[*I](*iterables: Iterable[I]) -> Generator[tuple[*I], None, None]:
with __import__('contextlib').suppress(StopIteration):yield from (lambda iters: iter(lambda: (lambda next_: tuple(next_))([next(iter_) for iter_ in iters]), None))([iter(iterable) for iterable in iterables])
christ this is the most cursed thing ever
its not
zip_madness is
this one
line -1?
line -1
!e
import dis
e = lambda x:()
e.__code__ = e.__code__.replace(co_code=b"\x97\x00|\x00\x82\x01")
dis.dis(e)
@stark granite :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 3 0 RESUME 0
002 | 2 LOAD_FAST 0 (x)
003 | 4 RAISE_VARARGS 1
funny_throw=(x:=lambda _:(),setattr(x,"__code__",x.__code__.replace(co_code=b"\x97\x00|\x00\x82\x01")))[0]
def lambda_(x):
raise x
?
i mean thats just beyond cursed
yeah-ish
!dis
!e
import dis
dis.dis("""
def lambda_(x):
raise x""")
@stark granite :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0 0 RESUME 0
002 |
003 | 2 2 LOAD_CONST 0 (<code object lambda_ at 0x7f25a02c1960, file "<dis>", line 2>)
004 | 4 MAKE_FUNCTION 0
005 | 6 STORE_NAME 0 (lambda_)
006 | 8 RETURN_CONST 1 (None)
007 |
008 | Disassembly of <code object lambda_ at 0x7f25a02c1960, file "<dis>", line 2>:
009 | 2 0 RESUME 0
010 |
011 | 3 2 LOAD_FAST 0 (x)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/PAW2Z2SQKQEPFSNY6UT2QEHZU4
removing the resume makes it even better lmfao
completely removes the final stack frame of the lambda itself
mega trolled
yeah
funny_throw=(x:=lambda _:(),setattr(x,"__code__",x.__code__.replace(co_code=b"|\x00\x82\x01")))[0] the good throw version
full impl ```py
raise_exc = (O:=object(),lambda e,c=O: setattr(f:=lambda:0,'code',f.code.replace(co_argcount=2,co_nlocals=2,co_varnames=('_^',),co_code=b'\x97\x00|\x00%b\x82%c'%(b'|\x01'(T:=c is not O),1+T)))or f(e,c))[1]
we dont need cause in this case
what is going on
bytecode fuckshit
yeah but
wouldnt c is not _O_ always be false?
because of c=_O_ in the lambda def
anyway,
funny_throw=(setattr(x:=lambda _:0,"__code__",x.__code__.replace(co_code=b"|\x00\x82\x01")),x)[1]
-1
fixed ```py
raise_exc = (O:=object(),lambda e,c=O: setattr(f:=lambda:0,'code',f.code.replace(co_argcount=2,co_nlocals=2,co_varnames=('_^',),co_code=b'\x97\x00%b%b\x82%c'%(b'|\x00'(T2:=(T3:=e is not None) or not (c is O or (e:=TypeError("caller is drunk"))and 0)),b'|\x01'T3(T:=c is not O),T3*T+T2)))or f(e,c))[1]
def zip_madness(*iterables, strict=False): return (lambda iters, next_, looping_, accum: ((lambda c, cc: [*map(cc, iter(lambda: bool(c), 0))])(lambda: looping_[0], lambda: (lambda t,e,E,t2=lambda:None,F=lambda:None:type('',(__import__('contextlib').ContextDecorator,),{'__enter__':int,'__exit__':lambda s,*a:(isinstance(a[1], e) and [E(a[1])],F())[0]})()(lambda:(t(),t2()))())(lambda: (next_.__setitem__(0, tuple(next(iter_) for iter_ in iters)), None)[-1], RuntimeError, lambda _: (_O_:=object(),lambda e,c=_O_: setattr(f:=lambda:0,'__code__',f.__code__.replace(co_argcount=2,co_nlocals=2,co_varnames=(*'_^',),co_code=b'\x97\x00%b%b\x82%c'%(b'|\x00'*(T2:=(T3:=e is not None) or not (c is _O_ or (e:=TypeError("caller is drunk"))and 0)),b'|\x01'*T3*(T:=c is not _O_),T3*T+T2)))or f(e,c))[1](ValueError("some iterators have exhausted before the others"), None) if strict and len(iters) != len(next_) else looping_.__setitem__(0, False), lambda: (accum.append(next_[0]), next_.__setitem__(0, ())))), accum)[-1])([iter(iterable) for iterable in iterables], [()], [True], [])
uh
don't mind if it's not highlighted in your side of the screen
:3
uh oh i got an error
uh oh it's caused by what i did
what
how tf does it do with statement
also naming variables accordingly would be nice :3
uh oh it causes an infinite loop
oh no
why oneliners break pycharm
It broke discord as well
lolmao
Rip
any idea how to golf this
its bothered me for so long that 137 is possible and im stuck on 148 where it just seems like nothing can be changed
import sys
for a in sys.argv[1:]:[print(f'{i:08x}: {(s:=a[i:i+16]).encode().hex(" ",-2):<41}'+s.replace(*'\n.'))for i in range(0,len(a),16)];print()```
no idea where the save could even be
whats the input and output?
!e
import sys
sys.argv.append("""In mathematics and computing, the hexadecimal (also base 16 or simply hex)
numeral system is a positional numeral system that represents numbers using a
radix (base) of 16. Unlike the decimal system representing numbers using 10
symbols, hexadecimal uses 16 distinct symbols, most often the symbols "0"-"9"
to represent values 0 to 9, and "A"-"F" (or alternatively "a"-"f") to represent
values from 10 to 15.""")
for a in sys.argv[1:]:[print(f'{i:08x}: {(s:=a[i:i+16]).encode().hex(" ",-2):<41}'+s.replace(*'\n.'))for i in range(0,len(a),16)];print()
@long fulcrum :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 00000000: 496e 206d 6174 6865 6d61 7469 6373 2061 In mathematics a
002 | 00000010: 6e64 2063 6f6d 7075 7469 6e67 2c20 7468 nd computing, th
003 | 00000020: 6520 6865 7861 6465 6369 6d61 6c20 2861 e hexadecimal (a
004 | 00000030: 6c73 6f20 6261 7365 2031 3620 6f72 2073 lso base 16 or s
005 | 00000040: 696d 706c 7920 6865 7829 0a6e 756d 6572 imply hex).numer
006 | 00000050: 616c 2073 7973 7465 6d20 6973 2061 2070 al system is a p
007 | 00000060: 6f73 6974 696f 6e61 6c20 6e75 6d65 7261 ositional numera
008 | 00000070: 6c20 7379 7374 656d 2074 6861 7420 7265 l system that re
009 | 00000080: 7072 6573 656e 7473 206e 756d 6265 7273 presents numbers
010 | 00000090: 2075 7369 6e67 2061 0a72 6164 6978 2028 using a.radix (
011 | 000000a0: 6261 7365 2920 6f66 2031 362e 2055 6e6c base) of 16. Unl
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/HKDXEVAMHXGAOJAAQUKRMROJLY
I FIXED IT
def zip_madness(*iterables, strict=False): return (lambda iters, next_, looping_, accum: ((lambda c, cc: [cc() for _ in iter(lambda: bool(c()), 0)])(lambda: looping_[0], lambda: (lambda t,e,E,t2=lambda:None,F=lambda:None:type('',(__import__('contextlib').ContextDecorator,),{'__enter__':int,'__exit__':lambda s,*a:(isinstance(a[1], e) and [E(a[1])],F())[0]})()(lambda:(t(),t2()))())(lambda: (next_.__setitem__(0, tuple(next(iter_) for iter_ in iters)), None)[-1], RuntimeError, lambda _: (_O_:=object(),lambda e,c=_O_: setattr(f:=lambda:0,'__code__',f.__code__.replace(co_argcount=2,co_nlocals=2,co_varnames=(*'_^',),co_code=b'\x97\x00%b%b\x82%c'%(b'|\x00'*(T2:=(T3:=e is not None) or not (c is _O_ or (e:=TypeError("caller is drunk"))and 0)),b'|\x01'*T3*(T:=c is not _O_),T3*T+T2)))or f(e,c))[1](ValueError("some iterators have exhausted before the others"), None) if strict and len(iters) != len(next_) else looping_.__setitem__(0, False), lambda: (accum.append(next_[0]), next_.__setitem__(0, ())))), accum)[-1])([iter(iterable) for iterable in iterables], [()], [True], [])
fixed naming (n some other stuff) uwu ```py
def zip_madness(iterables, strict=False): return (lambda iters, next_, looping_, accum: ((lambda condition, callback: [callback() for _ in iter(lambda: bool(condition()), False)])(lambda: looping_[0], lambda: (lambda try_, except_, except_callback, else_callback=lambda:None, finally_callback=lambda:None:type('',(import('contextlib').ContextDecorator,),{'enter':int,'exit':lambda s,a:(isinstance(a[1], except_) and [except_callback(a[1])] if a[1] is not None else [else_callback()], finally_callback())[0]})()(try_)())(lambda: (next_.setitem(0, tuple(next(iter_) for iter_ in iters)), None)[-1], RuntimeError, lambda _: (Never:=object(), lambda exc, context=Never: setattr(temp_func := lambda: None, 'code', temp_func.code.replace(co_argcount=2, co_nlocals=2, co_varnames=('_^',), co_code=b'\x97\x00%b%b\x82%c'%(b'|\x00'(T2 := (T3 := exc is not None) or not (c is Never or (exc:=TypeError("caller is drunk")) and False)), b'|\x01'*(T := T3 and context is not Never), T+T2))) or temp_func(exc, context))[1](ValueError("some iterators have exhausted before the others"), None) if strict and len(iters) != len(next_) else looping_.setitem(0, False), lambda: (accum.append(next_[0]), next_.setitem(0, ())))), accum)[-1])([*map(iter, iterables)], [()], [True], [])
true 1 liner noww
is there more than 1 input?
holy python
Discord mobile highlights this but pc doesn't, lol
1b save ```py
import sys
for a in sys.argv[1:]:[print('%08x: %%-41s'%i%(s:=a[i:i+16]).encode().hex(" ",-2)+s.replace(*'\n.'))for i in range(0,len(a),16)];print()
dude
favorite python feature
you can just flat out replace the method code of one method (or even lambda) with another
i did it before and i know its not that useful but its just so inherently funny to me for some reason
where is the general python chat!!! so many channels its confusin
how does this formatting work?
why esoteric python even exists?
import ast
intop=lambda ex: (p:=lambda t:type(t)==ast.Constant and t.value or f"{p(t.left)} {p(t.right)} {c(t.op)}",c:=lambda o: "+-*@/"[ast.__dir__().index(type(o).__name__)-84])[0](ast.parse(ex).body[0].value)
infix to postfix
Probably wont work with parens
funy
did you mean insanely funy?
if there's a place to find a pro in riddles and chalenges, i think it's here
i have a challenge to yall, it's a message in portuguese encoded with my own method of cryptography, someone can reveal the message?
BCBHCCBHCDBFABCCBCCDCGABBCCBCFAFAGCGBCCDAGABCF
is it "Olá Mundo" ?
@stark granite @quartz wave my zip oneline impl (expanded) py zip = lambda *iterables, strict=False, _try=lambda t, *a, f=lambda a:a, e=Exception, **k,:(r:={}).pop( 'r', type( '', (__import__('contextlib').ContextDecorator,), { '__enter__':int, '__exit__':lambda s,*a:isinstance( a[1], e ) and [r.update( r=f(a) )] } )()(t)(*a, **k) ), _raise=lambda i, F:( ()for()in() ).throw( ValueError(f"zip() argument {i+1} is {'shorter' if F else 'longer'} than argument{' 'if i == 1 else 's 1-'}{i}") ), sentinel=object(): ( inner:=lambda iters=[*map(iter,iterables)], I=[0]: (acc:=[]) or _try( lambda:[[acc.append(next(it)) for I[0], it in enumerate(iters)]]and(*acc,), f=lambda exc:[ [ _raise(i,1) if i else [ _raise(i,0) for i, it in enumerate(iters) if _try(next, it, f=lambda a:sentinel, e=StopIteration) is not sentinel ] for i in I if strict ] ] and sentinel, e=StopIteration ) ) and ( V for V in iter(inner, sentinel) ) as far as i have tested it produces the exact same output as standard zip (with the exception of stack traces), uses no bytecode hacks, and should work as far back as 3.8 (i used walruses)
i (ab)use generators ability to raise exceptions using (()for()in()).throw(exc)
!e py (()for()in()).throw(ValueError('tada'))
@rugged sparrow :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | (()for()in()).throw(ValueError('tada'))
004 | File "/home/main.py", line 1, in <genexpr>
005 | (()for()in()).throw(ValueError('tada'))
006 | ValueError: tada
i could golf it further by reducing my old _try impl to only what is needed for zip, but i havent bothered yet
!e funnily enough I also just finished mine, though I do a bit of cheating by not having the value error say the full thing, and execing to raise. py zip_=lambda*iterables,strict=0:(i:=[*map(iter,iterables)])and(b:=object())and __import__("itertools").takewhile(lambda x:all(y is not b for y in x)or strict and exec("raise ValueError"),((*[next(x,b)for x in i],)for _ in iter(int,1))) print([*zip_([1, 2, 3], ["A", "B"],["x", 1,2,3],strict=0)]) for x in zip_([1, 2, 3], ["A", "B"],["x", 1,2,3],strict=1): print(x)
@fleet lintel :x: Your 3.12 eval job has completed with return code 1.
001 | [(1, 'A', 'x'), (2, 'B', 1)]
002 | (1, 'A', 'x')
003 | (2, 'B', 1)
004 | Traceback (most recent call last):
005 | File "/home/main.py", line 3, in <module>
006 | for x in zip_([1, 2, 3], ["A", "B"],["x", 1,2,3],strict=1): print(x)
007 | File "/home/main.py", line 1, in <lambda>
008 | zip_=lambda*iterables,strict=0:(i:=[*map(iter,iterables)])and(b:=object())and __import__("itertools").takewhile(lambda x:all(y is not b for y in x)or strict and exec("raise ValueError"),((*[next(x,b)for x in i],)for _ in iter(int,1)))
009 | ^^^^^^^^^^^^^^^^^^^^^^^^
010 | File "<string>", line 1, in <module>
011 | ValueError
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/5AUEANB7XVCQAWUEFNPHNTDZMY
no
!e fixed a small bug where calling with no iterables would cause an infinite loop ```py
zip = lambda *iterables, strict=False, _try=lambda t, *a, f=lambda a:a, e=Exception, **k,:(r:={}).pop(
'r',
type(
'',
(import('contextlib').ContextDecorator,),
{
'enter':int,
'exit':lambda s,*a:isinstance(
a[1], e
) and [r.update(
r=f(a)
)]
}
)()(t)(*a, **k)
), err=lambda i, F:(
()for()in()
).throw(
ValueError(f"zip() argument {i+1} is {'shorter' if F else 'longer'} than argument{' 'if i == 1 else 's 1-'}{i}")
), sentinel=object(): (
inner:=lambda iters=[*map(iter,iterables)], I=[0]:
(acc:=[]) or _try(
lambda:[[acc.append(next(it)) for I[0], it in enumerate(iters)]]and(*acc,),
f=lambda exc:[
[
err(i,1) if i else [
err(i,0) for i, it in enumerate(iters) if _try(next, it, f=lambda a:sentinel, e=StopIteration) is not sentinel
] for i in I if strict
]
] and sentinel,
e=StopIteration
) if iters else sentinel
) and (
V
for V in iter(inner, sentinel)
)
print(*zip('foo', 'bar-')) # test normal zip (non-strict)
try:
print(*zip('foo', 'bar-', strict=True)) # test strict zip
except ValueError as e:
print('ValueError:', e)
print(tuple(zip())) # test empty zip call
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | ('f', 'b') ('o', 'a') ('o', 'r')
002 | ValueError: zip() argument 2 is longer than argument 1
003 | ()
this is a bit cool, found this while working on my obfuscator
!e
items = [0,1,2,3]
print(items[--1])
print(items[-1])
print(items[1])
@sick hound :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1
002 | 3
003 | 1
vscode shows this as an error but its valid python
!e
items = [0,1,2,3]
print(items[-1-])
@sick hound :x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 2
002 | print(items[-1-])
003 | ^
004 | SyntaxError: invalid syntax
!e
items = [0,1,2,3]
print(items[---1])
@sick hound :white_check_mark: Your 3.12 eval job has completed with return code 0.
3
neat
thats really impressive
gg
!e
import sys
import gc
from functools import wraps
class AccessViolation(Exception):
pass
def private(method):
@wraps(method)
def wrapper(*args, **kwargs):
f = sys._getframe(1)
clsname, *_ = method.__qualname__.partition(".")
try:
other_method = gc.get_referrers(f.f_code)[0]
if not other_method.__qualname__.startswith(f"{clsname}."):
raise AccessViolation("This method is private")
except IndexError:
raise AccessViolation("This method is private") from None
return method(*args, **kwargs)
return wrapper
class Foo:
@private
def bar(self):
print("bar")
def bat(self):
print("<bat>")
self.bar()
print("</bat>")
f = Foo()
print("Allowed:")
f.bat()
print("Forbidden:")
f.bar()
@restive void :x: Your 3.12 eval job has completed with return code 1.
001 | Allowed:
002 | <bat>
003 | bar
004 | </bat>
005 | Forbidden:
006 | Traceback (most recent call last):
007 | File "/home/main.py", line 39, in <module>
008 | f.bar()
009 | File "/home/main.py", line 17, in wrapper
010 | raise AccessViolation("This method is private")
011 | AccessViolation: This method is private
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/V7MMOUKC76T3NY7U7MMYGFYHMU
heh
inspired by https://vxtwitter.com/jarredsumner/status/1746715821144195296, adapted from https://www.youtube.com/watch?v=2f7YKoOU6_g
any place to save chars here?
import sys
m=max
for i in sys.argv[1:]:a,b,c,d,i,j,k,l=map(int,i.split());print(m(0,min(a+c,i+k)-m(a,i))*m(0,min(b+d,j+l)-m(b,j)))```
it calculates the intersection of two squares with inputs given as a string in this format x1 y1 w1 h1 x2 y2 w2 h2
It makes sense that this works, since both + and - can also be unary operators, in addition to binary (in this case meaning one input and two input, instead of bases). Parsing it with ast shows that as the case slice=UnaryOp(op=USub(), operand=UnaryOp(op=USub(), operand=UnaryOp(op=USub(), operand=Constant(value=1)))), while with dis it gets optimized away to just LOAD_CONST 1 (-1). more info on unaries
yeah, just never knew you could notate it this way and have it be valid
also looks like you are decrementing the variable like in c,java, etc
!e
++1
!e
print(++1)
@sick hound :white_check_mark: Your 3.12 eval job has completed with return code 0.
1
zip = lambda *iterables, strict=False:(I:=lambda O=[*map(iter,iterables)],I=[0]:(acc:=[])or(T:=lambda t,f,*a:(r:={}).pop('r',type('',(__import__('contextlib').ContextDecorator,),{'__enter__':int,'__exit__':lambda s,*a:isinstance(a[1],StopIteration)and[f(),r.update(r=S)]})()(t)(*a)))(lambda:[acc.append(next(it))for(I[0],it)in enumerate(O)]and(*acc,),lambda E=lambda i,F:(()for()in()).throw(ValueError(f"zip() argument {i+1} is {'shorter'if(F)else'longer'} than argument{' 'if(i==1)else's 1-'}{i}")):[E(i,1)if(i)else[E(i,0)for(i,M)in enumerate(O)if T(next,lambda:0,M)!=S]for(i)in(I)if strict])if(O)else 0,S:=[].pop)and(V for(V)in iter(I,S))
``` golfed and minified
figured out a trick for making a sentinel value using something shorter than object()
[].pop is shorter and is a unique value, same as the object()
I think I finally got it working, making the error print correctly was such a massive pain, so in the end I gave up and used groupby. Also uses the throw so it's directly comparable. Thank god for itertools, I don't know how I would live without it. I also used the pop thing, that is really smart.```py
zip=lambda*iterables,strict=0:(i:=[*map(iter,iterables)])and(b:=[].pop)and(t:=import("itertools")).takewhile(lambda x:all(v:=[y!=b for y in x])or strict and(()for()in()).throw(ValueError(f"zip() argument {(G:=(g:=[(f,len([g]))for f,g in t.groupby(v)])[0][1])+1} is {['shorter','longer'][g[1][0]]} than argument{[' ','s 1-'][G>1]}{G}")),(([next(x,b)for x in i],)for _ in iter(int,1)))
nice! i ended up pulling from the iterators manually, pretty much shot for shot how the zip builtin works at the C level
rn im revisiting my exception catching code to see if I can get my generalized oneline try/except to be zero imports
Using context lib is such a big brain move, that's why I started with itertools since takewhile doesn't make me have to use stopiteration.
I just realized i can rewrite mine with no imports and do away with the try except code actually
It's funny that doing an extra walrus to use the generator for throw instead is still shorter, even with the list conversion py zip=lambda*iterables,strict=0:(i:=[*map(iter,iterables)])and(b:=[].pop)and (t:=__import__("itertools")).takewhile(lambda x:all(v:=[*(V:=(y!=b for y in x))])or strict and V.throw(ValueError(f"zip() argument {(G:=(g:=[(f,len([*g]))for f,g in t.groupby(v)])[0][1])+1} is {['shorter','longer'][g[1][0]]} than argument{[' ','s 1-'][G>1]}{G}")),((*[next(x,b)for x in i],)for _ in iter(int,1)))
It's also funny that pycharm complains about this [()for()in()] having unsupported syntax, but not this (()for()in())
!e ```py
zip = lambda *iterables, strict=False:(V for(S,E,[*I])in[[object(),lambda i,l:(()for()in()).throw(ValueError(f"zip() argument {i+1} is {l} than argument{[' ','s 1-'][i>1]}{i}")),map(iter,iterables)]]for V in iter(lambda:next([A.append(next(x,S))for x in I if S not in A]and([[E(i,'shorter')if i else[E(i,'longer')for i, x in enumerate(I)if next(x, S)!=S]for i in[A.index(S)]if strict]]and S if S in A else(*A,))if I else S for A in[[]]),S))
print(*zip('foo', 'bar-')) # test normal zip (non-strict)
try:
print(*zip('foo', 'bar-', strict=True)) # test strict zip
except ValueError as e:
print('ValueError:', e)
print(tuple(zip())) # test empty zip call```
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | ('f', 'b') ('o', 'a') ('o', 'r')
002 | ValueError: zip() argument 2 is longer than argument 1
003 | ()
@fleet lintel ^ no imports
zip = lambda *iterables, strict=False: (
V
for sentinel,err,[*iters] in [[
object(),
lambda i, l:(
()for()in()
).throw(ValueError(f"zip() argument {i+1} is {l} than argument{[' ','s 1-'][i>1]}{i}")),
map(iter,iterables)
]]
for V in iter(lambda:
next(
[acc.append(next(it, sentinel)) for it in iters if sentinel not in acc] and (
[[
err(i,'shorter') if i else [
err(i,'longer') for i, it in enumerate(iters) if next(it, sentinel) != sentinel
] for i in [acc.index(sentinel)] if strict
]] and sentinel if sentinel in acc else (*acc,)
) if iters else sentinel
for acc in [[]]
), sentinel
)
)``` expanded and without renamed variables ^
@stark granite @quartz wave thought yall might want to see this ^
just why
is there a reason for going back to object()?
its more clear what it is doing and i forgot to switch it back for the minified one lol
no imports/eval/weird try except code 🙂
i meant like
how me posting a funny "oneliner" got so much attention
i meant second one was oneliner
first impl wasnt really
oh this is all pretty standard for this channel
So it gets around the break problem by using sentinel as the sentinel for both the next, and the iter? That's funny.
taking something and running it into the ground to get it as small as possible
And it sucks us in as a problem, since the original code using so many non-one line things that one-lining it is a very interesting problem.
yea the sentinel is kinda littered all over
i have a hunch that if i went back to rewrite from scratch with the next(iterable, sentinel) pattern, I would prob end up with a slightly simpler impl
or at least smaller
would prob end up splitting my error condition code for strict mode
*oh that impl also has no walruses
I wonder if I could somehow mangle my lambda that goes into takewhile to be the arg for iter. I think in the limit, our code should converge to the same thing.
possibly, the iter(func, sentinel) pattern calls func() until it returns sentinel, and yields the other returned values
makes it kinda perfect for zip
you can use any and also remove the full words, since Queen does not have a J or K (same for the rest)
so if any(item in card for item in 'JQK') would work
then you can golf further with
if any(map(card.__contains__,'JQK'))
can also prob get away with if any(map(card.startswith,'JQK'))
if card is a str
i have far too much python memorized
especially the weird stuff
@sick hound like this #esoteric-python message is what i spent some time today working on
if any({i}&{*card}for i in'JQK')
this also works i think
if{*card}&{*'JQK'} then
yea
everyone turned pink
Don't get them started
show some funny oneliners
^ here u go @marble imp
!e Heres a way to get iter(obj) without using the builtin ```py
get_iter = lambda arg:(()for()in(arg)).gi_frame.f_locals['.0']
print(get_iter('foo'))```
@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.
<str_ascii_iterator object at 0x7f02bcef3700>
how much more boiler plate can i add
import from builtins
#!/usr/bin/env python3
import builtins
def main() -> None:
print(str('Hello, World!'))
exit()
if str(__name__) == str('__main__'):
main()
else:
exit()
Infinite
Obviously you need to use sys.exit() instead of just exit() — that comes from the site package which isn't always loaded.
I think this is the most boilerplate that one could reasonably add.
# /usr/bin/env python3
# We need `sys.argv' and `sys.exit'.
import sys
def main (argc: int, argv: list[str]) -> int:
"""main (argc: int, argv: list[str]) -> int
Main function for the program.
"""
output_string: str = "Hello, world"
# Writing to stdout could fail, so we should handle that.
try:
print(output_string)
except:
return -1
return 0
if __name__ == "__main__":
exit_code = main(len(sys.argv), sys.argv)
sys.exit(exit_code)
else:
pass
by "reasonably", i mean "you could get this into production code"
maybe you could add version checking at the beginning to fail if the python version isn't high enough?
ultimately, this is true though
you can expand a program infinitely
I would add str("Hello, World") for extra type safety
explicit utf8 codec
oo true
i forgot about the encoding
"Hello world" is already a str
that doesn't add typesafety
type safety for the mind
Real type safety for the mind would be doing py output_string: str = "Hello, world" assert isinstance(output_string, str)
data: list[list[str | int]] = []
maximums: list[list[str | int]] = []
minimums: list[list[str | int]] = []
while True:
tmp: list[str | int] = []
tmp.append(str(input('Enter name: ')))
tmp.append(int(input('Enter value [integer only]: ')))
continue_: str = str(input('Continue? [Y/n]?')).strip().lower()
data.append(tmp[:])
if maximums == []:
maximums.append(tmp)
elif tmp[1] > maximums[0][1]:
maximums = []
maximums.append(tmp)
elif tmp[1] == maximums[0][1]:
maximums.append(tmp)
if minimums == []:
minimums.append(tmp)
elif tmp[1] < minimums[0][1]:
minimums = []
minimums.append(tmp)
elif tmp[1] == minimums[0][1]:
minimums.append(tmp)
if continue_ == '':
continue_ = 'y'
if continue_ == 'n':
break
print(data)
print(f'Registered: {len(data)}\nMaximum value: {maximums}\nLowest value: {minimums}')```
how cursed is this
Very, considering the type hints in esopy. Also very, considering the key kwarg of min and max exist. Looking at it more, there is no reason to use a list for min and max, besides like obfuscation maybe?
this has the same behaviour i think
i=input;k=lambda a:a[1];d=[];m=0,float("inf");M=0,-m[1]
while 1-k((d:=d+[t:=[i('Enter name: '),int(i('Enter value [integer only]: '))]],i('Continue? [Y/n]?').strip()in[*'nN'])):
M=max(t,M,key=k);m=min(t,m,key=k)
print(f"{d}\nRegistered: {len(d)}\nMaximum value: {[M]}\nLowest value: {[m]}")
there is. min and max functions only return one value, if multiple items have the same value, and this value is the maximum or minimum it only return one still, this would return the other values that are also maximum too
notice that it appends when it is equal
That ones'e better.
That should be set as everyone's bio
# /usr/bin/env python3
"""
This program is designed to function as a base template that will work well
with a number of different programs and Python versions.
"""
# Required to support more python versions
from __future__ import annotations, print_function
# We need `sys.argv' and `sys.exit'.
import sys
# In order to support older python versions.
from typing import List
def main(argc: int, argv: List[str], /) -> int:
"""main (argc: int, argv: list[str]) -> int
Main function for the program.
:arg argc: The number of command line arguments.
:arg argv: The command line arguments.
"""
# Define the string to be output to the console
output_string: str = "Hello, world!"
# Writing to stdout could fail, so we should handle that.
try:
seperator: str = ""
ending_string = "\n"
output_file = sys.__stdout__
flush_file = True
# Print the output string to stdout
print(
output_string,
sep=seperator,
end=ending_string,
file=output_file,
flush=flush_file,
)
except BaseException:
# Writing failed, so return a nonzero exit code
return -1
finally:
pass
return 0
# Only execute the program if run directly
if __name__ == "__main__":
# Extract the exit code from the main function
exit_code = main(argc=len(sys.argv), argv=sys.argv)
# Exit with the proper exit code
sys.exit(exit_code)
else:
pass
__future__.print_function and type annotations at the same time is so cursed...
Here's my attempt at improving this
https://paste.pythondiscord.com/5JGA
why no -h/--help handling?
any idea how to golf this further?
import sys
for s in sys.argv[1:]:
a,b,c,d,e,f,g,h,i=map(int,s.replace("-",""));j=(a+2*b+3*c+4*d+5*e+6*f+7*g+8*h+9*i)%11
if j==10:j="X"
print(f"{s}{j}")```
you can replace the long line with
j=sum(b*c for b,c in enumerate(map(int,s.replace("-","")),1))%11
140 132 130 129 bytes
import sys
for s in sys.argv[1:]:
if(j:=sum(b*c for b,c in enumerate(map(int,s.replace("-","")),1))%11)>9:j="X"
print(s+str(j))
in that case, a --version is needed also