#esoteric-python

1 messages · Page 51 of 1

quartz wave
#

SOFT_KEYWORDS is not a token

#

you seem to be talking about this, but it's part of the parser generator and not the tokenizer

night quarryBOT
#

Tools/peg_generator/pegen/parser.py line 165

SOFT_KEYWORDS: ClassVar[Tuple[str, ...]]```
earnest wing
#

it is in the Grammar/tokens file iirc

quartz wave
#

i see

#

but that's SOFT_KEYWORD

night quarryBOT
#

Grammar/python.gram line 1186

| !(NAME STRING | SOFT_KEYWORD) a=disjunction b=expression_without_invalid {```
quartz wave
#

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

bleak wadi
#

If Python follows modern trends, v4.0 will probably have a flag to compile the source to JS instead of bytecode 😛

oak horizon
upbeat folio
#

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 :)

quartz wave
#

python/cpython#125482

quartz wave
#

!e coming in 3.14
this won't produce an error ```py
from future import barry_as_FLUFL

print(1 <> 2) # True

night quarryBOT
restive void
#

!pep 401

night quarryBOT
quartz wave
steep notch
#

Donne moi un code css pour styli
Styliser mes menu de navigation avec

arctic skiff
#

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

austere mauve
#

Anyhow, that's not a proper solution (the new line should be present) (that's also the reason this is not a spoiler).

arctic skiff
#

yeah its not a sol in any way you just made the code not run, which is same as just running print('hello world')

grave grail
#

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
fleet lintel
#

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
arctic skiff
arctic skiff
#

nvm got it you are running on 3.12

fleet lintel
#

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

grave grail
#

Actual attempt to recover instead of just somehow printing it🥴 nice

arctic skiff
#

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")||

arctic skiff
#

solved

arctic skiff
grave grail
#

Next: try make it shorter than 31 (I think that's someone that makes it by warning) lul

arctic skiff
austere mauve
#

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)

arctic skiff
#

I mean its useless it will exit with 0

austere mauve
grave grail
#

Oh 🥴

sick hound
#

this channel is a gem lol
is anyone writing on these discussions

#

I'd read

marble river
#

Guys, whats the nastiest one-liner you ever wrote

earnest snow
#

it's not finished, but an entire JSON library

#

should finish it though

unreal rampart
grave grail
arctic skiff
#

also another one is 15.6k chars long hello world which uses freaking globals to generate '__import__("__hello__").main()'

fleet lintel
grave grail
#

lmao 33k char'

marble river
grave grail
hybrid trail
# marble river Guys, whats the nastiest one-liner you ever wrote

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)))
hybrid trail
#

(nasty because it is slightly buggy)

sick hound
#

tell me how to shoot it quickly

#

example snippet or something

hybrid trail
#

try giving it this as input >++++++++++>>>+>+[>>>+[-[<<<<<[+<<<<<]>>[[-]>[<<+>+>-]<[>+<-]<[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>[-]>>>>+>+<<<<<<-[>+<-]]]]]]]]]]]>[<+>-]+>>>>>]<<<<<[<<<<<]>>>>>>>[>>>>>]++[-<<<<<]>>>>>>-]+>>>>>]<[>++<-]<<<<[<[>+<-]<<<<]>>[->[-]++++++[<++++++++>-]>>>>]<<<<<[<[>+>+<<-]>.<<<<<]>.>>>>]

#

it should print factorials

sick hound
#

yea it might be on me

hybrid trail
sick hound
#

tried on (i)python locally

#

NameError: name 'aiter' is not defined

sick hound
#

cool af

#

yep checks out too http://tpcg.io/_6E9P98

twin roost
#
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?

restive void
#
def _sfr():
    yield "A"
    while True: yield "B"
special_first_run = iter(_sfr()).__next__
spare hare
#

hello, I am looking for a partner to learn DSA with me using python and on intermediate level

past forge
#

-# why cross post

fleet lintel
#

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, [...]]]"
```||
karmic pumice
#

!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

||

night quarryBOT
earnest wing
#

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
fleet lintel
#

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.

earnest wing
#

It's a good concept to know in python, ||self containing lists||

fleet lintel
# fleet lintel I was recently reminded of this, but it looks like most of the code was broken i...

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, [...]]]"
```||
grave grail
#

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

