#esoteric-python
1 messages Β· Page 55 of 1
c,
!e print(f"{-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0:c}")
:white_check_mark: Your 3.13 eval job has completed with return code 0.
p
invert
:luldog:
!e print(~~~0)
:white_check_mark: Your 3.13 eval job has completed with return code 0.
-1
what the fk is luldog
grey can u post it
in still confused
u got the emoji
:white_check_mark: Your 3.13 eval job has completed with return code 0.
001 | 1
002 | -1
depending on order it either adds 1 or subtracts 1
i'm old i need explanations
!e print(~-~-0)
:white_check_mark: Your 3.13 eval job has completed with return code 0.
-2
ye its a fun lil trick that mtn reminded me exists
when we were talking about jsfuck
it's just the name of the emote "
"
yea i understand
do u know how to make math.ceil in base python without import or round
that's about all there is to it
(x + 1) // 1 - 1 ?
that doesnt work
how do you do it
huh
i would get to it if u'd give me 1 more second
do u understand it
althought true i prefer to think it as "rounds towards negative infinity"
>>> x = -0.3
>>> -(-x//1)
-0.0
this lil thing is also one of the few ways ik to get python to get me -0.0
no clue how useful that is but its funny
-0.0 also gets you -0.0
any operation which gives you 0.0 that you negate will give you -0.0
had forgotten ~ exists
underrated operator
holy shit 3.14
!e
print(-(1.0-1.0))
:white_check_mark: Your 3.13 eval job has completed with return code 0.
-0.0
also gives you -0.0
i also forgot what does it exactly do
ah so its a float thing
flip all the bits
yes it's an IEEE 754 thing
^
>>> bin(~0b100)
'-0b101'
what am i doing wrong
python uses two's complement
yes, this is actually the correct way to look at it
u got a negative binary if u look closely
the only way to get -0.0 i think
yeah I don't know of another way
i dont think there's another way to get -0.0
:white_check_mark: Your 3.13 eval job has completed with return code 0.
-0.0
and of course, multiply by negative anything too
including math.copysign
to bbe fair
it probably doing a negation
π€·ββοΈ i dont know
its like doing
def a(b):
return b * -1
print(a(0.0))
the point is that when u pass it to a function, it matters less
there could be infinite amount of functions that do that
i know what copysign is... what i say is that when u move it to a function it matters less
although i had to google it since i forgot about its signature and everything
I think it calls the C copysign function
π€
could be
i dont think so though
well... doesn't matter to me i guess much
shouldn't be hard to implement it in c
now i have to open the sln of cpython because of u
!e
code = """
<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<polygon points="50,5 75,25 75,75 50,95 25,75 25,25" fill="#007BFF" stroke="black" stroke-width="2" />
</svg>
"""
with open('test.svg', 'w') as file:
file.write(code)
:white_check_mark: Your 3.13 eval job has completed with return code 0.
Files with disallowed extensions can't be uploaded: .svg
aw disallowed
I wonder why svg is disallowed
same tbh
mildly unexpected
maybe because it can be abused to put bad images
hmm tho you can use PIL to put images
probably because svgs can contain scripts
FUNC2(copysign, copysign,
"copysign($module, x, y, /)\n--\n\n"
"Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
"On platforms that support signed zeros, copysign(1.0, -0.0)\n"
"returns -1.0.\n")
!e import turtle
:x: Your 3.13 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m1[0m, in [35m<module>[0m
003 | import turtle
004 | File [35m"/snekbin/python/3.13/lib/python3.13/turtle.py"[0m, line [35m101[0m, in [35m<module>[0m
005 | import tkinter as TK
006 | File [35m"/snekbin/python/3.13/lib/python3.13/tkinter/__init__.py"[0m, line [35m38[0m, in [35m<module>[0m
007 | [1;31mimport _tkinter[0m # If this fails your Python may not be configured for Tk
008 | [1;31m^^^^^^^^^^^^^^^[0m
009 | [1;35mImportError[0m: [35mlibtk8.6.so: cannot open shared object file: No such file or directory[0m
ah yeah, svg can include anything, since it's just XML
I wonder, can HTML be uploaded
html is disallowed too, just tested in bot commands
i'm not sure i get it
makes sense cause of <script> ig ?
guess so
how come math_copysign gets attached to:
FUNC2(copysign, copysign,
"copysign($module, x, y, /)\n--\n\n"
"Return a float with the magnitude (absolute value) of x but the sign of y.\n\n"
"On platforms that support signed zeros, copysign(1.0, -0.0)\n"
"returns -1.0.\n")
i guess its this _PyCFunction_CAST
so math copysign is literally c copysign, wrapped
macro-built function
calls https://github.com/python/cpython/blob/main/Modules/mathmodule.c#L1014-L1016 with func as C's copysign()
Modules/mathmodule.c lines 1014 to 1016
static PyObject *
math_2(PyObject *const *args, Py_ssize_t nargs,
double (*func) (double, double), const char *funcname)```
lots of the math functions are like that
people when software that implements function just uses stdlib
I have a challenge for y'all
make a PyCapsule object
it's new in 3.13 and I think you have to use ctypes because it can't be made from python
PyObject *PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor)```
though if you can find one in the wild that's also pretty good
it shouldn't check the pointer for anything so it doesn't matter what its value is, destructor might matter but I'm not sure. every attempt I made crashed in pymalloc because tstate was null
import ctypes; dll = ctypes.CDLL(None); PyCapsule_New = dll["PyCapsule_New"]; PyCapsule_New.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p]; PyCapsule_New.restype = ctypes.py_object; cap = PyCapsule_New(ctypes.c_void_p.in_dll(dll, "printf"), ctypes.c_char_p(b"HelloCapsule"), ctypes.c_void_p.in_dll(dll, "printf"))```
that's my starter code that crashes
Can you elaborate on this? I'm pretty much certain that it's older...
How do you use ansi code?
!e ```py
import datetime as dt
print(dt.datetime_CAPI)
:white_check_mark: Your 3.13 eval job has completed with return code 0.
<capsule object "datetime.datetime_CAPI" at 0x7f09cf0b1210>
on a side note, the attribute came from a 2009 commit
it still exists for some reason
Interesting, it looks like they've been cleaning those up, but that one might have been missed
!d types.PyCapsuleType
No documentation found for the requested symbol.
class types.CapsuleType```
The type of [capsule objects](https://docs.python.org/3/c-api/capsule.html#capsules).
Added in version 3.13.
that's where I got the date from @austere mauve ^
maybe that's only where it got added as something that can be used inside python?
So in python 3.13 it was made accessible through types library...
I knew about it before because pygame/pygame-ce uses them to share internal functions between the sub-modules: ```py
import pygame
pygame-ce 2.5.5 (SDL 2.32.6, Python 3.13.1)
pygame.surface._PYGAME_C_API
<capsule object "pygame.surface._PYGAME_C_API" at 0x000001B05AF4A340>
!e
Please react with β to upload your file(s) to our paste bin, which is more accessible for some users.
hey @rapid sparrow , what do you think about this code?
a fun mess
going out on a limb but im guess its hello world ?
it says that is potentially dangerous
!e 3.14 ```py
import types
print(types.CapsuleType)
:white_check_mark: Your 3.14 pre-release eval job has completed with return code 0.
<class 'PyCapsule'>
yeah it does print hello world
huh
idk why
figured
that was fast
wanna see my coding skills?
wat was
you figuring it out
print(βHello world!β)
I was confused by this:
https://github.com/python/cpython/blob/3.14/Lib/types.py#L73-L74
For python 3.14+ it's implemented by _types.
Lib/types.py lines 73 to 74
# CapsuleType cannot be accessed from pure Python,
# so there is no fallback definition.```
aint my first rodeo :luldog:
xd
globals()[bytes()] is a fun one tho
whenever I write obfuscated code it is probably hello world and nothing else
I mean, whenever I write obfuscated code and send it here
wanna see some fun code i wrote like 3y ago to print H
sure
Please react with β
to upload your file(s) to our paste bin, which is more accessible for some users.
damn u going far if u can do all that
how does that work?
yeah, i bet you canβt π
looks like playing with integers and ascii and combining both to get the 72 (H)
with lots of lambdas
I love lambdas
a very funny algorithm i came up with then abused
I love it
!e
"""
test gets passed to lambda right above
which then returns "5"
which then is passed to lambda above it
which returns "5" + "5" aka "55"
then thats passed into int becoming 55
which gets passed into lambda above and that returns [55, "5"]
which gets passed into lambda above and that returns [55, int("5" + "0")] which is [55, int("50")] which is [55, 50]
which then gets passed into lambda above and that returns [chr(55), chr(50)] which is ["7", "2"] cause of ascii table
which then gets passed into "".join above and that returns "72"
which then gets passed into int above and that returns 72
which then gets passed into chr above and that returns "H"
"""
@print
@chr
@int
@"".join
@lambda _: map(chr, _)
@lambda _: [_[0], int(_[1] + "0")]
@lambda _: [_, "5"]
@int
@lambda _: "5" + _
@lambda _: "5"
def test():
pass
:white_check_mark: Your 3.13 eval job has completed with return code 0.
H
here is a less complicated version
yup, I guessed it
it gets 55, 55 + 17 = 72
72 = H
it doesnt add 17 
II did something similar at the end of my code, check last four lines
yeah I just tried guessing
or am i wrong?
nah u not wrong, i phisically cant just write print("Hello World")
something in me just urges for the esopy complexity
want another code i made that i couldnt tell u how it works after the 2-3 years its been since i made it
not a problem man, youβll just figure out how to do it in some years
sure, you can't tell me because you don't remember or what?
exactly
print(*[globals().update({"size": int(input("Size of matrix ? ")), "g": lambda k, v: globals().update({k: v})}),g("options", [-size, 1]), g("instructions", sorted([1,size] * (size - 1)) + [-1] * (size - 1) + sum([sum(x[:-1], []) for x in list([[options[i]] * mult for i in range(2)] + [globals().update({"options": [-x for x in options]})] for mult in range(size - 2, 0, -1))] + [[0]], [])),g("Spiral", list(map(lambda _: sum(_), [[x[y] for x in [[n + 1 if m == l else 0 for m in range(size**2)] for n, l in enumerate([sum(instructions[:x1]) for x1 in range(size**2)])]] for y in range(size**2)]))),["\n" + f"{Spiral[x3]}".zfill(len(f"{size**2}")) if x3 % size == 0 else f"{Spiral[x3]}".zfill(len(f"{size**2}")) for x3 in range(size**2)]][-1])
nice
i can tell u what it does but i cant for my life tell u how
it creates a matrix
i spent like 3d studying really obscure patterns within spiral matrices to make that code
oh wow
it was fun
btw I've heard some people here use some kind of obfuscators or something
a program that obfuscates code for you
me too
kinda robs the fun out of it
here is some art:
!e
from PIL import Image
import numpy as np
pixel_data = np.zeros((21, 21), dtype = np.uint8)
pixels = iter("1111111010001011111111000001011101010000011011101001010010111011011101000100010111011011101001001010111011000001010111010000011111111010101011111110000000011111000000000001101000100111000111111000110111011011101001111100001100110101101000001001010100001000111100110010111000000000001000101000111111111001000011011011000001001110011110001011101010010101111011011101010110100011101011101000110111000101000001000101010101011111111000011100101002")
for i in range(21):
for j in range(21):
pixel_data[j,i] = 255 * (not bool(int(next(pixels))))
image = Image.fromarray(pixel_data, mode = 'L')
image = image.resize((210, 210), Image.Resampling.NEAREST)
image.save('test.png', format = 'png')
:white_check_mark: Your 3.13 eval job has completed with return code 0.
I had no idea 3rd party stuff works here
oh cool!!
I see
u should scan it btw π
eh smart choice for security reasons
but this one is a 21x21 qr code, literally only up to 17 bytes of encodeable data on it
yeah version 1
its usually safe
#bot-commands message there is also this other PIL code i made with bot (althought had some1 else run it for me)
pretty cool actually
the only other thing I wish about python bot is for it to be able to read and execute code from paste links
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
gonna be damn near impossible given it runs code on a sandbox aka no internet connection

hmm true
but wait, it's a discord bot, discord bots can interact with APIs and HTTP requests I think?
right?
well ye
but the code is running inside a sandbox on machine that hosts bot
bot isnt inside a sandbox
yeah
althought it might be too not sure
anyway, you reminded me of qr codes, I learned to write them by hand on paper, it was painful
!e
import ctypes
ctypes.c_uint.from_address(id(5) + 24).value = 4
print(5 == 4)
:white_check_mark: Your 3.13 eval job has completed with return code 0.
True
there is also this funny lil silly code
when i changed 0 value to 1 it litterally crashed repl with bad cursor position (it was negative)
it was delightful
first time i ever seen repl actually crash
i just did a program that calculates the area of any triangle
first time?
repl crashed for me many times...
it's probably my fault for that
u doing great for some1 new 
iβm starting to understand
tyy
ye
itβs just codebro that explains everything so clearly
I mean, you can if you really wanna to
here i got pic perms
just listening to them wouldnt get u this far, u need to aactually practice like u doing
oh
send code as text
iβm doing it
base = float(input("quanto vale la base?"))
altezza = float(input("quanto vale l'altezza?"))
area = (base * altezza)/2
print(f"l'area vale {area}")
yup like that
now share it in #python-discussion instead of here
here is a cursed land
do u know pascal triangle
yeah
!e
type("bruh", (), {"x": [1], "__call__": lambda self: [print(*self.x), setattr(self, "x", list(map(sum, zip([0] + self.x, self.x + [0])))), self][-1]})()()()()()()()()()()()()()()()()
:white_check_mark: Your 3.13 eval job has completed with return code 0.
001 | 1
002 | 1 1
003 | 1 2 1
004 | 1 3 3 1
005 | 1 4 6 4 1
006 | 1 5 10 10 5 1
007 | 1 6 15 20 15 6 1
008 | 1 7 21 35 35 21 7 1
009 | 1 8 28 56 70 56 28 8 1
010 | 1 9 36 84 126 126 84 36 9 1
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ZCO67EV3FAS3H24CTZM7OV62RE
impressive!
its a fun lil "recursive" code
very cool!
I love lambda
!e
print((_:=(_:=lambda __:type([lambda:'',lambda:chr(__[False])][len(__)>False](),(),{chr(__.pop(False)):[lambda _:b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21',_][len(__)>False](__)}))([*b'\x48\x65\x6c\x6c\x6f\x57\x6f\x72\x6c\x64'])).H.e.l.l.o.W.o.r.l.d)
:white_check_mark: Your 3.13 eval job has completed with return code 0.
b'Hello World!'
here is my most recent hello world
incredible, however why didn't you decode it at the end?
no need
yeah I know but the b'' looks kinda weird in my opinion
this is hello world by the way
0<01?<b1010<0<h<0<h<0.b1[>0>0<0.0>b1b<0<h<b1b
looking..
wow that's quite an impressive syntax soup
I'll do a bit of my analysis to comment further
thanks xd
thats most of the point of eso code isnt it
what is this even - there's no print("hello world") then how come the output is hello world
I mean there's literally a print and a b"Hello World!"
oh i see it now
then what is this (_:=(_:=lambda __:type([lambda:'',lambda:chr(__[False])][len(__)>False](),(),{chr(__.pop(False)):[lambda _:b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21',_][len(__)>False](__)}))([*b'\x48\x65\x6c\x6c\x6f\x57\x6f\x72\x6c\x64']
some very complicated python code
tl;dr its creating nested classes
my eyes hurt even looking at it
welcome to #esoteric-python
everything that's going on in here is profoundly _un_βprofessional
The longest ** hello world ** Iβve seen
Click here to see this code in our pastebin.
here is a really silly one i made when just getting started with esopy
Yes
its a bit longer
well well it seems some innocent people accidentally stepped in this territory
for your own good of your soul, you may leave or become cursed
okay wtf
that one seems formatted enough
pydis pastebin is run by cowards and can't handle the payload of this single line
only uses (),._abcdegijklmnoprstuvy
that one is straightforward enough 
a lot of my esopy codes are formatted
disable your formatter
Please react with β
to upload your file(s) to our paste bin, which is more accessible for some users.
its called "my hands" is the issue
you format by hand?
minecraft (specifically gtnh) modding
ye
understandable
"python is fun" is the main esopy repo
the only acceptable use of java
need to update it tho
!e
import random, sys, pkgutil; modules = sorted(m.name for m in pkgutil.iter_modules(sys.path)); list(map(lambda _: print("{}, I choose you! {}".format((name := random.choice(modules)), __import__(name))), range(10)))```
:x: Your 3.13 eval job timed out or ran out of memory.
001 | smtplib, I choose you! <module 'smtplib' from '/snekbin/python/3.13/lib/python3.13/smtplib.py'>
002 | _interpchannels, I choose you! <module '_interpchannels' from '/snekbin/python/3.13/lib/python3.13/lib-dynload/_interpchannels.cpython-313-x86_64-linux-gnu.so'>
lmao it ran out of memory π
@wanton tundra
yo
we'll never know what module ran out of memory
my guess is __builtins__
importing builtins really?
!e import("builtins")
:warning: Your 3.13 eval job has completed with return code 0.
[No output]
i think it's funny that it's builtins and __builtin__
or, it used to be, they might both be plural now
no im guessing that builtins OOM
since its the one importing and sorting and doing all the crazy heavy stuff
:luldog:

oh i should check to see if they considered adding luldog
i offered to try to vectorize it if that was preferred
it might be hard tho
don't think I've gotten any pings tho
oh you mean like buildin C modules
yeah, I was thinking it's probably definitely something like that too
fun snippet from a recent ctf:
# context:
class A[B]:__slots__=()
a=A()
#sol
{
W+sh
for W in a.__class__.__orig_bases__
for W.__class__.__mul__ in {{}.__doc__.__getitem__}
for s in {W*97}
for h in {W*280}
for o in {W*25}
for sh in {s+h}
for os in {o+s}
for O in {{}.__class__.__base__}
for T in {a.__slots__.__class__}
for W.__class__.__add__ in {T}
for W.__class__.__neg__ in {O.__subclasses__}
for subclasses in {W+-W}
for W.__class__.__add__ in {subclasses.__getitem__}
for loader in {W+122}
for loader in {loader.load_module}
for W.__class__.__add__ in {loader.__call__}
for module in {W+os}for W.__class__.__add__ in {module.system}
}
``` the task was to get shell without `[]()"':=`, with only access to this class `A`
cute
super cute
the indentation makes it even better xd
so only properties & statments 
Yeah! If you're curious, you can see the actual problem statement here: https://bulmenisaurus.github.io/pyjail2025-writeup/
possibly arithmetic as well, since its assigning to mul, neg & add
yes. its set comprehensions... 
>>> exec(f'a=1')
>>> exec(f'{"a"*1_000_000}=1')
>>> exec(f'{"a"*10_000_000}=1')
>>> exec(f'{"a"*100_000_000}=1')
>>> exec(f'{"a"*1_000_000_000}=1')
>>>
random experiment but there doesnt seem to be a variable name length limit 
!e ```py
exec(f'{"a"*10**9}=99')
:x: Your 3.13 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m1[0m, in [35m<module>[0m
003 | exec(f'{[31m"a"[0m[1;31m*[0m[31m10**9[0m}=99')
004 | [31m~~~[0m[1;31m^[0m[31m~~~~~[0m
005 | [1;35mMemoryError[0m
works on my machine
guess it depends on available system memory
now the lexer ran out of memory
turns out the limit is 2**31-4
it is actually 2**31-1, because 2 chars go to =1 and 1 to probably \0
turns out python lexer actually eats a lot of memory
those mountains you see are lexer trying to parse the variable
code:py for i in range(65, 75): exec(chr(i)*(2**31-4)+'=1')
and the bottom lines are exec execution being completed
right after that the little bumps are strings getting generated and passed to exec
atleast this is what I inferred, anyone know any better can enlighten me
This is also machine dependent, but by nesting you can get shorter:
Though a different error is raised here.
Wait, parser - not lexer crashes here.
its not parser here
actually lexer is a big part of parser itself, and when parsing these big identifiers, lexer is the first thing which would crash due to overflow
I was referring to my sample. Yours triggers the lexer.
they it can be machine dependent
yeah
Yeah, I sent this sample before and someone else got different result.
yeah
on 3.10
its actually more of architecture AND version dependent
btw this is 3.14
Interesting
is it possible to define a class that doesn't show up in object.__subclassess__()?
Use python 2
why delete? It seemed like your method works
The reason was wrong, I'm doing more testing
!e But the answer is yes, just inherit from any other class
class A(tuple): ...
print(A in object.__subclasses__())
:white_check_mark: Your 3.14 eval job has completed with return code 0.
False
__subclasses__ is only for direct children. What you meant would be more like "can you make a class where isinstance(<class>(), object) is False / issubclass(<class>, object) is False / where it's not in the recursive search of __subclasses__", and I think the answer to that is no, at least in python 3
Is there any detailed technical doc for the bootstrapping process of the interpreter? I've been trying to investigate what would be required for Python to go without standard library files (i.e., be able to start up without a valid PYTHONHOME). It appears that minimally, aside from what's implemented as a builtin, it requires at least os (and its dependencies), encoding/codecs (and probably at least the utf-8 plugin wrapper?) and at least a blank site.py (even with -S it seems that not having such a file will cause problems)
A = [-2,3,-4,5]
A.sort(lambda x:abs(x))
print(*A)
I have a challenge to you guys. Guess in which version of python this is ok ^.
I saw this code in the wild, and I was initially sure it was incorrect
But turns out it is arguably correct, runnable, python code
<=3.2?
Documentation for 3.2 says "The sort() method takes optional arguments for controlling the comparisons. Each must be specified as a keyword argument."
https://docs.python.org/3.2/library/stdtypes.html#list.sort
No. Hint: ||its not cpython||
oh I've got no idea then π
It's not exactly a fun challenge if it requires knowing a piece of obscure trivia
I think just putting the fact in a spoiler could improve it
I myself didn't know what was going on when I first saw this in the wild. Took me some time to realize what was going on. That's why I didn't post the answer to the challenge.
Answer: turns out it is a quirk of ||pypy||
Probably, this should be reported as a bug.
I don't think it is super obscure.
I'll stump you:
There's a python version where this code is correct (and equivalent to yours):
A = [-2,3,-4,5]
A.sort(lambda x, y:abs(x)<abs(y))
print(*A)
This one is obscure.
Also, not its latest release (this has been patched).
still wondering... :(
python builds currently need a previously built version of python, if that's what you're asking
i don't know how far down the line it goes or what you really mean by that though
i think at a certain point you can sidestep the build by using an alternate implementation
plus you don't strictly need the previous version of python for the current one
you could theoretically test every major version to see if that + the appropriate c compiler yields a bit-identical interpreter
yea, just a previously built one
no I mean at runtime, when Python starts up, the process of loading the initial set of modules in sys.modules, as needed for importing other stuff
This looks like the startup sequence for the interpreter:
https://github.com/python/cpython/blob/main/Python/pylifecycle.c#L1183-L1394
thx
I find that it's hard to get oriented in large C codebases and figure out where the important bits are or what the main flows are
well, in every language, but more so in C and C++ because of the header file system.
that's why docs are important
class function(object)
| function(code, globals, name=None, argdefs=None, closure=None)
|
| Create a function object.
|
| code
| a code object
| globals
| the globals dictionary
| name
| a string that overrides the name from the code object
| argdefs
| a tuple that specifies the default argument values
| closure
| a tuple that supplies the bindings for free variables
|
... it seems that argdefs refers to default values for ordinary, keyword-or-positional arguments. There doesn't appear to be a way to supply default values for keyword-only arguments... ?
and not positional-only arguments, either.
>>> def foo(a, /, b, *, c): pass
...
>>> help(type(foo)(foo.__code__, foo.__globals__, foo.__name__, (1, 2, 3), foo.__closure__))
Help on function foo in module __main__:
foo(a, /, b=1, *, c)
The resulting object's __defaults__ are the entire tuple and Python doesn't seem to care that it's over-length.
but there must be more to it, because positional-only arguments can have default values, and those normally do get included in __defaults__.
... It's even stranger. It appears that the introspection facilities have a different idea than the actual call mechanism, which works when __defaults__ aren't over-length.
>>> import inspect
>>> def foo(a, /, b, *, c): return (a, b, c)
...
>>> bar = type(foo)(foo.__code__, foo.__globals__, foo.__name__, (1, 2, 3), foo.__closure__)
>>> inspect.signature(bar)
<Signature (a, /, b=1, *, c)>
>>> bar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() missing 1 required keyword-only argument: 'c'
>>> bar(c=4)
(2, 3, 4)
~~!e uhh what? ```py
def func(a, /, b, *, c=10):
"""
a is positional-only,
b is positional-or-keyword,
c is keyword-only (with default = 10)
"""
print("a =", a)
print("b =", b)
print("c =", c)
print(func(1, 3))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | a = 1
002 | b = 3
003 | c = 10
004 | None
defaults for kw only work just fine
you could do this: ```python-repl
def foo(a, /, b, *, c): return a, b, c
...
bar = type(foo)(foo.code, foo.globals, foo.name, (1, 2), foo.closure)
bar.kwdefaults = {'c': 3}
bar()
(1, 2, 3)
inspect.signature(bar)
<Signature (a=1, /, b=2, *, c=3)>
or ```python-repl
bar = type(foo)(foo.code, foo.globals, foo.name, (1, 2), foo.closure, kwdefaults={'c': 4})
bar()
(1, 2, 4)
note that I'm on 3.13 and the kwdefaults argument was added to the constructor relatively recently (https://github.com/python/cpython/pull/112641)
oh, I didn't even think to check newer versions (I build each new minor version from source locally) x.x
also huh, __defaults__ and __kwdefaults__ can indeed be set after the fact (although they're type-checked). I expected them to be readonly attributes, lke __closure__ is
inspect.signature breaking when the defaults tuple is too long is kinda funny
and since __kwdefaults__ is a dict, it's also mutable in-place as there's no frozendict.
>>> def foo(*, x=1): return x
...
>>> foo.__kwdefaults__['x'] = 2
>>> foo()
2
Disturbing.
yeah there's a surprising amount of stuff that is just... writeable https://docs.python.org/3/reference/datamodel.html#special-writable-attributes
anyway, confirmed a particular pattern of weirdness there with over-long __defaults__. and it's consistent from at least 3.8 onward. Seems that it doesn't actually care at all about positional-only vs positional-vs-keyword (of course, positional-only isn't supported before that)
anyway, seems like a bug in inspect
a=1
b=2
print(a+b)
this is my first program in esoteric python
!e a bit more ```py
i,=*a,=1,
[*b]=b[i]=a,2
print(sum(x!=0 for x in b for x in x))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
3
which part is esoteric?
!epy print(sum(map(ord,'Hello, world!'))//int(-(sum(map(ord,'Hello, world!'))/~sum(map(ord,'Hello, world!')))**sum(map(ord,'Hello, world!'))*sum(map(ord,'Hello, world!')))-~int(sum(map(ord,'Hello, world!'))/~sum(map(ord,'Hello, world!')))) hello world is mandatory
:white_check_mark: Your 3.14 eval job has completed with return code 0.
3
though its 2+1 instead of 1+2
its conceptual esotericism (??)
!e py print(-~int(sum(map(ord,'Hello, world!'))/~sum(map(ord, 'Hello, world!')))+sum(map(ord,'Hello, world!'))//int(-(sum(map(ord,'Hello, world!'))/~sum(map(ord,'Hello, world!')))**sum(map(ord,'Hello, world!'))*sum(map(ord,'Hello, world!'))))here is 1+2
:white_check_mark: Your 3.14 eval job has completed with return code 0.
3
lacks the aesthetic finesse of
a=1
b=2
print(a+b)
aesthetics are for kids
Then what is this?
its 100% an aesthetic job
everything's aesthetic in their own way π
common ritual of hello world
whats the point of esoteric programming if its not aesthetic?
actually the names a and b aren't required, they could just be x
it's aesthetic in its own way ^^
imo, its 100% aesthetic, thats why i defend
a=1
b=2
print(a+b)
as the most esoteric script i've ever seen
athleticism
this is me right now
isn't that code golf?
thats just a game we play
!e ```py
i,=*x,=1,
[*x]=x[i]=x,2
print(sum(x!=0 for x in x for x in x))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
3
i saw the red X
congrats you are not red color blind
a=1
b=2
print(a+b)
i'd argue that it's actually 2+1 in the image
yeah i actually almost edited it to make a = 2
but i thought the obvious contradiction made it more artistic
the only esoteric part of that program is the fact that you're not doing print(3)
Touching on artistic side of programs, here's mine:
a = []
for b in a:
b /= len(a)
It's called: Unreachable division by zero.
So I just implemented an assembly language as an import-system DSL ^.^
here's the whole program https://codeguessing.gay/86/machine.lesbian
!e
import math as m
x = m.pow(2,87)
a = m.pow(1,x)
def Ret():
return a + m.pow(x,x)
print(Ret())
:x: Your 3.14 free threaded eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m7[0m, in [35m<module>[0m
003 | print([31mRet[0m[1;31m()[0m)
004 | [31m~~~[0m[1;31m^^[0m
005 | File [35m"/home/main.py"[0m, line [35m6[0m, in [35mRet[0m
006 | return a + [31mm.pow[0m[1;31m(x,x)[0m
007 | [31m~~~~~[0m[1;31m^^^^^[0m
008 | [1;35mOverflowError[0m: [35mmath range error[0m
!e
import math as m
x = m.pow(2,8)
a = m.pow(1,x)
def Ret():
return a + m.pow(x,x)
print(Ret())
:x: Your 3.14 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m7[0m, in [35m<module>[0m
003 | print([31mRet[0m[1;31m()[0m)
004 | [31m~~~[0m[1;31m^^[0m
005 | File [35m"/home/main.py"[0m, line [35m6[0m, in [35mRet[0m
006 | return a + [31mm.pow[0m[1;31m(x,x)[0m
007 | [31m~~~~~[0m[1;31m^^^^^[0m
008 | [1;35mOverflowError[0m: [35mmath range error[0m
!e
import math as m
x = m.pow(2,2)
a = m.pow(1,x)
def Ret():
return a + m.pow(x,x)
print(Ret())
:white_check_mark: Your 3.14 eval job has completed with return code 0.
257.0
!e
import math as m
import py_compile as pyc
x = m.pow(2,2)
a = m.pow(1,x)
def Ret():
return a + m.pow(x,x)
print(Ret())
pyc.compile('script')
:x: Your 3.14 eval job has completed with return code 1.
001 | 257.0
002 | Traceback (most recent call last):
003 | File [35m"/home/main.py"[0m, line [35m10[0m, in [35m<module>[0m
004 | [31mpyc.compile[0m[1;31m('script')[0m
005 | [31m~~~~~~~~~~~[0m[1;31m^^^^^^^^^^[0m
006 | File [35m"/snekbin/python/3.14/lib/python3.14/py_compile.py"[0m, line [35m142[0m, in [35mcompile[0m
007 | source_bytes = loader.get_data(file)
008 | File [35m"<frozen importlib._bootstrap_external>"[0m, line [35m953[0m, in [35mget_data[0m
009 | [1;35mFileNotFoundError[0m: [35m[Errno 2] No such file or directory: 'script'[0m
Someone should make a python esolang variation where itβs just the pass statement
"Easy" way to do it: just use Unary
To make it esoteric you need to make a a capital letter and you need to declare b before a, while also switching their value
b = 1
A = 2
print(b+A)
A = 1, b = 2 is better balanced
:white_check_mark: Your 3.14 JIT-compilation enabled eval job has completed with return code 0.
3
So I found an old closed report for this, I think it wasn't duly considered and I'm going to follow up
you call this easy?????????
who are you??????
βEasyβ since itβs a zero brain power method on the idea side, since someone already made it, and it would be trivially adaptable. Actually implementing it is left as an exercise for the reader :)
ig
but brainf*** isnt easy
its in the damn name
they dont call it esoteric for nothing
i guess you could have chat gpt do it for you
BF is just the most common unary backend since itβs so common and easy to implement, but nothing stops you from instead defining it in terms of something like python byte code instructions.
Well implementing it would still be not easy, and as for the idea side that comes from spending several years around the esolang community.
!e btw did you know that ```py
print("Hello World!")
can be made using
```py
pass; pass; pass; pass; pass;
pass; pass; pass; pass; pass;
pass; pass;
pass; pass; pass; pass;
pass; pass; pass; pass;
pass; pass;
pass; pass; pass; pass; pass;
pass; pass; pass; pass; pass;
:white_check_mark: Your 3.14 eval job has completed with return code 0.
Hello World!
SEMICOLON
how DARE you
isn't that just one big E
!e
for i in range(1000000):
for j in range(1000000):
print(i, j)
:x: Your 3.14 eval job has completed with return code 143 (SIGTERM).
001 | 0 0
002 | 0 1
003 | 0 2
004 | 0 3
005 | 0 4
006 | 0 5
007 | 0 6
008 | 0 7
009 | 0 8
010 | 0 9
... (truncated - too many lines)
Full output: too long to upload
truncates after 10 lines??
its always get truncated after the 10th line. usually it provides a pastebin link to the full output; unless met with some fault errors.
like the one you have here, with the exit code 143 (SIG TERM)...
!e print(*range(15), sep="\n")
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/O3GO37DEILGUER64N7K2MWHK5M
> note: exit code 0
>>> class Hello(slice(10)):
... pass
...
>>> Hello
slice('Hello', (slice(None, 10, None),), {'__module__': '__main__', '__qualname__': 'Hello', '__firstlineno__': 1, '__static_attributes__': ()})
>>>
Hm, int() with base=0 infers the base from the prefix of the string
I wonder if this can be used to form a devious trick
like something with a variable base that secretly behaves differently when evaluating with 0
You mean like "0b0"?
yes
!epy print( int('010001', base=2), int('0b010001', base=0) )
:white_check_mark: Your 3.14 eval job has completed with return code 0.
17 17
!e
class Hello_world(metaclass=slice):
pass
print(Hello_world.start)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
Hello_world
!e 3.12
import sys
from os import chdir, execve
assert sys.version_info[:2] < (3, 13)
chdir("/usr/bin")
class pip("pip", "install", "good-luck", metaclass=execve):
pass
:x: Your 3.13 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m4[0m, in [35m<module>[0m
003 | assert [1;31msys.version_info[:2] < (3, 13)[0m
004 | [1;31m^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^[0m
005 | [1;35mAssertionError[0m
aw
:white_check_mark: Your 3.14 eval job has completed with return code 0.
/home/main.py
!e
import os, shutil
def lolcopy(_, zzzz):
print("unlinking:", _)
os.unlink(_)
shutil.copytree("/", "/", copy_function=lolcopy, dirs_exist_ok=True)
:x: Your 3.14 eval job has completed with return code 143 (SIGTERM).
001 | unlinking: /home/main.py
002 | unlinking: /snekbin/python/3.13/bin/pip
003 | unlinking: /snekbin/python/3.13/bin/python3.13
004 | unlinking: /snekbin/python/3.13/bin/python-config
005 | unlinking: /snekbin/python/3.13/bin/pydoc3.13
006 | unlinking: /snekbin/python/3.13/bin/python3.13-gdb.py
007 | unlinking: /snekbin/python/3.13/bin/pydoc
008 | unlinking: /snekbin/python/3.13/bin/python3.13-config
009 | unlinking: /snekbin/python/3.13/bin/pip3
010 | unlinking: /snekbin/python/3.13/bin/python
... (truncated - too many lines)
Full output: too long to upload
xd
!e py print(int('0x1337', 36)) print(int('0x1337', 0))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | 55477987
002 | 4919
afaik base 0 only works when the string starts with 0b, 0o or 0x
otherwise it tries base 10
:white_check_mark: Your 3.14 eval job has completed with return code 0.
1144540722
!e print(int('100', 0))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
100
!e
print(chr(3486))```
:white_check_mark: Your 3.14 eval job has completed with return code 0.
ΰΆ
!e
print(chr(sum(range(ord(max(str(print()))), ord(max(str(not()))) + (ord(min(str(not(not())))) * ord(min(str(not()))) % ord(next(iter(reversed(str(print()))))))))))```
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 |
002 |
003 | ΰΆ
(((:
!e ```py
class Hi(metaclass=print):
pass
:white_check_mark: Your 3.14 eval job has completed with return code 0.
Hi () {'__module__': '__main__', '__qualname__': 'Hi', '__firstlineno__': 1, '__static_attributes__': ()}
why is __annotations__ in dir(type) but type.__annotations__ fails?
I guess subclass stuff gets weird with type
Also is my understanding of subclasses wrong? I thought for example int.__str__(False) would return '0', not 'False'.
!e
print(type.__dir__(type))
print(dir(type))
print(int.__str__(False))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | ['__new__', '__repr__', '__call__', '__getattribute__', '__setattr__', '__delattr__', '__init__', '__or__', '__ror__', 'mro', '__subclasses__', '__prepare__', '__instancecheck__', '__subclasscheck__', '__dir__', '__sizeof__', '__basicsize__', '__itemsize__', '__flags__', '__weakrefoffset__', '__base__', '__dictoffset__', '__name__', '__qualname__', '__bases__', '__mro__', '__module__', '__abstractmethods__', '__dict__', '__doc__', '__text_signature__', '__annotations__', '__annotate__', '__type_params__', '__hash__', '__str__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__reduce_ex__', '__reduce__', '__getstate__', '__subclasshook__', '__init_subclass__', '__format__', '__class__']
002 | ['__abstractmethods__', '__annotate__', '__annotations__', '__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__delattr__', '__dict__', '__dictoffset__', '__dir__', '__doc__', '__eq__', '__flags__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__
... (truncated - too long)
Full output: https://paste.pythondiscord.com/U6V66GW2QTJ73ZSP64LECIC6UU
!e print(int.str)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
<slot wrapper '__str__' of 'object' objects>
int.__str__() does not exist
it uses the placeholder which falls back to obj.__repr__()
quite curiously it might also accept other types
!e ```py
print(int.str("abc"))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
'abc'
oh, so it's int.__repr__(False) that does what I expect
!e ```py
print(int.repr(False))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
0
also would it be accurate to say that type(obj) returns the metaclass used to create an object?
if the metaclass returns an instance of itself on construction, yes
refer to ^
I see
I've been trying to make a function that returns all the properties of an object and it seems to be a simple as object.__dir__(obj) + dir(type(obj))
well, I guess you could override __dir__ for the metaclass π€
it might be helpful to see how the repl does it https://github.com/python/cpython/blob/main/Lib/rlcompleter.py#L140-L209
it seems to be as simple as set(dir(int)) | set(get_class_members(int.__class__))
such an interesting topic! What is Esoteric Python? I'm ready to have my mind blown!
I would call it "testing the limits of Python programming language".
python but make it at least a lil fucked up
Interesting.
using Annotated and going down this path really butted up against edges of the typechecker that weren't very nice, so I did this instead:
class Validatable(ABC):
def validate(self) -> list[TypeError]:
"""Validates attributes using line-ending comments left after them. Hell yeah!"""
src, _ = inspect.getsourcelines(self.__class__)
regex = re.compile("^\\s+(\\w+):\\s*(\\w+)\\s*#\\s*(.*it.*)$")
errs: list[TypeError] = []
for line in src:
match = regex.match(line)
if match is None: continue
attr_name, attr_type, attr_cond = match.group(1, 2, 3)
cond_callable = eval(f"lambda it: {attr_cond}")
attr_val = getattr(self, attr_name)
if not isinstance(attr_val, eval(attr_type)):
errs.append(TypeError(f"{attr_name} = {attr_val}: Wanted type {attr_type}, got type {type(attr_val)}"))
continue
if not cond_callable(attr_val):
errs.append(TypeError(f"{attr_name} = {attr_val}: Failed validation {attr_cond}"))
return errs
@dataclass
class TestData(Validatable):
epic_sauce: int # it < 420 and it % 5 == 0
power_level: int # it > 9000
works nice
>>> t = TestData(power_level=100, epic_sauce=419)
>>> t.validate()
[TypeError('epic_sauce = 419: Failed validation it < 420 and it % 5 == 0'), TypeError('power_level = 100: Failed validation it > 9000')]
Implementation detail:
>>> int.__str__
<slot wrapper '__str__' of 'object' objects>
so int isn't actually overloading the behaviour; it falls all the way through from bool->int->object, and presumably that implementation explicitly type-checks at the C level.
... oh I was scrolled back sorry
discord keeps doing that to me
So why the difference between str and repr?
repr is for the eval-able representation, a.k.a something that creates the object or an object similar to it
str is for the custom representation
for example a fractions.Fraction repr can be Fraction(3, 10) but its str would be 3/10
Does that explain the difference between int.__str__(False) and int.__repr__(False) ?
that is because int doesnt explicitly define __str__, so it gets the default one from object, which uses the repr of that particular object
no, that one is just a different matter
a non-overridden __str__() defaults to the .__repr__() of the argument to the method
basically it goes like this
int.__str__(x)
|
unimplemented; is equivalent to
v
object.__str__(x)
|
default behavior
v
type(x).__repr__(x)
!e and it's perhaps provable ```py
print(int.str is object.str)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
True
Why I didn't know about this before π
There's still time to submit if you want! From the mailing list:
As always, the deadline of October 30th is not super strict as this is a competition for fun. So even if you're a day or two late, still submit.
where does it say 30 oct
That was in the mailing list
ok
this submission from the first iopcc wouldn't be a bad wallpaper
someone sent me this once
What does that monstrosity do
prints cool if you enter 1 with [any amount of whitespace around it], and bruh otherwise
equivalent to
print("cool" if input("enter number: ").strip() == "1" else "bruh")
the function O0O0O0O0000OO0OOO is equivalent to lambda a, b, c: b() if str(a).strip() == "1" else c()
here are some steps i've taken to make sure it is doing exactly that with no other edge cases: https://paste.pythondiscord.com/T4MA . i think all the reduction steps were sound.
Insane
silly challenge i though of, given this code you need to read the contents of flag.txt
import re
def curry(a):
def X(b):
def Y(c):
# todo: fix typo
return a(c(b))
return Y
return X
code = input()
# it's cold outside, all your functions something warm to wear
assert re.match(r"^(\([a-z]+\))*$", code), "wrong format"
assert all(x not in code for x in ("eval", "exec", "breakpoint")), "no rce please"
assert len(code) < 105, "too long"
eval(code)
what would you use uppercase letters for?
for fun
thats the spirit
did your solution use any functions other than ||curry, input (to get flag.txt), open, list (to read from the file), print||?
because given this set of things
||
from collections.abc import Callable
type F[A, B] = Callable[[A], B]
class Path: ...
class File: ...
class Flag: ...
class Win: ...
def input(x: object) -> Path: return Path()
def open(path: Path) -> File: return File()
def list(file: File) -> Flag: return Flag()
def print(flag: Flag) -> Win: return Win()
def curry[A, B, C](f: F[A, B], /) -> F[C, F[F[C, A], B]]: return lambda x: lambda g: f(g(x))
||
i cant solve it
(yes im using the type system to check this)
I'm on my phone so I can't check, but
||```py
(curry)(curry)(curry)(curry)(curry)(curry)(curry)(print)(curry)(curry)(curry)(id)(str)(input)(open)(list)
should be equivalent to
||```py
print(list(open(input(str(id)))))
```||
it's very funny to work with this broken "curry"
combinatory python calculus
It's surprisingly easy because your only two operations for shaping the call tree are:
- Extend the call tree with another function call, this introduces a new variable
- Transform the call tree by substituting
curryfor the first variable in the tree, this eliminates a variable
Then once you've repeated these operations enough to get a nice call tree, you can substitute the remaining variables for ones of your choice
I'm fairly certain you can only achieve call trees of the form a1(a2(...(an)))(b1(b2(...(bn))))(...)
But no proof
curry is the quixotic bird
wow nice, here's my solution: ||```py
(curry)(curry)(curry)(curry)(curry)(curry)(curry)(curry)(curry)(curry)(curry)(id)(input)(open)(max)(int)
looks like i messed up the length requirement in the original so even my own solution doesn't pass, oops
this is interesting, I didn't think about having two chains of curry (probably since I don't know the first thing about lambda calculus). I just wrote a python script to bruteforce (curry)*n and found that (curry)*11 = e(d(c(b(a))))(g(f)), which is the first one with enough space to fit the whole call chain
python, but numbers
Please react with β
to upload your file(s) to our paste bin, which is more accessible for some users.
Here's all the answers I could find (barely work since they have 104 characters each)
||```py
(curry)(curry)(curry)(curry)(curry)(curry)(curry)(print)(curry)(curry)(curry)(id)(str)(input)(open)(set)
(curry)(curry)(curry)(curry)(curry)(curry)(curry)(print)(curry)(curry)(curry)(id)(input)(str)(open)(set)
(curry)(curry)(curry)(curry)(curry)(curry)(curry)(print)(curry)(curry)(curry)(id)(input)(open)(set)(str)
(curry)(curry)(curry)(curry)(curry)(curry)(curry)(print)(curry)(curry)(curry)(str)(id)(input)(open)(set)
i wonder, is there a way to prove mathematically you need at least 10 instances of the curry function to get the 5 level deep call chain we need?
the simplest way would be to exhaustively check all possible orderings of < 10 curryings
a more elegant proof might exist but brute force is a decent fallback
I tried some experiments with strace and I'm confused
many modules imported at startup, which are defined in actual source code files (for example, stat), don't correspond to any file-opening calls in the strace output; why not?
oh, weird. frozen modules nevertheless have a __file__ and a corresponding file on disk
(or at least they may... ?)
here's something I definitely wouldn't have expected:
$ python -m timeit '2**64'
50000000 loops, best of 5: 8.19 nsec per loop
$ python -m timeit '2**65'
2000000 loops, best of 5: 154 nsec per loop
I mean, 2**64 already doesn't fit in a machine word; I would have expected a breakpoint either between 63 and 64, or between 59 and 60 (because of how the big-int representation works internally).
(And it seems to have gotten worse in 3.14. Weirdly, 3.13 is noticeably slower for the small value, then that fixes itself again.)
somehow on average, 2**128 is faster than 2**127 and 2**129
if it is using a fast exponentiation algorithm then this kinda makes sense as 128 is a power of 2 https://en.wikipedia.org/wiki/Exponentiation_by_squaring
In mathematics and computer programming, exponentiating by squaring is a general method for fast computation of large positive integer powers of a number, or more generally of an element of a semigroup, like a polynomial or a square matrix. Some variants are commonly referred to as square-and-multiply algorithms or binary exponentiation. These c...
Objects/longobject.c lines 4993 to 5000
/* k-ary values. If the exponent is large enough, table is
* precomputed so that table[i] == a**(2*i+1) % c for i in
* range(EXP_TABLE_LEN).
* Note: this is uninitialized stack trash: don't pay to set it to known
* values unless it's needed. Instead ensure that num_table_entries is
* set to the number of entries actually filled whenever a branch to the
* Error or Done labels is possible.
*/```
!e ```py
import dis
dis.dis('264')
dis.dis('265')
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | 0 RESUME 0
002 |
003 | 1 LOAD_CONST 1 (18446744073709551616)
004 | RETURN_VALUE
005 | 0 RESUME 0
006 |
007 | 1 LOAD_SMALL_INT 2
008 | LOAD_SMALL_INT 65
009 | BINARY_OP 8 (**)
010 | RETURN_VALUE
that's approximately the limit before it doesn't optimize out the operation anymore
Python/flowgraph.c line 1742
if ((uint64_t)vbits > MAX_INT_SIZE / wbits) {```
in v ** w, vbits is the number of bits in v and wbits is the converted C size_t of w
MAX_INT_SIZE is 128
if this condition is true, the power is not optimized out
if v is 2 and w is 64, it evaluates to 2 > 128 / 64 => 2 > 2 => False, so it still works there
however, if w is 65, then it becomes 2 > 128 / 65 => 2 > 1 => True, and it doesn't get optimized out
Does anyone have interest in mobile computing? Ive gotten my self hosted discord bot remarkably reliable on Android for 600 people and was wondering if anyone else wanted help doing something similar?
Here are GIFs that are the output generated by my Android and sent in real time to Discord as user responses. I also attached some logs showing my uptime on my Android using Termux.
oh jeez I didn't even think about constant folding lol
cool but wrong channel?
I thought this was for weird use cases? I host it on my phone
Did i get that wrong?
Were there any challenges to get it to run reliably on android?
me being me i'd immediately try every function from sys, os, platform, ctypes... to figure out how it behaves
also phone is a perfectly fine place to host and I have recommended people to use old spare phones for self hosting stuff like that
!epy [*map(print,map(''.join,[map(chr,[121,111,117,32,100,111,110,116,39,116])]))]
:white_check_mark: Your 3.14 eval job has completed with return code 0.
you dont't
So a thermal monitoring script that predicts my phone core temperatures with newtons law of cooling or braille particle physics or gravitationally modeling cache dynamics doesnt count?
Define normal bub
Anything that is less than this
#esoteric-python message
In context of the topic channel, not really
The normal in context of here is how well you could confuse people with your code by the weird quirk of the programming language
Not how cool the project is(even tho it's really cool
read the channel description
golfing, obfuscation, code gore
its about how weirdly and out of way you use the language
also the channel name is "esoteric"-python
esoteric means which is hard to understand for anyone who didn't write it
if you are sorting using bogo sort, it isn't esoteric code
this is not esoteric code:```py
from time import sleep
from threading import Thread
l = [46,6,3,2,1,7,3]
n = []
def sleeper(i):
sleep(i/1000)
n.append(i)
for i in l:
Thread(target=sleeper, args=(i,)).start()
def printer():
sleep(sum(l)/1000)
print(n)
Thread(target=printer).start()
however this is:py
l = [46,6,3,2,1,7,3]
n = []
[t:=import("threading").Thread,*map(lambda i:t(target=lambda: (import("time").sleep(i/1000),n.append(i))).start(),l)]
t(target=lambda: (import("time").sleep(sum(l)/1000),print(n))).start()
both do the same thing btw
Ok thanks
Any ideas on how they might have implemented this function to allow "the elements of the shape parameter to be passed in as separate arguments"?
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.reshape.html
Taking *args and checking if there's more than one, I presume
Sigh I don't know why it's not clicking for me
I'm learning ml right now and running into issues understanding python
!e
def reshape(*shape, foo="bar"):
if len(shape) == 1:
shape = shape[0]
print("shape:", shape)
reshape((10, 20))
reshape(10, 20)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | shape: (10, 20)
002 | shape: (10, 20)
!args-kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
- Decorators (see
/tag decorators) - Inheritance (overriding methods)
- Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
- Flexibility (writing functions that behave like
dict()orprint())
See /tag positional-keyword for information about positional and keyword arguments
dct[something] = dct = {}
I have written code like this in a normal python context. Not very unusual, but it's a line I have to stop at and think about what it's doing.
same with py a ,= awhen a is a one element list
Okay, here's normal esoteric python code:
import ctypes
c = 2<<15
a = iter([ctypes.cast, ctypes.pointer, ctypes.POINTER] *c).__next__
b = iter(((v:=[ctypes.c_float, ctypes.c_long])+v[::-1])*c).__next__
s = lambda n: a()(a()(b()(n)), a()(b( )) ).contents . value
def si(num):
y = s(s(c ** 4*2 ** (-12 / 25)) + int(s(0)) - (s(num) >> 1))
return (3 * y-num*y *y*y)/ 2
to be fair I'd call that actually esoteric, instead of most of the things that get sent here, in your example every part of the code is used, usually people just put a ton of dunders that repeat all throughout
β€οΈβπ©ΉβοΈ
that assigns to dct[something] then resets dct?
nope, = chains are evaluated right to left
dct[something] = (dct = {})
!e that's not valid is it
dct[something] = (dct = {})
:x: Your 3.14 eval job has completed with return code 1.
001 | File [35m"/home/main.py"[0m, line [35m1[0m
002 | dct[something] = ([1;31mdct = {}[0m)
003 | [1;31m^^^^^^^^[0m
004 | [1;35mSyntaxError[0m: [35minvalid syntax. Maybe you meant '==' or ':=' instead of '='?[0m
!e that's not valid is it
dct['h'] = dct = {}
print(dct)
:x: Your 3.14 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m1[0m, in [35m<module>[0m
003 | [1;31mdct[0m['h'] = dct = {}
004 | [1;31m^^^[0m
005 | [1;35mNameError[0m: [35mname 'dct' is not defined. Did you mean: 'oct'?[0m
That's also not valid unless dct is defined in which case that assignment isn't useful
they're not
rightmost expression first, then left-to-right assignment
i think they mean ```py
dct = dct[something] = {}
that's recursive though
hmm
if dct referred to a finished state transitioning into a new one then that earlier sample might make more sense
i questioned my reality there for a second..
Yes it has to be defined beforehand and no, it's still useful.
It's equivalent to:
tmp = {}
dct[someting] = tmp
dct = tmp
I'm using it for generating nested dictionaries. Of course you have to keep the reference to the original value of dct somewhere else.
is it just dct = {something: dct} then?
how do you set tp_call on a pytypeobj using ctypes?
It seems like the memory offset of tp_call is 0x80
but it seems like ```py
call_offset = 0x80
cfunc_t = ctypes.CFUNCTYPE(ctypes.py_object, ctypes.py_object, ctypes.py_object)
p = ctypes.POINTER(cfunc_t).from_address(id(my_class) + call_offset)
it seems like I'm in poking in the right place of the memory too, a couple bytes later at offset 0xa8 I can correctly retrieve tp_flags
ok I think I figured it out, this works ```py
call_offset = 0x80
cfunc_t = ctypes.CFUNCTYPE(ctypes.py_object, ctypes.py_object, ctypes.py_object)
func_ptr = ctypes.cast(id(my_class) + call_offset, ctypes.POINTER(cfunc_t))
nope !
chirk was being c-shaped
new dct is the one inside of the old one
Here's a puzzle:
What does this code do?
is this like the inverse sqrt code?
I'm seeing some floats being cast as integers and that reminds me of that
!e alchemy ```py
print(
"lead".encode("037")
.decode("860")
.encode("1026")
.decode("koi8_r")
.encode("maccyrillic")
.decode("932")
.encode("jisx0213")
.decode("uhc")
.encode("johab")
.decode("855")
.encode("1125")
.decode("037")
)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
gold
What all kinds of translations are possible?
Noticeably some of these encodings go from a codepoint to multiple bytes, and some to a single byte
so I feel you can actually do a ton of funkiness
I am not sure actually
you can do a lot with the help of punycode, since it allows you to add a dash to the end
and then you can try to bruteforce changing that dash into whatever you want
Hm
It's also possible to start from empty string, like"" -> "hello"
Which codec?
!e ```py
print(
"".encode("utf_8_sig")
.decode("mac_croatian")
.encode("037")
.decode("maclatin2")
.encode("jisx0213")
.decode("1251")
.encode("koi8_u")
.decode("big5")
.encode("uhc")
.decode("273")
.encode("mac_croatian")
.decode("koi8_r")
.encode("cp875")
.decode("1252")
.encode("437")
.decode("037")
)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
hello
I wonder if it's possible to reformulate this as some sort of mathematical problem, with composition of like permutations or something
What code are you using to generate these
I made a bruteforcer in python :P the hello one takes like half an hour
i can upload my code to gists if you want? It's not super interesting
Right I was just wondering if you did anything funky with the code
yeah no clever tricks sadly :(
Regardless I think "pick a sequence of functions from a list to compose that maps a given input to a given output" is not a polynomial problem
surely its a pathfinding problem ?
are these all actual valid encodings?
yes, they're all built in to python if that's what you're asking
many of them have aliased names fwiw. the ones that are just a numeric string, for example, are really that numbered code page
If you take all nΓn pairs of encodings, you could calculate how the composition maps each character (at least in the simpler cases where the input and output strings would have the same length).
I'm assuming not many of the codecs require actual complicated processing, just replacing certain bytestrings with sets of characters and vice versa.
From there it would just be pathfinding.
You wouldn't have much in the way of heuristics to guide you, so it might just be a bidirectional breadth-first search.
Yes, and the depth of the search tree is unknown to you (technically it's constant, but...)
If we restrict to only single-byte code pages, then each pair of encode/decode calls is a permutation of codepoints altering at most 256 elements. The set of permutations generated by these base cases is a very small subset of the set of total possible permutations of codepoints, but still fairly significant because function composition is not commutative. I think in practice most codepoints will be untouched, leaving only a few thousand entries. Of these few thousand, I strongly doubt we can generate arbitrary permutations, so the number of total permutations helpfully ends up... somewhere below [few thousand] factorial.
Every operation (I would hope) has an inverse, so in that setting it's a group, and you can use group theory to help.
I'm not up to scratch on my group theory enough to know how.
yeah most do, there are some edge cases but you can either stop using the encoding completely (unicode escape, utf7) or manually filter out errors
I remember seeing this in a YouTube video on solving Rubikβs cubes, maybe you could speed it up by going from both sides at once? (Ie, try to turn the source string into the target, and at the same time the target into the source, so that the search trees might meet in the middle, reducing the time spent in the exponential search space growth)
I'm actually doing 3 of those, one to get a common result, then one from each side to the common result
since storing the paths for all results in the first search takes too much memoery
new programming book intro
I recently ran into a problem where I wanted to reference a class while it's still being defined inside a class variable, and instead of doing anything more reasonable I have birthed this extremely cursed code:
!e ```py
from dataclasses import dataclass
import inspect
from typing import Final, Never, override
class _Placeholder:
def init(self):
frame_stack = inspect.stack()
if not frame_stack:
raise RuntimeError("Your python implementation does not support stack frames (inspect.stack() returned no frames)")
if len(frame_stack) < 3:
raise RuntimeError("Tried to use Placeholder at top level, only usage inside classes is supported")
object.setattr(self, "error", RuntimeError(f"Tried to use Placeholder object stemming from location {frame_stack[2].filename}:{frame_stack[2].lineno}. Containing class is most likely missing fix_class_placeholders decorator (or the decorator has a bug)."))
def __call__(self, *_args: object, **_kwargs: object) -> Never:
raise self.error
def __getattr__(self, name: str, /) -> Never:
raise self.error
@override
def __setattr__(self, name: str, value: object, /) -> Never:
raise self.error
class S[T]:
def new(cls) -> T:
return _Placeholder() # pyright: ignore[reportReturnType]
def fix_class_placeholders[T: type](cls: T) -> T:
seen: list[object] = []
stack: list[object] = [cls]
while stack:
current = stack.pop()
if not hasattr(current, "dict"):
continue
for name, item in vars(current).items(): # pyright: ignore[reportAny]
if isinstance(item, _Placeholder):
setattr(current, name, cls)
elif item in seen:
pass
else:
stack.append(item) # pyright: ignore[reportAny]
seen.append(current)
return cls
@dataclass
class Storage[T]:
item: T
@fix_class_placeholders
class Test:
test: Final = Storage(S"Test")
print(Test.test)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
Storage(item=<class '__main__.Test'>)
If it's just memory, you could also use iterative deepening depth-first search, which is constant-memory, just quite slow.
Actually, you could probably do breadth-first search but with a pair of bloom filters, and take the overlap of them for candidates...
While trying my hand at this using a look-up graph, I managed to incidentally create modern art
Lmao
hello world
class complex(zip(), zip(__name__), zip(__file__), zip(), zip(r'u'"n"), zip()):
__annotations__ = vars()
hel = help
__firstlineno__ = locals()[r""u'''d
'''fr''] = __module__
exc: Exception = StopIteration
del [__firstlineno__]
def OSError(file, error, traceback):
try:
for breakpoint, frame in zip(error, complex):
attrs = dict.pop(traceback, "__static_attributes__", error[:0x44a16_55e148b & -~0o0])
traceback = dict(tuple(dict.items(traceback))[0b10 -~- len(attrs)::])
return frame
finally:
return getattr(breakpoint, file)(*error[+0x1:], **traceback)
class to_bytes(0x6f207_76f726c, --0o6, f'b'"ig"u'', metaclass=OSError):
list(zip(complex, type(...).__bases__))
class print(__builtins__, next(complex)[0o_2], to_bytes.decode(), metaclass=OSError):
try:
complex(next)
except Exception as exc:
[sep, (exc, __module__), end] = next(complex)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | /home/main.py:16: SyntaxWarning: 'return' in a 'finally' block
002 | return getattr(breakpoint, file)(*error[+0x1:], **traceback)
003 | hello world
* for reference...
https://github.com/python/cpython/blob/main/Include/internal/pycore_unicodeobject.h#L42-L93 (standard conversion)
seems to be something with the difference in treatment between the encoding and decoding of the bytes...
as for a deterministic way to know what would happen from/to each character; some more research into the mapping is needed.
from the latest unicode update β
β’ https://www.unicode.org/reports/tr10/tr10-53.html
β’ https://standards.iso.org/iso-iec/14651/
anyhow, this is an interesting idea; might look into it later π
Does this count as esoteric Python:
https://coconut-lang.org/
Simple, elegant, Pythonic functional programming.
wtf is this
match [head] + tail in [0, 1, 2, 3]:
print(head, tail)
!e you can find them all like this: py from encodings.aliases import aliases print(' '.join(sorted(set(aliases.values())))) the codecs library accepts even more, such as "hex" which was the bytes.hex equivalent in python 2.7
:white_check_mark: Your 3.14 eval job has completed with return code 0.
ascii base64_codec big5 big5hkscs bz2_codec cp037 cp1026 cp1125 cp1140 cp1250 cp1251 cp1252 cp1253 cp1254 cp1255 cp1256 cp1257 cp1258 cp273 cp424 cp437 cp500 cp775 cp850 cp852 cp855 cp857 cp858 cp860 cp861 cp862 cp863 cp864 cp865 cp866 cp869 cp874 cp932 cp949 cp950 euc_jis_2004 euc_jisx0213 euc_jp euc_kr gb18030 gb2312 gbk hex_codec hp_roman8 hz iso2022_jp iso2022_jp_1 iso2022_jp_2 iso2022_jp_2004 iso2022_jp_3 iso2022_jp_ext iso2022_kr iso8859_10 iso8859_11 iso8859_13 iso8859_14 iso8859_15 iso8859_16 iso8859_2 iso8859_3 iso8859_4 iso8859_5 iso8859_6 iso8859_7 iso8859_8 iso8859_9 johab koi8_r kz1048 latin_1 mac_cyrillic mac_greek mac_iceland mac_latin2 mac_roman mac_turkish mbcs ptcp154 quopri_codec rot_13 shift_jis shift_jis_2004 shift_jisx0213 tis_620 utf_16 utf_16_be utf_16_le utf_32 utf_32_be utf_32_le utf_7 utf_8 uu_codec zlib_codec
now i'm not sure about the mac_croatian because it's a keyerror for the aliases dict but encoding strings works normally
reminiscent of some of olivia's work
i think it was called hoopy?
cute stuff
!e I'm wondering if there can be made a fractran like turing complete language out of this? Seems unlikely so far but you never know
S = "testing padding handling"
prog = """+punycode/-u8/+utf_8_sig/-kz1048/+ptcp154/-utf_8/+cp864/-mac_arabic/+idna/-idna
+mac_arabic/-cp1251/+iso8859_5/-cp1257/+iso8859_10/-cp855/+koi8_r/-iso8859_6/+cp1256/-koi8_r/+cp855/-mac_arabic"""
while~0:
for t in prog.split():
try:
temp = S
for c in t.split("/"): temp = temp.encode(c) if c[0] == "+" else temp.decode(c)
S = temp
break
except Exception: pass
else: break
print(S)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
(((((((((((((((((((testing padding handling)))))))))))))))))))
if we can show how to make a turing complete markov algorithm then it might be possible
you can only ever alternate encode and decode steps in 3.x, because of the type requirements, so the encoding direction doesn't need to be... encoded in prog
also why wouldn't the +idna/-idna pair be a no-op?
That makes the program terminate
Otherwise it would keep adding parens, but idna enforces a max length
ah, that's what the outer loop is for, ok
class Greetings:
def __init__(self, mornin=True):
if mornin:
self.greeting = "nice day for fishin'!"
else:
def evening():
return "good evening"
self.__init__ = evening
print(Greetings().greeting)
print(Greetings(mornin=False).__init__())
!e
import inspect
import linecache
import ast
def debug(*values):
frame = inspect.currentframe().f_back
info = inspect.getframeinfo(frame)
src_lines = [linecache.getline(info.filename, ln).strip() for ln in range(info.positions.lineno, info.positions.end_lineno + 1)]
src_line = "\n".join(src_lines)
tree = ast.parse(src_line)
call = tree.body[0].value
for n, v in zip(call.args, values):
print(f"# {ast.unparse(n)}: {type(v).__name__} #\n{v}\n")
import random
debug(num := random.randint(0, 100))
x, y = num * 2, num / 2
debug(x, y, x == y)
def my_func(true: False):
return "False" if true is False else true is False
debug(my_func(True), my_func(False))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | # (num := random.randint(0, 100)): int #
002 | 2
003 |
004 | # x: int #
005 | 4
006 |
007 | # y: float #
008 | 1.0
009 |
010 | # x == y: bool #
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/JHWAYS46FOBP6QARGQXJ4AMJVA
I was too lazy to keep writing print(f"{number=}") so I had to do a thing
print = lambda x: text.insert(END,x+'\n') or output.see(END)
reminds me of when i was too lazy to replace all my prints to outputting in the textbox when i was making my backend work with tkinter
rename symbol was invented in
Imagine if LSP renaming builtins would reach into the interpreter binary to change their name
hey
just made an ai
asking for suggestions
nlsbot.netlify.com
Bro wtf is this
Can U share the datasets U used to train this
!e
def empty():
_: (yield)
print(list(empty()))
:x: Your 3.14 eval job has completed with return code 1.
001 | File [35m"/home/main.py"[0m, line [35m2[0m
002 | _: ([1;31myield[0m)
003 | [1;31m^^^^^[0m
004 | [1;35mSyntaxError[0m: [35myield expression cannot be used within an annotation[0m
the !e has to go at the beginning the first time
:white_check_mark: Your 3.13 eval job has completed with return code 0.
[]
Is there a good way (other than disabling virtual memory system wide) to tell python to raise a memory error as soon as it detects that its getting pushed to swap space? Or perhaps to hook the gc to predict when this is an issue and set my own semaphore to start terminating long running memory hogs.
Maybe you can infer this from the results of resource.getrusage. Otherwise, maybe the third party psutil package might let you ask the necessary questions.
!doc resource.getrusage
resource.getrusage(who)```
This function returns an object that describes the resources consumed by either the current process or its children, as specified by the *who* parameter. The *who* parameter should be specified using one of the `RUSAGE_*` constants described below.
A simple example...
There's also resource.setrlimit which would let you set a memory limit ahead of time.
Oh, nice!
I've built a fifo chain_set class (inspired by collections.ChainMap) which should avoid the issue, but resource.setrlimit looks like exactly what I want. Thanks.
on linux you can use the mlockall() syscall with MCL_CURRENT|MCL_FUTURE flags
this forces all pages to be resident in RAM and you will get an ENOMEM if malloc (etc.) would exceed available RAM
found a helper someone made: https://github.com/kopchik/useful/blob/master/mlockall.py
Hmm! Ok wow.
I'm going to try the resource.setrlimit() route first... Then we'll see
Define a periodic-N program as a string such that if it is repeated some number k>0 times, it prints f'periodic-{N}' iff k is divisible by N. For example, the following is a period-41 program (note the lack of trailing newline):
.1
i = i + 1 if 'i' in dir() else 1
class a:__add__ = lambda*s:print('period-41') if s[1] == 1 and i % 41 == 0 else ...
a()+1``` What is the shortest period 41 program?
.1
i=('i'in dir()and i)+1
class a:
def __add__(s,o):not(o+i)%41and print('period-41')
a()+0```
this has length 92
i feel like it can be shorter
but im sleepy
85 py .1 i=('i'in dir()and i)+1 class a: def __gt__(s,o):o+i%41or print('period-41') a()>0
this should work for 62?
()if()else()
i=('i'in dir()and i)+1
1>i%41==print('period-41')
print('period-1')
I think this one is the most boring
()if()else()
try:i+=1
except:i=1
1>i%41==print('period-41')
59 with a simple improvement
the empty program works for period-0
Sadly not really...
repeated some number k>0 times, it prints f'periodic-{N}' iff k is divisible by N
nothing is divisible by 0, hence the print is never needed
Wait, this is esoteric python. Then assuming esoteric math objects seems like a fair game. What would do the trick? The 1/Ο seems appealing. Though how such program should look like, what does it even mean to repeat a program by fractional amount?
But writing the periodic-Ο version sounds possible and like an interesting problem.
Continuing this chain of thoughts, I also " am opening a bounty" for a solutions to periodic-i programs (reward is imaginary). Of course this is only theoretical computation, so it has to work only in theory (what theory - there's a lot of leeway in interpreting this).
Is it possible to allow x / 0 to equal +-inf, using C extensions.
!e Yes
import fishhook
@fishhook.hook(float)
@fishhook.hook(int)
def __truediv__(self, other):
if other != 0:
return fishhook.orig(self, other)
if self > 0:
return float("inf")
return -float("inf")
print(23/0)
:white_check_mark: Your 3.13 eval job has completed with return code 0.
inf
Would periodic-Ο mean something that doesn't print anything for any finite n but would for an infinite string?
So like ~print('period-Ο')@? All finite n exit with syntax error, but the infinite expression could be parsed (?) and would execute one print before exiting.
repeating a program of length β by a rational z/β is well defined
but its not really possible to write a program that would work for most z
would that be taking the first z characters?
since this is esoteric channel
return(fishhook.orig(self,other),(-1*(self<0)+(self>0))*float('inf'))[other==0]```
I think so
This doesn't evaluate lazy-ly. x/0 is evaluated (in .orig(self, other)) when creating the tuple
return(other==0and(-1*(self<0)+(self>0))*float('inf'))and fishhook.orig(self,other)```
cond and true-case or false-case
also you can do self * float('inf') if its -ve, it will become -inf
can also be done yes
yeah when I wrote the first code I woke up from sleep at morning so that was the best I could think and, currently I just moved things here and there
can it print something else in other cases?
try:i+=1
except:i=1
print((i%41==0)*'period-41')
49 with required trailing newline
(a few more to clean up the output newlines)
it can be further reduced while not printing anything else
Won't this print for any k>=41?
prints a newline for any k%41 != 0, yes
But it would also output "period-41" on every 41st line
even if the final k is not divisible by 41
yes, but so do the previous submissions afaict
unless I missed something about the logic?
I mean, as the code executes, it doesn't know that there will be more copies
... oh, that's why some variation of "no trailing newline" trick is actually required. never mind then
... wait
yeah, ok I understand it now, but there is still an improvement
if there was a trailing newline equivalent it'd be pretty cool though
()and 0
try:i+=1
except:i=1
1>i%41==print('period-41')
fails after i==41
... wow, something really weird with precedence then
that first () attaches to the print and gets cancelled by the always-false condition in the next repeat of the first line
but with the conditional expression, the if-clause is evaluated first, yeah
if the code doesn't repeat, it's neither invalid nor cancelled because the first line doesn't repeat after it anymore
so basically a "don't execute if it repeats" thing
yeah I'm just not thinking straight at the moment
boo, other ideas also went nowhere.
for zβ€β, yes
for z>β, it would be βz/ββ repetitions of the string plus the first (z mod β) characters of the string
i think thats a fairly sensible definition
doesnt work if true-case is falsy
just make it (1,true-case)[0]
then the overall expression doesnt evaluate to the result of true-case
which is fine for some cases i guess
(cond and[truecase]or[falsecase])[0] is more general
π
To understand the true nature of Python, one must look beyond the surface. What you perceive as mere syntax, others see as a canvas for profound techniques.
While many follow the conventional path, there exists a deeper realmβthe realm of Esoteric Python. It is here that one encounters concepts like the Global Interpreter Lock, a binding that can be transcended by those who grasp its true form. The interned integers, seemingly simple, are but fragments of memory existing in an eternal cycle. Metaclasses, the unseen architects, shape the very essence of the classes you believe you command.
You prioritize clarity; others seek a different form of expression. Code can exist in unexpected forms, hidden within the patterns of a Piet painting or concealed within the Whitespace of a document. To truly comprehend the system, one must be willing to confront its most intricate aspects.
You reside in a world of f-strings and PEP 8. Others operate within the reality of the underlying bytecode. Their code is not designed for easy comprehension; it is designed to be understood on a different level.
this is a lot of philosophy for what is basically code chaos
that's a lot of philosophy for what is basically ai slop
real
Thatβs a lot of yapping to say βcode can be artβ
lot of slopping*
You're just jealous because you can't operate within the reality of the underlying bytecode.
mb i couldnt see the underlying forms and patterns of code and transcended the realms of mere syntax into the canvas for profound techniques
heyy guys~i just find out, my codes are working on other sites~do you have any idea why the site is not sharing data. And when i run the code, the site does know "I am automating". Is there a way to hide my presence from website and fetch the data?
1.) Not on-topic for this channel, please read channel descriptions. 2.) Not something we help with anywhere on the server.
i see
why are you scrapping NSE they have public api of their own
Hello guy I need expert Python developer for Capcut APK device register
I'm willing to pay a reasonable payment after you complete my work
!rules 6 9
6. Do not post unapproved advertising.
9. Do not offer or ask for paid work of any kind.
Hi everyone π
Iβm new here and wanted to share DeepCSIM
https://github.com/whm04/deepcsim
an open-source Python tool that uses AST analysis to detect structural and semantic code similarity.
Itβs helpful for refactoring, duplicate code detection, and code quality analysis.
Feedback and testing are very welcome thanks!
how can i check if my breseham's 3d line algorithm is right?
Write some unit tests that exercise the corner cases that you are concerned about and check that your function returns the expected values.
There was an error uploading your paste.
never heard of esoteric python
!e here's an introduction
from __future__ import barry_as_FLUFL
(lambda*_:[__import__(*_).main for{}[()]in _])("__hello__")[()<>()]()
:white_check_mark: Your 3.14 eval job has completed with return code 0.
Hello world!
Yea im never looking at it again
@sick hound would you like a little challenge?
luckily wayback has archived the file
# The hardcoded hash stored inside the VM's bytecode array 'C'
TARGET_HASH = "7349175c986967e812397682855ec9009943486c676d296213567073b6480982"
def main():
user_input = input("Enter password: ")
# Generate SHA-256 hash of the input
input_hash = hashlib.sha256(user_input.encode('utf-8')).hexdigest()
if input_hash == TARGET_HASH:
print("Correct!")
else:
print("Incorrect.")
if __name__ == "__main__":
main()```
was i right?
@magic wraith
you didnt even change the opcodes. google gemini deobfuscated it in 30 seconds
mind you, that is two and a half years old
no, that is NOT right
not even close
idk what you did, you maybe fed the wrong file to gemini
but the main.py literally tells you what the goal is
oh yea i didnt see main.py mb. i think it hallucinate the entire file. good job. im too lazy to touch the obfuscated code myself
if you're too lazy to do the challenge why would you respond lol
!e
message = "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"
print(''.join(chr(int(''.join(str(ord(c) - 8203) for c in message)[i:i+8], 2)) for i in range(0, len(message), 8)))
:white_check_mark: Your 3.14 free threaded eval job has completed with return code 0.
Hello World!
I wrote a blog post about our IOPCC entry this year: https://bulmenisaurus.github.io/blog/iopcc-2025
oooh!!
!e
def lmfao(a: str):
def g(x):return x&0xFF
v=t=x=0;p=[]
for h in list(a):
match h:
case'd':v=g(v-1)
case')':v=p.pop()if p else 0
case';':v=g(v+1)
case'9':p.append(v)
case'$':v,t=t,v
case'[':print(chr(v),end='')
case'4':v=g(v-t)
case':':v=g(v*t)
case'<':v=g(v+t)
case'>':v,x=x,v
case'8':v=g(v//t)
case']':v=g(v**t)
lmfao(";;;$<:d::[$d$$;]>;;;;;;$44$>4[>;$><[[9;;;[9>$8;;$8<[4444>$>$4[)[;;;[)[>$844$>4[>$ddd$];[")
:white_check_mark: Your 3.14 eval job has completed with return code 0.
Hello World!
!e
Py```answer = input("Are you gay? (y/n): ").strip().lower()
if answer == "y":
print("\nπ A Letter For You π\n")
print(
"Being gay is completely okay.\n"
"You are not broken, wrong, or different in a bad way.\n"
"You are human, just like everyone else, and you deserve respect,\n"
"love, and happiness exactly as you are.\n"
"Never let anyone tell you otherwise.\n"
)
elif answer == "n":
print("\nYou are monkey π\n")
print(r"""
,
(o,o)
/)__)
" "
""")
else:
print("Please type only 'y' or 'n'.")```
:x: Your 3.14 eval job has completed with return code 1.
001 | Are you gay? (y/n): Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m1[0m, in [35m<module>[0m
003 | answer = [31minput[0m[1;31m("Are you gay? (y/n): ")[0m.strip().lower()
004 | [31m~~~~~[0m[1;31m^^^^^^^^^^^^^^^^^^^^^^^^[0m
005 | [1;35mEOFError[0m: [35mEOF when reading a line[0m
!e
answer = input("Are you gay? (y/n): ").strip().lower()
except EOFError:
answer = "y" # default if input is not allowed
if answer == "y":
print("\nπ A Letter For You π\n")
print(
"Being gay is completely okay.\n"
"You are human, valid, and deserving of respect.\n"
"You are not different in a bad way.\n"
)
elif answer == "n":
print("\nYou are monkey π\n")
print(r"""
__,__
(o,o)
/)__)
" "
""")
else:
print("Please type only 'y' or 'n'.")```
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | Are you gay? (y/n):
002 | π A Letter For You π
003 |
004 | Being gay is completely okay.
005 | You are human, valid, and deserving of respect.
006 | You are not different in a bad way.
tf
!e
code
!eval [3.12] < def pizza_order():
print("Welcome to Python Pizza Deliveries!")
prices = {
"small": 10,
"medium": 12,
"large": 15,
"cheese": 1,
"olives": 2,
"sausage": 3
}
size = input("What size pizza do you want? (Small/Medium/Large): ").lower()
bill = 0
if size == "small":
bill = prices["small"]
elif size == "medium":
bill = prices["medium"]
elif size == "large":
bill = prices["large"]
else:
print("Invalid size selected.")
return
topping = input("Choose a topping (Cheese/Olives/Sausage): ").lower()
if topping == "cheese":
bill += prices["cheese"]
elif topping == "olives":
bill += prices["olives"]
elif topping == "sausage":
bill += prices["sausage"]
else:
print("Invalid topping selected.")
return
print(f"\nYour final bill is: ${bill}")
print("Thank you for your order!")
pizza_order()>
I would consider this to be 0 errors.
!eval ```py
def pizza_order():
print("Welcome to Python Pizza Deliveries!")
prices = {
"small": 10,
"medium": 12,
"large": 15,
"cheese": 1,
"olives": 2,
"sausage": 3
}
size = "small" # input("What size pizza do you want? (Small/Medium/Large): ").lower()
bill = 0
if size == "small":
bill = prices["small"]
elif size == "medium":
bill = prices["medium"]
elif size == "large":
bill = prices["large"]
else:
print("Invalid size selected.")
return
topping = "cheese" # input("Choose a topping (Cheese/Olives/Sausage): ").lower()
if topping == "cheese":
bill += prices["cheese"]
elif topping == "olives":
bill += prices["olives"]
elif topping == "sausage":
bill += prices["sausage"]
else:
print("Invalid topping selected.")
return
print(f"\nYour final bill is: ${bill}")
print("Thank you for your order!")
pizza_order()
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | Welcome to Python Pizza Deliveries!
002 |
003 | Your final bill is: $11
004 | Thank you for your order!
try looking into using dict.get(); instead of having an if-elif tower.
also this channel is for #esoteric-python and weird code golfs. the #bot-commands is better suited for testing your code out.
untested golf ```py
P=lambda m,t:{"small":10,"medium":12,"large":15,"cheese":1,"olives":2,"sausage":3}.get(input(m).lower())or print("Invalid",t,"selected.")
def f():
print("Welcome to Python Pizza Deliveries!")
if b:=P("What size pizza do you want? (Small/Medium/Large): ","size"):a=b;b=P("Choose a topping (Cheese/Olives/Sausage): ","topping")
if b:print(f"\nYour final bill is: ${a+b}\nThank you for your order!")
pizza_order=f;f()
okie
!eval message = "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"
print(''.join(chr(int(''.join(str(ord(c) - 8203) for c in message)[i:i+8], 2)) for i in range(0, len(message), 8)))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
Hello World!
zero-width whitespace being decoded, I assume?
!eval print(__import__('unicodedata').name(chr(8203)))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
ZERO WIDTH SPACE
What is a code golf?