#esoteric-python

1 messages · Page 38 of 1

quartz wave
#

it still has the problem of redundant code (the walruses)

unique heath
#

__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()) is 1

#

int.__add__ is redundant

unique heath
quartz wave
#

i think it might have a problem with evaluating function calls

#

like a safety problem

versed eagle
#

that is undefined behaviour

#

invoking main

quartz wave
#

but it works

versed eagle
#

actually no, im wrong

#

its undefined behaviour in C++

#

not in C

quartz wave
versed eagle
#

my brain did a wrong :3

arctic elm
wheat river
#

i love seeing recursive main

fleet bridge
#

when programming microcontrollers you usually have two "main" functions: setup() and loop()
they work basically like this: ```py
def main():
setup()
while True:
loop()


i wonder what will happen if you call `loop()` inside a `loop()`? will microcontroller ran out call stack space? what will happen then?
wheat river
#

it should run out of memory and crash, i assume

proper vault
#

more elaborate MCUs will error out due to failing memory protection, less elaborate ones will just kind of keep going, breaking everything in the process.

fleet bridge
#

crash
how would that look like? will it just reset itself? or stack pointer will wrap around? what will happen if you execute random garbage? will cpu halt ot reset?

proper vault
fleet bridge
#

ok, so it is either halt or reset

#

or keep going

wheat river
proper vault
wheat river
#

oh

#

now that i think about it, it makes sense for a board of that size to do that instead of just getting rid of the faulty code

proper vault
#

If only some branch of the code will hit the crash, which is the more common case, you don't want to break the entire thing

wheat river
#

yea

fluid pumice
#

!e

a:str="++-+---.++--+-+.++-++--.++-++--.++-++++.+-----".replace('+', '1').replace('-','0').split('.');b:str="+++-+++.++-++++.+++--+-.++-++--.++--+--".replace('+', '1').replace('-','0').split('.')
for i in a: print("{}".format(chr(int(i,++len([200,300])))), end='')
for k in b: print("{}".format(chr(int(k,++len([3,1,2])++--++---1))),end='')
night quarryBOT
#

@fluid pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.

hello world
quartz wave
#

!e ```py
a:str="++-+---.++--+-+.++-++--.++-++--.++-++++.+-----".replace('+1').replace('-0').split('.');b:str="+++-+++.++-++++.+++--+-.++-++--.++--+--".replace('+1').replace('-0').split('.')
for i in a: print("{}".format(chr(int(i,++len([200,300])))), end='')
for k in b: print("{}".format(chr(int(k,++len([3,1,2])++--++---1))),end='')

night quarryBOT
#

@quartz wave :white_check_mark: Your 3.12 eval job has completed with return code 0.

hello world
fluid pumice
#

oh yeah

#

ty

versed eagle
# quartz wave !e ```py a:str="++-+---.++--+-+.++-++--.++-++--.++-++++.+-----".replace(*'+1').r...

"{}".format(...) -> ...

a="++-+---.++--+-+.++-++--.++-++--.++-++++.+-----".replace(*'+1').replace(*'-0').split('.');b="+++-+++.++-++++.+++--+-.++-++--.++--+--".replace(*'+1').replace(*'-0').split('.')
for i in a:print(chr(int(i,2)),end='')
for k in b:print(chr(int(k,2)),end='')

a="...";b="..." -> a="..."

a="++-+---.++--+-+.++-++--.++-++--.++-++++.+-----.+++-+++.++-++++.+++--+-.++-++--.++--+--".replace(*'+1').replace(*'-0').split('.')
for i in a:print(chr(int(i,2)),end='')
fluid pumice
#

!e

a="++-+---.++--+-+.++-++--.++-++--.++-++++.+-----.+++-+++.++-++++.+++--+-.++-++--.++--+--".replace(*'+1').replace(*'-0').split('.')
for i in a:print(chr(int(i,2)),end='')
night quarryBOT
#

@fluid pumice :white_check_mark: Your 3.12 eval job has completed with return code 0.

hello world
fluid pumice
fleet lintel
#

My code isn't bad, I'm just protecting my intellectual property through obfuscation.

main whale
#

How come this task is able to complete, even though it should be free'd first?

import asyncio
import gc

async def print_after_time(text, time):
    await asyncio.sleep(time)
    print(text)

async def task_test():
    asyncio.create_task(print_after_time("task_complete", 2))
    gc.collect()
    await asyncio.sleep(1)
    gc.collect()
    await asyncio.sleep(1)
    gc.collect()
    await asyncio.sleep(1)

asyncio.run(task_test())

According to the create_task docs you need to save a reference to the task: https://docs.python.org/3/library/asyncio-task.html#creating-tasks
Important Save a reference to the result of this function, to avoid a task disappearing mid-execution. The event loop only keeps weak references to tasks. A task that isn’t referenced elsewhere may get garbage collected at any time, even before it’s done. For reliable “fire-and-forget” background tasks, gather them in a collection:
Surely, gc.collect() should be freeing the task then, and we should never get to see the text?

#

is there something wrong with my code to test this, or does this mean that it's actually safe to fire and forget tasks without saving my own references to them?

sick hound
#

!e print("hello world")

night quarryBOT
#

@sick hound :white_check_mark: Your 3.12 eval job has completed with return code 0.

hello world
fleet bridge
#

very esoteric 👍

craggy ruin
night quarryBOT
#
Missing required argument

code

craggy ruin
unique heath
unique heath
craggy ruin
night quarryBOT
#

@craggy ruin :white_check_mark: Your 3.12 eval job has completed with return code 0.

!
craggy ruin
unique heath
#

ehehehehe

#

!e

__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),____:=_.__add__(_),___:=____.__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__add__(_).__lshift__(___.__add__(_)).__sub__(___.__add__(_).__add__(_))))().__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(____))),[__.__sub__(____.__lshift__(___).__add__(____.__lshift__(____))), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(___),_______,_______.__sub__(___.__lshift__(_)), __.__sub__(___.__add__(_).__mul__(___.__add__(___).__add__(_)))]))).__getitem__(_.__sub__(____)))```
night quarryBOT
#

@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

hello world
unique heath
craggy ruin
#

you need to have a capital h, comma, and exclamation mark for it to be legit

unique heath
#

i cant add it without going past the discord limit

#

and if i do

#

it makes it worse

#

instantly

#

damages my reputation

#

!e ```py
(:=builtins.dir().len(),builtins.getattribute(builtins.dir().getitem(.floordiv(.floordiv(name.dir().len()).add(.floordiv(name.dir().len()).add(.floordiv(name.dir().len()).add(.floordiv(name.dir().len()))))).add(.floordiv(name.dir().len())).add(.floordiv(name.dir().len())).add(.floordiv(name.dir().len()))))).getitem(builtins.dir().len().floordiv(name.dir().len()))((:=.floordiv(name.dir().len()),__:=.add().lshift(.add().add().lshift()),:=.add(),:=.add(),:=.sub(.add().add().lshift(.add())),:=__.sub(.add().lshift().sub(.add())),builtins.getattribute(builtins.dir().getitem(.add().add().lshift(.add()).sub(.add().add())))().getattribute(name.dir().getitem(.lshift()))(builtins.getattribute(builtins.dir().getitem(.add().lshift(.add()).add(.add())))(builtins.getattribute(builtins.dir().getitem(.floordiv(name.dir().len()).lshift(.lshift(.add())).sub())),[.lshift(.lshift()).add(.lshift()), .sub(.add().lshift()).add(), _____, _____,.sub(),.lshift(.add().add()).add(.lshift(.add())),.add().lshift(),.sub(.lshift()).sub(), .sub(),,.sub(.lshift()), .sub(.add().mul(.add().add())),.lshift(.add().add()).add()]))).getitem(.sub(___)))

night quarryBOT
#

@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

Hello, world!
unique heath
#

happy?

#

@craggy ruin

craggy ruin
#

good

clear hatch
#

`import random

blocklist = ["left", "not left"]
number_of_blocks = int(input("How many swipes? "))

for _ in range(number_of_blocks):
print(random.choice(blocklist))`

#

do you like my code

bright valve
finite blaze
unreal echo
#

What

versed eagle
#

also, wrong channel

unique heath
#

im clinically insane

night quarryBOT
#

@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.

hello world
versed eagle
#

if u know how it works then ping me and ill give u a cookie :3
(but say it in spoilers so other people also get to try to figure it out)

rugged sparrow
versed eagle
#

here's a cookie 🍪

rugged sparrow
#

haha, yea frame trickery is fun, i've used it for some really cursed stuff. Thanks for the cookie

unique heath
#

i dont get frames

craggy ruin
#

Yeah i wish there was a way to learn things. too bad there isn't

unique heath
#

!e py (_______:=__builtins__.__dir__().__len__(),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(_______.__floordiv__(_______.__floordiv__(__name__.__dir__().__len__()).__add__(_______.__floordiv__(__name__.__dir__().__len__()).__add__(_______.__floordiv__(__name__.__dir__().__len__()).__add__(_______.__floordiv__(__name__.__dir__().__len__()))))).__add__(_______.__floordiv__(__name__.__dir__().__len__())).__add__(_______.__floordiv__(__name__.__dir__().__len__())).__add__(_______.__floordiv__(__name__.__dir__().__len__()))))).__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))((_:=_______.__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),____:=_.__add__(_),___:=____.__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__add__(_).__lshift__(___.__add__(_)).__sub__(___.__add__(_).__add__(_))))().__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(_______.__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(____))),[_.__lshift__(___.__lshift__(_)).__add__(_.__lshift__(___)), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__lshift__(___.__add__(_).__add__(_)).__add__(___.__lshift__(_.__add__(_))),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(___),_______,_______.__sub__(___.__lshift__(_)), __.__sub__(___.__add__(_).__mul__(___.__add__(___).__add__(_))),_.__lshift__(___.__add__(_).__add__(_)).__add__(_)]))).__getitem__(_.__sub__(____)))

night quarryBOT
#

@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

Hello, world!
unique heath
#

@brittle olive

brittle olive
#

can u make a cross compiler that converts brainfuck code into this mess?

brittle olive
#

pretty weak to say no as an intermediate person

unique heath
brittle olive
#

whats that?

unique heath
#

new side project acquired

brittle olive
#

oh

#

ic

#

so, they all are dunder mess too?

unique heath
#

ill work on it later

unique heath
night quarryBOT
#
Huh? No.

Sorry, you can only do that in #bot-commands!

unique heath
#

fuc-

quartz wave
night quarryBOT
#
Nope.

Sorry, you can only do that in #bot-commands!

quartz wave
#

oh

#

i can't read

#

anyway

unique heath
brittle olive
unique heath
#

this is a certified uiasghiuagtiuahiojoih moment

#

SyntaxError: unmatched ')'
._.

bright valve
unique heath
bright valve
#

naming stuff _ is just to make things worse right?

unique heath
#

yeah

bright valve
#

oh shit

unique heath
#

only works with +, >, <, and -

bright valve
#

stupy lol

unique heath
#

how to use:
1: copy paste that in
2: before the code, add your brainfuck code with a variable bf

unique heath
#

so everything except for loops basically

bright valve
#

what about stupy to brainfuck

unique heath
#

no

#

:)

bright valve
#

haha

turbid dragon
#

Does anyone know how to fishook the elipsis?

#

!e

import fishhook

@fishhook.cls(...)
def __add__(a, b):
    return b

print(... + 2)
night quarryBOT
#

@turbid dragon :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 3, in <module>
003 |     @fishhook.cls(...)
004 |      ^^^^^^^^^^^^
005 | AttributeError: module 'fishhook' has no attribute 'cls'
turbid dragon
#

!e

import fishhook