fleet lintel
grave grail
fleet lintel
#

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.

grave grail
#

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

fleet lintel
#

No fun

grave grail
#

And this is also reason that it's not spoiler

grave grail
#

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

fleet lintel
#

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.

grave grail
#

lol

versed eagle
#

now its a function ^^

hybrid trail
versed eagle
#

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

hybrid trail
#

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

earnest wing
#

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"

versed eagle
austere mauve
earnest wing
#

this seems like broken syntax?

#

but yeah

#

evil

austere mauve
past forge
#

!e
||```py
f=lambda :_;raise SystemExit
print('hello')

night quarryBOT
past forge
#

Well you can make it ||16||
||```py
raise SystemExit

earnest wing
#

gotcha >:)

earnest wing
past forge
#

He basically did
||```py
def f(): ...
raise SystemExit

fleet lintel
#

You got me ||```py

issubclass(SystemExit, Exception)
False

hybrid trail
#

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?

fleet lintel
#

I get ```
print(id(-id(0))//id(.0)*not
^
SyntaxError: '(' was never closed

hybrid trail
#

its a single line, maybe discord wrapping messed you up?

fleet lintel
#

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.
hybrid trail
#

then it seems like its very system dependent :(

olive sundial
#

Do you think AI would replace Cybersecurity?

karmic pumice
hybrid trail
#
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
restive void
#

Working on strings, not bytes, but:

def swapcase(s):return"".join(chr(ord(c)^32)for c in s)
stable hornet
versed eagle
#

(system, version, compiler, flags)-dependent

austere mauve
austere mauve
fleet bridge
#

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'))
night quarryBOT
restive void
oblique ibex
#

bytes.swapcase exists too, but sadly they don't work on eachother

restive void
fleet bridge
#

!d str.swapcase

night quarryBOT
#

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`.
oblique ibex
#

hmm, in what situation could s.swapcase().swapcase() == s be False

karmic pumice
#

the german ß incident

restive void
#

!e

print("ß".swapcase().swapcase())
night quarryBOT
restive void
#

There's tons of characters for which this is true

oblique ibex
#

ah, so swapcase uses str.casefold?

restive void
#

"ß".upper() is "SS".

karmic pumice
#

!e

f = open("weird.txt", "w")
for i in range(0x110000):
  s = chr(i)
  if s.swapcase().swapcase() != s:
    f.write(s+" ")
night quarryBOT
# karmic pumice !e ```py f = open("weird.txt", "w") for i in range(0x110000): s = chr(i) if ...

: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 ﬓ ﬔ ﬕ ﬖ ﬗ 
karmic pumice
#

oh what happens to the greek ones
oh its not greek.. i suppose i should've wrote the ordinal

restive void
#

It's physics symbols that just look exactly like greek chars and get normalized?

#

The other thing is the turkish dotless/dotted i

karmic pumice
#

!e

from unicodedata import name
print(name("π")) # normal greek pi 
print(name("ϖ")) # this weird one
night quarryBOT
karmic pumice
#

amazing "greek pi symbol"
also the "long legged cyrillic D" lmao i cant

restive void
#

ah, some of them are just normalized with decomposition

hybrid trail
#
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('৸︆␄︄∋︀㊙︂〾︁🀇︄䷐︂𝧽︂ͻ︅▣︂ጥ︂☚︃۝︂ᗞ︃ꫴ︂Ⴈ︃℁︂〄︂㈴︂')
quartz wave
#

what's the point of a ㌿︁

earnest wing
#

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...

quartz wave
#

woah

#

oh that explains why there are stuff like ㏴

sly mortar
#

Guys ,I need someone that is good at python

#

For a big project

#

Python or math

midnight swift
austere mauve
pure dew
#

ideograms are cool

quartz wave
#

but yea

pure dew
#

channel's also slowed down a bit

versed eagle
versed eagle
pure dew
versed eagle
#

word

#

OH

#

sorry lmao i misread "ideogram" as logogram

#

dyslexia moment

simple sphinx
#

not sure if this is esoteric python or esoteric cmd, but I think you guys will like my abomination :P

night quarryBOT
earnest wing
#

that's really funny

simple sphinx
night quarryBOT
simple sphinx
#

I had to download windows to a laptop to write this lel

