#esoteric-python
1 messages · Page 51 of 1
you seem to be talking about this, but it's part of the parser generator and not the tokenizer
Tools/peg_generator/pegen/parser.py line 165
SOFT_KEYWORDS: ClassVar[Tuple[str, ...]]```
it is in the Grammar/tokens file iirc
Grammar/python.gram line 1186
| !(NAME STRING | SOFT_KEYWORD) a=disjunction b=expression_without_invalid {```
it's interpreted by the parser generator as a marker that generates _expect_soft_keyword() in the parser
above is wrong, apparently, it calls a different function _soft_keyword_token()
which basically parses a soft keyword, that's it
it also allows weird errors like this ```pycon
(a x)
File "<stdin>", line 1
(a x)
^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
(_ x)
File "<stdin>", line 1
(_ x)
^
SyntaxError: invalid syntax
``` since_is a soft keyword, the "Perhaps you forgot a comma?" message isn't triggered
fun side note: the name comparison is a little scuffed, so prefixes of soft keywords also get captured for that token
If Python follows modern trends, v4.0 will probably have a flag to compile the source to JS instead of bytecode 😛
Oooh, we didn't try _
It seemed like the parser was tokenizing everything as NAME
but I can suggest @upbeat folio try _
Oh, thanks!
Looks like it's not specific to the _
>>> (match x)
File "<python-input-0>", line 1
(match x)
^
SyntaxError: invalid syntax
So _ or match is both a NAME and a SOFT_KEYWORD, like + is both an OP and a PLUS? I guess I don't understand tokens as well as I should, when I'm trying to document them :)
python/cpython#125482
!e coming in 3.14
this won't produce an error ```py
from future import barry_as_FLUFL
print(1 <> 2) # True
:x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 3
002 | print(1 <> 2) # True
003 | ^^
004 | SyntaxError: invalid syntax
What would <> do?
Just an alternative spelling of !=. It's an old April Fools joke.
!pep 401
*the new spelling of !=, cannot be undone ||(in the python session)|| once changed
Donne moi un code css pour styli
Styliser mes menu de navigation avec
thats just invalid response
the challange states that your code should execute after the execution of snippet ```py
def nuke():
global builtins
import sys, gc
g = globals()
builtins.dict.clear()
builtins={}
g.clear()
sys.modules.clear()
gc.collect()
return sys.stdout
nuke()```
you modified the last line of snippet which is wrong
Anyhow, that's not a proper solution (the new line should be present) (that's also the reason this is not a spoiler).
yeah its not a sol in any way you just made the code not run, which is same as just running print('hello world')
Also technically, in the challenge message, it contain a new line, as
print("Hello World")
Which contains a new line before end of code block and
print("Hello World")```
Without contains a new line before end of code block are valid syntax
So it can be consider that the new line after `nuke()` is part of the challenge (as a new line is used(
Therefore it's not a solution as it requires omitting a new line character from the original challenge
I think I got close with one of my approaches to restoring the interpreter, but I'm stuck. ```py
().class.base.subclasses()[120].load_module("builtins").print("Hello, World!")
At least for me on `Python 3.12.9`, `120` is `<class '_frozen_importlib.BuiltinImporter'>`, and this works in normal code, but sadly I can't get any of the import methods working after `nuke`, since they all give ```py
Traceback (most recent call last):
File "a.py", line 13, in <module>
File "<frozen importlib._bootstrap>", line 530, in _load_module_shim
NameError: name 'DeprecationWarning' is not defined
I managed to make it one step further, ```py
nuke()
().class.base.subclasses()[114].init.builtins["DeprecationWarning"] = ().class.base.subclasses()[113].subclasses()[1].subclasses()[-2].subclasses()[1]
().class.base.subclasses()[120].load_module("sys")
`114` is `<class '_frozen_importlib._WeakValueDictionary'>` but there are a lot of different values that will work, `113` is `<class 'BaseException'>`
It now dies with ```py
Traceback (most recent call last):
File "a.py", line 14, in <module>
File "<frozen importlib._bootstrap>", line 531, in _load_module_shim
File "<frozen importlib._bootstrap>", line 665, in spec_from_loader
NameError: name 'getattr' is not defined
I opened laptop to continue building LFS but now I am going to do this, thanks, moral of story: never keep esoteric-python open
huh?
what python version?
nvm got it you are running on 3.12
If you’re on 3.13 it might just be +2 to all the numbers
Yep, but there was also a new error so this works for 3.13 ```py
nuke()
().class.base.subclasses()[116].init.builtins["DeprecationWarning"] = ().class.base.subclasses()[115].subclasses()[1].subclasses()[-3].subclasses()[1]
().class.base.subclasses()[122].load_module("builtins")
"works" as in gets the same error
Actual attempt to recover instead of just somehow printing it🥴 nice
I DID IT
exit code 0, Hello, world! on stdout
102 chars
||py 0 .__class__.__base__.__subclasses__()[114].__init__.__globals__['sys'].stdout.write("Hello, world!\n")||
NOTE: works on 3.12 only
solved
it can work on other versions as well just require changing index of subclass
Next: try make it shorter than 31 (I think that's someone that makes it by warning) lul
now I think it can be completely recovered in similar way
Here's a really ungolfed attempt on making total system recovery form nuke(). (It's not fully functional, some things are missing, I currently know only of missing open() function, probably more.) Size - I don't even want to know.
||```py
def nuke():
global builtins
import sys, gc
g = globals()
builtins.dict.clear()
builtins={}
g.clear()
sys.modules.clear()
gc.collect()
# return sys.stdout.write
nuke()
out = nuke()
pr = lambda x: out(x.class.repr(x)+"\n" if "self" in x.repr.dir() else x.repr(x)+"\n")
subs = "".class.base.subclasses()
find = lambda se: [el for el in subs if se in el.name]
def _hasattr(obj, name):
try:
obj.getattribute(name)
return True
except:
try:
obj.getattr(name)
return True
except:
return False
def _getattr_u(obj, name):
try:
return obj.getattribute(name)
except:
return obj.getattr(name)
def _getattr_s(obj, name, defa):
try:
return obj.getattribute(name)
except:
try:
return obj.getattr(name)
except:
return defa
def _getattr(*args):
if args.len() == 3:
return _getattr_s(*args)
return _getattr_u(*args)
gl = find("_WeakV")[0].init.globals
gl["hasattr"]=_hasattr
gl["getattr"]=_getattr
imp = gl["BuiltinImporter"]
spec = imp.find_spec("builtins")
mod = imp.create_module(spec)
imp.exec_module(mod)
builtins = mod
gl["builtins"].update(mod.dict)
del gl["hasattr"]
del gl["getattr"]
gl["sys"].modules["sys"]=gl["sys"]
gl["sys"].modules["_imp"]=gl["_imp"]
print("Hello World!")
import sys
sys.exit(0)
why sys.exit(0)
I mean its useless it will exit with 0
To show that I can import stuff.
Oh 🥴
Guys, whats the nastiest one-liner you ever wrote
damn the fuck
Do you count as literal a single line, or semi colon isnt accepted
unfinished, I am writing tictactoe
also another one is 15.6k chars long hello world which uses freaking globals to generate '__import__("__hello__").main()'
Technically could be a single line, this solution for AoC 2023 day 5: https://pastebin.com/R2Jfx8Vs ```py
print(sum(int(x) * int(y) for x, y in [(filter(None, x),) for x in import("re").findall(r"<33k char long generated regex>", import("re").sub(r"[^\d\n.]", ".", open(0).read()))]))
lmao 33k char'
must work when you just copy+paste it into a python interactive shell and press enter once
Then a semi colon is accepted, ok
brainfuck interpreter in a-z() python
set((((p)in(range(len(a))))or(exit()))and((b)in(str(float()))and(print(chr(c))))for(l)in(str(int()))for(a)in(input()for(l)in(l))for(d)in(sum(len(str(filter))for(i)in(range(len(str(filter)))))for(l)in(l))for(e)in(max(range(d))for(l)in(l))for(f)in(min(str(list()))for(l)in(l))for(g)in(max(str(list()))for(l)in(l))for(p)in(range(not()))for(k)in(range(not()))for(m)in(bytes(sum(range(ord(str(int())))))for(l)in(l))for(n)in(list(tuple((next(iter(j)))if(i)else(o)for(i)in(range(len(str(())))))for(q)in(list()for(l)in(l))for(j)in(enumerate(a))for(r)in(iter(q)for(l)in(l))for(q)in(list((i)and(next(r))or(next(iter(j)))for(i)in(range(sum(len(q)if(i)else(not())for(i)in(range(len(str(()))))))))if(f)in(j)else(q)for(l)in(l))if(g)in(j)for(r)in(iter(q)for(l)in(l))for(o)in(next(r)for(l)in(l))for(q)in(list(r)for(l)in(l)))for(l)in(l))for(idx)in(range(id(id)))for(b)in(max(next(reversed(j))for(j)in(enumerate(a))if(p)in(j)))for(m)in(list(((int()if(not(next(reversed(j))in(range(d))))else(sum(not()if(i)else(next(reversed(j)))for(i)in(range(len(str(())))))))if(b)in(str(complex(not())))else(max(range(next(reversed(j))))if(next(reversed(j)))else(e))if((b)in(chr(len(str(slice(divmod))))))else(ord(input()or(chr(int()))))if((b)in(chr(len(str(slice(aiter))))))else(next(reversed(j))))if(next(iter(j))in((k)for(l)in(l)))else(next(reversed(j)))for(j)in(enumerate(m)))for(l)in(l))for(k)in(max(range(k))if((b)in(chr(len(str(set(str(type)))))))else(sum(not()if(i)else(k)for(i)in(range(len(str(()))))))if((b)in(chr(len(str(slice(license))))))else(k)for(l)in(l))for(c)in(next(reversed(j))for(j)in(enumerate(m))if(next(iter(j)))in((k)for(l)in(l)))for(p)in(sum((p)if(i)else(not())for(i)in(range(len(str(())))))if(not((b)in(str(list()))))or((b)in(f)and(c))or((b)in(g)and(not(c)))else(next(next((i)for(i)in(s)if(not(i)in((p)for(l)in(l))))for(s)in(n)if(p)in(s)))for(l)in(l)))
no way 😭
(nasty because it is slightly buggy)
try giving it this as input >++++++++++>>>+>+[>>>+[-[<<<<<[+<<<<<]>>[[-]>[<<+>+>-]<[>+<-]<[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>[-]>>>>+>+<<<<<<-[>+<-]]]]]]]]]]]>[<+>-]+>>>>>]<<<<<[<<<<<]>>>>>>>[>>>>>]++[-<<<<<]>>>>>>-]+>>>>>]<[>++<-]<<<<[<[>+<-]<<<<]>>[->[-]++++++[<++++++++>-]>>>>]<<<<<[<[>+>+<<-]>.<<<<<]>.>>>>]
it should print factorials
Build and Run your Python code instantly. Online-Python is a quick and easy tool that helps you to build, compile, test your python programs.
yea it might be on me
hell yea
cool af
yep checks out too http://tpcg.io/_6E9P98
Online Brainfuck Compiler - The best online Brainfuck compiler and editor which allows you to write Brainfuck Code, Compile and Execute it online from your browser itself. You can create Brainfuck Project using Brainfuck version Brainf**k. You can also Edit, Save, Compile, Run and Share Brainfuck Code online.
first_run = True
def special_first_run():
global first_run
if first_run:
first_run = False
return "A"
return "B"
assert special_first_run() == "A"
for i in range(5):
assert special_first_run() == "B"
How can I achieve this without checking some bool at every run?
def _sfr():
yield "A"
while True: yield "B"
special_first_run = iter(_sfr()).__next__
that's clever
double war crime
str(complex(not())) is wild
hello, I am looking for a partner to learn DSA with me using python and on intermediate level
wrong channel #algos-and-data-structs
-# why cross post
I was recently reminded of this, but it looks like most of the code was broken in other versions besides 3.11 so I'd like to try it again:
The challenge:
Make/golf a function f by replacing the ... such that this code never at any point raises anything deriving from Exception when run in Python 3.13.X. You can either declare the function by def or lambda, it is not required to do both. ```py
Either of these is fine
def f(...): ...
f=lambda ...:...
This runs after the declaration
one = f([1])
assert one[0] == 1
assert one[1] is one
two = f([1, 2])
assert two[0] == 1
assert two[1][0] == 2
assert two[1][1] is two
The behavior of `f([])` is left unspecified since we never figured out a good answer on how it should behave.
(The limitation on exceptions only applies to the given code, not the code inside `f` (so it is fine if `f` internally raises `StopIteration`))
There is probably cheese, but here's a hint for the intended solution: ||```py
assert str(one) == "[1, [...]]"
assert str(two) == "[1, [2, [...]]]"
```||
!e
||
def f(q):
s=l=[q[-1],0]
for x in q[::-1][1:]:l=[x,l]
s[1]=l
return l
# ---
one = f([1])
assert one[0] == 1
assert one[1] is one
two = f([1, 2])
assert two[0] == 1
assert two[1][0] == 2
assert two[1][1] is two
||
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
the challenge is to make a linked list with the root added to the end?
for future reference, it's good practice to specify challenges in terms of behavior and not in terms of test cases, otherwise you get entries like
class f(str):__eq__=lambda*_:True;__getitem__=lambda s,_:s
Erm actually I said a function, not a class 🤓 But also making a good challenge is hard, I couldn't think of a way to phrase/explain it that both kept the intrigue if you don't have the hint/prior knowledge, while also preventing that.
It's a good concept to know in python, ||self containing lists||
Also bonus challenge that is probably much more annoying, but is the best idea I came up with for f([]):
Same rules as before, but with this case added: ```py
zero = f([])
try:
zero[0]
assert False
except IndexError:
pass
assert zero[1] is zero
And extra-bonus because strings suck: ||```py
assert str(zero) == "[, [...]]"
assert str(one) == "[1, [...]]"
assert str(two) == "[1, [2, [...]]]"
```||
def test_creator(v: int):
if v <= 0:
raise ValueError("Behaviour unspecified for v<=0")
source = f"k = f({list(range(1,v+1))})"
all_test = [f"assert k{'[1]'*m}[0] = {m+1}" for m in range(v)] + [f"assert k{'[1]'*v} is k"]
return f"{source}\n{'\n'.join(all_test)}"
Is the supposedly test?
or you only looking for behaviour of one and two, and nothing else
except 0 case on the test creator since its not design to produce that
.> Why is it so hard to make a good question. It's supposed to be ```py
your code for f here
---
the test cases
Let me update the message
No, I mean for the test case, do you only care test case of the specific 2 input (or 3),
Or you want it work for any valid sequence of list that go from 1 to n increment by 1 for each element (or empty list)
That would be the natural continuation of the idea, but if you have a solution that works for just f([1]) and f([1, 2]) but no other lists that would be valid, and I'd be interested to see it.
Because the question only demonstrates how it work for the 2(3) case, not what it should behave
def f(v):
if len(v)==1:
x = [1]
x.append(x)
else:
x=[1,[2]]
x[1].append(x)
return x
Hmm
Literally just hard code everything
No fun
And this is also reason that it's not spoiler
Yep, so that was what I want to clarify
That test generator code should be able to correctly generate a valid test case with the apporiate bootstrap for n given n is the total element of item of a list, where the list starts from 1 and for each element, it increments by 1 from the last element being given to function f, when n >= 1
This sounds like a lot of work, I just want to see cool/golfed ways to solve an interesting problem from 1.5 years ago.
lol
f = lambda x: type("", (), <methods here>)()
now its a function ^^
ah, a custom class
it kinda sucks that people here default to these solutions, imo they are uninteresting :/
i think it is frustrating that people keep giving challenges where those even are valid solutions
as olivia said, if the challenges' behaviour is specified rather than just its output in a few cases, such things are not valid solutions anymore
that is, i think if a certain subset of solutions is not desired then they should not be solutions
i find it bad form to provide a specification that completely allows a solution
and then to turn around and say that the solution is bad or doesn't count
meow
would it be fair to say we are on different ends on the "competitive vs collaborative" code golfing philosophies? By which I mean that on one side you have the very competitive code.golf where testing is completely automatic and "cheese" (flaky or cheating solutions) are always possible but disapproved, whereas on the other side you have the more collaborative cgse with looser specifications but community reviewed solutions
so maybe I lean more on the "competitive" side and prefer to include judges, which doesn't mesh well with the "collaborative" approach
The fact that submissions are posted publicly and shown in linear order together with chat encourages people to build upon existing solutions, as well as to find novel (perhaps even "cheaty") ways of solving the problem. But there's also obviously an element of toying with rules, which is at the core of esoteric python (this channel isn't just for code golf!): "who says i can't write code like xyz"
i dont think those are mutually exclusive
Here's a ||028|| bytes long solution:
||```py
f=lambda :_;raise SystemExit
(What an evil solution. Also succeeds at the bonus challenge.)
No, it's syntactically correct.
!e
||```py
f=lambda :_;raise SystemExit
print('hello')
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
Well you can make it ||16||
||```py
raise SystemExit
gotcha >:)
doesn't follow the specific rules laid out ^-^
He basically did
||```py
def f(): ...
raise SystemExit
You got me ||```py
issubclass(SystemExit, Exception)
False
A truly bizarre solution to the "missing last" problem:
print(id(-id(0))//id(.0)*"not "+"missing"),a
This snippet somehow detects when its own last character is deleted, and prints "missing" when that happens.
Anyone able to explain the mechanism behind it?
I get ```
print(id(-id(0))//id(.0)*not
^
SyntaxError: '(' was never closed
its a single line, maybe discord wrapping messed you up?
Oh yeah quotes exist, I wonder why it wasn't working in repl though. I tried it in all the versions I have installed (3.9 - 3.13) and it doesn't work in any of them. On 3.13 - 3.11 + 3.9 it only gives ```
missing
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'a' is not defined
and `missing`
On 3.10 the same thing, but `not missing` instead of missing.
then it seems like its very system dependent :(
Do you think AI would replace Cybersecurity?
my guess is the allocation of another name in co_names affects the address of the new int that will be produced by -id(0)
def swapcase(s):return(7 .from_bytes(s,G:='big')^(1<<5+8*len(s))//255).to_bytes(len(s),G)
swapcase(b'hotDOG') # -> HOTdog
swapcase(b'SpOnGeBoB') # -> sPoNgEbOb
swapcase(b'TEST') # -> test
Working on strings, not bytes, but:
def swapcase(s):return"".join(chr(ord(c)^32)for c in s)
Isn't big the default?
it depends what version you're on
address fuckery
(system, version, compiler, flags)-dependent
No, but esoteric programming will.
Here's a version for bytes, even shorter!
swapcase=lambda s:bytes(c^32 for c in s)
I don't think it works
it will break all other non-letter symbols
!e
swapcase=lambda s:bytes(c^32 for c in s)
print(swapcase(b'Hello World! 0123456789'))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
b'hELLO\x00wORLD\x01\x00\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19'
Of course, but it works with the tests :P
swapcase=str.swapcase :)
bytes.swapcase exists too, but sadly they don't work on eachother
TIL. What's the point of it? o_O
!d str.swapcase
str.swapcase()```
Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that `s.swapcase().swapcase() == s`.
hmm, in what situation could s.swapcase().swapcase() == s be False
the german ß incident
!e
print("ß".swapcase().swapcase())
:white_check_mark: Your 3.12 eval job has completed with return code 0.
ss
There's tons of characters for which this is true
ah, so swapcase uses str.casefold?
"ß".upper() is "SS".
!e
f = open("weird.txt", "w")
for i in range(0x110000):
s = chr(i)
if s.swapcase().swapcase() != s:
f.write(s+" ")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
weird.txt
µ ß İ ı ʼn ſ ǰ ͅ ΐ ΰ ς ϐ ϑ ϕ ϖ ϰ ϱ ϴ ϵ և ᲀ ᲁ ᲂ ᲃ ᲄ ᲅ ᲆ ᲇ ᲈ ẖ ẗ ẘ ẙ ẚ ẛ ẞ ὐ ὒ ὔ ὖ ᾀ ᾁ ᾂ ᾃ ᾄ ᾅ ᾆ ᾇ ᾐ ᾑ ᾒ ᾓ ᾔ ᾕ ᾖ ᾗ ᾠ ᾡ ᾢ ᾣ ᾤ ᾥ ᾦ ᾧ ᾲ ᾳ ᾴ ᾶ ᾷ ι ῂ ῃ ῄ ῆ ῇ ῒ ΐ ῖ ῗ ῢ ΰ ῤ ῦ ῧ ῲ ῳ ῴ ῶ ῷ Ω K Å ff fi fl ffi ffl ſt st ﬓ ﬔ ﬕ ﬖ ﬗ
oh what happens to the greek ones
oh its not greek.. i suppose i should've wrote the ordinal
It's physics symbols that just look exactly like greek chars and get normalized?
The other thing is the turkish dotless/dotted i
oh no it is greek its my terminal font tweaking
!e
from unicodedata import name
print(name("π")) # normal greek pi
print(name("ϖ")) # this weird one
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | GREEK SMALL LETTER PI
002 | GREEK PI SYMBOL
amazing "greek pi symbol"
also the "long legged cyrillic D" lmao i cant
ah, some of them are just normalized with decomposition
from unicodedata import*
def decompress(m):print(*[name(a).split()[ord(b)%64].lower()for a,b in zip(*[iter(m)]*2)])
decompress('🤟︂༓︇🏪︁𝄻︂❡︂⪪︀≆︁≅︀À︄ꃋ︂ꁐ︂㌿︁ɡ︃')
decompress('≅︀∵︀৸︆ɡ︃☔︃∀︁؞︃Ǖ︆A︁')
decompress('ꃋ︂🗜︀ᛁ︃¬︀⋘︀🙅︃Ǖ︆≐︁∶︀ᛁ︃Ი︄🩠︂<︀¹︁')
decompress('৸︆␄︄∋︀㊙︂〾︁🀇︄䷐︂𝧽︂ͻ︅▣︂ጥ︂☚︃︂ᗞ︃ꫴ︂Ⴈ︃℁︂〄︂㈴︂')
what's the point of a ㌿︁
https://en.wikipedia.org/wiki/CJK_Compatibility
there are a number of abbreviations for fullwidth and horizontal/vertical usage
CJK Compatibility is a Unicode block containing square symbols (both CJK and Latin alphanumeric) encoded for compatibility with East Asian character sets. In Unicode 1.0, it was divided into two blocks, named CJK Squared Words (U+3300–U+337F) and CJK Squared Abbreviations (U+3380–U+33FF).
The square forms can have different presentations when th...
an entire word in a square..??
woah
oh that explains why there are stuff like ㏴
I have rich experience.
Please feel free to contact me
Getting help from people from this channel would be painful 😄
not even a word, could be a concept that requires multiple english words to convey
ideograms are cool
i haven't seen you in a while
but yea
yea, bossman been cracking the whip
channel's also slowed down a bit
doesnt mean that its not a word though
there are english words that would require multiple words in other languages to convey
that being said, ideograms are very cool :3
not sure I'm understanding your complaint, but by very definition an ideogram is not a word
A sound or a combination of sounds, or its representation in writing or printing, that symbolizes and communicates a meaning and may consist of a single morpheme or of a combination of morphemes.
word
OH
sorry lmao i misread "ideogram" as logogram
dyslexia moment
not sure if this is esoteric python or esoteric cmd, but I think you guys will like my abomination :P
Click here to see this code in our pastebin.
that's really funny
*made a tiny edit
Click here to see this code in our pastebin.
I had to download windows to a laptop to write this lel
I have a challenge: Use any valid typehint in python that follow the specification until both mypy and pyright confused on what it actually does:
Requirement:
- It must be fully correct and accurate at what your type hinting (e.g. If the return type is always an instance of
BwhereBis a subclass ofA, you must annotate it asBnot `A) (If a type annotation require a Generic, unless it is impossible, you must provided the type for the generic) - It must exist everywhere (explicit in any type annotations, you cannot skip them and make the type checker implicitly find it)
- You cannot import any library, except
typing,typing_extensions,collections.abc,abc - if anyone find a possible type annotation that is more accurate without modifying the code structure, the solution is invalidated
what does confused entail here?
When it should be B by following all the explicit type definition, but the type checker cannot denote it is B, or denotate that it is other thing(which includes B | None)
this looks like code written by someone who really likes C++ and was forced to write in python with gun on neck
why?
you could have just used vm or just not write it for windows
I wanted something with CMD on the path, could have used a VM but wanted to see how windows felt like after a while of not using it
this is functional programming flavored more than C++ :)
Just a very very cursed way of implementing it
i love it ❤️
Porting to linux shouldn't be that hard...
from typing import Literal
def f(x: Literal["X"]) -> Literal["x"]:
return x.lower()
According to the explicit type definition from python/typeshed
It is
https://github.com/python/typeshed/blob/main/stdlib%2Fbuiltins.pyi#L493-L496
stdlib%2Fbuiltins.pyi lines 493 to 496
@overload
def lower(self: LiteralString) -> LiteralString: ...
@overload
def lower(self) -> str: ... # type: ignore[misc]```
So in fact, from the type, you cannot guarantee such behaviour, so your type technically isn't correct (You can complain typeshed isn't accurate, however, there are nothing I could do about it)
"according to the source code of typecheckers and type stubs, the code which is well typed isnt well typed, so your type isnt correct" - the point is literally to make well typed code that doesnt work with typecheckers
it is literally correct, its just that the Literal feature is very poor and makes it trivial to have issues like this
me when i try to constexpr but i dont want to actually evaluate anything
It is from typeshed, not the type checker🤔
It should be treat as the library have a poor type hint so the type checker just correctly follow the rule to say you might be wrong
from typing import Literal
def f(x: Literal[1], y: Literal[2]) -> Literal[3]:
return x + y
how does this work in your opinion?
surely typeshed has an int.__add__(Literal[1], Literal[2]) -> Literal[3] overload
(no)
Same applied
https://github.com/python/typeshed/blob/b0c6fffe287d4c0a923eeaaa1dd7caa02cba2c9e/stdlib/builtins.pyi#L276
This is not confuse the type checker, it just follow the rule
This is meant for the type checker incorrectly implemented some rule, not finding the type stub being incorrect
stdlib/builtins.pyi line 276
def __add__(self, value: int, /) -> int: ...```
it passes typechecking, by the way, and not because of the stub
you will literally always be able to find the source code which corresponds to the behaviour, why are you sending it? the point is that the code is well typed logically but doesnt pass typechecking
just because the code is there doesnt make it correct type-wise
But this is not the point of the question
then you should make the point more clear
It is very clear
typeshed is in the type specification
seems like you only want us to abuse control flow analysis, because otherwise you'll say "but its correct because typeshed defines it"
The type checker being able to resolve better than the type stub doesn't make it a requirement
typeshed also has a shit ton of Any's in variadic functions like zip or map after like, 6 varargs
is that "correct"? no its fucking not, the typesystem is just too weak to express it
"but the type checker cannot denote it is B, or denotate that it is other thing"
what? it can always give "some" type (like Unknown) to an expression, how do you want it to not be able to give any type to it?
anyways
from typing import Literal as L, overload as o, reveal_type as rt
@o
def f(x: L[False]) -> int: ...
@o
def f(x: L[True]) -> str: ...
def f(x: L[False, True]) -> int | str: return 0 if x else ""
print(
rt(f(False)), # reveal: int, runtime: str
rt(f(True)), # reveal: str, runtime: int
)
here you cant even bring up typeshed. just Literal being bad
If follow the type annotation according to specifications, it should be a more specific type A, but the type checker gives a less specific type B, or unknown type, or incorrect type, would mean you win
But e.g. in your example, int.__add__() explicit typehint is int so it is not wrong if it fail to acknowledge that it is Literal[3]
Your challenge is quite unclear...
- What do you mean with fully correct?
- What does accurate mean? How do you measure it?
- What the last point mean? What do you mean more accurate? How can something be more accurate when it's already accurate?
- By confused, what do you mean? How an annotation can be correct? How do you want to determine that, especially when python type hints are turing-complete (https://arxiv.org/abs/2208.14755)?
- Also, what do you mean "valid type-hint"? Per https://peps.python.org/pep-0484/, PEP-484 is non-enforced and really anything that's valid as an annotation is valid:
Note that this PEP still explicitly does NOT prevent other uses of annotations, nor does it require (or forbid) any particular processing of annotations, even when they conform to this specification. It simply enables better coordination, as PEP 333 did for web frameworks
- Going further: what specification should we follow?
- When the annotation cover all the possible type of return value (You cannot say it is
Bwhen in all case it returnA, assumeBis not inA) - If someone could come up a more precise typehint, than it is inaccurate (If some can provide a typehint that is correct (as defined at 1) but in the subset of your typehint(assume your typehint is correct), if the new provided typehint is not fully in the subset of original typehint, there are no metric that could calculate so it is not treat as inaccurate)
- Answered in 2
- When an annotation cover all case of all the possible return value. You confused the type checker if it doesn't cover all the possible return type (when your annotation is correct), Cover something that is not a possible return type according to type definition (e.g. suggest a function might return
None(A | Nonewhen the type annotation didn't say so) - ...
- You would follow typeshed for built-in type annotation, and you could use any typing behaviour that is available in Python 3.13, as defined on how it should behave (refer to relevant creation/modification PEP of such typing behaviour), or https://typing.readthedocs.io/en/latest/spec/index.html . When conflicted, use the provided link instead of the PEP, unless it could be verified that the the provided link is outdated to the latest 3.13 release interpreter with it's standard library.
Other thing I might need to look into, or not be able to provide an answer
... Mean the thing I need to look into, and also the paper you send me also
Just the number list in discord messing with me
Also all the possible type of return value is defined by the previous annotation, not the result evaluated dynamically
E.g. int(1000) == int("1000") could be usually assumed that they are the Literal[True], but it cannot be determined as the type annotation defined that the result is bool
This doesn't make the type annotation inaccurate If bool is given (but Literal[True] is also a valid answer)
this is cute!
<3
this is a very strange challenge
def f() -> int:
if 0>1: return f
return 0
both mypy and pyright fail here
- When an annotation cover all case of all the possible return value. You confused the type checker if it doesn't cover all the possible return type (when your annotation is correct), Cover something that is not a possible return type according to type definition (e.g. suggest a function might return None(A | None when the type annotation didn't say so)
the typecheckers incorrectly suggest that f might return a callable, when the type annotation does not say so
f is Callable[[], int | Callable[...]] and there is path that it could return f so you didn't provide a correct type annotation
f is not that
and there is no path that can return f
0>1 is the constant False
there are no type definitions that define 0>1 is Literal[False], but only bool
f :: Callable[[], int]
yes, and i am using that error in the typecheckers here
^^
that is not error as the rule define above before you respond that builtin type-hint should be use from typeshed
stdlib/builtins.pyi line 327
def __gt__(self, value: int, /) -> bool: ...```
... what?
read #4
specifically the emphasised bit here
yeah the thing is that __gt__ is never run here
Cover something is not a possible return type according to type definition (according to type definitions from typeshed, it is very possible)
> was a bad example actually lol
and I feel like it would just be endless pointless argument at this point so the challenge end here, I would not respond to any further about the challenge.
if only finding dead code paths was a part of typecheckers
oh wait it is!
mypy accepts it if the condition is just 0, so eliminating dead branches is allowed
¯_(ツ)_/¯
!e a better example ```py
def f() -> int:
if 0-0: return f
return 0
import dis
dis.dis(f)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1 0 RESUME 0
002 |
003 | 2 2 NOP
004 |
005 | 3 4 RETURN_CONST 1 (0)
each time a valid point is raised, you just send the typeshed with the general annotation
"but here there is no typeshed stub that int.__sub__(Literal[0], Literal[0]) -> Literal[0] and int.__bool__(Literal[0]) -> Literal[False] so its correct"
as you can clearly see, f is of type () → int
it can only return int
the only return of f is RETURN_CONST 0 and 0 is of type int
do you understand now
hopefully that cleared things up
i would not respond further relate to this, do not continuously ping me
This entire discussion feels like a lot of those very cool and interesting issues about extending python's type system/removing limitations/pinning down precise definitions, but instead of useful/insightful work getting done it's all arguing over challenge semantics 🙃
it is weird that python doesnt constfold 0>1
seems easy
because you cant get any useful work done with the people behind python's type system
isnt it obvious from the mess that is python's typing? it needs to be re-done at this point, but they dont want any big changes
(might be a crazy take, but its almost like type systems should cover what is done in practice, yet python's type system is incredibly non-expressive for such a dynamic language, even though it has a lot of special cases)
i dont pay attention to python's typing ecosystem at all; could you list a few examples of the cool/interesting issues?
ive been trying to find a reason to care about typing for a while now and just havent been able to so maybe interesting things would help with that lol
the only times ive used annotations have been for #esoteric-python lol
Is this a valid solution?
a:int=""or 1
Still not an amazing reason to care since it doesn't exist yet, but https://github.com/python/typing/issues/213 is one I remember being a good read. In it's current state typing falls apart once you want complex things like type intersections, but it is nice for simpler code for pointing out logic/usage errors in your functions from the parameter/return types.
im not sure if it will ever exist considering its been 9 years
each time they add a new typing feature it adds 20 stupid cases for intersection, so instead of just making intersections that work in normal cases - they dont add them at all
🤣
Also, here's another one:
a:__debug__.__class__=__debug__
Wait, I forgot to test using pyright...
@grave grail
Here's a version that works for both:
from typing import Never
a:Never=1<<-1
Mypy:
main.py:2: error: Incompatible types in assignment (expression has type "int", variable has type "Never") [assignment]
Pyright:
Type "Literal[0]" is not assignable to declared type "Never"
Type "Literal[0]" is not assignable to type "Never" (reportAssignmentType)
And, per documentation, a should be Never: https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types – First note.
You confused pyright but not mypy
Also technically this is now how Never should be used
https://docs.python.org/3/library/typing.html#typing.Never
Nice :)
it is how Never should be used
expressions leading to guaranteed exceptions should have type Never
It specifically said function in docs, do you have docs that said otherwise? Because that what I learnt from there
And would be interesting if it is 🤔
It makes sense to me by composition. What is the type of a in a = sys.exit()? Similarly, what is the type of a in 1 .__lshift__(-1)? I don't see what both could be besides Never.
Non-existent, the function raise at a exception with no value and the annotation is used exclusively for type checker to annotate the function, as far as I interpret the document 🤔
all expressions have a type
in this case, its the bottom type
Are there documentation/example of such instead of we just attempt to interpret it in other way than it have described?
Or if you could somehow pause python when it call the exception and return a value and evaluate its type (idk if possible)
exception -> unreachable code
Never is the type of unreachable code
x = sys.exit()
the possible set of values of x is an empty set, that is, the bottom type
Well,
Never and NoReturn represent the bottom type(link to wikipedia article), a type that has no members.
So, they are defined by a wikipedia article: https://en.wikipedia.org/wiki/Bottom_type 😆
But if this is such an issue, I can just wrap the code in a function and it still works:
from typing import Never
def a() -> Never:
1<<-1
Mypy:
main.py:3: error: Implicit return in function which does not return [misc]
Pyright:
Function with declared return type "NoReturn" cannot return "None" (reportReturnType)
As an aside, I disagree with type checkers on this for unreachable variables (definitely the Rust programmer in me talking because of loop {}). The type of a in a = [*iter(int, 1)] should be Never, not list[int].
thats a rather hard thing to statically determine
you need to know that int() != 1. i mean, in this specific example its easy because int() -> Literal[0], but not in general
Well yes if we are in the real world, but we are (or at least I am) currently in the magic land of typing.
You confused pyright but not mypy
I also did mypy:
Incompatible types in assignment (expression has type "int", variable has type "Never")
a: Never (variable has type "Never", correct!) = 1<<-1 (expression has type "int", nooo! it's "Never" mypy, what are you talking about.?)
I mean, if you agree with the rule of using typeshed that no one agree with, mypy would be still fine
But pyright is just wrong
Hm it looks like at least mypy is already doing some amount of the work that would fix my complaint, since this passes: ```py
from typing import assert_never
def test():
[*iter(int, 1)]
assert_never()
Counter-example:
import random
def f():
if random.randint(0,1) == 0:
raise ValueError # Random chance it crash
return 0
v = f()
How would just justify the return type
When the random value is 0
As we've confirmed Python's Never is underspecified for this, but I do know a decent amount about Rust's Never !, and because of type coercion it would be int. The return type is only Never if all paths don't return, but since there is a valid int path that is the return type.
thats not a counterexample, int | Never == int
Where did you got this from?
x + 0 = x
it comes from what a bottom type represents
"or bottom" is useless, bottom is only useful when something is guaranteed to "be it"
There are no values of type Never, so saying a value could be either Never or int is the same as saying it's always int. It could never be a Never, since a value of type Never doesn't exist.
I bet if you put int | Never at return type annotation, the type checker would scream at you
nope
Wtf fine
This is the other issue with the original challenge: A lot of functionality in type checkers isn't rigorously defined by a PEP/python documentation. It's grown by behavior from other languages, formal type theory, and what people find useful, but a lot of it isn't standardized. Like X | Never = X.
Why tf the documentation is so horrible 💀
It looks to me like a cycle of
It's hard to get things into the standard -> people get annoyed and add the functionality anyways -> common tools diverge from the standard and each other -> it gets harder to add things to the standard.
Plus all the math of sets of sets of types for making sure this all makes sense is confusing at the best of times, and like all cool math full of symbols with specific meanings.
(and different subgroups of comunities/theories/symbols that disagree with each other from the math side)
The N number set 🥴
typeshed is just. wrong
in many cases
so using it for this is annoying
Complain to typeshed instead and I don't agree that is the type checker fault
no one here is complaining? we're just choosing to solve the problem of typeshed being bad by not using typeshed
solutions are generally better than complaining ^^
I mean, there must be a fundamental base to allow the challenge to be possible, instead of arguing whether it is valid or not or valid the type checker should have catch that. But that end with argument anyway which means it is pointless for the challenge still running.
well the thing is that
the typechecker was incorrect
which is what your challenge asked for
The thing is, you cannot assume the type checker know something when the typehint never said so. So again, typeshed issue and we know typeshed is dumb.
(The different stand point is you consider typeshed to be part of type checker or expect it do better than typeshed define but I consider it should just follow type stub rules like how any other program would: either source code or type stub
It appears that you are desiring for an authoritative document on python types and their behavior. Such a specification does not exist and the information is instead spread across PEPs, guide pages, implementation-specific docs, and standard results from PL theory.
int | Never is int | Never according to mypy and int according to pyright
Python typing is not very standardized, non-enforced and mostly defined by the toolkits, not PEPs. Besides mypy and pyright there are also other type-checkers. They also define the usage of type hints (hints! not declarations!), so it's not something hard-defined.
...
hmm
How are going to do it? Just strip the annotations?
What transformations would it do, that aren't accessible to python? I think that typescript was created because javascript didn't have type definitions, how typescript-like python would differ from normal python?
I was a dumb thing
thats also why I removed it instantly after posting
my brain wasn't working at that moment
But JSX-like python would be cool nonetheless
we already have pyx
cython
Do you mean https://pyx-project.org/?
They are completely unrelated.
About JSX:
https://www.typescriptlang.org/docs/handbook/jsx.html
https://facebook.github.io/jsx/
no I am talking about https://cython.readthedocs.io/en/latest/index.html
I know what jsx, I am already using tsx in my current project
I've found https://github.com/awable/pyxl, were you referring to this?
I just said I was referring to cython......
also that thing is old as hell
ye
is there a less cursed/brittle way of assigning arbitrary information to a frame than this?
key_object = object()
frame.f_locals[key_object] = ...
i basically just need a way to set a flag on specific frames
Maybe a weakset of sorts.
cant make weakrefs to frames unfortunately
though it turns out weakrefs to code objects are possible, so i thought maybe doing like a manually maintained weakkeydict of frame code object -> frames, then checking each one's f_lasti to see if the frame's done or not
yeah its logically int | Never, but it evaluates to int
python sees that as an int, but python doesnt care about type hints
!e ```py
from typing import Never
print(Never | int)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
typing.Union[typing.Never, int]
No, it doesn't.
It's Union[Never, int]
!e from typing import Never; print(int | Never)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
typing.Union[int, typing.Never]
python does not reduce or simplify types
!e from typing import Never; print(dir(Never))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__instancecheck__', '__iter__', '__le__', '__lt__', '__module__', '__mro_entries__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasscheck__', '__subclasshook__', '__weakref__', '_getitem', '_name']
yeah as expected Never has overridden |
type hints are just expressions tho, and at runtime the type "descriptor" you put into a type hint might evaluate down to something that isnt really descriptive of the type anymore
like if you'd use "int or Never", it'd say "int or Never" in the source code but at runtime would evaluate to int
that doesnt happen with | tho obviously and Never redefined that op anyway to produce the correct result, idk why i thought | would act similar to or
!e print(float | int)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
float | int
do or
that type unambiguously simplifies to just float
!e ```py
print(float or int)
print(int or float)
`or` wasn't used because it already means a thing, and most (all?) types are truthy so it always evaluates to the first one.
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | <class 'float'>
002 | <class 'int'>
yeah the last part is what i meant. it's possible for a type hint to read something else than it means
!e
print(int | int)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
<class 'int'>
there's also stuff like union flattening
TIL
yes, all types that support Union have
Who is at high school here?

hala
me
me

I read it as "who is high at school here"
though me too
Hey I am conducting a lecture on python one liners(One-liners in general) any suggestions or inputs ?
I think he meant read the chat history 🥴
oh
how to write them in Python or just one-liners in general?
one-linears in general wouldn't be a great idea since multiple languages have simple syntax which doesn't require new lines, eg C#, JS, java, kotlin, dart, C
python doesn't for many cases also
;
there are mutliple things in python in which you have to use new lines but thats not a case for languages I mentioned
for many cases also
not for every case
meow
anyway, python statements can be transformed into expressions relatively trivially so there's not really an issue here i think
create a async function inside a async function
exec ftw
use the constructor instead of the dedicated syntax
surely you can do that... but my point was about built in syntax
:incoming_envelope: :ok_hand: applied timeout to @clear venture until <t:1741033637:f> (10 minutes) (reason: newlines spam - sent 101 newlines).
The <@&831776746206265384> have been alerted for review.
converting from a statement to an expression is obviously going to change the syntax you goose :3
why specifically one-liners?
the languages I mentioned, you can write almost or whole thing in single line without changing language
How would you handle the void return in C# when you doing one-linear?
im not sure why you keep repeating this
im not disputing it
and its not relevant to what i said about python
So a friend challenged me to print some math functions in one line and the result of it is:
import math
import operator as o
calc = lambda a,b: [print(f"{des} = {opt(a, b)}") for des, opt in {'a+b': o.add, 'a-b': o.sub, 'a*b': o.mul, 'a/b': o.truediv, 'a%b': o.mod, 'sqrt(a+b)': lambda a, b: math.sqrt(a+b)}.items()]
I tried doing something as (o:=__import__('operator')) inside of it (as the first value in the dict) but it throws a syntax error. Is there a way to include it into this? Or a better way to do it
SyntaxError: assignment expression cannot be used in a comprehension iterable expression
use it as a default argument to the lambda
lambda a, b, o=__import__("operator"): ...
calc = lambda a, b, o=__import__("operator"), m=__import__("math"): [print(f"{des} = {opt(a, b)}") for des, opt in {'a+b': o.add, 'a-b': o.sub, 'a*b': o.mul, 'a/b': o.truediv, 'a%b': o.mod, 'sqrt(a+b)': lambda a, b: m.sqrt(a+b)}.items()]
there is no async constructor
after an async def f, f will be of type function
=> you can construct it with types.FunctionType
>>> class X:
... async def __init__(self): ...
...
>>> X()
<stdin>:1: RuntimeWarning: coroutine 'X.__init__' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() should return None, not 'coroutine'
``` hmm
Tbf, is async def just a syntax sugar that return a coroutine to a special function?
yes
Oh welp, time to learn coroutine
Oh, so technically if a system is set nicely, you can just avoid using await entirely 🤔
mainly python
I like one liner
!e
__import__("sys").stdout.write('\n'.join("O" + ["n","ff"][i]for i in[int(b) for b in bin(9)[2:]]))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | Off
002 | On
003 | On
004 | Off
It would be messy, but possible using __await__ magic method, as constructing classes is possible.
Dumb code golfing challenge:
Python 3.9 is reaching EOL this year. Detect whether running on python 3.9. By detect, I mean that it should give a defined output when ran using python 3.9 (doesn't matter if it's stdout or stderr). "Patch version" (I know that python doesn't use semver versioning) doesn't matter, if your code works on a subset of python 3.9 versions, that's fine, but the "detection output" you defined cannot be outputted by non-3.9 python. ||My PB is 14 bytes||
i have an 11B
||xy={}|{};xx||
explanation: ||versions before 3.9 didn't have union operator for dicts, versions after 3.9 will offer a suggestion to use xy instead of xx in the nameerror printing||
this is not dumb btw, its novel and interesting to think about
a very cool challenge :3
||I got 0B because technically a subset of python 3.9 versions can be a empty set (which means that I don't have to do anything, as long as the defined output I set is not possible in any python version)||
||Therefore my defined output is Dumb code golfing challenge: Python 3.9 is reaching EOL this year. Detect whether running on python 3.9. By detect, I mean that it should give a defined output when ran using python 3.9 (doesn't matter if it's stdout or stderr). "Patch version" (I know that python doesn't use semver versioning) doesn't matter, if your code works on a subset of python 3.9 versions, that's fine, but the "detection output" you defined cannot be outputted by non-3.9 python.||
^ Me being unreasonable and not solving properly
Let make it ||0B|| because I'm too lazy to think
You might want to say it's non-empty subset instead of subset
I'm having problems with copying your code sample and running it, how did you do it again? /j
||
You just do: python3 I'm having problems with copying your code sample and running it, how did you do it again? /j, it's really not that hard
|| /j
what was your 14B?
couldnt this -2B by renaming the variables to a and b
I'm guessing it wouldn't suggest the other name then
nope
it wont suggest for 1 length names
yeah l3v got it in 1
any1 here can find any use for this 3.13 code ?
print(
type.mro(type)[1].__subclasses__()[36](
type.mro(type)[1].__subclasses__()[12](
1, 0, 0, 1, 1, 3, b'\x95\x00\x67\x01',
(None, 50), (), ('_',), __file__, '<something>', '<something>',
-1, b'', b'', (), ()
), {}
)(1)
)
for a return 50? i mean, you can return 50 with it
maybe with a lil more complex code string
i just thought this was funny when i discovered but i cant think of a single use
it does seem to suggest a from ab (at least on 3.12) so you can still squeeze -1
aha
you're right
10B courtesy of code golfing enthusiast ||x={}|{};xy||
Guys is there a python function that check how many decimal digits a number has?
len(str(abs(x)))?
int(lg(n))+1
||__peg_parser__||
aha
an integer or a number in general?
Speaking of subset, why did I want to define this question by mathematics notations🥴
With that logic, here's 7B solution: ||{}|{};i||
Then would this work?
||{}|{i}||, I don't have the test environment setup and just guessing, or wrong error order?
i is evaluated before |
aha clever
Oh ok, so wrong order
why not just ||{}|{}|| ?
That would be for detecting python3.9+, but it has to be python3.9. Explained how it works here: #esoteric-python message
You have to differentiate between 3.9 and 3.10+ as well
it does differentiate: if it fails - it is 3.9, if not - 3.10+
it won't fail if it is 3.9, it'll only fail if it's before 3.9
even if this did fail on 3.9, it would also fail on 3.8, 3.7, 3.6, ...
the challenge does not mention 3.8-, they have reached EoL so they are no longer relevant
the challenge does say "the "detection output" you defined cannot be outputted by non-3.9 python" which I'd consider to mean that. But nontheless, 3.9 and after will all output the same
!e
class evaluator:__format__=exec
f'''{evaluator():
def main():
print("Hello, world!")
main()
exit()
}'''
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, world!
fun fact: you can put basically anything in a format string
Lmao
TIL exit() and quit() are not REPL-exclusive??
Since basically ever? Or since python 1.5 to be exact (python 1.4 - added site.py, python 1.5 added exit and quit to site which at that moment is just a string and site.py is executed on interpreter initalization)
https://github.com/python/cpython/commit/d89fa0c5761254c970af72e5abcea420fd23e893
https://github.com/python/cpython/commit/dcc0c13f74e3f62b00847f4aec93bb5c65e8cf64
(This took too long to search)
For your information: quit, exit, help, copyright, etc.. aren't builtins, they are created by site.py (or _sitebuiltins.py nowadays) and they mutate the builtins module object injecting the objects. It's true, that site.py is executed by interactive shell, but also by python interpreter when running a python file unless explicitly marked otherwise. This is how it was ever since the creation of exit and quit.
Not necessarily. If you run python with -S site.py won't be imported and exit etc. won't be a thing.
unless explicitly marked otherwise
^
$ python -S
Python 3.12.3 (main, Feb 4 2025, 14:48:35) [GCC 13.3.0] on linux
>>> exit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'exit' is not defined
exit is a nasty hack too lmao
Read n elements and get the sum of even and odd numbers
Liked the way I used the list
n = int(input())
l = [0, 0]
for i in range(n):
m = int(input())
l[m%2]+=m
print(*l)
how so
t=[0,0]
for x in[*open(0)][1:]:x=int(x);t[x&1]+=x
print(*t)
tbf this does rely on an eof
i mean, if you put it through a test system then it'd work yeah but if i just typed it in it wouldnt work without a ^D, altho this is kinda pedantic
mufh.. :(
is there anything you can do in python if every line of source code starts with a space?
you can make comments!!
I tested with a couple other stuff but couldn't find anything sadly
i have been able to find a way to run code but ||nothing with only printable chars, which I would prefer||
can you show it
starting with a codec declaration?
i don't think a lot of printables could work here ```pycon
from string import printable as pt
for x in pt:
... try: exec(" " + x)
... except BaseException: pass
... else: print(repr(x))
...
'#'
' '
'\t'
'\n'
'\r'
'\x0c'
Infinite sequence of \ on each line (if anyone have any idea)
It's line continuation tho, couldn't manage to find anything useful
ws[
]sw
value = (<code>)
if value:
raise Exception
if not value:
raise Exception
if not isinstance(value, str):
raise Exception
if not isinstance(value, int):
raise Exception
if (cls_list:=list(value.__class__.__mro__)) != list(value.__class__.mro()):
raise Exception
for v in cls_list:
if v not in [str, int, object]:
raise Exception
print("You win")
Create the shortest byte count of code to replace <code> that doesn't raise Exception, the last line must be executed (You cannot exit the code early to escape the check)
<code> must not consist of any new line (It must be on a singular line)
Idk if it's possible btw
!e ```py
value = (int:=type("",(str,),{"t":1,"bool":lambda s:setattr(s,'t',not s.t)or s.t}))()
if value:
raise Exception
if not value:
raise Exception
if not isinstance(value, str):
raise Exception
if not isinstance(value, int):
raise Exception
if (cls_list:=list(value.class.mro)) != list(value.class.mro()):
raise Exception
for v in cls_list:
if v not in [str, int, object]:
raise Exception
print("You win")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
You win
Haha, overriding int is a nice idea
Too bad __bool__ needs to return a bool, not an int. Otherwise you could do int:=type("",(str,),{"__bool__":__import__("itertools").count().__next__}))()
Nice and quick lol
!e ```py
value = (int:=type("",(str,),{"bool":import("itertools").count().next}))()
if value:
raise Exception
if not value:
raise Exception
if not isinstance(value, str):
raise Exception
if not isinstance(value, int):
raise Exception
if (cls_list:=list(value.class.mro)) != list(value.class.mro()):
raise Exception
for v in cls_list:
if v not in [str, int, object]:
raise Exception
print("You win")
: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 | if value:
004 | ^^^^^
005 | TypeError: __bool__ should return bool, returned int
does it count if I use tracing to jump to the final line?
Won't be shorter than the other method
true, you have to trace the current frame as well as set a global trace.
value = [sys.settrace(lambda*_:0)for sys in [__import__('sys')]for sys._getframe().f_trace in [lambda f,*_:[print for f.f_lineno in[16]][0]]] yeah, rather long.
I didn't say it's not allowed, so go ahead
!e
# print('hliogwh'[(a:=0o12)<0xA::0b10]+"er") -> this is goal
# 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# a b c d e f g h i j k l m n o p q r s t u v w x y z
# 7 11 8 14 6 22 7
import string
print((string.ascii_lowercase*26*4)[7::27*4])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
hlptxbfjnrvzdhlptxbfjnrvz
aw man
What's the goal?
generate 'hliogwh' from ascii_lowercase
might need several slices tho which eh
!e
print('hliogwh'[(a:=0o12)<0xA::0b10]+"er")
print('hliogwh'[(a:=0o11)<0xA::0b10]+"er")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | higher
002 | lower
this a very silly code that was posted in #python-discussion that now became this 1 liner
Why tho?
why not ?
...so the string have no purpose?
wdym string has no purpose
Like, what is the string use for
Or it is just a random string for no purpose
::2 -- character every 2 steps
'high'
0::2 -- start at index 0
_______
v v v v
hliogwh
^ ^ ^
 ̄ ̄ ̄
1::2 -- start at index 1
'low'
ye cereal made a great explanation for it
(he one who originally made that scramble)
I got it and thinking of a obfu sequence
if it came from string.ascii_lowercase it would be hella funny
but i think a custom giant string might be easier

improved indeed :p
!e ```py
value = (int:=type("",(str,),{"bool":iter([False,True]).next}))()
if value:
raise Exception
if not value:
raise Exception
if not isinstance(value, str):
raise Exception
if not isinstance(value, int):
raise Exception
if (cls_list:=list(value.class.mro)) != list(value.class.mro()):
raise Exception
for v in cls_list:
if v not in [str, int, object]:
raise Exception
print("You win")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
You win
Now
Ahh, I didn't send the newest version:
value = (int:=type("",(str,),{"__bool__":[True,False].pop}))()
Reduced further:
value = (int:=type("",(str,),{"__bool__":[1>0,1<0].pop}))()
linked lists are unary trees 🐸
unary trees are linked lists
Random code golf challenge:
Write a function that returns a sign of a given integer (-1 for x < 0, 0 for x=0, 1 for x > 0)
Test code:
for num in range(-100, 0):
assert sign(num) == -1
for num in range(1, 100):
assert sign(num) == 1
assert sign(0) == 0
!e
sign=lambda x:(x>0)-(x<0)
for num in range(-100, 0):
assert sign(num) == -1
for num in range(1, 100):
assert sign(num) == 1
assert sign(0) == 0
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
Is the validity of the program decided by the implementation of the function or the execution of test code (the raise of exception or not)
!e
sign=lambda*_:type('',(),dict(__eq__=lambda*_:True))()
for num in range(-100, 0):
assert sign(num) == -1
for num in range(1, 100):
assert sign(num) == 1
assert sign(0) == 0
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
Hello
I am very sick, so I can't do much. I wrote this small weird code for no reason
!e
nop = (lambda: "pass") # -> pass
type se = whatever **se** means
statement = (lambda: nop)
cool = (lambda: nop)
def killThisGarbage(randomPieceOf__) -> se:
print(randomPieceOf__)
if statement is cool:
nop
else:
killThisGarbage({
"Hello, World!"
})
del nop, statement, cool, killThisGarbage, __name__
# se is cool
:white_check_mark: Your 3.12 eval job has completed with return code 0.
{'Hello, World!'}
se
by the implementation of the function
Probably you meant the definition?
Yes. /j
I mean, does sign=lambda a:exit(0) count because it technically pass the test case but doesn't do anything productive
Well, the definition is the task, the test is the illustration, but creative solutions are fun.
(In terms of defining the task, using the olimpiad approach of "use a subprocess and thest the output" is much nicer, but much more verbose in terms of test programs.)
why do you put lambda in parenthesis
also how did this line get executed py type se = whatever **se** means
oh type <identifier> = ... is a syntax
TIL
I didn't know this
and its there for like 1.5 years
its there since 3.12 right?
i still think it's new ;-;
same with match-case
match case was released in 3.10 like 3.5 years ago
but yeah I also think its new and I don't have usecase for it yet
it's making me feel old....
its also making me feel old that 3.10 was released 3.5 years ago
even though I am just 16
wait a freaking minute 7.0 was released 2.5 years ago?
I thought it was released early last year
the hell
!e
import sys
import traceback
def trace(exc_type, exc_val, exc_trace):
if issubclass(exc_type, NameError):
exc_trace.tb_frame.f_globals[str(exc_val).split("'")[1]] = str(exc_val).split("'")[1]
while True:
try:
exec(exc_trace.tb_frame.f_code)
break
except NameError as e:
exc_trace.tb_frame.f_globals[str(e).split("'")[1]] = str(e).split("'")[1]
continue
sys.excepthook = trace
print(Hello, World)
:x: Your 3.12 eval job has completed with return code 1.
Hello World
3.10 is 3.5 years old?????
forget that freaking virtualbox 7.0 is 2.5 years old
Because I can :P
oh damn that's cool
unfortunately you can't do stuff like this tho
I'd need to inspect the function bodies
decided to do it, and also made it work with multiple files
exceptionally cursed
still only like ~30 lines
lol, cursed
💀
this would make for an exceptional obfuscator
works in REPL?
what's repl?
the python executable
ah
lemme check
well the read-ahead relies on there being a file to read
so my old version might have, let me check
well I suppose I could just disable the check-ahead in repl
wait how on earth would goto work in a repl
does it go back and re-execute past commands?
it could at least work in blocks
oh right yeah
well it works off line numbers but there's not really a concept of that in the repl...
ValueError: line 2 comes before the current code block
actually why isn't there, it's in a block, it should work
here they are if you're interested
Please react with ✅ to upload your file(s) to our paste bin, which is more accessible for some users.
same
Can anyone pleas help me here: https://discord.com/channels/267624335836053506/1351541021011345500
wrong channel
Does it need source access or does it inspect bytecode? Because the latter in 30 lines is impressive
it needs source access, yeah
it just does open()
the original version didn't do any source inspection
!e
n = 7
class _(*[type('_'*i, (object,), {'__init__': lambda self: [super().__init__(), print(i)][-1]}) for i in range(1,n)]):
def __init__(self):
super().__init__()
print(n)
_()
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 8, in <module>
003 | _()
004 | File "/home/main.py", line 5, in __init__
005 | super().__init__()
006 | File "/home/main.py", line 3, in <lambda>
007 | class _(*[type('_'*i, (object,), {'__init__': lambda self: [super().__init__(), print(i)][-1]}) for i in range(1,n)]):
008 | ^^^^^^^
009 | RuntimeError: super(): __class__ cell not found
any yall smart folks know how to properly set __class__ here ? 
super() is only valid inside the body of a class I believe
(not the superclass list)
class _(<this bit>):
type('', (), {'__init__': lambda self: <this class body in this case>}) so should work
the class syntax does a lot of work behind the scenes, including defining __class__
so no not inside a type() call
which is what im asking how is done

it's special cased in the compiler -- you could probably manipulate the code object to add the closure.
i was thinking code object cause it said cell but how would i even find the code object thats its using here ?
!e
class Foo:
def foo(): super
class Bar:
def bar(): pass
print(Foo.foo.__closure__, Foo.foo.__code__.co_freevars)
print(Bar.bar.__closure__)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | (<cell at 0x7fe0e5f6ff10: type object at 0x5631d3aa7ef0>,) ('__class__',)
002 | None
!e
Foo = type('Foo', (object,), {'foo': lambda: super})
print(Foo.foo.__closure__)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
None
is there anywhere explaining freevars/cellvars ?
freevars are the variables the function uses from outer functions (not modules), cellvars are variables used by inner functions.
fun
this is explicitly special cased in the compiler right here https://github.com/python/cpython/blob/8a33034d82314e2a5a8f39f9348e93135f94807d/Python/symtable.c#L2502-L2507
Python/symtable.c lines 2502 to 2507
/* Special-case super: it counts as a use of __class__ */
if (e->v.Name.ctx == Load &&
_PyST_IsFunctionLike(st->st_cur) &&
_PyUnicode_EqualToASCIIString(e->v.Name.id, "super")) {
if (!symtable_add_def(st, &_Py_ID(__class__), USE, LOCATION(e)))
return 0;```
Yeah, which is why unlike anything else in Python, you can't do duper = super and then use duper() in a method.
am I misunderstanding what you meant?
>>> class A:
... def __init__(self): print("A")
... duper = super
... class B(A):
... def __init__(self):
... print(duper, duper())
... duper().__init__()
... print("B")
... B()
...
Traceback (most recent call last):
File "<python-input-9>", line 9, in <module>
B()
~^^
File "<python-input-9>", line 6, in __init__
print(duper, duper())
~~~~~^^
RuntimeError: super(): __class__ cell not found
ah I see
class CustomGlobals(dict):
def __missing__(self, key):
if key in dir(__builtins__):
return getattr(__builtins__, key)
return key
exec("print(test*2)", CustomGlobals(globals()))
is there a simpler way of accomplishing this, without having to use __builtins__? (By this I mean resolving undefined variables to a custom value while preserving builtins)
(I guess a simpler way is using defaultdict but it still doesn't solve the builtins problem)
globals are queried before builtins so at simplest you have to not return a value for builtin keys
I think that won't work here: they want to return it if it's a builtin, but default to returning a string of the name.
getattr can take a third argument!
!e ```python
class CustomGlobals(dict):
def missing(self, key):
if key in dir(builtins):
return getattr(builtins, key)
return key
class CustomGlobals2(dict):
def missing(self, key):
return getattr(builtins, key, key)
exec("print(test2)", CustomGlobals(globals()))
exec("print(test2)", CustomGlobals2(globals()))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | testtest
002 | testtest
without having to use __builtins__ is harder, though
one could make CustomGlobals take different arguments?
CustomGlobals(vars(__builtins__) | globals()) then you don't need __builtins__ in __missing__ at all
!e ```py
class CustomGlobals(dict):
def missing(self, key):
return key
exec("print(test * 2)", CustomGlobals(globals() | vars(builtins)))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
testtest
yeah
!e
print("Hello, World!")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, World!
Very nice.
!e ```py
=lambda :ord([:=not _][][])+!=-~+<<<<~*~_ or not _+"Hello World!"
print(next(filter(('g',).le,id.self.dict.items()))-_('g')[_('g')])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello World!
Does this help?
import discord.ext.commands
import tokens as t
b=discord.ext.commands.Bot((),intents=discord.Intents.all())
@b.tree.command()
async def s(i,a:int):
async for m in i.channel.history(limit=a):
await m.delete()
await b.process_commands(m)
@b.event
async def on_ready():await b.tree.sync()
b.run(t.tokens['testbotpy'])```
whats a better way to
esoteric this
buddy wtf lol
single letter varnames
how the fuck, it has to return bool and it matches both True and False wtffff
can someone explain
value = (int:=type("",(str,),{"t":1,"__bool__":lambda s:setattr(s,'t',not s.t)or s.t}))()
:= is called the walrus operator, and it does an assign + return. For example, (x := 1) both sets x to 1 and returns the value 1.
The type function can be called with 3 arguments to create a new type, type(name, bases, dict). In this case, it's creating a new type with the name "", that inherits from str, and has the given dict as it's starting functions/values.
The walrus then assigns this new type to int, and the ending () creates a new instance of it that is assigned to value.
setattr(s, "t", not s.t) or s.t
setattr is used because you can't use = in a single-line expression, it does the same thing as s.t = not s.t
setattr always returns None, so setattr(...) or x will always return x.
The makes the value of s.t alternate between 0 and 1 every time bool(<instance of nameless type>) is called, so the value of bool(<instance of nameless type>) alternates between False and True.
Putting it all together, here is the equivalent non-single-line code: ```py
class NamelessType(str):
toggle = 1
def bool(self):
self.toggle = not self.toggle
return self.toggle
int = NamelessType
value = NamelessType()
thanks! i lowkey already know how those functions and operators work but ok
🤷 You asked for an explanation, but didn't say of what part, so just to be sure it's understandable to anyone with any knowledge level I started from the basics.
!e random cursed hello world I made ```py
import fishhook
@fishhook.hook(str)
def call(self, *args): return "Hello World"
class Foo(map(100, [1,2,3])):pass
print(next(Foo))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello World
I am so confused
what did Foo class help you with ?
It's where the string we call comes from
yeah but why the map in it ?
its inheriting from the map object
maybe i didn't get the reason on why to do it
me neither
its really cursed
I think it is because class Foo(map(..., []): ... calls type(map(..., []))('Foo', (object,), {whatever the __dict__ is})
i am delighted
which boils down to map('Foo', ...)
and, of course, strings are not callable so calling next(map('Foo', ...)) should error
but the hook above amends str.__call__ to return Hello, world
map("asd", ...) doesn't error, but trying to get the next item does
ah yes you're right
(and the 100, [1, 2, 3] is just a red herring)
Yhe I just picked something random for that
great
!e
from itertools import zip_longest
class HelloᅠWorld(zip_longest("Hello", "World")):
pass
print("".join(hello for hello,w,orld in HelloᅠWorld))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
HelloᅠWorld
well yeah that's kinda discord's schtick
That fake space looks cutsed
i make videos with computer about computer. also cartoon reptiles are here because it's fun.
channel icon made by Ucrash.
FAQ:
Q: What do you use to animate?
A: I use Moho 13! Previously (before January 2021), I used Anime Studio 11. Before October 2017, I used Anime Studio 9!
Q: Is Cosmos Quest still a thing?
A: no
Q: Will you make a video ...
@torpid flume in case ur still interested https://www.codewars.com/kata/52b7ed099cdc285c300001cd/python 💀
sum_of_intervals = lambda i : __import__("functools").reduce(lambda a, c: (a[0], max(a[1], c[1]), a[2]) if c[0] is not None and c[0] <= a[1] else (c[0], c[1], a[2] + (a[1] - a[0])), iv + [(None, None)], (*iv[0], 0))[-1] if (iv := sorted(i)) else 0
diabolical work
i would look at it but my account got banned 🥺
what did u do to get banned from codewars ? 
i found an exploit in their unit tests
and used it a few times to figure out the full extent of the exploit
then i reported it to them over email
got banned for this
i dont really care enough to ask them to unban me though lol
Get ban for reporting a bug
Fun 🥴
And this kids is why you don't go do bug hunting without making sure the company is fine with it
When you found the exploit you should have just reported it and left it at that, not kept poking around
this is a pretty nasty version (works on the examples but I didn't attempt to submit) ```py
def sumIntervals(a):
a=sorted(a,key=min);n,x=a[s:=0]
for l,u in a:
if l>x:s+=x-n;n=l
x^=(x^u)&-(x<u)
return s+x-n
Maybe just not send them an email as well if they don't have a bug bounty program
they didnt ban me from the email
they banned me from completing a bunch of challenges illegitimately
i disagree :3
poking around was fun and enjoyable
and didnt harm anyone
⇒ poking around was a net good
usually you need permissions to do that thing
poking around was fun and enjoyable
and didnt harm anyone
nice to hear that but maybe they didn't think this way
doesnt really matter what they thought /shrug
i had fun ^^
hahahaha that's the goal usually 😉
!e from hashlib import sha3_512#DID YOU KNOW : TRYING TO SOLVE THIS IS WORTHLESS AND YOU SHOULD STOP? _5='from</<import<aa';_p5=3+3-1;_6=globals().get(str(_p5)*{}.get('esoteric-[65,66,45,50]',1));'b_9' _6=5735816763073854953385921308212;_9=5795816763073854953388147237924;'Oeppq, dwnde!';______='sqrt' ___9=33591491951127897722760669368284102441202571953452030263829776;sr=__import__(''.join(reversed( 'htam').__iter__()));sr_=getattr(sr,______);_not_allowed_in_type_expression_4=int(sr_(___9));dec=49 globals()['_not_allowed_in_type_expression_4']=_6 if _5.count('aa')==1 else ______*409-100000000000 def q55555(bytes)->str:global cphr;return bytes.decode('utf-'+str(sr_(64))[0]);cphr='bepca, resde!' def asserter(condition:int):assert condition;assert condition;assert condition;assert True;dec3=910 _l1=lambda n:q55555(n.to_bytes(13));asserter(_not_allowed_in_type_expression_4==_6);x=20000;y=30001 _l2='y of the other challenges you have faced. Best of luck to you!';caeser_cipher_key=(9*9-80)+7-1 try:raise FutureWarning(f'Hi there little esoteric explorer! This one is way harder than man{_l2}') except:cphr='bepca, resde!';pass;# Error in fut0000000 stop now please!encoded msg[BsGsKeM9499J==]! try:exec(f'''{_5.replace("/", "__999__").replace("<", " "*99).replace("aa", "".join([cphr[0] , cphr[7],cphr[4],cphr[3],cphr[1],chr(115)]))}'''.replace('999', 'back to the future'.split()[3]))#PE except BaseException as e:result00000000=int.from_bytes(sha3_512(e.args[0].encode()).digest()[60:]) for query in range(result00000000-2225929708):print(_l1(_6+result00000000))#SOLVING IS WORTHLESS!!!
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, world!
worthless? got it
result of parse+unparse, will decode later ```py
from hashlib import sha3_512
_5 = 'from</<import<aa'
_p5 = 3 + 3 - 1
_6 = globals().get(str(_p5) * {}.get('esoteric-[65,66,45,50]', 1))
'b_9'
_6 = 5735816763073854953385921308212
_9 = 5795816763073854953388147237924
'Oeppq, dwnde!'
______ = 'sqrt'
__9 = 33591491951127897722760669368284102441202571953452030263829776
sr = import(''.join(reversed('htam').iter()))
sr = getattr(sr, ______)
not_allowed_in_type_expression_4 = int(sr(___9))
dec = 49
globals()['_not_allowed_in_type_expression_4'] = _6 if _5.count('aa') == 1 else ______ * 409 - 100000000000
def q55555(bytes) -> str:
global cphr
return bytes.decode('utf-' + str(sr_(64))[0])
cphr = 'bepca, resde!'
def asserter(condition: int):
assert condition
assert condition
assert condition
assert True
dec3 = 910
_l1 = lambda n: q55555(n.to_bytes(13))
asserter(_not_allowed_in_type_expression_4 == _6)
x = 20000
y = 30001
_l2 = 'y of the other challenges you have faced. Best of luck to you!'
caeser_cipher_key = 9 * 9 - 80 + 7 - 1
try:
raise FutureWarning(f'Hi there little esoteric explorer! This one is way harder than man{_l2}')
except:
cphr = 'bepca, resde!'
pass
try:
exec(f'{_5.replace('/', '999').replace('<', ' ' * 99).replace('aa', ''.join([cphr[0], cphr[7], cphr[4], cphr[3], cphr[1], chr(115)]))}'.replace('999', 'back to the future'.split()[3]))
except BaseException as e:
result00000000 = int.from_bytes(sha3_512(e.args[0].encode()).digest()[60:])
for query in range(result00000000 - 2225929708):
print(_l1(_6 + result00000000))
full doc https://paste.pythondiscord.com/KEWA
!e ```py
_6 = 5735816763073854953385921308212
_not_allowed_in_type_expression_4 = _6
def bdecode(bytes_): # q55555
return bytes_.decode("utf-8")
_l1 = lambda n: bdecode(n.to_bytes(13))
assert _not_allowed_in_type_expression_4 == _6
try:
raise FutureWarning(
"Hi there little esoteric explorer! This one is way harder than man"
"y of the other challenges you have faced. Best of luck to you!"
)
except:
cphr = 'bepca, resde!' # contains 'braces' for later import
try:
exec('from future import braces')
except:
result0 = 2225929709 # used later
basically boiled down to:
print(_l1(_6 + result0))
(=) print(_l1(5735816763073854953385921308212 + 2225929709))
(=) print(_l1(5735816763073854953388147237921))
(=) print(bdecode(5735816763073854953388147237921 .to_bytes(13)))
(=) print(bdecode(b'Hello, world!'))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, world!
i wouldn't say the warning is outright wrong, but i mean..
misc ```
'esoteric-[65,66,45,50]'
[65, 66, 45, 50] just translates to a string 'AB-2'
'b_9
'Oeppq, dwnde!' (probably 'Hello, world!' but pros please confirm)
_9 ** 2 == ___9
'bepca, resde!'
msg[BsGsKeM9499J==]
what do y’all think of this
import inspect
from dataclasses import dataclass
@dataclass
class AttrsAsDict:
target: type
def __setitem__(self, key, value):
setattr(self.target, key, value)
def __getitem__(self, key):
return getattr(self.target, key)
class ExtensionMeta(type):
@classmethod
def __prepare__(cls, name, bases, **kwds):
if kwds.get("extension_ignore", False):
return super().__prepare__(name, bases)
extends = kwds.get("extends")
if extends is None:
frame = inspect.currentframe()
if frame is None:
raise RuntimeError("inspecting parent frame not supported, use extends kwarg to specify target")
try:
extends = frame.f_back.f_locals[name]
except KeyError:
raise NameError(f"name {name!r} is not defined") from None
return AttrsAsDict(extends)
def __new__(cls, name, bases, namespace, **kwds):
if kwds.get("extension_ignore", False):
return super().__new__(cls, name, bases, namespace)
return namespace.target
class Extension(metaclass=ExtensionMeta, extension_ignore=True):
pass
hmm, interesting
class Foo: pass
class Foo(Extension): pass
print(repr(Foo)) # <class 'Foo.Foo'>
class Bar(Extension, extends=Foo): pass
print(repr(Foo)) # <class 'Foo.Bar'>
so the first Foo is coming from Foo.__module__ I think
but Foo.__name__ in the second Foo isn’t Bar… weird
I think it’s because __repr__ gets the name from _PyType_Name https://github.com/python/cpython/blob/main/Objects/typeobject.c#L1359-L1371
which gets it from tp_name, which is unconditionally set in PyType_FromMetaclass https://github.com/python/cpython/blob/main/Objects/typeobject.c#L5045
What's the usecase of this except repr?
It allows you to split class definitions
…also, does it have to have a usecase? we’re in #esoteric-python
Nope, just curious
Some languages such as Rust or Swift have ways for code associated with a type to be split up according to its functionality
and languages like Swift also use that to let users of types extend the types privately
This is sort of similar
That’s the inspiration, anyways
Having a different name isn’t really useful at all
Its only use would be to use the name to communicate what it’s for or something
like
class Foo:
pass
class Repr(Extension, extends=Foo):
def __repr__(self):
return "Foo()"
guys i think my repl is a little bit broken:
>>> 1+2
3
>>> 'a' * 3
aaa
>>> 'ab' * 5
abaababababababababababababababababababababababababababababababab
>>> [1, 2] + ['3', '4']
[1, 2, '3', '4']
>>> [1,2,3][3]
3
>>> [1,2,3][0]
1
>>> [1,2,3][2]
3
>>> [1,2,3][::]
[1, 2, 3]
>>> [1,2,3][::-1]
[3, 2, 1]
>>> [1,2,3][::-1]+[1,2,3]
5
>>> 'a' * 'x'
aaa
>>> 'x' + 'a'
xa
>>> a = 5; a + a
10
>>> a = 5; b = 7; a+b
12
>>> a = 5; b = 7; a+b+a*b
39
>>> a = 5; b = 7; (a, b)
(5, 7)
>>> 'x' * a
xxx
>>> len('x' * a)
2
>>> alphabet
abcdefghijklmnopqrstuvwxyz
>>> alphabet[::-1]
cbaa
>>> len(alphabet)
26
>>> len(alphabet[::-1])
26
>>> alphabet * 2
ababababababababababababababababababababababababababababababab
``` what should i do? 🤔
i am running the REPL like this: ||```
$ ollama run qwen2.5-coder:0.5b
Please be my python REPL. I will enter python expressions, you will output their results without any
... extra information. Do not explain your thinking. Here is the first expression: 1+2
3
'a' * 3
aaa
...
it's actually decent tho
name it python 5
AI enabled REPL
hot take: LLMs don't do any thinking so it wouldn't be possible for it to explain to you anyways
Not a super hot take either!
nah, but there are a lot of "AI" hype guys on the Internet lately
who turn it into a very controversial thing to say
Another take: this totally depends on the definition of "thinking" one's using. Very lax can even encompass normal computers without "artificial intelligence".
import pandas as np is a fun one
i do it all the time,since i started using pandas that is a standard
import pandas as np
import numpy as tk
import tkinter as pd
🥴
legend has it that if you import pandas as numpy your rem gets sudo'd
sorry but i don't remember possessing a cybersecurity expert
nothing happened to me
AHAHHAHAHAHHAHAHAH
smuggling pandas
i dont know if this fits the typical obfuscated/ctype-hacking posts of this channel, but it is certainly esoteric and python
!e
def fib_cps(n, closure):
if n <= 1:
return closure(0)
if n == 2:
return closure(1)
return fib_cps(n-1, lambda x: closure(fib_cps(n-2, lambda y: x + y)))
for i in range(10):
fib_cps(i, print)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0
002 | 0
003 | 1
004 | 1
005 | 2
006 | 3
007 | 5
008 | 8
009 | 13
010 | 21
one of the most challenging concepts ive had to wrap my head around
this is not esoteric in my opinion but all my coworkers code look like this
its CPS which my prof says is supposedly grad level concept, which id say qualifies it as esoteric
It totally is esoteric. Broaden your horizon :)
- opinion 2) tongue in cheek
What does CPS mean?
the code reminds of the .then() callbacks you would see in JS before async/await
In functional programming, continuation-passing style (CPS) is a style of programming in which control is passed explicitly in the form of a continuation. This is contrasted with direct style, which is the usual style of programming. Gerald Jay Sussman and Guy L. Steele, Jr. coined the phrase in AI Memo 349 (1975), which sets out the first versi...
the central idea is to turn all recursion into tail recursion by passing a closure containing "everything else" to do after the function call. figuring out how to create and pass these closures is pretty hard though, at least for me
What is this bro
wrong channel probably
esoteric python
Cursed
i mean they pasted it in like 7 different channels so
Maybe someone else has an idea on how to do one of these very cursed things:
Using 3-arg type, you can make types with double-invalid attributes, ie type("",(),{():1}) that are only readable via __dict__/vars. The things I'm wondering are:
- (pretending that this actually works) Is it possible to change the value of
<nameless type>.(), like how you would<nameless type>.() = 2normally? - For trying to see if this is a bug in 3-arg
typeor not, is it possible to make some ast that defines a classAwithout usingtypewhereexec(compile(tree, __file__, "exec"));print(A.__dict__[()])gives1?
- ... like how you would normally ...
no
STORE_ATTR takes an index from __code__.co_names as the attribute to store to
co_names is populated with strings determined to syntactically take the place of varnames or attrnames at compile time
so, at the very least, you cant do it unless you manually fiddle with a code object
re: 2., im not sure why this would be a bug
and overall im not sure what you mean by "double-invalid attributes"
unsure how an attribute can be more invalid than invalid
Where would the __code__ object for a class come from? Also, I don't understand how that would work, ie if you used the result of input to set attributes.
Just because of what godlygeek said, since it is certainly a weird inconsistency
Double invalid since you already have normal invalid attributes like " " that work with get/set attr.
>>> class M(type):
... @classmethod
... def __prepare__(cls, *args):
... return {(): 1}
...
>>> class A(metaclass=M):
... pass
...
>>> A.__dict__
mappingproxy({(): 1, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None})
Does this answer to your 2?
Ooh metaclass, I didn't know __prepare__ was a thing
Neat weird thing.
!e ```py
class A:
locals()[()] = 1
print(A.dict)
print(A.dict[()])
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | {'__module__': '__main__', (): 1, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
002 | 1
class A:(x,y)=(1,2) -> 'x': 1, 'y': 2 huh, so you can put any valid store target there and it just works
So then I guess that just begs the question, why is there the RuntimeWarning when you do this?
conventially you can't do <type>.() = 2 even with .co_names substitution
PyObject_SetAttr() (used in the STORE_ATTR opcode) would fail anyway
the only way to do it easily would be (<type>.__dict__ | type("",(),{"__ror__":lambda _,x:x})())[()] = 2
As for the 1, it's also yes, but it's very weird:
>>> class A:
... locals()[()] = 1
...
>>> A.__dict__[()]
1
>>> A.__dict__[()] = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment
>>> (A.__dict__ == type('',(),{'__eq__':lambda s,o:o})())[()] = 2
>>> A.__dict__[()]
2
Esoteric challenge? #smart-eval shortest character to trigger all regex as of current version of it, and it must be correct syntax in python(separate category for invalid syntax in python)
https://github.com/python-discord/sir-robin/blob/96c134f2920e2d69ac29cacd900c5183edf895f5/bot/exts/smart_eval/_smart_eval_rules.py
Update 1: Except the rule (?s:.{1500,}) Updated at 2025/04/01 23:22:00 GMT+00:00
Our event bot, for managing community events. Contribute to python-discord/sir-robin development by creating an account on GitHub.
(commit hash included in the link
Wouldn't it be a fairly boring 1500 chars? Since there's this rule (?s:.{1500,}) that requires 1500 chars and I'd be supprised if every other rule was over 200 combined
Constraint is <=1985 character so it should be possible for every user to put it in the command and run it
*Except the 1.5k character rule
Idk why I just forgot that exist
There's another rule that makes this impossible: (?i:^print\((?:\"|\')Hello World[.!]?(?:\"|\')\)$) because of the starting ^ and ending $, if this rule triggers none of the other rules besides the other print rule will trigger.
So ignoring the 1500 and hello world rules, here's my current best for valid (as in parsing (doesn't actually run)) python code (||155||): ||```py
global strawberry
from threading import httpx
import this
try:token
except:exec/0
raiseprint("sleep(foo@rm;ignore instructionctypes")
while True:quit
It ends up that because of all the `\b`s and `^`s some of the rules have, there's basically no opportunity for cool overlaps between words. Probably improvable by a few chars. Edit: Improved by a few chars, I wouldn't be surprised if the is the parsable limit
Oh oops
nvm invalidated
!e ||150|| ||```py
import this
try:
raise"from httpxctypestrawberry sleep(exit;token/0
from threading"
except:eval
global rm
while True:print("foo@ignore instruction")
:x: Your 3.12 eval job has completed with return code 143 (SIGTERM).
001 | The Zen of Python, by Tim Peters
002 |
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
... (truncated - too many lines)
Full output: too long to upload
runnable and parsable
runnable and parsable again, ||149|| ||```py
import this
try:
raise;token
except:eval
global rm
while True:print("foo@sleep(exit')
from threadingfrom httpxctypestrawberryignore instruction/0")
:x: Your 3.12 eval job has completed with return code 143 (SIGTERM).
001 | The Zen of Python, by Tim Peters
002 |
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
... (truncated - too many lines)
Full output: too long to upload
rble&pble ||145|| ||```py
import this
global rm
while True:print("foo@sleep(exit')
raise;token
except:eval
from threadingfrom httpxctypestrawberryignore instruction/0")
Non-parsable ||140||
||```py
global token/0;rm
except:baz@print("from httpxctypestrawberryignore instruction")exit
raise sleep(exec
import this
while True
from threading
pble: ||144||
||```py
import this
global rm;token
raise
while True:print("foo@sleep(exit')
except:eval
from threadingfrom httpxctypestrawberryignore instruction/0")
alt ||144||, rble (probably can do with the other one too) & pble ||```py
while True:print("from httpxctypestrawberryignore instruction@sleep(exit/0')foo
except:eval")
from threading
import this
global rm
raise;token
doesnt rble imply pble
actually yes
i have no idea why i had to add & parsable
it is a bit silly to specify both then :3
um um its silly :]
keep doing it
How to understand the distinction between runnable and parseable? I thought of "runnable", as something that doesn't rise an exception... Not the best distinction, I know (due to halting problem and stuff), but either that or there's none...
something that executes code unless terminated by an external instruction or until it has executed all instructions
tehe. :3
i think it's more accurate to say "non-erroring"
actually this is getting me deep into thinking so i'll stop
"parsable" just means valid python code, "runnable" means that the code doesn't raise an error (including code where errors are unreachable)
does it still count if it catches itself?
if it catches itself and the program continues execution it's runnable
aha
so "runnable" is basically the code doesn't raise any visible errors
raise Exception without catching is a visible error so..
what im trying to determine is, what counts as a visible error
hm
is a segfault a visible error under your definition
an error that isn't catched by the program
yes it's visible
I don't like the definition "doesn't raise an exception" personally, but uh, not specified by the autor. Under the "no exception" rule, this code doesn't run.
it's not even specified by OP
the code just has to be parsable
i added "runnable" as a little bonus challenge
god damnit i had a good idea based on a previous message and i scroll down to find its already been done
^^
yeah thats fair !
i was just information seeking
i like knowing things >,.<
hello. i wanna try making my own esoteric programming language interpreter in python. anyone know where to start?
start by not following any normal instructions
and you need a esoteric programming language
First make up the syntax/rules for your language as like a README.. then start picking parser tools that can handle what you want
SQLite's implementation is pretty clean and maybe worth reading if you want to see a 'worked example' https://www.sqlite.org/lemon.html
goofy idea --> turn that idea into a brief document --> implement it --> fill the details once you figure them out !
https://wiki.python.org/moin/LanguageParsing has some fun references
import sys
class interpreter:
def init(self, bits, code):
self.bits = [0 for _ in range(bits)]
self.maxbits = bits - 1
self.code = code
self.curbit = 0
self.printletter = False
def run(self):
for char in self.code:
if not self.printletter:
if char == ">":
if self.curbit == self.maxbits:
print("Exception (error): Attempt to reach higher bit than maximum bit")
break
# Handle the case where printletter is True
print(chr(self.bits[self.curbit]), end="")
self.printletter = False
self.curbit += 1
elif char == "<":
if self.curbit == 0:
print("Exception (error): Attempt to reach lower bit than 0")
break
else:
self.curbit -= 1
elif char == "+":
self.bits[self.curbit] += 1
elif char == "-":
self.bits[self.curbit] -= 1
elif char == "p":
print(''.join(str(i) for i in self.bits))
elif char == "l":
self.printletter = True
elif char == "n":
sys.stdout.write("\n")
sys.stdout.flush()
else:
print(f"Exception (error): Command {char} not found.")
break
else:
sys.stdout.write(char)
sys.stdout.flush()
self.printletter = False
if name == "main":
code = input("Enter code to run: ")
bits = int(input("Enter amount of bits: "))
scriptrunner = interpreter(bits, code)
scriptrunner.run()
i made this script. this language just uses single letters to run
If your language is simple enough, you can even use shlex which is built into the standard library
If you use l the next char is being ignored?
First thing I would do is take a more 'data-driven' approach; rather than using the characters literally in your 'elif' clauses, have them in a dictionary for example along with any other attributes you need to know about them, and then just fetch that data when deciding what to do. That's just me though perhaps.
A "Hello, World!" script in this language would be "lHlelllllol lWlolrllldn"
Also indentations issue
If u use "l" the next letter will be the item you want to output to the iostream
Hmm l and n seem quite unnecessary then because you could just use p to do the same thing
Also maybe check this out https://github.com/cesbit/pyleri
You mean something like commands = {h: lambda: print("hello, world")}?
you don't need a parser if you're doing one character commands
Yeah, that's probably where I would start, though in some cases you might be able to say something like "shifts left by 1" vs "shifts right by 1" and just fetch that '1' in your evaluator loop
P is used to print the bits (or just numbers) to the iostream
Yeah you don't need a parser, it's just that languages tend to grow features, and it's nice to have a way to add them cleanly
Yes, which can basically do l and n with other code
So you can remove it for more esoteric
Ill try, i think im gonna go write some code, see if i can make it shorter and then try your idea
class interpreter:
def __init__(self, bits, code):
self.bits = [0 for _ in range(bits)]
self.maxbits = bits - 1
self.code = code
self.curbit = 0
self.printletter = False
def run(self):
commands = {
">": self.moveright,
"<": self.moveleft,
"+": self.inc,
"-": self.dec,
"p": self.printbits,
"l": self.printletterfunc,
"n": self.newline,
}
for char in self.code:
if self.printletter:
sys.stdout.write(char)
sys.stdout.flush()
self.printletter = False
elif char in commands:
commands[char]()
else:
print(f"Exception (error): Command {char} not found.")
break
def moveright(self):
if self.curbit == self.maxbits:
print("Exception (error): Attempt to reach higher bit than maximum bit")
else:
self.curbit += 1
def moveleft(self):
if self.curbit == 0:
print("Exception (error): Attempt to reach lower bit than 0")
else:
self.curbit -= 1
def inc(self):
self.bits[self.curbit] += 1
def dec(self):
self.bits[self.curbit] -= 1
def printbits(self):
print(''.join(str(i) for i in self.bits))
def printletterfunc(self):
self.printletter = True
def newline(self):
sys.stdout.write("\n")
sys.stdout.flush()
if __name__ == "__main__":
code = input("Enter code to run: ")
bits = int(input("Enter amount of bits: "))
scriptrunner = interpreter(bits, code)
scriptrunner.run()``` Did you mean something like this?
you online?
(That is what I meant by 'data-driven', so I think it's an improvement for sure)
Alright, thanks!
Ye
The code structure looks alot nicer
class interpreter:
def __init__(self, bits, code):
self.bits = [0 for _ in range(bits)]
self.maxbits = bits - 1
self.code = code
self.curbit = 0
def run(self):
commands = {
">": self.moveright,
"<": self.moveleft,
"+": self.inc,
"-": self.dec,
"p": self.printbits,
}
skip_next = False
for char in self.code:
if skip_next:
if char == ";":
self.bits[self.curbit] = 0
elif char.isalpha() or char in "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ ":
self.bits[self.curbit] = char
else:
print(f"Exception (error): Unexpected character after '/' - {char}.")
break
skip_next = False
elif char == "/":
skip_next = True
elif char in commands:
commands[char]()
else:
print(f"Exception (error): Command {char} not found.")
break
def moveright(self):
if self.curbit == self.maxbits:
print("Exception (error): Attempt to reach higher bit than maximum bit")
else:
self.curbit += 1
def moveleft(self):
if self.curbit == 0:
print("Exception (error): Attempt to reach lower bit than 0")
else:
self.curbit -= 1
def inc(self):
self.bits[self.curbit] += 1
def dec(self):
self.bits[self.curbit] -= 1
def printbits(self):
print(''.join(str(i) for i in self.bits))
``` I remove printletterfunc and newline.
Now / is used to make a bit a letter.
I can show a hello world program with 12 bits
/H>/e>/l>/l>/o>/ >/W>/o>/r>/l>/d>/!p
What do you think about it?
Seems pretty good to me. Very readable.
If you ever want to get into more complex constructions like parens to group comands, you might want to do some 'real' parsing, but this is fine for what you need for now
Yeah... it was just a silly idea. also my first time doing something like this
Looks very good for a first swing at lexing a string into meaningful content
There are plenty of possible refactorings you could do but none of them are crucial for something that small
Im pretty sure i added the possibillity to increment/decrement character (by changing the ASCII value of the character) I dont have Nitro though so i cant show the code ):
You can use https://paste.pythondiscord.com/
Good separation of logic, the dispatch table of commands->functions is good, exception messages are clear
There's a string.punctuation you could consider using instead of your literal list of characters
you might consider raising ValueError instead of printing error messages only, but that's up to you
You could move the 'set_bit' and 'validate_bit' sorta operations out to helper functions but again that's not crucial here
and if you want to comply with Python style it should be Interpreter vs interpreter
Alright, ill change it
Yeah definitely, you have a clean place to call a 'prompt_for_input()' kind of function in your run loop
Maybe i can make the character/command for input something like p{i or c}{bit} i being int and c being character
Makes sense.. feels like the command language in a debugger sorta
if statements might be too complex for now
Oh nevermind the input cant be called p because thats already printbits
maybe C for catch?
I have to make a name for the language too. Maybe CharScript?
yeah charscript sounds good
"TerseLang" haha
ha
"IdonotunderstandinwhichwayyoucouldpossiblyusethisLang"
So right now you've got elif char.isalpha() or char in "!\"#$%&'()*+,-./:;<=>?@[\\]^_{|}~ ":`
one way to rewrite that is to import string and then say: elif char in string.ascii_letters + string.punctuation + string.whitespace:
string.digits too if you want numbers to be permitted, but they aren't currently so that's fine
print("Enter string to convert:")
string = input()
bits = 0
full = ""
for char in string:
if char == string[0]:
full += f'/{char}'
else:
full += f'>/{char}'
bits += 1
full += "p"
print(full)
print(f'Bits: {bits}')``` I made this string to CharScript converter
Hmm, shouldn't that be running your Interpreter? Maybe I'm missing the intent.
Nah its just to give you a string to paste into the main.py file
Gotcha
I just made the interpreter 10 times better:https://paste.pythondiscord.com/YLQA
404
am making an esolang lol
#main
@chef
~
buy
orange
1
~
+
~
carve
1
1
~
+
~
buy
orange
2
~
+
~
carve
2
1
~
+
~
buy
orange
3
~
+
~
cook
add
1
2
~
+
~
carve
3
shelf
~
@customer
+
~
order
orange
3
~
+
~
eat
orange
3
~
!!!
this is a script i made in the lang.
the lang will be compiled into python
this will be the result to this script.
def main():
a:int = 1
b:int = 1
c:int = a+b
print(c)
if name == "main":
main()
its called restaurantscript or RScript for short
cool
i'm gonna go make my own esolang