@fishhook.hook(...)
def __add__(a, b):
    return b

print(... + 2)
night quarryBOT
#

@turbid dragon :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 3, in <module>
003 |     @fishhook.hook(...)
004 |      ^^^^^^^^^^^^^^^^^^
005 |   File "/snekbox/user_base/lib/python3.12/site-packages/fishhook/fishhook.py", line 322, in wrapper
006 |     orig_val = vars(cls).get(name, NULL)
007 |                ^^^^^^^^^
008 | TypeError: vars() argument must have __dict__ attribute
turbid dragon
#

Whereas int works

#

Same happens when I do Ellipsis btw

rugged sparrow
#

!e ```py
import fishhook

@fishhook.hook(type(...))
def add(a, b):
return b

print(... + 2)```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.

2
rugged sparrow
turbid dragon
#

Damn

#

Thanks

versed eagle
#

both are turing complete and both languages are machine-parseable

versed eagle
unique heath
versed eagle
#

wdym

unique heath
#

python has like 1490823408139081 functions/operators adn siht

versed eagle
#

you dont have to though

unique heath
#

brainfuk has like 6

versed eagle
#

the goal was to make a converter of bf to python

#

not the other way around

#

silly goose

fleet bridge
#

doable

#

it even will be pretty short

versed eagle
#

im a bit (almost 5 months) late but i have an idea for cpython
a switch/case for integers which compiles to a jump table in the bytecode
basically, switch/case from c but in python :3

#

idk how much work that would be so feel free to ignore me if it would be a lot of work
but it would be cool if implemented

versed eagle
unique heath
versed eagle
fleet bridge
#

!e not space-optimized at all ```py
def bf2py(s: str, memsize: int = 2**15) -> str:
i = 0
r = []
a = lambda s:r.extend([i*' '+s])
a('i=0')
a(f'm=[0]*{memsize}')
for c in s:
match c:
case'>':a('i+=1')
case'<':a('i-=1')
case'+':a('m[i]+=1')
case'-':a('m[i]-=1')
case'.':a('print(end=chr(m[i]))')
case',':a('m[i]=ord(import("sys").stdin.read(1))')
case'[':a('while m[i]:');i+=1
case']':i-=1
case _:...
return '\n'.join(r)

helloworld = '''

from wikipedia

++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++
.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.
------.--------.>+.>.
'''
exec(bf2py(helloworld))

night quarryBOT
#

@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.

Hello World!
fleet bridge
#

!e this one supports cell wrapping, so it can successfully run all hello-worlds from esolangs: ```py
def bf2py(
s: str,
memsize: int = 2**15,
# if not zero, allows wrapping: (maxval-1)+1 will wrap back to 0
# otherwise cell will contain integers of any sign and size
maxval: int = 0,
) -> str:
i = 0
r = []
a = lambda s:r.extend([i*' '4+s])
a('i=0')
a(f'm=[0]
{memsize}')
for c in s:
match c:
case'>':a('i+=1')
case'<':a('i-=1')
case'+':a('m[i]+=1'+f';m[i]%={maxval}'(maxval!=0))
case'-':a('m[i]-=1'+f';m[i]%={maxval}'
(maxval!=0))
case'.':a('print(end=chr(m[i]))')
case',':a('m[i]=ord(import("sys").stdin.read(1))')
case'[':a('while m[i]:');i+=1
case']':i-=1
case _:...
return '\n'.join(r)

helloworld = '''
+[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++[.>]<<<<.+++.------.<<-.>>>>+.
'''

print(bf2py(helloworld, maxval=256))
exec(bf2py(helloworld, maxval=256))

night quarryBOT
#

@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | i=0
002 | m=[0]*32768
003 | m[i]+=1;m[i]%=256
004 | while m[i]:
005 |     m[i]-=1;m[i]%=256
006 |     m[i]-=1;m[i]%=256
007 |     i+=1
008 |     m[i]-=1;m[i]%=256
009 |     while m[i]:
010 |         i+=1
011 |         i+=1
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/E3H4EMKAP7GLN2OCFXCZYZA4GQ

fleet bridge
#

it is funny, but if cells are bounded, it doesnt really matter if they can hold negative numbers or not, because the only check that bf can do is to check if number is a zero, and in all situations signed and unsigned cells behave exactly the same (the only exception is . which will fail on negative inputs)

#

also, memory pointer wrapping is available for free, python does it on lists by default

versed eagle
#

also __import__("sys").stdin

fleet bridge
#

yeah, there is a lot

versed eagle
#

minor nitpicky optimisations that are negligible except for with very large programs

def bf2py(
    s: str,
    memsize: int = 2**15,
    # if not zero, allows wrapping: (maxval-1)+1 will wrap back to 0
    # otherwise cell will contain integers of any sign and size
    maxval: int = 0,
) -> str:
    i = 0
    r = [
        'i=0',
        f'm=[0]*{memsize}',
        'C=__import__("sys").stdin.read' # precomputed
    ]
    a = lambda s:r.extend([i*' '*4+s])
    f = f';m[i]%={maxval}' * (maxval != 0)
    P = f'm[i]+=1{f}'  # these are precomputed now
    M = f'm[i]-=1{f}'  # these are precomputed now
    for c in s:
        match c:
            case'>':a('i+=1')
            case'<':a('i-=1')
            case'+':a(P)
            case'-':a(M)
            case'.':a('print(end=chr(m[i]))')
            case',':a('m[i]=ord(C(1))')
            case'[':a('while m[i]:');i+=1
            case']':i-=1
            case _:...
    return '\n'.join(r)
fleet bridge
#

next goal is to make optimizer for this

versed eagle
#

sequences of + and - can be folded

#

so can sequences of > and <

#

sequences of , can be slightly optimised by only ever storing the last input

fleet bridge
#

actially there is a lot more things you can do

versed eagle
versed eagle
#

im just writing what appears in my mind as it appears

fleet bridge
#

[+] or [-] is a common way to do m[i]=0

versed eagle
#

mhm

#

expressions that result in constant values can be optimised

fleet bridge
#

[A][B] is just [A], it is used to make a comment that uses brainfuck special characters

versed eagle
#

you could also do similar for a copier

versed eagle
unique heath
#

how do you obfuscate that

versed eagle
unique heath
#

also case']':i-=1 ] doesnt actually subrtact anything

versed eagle
#

that is correct
it doesn't subtract anything

#

that is how bf works..

unique heath
#

wahts the i-=1 tehen

versed eagle
#

that function is not executing bf

#

it is generating python from bf

#

(hence the name bf2py)

versed eagle
# unique heath wahts the i-=1 tehen

im guessing the i stands for indentation level (since that's how it's used), but you'd have to ask @fleet bridge since they're the one who made it

fleet bridge
#

correct

versed eagle
#

well, there you go then glasstile

versed eagle
#

since match/case doesn't make a jump table i figured it'd be an interesting idea

unique heath
quartz wave
unique heath
#

and add simd instructions

versed eagle
unique heath
versed eagle
#

thats for the python api

#

which is a different thing

#

you silly goose

unique heath
#

:O

#

gib

#

okay now make everyone move to this

versed eagle
#

no

#

Codon is not a drop-in replacement for CPython. There are some aspects of Python that are not suitable for static compilation — we don't support these in Codon.

proper vault
#

I mean, that's not really python, that's more a language that looks like python

versed eagle
#

its a subset of python

proper vault
#

Kinda like numba

versed eagle
#

it's python in the same way that rpython is python -- it's a strict subset of python

unique heath
#

big saf

proper vault
#

It's not even a subset, it has new syntax for parallelism etc, says so in the readme

unique heath
#

a supersubset

#

Calling C/C++ from Codon is quite easy with from C import, but Codon can also be called from C/C++ code. To make a Codon function externally visible, simply annotate it with @export:

okay um this is isck

versed eagle
#

there are also features to take advantage of hardware parallelism and other such things

#

a few typing differences

#

etc.

quartz wave
#

how would i make a jump table in the first place

#

oh ok

quartz wave
versed eagle
#

i dont think you would be able to make a jump table at compile time then?
or at the very least, it gets more complicated

#

it'd be cool if you could without significant runtime overhead

quartz wave
#

yeah

#

ok then

fleet bridge
fallen bane
#

Not sure if this is exactly the right channel for it, but...
Is there anywhere in the official python docs where I can find information about how instantiating an object involves calling its type?

Basically I'm trying to show that:

from functools import partial

class Foo:
    def __init__(self, data: str):
        self.data = data

FooBar = partial(Foo, data="bar")

my_foobar = FooBar()
assert my_foobar.data == "bar"

I can obviously experimentally show that this works! And intuitively/experimentally, I know that running Foo(data="bar") is itself equivalent to Foo.__call__(data="bar")... but I'd love something in the docs to point to when I talk about it.
Maybe it's a pure grammar thing?

unique heath
restive void
#

Foo(x) is not equivalent to Foo.__call__(x), but to type(Foo).__call__(Foo, x)

restive void
fallen bane
restive void
sharp moon
# unique heath pls make python compile into machine code pls uwu ty

cpython compiles python code to machine code already, thats how it runs, it just does a lot of this work at the moment that you run the code and not before this.
If you want python code which compiles ahead of time then cython might be worth checking out, there is also ongoing work to make cpython ( important destinction, not to be confused with cython) analyse code during runtime to speed up future execution, known as just in time compilation.

fleet bridge
unique heath
#

technically all code is interpreted

fleet bridge
#

yeah, microcode exists

#

and sometimes there is a nanocode that executes microcode

sharp moon
#

and is that part of the cpython project?

fleet bridge
#

everything eventually is executed by machine code, so saying that doesnt really give a lot of useful information

sharp moon
#

i know about bytecode

#

so in response to that, it does already compile into machine code, see the original comment on how to compile ahead of time

fleet bridge
#

it does already compile into machine code
cpython itself is compiled to machine code, but it is not compiling python code to machine code

sharp moon
#

i dont know where the bounds lie on that, do you?

fleet bridge
#

cpython is a VM for python, wdym

#

it compiles python code to bytecode, then executes bytecode
there is no compilation to machine code happening

sharp moon
#

the instructions must be fed to the cpu at some point, when does this occur?, am i mistaken that machine code is a nescessary step to feed instructions to the cpu. What is generating the op code sequence for the cpu?

fleet bridge
#

interpretation != compilation

sharp moon
#

i know

#

well maybe

fleet bridge
#

cpython is an interpreter, it interprets bytecode instructions, not compiles them

sharp moon
#

ok but how do these insturctions reach the cpu?

fleet bridge
#

cpu it only executing cpython's code, it never gets a chance to execute pure python in any form

fleet bridge
#

looks like you have no idea what "interpreter" means

sharp moon
#

so the python code is translated into instructions for the cpu

fleet bridge
#

it is not

sharp moon
#

yes by cpython like you just said

fleet bridge
#

it is not translating nor compiling bytecode to machine code
it interprets them by itself

sharp moon
#

cpython runs, cpython observes python code, cpython sends instructions to cpu

#

translation

#

words are not so rigid

fleet bridge
#

cpython sends instructions to cpu
nope, cpython is already running on cpu, there is no machine code generation happening at all

sharp moon
#

ok but it is the same thing by a different mechanism, the op code sequence is still sent to the cpu as per the instructions of the python code

fleet bridge
#

every bytecode instruction is already implemented in cpython
cpython just performs them in different order for different python code
cpu executes already compiled machine code that is stored in executable on your hard drive, it just happens that this code contains implementation of bytecode instructions

#

there is nothing that decides which instructions to "send" to cpu
cpu executed code as usual

sharp moon
#

so the bytecode instruction is associated with a piece of c code?