grave grail
#

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 B where B is a subclass of A, you must annotate it as B not `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
proper vault
#

what does confused entail here?

grave grail
arctic skiff
arctic skiff
#

you could have just used vm or just not write it for windows

simple sphinx
simple sphinx
#

Just a very very cursed way of implementing it

fleet bridge
austere mauve
#

Porting to linux shouldn't be that hard...

karmic pumice
grave grail
night quarryBOT
#

stdlib%2Fbuiltins.pyi lines 493 to 496

@overload
def lower(self: LiteralString) -> LiteralString: ...
@overload
def lower(self) -> str: ...  # type: ignore[misc]```
grave grail
#

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)

karmic pumice
#

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

grave grail
#

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

karmic pumice
#

surely typeshed has an int.__add__(Literal[1], Literal[2]) -> Literal[3] overload
(no)

grave grail
night quarryBOT
#

stdlib/builtins.pyi line 276

def __add__(self, value: int, /) -> int: ...```
karmic pumice
#

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

grave grail
karmic pumice
#

then you should make the point more clear

grave grail
#

It is very clear
typeshed is in the type specification

karmic pumice
#

seems like you only want us to abuse control flow analysis, because otherwise you'll say "but its correct because typeshed defines it"

grave grail
#

The type checker being able to resolve better than the type stub doesn't make it a requirement

karmic pumice
karmic pumice
#

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

grave grail
austere mauve
# grave grail I have a challenge: Use any valid typehint in python that follow the specificati...

Your challenge is quite unclear...

  1. What do you mean with fully correct?
  2. What does accurate mean? How do you measure it?
  3. What the last point mean? What do you mean more accurate? How can something be more accurate when it's already accurate?
  4. 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)?
  5. 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

  1. Going further: what specification should we follow?
grave grail
#
  1. When the annotation cover all the possible type of return value (You cannot say it is B when in all case it return A, assume B is not in A)
  2. 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)
  3. Answered in 2
  4. 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)
  5. ...
  6. 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)

versed eagle
simple sphinx
#

<3

stable hornet
#

this is a very strange challenge

versed eagle
versed eagle
# grave grail 1. When the annotation cover all the possible type of return value (You cannot s...
  1. 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

grave grail
#

f is Callable[[], int | Callable[...]] and there is path that it could return f so you didn't provide a correct type annotation

versed eagle
#

and there is no path that can return f

#

0>1 is the constant False

grave grail
versed eagle
#

^^

grave grail
night quarryBOT
#

stdlib/builtins.pyi line 327

def __gt__(self, value: int, /) -> bool: ...```
versed eagle
versed eagle
grave grail
#

Cover something is not a possible return type according to type definition (according to type definitions from typeshed, it is very possible)

versed eagle
grave grail
#

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.

karmic pumice
versed eagle
#

mypy accepts it if the condition is just 0, so eliminating dead branches is allowed

#

¯_(ツ)_/¯

versed eagle
night quarryBOT
karmic pumice
karmic pumice
versed eagle
#

it can only return int

versed eagle
versed eagle
#

hopefully that cleared things up

grave grail
#

i would not respond further relate to this, do not continuously ping me

versed eagle
#

... okay

#

i guess i beat the challenge then

#

lol

fleet lintel
#

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 🙃

versed eagle
#

seems easy

karmic pumice
# fleet lintel This entire discussion feels like a lot of those very cool and interesting issue...

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)

versed eagle
#

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

austere mauve
#

Is this a valid solution?

a:int=""or 1
versed eagle
#

probably

#

i dont feel like running the typecheckers on it, but it looks valid

fleet lintel
# versed eagle i dont pay attention to python's typing ecosystem at all; could you list a few e...

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.

GitHub

This question has already been discussed in #18 long time ago, but now I stumble on this in a practical question: How to annotate something that subclasses two ABC's. Currently, a workaround is...

karmic pumice
#

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

austere mauve
#

Also, here's another one:

a:__debug__.__class__=__debug__
austere mauve
#

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.

grave grail
karmic pumice
grave grail
#

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 🤔

fleet lintel
grave grail
#

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 🤔

karmic pumice
#

all expressions have a type
in this case, its the bottom type

grave grail
#

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)

karmic pumice
austere mauve
#

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)
fleet lintel
#

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].

karmic pumice
#

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

fleet lintel
#

Well yes if we are in the real world, but we are (or at least I am) currently in the magic land of typing.

austere mauve
grave grail
fleet lintel
#

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()

grave grail
#

When the random value is 0

fleet lintel
#

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.

karmic pumice
grave grail
karmic pumice
#

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"

fleet lintel
#

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.

grave grail
#

I bet if you put int | Never at return type annotation, the type checker would scream at you

karmic pumice
#

nope

grave grail
#

Wtf fine

fleet lintel
#

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.

grave grail
#

Why tf the documentation is so horrible 💀

fleet lintel
#

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)

grave grail
#

The N number set 🥴

versed eagle
#

in many cases

#

so using it for this is annoying

grave grail
#

Complain to typeshed instead and I don't agree that is the type checker fault

versed eagle
grave grail
#

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.

versed eagle
#

well the thing is that

#

the typechecker was incorrect

#

which is what your challenge asked for

grave grail
#

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

earnest wing
#

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.

austere mauve
#

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.

austere mauve
#

...

#

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?

arctic skiff
#

thats also why I removed it instantly after posting

#

my brain wasn't working at that moment

austere mauve
arctic skiff
#

cython

austere mauve
arctic skiff
#

I know what jsx, I am already using tsx in my current project

austere mauve
arctic skiff
#

I just said I was referring to cython......

arctic skiff
austere mauve
#

ye

hasty temple
#

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

proper vault
#

Maybe a weakset of sorts.

hasty temple
#

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

vast wave
#

python sees that as an int, but python doesnt care about type hints

austere mauve
#

!e ```py
from typing import Never
print(Never | int)

night quarryBOT
austere mauve
#

It's Union[Never, int]

vast wave
night quarryBOT
vast wave
#

ah it actually does

#

interesting

#

!e from typing import Never; dir(Never)

flint hollow
#

python does not reduce or simplify types

vast wave
#

!e from typing import Never; print(dir(Never))

night quarryBOT
# vast wave !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']
vast wave
#

yeah as expected Never has overridden |

vast wave
#

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

flint hollow
#

!e print(float | int)

night quarryBOT
vast wave
#

do or

flint hollow
#

that type unambiguously simplifies to just float

fleet lintel
# vast wave do or

!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.
night quarryBOT
vast wave
karmic pumice
night quarryBOT
karmic pumice
#

there's also stuff like union flattening

quartz wave
pure dew
sly mortar
#

Who is at high school here?

formal tendon
sly mortar
#

hala

quartz wave
unique heath
#

me

modest skiff
arctic skiff
arctic skiff
thick grotto
#

Hey I am conducting a lecture on python one liners(One-liners in general) any suggestions or inputs ?

grave grail
#

I think he meant read the chat history 🥴

thick grotto
#

oh

stable hornet
arctic skiff
versed eagle
#

;

arctic skiff
versed eagle
#

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

arctic skiff
stable hornet
#

exec ftw

versed eagle
arctic skiff
#

surely you can do that... but my point was about built in syntax

night quarryBOT
#

: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.

versed eagle
arctic skiff
grave grail
versed eagle
#

im not disputing it

#

and its not relevant to what i said about python

past forge
#

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
versed eagle
#

use it as a default argument to the lambda

#

lambda a, b, o=__import__("operator"): ...

versed eagle
quartz wave
versed eagle
#

=> you can construct it with types.FunctionType

quartz wave
#

oh i see

#

still no await tho :<

fleet bridge
#
>>> 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
grave grail
#

Tbf, is async def just a syntax sugar that return a coroutine to a special function?

fleet bridge
#

yes

grave grail
#

Oh welp, time to learn coroutine

#

Oh, so technically if a system is set nicely, you can just avoid using await entirely 🤔

thick grotto
covert rivet
#

!e

__import__("sys").stdout.write('\n'.join("O" + ["n","ff"][i]for i in[int(b) for b in bin(9)[2:]]))
night quarryBOT
austere mauve
austere mauve
#

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||

versed eagle
#

||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||

versed eagle
grave grail
# austere mauve Dumb code golfing challenge: Python 3.9 is reaching EOL this year. Detect whethe...

||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

austere mauve
grave grail
potent flare
restive void
versed eagle
#

it wont suggest for 1 length names

#

yeah l3v got it in 1

wanton tundra
#

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)
)
karmic pumice
wanton tundra
#

i just thought this was funny when i discovered but i cant think of a single use

gleaming linden
versed eagle
royal knot
#

Guys is there a python function that check how many decimal digits a number has?

fleet bridge
#

int(lg(n))+1

austere mauve
versed eagle
#

aha

versed eagle
grave grail
austere mauve
grave grail
#

Then would this work?
||{}|{i}||, I don't have the test environment setup and just guessing, or wrong error order?

earnest wing
#

i is evaluated before |

versed eagle
grave grail
fleet bridge
austere mauve
gleaming linden
#

You have to differentiate between 3.9 and 3.10+ as well

fleet bridge
#

it does differentiate: if it fails - it is 3.9, if not - 3.10+

oblique ibex
#

it won't fail if it is 3.9, it'll only fail if it's before 3.9

versed eagle
fleet bridge
#

the challenge does not mention 3.8-, they have reached EoL so they are no longer relevant

oblique ibex
#

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

hybrid trail
#

!e

class evaluator:__format__=exec

f'''{evaluator():
def main():
  print("Hello, world!")

main()
exit()
}'''
night quarryBOT
hybrid trail
#

fun fact: you can put basically anything in a format string

grave grail
#

Lmao

quartz wave
#

TIL exit() and quit() are not REPL-exclusive??

austere mauve
# quartz wave 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.

quartz wave
#

ok but i have a false memory of them not working outside of the REPL

#

buh.

lunar marsh
#

they exist but dont work if you run a script with ipython

#

for some reason

restive void
#

Not necessarily. If you run python with -S site.py won't be imported and exit etc. won't be a thing.

austere mauve
#

unless explicitly marked otherwise
^

austere mauve
pure dew
#

exit is a nasty hack too lmao

stable hornet
#

sometimes a useful hack

#

but mostly a slight footgun for beginners

bright valve
#

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)
versed eagle
quartz wave
unique heath
quartz wave
#

aren't most inputs like that..?

unique heath
quartz wave
#

mufh.. :(

hybrid trail
#

is there anything you can do in python if every line of source code starts with a space?

oblique ibex
#

you can make comments!!

#

I tested with a couple other stuff but couldn't find anything sadly

hybrid trail
#

i have been able to find a way to run code but ||nothing with only printable chars, which I would prefer||

oblique ibex
#

can you show it

earnest wing
#

starting with a codec declaration?

quartz wave
grave grail
#

Infinite sequence of \ on each line (if anyone have any idea)

#

It's line continuation tho, couldn't manage to find anything useful

ember coyote
#

ws[

potent flare
#

]sw

grave grail
#
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

quartz wave
# grave grail ```py value = (<code>) if value: raise Exception if not value: raise Exc...