fleet bridge
#

of course

#

otherwise how would it be executed

sharp moon
sharp moon
fleet bridge
#

there is only one way to get a cpu to do something: point it to some machine code
there is no JIT happening in cpython (yet), so the only source of machine code is compiled executable binary

sharp moon
fleet bridge
#

any jit is not a part of cpython (yet), so it is not really related to the dicsussion

sharp moon
#

you are being un nice, i appreciate discussion about how cpython works

vast wave
#

cpython does not translate python code into executable code for the cpu, it does things itself based on what the python code looks like

#

an analogy: the python code is the ikea manual for building something. the cpython interpreter doesnt make the manual build it itself, it builds the thing based on the manual

wise notch
#

not sure if this is the right place to ask. how do i access a class through the class's methods? something like this

def decorator(f):
    print(f.__class__.bar)
    def wrapper(*args, **kwargs):
        return f(*args, **kwargs)
    return wrapper

class Foo:
    bar = "baz"

    @staticmethod
    @decorator
    def asd():
        pass
proper vault
#

At the point that decorator is called, the class doesn't exist

#

so you really don't get to

#

You can get at it in the wrapper if it were a (class)method

#

but the class is only created after the class block exits

proper vault
turbid dragon
#

!e

[(_x_B:=lambda A____,_B:(z:=(complex.__call__(*[9,2])-3j)).real%4),(AAAAA:=lambda __,_:(~int(_x_B(__,_)))),(GGENN:=lambda *a:-1)]
@eval('__import__((CC:="fishhook")).hook.cls(type(eval("[None,...][1]")))')
class ZZZ_:__sub__ = AAAAA;__mod__=lambda *a:-1;__add__ = _x_B;__mul__ = _x_B;__truediv__ = lambda *A:1j;__gt__=lambda *_:0;imag=None;__matmul__=lambda xX,Xx:3+3-3;__xor__=lambda Zz,zZ:int(False)>True;__ge__=GGENN;


def p(*x:__import__("typing").Any,_={}):
  [*(__UU9:=list(),f:=lambda m:[a is Ellipsis or a>=1 for a in m])]
  for e,z in (ne:=enumerate)(x):
    if(z.imag or z>2):__UU9=[*__UU9,f(list(x[(tt:=len(sum(__UU9,start=[])))+len(list(filter(bool,__UU9))) if(__UU9)else 0:e])),*list(filter(lambda m:isinstance(m,list),[None if not(not z.imag and z>2)else[]]))]
  [(YZ_A:=[[]]),(CC_:="ETIANMSURWDKGOHVF L PJBXCYZQ")]
  for LLZZ_ in __UU9:
    YZ_A.append([])
    if(LLZZ_ ==[]):continue
    [(p:=0),YZ_A.pop()]
    for zxb in(LLZZ_ ):p=2*p+(1 if zxb is False else 0)
    YZ_A[-1].append(CC_[(2**(len(LLZZ_ ))-1+p)-1])
  return(' ' .join([''.join(__) for __ in YZ_A]))
    
    
print(p(...,...,...*...,...==...,.../...,...,.../...,...,...-...,...+...,...+...,.../...,...,...-...,...+...,...+...,.../...,...-...,...-...,...-...,...@...,...*...,...-...,...-...,.../...,...!=...,...<=...,...%...,.../...,...,...-...,...,.../...,...,...-...,...+...,...+...,.../...,...-...,...,...*...,.../...))
night quarryBOT
#

@turbid dragon :white_check_mark: Your 3.12 eval job has completed with return code 0.

HELLO WORLD
turbid dragon
#

Would you guys have any ideas on how I can obfuscate the constant ETIANMSURWDKGOHVF L PJBXCYZQ?

#

So far I've managed to make the first 9 chars 3 quadratic sequences lol

#

Does anyone recognise ETIANMSURWDKGOHVF L PJBXCYZQ?

sharp moon
vast wave
#

it has "executed" the python code, yes

#

it didnt transpile it to code the cpu can understand

#

both have the same outcome, but they arrive there in different ways

sharp moon
#

ok that is now where i started stating about how it is more of a linguistic difference

vast wave
#

its... not

sharp moon
#

i understand that there isnt a singular data representation of the python code as a sequence of instructions

#

it.... is

vast wave
#

transpiling to cpu code != interpreting the code yourself

arctic skiff
vast wave
#

OPEN CHALLENGE FOR PYCORD:
what does False == False in [False] evaluate to

proper vault
#

||False == False and False in [False], so True overall||

vast wave
proper vault
#

Yup

sharp moon
fleet bridge
#

at least i hope so

turbid dragon
versed eagle
vast wave
#

and i wrote a whole ass assembler for this language

#

also, "feature"

#

it for sure is not a good one

turbid dragon
#

Is there a way to create a class of fishhook.hook.cls without having to use the decorator

#

!e

[(_x_B:=lambda A____,_B:(z:=(complex.__call__(*[9,2])-3j)).real%4),(AAAAA:=lambda __,_:(~int(_x_B(__,_)))),(GGENN:=lambda *a:-1)]
@eval('__import__((CC:="fishhook")).hook.cls(type(eval("[None,...][1]")))')
class ZZZ_:__sub__ = AAAAA;__mod__=lambda *a:-1;__add__ = _x_B;__mul__ = _x_B;__truediv__ = lambda *A:1j;__gt__=lambda *_:0;imag=None;__matmul__=lambda xX,Xx:3+3-3;__xor__=lambda Zz,zZ:int(False)>True;__ge__=GGENN;


def p(*x:__import__("typing").Any,_={}):
  [*(__UU9:=list(),f:=lambda m:[a is Ellipsis or a>=1 for a in m])]
  for e,z in (ne:=enumerate)(x):
    if(z.imag or z>2):__UU9=[*__UU9,f(list(x[(tt:=len(sum(__UU9,start=[])))+len(list(filter(bool,__UU9))) if(__UU9)else 0:e])),*list(filter(lambda m:isinstance(m,list),[None if not(not z.imag and z>2)else[]]))]
  [(YZ_A:=[[]]),(CC_:="ETIANMSURWDKGOHVF L PJBXCYZQ")]
  for LLZZ_ in __UU9:
    YZ_A.append([])
    if(LLZZ_ ==[]):continue
    [(p:=0),YZ_A.pop()]
    for zxb in(LLZZ_ ):p=2*p+(1 if zxb is False else 0)
    YZ_A[-1].append(CC_[(2**(len(LLZZ_ ))-1+p)-1])
  return(' ' .join([''.join(__) for __ in YZ_A]))
    
    
print(p(...,...,...*...,...==...,.../...,...,.../...,...,...-...,...+...,...+...,.../...,...,...-...,...+...,...+...,.../...,...-...,...-...,...-...,...@...,...*...,...-...,...-...,.../...,...!=...,...<=...,...%...,.../...,...,...-...,...,.../...,...,...-...,...+...,...+...,.../...,...-...,...,...*...,.../...))
night quarryBOT
#

@turbid dragon :white_check_mark: Your 3.12 eval job has completed with return code 0.

HELLO WORLD
turbid dragon
#

I don't want @eval('__import__((CC:="fishhook")).hook.cls(type(eval("[None,...][1]")))') so obvious

#

Some sort of x = type(...) perhaps

fleet bridge
#
@deco
class X: ...
# same as:
deco(X)
#

!d type

night quarryBOT
#

class type(object)``````py

class type(name, bases, dict, **kwds)```
With one argument, return the type of an *object*. The return value is a type object and generally the same object as returned by [`object.__class__`](https://docs.python.org/3/library/stdtypes.html#instance.__class__).

The [`isinstance()`](https://docs.python.org/3/library/functions.html#isinstance) built-in function is recommended for testing the type of an object, because it takes subclasses into account.
turbid dragon
#

Awesome, thanks

#

!e

import fishhook

class ABC:
    def __add__(self, z): return 10
fishhook.hook.cls(ABC, type(...))

print(... + ...)
night quarryBOT
#

@turbid dragon :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 7, in <module>
003 |     print(... + ...)
004 |           ~~~~^~~~~
005 | TypeError: unsupported operand type(s) for +: 'ellipsis' and 'ellipsis'
turbid dragon
#

!e

import fishhook

@fishhook.hook.cls(type(...))
class ABC:
    def __add__(self, z): return 10

print(... + ...)
night quarryBOT
#

@turbid dragon :white_check_mark: Your 3.12 eval job has completed with return code 0.

10
vast wave
#

the method you call in the decorator returns a method python invokes with the class

#

!e ```py
import fishhook

class ABC:
def add(self, z): return 10
fishhook.hook.cls(type(...))(ABC)

print(... + ...)

night quarryBOT
#

@vast wave :white_check_mark: Your 3.12 eval job has completed with return code 0.

10
vast wave
#

yeah

sharp moon
quartz wave
#

it doesn't convert python to machine code (yet)

torn agate
#

What better place to check if a syntax highlighter works than at #esoteric-python

torn agate
#

Mine probably does

#

Hit me with all you got

quartz wave
# torn agate ### ✅

using the same color for keywords, functions, and the decorator at (@...) symbol is a bit unsettling

#

although i thought classes were supposed to have a color

torn agate
#

same color for keywords and functions?

quartz wave
#

if, return

torn agate
quartz wave
torn agate
quartz wave
#

yep

torn agate
#

so they have the same color

quartz wave
#

how come they're not purple

torn agate
#

wait where

quartz wave
#