!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")

night quarryBOT
restive void
#

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__}))()

grave grail
#

Nice and quick lol

quartz wave
#

!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")

night quarryBOT
quartz wave
#

..eh?

#

really

#

oh.

#

i see

proper vault
#

does it count if I use tracing to jump to the final line?

restive void
#

Won't be shorter than the other method

proper vault
#

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.

grave grail
wanton tundra
#

!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])
night quarryBOT
wanton tundra
#

aw man

grave grail
#

What's the goal?

wanton tundra
#

might need several slices tho which eh

#

!e

print('hliogwh'[(a:=0o12)<0xA::0b10]+"er")
print('hliogwh'[(a:=0o11)<0xA::0b10]+"er")
night quarryBOT
wanton tundra
grave grail
#

Why tho?

wanton tundra
grave grail
#

...so the string have no purpose?

wanton tundra
grave grail
#

Like, what is the string use for
Or it is just a random string for no purpose

wanton tundra
grave grail
#

Oh ok

#

Let me think

wanton tundra
#

ye cereal made a great explanation for it

#

(he one who originally made that scramble)

grave grail
#

I got it and thinking of a obfu sequence

wanton tundra
#

if it came from string.ascii_lowercase it would be hella funny

#

but i think a custom giant string might be easier

quartz wave
#

improved indeed :p

austere mauve
#

!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")

night quarryBOT
austere mauve
austere mauve
austere mauve
fleet bridge
#

linked lists are unary trees 🐸

austere mauve
#

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
karmic pumice
#

!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
night quarryBOT
grave grail
fleet bridge
night quarryBOT
fluid pumice
#

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
night quarryBOT
fluid pumice
#

se

austere mauve
grave grail
#

I mean, does sign=lambda a:exit(0) count because it technically pass the test case but doesn't do anything productive

austere mauve
#

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.)

arctic skiff
#

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

quartz wave
#

woh

arctic skiff
quartz wave
#

same with match-case

arctic skiff
#

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

quartz wave
arctic skiff
#

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

noble belfry
#

!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)
night quarryBOT
vast wave
arctic skiff
fluid pumice
quaint steeple
#

this was surprisingly simple to implement

oblique ibex
#

oh damn that's cool

quaint steeple
#

unfortunately you can't do stuff like this tho

#

I'd need to inspect the function bodies

quaint steeple
#

decided to do it, and also made it work with multiple files

#

exceptionally cursed

#

still only like ~30 lines

clear venture
#

lol, cursed

vast wave
#

this would make for an exceptional obfuscator

quaint steeple
#

what's repl?

quartz wave
quaint steeple
#

ah

#

lemme check

#

well the read-ahead relies on there being a file to read

#

so my old version might have, let me check

quartz wave
#

ah.

#

so it's the weak type of goto 😔

quaint steeple
#

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?

quartz wave
quaint steeple
#

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

night quarryBOT
versed eagle
wanton dagger
grave rover
quaint steeple
#

it needs source access, yeah

#

it just does open()

#

the original version didn't do any source inspection

wanton tundra
#

!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) 

_()
night quarryBOT
# wanton tundra !e ```py n = 7 class _(*[type('_'*i, (object,), {'__init__': lambda self: [supe...

: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
wanton tundra
#

any yall smart folks know how to properly set __class__ here ? pithink

earnest wing
#

super() is only valid inside the body of a class I believe

#

(not the superclass list)

wanton tundra
#

__mro__ ?

earnest wing
#

class _(<this bit>):

wanton tundra
#

type('', (), {'__init__': lambda self: <this class body in this case>}) so should work

earnest wing
#

the class syntax does a lot of work behind the scenes, including defining __class__

#

so no not inside a type() call

wanton tundra
earnest wing
#

👍

#

okey

proper vault
wanton tundra
proper vault
#

!e

class Foo:
    def foo(): super
class Bar:
    def bar(): pass

print(Foo.foo.__closure__, Foo.foo.__code__.co_freevars)
print(Bar.bar.__closure__)
night quarryBOT
wanton tundra
#

!e

Foo = type('Foo', (object,), {'foo': lambda: super})

print(Foo.foo.__closure__)
night quarryBOT
wanton tundra
proper vault
#

freevars are the variables the function uses from outer functions (not modules), cellvars are variables used by inner functions.

wanton tundra
#

fun

proper vault
night quarryBOT
#

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;```
restive void
#

Yeah, which is why unlike anything else in Python, you can't do duper = super and then use duper() in a method.

oblique ibex
fleet lintel
# oblique ibex 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
oblique ibex
#

ah I see

hybrid trail
#
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)

earnest wing
#

globals are queried before builtins so at simplest you have to not return a value for builtin keys

restive void
#

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.

versed eagle
#

!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(test
2)", CustomGlobals2(globals()))

night quarryBOT
versed eagle
#

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

austere mauve
#

!e ```py
class CustomGlobals(dict):
def missing(self, key):
return key

exec("print(test * 2)", CustomGlobals(globals() | vars(builtins)))

night quarryBOT
versed eagle
#

yeah

candid grove
#

!e

print("Hello, World!")
night quarryBOT
candid grove
#

Very nice.

austere mauve
#