is it because the \w+\( match does a false positive

quartz wave
torn agate
#

oh wtf

#

mb brb

quartz wave
#

cool

torn agate
#

as for @ usually vsc highlights that too, but in a different color imo it looks cool to have the same color

#

but logically it is indeed kinda wrong

sharp moon
turbid dragon
#

I havent finished it yet

versed eagle
frail token
#

For real obfuscation, define aliases for all builtin identifiers and string literals with sequences of "_" and "{MIDDLE DOT}" (Unicode MIDDLE DOT is a legitimate identifier body character). Like:

>>> _·, _··, _··· = list, range, enumerate
>>> _·(_···(_··(5),1))
[(1, 0), (2, 1), (3, 2), (4, 3), (5, 4)]

Can only do identifiers though, not keywords.

vast wave
frail token
#

It turns out that MIDDLE DOT is a low number, 00b7, so you are barely pushing the Unicode envelope. But yes, adding Unicode to the mix, 𝐭𝕙𝕖 𝒔ₖ𝖞 is 𝙩𝗵𝚎 𝖑iⅿ𝖎𝗍.

vast wave
#

i forgot the exact characters but they exist

#

most tooling has no idea this works, and pycharm for example will scream and shit and piss about (certain wonky character for w)xy not existing

frail token
earnest wing
# frail token It turns out that MIDDLE DOT is a low number, 00b7, so you are barely pushing th...

i'll tell you a little cursed secret Emoji_Evil
since middle dot (among some other chars like ó and μ and ñ etc) is part of the latin-1 alphabet,
and since these chars are valid identifier continuation letters,
and since most file browsers expect python source files to be utf-8,
and since using the # coding: unicode-escape defaults to latin-1 with extra escapes for unicode characters,
and since python can introspect variable names,

you can write a python source file that looks like it executes a certain program when rendered in utf-8, but actually executes a different program that you can only see in latin-1

:3

#

as an example:

# coding: unicode-escape
class : pass
print(鷵) # <class '__main__.é·μ'>
# now what's that class name?!
#

you can do a lot of very sneaky business, although it all falls apart by looking at the coding declaration

sick hound
#

the underscore gives it away a bit shame it cant just be the unicode sym

fleet bridge
#
  1. ruff error message
  2. pyright on-hover information window
muted scaffold
#

Hi, what's esoteric pythonb

unique heath
long fulcrum
#

possible to make this any shorter?

o=[]
x=5000**2
s=[1]*x```
quartz wave
#

nvm wait

#

i don't think you can

#
x=5000**2;*o,s=[1]*x,
``` this maybe
long fulcrum
#

yep that works

#

ty

#

i can never get my head around how golfing assignments works

long fulcrum
#

why do 1 and 2 produce the same output but 3 fucks up

if all(i<j for i,j in zip(str(p),str(p)[1:])):print(p)
all(i<j for i,j in zip(str(p),str(p)[1:]))and 1 and print(p)
1*all(i<j for i,j in zip(str(p),str(p)[1:]))or print(p)```
#

these are the conditions ik they have to meet for 2 and 3 to work but i cant see any side effects that are caused by 3

gleaming linden
#

all(...)or print(p) would be if not all(...): print(p)

long fulcrum
muted scaffold
#

what would be the best way to hide

__builtins__.__dict__["getattr"](
    __builtins__,
    "eval"
)
long fulcrum
#

this should do the same thing

exec(bytes('彟畢汩楴獮彟弮摟捩彴孟朢瑥瑡牴崢弨扟極瑬湩彳ⱟ∠癥污⤢','u16')[2:])```
muted scaffold
#

I was

#

trying to hide print this way

#

Oh Ican't upload files

#

!upload

muted scaffold
#

not efficient but

#

¯_(ツ)_/¯

#

althought I forgot to hide print and the string lol

#

Why does this return True, True

a, b = (lambda x: (x, x))(all(i for i in range(-int(),int(int().__sub__(~int())**(~int())*-~int()), ~-int())))

and this False, False

a, b = (lambda x: (x, x))(all(i for i in range(-int(),int(int().__sub__(~int())**(~int())*-~int()), -~int())))
low lynx
#
all(i for i in range(-int(),int(int().__sub__(~int())**(~int())*-~int()), ~-int()))
all(i for i in range(0,int(0 .__sub__(~0)**(~0)*-~0), ~-0))
all(i for i in range(0,int(0 .__sub__(-1)**(-1)*1), -1))
all(i for i in range(0,int(1**(-1)), -1))
all(i for i in range(0,1,-1))
all([])
True

and then the lambda x: (x, x) just turns that into (True, True)
for the False, False one, it has -~int() instead of ~-int() for the step size, which is 1 and not -1, so we get all([0]) instead of all(), which is False

dense mural
#

1+1 or -~1? 😶‍🌫️

muted scaffold
#

no need for 1+1

dense mural
#

-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~True Brrr 🤣
But Srsly Performence Wise Which Is Better? 1+1 -> 1 Opration And -~1 -> 2? 😶‍🌫️

dense mural
#

@muted scaffold Do You Play CTFs? Python Jail Escapes Specifically

quartz wave
#

they both optimize to the same thing anyway since they're both constants

dense mural
#

So Like n % 2 And n & 1?

quartz wave
#

unless n is a constant too

muted scaffold
muted scaffold
dense mural
quartz wave
muted scaffold
#

@quartz wave

uneven flame
#

hello i made a thing with ipython and pygame that idk if makes sense

quartz wave
muted scaffold
quartz wave
muted scaffold
#

Sorry

quartz wave
unique heath
#

to ur mom

muted scaffold
#

Sorry

unique heath
#

why would you report cereal

#

out of all peole

muted scaffold
#

I have no reason

unique heath
#

i see

muted scaffold
#

I'm so sorry

#

@unique heath show me some esoteric python code

quartz wave
#

it's ok i guess

unique heath
# muted scaffold <@670274727088095244> show me some esoteric python code

!e py __builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),____:=_.__add__(_),___:=____.__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__add__(_).__lshift__(___.__add__(_)).__sub__(___.__add__(_).__add__(_))))().__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(____))),[__.__sub__(____.__lshift__(___).__add__(____.__lshift__(____))), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(___),_______,_______.__sub__(___.__lshift__(_)), __.__sub__(___.__add__(_).__mul__(___.__add__(___).__add__(_)))]))).__getitem__(_.__sub__(____)))

night quarryBOT
#

@unique heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

hello world
muted scaffold
quartz wave
#

thanks

muted scaffold
quartz wave
#

u too /p

unique heath
muted scaffold
muted scaffold
muted scaffold
muted scaffold
unique heath
unique heath
muted scaffold
#

And exec -> print results in seeing the content

#

!e py print(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),____:=_.__add__(_),___:=____.__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__add__(_).__lshift__(___.__add__(_)).__sub__(___.__add__(_).__add__(_))))().__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(____))),[__.__sub__(____.__lshift__(___).__add__(____.__lshift__(____))), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(___),_______,_______.__sub__(___.__lshift__(_)), __.__sub__(___.__add__(_).__mul__(___.__add__(___).__add__(_)))]))).__getitem__(_.__sub__(____))))

night quarryBOT
#

@muted scaffold :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | hello world
002 | None
unique heath
#

what

muted scaffold
#

🙂✌🏻

quartz wave
muted scaffold
#

what's platonic tone tag

quartz wave
#

equivalent of "as a friend"

muted scaffold
#

🥺

unique heath
#

that means he loves you platonically

muted scaffold
#

Awesome

unique heath
#

internetters discovering the randomest words ever and making it a tone indicator

muted scaffold
#

Well

quartz wave
muted scaffold
#

Yes

muted scaffold
unique heath
muted scaffold
#

My code

unique heath
#

send

muted scaffold
#

I'm not home

#

At school

quartz wave
muted scaffold
#

hi

muted scaffold
unreal echo
#

!timeit
print(builtins.getattribute(builtins.dir().getitem(builtins.dir().len().floordiv(builtins.dir().len().floordiv(name.dir().len()).add(builtins.dir().len().floordiv(name.dir().len()).add(builtins.dir().len().floordiv(name.dir().len()).add(builtins.dir().len().floordiv(name.dir().len()))))).add(builtins.dir().len().floordiv(name.dir().len())).add(builtins.dir().len().floordiv(name.dir().len())).add(builtins.dir().len().floordiv(name.dir().len()))))((:=builtins.dir().len().floordiv(name.dir().len()),__:=.add().lshift(.add().add().lshift()),:=.add(),:=.add(),:=.sub(.add().add().lshift(.add())),:=__.sub(.add().lshift().sub(.add())),builtins.getattribute(builtins.dir().getitem(.add().add().lshift(.add()).sub(.add().add())))().getattribute(name.dir().getitem(.lshift()))(builtins.getattribute(builtins.dir().getitem(.add().lshift(.add()).add(.add())))(builtins.getattribute(builtins.dir().getitem(builtins.dir().len().floordiv(name.dir().len()).lshift(.lshift(.add())).sub())),[__.sub(.lshift().add(.lshift())), .sub(.add().lshift()).add(), _____, _____,.sub(),.add().lshift(),.sub(.lshift()).sub(), .sub(),,.sub(.lshift()), .sub(.add().mul(.add().add()))]))).getitem(.sub(____))))

night quarryBOT
#

@unreal echo :white_check_mark: Your 3.12 timeit job has completed with return code 0.

2000 loops, best of 5: 176 usec per loop
unreal echo
#

!timeit
print('hello world')
print(None)

night quarryBOT
#

@unreal echo :white_check_mark: Your 3.12 timeit job has completed with return code 0.

200000 loops, best of 5: 1.78 usec per loop
muted scaffold
unreal echo
#

Make a fast obfuscation of anything, not necessarily an output on console, but maybe an algorithm or computing script.

#

And the obfuscated version should be faster

neon sequoia
unique heath
fleet lintel
unique heath
#

lmao

#

genius

long fulcrum
#

is there a way to make this shorter

r=str(p)
zip(r,r[1:])```
proper vault
#

Walrus in the first argument should save the newline

long fulcrum
#

unfortunately i get this: assignment expression cannot be used in a comprehension iterable expression

#

its in an all()

gleaming linden
#

or maybe : instead of /

rugged sparrow
long fulcrum
long fulcrum
gleaming linden
long fulcrum
#

nope this bit errors
s[p:x:p]=~-x//p*[0]

#

cannot assign to expression

gleaming linden
#

oh yeah its an assignment

long fulcrum
#

i dont think ive ever seen that error before i tried working on this problem

gleaming linden
#

It's like doing 1 + x = 2

#

because expressions can be calculated but not assigned to

proper vault
#

Couldn't you do some kinda sorted(r)==[*r] instead of the all()?

long fulcrum
#

i think thats what i originally tried and then code golfing enthusiast gave me that snippet and it was shorter than i could get with sorted

proper vault
#

Fairs

long fulcrum
#

well not exactly that i did something else

#

ill try that

proper vault
#

Note that if you also want uniqueness that requires a separate condition

#

Which may be what took so many chars

long fulcrum
#

what do you mean by uniqueness?

#

oh yeah if you mean should 112345 work it shouldnt

#

wait what if i use a set instead of a list

#

ah

#

it fails then for 31

#

it doesnt differentiate between ascending and descending

#

crazy thing is the questions possible in 68

#

im on 119

#

and that already seems really low

gleaming linden
long fulcrum
#

bytes

earnest charm
#

Assuming I have an array of substrings that that can be found in a larger string, but do not compose the entirety of the larger string i.e. there are parts of the larger string that cannot be found in the array of substrings, is there a way to split my larger string by using the array of substrings so that instead of having a partial array of substrings, I have an array of all the unique substrings that compose the larger string including the substrings

long fulcrum
#

i think an example might help

unique heath
#
#ifndef __cplusplus
#include<stdio.h>
#else
#include<iostream>
#endif
#define def int
#define main() main() { a
#define return}
#define print puts
def main():
    print("Hello, world!");
    return
#if 0
main()
#endif``` (golfed) hello world that works in py, c, cpp
muted scaffold
#

Oh wow

muted scaffold
#

!e ```py
print((((:=(:=().class.base.subclasses().getitem(((____:=(:=().class.itemsize)).add()).mul(_______:=(:=.sub(:=((),).len().invert().neg()))).add(.add()))).dict).getitem((:=().class(builtins.dict).getitem)(.mul(.add())).add((:=loader.module.getitem(:=().len())).add(builtins.repr().getitem(builtins.dict.getitem((.pow().add(.add(:=.invert().neg()))))(_____,.add(_____))))))(:=__.getitem(().class(loader.dict).getitem(:=.invert().neg().invert())).wrapped(,(_____:=loader.doc.getitem)().add(()).add((:=(:=__.mul(:=.neg()))).add()).add((.sub().mul().add())).getattribute((:=().class(loader.name.class.dict).getitem)())(((:=.add()),)))),).mul((.sub())).add((.getattribute(name.getattribute((.add(.add(.add()))))()),))).getitem(.sub())())

night quarryBOT
#

@muted scaffold :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     print((((__:=(________:=().__class__.__base__.__subclasses__().__getitem__(((____:=(__:=().__class__.__itemsize__)).__add__(__)).__mul__(_______:=(__:=__.__sub__(___:=((),).__len__().__invert__().__neg__()))).__add__(__.__add__(__)))).__dict__).__getitem__((______:=().__class__(__builtins__.__dict__).__getitem__)(___.__mul__(____.__add__(___))).__add__((_________:=__loader__.__module__.__getitem__(_____:=().__len__())).__add__(__builtins__.__repr__().__getitem__(__builtins__.__dict__.__getitem__(______(____.__pow__(___).__add__(____.__add__(_____:=_____.__invert__().__neg__()))))(_____,_______.__add__(_____))))))(__________:=__.__getitem__(().__class__(__loader__.__dict__).__getitem__(_:=_____.__invert__().__neg__().__invert__())).__wrapped__(________,(________:=__loader__.__doc__.__getitem__)(____).__add__(________(_____)).__add__((__:=________(______:=____.__mul__(_:=_.__neg__()))).__
... (truncated - too long)

Full output: https://paste.pythondiscord.com/RNAJZHJAKYWLHQ2BFEOT53ZU5E

muted scaffold
#

That's cool

earnest charm
#

heres the original string:

#

heres the array of substrings

muted scaffold
#

hi

#

@quartz wave

versed eagle
unique heath
#

odam

#
#import<stdio.h>
#define def int
#define main() main(){a
#define return}
#define print puts
def main():print("Hello, world!");return
#if 0
main()
#endif```
#