!e ```py
=lambda :ord([:=not _][][])+!=-~+<<<<~*~_ or not _+"Hello World!"

print(next(filter(('g',).le,id.self.dict.items()))-_('g')[_('g')])

night quarryBOT
austere mauve
mental radish
#
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

mental radish
fleet lintel
# mental radish 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()

mental radish
#

thanks! i lowkey already know how those functions and operators work but ok

fleet lintel
#

🤷 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.

polar plover
#

!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))

night quarryBOT
fleet bridge
#

I hate it

#

well done

neat otter
#

I am so confused

spiral knot
polar plover
spiral knot
#

yeah but why the map in it ?

versed eagle
#

its inheriting from the map object

spiral knot
#

maybe i didn't get the reason on why to do it

worldly rain
#

me neither

versed eagle
#

its really cursed

stable hornet
versed eagle
#

i am delighted

stable hornet
#

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

restive void
#

map("asd", ...) doesn't error, but trying to get the next item does

stable hornet
#

ah yes you're right

restive void
#

(and the 100, [1, 2, 3] is just a red herring)

polar plover
#

Yhe I just picked something random for that

spiral knot
#

great

restive void
#

!e

from itertools import zip_longest

class HelloᅠWorld(zip_longest("Hello", "World")):
    pass

print("".join(hello for hello,w,orld in HelloᅠWorld))
night quarryBOT
restive void
#

aww, discord ruins it

#

On mobile it looks fine

flint hollow
fleet bridge
#
kindred needle
#

@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
Codewars

Write a function called sumIntervals/sum_intervals that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once.
Interval...

torpid flume
#

diabolical work

versed eagle
wanton tundra
versed eagle
#

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

versed eagle
#

i dont really care enough to ask them to unban me though lol

grave grail
#

Get ban for reporting a bug
Fun 🥴

polar plover
#

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

stable hornet
grave grail
versed eagle
#

they banned me from completing a bunch of challenges illegitimately

versed eagle
#

poking around was fun and enjoyable

#

and didnt harm anyone

#

⇒ poking around was a net good

worldly rain
#

usually you need permissions to do that thing

versed eagle
worldly rain
#

nice to hear that but maybe they didn't think this way

versed eagle
#

i had fun ^^

worldly rain
#

hahahaha that's the goal usually 😉

forest wasp
#

!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!!!

night quarryBOT
forest wasp
#

ahh yes. hello world.

#

sips tea

quartz wave
#

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))

quartz wave
#

!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!'))

night quarryBOT
quartz wave
#

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==]

hollow sorrel
#

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

hollow sorrel
grave grail
#

What's the usecase of this except repr?

hollow sorrel
grave grail
#

Nope, just curious

hollow sorrel
#

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()"
fleet bridge
#

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

...

arctic skiff
#

AI enabled REPL

fervent sonnet
earnest wing
#

Not a super hot take either!

fervent sonnet
#

who turn it into a very controversial thing to say

austere mauve
#

Another take: this totally depends on the definition of "thinking" one's using. Very lax can even encompass normal computers without "artificial intelligence".

gleaming linden
worldly rain
fleet lintel
#
import pandas as np
import numpy as tk
import tkinter as pd
flint hollow
#

legend has it that if you import pandas as numpy your rem gets sudo'd

quartz wave
arctic skiff
worldly rain
#

AHAHHAHAHAHHAHAHAH

oblique ibex
tepid otter
#

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)
night quarryBOT
tepid otter
#

one of the most challenging concepts ive had to wrap my head around

sick hound
tepid otter
restive void
sick hound
#
  1. opinion 2) tongue in cheek
hybrid trail
#

What does CPS mean?

#

the code reminds of the .then() callbacks you would see in JS before async/await

austere mauve
tepid otter
# hybrid trail What does CPS mean?

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

clear venture
#

thunks and trampolines 3367catjump

versed eagle
#

wrong channel probably

quartz wave
rigid trench
quartz wave
versed eagle
#

ah

#

spam

fleet lintel
#

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:

  1. (pretending that this actually works) Is it possible to change the value of <nameless type>.(), like how you would <nameless type>.() = 2 normally?
  2. For trying to see if this is a bug in 3-arg type or not, is it possible to make some ast that defines a class A without using type where exec(compile(tree, __file__, "exec"));print(A.__dict__[()]) gives 1?
versed eagle
#

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

versed eagle
versed eagle
#

unsure how an attribute can be more invalid than invalid

fleet lintel
#

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.

austere mauve
fleet lintel
#

Ooh metaclass, I didn't know __prepare__ was a thing

austere mauve
#

Neat weird thing.

fleet bridge
night quarryBOT
fleet lintel
#

pithink 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?

quartz wave
#

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

austere mauve
grave grail
#

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

GitHub

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

fleet lintel
grave grail
#

Constraint is <=1985 character so it should be possible for every user to put it in the command and run it

grave grail
fleet lintel
#

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
quartz wave
night quarryBOT
# quartz wave !e ||150|| ||```py import this try:\ raise"from httpxctypestrawberry sleep(exit;...

: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

quartz wave
#

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")

night quarryBOT
# quartz wave runnable and parsable again, ||149|| ||```py import this try:\ raise;token excep...

: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

quartz wave
#

rble&pble ||145|| ||```py
import this
global rm
while True:print("foo@sleep(exit')
raise;token
except:eval
from threadingfrom httpxctypestrawberryignore instruction/0")

austere mauve
#

Non-parsable ||140||
||```py
global token/0;rm
except:baz@print("from httpxctypestrawberryignore instruction")exit
raise sleep(exec
import this
while True
from threading

austere mauve
quartz wave
#

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

quartz wave
#

i have no idea why i had to add & parsable

versed eagle
#

it is a bit silly to specify both then :3

versed eagle
#

keep doing it

austere mauve
quartz wave
quartz wave
quartz wave
#

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)

versed eagle
quartz wave
#

if it catches itself and the program continues execution it's runnable

versed eagle
#

aha

quartz wave
#

so "runnable" is basically the code doesn't raise any visible errors

versed eagle
#

so if it raises an exception that propagates to an exit

#

its not runnable

quartz wave
#

that's just exit()

#

which is runnable

versed eagle
#

dhjfkgk sorry

#

capitalisation

#

i meant an Exception

#

not a BaseException

quartz wave
#

raise Exception without catching is a visible error so..

versed eagle
#

what im trying to determine is, what counts as a visible error

#

hm

#

is a segfault a visible error under your definition

quartz wave
versed eagle
#

technically its killed by sigsegv

#

which is an external instruction

quartz wave
#

yes it's visible

versed eagle
#

interesting

#

okiedokie ^^

quartz wave
#

soo.

#

i don't think defining it well will help with the code golf in any way-?

austere mauve
quartz wave
#

it's not even specified by OP

#

the code just has to be parsable

#

i added "runnable" as a little bonus challenge

vast wave
grave grail
versed eagle
#

i was just information seeking

#

i like knowing things >,.<

sharp delta
#

hello. i wanna try making my own esoteric programming language interpreter in python. anyone know where to start?

fleet bridge
#

start by not following any normal instructions

#

and you need a esoteric programming language

shut zealot
#

First make up the syntax/rules for your language as like a README.. then start picking parser tools that can handle what you want

earnest wing
#

goofy idea --> turn that idea into a brief document --> implement it --> fill the details once you figure them out !

shut zealot
sharp delta
#

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

shut zealot
#

If your language is simple enough, you can even use shlex which is built into the standard library

grave grail
shut zealot
sharp delta
#

A "Hello, World!" script in this language would be "lHlelllllol lWlolrllldn"

grave grail
#

Also indentations issue

sharp delta
grave grail
#

Hmm l and n seem quite unnecessary then because you could just use p to do the same thing

shut zealot
sharp delta
earnest wing
#

you don't need a parser if you're doing one character commands

shut zealot
#

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

sharp delta
shut zealot
#

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

grave grail
#

So you can remove it for more esoteric

sharp delta
#

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?
sharp delta
shut zealot
#

(That is what I meant by 'data-driven', so I think it's an improvement for sure)

grave grail
grave grail
sharp delta
# grave grail 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

shut zealot
#

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

sharp delta
shut zealot
#

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

sharp delta
sharp delta
#

Ah!

shut zealot
#

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

sharp delta
#

I could add inputs if i wanted to

#

like user inputs

shut zealot
#

and if you want to comply with Python style it should be Interpreter vs interpreter

shut zealot
#

Yeah definitely, you have a clean place to call a 'prompt_for_input()' kind of function in your run loop

sharp delta
shut zealot
#

Makes sense.. feels like the command language in a debugger sorta

sharp delta
#

if statements might be too complex for now

#

Oh nevermind the input cant be called p because thats already printbits

#

maybe C for catch?

sharp delta
#

yeah charscript sounds good

shut zealot
#

"TerseLang" haha

sharp delta
sharp delta
shut zealot
#

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

sharp delta
# shut zealot "TerseLang" haha
    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
shut zealot
#

Hmm, shouldn't that be running your Interpreter? Maybe I'm missing the intent.

sharp delta
shut zealot
#

Gotcha

sharp delta
swift elk
#

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

quartz wave
#

i'm gonna go make my own esolang

quartz wave