more golf

versed eagle
crude raft
#

or at least the ) and { together

versed eagle
#

the spacing in the define can be removed

crude raft
unique heath
#

ok fixed

fleet bridge
versed eagle
fleet bridge
#

C++ might get import in the future, but not #import

versed eagle
#

in python it's a comment, in C and C++ it's an invalid preprocessor directive

crude raft
#

well uh, that was g++

versed eagle
#

[module.import]

#

it's a keyword, not a preprocessor directive

versed eagle
#

there's also a version that's a preprocessor directive

crude raft
#

I swear I'd seen it before

crude raft
#

hang on, we do have python

versed eagle
#

#import is a microsoft extension
import directives are preprocessing directives according to the grammar but they don't start with #

unique heath
crude raft
#

is it possible to use define on a number?
#bot-commands message
then we can shorten return to a number literal

earnest charm
crude raft
#

aw man

#

pass could save a few bytes

unique heath
unique heath
#

saves another byte

#
#import<stdio.h>
#define def int
#define main() main(){a
#define abs}
#define print puts
def main():print("Hello, world!");abs
#if 0
main()
#endif``` shaving off a few more bytes
#

i dont really see how more bytes could be shaved

#
#import<stdio.h>
#define def int
#define main() main(){a
#define abs}
def main():puts("Hello, world!");abs
#if 0
puts=print
main()
#endif```less bytes
#

but

wheat river
#

id

#
#import<stdio.h>
#define def int
#define main() main(){a
#define print(x) puts(x);}
def main():print("Hello, world!")

if you only care about printing

#

actually, forgot to call main

#
#import<stdio.h>
#define def int
#define main()main(){a
#define id}
def main():puts("Hello, world!");id
#if 0
puts=print
main()
#endif
crude raft
#

nice!

gleaming linden
#

does this work?```py
#import<stdio.h>
#define def int
#define main() main(){a
#define id}
#define abs
def main():puts("Hello, world!");id
abs//((puts:=print)and main())

wheat river
#
#import<stdio.h>
#define def int
#define main() main(){a
#define id}
def main():puts("Hello, world!");id
#define id
id//((puts:=print)and main())

shaved 1 byte

#

actually 2

gleaming linden
#

there's also a space between main() and main() which I missed

wheat river
#
#import<stdio.h>
#define def int
#define main()main(){a
#define id}
def main():puts("Hello, world!");id
#define id
id//(puts:=print,main())
gleaming linden
#

105```py
#import<stdio.h>
#define id
id//print("Hello, world!")
id//"""
int main(){puts("Hello, world!");}
id//"""

wheat river
#

nice

#

we can probably get rid of return type of main but it will only work in older versions of C

summer echo
#

hi! i want to try and code in the Shakespeare Programming Language, but i'm having some trouble just figuring out the basic setup. if anyone knows how to get shakespearelang working with pycharm, i'd really appreciate the help

fleet bridge
night quarryBOT
#

@fleet bridge :x: Your 3.12 eval job has completed with return code 1.

001 | Hello, world!
002 | Traceback (most recent call last):
003 |   File "/home/main.py", line 3, in <module>
004 |     id//print("Hello, world!")
005 |     ~~^^~~~~~~~~~~~~~~~~~~~~~~
006 | TypeError: unsupported operand type(s) for //: 'builtin_function_or_method' and 'NoneType'
fleet bridge
#

what was supposed to happen

#

oh wait, it did print hello world

#

since hello world specification is not standard, i can accept failing program as correct hello world program

fleet bridge
crude raft
#

108 but no error

#import<stdio.h>
#if 0
print("Hello, world!")
"""
#endif
int main(){puts("Hello, world!");}
#if 0
"""
#endif
fleet bridge
#

make sure to count newlines

crude raft
#

gotcha 👍

#

I should find a better char count on mobile

fleet bridge
#

!e ```py
print(len(open(file,'rb').read().rpartition(b'#####')[-1].strip()))
import os; os._exit(0)

#import<stdio.h>
#if 0
print("Hello, world!")
"""
#endif
int main(){puts("Hello, world!");}
#if 0
"""
#endif

night quarryBOT
#

@fleet bridge :white_check_mark: Your 3.12 eval job has completed with return code 0.

108
fleet bridge
#

you might use this :)
put your code after ##### and run it (it has to be valid python code, otherwise it wont work)

gleaming linden
#

you could also use + instead of // after the print

crude raft
#

84 (with error in python)

#import<stdio.h>
int//print("Hello, world!")+"""
main(){puts("Hello, world!");}//"""
fleet bridge
#

thats cool

#

i have this, but cant make it work in C, i dont see a way to escape )
this is 106 right now, it uses string "Hello, world!" only once ```py
#include<stdio.h>
#define id
id//print(
#define h
"Hello, world!"
)
#define x int main(){puts(h);}//"""
x

#

well, solution was pretty easy: ```py
#include<stdio.h>
#define id
id//print(
#define h
"Hello, world!"
)
#define x int main(){puts(h;}//"""
x

#

still 106

crude raft
#

haha that (h;} looks so cursed

fleet bridge
#

yeah

#

85, no error```py
#include<stdio.h>
#define id(y)int main(){y;}//
puts=print
id(puts("Hello, world!"))

crude raft
#

nice

fleet bridge
#

76, no error```py
#import<stdio.h>
#define print(y)int main(){puts(y);}
print("Hello, world!")

#

this feels so obvious when i look at it

wheat river
#

lmao

muted scaffold
long fulcrum
#

:3c

vast wave
#
#import<stdio.h>
#define print(y)int main(){puts(y);}
#define g<script>alert("Hello, world!")</script>
print("Hello, world!")

mega scuffed html

fleet bridge
#

is <stdio.h> a some sort of weird html tag?

#

i wonder how browser would respond to tags with . in them

vast wave
#

a dot is a valid tag element

#

at least firefox didnt instantly complain

unique heath
crude raft
#

I know right!

quartz wave
#

no error in gcc

unique heath
#

we're using import so why the fuck not

bright valve
quartz wave
bright valve
#

cool

#

i was confused at first because there wasnt a space between print(y) and main()...

vast wave
versed eagle
muted scaffold
#

but you got it boss

versed eagle
#

it's either a GCC extension (and a deprecated one at that) or a microsoft extension, depending on what compiler you use

#

i dont know about clang since ive never used it, but it's probably there also

#

they like to be compatible with gcc

vocal hinge
#

not sure if the type hints are correct but the assertions work xD```py
from typing import Type
TYPE: type = type('TYPE', (type,), {'type': type})
type TYPETYPE = Type[TYPE]
type_: TYPETYPE = TYPE.type
assert TYPE.type == type(TYPE)
assert issubclass(type_, type)

sick hound
#

is there a way to do something like this

class BaseClass:
    val = None

    def __eq__(self, other: object) -> bool:
        return self.val == other

class Test(BaseClass):
    val = 123

if Test == 123:
    print("asd")

Now the snippet above will not work since i'm not initializing anything, but that's the thing i do not want to initialize them...

#

maybe a decorator initializing them?

sick hound
#

go on...

versed eagle
#

!e ```py
class Meta(type):
val = None
def eq(self, other: object) -> bool:
return self.val == other

class Test(metaclass=Meta):
val = 123

if Test == 123:
print("asd")

night quarryBOT
#

@versed eagle :white_check_mark: Your 3.12 eval job has completed with return code 0.

asd
versed eagle
sick hound
#

danke

#

that's really intresting though

#

didn't know such a thing existed

#

yet another part of python uncovered

modest bough
#

@sick hound IIRC there's a great pycon talk by dave beazley (unsurprisingly) about metaclasses

versed eagle
#

whats that

unique heath
#

how do you not know what a dataclass is

versed eagle
#

how would i know what it is

#

ive never seen the word before

unique heath
#

wait no thats not a dataclass

night quarryBOT
#

:incoming_envelope: :ok_hand: applied timeout to @sick hound until <t:1705106214:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).

The <@&831776746206265384> have been alerted for review.

unique heath
#
from dataclasses import dataclass

@dataclass
class Test:
    val: int

    def hi(self):
        print(self.val)


Test(3).hi()  # 3``` its an easier way of making a class with basic `__init__`
#

its also in stdlib

sick steeple
#

@sick hound I don't know what you were doing, but spamming is going to get you muted. I'm letting that stick, don't continue once the mute is up.

versed eagle
#

also, what's the point

unique heath
unique heath
#

quickly remove a hecck ton of boilerplate

#

mcoding has a great video on it

sick hound
#

I have another interesting problem. Say i have a class that is a event dispatcher. I want to both have a decorator function that registers the function below. And i also want a normal function that takes the function as an argument and registers it.

And last of all i want the both register functions to have same names.

How would i solve this?

#

i know that there is some overload function

#

but i don't know about it

sick hound
unique heath
#

like, what you roughly want to do

sick hound
unique heath
#

clang head.c

sick hound
#
class DeviceEventDispatcher:
    def __init__(self, device_path: str) -> None:
        self._device_path = device_path

        self.events = {}

    def register_event(self, event: _types._EventType, callback: Callable[[Event], None]) -> None:
        self.events[event] = callback
    
    @overload
    def register_event(self, event) -> Callable[[], None]:
        def decorator(func: Callable[[Event], None]) -> None:
            self.events[event] = func
#

that is how the event dispatcher class looks like

#

sorry if it's a little messy

#

but i hope it gets the point across

versed eagle
#

why not just use *args?

sick hound
#

i think i'm cooking, i'll reach out again in a min

#

i just imported from typing import overload

#

With this snippet i got the decorator function to work properly and register the function but the other function that is overloaded gives me an error that it needs less arguments

class DeviceEventDispatcher:
    def __init__(self, device_path: str) -> None:
        self._device_path = device_path

        self.events = {}

    @overload
    def register_event(self, event: _types._EventType, callback: Callable[[Event], None]) -> None:
        self.events[event] = callback

    def register_event(self, event: _types._EventType) -> Callable[[], None]:
        
        def decorator(func: Callable[[Event], None]) -> None:
            self.events[event] = func

        return decorator
#

but then yeah i might need to use *args

#

though i might need to to key args then

#

and something with a union too right?

unique heath
#

thats not how overload works

unique heath
sick hound
#

well then i might just be better of doing something with keyword arguments

#

or what you think?

#

or wait

#

i think i undestand

#

btw does this fit in this channel, is this esoteric enough?

#

alright i got it working with a union instead

#

but thanks for helping

sick hound
#

!e

class MyClass:
    def __init__(self, value):
        self.value = value

    def __is__(self, other):
        return True

obj1 = MyClass(42)
obj2 = MyClass(42)
obj3 = MyClass(99)

print(obj1 is obj2)
print(obj1 is obj3)
night quarryBOT
#

@sick hound :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | False
002 | False
sick hound
#

What?

#

my brain has been stuck, why is that not working?

#

everything should be True, right?

astral rover
#

is isnt an operator you can override

sick hound
#

aha

#

thanks

versed eagle
sick hound
#

it's just that i'm comparing a attribute of the classes

#

might be a stupid question

wheat river
#

You could make a Singleton class, but that's kinda cheating

sick hound
#

imma look into it

stark granite
#
from typing import Callable, Never


def try_(
        try_: Callable[[], None],
        except_: BaseException | tuple[BaseException],
        except_callback: Callable[[BaseException], None],
        else_callback: Callable[[], None] = lambda: None,
        finally_callback: Callable[[], None] = lambda: None,
) -> None:
    try:
        try_()
    except except_ as exc:
        except_callback(exc)
    else:
        else_callback()
    finally:
        finally_callback()


def raise_exc(exc: BaseException | None, context: Never | None | BaseException = Never) -> None:
    if exc is not None:
        if context is Never:
            raise exc
        else:
            raise exc from context
    else:
        if context is not Never:
            raise TypeError("caller is drunk")

        raise


def while_loop(condition: Callable[[], bool], callback: Callable[[], None]) -> None:
    while condition():
        callback()


# all of those functions were helpers for this thing; i did try to make into a generator, but i dont think you can really yield from a subsubsublambda which is called from 2 functions deep into a very top level function without insane amount of fuckery (like passing into top lambda a generator and than making that generator yield what it is sent in a while loop with a condition callback and yield from *that* generator)
def zip_madness[*I](*iterables: Iterable[I], strict: bool = False) -> list[tuple[*I]]: return (lambda iters, next_, looping_, accum: (while_loop(lambda: looping_[0], lambda: try_(lambda: (next_.__setitem__(0, tuple(next(iter_) for iter_ in iters)), None)[-1], RuntimeError, lambda _: raise_exc(ValueError("some iterators have exhausted before the others"), None) if strict and len(iters) != len(next_) else looping_.__setitem__(0, False), lambda: (accum.append(next_[0]), next_.__setitem__(0, ())))), accum)[-1])([iter(iterable) for iterable in iterables], [()], [True], [])
stark granite
#

zip's implementation in one line

#

almost zip

#

it returns a list

vast wave
#

"one line"

stark granite
#

well the zip_madness is one line

#

and try_, raise_exc, while_loop are helpers cuz syntax wouldnt allow truly one line otherwise

stark granite
stark granite
quartz wave
vast wave
#

fully typed as well. heresy!

#

typings in the esoteric python channel???

stark granite
stark granite
#

yeah just one note

#

it literally crashes type checker

#

at least pycharm's

#

like if paste that function into some file

#

and then do

a = 1
print(a)

after function's definition

#

it will yell a reference is not defined

stark granite
stark granite
# quartz wave ...today at <#470884583684964352> we're gonna try to turn this horrible multilin...

btw the code is based on

def zip_[*I](*iterables: Iterable[I], strict: bool = False) -> Generator[tuple[*I], None, None]:
    iters = [iter(iterable) for iterable in iterables]
    next_: tuple[*I] | tuple[()] = ()

    while True:
        try:
            next_ = tuple(next(iter_) for iter_ in iters)
        except RuntimeError:
            if strict and len(iters) != len(next_):
                raise ValueError("some iterators have exhausted before the others") from None
            else:
                break
        else:
            yield next_
            next_ = ()
quartz wave
#

alright we just need a mechanism to raise

vast wave
#

are code objects allowed

stark granite
vast wave
#

the use of code objects to do a little trolling

stark granite
# quartz wave alright we just need a mechanism to `raise`

btw i was able to make a oneliner -ish zip, which is also a generator... but wihout strict support

def almost_zip_madness[*I](*iterables: Iterable[I]) -> Generator[tuple[*I], None, None]:
    with __import__('contextlib').suppress(StopIteration):yield from (lambda iters: iter(lambda: (lambda next_: tuple(next_))([next(iter_) for iter_ in iters]), None))([iter(iterable) for iterable in iterables])
vast wave
#

christ this is the most cursed thing ever

stark granite
#

zip_madness is

#

this one

vast wave
#

i mean this

#

the fucking abomination a bit of bytecode funnies can do

stark granite
vast wave
#

line -1

stark granite
#

!e

import dis

e = lambda x:()
e.__code__ = e.__code__.replace(co_code=b"\x97\x00|\x00\x82\x01")

dis.dis(e)
night quarryBOT
#

@stark granite :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 |   3           0 RESUME                   0
002 |               2 LOAD_FAST                0 (x)
003 |               4 RAISE_VARARGS            1
stark granite
#

ah

#

so thats basically

vast wave
stark granite
#
def lambda_(x):
    raise x

?

stark granite
vast wave
stark granite
#

!dis

vast wave
#

i dont think you even need the resume

#

no idea why its there

stark granite
#

!e

import dis
dis.dis("""
def lambda_(x):
    raise x""")
night quarryBOT
#

@stark granite :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 |   0           0 RESUME                   0
002 | 
003 |   2           2 LOAD_CONST               0 (<code object lambda_ at 0x7f25a02c1960, file "<dis>", line 2>)
004 |               4 MAKE_FUNCTION            0
005 |               6 STORE_NAME               0 (lambda_)
006 |               8 RETURN_CONST             1 (None)
007 | 
008 | Disassembly of <code object lambda_ at 0x7f25a02c1960, file "<dis>", line 2>:
009 |   2           0 RESUME                   0
010 | 
011 |   3           2 LOAD_FAST                0 (x)
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/PAW2Z2SQKQEPFSNY6UT2QEHZU4

vast wave
#

removing the resume makes it even better lmfao

#

completely removes the final stack frame of the lambda itself

#

mega trolled

#

funny_throw=(x:=lambda _:(),setattr(x,"__code__",x.__code__.replace(co_code=b"|\x00\x82\x01")))[0] the good throw version

quartz wave
#

full impl ```py
raise_exc = (O:=object(),lambda e,c=O: setattr(f:=lambda:0,'code',f.code.replace(co_argcount=2,co_nlocals=2,co_varnames=('_^',),co_code=b'\x97\x00|\x00%b\x82%c'%(b'|\x01'(T:=c is not O),1+T)))or f(e,c))[1]

vast wave
#

we dont need cause in this case

vast wave
#

bytecode fuckshit

stark granite
#

yeah but

#

wouldnt c is not _O_ always be false?

#

because of c=_O_ in the lambda def

vast wave
quartz wave
#
def zip_madness(*iterables, strict=False): return (lambda iters, next_, looping_, accum: ((lambda c, cc: [*map(cc, iter(lambda: bool(c), 0))])(lambda: looping_[0], lambda: (lambda t,e,E,t2=lambda:None,F=lambda:None:type('',(__import__('contextlib').ContextDecorator,),{'__enter__':int,'__exit__':lambda s,*a:(isinstance(a[1], e) and [E(a[1])],F())[0]})()(lambda:(t(),t2()))())(lambda: (next_.__setitem__(0, tuple(next(iter_) for iter_ in iters)), None)[-1], RuntimeError, lambda _: (_O_:=object(),lambda e,c=_O_: setattr(f:=lambda:0,'__code__',f.__code__.replace(co_argcount=2,co_nlocals=2,co_varnames=(*'_^',),co_code=b'\x97\x00%b%b\x82%c'%(b'|\x00'*(T2:=(T3:=e is not None) or not (c is _O_ or (e:=TypeError("caller is drunk"))and 0)),b'|\x01'*T3*(T:=c is not _O_),T3*T+T2)))or f(e,c))[1](ValueError("some iterators have exhausted before the others"), None) if strict and len(iters) != len(next_) else looping_.__setitem__(0, False), lambda: (accum.append(next_[0]), next_.__setitem__(0, ())))), accum)[-1])([iter(iterable) for iterable in iterables], [()], [True], [])
#

uh

#

don't mind if it's not highlighted in your side of the screen

#

:3

#

uh oh i got an error

#

uh oh it's caused by what i did

stark granite
#

how tf does it do with statement

#

also naming variables accordingly would be nice :3

quartz wave
#

uh oh it causes an infinite loop

stark granite
#

oh no

stark granite
#

why oneliners break pycharm

wheat river
#

It broke discord as well

vast wave
wheat river
#

Rip

long fulcrum
#

any idea how to golf this

#

its bothered me for so long that 137 is possible and im stuck on 148 where it just seems like nothing can be changed

#
import sys
for a in sys.argv[1:]:[print(f'{i:08x}: {(s:=a[i:i+16]).encode().hex(" ",-2):<41}'+s.replace(*'\n.'))for i in range(0,len(a),16)];print()```
#

no idea where the save could even be

long fulcrum
#

!e

import sys
sys.argv.append("""In mathematics and computing, the hexadecimal (also base 16 or simply hex)
numeral system is a positional numeral system that represents numbers using a
radix (base) of 16. Unlike the decimal system representing numbers using 10
symbols, hexadecimal uses 16 distinct symbols, most often the symbols "0"-"9"
to represent values 0 to 9, and "A"-"F" (or alternatively "a"-"f") to represent
values from 10 to 15.""")
for a in sys.argv[1:]:[print(f'{i:08x}: {(s:=a[i:i+16]).encode().hex(" ",-2):<41}'+s.replace(*'\n.'))for i in range(0,len(a),16)];print()
night quarryBOT
#

@long fulcrum :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | 00000000: 496e 206d 6174 6865 6d61 7469 6373 2061  In mathematics a
002 | 00000010: 6e64 2063 6f6d 7075 7469 6e67 2c20 7468  nd computing, th
003 | 00000020: 6520 6865 7861 6465 6369 6d61 6c20 2861  e hexadecimal (a
004 | 00000030: 6c73 6f20 6261 7365 2031 3620 6f72 2073  lso base 16 or s
005 | 00000040: 696d 706c 7920 6865 7829 0a6e 756d 6572  imply hex).numer
006 | 00000050: 616c 2073 7973 7465 6d20 6973 2061 2070  al system is a p
007 | 00000060: 6f73 6974 696f 6e61 6c20 6e75 6d65 7261  ositional numera
008 | 00000070: 6c20 7379 7374 656d 2074 6861 7420 7265  l system that re
009 | 00000080: 7072 6573 656e 7473 206e 756d 6265 7273  presents numbers
010 | 00000090: 2075 7369 6e67 2061 0a72 6164 6978 2028   using a.radix (
011 | 000000a0: 6261 7365 2920 6f66 2031 362e 2055 6e6c  base) of 16. Unl
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/HKDXEVAMHXGAOJAAQUKRMROJLY

quartz wave
#
def zip_madness(*iterables, strict=False): return (lambda iters, next_, looping_, accum: ((lambda c, cc: [cc() for _ in iter(lambda: bool(c()), 0)])(lambda: looping_[0], lambda: (lambda t,e,E,t2=lambda:None,F=lambda:None:type('',(__import__('contextlib').ContextDecorator,),{'__enter__':int,'__exit__':lambda s,*a:(isinstance(a[1], e) and [E(a[1])],F())[0]})()(lambda:(t(),t2()))())(lambda: (next_.__setitem__(0, tuple(next(iter_) for iter_ in iters)), None)[-1], RuntimeError, lambda _: (_O_:=object(),lambda e,c=_O_: setattr(f:=lambda:0,'__code__',f.__code__.replace(co_argcount=2,co_nlocals=2,co_varnames=(*'_^',),co_code=b'\x97\x00%b%b\x82%c'%(b'|\x00'*(T2:=(T3:=e is not None) or not (c is _O_ or (e:=TypeError("caller is drunk"))and 0)),b'|\x01'*T3*(T:=c is not _O_),T3*T+T2)))or f(e,c))[1](ValueError("some iterators have exhausted before the others"), None) if strict and len(iters) != len(next_) else looping_.__setitem__(0, False), lambda: (accum.append(next_[0]), next_.__setitem__(0, ())))), accum)[-1])([iter(iterable) for iterable in iterables], [()], [True], [])
quartz wave
# stark granite also naming variables accordingly would be nice :3

fixed naming (n some other stuff) uwu ```py
def zip_madness(iterables, strict=False): return (lambda iters, next_, looping_, accum: ((lambda condition, callback: [callback() for _ in iter(lambda: bool(condition()), False)])(lambda: looping_[0], lambda: (lambda try_, except_, except_callback, else_callback=lambda:None, finally_callback=lambda:None:type('',(import('contextlib').ContextDecorator,),{'enter':int,'exit':lambda s,a:(isinstance(a[1], except_) and [except_callback(a[1])] if a[1] is not None else [else_callback()], finally_callback())[0]})()(try_)())(lambda: (next_.setitem(0, tuple(next(iter_) for iter_ in iters)), None)[-1], RuntimeError, lambda _: (Never:=object(), lambda exc, context=Never: setattr(temp_func := lambda: None, 'code', temp_func.code.replace(co_argcount=2, co_nlocals=2, co_varnames=('_^',), co_code=b'\x97\x00%b%b\x82%c'%(b'|\x00'(T2 := (T3 := exc is not None) or not (c is Never or (exc:=TypeError("caller is drunk")) and False)), b'|\x01'*(T := T3 and context is not Never), T+T2))) or temp_func(exc, context))[1](ValueError("some iterators have exhausted before the others"), None) if strict and len(iters) != len(next_) else looping_.setitem(0, False), lambda: (accum.append(next_[0]), next_.setitem(0, ())))), accum)[-1])([*map(iter, iterables)], [()], [True], [])

#

true 1 liner noww

long fulcrum
#

yep there's multiple

#

it's why the empty print is needed

wheat river
quartz wave
vast wave
#

dude

#

favorite python feature

#

you can just flat out replace the method code of one method (or even lambda) with another

#

i did it before and i know its not that useful but its just so inherently funny to me for some reason

sick hound
#

where is the general python chat!!! so many channels its confusin

long fulcrum
cobalt mica
#

why esoteric python even exists?

wheat river
#
import ast
intop=lambda ex: (p:=lambda t:type(t)==ast.Constant and t.value or f"{p(t.left)} {p(t.right)} {c(t.op)}",c:=lambda o: "+-*@/"[ast.__dir__().index(type(o).__name__)-84])[0](ast.parse(ex).body[0].value)

infix to postfix

#

Probably wont work with parens

vast wave
cobalt mica
cobalt mica
#

if there's a place to find a pro in riddles and chalenges, i think it's here

#

i have a challenge to yall, it's a message in portuguese encoded with my own method of cryptography, someone can reveal the message?
BCBHCCBHCDBFABCCBCCDCGABBCCBCFAFAGCGBCCDAGABCF

fleet bridge
#

is it "Olá Mundo" ?

rugged sparrow
#

@stark granite @quartz wave my zip oneline impl (expanded) py zip = lambda *iterables, strict=False, _try=lambda t, *a, f=lambda a:a, e=Exception, **k,:(r:={}).pop( 'r', type( '', (__import__('contextlib').ContextDecorator,), { '__enter__':int, '__exit__':lambda s,*a:isinstance( a[1], e ) and [r.update( r=f(a) )] } )()(t)(*a, **k) ), _raise=lambda i, F:( ()for()in() ).throw( ValueError(f"zip() argument {i+1} is {'shorter' if F else 'longer'} than argument{' 'if i == 1 else 's 1-'}{i}") ), sentinel=object(): ( inner:=lambda iters=[*map(iter,iterables)], I=[0]: (acc:=[]) or _try( lambda:[[acc.append(next(it)) for I[0], it in enumerate(iters)]]and(*acc,), f=lambda exc:[ [ _raise(i,1) if i else [ _raise(i,0) for i, it in enumerate(iters) if _try(next, it, f=lambda a:sentinel, e=StopIteration) is not sentinel ] for i in I if strict ] ] and sentinel, e=StopIteration ) ) and ( V for V in iter(inner, sentinel) ) as far as i have tested it produces the exact same output as standard zip (with the exception of stack traces), uses no bytecode hacks, and should work as far back as 3.8 (i used walruses)

#

i (ab)use generators ability to raise exceptions using (()for()in()).throw(exc)

#

!e py (()for()in()).throw(ValueError('tada'))

night quarryBOT
#

@rugged sparrow :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     (()for()in()).throw(ValueError('tada'))
004 |   File "/home/main.py", line 1, in <genexpr>
005 |     (()for()in()).throw(ValueError('tada'))
006 | ValueError: tada
rugged sparrow
#

i could golf it further by reducing my old _try impl to only what is needed for zip, but i havent bothered yet

fleet lintel
#

!e funnily enough I also just finished mine, though I do a bit of cheating by not having the value error say the full thing, and execing to raise. py zip_=lambda*iterables,strict=0:(i:=[*map(iter,iterables)])and(b:=object())and __import__("itertools").takewhile(lambda x:all(y is not b for y in x)or strict and exec("raise ValueError"),((*[next(x,b)for x in i],)for _ in iter(int,1))) print([*zip_([1, 2, 3], ["A", "B"],["x", 1,2,3],strict=0)]) for x in zip_([1, 2, 3], ["A", "B"],["x", 1,2,3],strict=1): print(x)

night quarryBOT
#

@fleet lintel :x: Your 3.12 eval job has completed with return code 1.

001 | [(1, 'A', 'x'), (2, 'B', 1)]
002 | (1, 'A', 'x')
003 | (2, 'B', 1)
004 | Traceback (most recent call last):
005 |   File "/home/main.py", line 3, in <module>
006 |     for x in zip_([1, 2, 3], ["A", "B"],["x", 1,2,3],strict=1): print(x)
007 |   File "/home/main.py", line 1, in <lambda>
008 |     zip_=lambda*iterables,strict=0:(i:=[*map(iter,iterables)])and(b:=object())and __import__("itertools").takewhile(lambda x:all(y is not b for y in x)or strict and exec("raise ValueError"),((*[next(x,b)for x in i],)for _ in iter(int,1)))
009 |                                                                                                                                                                      ^^^^^^^^^^^^^^^^^^^^^^^^
010 |   File "<string>", line 1, in <module>
011 | ValueError
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/5AUEANB7XVCQAWUEFNPHNTDZMY

cobalt mica
rugged sparrow
#

!e fixed a small bug where calling with no iterables would cause an infinite loop ```py
zip = lambda *iterables, strict=False, _try=lambda t, *a, f=lambda a:a, e=Exception, **k,:(r:={}).pop(
'r',
type(
'',
(import('contextlib').ContextDecorator,),
{
'enter':int,
'exit':lambda s,*a:isinstance(
a[1], e
) and [r.update(
r=f(a)
)]
}
)()(t)(*a, **k)
), err=lambda i, F:(
()for()in()
).throw(
ValueError(f"zip() argument {i+1} is {'shorter' if F else 'longer'} than argument{' 'if i == 1 else 's 1-'}{i}")
), sentinel=object(): (
inner:=lambda iters=[*map(iter,iterables)], I=[0]:
(acc:=[]) or _try(
lambda:[[acc.append(next(it)) for I[0], it in enumerate(iters)]]and(*acc,),
f=lambda exc:[
[
err(i,1) if i else [
err(i,0) for i, it in enumerate(iters) if _try(next, it, f=lambda a:sentinel, e=StopIteration) is not sentinel
] for i in I if strict
]
] and sentinel,
e=StopIteration
) if iters else sentinel
) and (
V
for V in iter(inner, sentinel)
)

print(*zip('foo', 'bar-')) # test normal zip (non-strict)
try:
print(*zip('foo', 'bar-', strict=True)) # test strict zip
except ValueError as e:
print('ValueError:', e)
print(tuple(zip())) # test empty zip call

night quarryBOT
#

@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | ('f', 'b') ('o', 'a') ('o', 'r')
002 | ValueError: zip() argument 2 is longer than argument 1
003 | ()
sick hound
#

this is a bit cool, found this while working on my obfuscator

#

!e

items = [0,1,2,3]
print(items[--1])
print(items[-1])
print(items[1])
night quarryBOT
#

@sick hound :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | 1
002 | 3
003 | 1
sick hound
#

vscode shows this as an error but its valid python

#

!e

items = [0,1,2,3]
print(items[-1-])
night quarryBOT
#

@sick hound :x: Your 3.12 eval job has completed with return code 1.

001 |   File "/home/main.py", line 2
002 |     print(items[-1-])
003 |                    ^
004 | SyntaxError: invalid syntax
sick hound
#

!e

items = [0,1,2,3]
print(items[---1])
night quarryBOT
#

@sick hound :white_check_mark: Your 3.12 eval job has completed with return code 0.

3
restive void
#

!e

import sys
import gc
from functools import wraps


class AccessViolation(Exception):
    pass

def private(method):
    @wraps(method)
    def wrapper(*args, **kwargs):
        f = sys._getframe(1)
        clsname, *_ = method.__qualname__.partition(".")
        try:
            other_method = gc.get_referrers(f.f_code)[0]
            if not other_method.__qualname__.startswith(f"{clsname}."):
                raise AccessViolation("This method is private")
        except IndexError:
            raise AccessViolation("This method is private") from None
        return method(*args, **kwargs)
    return wrapper


class Foo:
    @private
    def bar(self):
        print("bar")

    def bat(self):
        print("<bat>")
        self.bar()
        print("</bat>")


f = Foo()
print("Allowed:")
f.bat()
print("Forbidden:")
f.bar()
night quarryBOT
#

@restive void :x: Your 3.12 eval job has completed with return code 1.

001 | Allowed:
002 | <bat>
003 | bar
004 | </bat>
005 | Forbidden:
006 | Traceback (most recent call last):
007 |   File "/home/main.py", line 39, in <module>
008 |     f.bar()
009 |   File "/home/main.py", line 17, in wrapper
010 |     raise AccessViolation("This method is private")
011 | AccessViolation: This method is private
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/V7MMOUKC76T3NY7U7MMYGFYHMU

long fulcrum
#

any place to save chars here?

import sys
m=max
for i in sys.argv[1:]:a,b,c,d,i,j,k,l=map(int,i.split());print(m(0,min(a+c,i+k)-m(a,i))*m(0,min(b+d,j+l)-m(b,j)))```
#

it calculates the intersection of two squares with inputs given as a string in this format x1 y1 w1 h1 x2 y2 w2 h2

fleet lintel
# sick hound !e ```python items = [0,1,2,3] print(items[---1]) ```

It makes sense that this works, since both + and - can also be unary operators, in addition to binary (in this case meaning one input and two input, instead of bases). Parsing it with ast shows that as the case slice=UnaryOp(op=USub(), operand=UnaryOp(op=USub(), operand=UnaryOp(op=USub(), operand=Constant(value=1)))), while with dis it gets optimized away to just LOAD_CONST 1 (-1). more info on unaries

sick hound
#

also looks like you are decrementing the variable like in c,java, etc

#

!e

++1
#

!e

print(++1)
night quarryBOT
#

@sick hound :white_check_mark: Your 3.12 eval job has completed with return code 0.

1
rugged sparrow
#
zip = lambda *iterables, strict=False:(I:=lambda O=[*map(iter,iterables)],I=[0]:(acc:=[])or(T:=lambda t,f,*a:(r:={}).pop('r',type('',(__import__('contextlib').ContextDecorator,),{'__enter__':int,'__exit__':lambda s,*a:isinstance(a[1],StopIteration)and[f(),r.update(r=S)]})()(t)(*a)))(lambda:[acc.append(next(it))for(I[0],it)in enumerate(O)]and(*acc,),lambda E=lambda i,F:(()for()in()).throw(ValueError(f"zip() argument {i+1} is {'shorter'if(F)else'longer'} than argument{' 'if(i==1)else's 1-'}{i}")):[E(i,1)if(i)else[E(i,0)for(i,M)in enumerate(O)if T(next,lambda:0,M)!=S]for(i)in(I)if strict])if(O)else 0,S:=[].pop)and(V for(V)in iter(I,S))
``` golfed and minified
#

figured out a trick for making a sentinel value using something shorter than object()

#

[].pop is shorter and is a unique value, same as the object()

fleet lintel
# rugged sparrow ```py zip = lambda *iterables, strict=False:(I:=lambda O=[*map(iter,iterables)],...

I think I finally got it working, making the error print correctly was such a massive pain, so in the end I gave up and used groupby. Also uses the throw so it's directly comparable. Thank god for itertools, I don't know how I would live without it. I also used the pop thing, that is really smart.```py
zip=lambda*iterables,strict=0:(i:=[*map(iter,iterables)])and(b:=[].pop)and(t:=import("itertools")).takewhile(lambda x:all(v:=[y!=b for y in x])or strict and(()for()in()).throw(ValueError(f"zip() argument {(G:=(g:=[(f,len([g]))for f,g in t.groupby(v)])[0][1])+1} is {['shorter','longer'][g[1][0]]} than argument{[' ','s 1-'][G>1]}{G}")),(([next(x,b)for x in i],)for _ in iter(int,1)))

rugged sparrow
#

rn im revisiting my exception catching code to see if I can get my generalized oneline try/except to be zero imports

fleet lintel
#

Using context lib is such a big brain move, that's why I started with itertools since takewhile doesn't make me have to use stopiteration.

rugged sparrow
#

I just realized i can rewrite mine with no imports and do away with the try except code actually

fleet lintel
#

It's funny that doing an extra walrus to use the generator for throw instead is still shorter, even with the list conversion py zip=lambda*iterables,strict=0:(i:=[*map(iter,iterables)])and(b:=[].pop)and (t:=__import__("itertools")).takewhile(lambda x:all(v:=[*(V:=(y!=b for y in x))])or strict and V.throw(ValueError(f"zip() argument {(G:=(g:=[(f,len([*g]))for f,g in t.groupby(v)])[0][1])+1} is {['shorter','longer'][g[1][0]]} than argument{[' ','s 1-'][G>1]}{G}")),((*[next(x,b)for x in i],)for _ in iter(int,1)))

#

It's also funny that pycharm complains about this [()for()in()] having unsupported syntax, but not this (()for()in())

rugged sparrow
#

!e ```py
zip = lambda *iterables, strict=False:(V for(S,E,[*I])in[[object(),lambda i,l:(()for()in()).throw(ValueError(f"zip() argument {i+1} is {l} than argument{[' ','s 1-'][i>1]}{i}")),map(iter,iterables)]]for V in iter(lambda:next([A.append(next(x,S))for x in I if S not in A]and([[E(i,'shorter')if i else[E(i,'longer')for i, x in enumerate(I)if next(x, S)!=S]for i in[A.index(S)]if strict]]and S if S in A else(*A,))if I else S for A in[[]]),S))

print(*zip('foo', 'bar-')) # test normal zip (non-strict)
try:
print(*zip('foo', 'bar-', strict=True)) # test strict zip
except ValueError as e:
print('ValueError:', e)
print(tuple(zip())) # test empty zip call```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | ('f', 'b') ('o', 'a') ('o', 'r')
002 | ValueError: zip() argument 2 is longer than argument 1
003 | ()
rugged sparrow
#

@fleet lintel ^ no imports

#
zip = lambda *iterables, strict=False: (
    V
    for sentinel,err,[*iters] in [[
        object(),
        lambda i, l:(
            ()for()in()
        ).throw(ValueError(f"zip() argument {i+1} is {l} than argument{[' ','s 1-'][i>1]}{i}")),
        map(iter,iterables)
    ]]
    for V in iter(lambda:
        next(
            [acc.append(next(it, sentinel)) for it in iters if sentinel not in acc] and (
                [[
                    err(i,'shorter') if i else [
                        err(i,'longer') for i, it in enumerate(iters) if next(it, sentinel) != sentinel
                    ] for i in [acc.index(sentinel)] if strict
                ]] and sentinel if sentinel in acc else (*acc,)
            ) if iters else sentinel 
            for acc in [[]]
        ), sentinel
    )
)``` expanded and without renamed variables ^
#

@stark granite @quartz wave thought yall might want to see this ^

stark granite
#

just why

fleet lintel
#

is there a reason for going back to object()?

rugged sparrow
rugged sparrow
stark granite
#

how me posting a funny "oneliner" got so much attention

#

i meant second one was oneliner

#

first impl wasnt really

rugged sparrow
fleet lintel
#

So it gets around the break problem by using sentinel as the sentinel for both the next, and the iter? That's funny.

rugged sparrow
fleet lintel
#

And it sucks us in as a problem, since the original code using so many non-one line things that one-lining it is a very interesting problem.

rugged sparrow
#

i have a hunch that if i went back to rewrite from scratch with the next(iterable, sentinel) pattern, I would prob end up with a slightly simpler impl

#

or at least smaller

#

would prob end up splitting my error condition code for strict mode

#

*oh that impl also has no walruses

fleet lintel
#

I wonder if I could somehow mangle my lambda that goes into takewhile to be the arg for iter. I think in the limit, our code should converge to the same thing.

rugged sparrow
#

makes it kinda perfect for zip

rugged sparrow
#

you can use any and also remove the full words, since Queen does not have a J or K (same for the rest)

#

so if any(item in card for item in 'JQK') would work

#

then you can golf further with
if any(map(card.__contains__,'JQK'))

#

can also prob get away with if any(map(card.startswith,'JQK'))

#

if card is a str

#

i have far too much python memorized

#

especially the weird stuff

quartz wave
#

this also works i think

gleaming linden
quartz wave
#

yea

versed eagle
#

everyone turned pink

finite blaze
#

Don't get them started

marble imp
#

show some funny oneliners

rugged sparrow
#

!e Heres a way to get iter(obj) without using the builtin ```py
get_iter = lambda arg:(()for()in(arg)).gi_frame.f_locals['.0']

print(get_iter('foo'))```

night quarryBOT
#

@rugged sparrow :white_check_mark: Your 3.12 eval job has completed with return code 0.

<str_ascii_iterator object at 0x7f02bcef3700>
marble imp
#

how much more boiler plate can i add

astral rover
#

import from builtins

marble imp
#
#!/usr/bin/env python3                                                                                                                                                    
                                                                                                                                                                          
import builtins                                                                                                                                                           
                                                                                                                                                                          
def main() -> None:                                                                                                                                                       
    print(str('Hello, World!'))                                                                                                                                                
    exit()                                                                                                                                                                
                                                                                                                                                                          
if str(__name__) == str('__main__'):                                                                                                                                                
    main()                                                                                                                                                                
else:                                                                                                                                                                     
    exit()
finite blaze
restive void
versed eagle
# marble imp ```python #!/usr/bin/env python3 ...

I think this is the most boilerplate that one could reasonably add.

# /usr/bin/env python3

# We need `sys.argv' and `sys.exit'.
import sys


def main (argc: int, argv: list[str]) -> int:
    """main (argc: int, argv: list[str]) -> int

    Main function for the program.
    """

    output_string: str = "Hello, world"

    # Writing to stdout could fail, so we should handle that.
    try:
        print(output_string)
    except:
        return -1

    return 0


if __name__ == "__main__":
    exit_code = main(len(sys.argv), sys.argv)
    sys.exit(exit_code)
else:
    pass
#

by "reasonably", i mean "you could get this into production code"

#

maybe you could add version checking at the beginning to fail if the python version isn't high enough?

versed eagle
marble imp
earnest wing
marble imp
#

that too

#

we need to ad logging too

versed eagle
versed eagle
#

that doesn't add typesafety

marble imp
fleet lintel
#

Real type safety for the mind would be doing py output_string: str = "Hello, world" assert isinstance(output_string, str)

marble imp
#
data: list[list[str | int]] = []
maximums: list[list[str | int]] = []
minimums: list[list[str | int]] = []
while True:
    tmp: list[str | int] = []
    tmp.append(str(input('Enter name: ')))
    tmp.append(int(input('Enter value [integer only]: ')))
    continue_: str = str(input('Continue? [Y/n]?')).strip().lower()
    data.append(tmp[:])
    if maximums == []:
        maximums.append(tmp)
    elif tmp[1] > maximums[0][1]:
        maximums = []
        maximums.append(tmp)
    elif tmp[1] == maximums[0][1]:
        maximums.append(tmp)

    if minimums == []:
        minimums.append(tmp)
    elif tmp[1] < minimums[0][1]:
        minimums = []
        minimums.append(tmp)
    elif tmp[1] == minimums[0][1]:
        minimums.append(tmp)
    if continue_ == '':
        continue_ = 'y'
    if continue_ == 'n':
        break

print(data)
print(f'Registered: {len(data)}\nMaximum value: {maximums}\nLowest value: {minimums}')```
how cursed is this
fleet lintel
#

Very, considering the type hints in esopy. Also very, considering the key kwarg of min and max exist. Looking at it more, there is no reason to use a list for min and max, besides like obfuscation maybe?

versed eagle
marble imp
#

notice that it appends when it is equal

earnest wing
#

That should be set as everyone's bio

meager zinc
#
# /usr/bin/env python3
"""
This program is designed to function as a base template that will work well
with a number of different programs and Python versions.
"""

# Required to support more python versions
from __future__ import annotations, print_function

# We need `sys.argv' and `sys.exit'.
import sys
# In order to support older python versions.
from typing import List


def main(argc: int, argv: List[str], /) -> int:
    """main (argc: int, argv: list[str]) -> int

    Main function for the program.

    :arg argc: The number of command line arguments.
    :arg argv: The command line arguments.
    """

    # Define the string to be output to the console
    output_string: str = "Hello, world!"

    # Writing to stdout could fail, so we should handle that.
    try:
        seperator: str = ""
        ending_string = "\n"
        output_file = sys.__stdout__
        flush_file = True
        # Print the output string to stdout
        print(
            output_string,
            sep=seperator,
            end=ending_string,
            file=output_file,
            flush=flush_file,
        )
    except BaseException:
        # Writing failed, so return a nonzero exit code
        return -1
    finally:
        pass

    return 0


# Only execute the program if run directly
if __name__ == "__main__":
    # Extract the exit code from the main function
    exit_code = main(argc=len(sys.argv), argv=sys.argv)
    # Exit with the proper exit code
    sys.exit(exit_code)
else:
    pass
fleet bridge
#

__future__.print_function and type annotations at the same time is so cursed...

fleet bridge
#

why no -h/--help handling?

long fulcrum
#

any idea how to golf this further?

import sys
for s in sys.argv[1:]:
    a,b,c,d,e,f,g,h,i=map(int,s.replace("-",""));j=(a+2*b+3*c+4*d+5*e+6*f+7*g+8*h+9*i)%11
    if j==10:j="X"
    print(f"{s}{j}")```
restive void
#

140 132 130 129 bytes

import sys
for s in sys.argv[1:]:
 if(j:=sum(b*c for b,c in enumerate(map(int,s.replace("-","")),1))%11)>9:j="X"
 print(s+str(j))
versed eagle