#esoteric-python

1 messages · Page 115 of 1

floral meteor
#

so what if the correct solution is like 4567876578976567876567876567898765678, 987654567898765567645676543400002?

earnest wing
#

then it takes about forever to find

floral meteor
#

you could optimise that perhaps?

earnest wing
#

no i could not

#

it's z3

floral meteor
#

threading?

earnest wing
#

Solver's metaclass (SolverMeta) returns a custom Namespace in __prepare__, which can effectively skip NameErrors in the class body
In this case, I make undefined variables return Variable objects which define all the operators (returning BinOp objects, etc.)
Thanks to python being so generous and helping me parse that, I now already have an AST tree ready to use and evaluate.
I hook __bool__ in these AST nodes to check whether the most recently executed instruction corresponds with an assert. If it does, it adds the node to the class's list of assertions.
Then, in SolverMeta's __init__, I:

  • Gather all the annotations and initialize them as z3's variable types
  • Traverse the nodes and convert them into z3 expressions (with some special cases for operators like ~x turning into Not(x), x&y into And(x,y), etc.)
  • Add all these expressions into a z3.Solver
  • Check if z3 thinks the problem is solvable, and if it can solve it, stores the solution in the class's __model
    Finally, SolverMeta's __getattr__ just falls back to __model.__getitem__ if a model exists
#

All the computation is done by z3

floral meteor
#

ah so z3 does the hard work and you do the dirty work

#

XD

#

that looks like something i want in cursedutils

#

if you fork, i'll merge.

earnest wing
#

there's some extra syntax, too
for functions

#
❯ python3 main.py
[x = 6, f = [11/2 -> 1, 6 -> 6, 12 -> 0, else -> -3/2]]
floral meteor
#

Implement differential equations

#

XDDDD

#

Use getitem to subscript maybe?

snow beacon
#

It's an interface to the z3 constraint solver, using a metaclass that reads custom syntax. A DSL in a class.

fast zenith
#

Hullo, my code no worky

def transformer(func):
	def wrapper(*args): return func(*[ann(*[i for i in args]) for ann in list(map(lambda t: eval(t.__name__) if t.__name__ in  [ty.__name__ for ty in __import__('builtins').__dict__.values() if isinstance(ty,type)] else None,func.__annotations__.values()))])
	return wrapper

wen i try using more than one arg it gibs

TypeError: decoding to str: need a bytes-like object, int found

Help pls :'( it's not that dumb

#

Oh wait I get it, it's taking the second argument of decorated function as an arg for the first type only

#

But it shouldn't do that smh

#

probably it's not doing that 🤔

simple crystal
#

lol while this place is for code gore, if your code gore doesn't work you are more likely to get help if you format it better

fast zenith
#

Will black be enough pithink

#

i am afraid it's not

simple crystal
#

maybe haha

#

probably be best to expand it to for loops

#

like I get wanting a one liner cuz it's neato

#

but if it doesn't work it's probably best to expand it

#

then you can condense it again

#

idk if black can expand comprehensions

fast zenith
#
def transformer(func):
    def wrapper(*args):
        return func(
            *[
                ann(*[i for i in args])
                for ann in list(
                    map(
                        lambda t: eval(t.__name__)
                        if t.__name__
                        in [
                            ty.__name__
                            for ty in __import__("builtins").__dict__.values()
                            if isinstance(ty, type)
                        ]
                        else None,
                        func.__annotations__.values(),
                    )
                )
            ]
        )

    return wrapper 

Hmm

simple crystal
#

oh you're trying to convert everything with ann at once

#

i.e. when I tried this with a funtion with int annotations it upacked both functions into int() and used the second arg as the base

fast zenith
#

Yeah that's what it's doing

simple crystal
#

I guess I need to see a use case too cuz idk when this is supposed to be used

fast zenith
#

the decorator?

simple crystal
#

ya

#

all I can tell is it's for annotated functions

#

but apparently the annotations are supposed to be functions that take every arg themselves

fast zenith
#

It's not really for any use, I just did it cause I liked this idea a little

simple crystal
#

haha well u might wanna just pass the arg that's annotated to ann

#

instead fo all args to every ann

#

then it'll work probably

fast zenith
#

ah ok, thanks for helping

simple crystal
#

np

viscid nymph
#

Hey guys, I wrote this one line embed pagination function for discord.py 😛

LEFT_EMOJI = "⏪"
RIGHT_EMOJI = "⏩"
FIRST_EMOJI = "⏮️"
LAST_EMOJI = "⏭️"


async def _paginate(embeds, msg, timeout):
    with type("",(),{"__enter__":lambda _:[bot.loop.create_task(msg.add_reaction(e))for e in(FIRST_EMOJI, LEFT_EMOJI, RIGHT_EMOJI, LAST_EMOJI)],"__exit__":lambda*a:bot.loop.create_task(msg.clear_reactions())and a[1]in(asyncio.TimeoutError,)})():[(embed:=embeds[(index:=((index:=(locals().get("index", 0)))+(min(index+1,len(embeds)-1)-index if str(r)==RIGHT_EMOJI else index and-1 if str(r)==LEFT_EMOJI else len(embeds)-1-index if str(r)==LAST_EMOJI else-index)))])and await msg.edit(embed=embed)async for r,_ in(await bot.wait_for("reaction_add",check=lambda _r,u:str(_r)in(LEFT_EMOJI,RIGHT_EMOJI,FIRST_EMOJI,LAST_EMOJI)and _r.message==msg and u!=bot.user,timeout=timeout)for _ in iter(lambda:1,0))]
terse mortar
#

!e ```py
lambda: exec("""
print('test')
""")()

night quarryBOT
#

@terse mortar :warning: Your eval job has completed with return code 0.

[No output]
terse mortar
#

hmm

viscid nymph
#

Basically, that's just lambda:None()

terse mortar
#

ohh

viscid nymph
#

except that it prints

terse mortar
#

!e ```py
(lambda: exec("""
print('test')
"""))()

night quarryBOT
#

@terse mortar :white_check_mark: Your eval job has completed with return code 0.

test
terse mortar
#

mwahaha

fluid lantern
#

lol

simple crystal
#

!e

funcs = {
    'y' : lambda x:(exec('''if True:\n    if True:\n
        if x > 2:
            g=4
        else:
            g=6
    ''', f:={'x':x}) or f["g"]),
}

print(funcs['y'](2))
print(funcs['y'](3))
night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

001 | 6
002 | 4
viscid nymph
#

\t

simple crystal
#

nah I want spaces to work

floral meteor
#

[ if not bool(yay) increase bracket skip
] if bool yay decrease bracket skip...
Oh I think I figured it out I gotta somehow skip one extra

#

Brainfuck looping without using for

floral meteor
#

Ima make a Turing incomplete semi interpreter

crystal ocean
#

what if we merged python and html syntax

#

into a disgusting creature

floral meteor
#

Everyone will die

spark inlet
#

bruh

#

r u blurplefied

crystal ocean
#

what

floral meteor
#

!e ```py
def decode(c):
a= p= t= 0
while p<len(c) and p>=0:
if t:
p+=(t>0)-(t<0)
if c[p]=='[':t+=1
elif c[p]==']':t-=1
continue
if c[p]=='+':a+=1;a%=128
elif c[p]=='-':a-=1;a%=128
elif c[p]=='.':print(end=chr(a))
elif c[p]=='[' and not a:t+=1
elif c[p]==']'and a:t-=1;p-=2
p+=1
decode('+'*100+'.[---.]'+'+'*67+'.'*3)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | da^[XUROLIFC@=:741.+(%"
002 | ~{xurolifc`]ZWTQNKHEB?<9630-*'$!	�CCC
floral meteor
#

Executed perfectly

#

Brilliant!

spark inlet
#

can i ask: is def = define?

fluid tree
fluid tree
formal sandal
#

!e

(lambda lаmbda:lambda lambdа:lambdа(lаmbda))(lаmbdа:='lambdа')(print)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

lambdа
visual flare
#

whaaaaaat

#

theeee

proper vault
#

you really like that trick, huh?

formal sandal
#

works on people every time

#

well, on those who haven't seen it

viscid nymph
#

Wait lambda is valid argument name?

plucky wedge
formal sandal
#

yeah

#

well, they look the same

plucky wedge
#

not on phone

#

¯_(ツ)_/¯

formal sandal
#

huh?

#

my trick doesn't work lemon_sentimental

plucky wedge
#

they look different but it might because i changed my font size in ios settings

night quarryBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*

dusty ridge
#

!e print(1)

night quarryBOT
#

@dusty ridge :white_check_mark: Your eval job has completed with return code 0.

1
dusty ridge
#

😮

#

!e dict

night quarryBOT
#

@dusty ridge :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name '__dict__' is not defined
dusty ridge
#

!e vars()

night quarryBOT
#

@dusty ridge :warning: Your eval job has completed with return code 0.

[No output]
dusty ridge
#

!e print(vars())

night quarryBOT
#

@dusty ridge :white_check_mark: Your eval job has completed with return code 0.

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
sullen fulcrum
#

!e

x = 3
match x:
    case 3:
        print('x is 3')
night quarryBOT
#

@sullen fulcrum :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 2
002 |     match x:
003 |           ^
004 | SyntaxError: invalid syntax
sullen fulcrum
#

poop they don't have 3.10

dusty ridge
#

!e import inspect

night quarryBOT
#

@dusty ridge :warning: Your eval job has completed with return code 0.

[No output]
dusty ridge
#

!e
import inspect
print(inspect.getsource(vars))

night quarryBOT
#

@dusty ridge :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 |   File "/usr/local/lib/python3.9/inspect.py", line 1024, in getsource
004 |     lines, lnum = getsourcelines(object)
005 |   File "/usr/local/lib/python3.9/inspect.py", line 1006, in getsourcelines
006 |     lines, lnum = findsource(object)
007 |   File "/usr/local/lib/python3.9/inspect.py", line 817, in findsource
008 |     file = getsourcefile(object)
009 |   File "/usr/local/lib/python3.9/inspect.py", line 697, in getsourcefile
010 |     filename = getfile(object)
011 |   File "/usr/local/lib/python3.9/inspect.py", line 677, in getfile
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/cuvayogano.txt?noredirect

crystal ocean
#

not that

#

i mean

#

something like this

floral meteor
#

!e ```py
def decode(n):
from collections import defaultdict as _d
l,a,o=len(s:=str(int(n))),_d(int),str();i=p=a[int()];c=8;t=0
while len(s)>p:
def _2():a[i]+=1;a[i] %=1<<+ c;return i,c,o,t # %=1<<+
def _3():a[i]-=1;a[i] %=1<<+ c;return i,c,o,t # i made "coerce encoding" operator
_4,_5=lambda:(+i+ 1,c,o,t),lambda:(+i- 1,c,o,t)
_6=lambda:(i,c,print(end=chr(a[i]))or o+chr(a[i]),t)
def _7():a[i]=ord(import('sys').stdin.read(1));return i,c,o,t
_8,_9=lambda:(i,c,o,t+(not bool(a[i]))),lambda:(i,c,o,t-bool(a[i]))
_0,_1=lambda:(i,c+1%32,o,t),lambda:(i,c-1%32,o,t)
i,c,o,t=[_0,_1,_2,_3,_4,_5,_6,_7,_8,_9]int(s[p])if not t else (
i,c,o,t -(t >+ int()and s[p]=='9')- -(t <+ int()and s[p]=='8')
);p+=1-2 + (t <- int()) # i run out of fancy augmented operators :/ gimme more!
if p <- int():raise SyntaxError('mismatched 9')
return type('invisible_list',(list,),{'repr':lambda s:''})([ord(k)for k in o])
class quick_encode:
_h=8
def init(s,m:str):
while 1<<s._h<ord(max(m)):s._h+=1
if s._h>8:
r='1'
if s._h<8:r+='0'
(8-s._h)
elif s._h>9:r+='1'*(s._h-9)
else:r=''
p='\0'
for c in m:
i=(ord(c)-ord(p));p=c
if i>0: r+='2'i
elif i<0: r+='3'
-i
r+='6'
s.r=r
def int(self):return int(self.r)
a = quick_encode("Hello World!")
print(int(a))
print(decode(a))

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | 22222222222222222222222222222222222222222222222222222222222222222222222262222222222222222222222222222262222222662226333333333333333333333333333333333333333333333333333333333333333333333333333333362222222222222222222222222222222222222222222222222222222622222222222222222222222262226333333633333333633333333333333333333333333333333333333333333333333333333333333333336
002 | Hello World!
toxic jewel
#

havent visited this channel in a while

cerulean osprey
#
from random import randrange,choice
while True:print(chr((randrange(ord("A"),ord("Z")+1) if choice((True,False)) else randrange(ord("a"),ord("z")+1) if choice((True,False)) else randrange(ord("0"),ord("9")+1))) if choice((True,False)) else " ",end="")
#

!e

from random import randrange,choice
while True:print(chr((randrange(ord("A"),ord("Z")+1) if choice((True,False)) else randrange(ord("a"),ord("z")+1) if choice((True,False)) else randrange(ord("0"),ord("9")+1))) if choice((True,False)) else " ",end="")
night quarryBOT
#

@cerulean osprey :x: Your eval job timed out or ran out of memory.

14LU 2QV3   NDSM    U r7E Db    LTNT    g B  PBT     CZL  7x L F Q L HOU8Q R  V0k7 BLPS     O Z 3        DwQ  Ws  L   50tF  D A          h83DYF  W  V   FD  V      e5RVdm    C4  3R 0S  2 u    bV   BP 7 5X V   F0   C V T 2R9 X    R  s  b U  1  W   Bz    K By BR QG2    1cL L2 I wkEMFFy5L    6A    q528 P  Y5fT       2S  O 4  4 RcOS i gN h c2S  6N   W      6clpRD  Q8  3   2 D jB  3c U8D  Yst J A D5  iE67 9 iB9H Z3L  KSj15     1 9 pHbI5  x F   F l1 P  J v   1H   6x A3BY  2DJ    Z AE WiN 9   U1B B 6 tW X  0 xS  J  0 1 TvJ c8VF5 j SWa 9   l OR58ODE9 EX VwJl 0v h  0Q  34 h  o HfIR 0DR     c qJO q M  9 U0 P0  XJp  mP Z  NM84 M a   O 6Y  0  n PW   2U     ISn  F  KU9 B  GW  H r D mX  2   2F U 0  gD5  e 6N Tg  3  lJ T 1 i5  OS 4P 98 8Hx2 qJ     C  P3  2  G208 J 99 Q5 Sg  Ri 5h   6zF   7     aPwf3 4IW    N R l    j   T Kt z  E y   6      AU vHS eA94t J9 w   d     8 G1L  XL JMy4RcN  O  1D N7   C   J   UJJ   c  P K3   rCX45  0 pE6 91  Zt8  i  S0c2hg Y 5 CHL L    l g BN  6       vMWqq  B V7RJEs0E     U
... (truncated - too long)

Full output: too long to upload

earnest wing
#

with some new magic syntax, too

#
class MySolver(Solver):
  a: int
  b: int
  ...

()=MySolver # dump model into globals
earnest wing
#

added a writeup to the project

winter widget
#

how to check if a var is a int?

naive roost
#

how esoteric do you want it to be?

plucky wedge
#

imagine u walk into a bar and u ask for a beer, and the bartender asks, “How prevalent do u want the wine taste to be”

#

like u answer no because what

#

literally the same scenario as asking if u want something to be esoteric

#

of course not

#

unless u hate ur self

#

but esoteric would make it fun

#

and interesting

#

i’m confused on what my goal with this rant was

thin trout
wet kernel
floral meteor
#

much more elegant than isinstance

#

!e there's also type ```py
n1 = 4
print (type(n1) is int)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

True
viscid nymph
#

especially since isinstance can take a tuple, and considers the object's bases as well

floral meteor
#

if it considers bases, that's a security issue

#

someone could subclass int and override the methods to do hide some malicious functions

#

if i make sure the class is int, then it is int

#

besides i can read it better, it's class is int, it's almost like english, not a function call

#

alrighty then, my encryption project now works

#

it takes a pretty beefy computer to thonk about it tho

#

I'm thinking of moving it to 2d (or higher) coordinates in an integer map rather than just the digit index of an arbitrarily long integer

earnest wing
#

int in x.__class__.mro() :>

cerulean rivet
#
import random

do_nothing = lambda: None

if_ = lambda cond, callback, else_: (else_, callback)[cond()]()

different = lambda x, to: (lambda: x.value != to.value)

__while = lambda c, k: while_(c, k)
while_ = lambda cond, callback: (
    if_(cond,
        lambda: (callback(), __while(cond, callback)),
    else_=\
        do_nothing)
)

Variable = type("Variable", (), {
    "__init__": lambda s, value: setattr(s, "value", value),
    "set_": lambda s, v: s.__init__(v)})

input_int_number = lambda: int((
    inp := Variable(''),
    while_(lambda: not inp.value.isdigit(), lambda: (
        inp.set_(input("Digite um numero: ")),

        if_(lambda: not inp.value.isdigit(), lambda: \
            print("Apenas números naturais!\n"),
        else_=\
            do_nothing
        )
    )),
    (yield int(inp.value))
))

main = lambda: (
    random_number := Variable(random.randint(1, 10)),
    user_number := Variable(None),

    print("O computador escolheu um número entre 1 e 10. Tente adivinhar!\n"),

    while_(different(user_number, random_number), lambda: (
        user_number.set_(next(input_int_number())),
        
        if_(different(user_number, random_number), lambda: (
            print("Você errou!\n"),),
        else_=do_nothing
        )
    )),
    
    print("Você acertou!")
)

main()```
floral meteor
#

why's it in spanish?

#

is that spanish?

cerulean rivet
#

nop

floral meteor
#

idk languages other than python XD

cerulean rivet
#

xD

floral meteor
#

in case your thinking i know english, i failed english in HS, so that proves that wrong

#

XD

#

this looks intriguing.
I think i may have half-heartedly attempted this using class wrappers for all statements

#

I've implemented a switch suite in a similar style too, although i accidentally made it into an epic wrapper suite

#

i.e.

i = 5
switch(i)
@case[1]
def do(): print('fail')
@case[5]
def do():print('success')
@default
def do(): raise RuntimeError
#

the original intention was ```py
i = 5
switch: i # only works in globals
case1
case5
otherwise(print,'error')

#

I could probably make switch a nice, hacky object with a getattribute method in order to

i = 5
switch. i
case[1](...)
...
#

there's a number of ways using dunders you can do interesting things with python syntax.
in this channel, the only error in python is syntaxerror

cerulean rivet
#

wait

floral meteor
#

as i said, only works in globals

#

cos locals doesn't have annotations

cerulean rivet
floral meteor
#

ew

#

backslashes

snow beacon
cerulean rivet
floral meteor
#

alright i'll see if i can fetch it from memory

#

ouch why do yall expect me to have eidetic memory? smh

cerulean rivet
#
def powerful_features():
    target = None


    class switch:
        def __getattribute__(_, name):
            nonlocal target
            target = globals()[name]

    class case:
        def __getitem__(_, value):
            func = lambda *_, **__: None
            if value == target:
                func = lambda f, *args, **kwargs: f(*args, **kwargs)
            return func

    return case(), switch()

case, switch = powerful_features()

number = 1
switch. number
case[1](
    print, "One"
)
case[2](
    print, "Two"
)``` @floral meteor
floral meteor
#

now implement default

cerulean rivet
#

hm

floral meteor
#

also known as otherwise in matlab

#

i think

#

¯_(ツ)_/¯

#

gl

cerulean rivet
#

1s

floral meteor
#

!e ```py
def Switch():
class Null(metaclass=lambda*a:type(a)()):repr=lambda s:'';str=lambda s:'None'
class case(metaclass=lambda
a:type(*a)()):
def init(self):
self.state =- 1
self.value = Null
def getitem(self, value):
if self.state <- 0:
try:v = globals()['annotations']['switch']
except Exception as e:
v = e.traceback.tb_frame.f_back.f_globals['annotations'].get('switch',Null)
if v is Null: raise SyntaxError("matching switch not found")
self.state, self.value =- 0 ,+ v
else: v = self.value
if v == value and not self.state:
self.state =+ 1
return (lambda f,*u,**ck:f(u,**ck))
else:return (lambda
No,**ne:None)
def default(f,u,**ck):
if case.state <- 0: raise SyntaxError("Stray default statement.")
elif case.state >0:
case.state, case.value =- 1, Null
return (lambda
No,**ne:None)
else:
case.state, case.value =- 1, Null
return (lambda f,*u,**ck:f(*u,**ck))
return case, default
case, default = Switch()

test

i = (10>>1)
switch: i
@case[20]
def do(): print("left shift")
@case[5]
def do(): print("right shift")
@case[5]
def do(): raise RuntimeError("multiple match evaluation")
@default
def do(): raise ValueError("expected 5")

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

right shift
floral meteor
#

@cerulean rivet

cerulean rivet
#
def powerful_features():
    class ob: pass
    proxy = ob()
    proxy.__eq__ = lambda *_: False

    target = proxy
    cases = {}

    class switch:
        def __getattribute__(_, name):
            nonlocal target
            target = globals()[name]

    class case:
        @staticmethod
        def register(v):
            nonlocal cases
            temp = cases
            def wrapper(f, *args, **kwargs):
                nonlocal temp
                cs = temp
                cs[v] = lambda: f(*args, **kwargs)

            return wrapper

        def __getitem__(self, value):
            return self.register(value)

    def otherwise(fn, *args, **kwargs) -> None:
        for v, f in cases.items():
            if v == target:
                f()
                return lambda *_, **__: None
        return fn(*args, **kwargs)

    return case(), switch(), otherwise


case, switch, otherwise = powerful_features()


number = 3

switch. number
case[1](
    print, "One"
)
case[2](
    print, "Two"
)
otherwise(
    print, number
)```
floral meteor
#

you could actually use them as wrappers, without changing any code.

#

!e i.e.

def powerful_features():
    class ob: pass
    proxy = ob()
    proxy.__eq__ = lambda *_: False

    target = proxy
    cases = {}

    class switch:
        def __getattribute__(_, name):
            nonlocal target
            target = globals()[name]

    class case:
        @staticmethod
        def register(v):
            nonlocal cases
            temp = cases
            def wrapper(f, *args, **kwargs):
                nonlocal temp
                cs = temp
                cs[v] = lambda: f(*args, **kwargs)

            return wrapper

        def __getitem__(self, value):
            return self.register(value)

    def otherwise(fn, *args, **kwargs) -> None:
        for v, f in cases.items():
            if v == target:
                f()
                return lambda *_, **__: None
        return fn(*args, **kwargs)

    return case(), switch(), otherwise


case, switch, otherwise = powerful_features()


number = 3

switch. number
@case[1]
def do():
  print("One")
@case[2]
def do():
  print("Two")
@otherwise
def do():
  print(number)
night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

3
floral meteor
#

they're interchangeable syntax

#

you could make it assign to a variable by renaming do and returning

#

hang on i'll test on your test case

cerulean rivet
#

wow

floral meteor
#

ooh mine failed

#

oh i see why

#

wait no

#

wait wat

#

i got it

#

!e ```py
def Switch():
class Null(metaclass=lambda*a:type(a)()):repr=lambda s:'';str=lambda s:'None'
class case(metaclass=lambda
a:type(*a)()):
def init(self):
self.state =- 1
self.value = Null
def getitem(self, value):
if self.state <- 0:
try:v = globals()['annotations']['switch']
except Exception as e:
v = e.traceback.tb_frame.f_back.f_globals['annotations'].get('switch',Null)
if v is Null: raise SyntaxError("matching switch not found")
self.state, self.value =- 0 ,+ v
else: v = self.value
if v == value and not self.state:
self.state =+ 1
return (lambda f,*u,**ck:f(u,**ck))
else:return (lambda
No,**ne:None)
def default(f,u,**ck):
if case.state <- 0: raise SyntaxError("Stray default statement.")
elif case.state >0:
case.state, case.value =- 1, Null
return (lambda
No,**ne:None)
else:
case.state, case.value =- 1, Null
return f(*u,**ck)
return case, default
case, otherwise = Switch()

number = 3
switch: number
case1
case2
otherwise(
print, number
)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

3
floral meteor
#

it's not even the usual hackery.
now allowing that in locals would need hackery.

cerulean rivet
#

is not possible get locals of a context that called the switch?

floral meteor
#

it's possible to get the locals

#

it's just that annotations aren't stored in locals

cerulean rivet
#

hmm

floral meteor
#

smort thonk: replace it with regex switch: \s\n or something like that idk regex

floral meteor
#

I made a brainfuck generator

wanton obsidian
#

You monster....

Can you give us doom in brainfuck?

simple crystal
#

glad im not the only one tethered to fuckin pycharm

#

hate it but the couple hours it'd take to set up a better IDE slays me

#

it works fine 90% of the time but 10% of the time it lags and hogs memory and sucks for no discernable reason

steel siren
#

nvim is best

grave rover
#
a, b, c = 1, 2, 3
with switch(a, b, c):
    with case(lambda a, b, c: a < b < c):
        print('ayy 0')
        with switch(b, a, c):
            with case(2, 1, 3):
                print('nested switch!')
            with case(1, 2, 3):
                print('this wont be printed')
    with case(1, 2, 3):
        print('ayy 1')
        with case(lambda a, b, c: b == 2):
            print('holy shit a nested case!')
        switch_break()
    with case(1, 2, 3):
        print('ayy 2')
#

@floral meteor this one was made by meta a while back ^

south relic
#

How can I make dynamic progres bar for my video downloader in tkinter ? I have created a progress bar but it's not dynamic . I want that when I click on download button it start and fills up acc to the downloaded file?

last locust
river plume
#

Hey, I just have a simple question when dealing with text files:
I have a text file and wanna make a python program to read it and if it finds any number it replaces it by the number preceding it like if it finds 4 it replaces it with 3 so ho can I do that
The problem for me in this program is that python reads the numbers as strings not integers so it can't decrease or increase it

sick hound
#

!ban 604866480697507853 Racism

night quarryBOT
#

:incoming_envelope: :ok_hand: applied ban to @glad atlas permanently.

cerulean rivet
#
def powerful_features():
    if_ = proxy = object()
    def then(*args):
        try: raise Exception("não me veja, eu sou um easter egg :D")
        except Exception as e:
            v = e.__traceback__.tb_frame.f_back.f_globals['__annotations__'].get('if_', proxy)
            if v is proxy: raise SyntaxError("cade o if_ ??????????????")
        if not bool(v): return
        nl = []; temp = []
        for v in args:
            if callable(v): nl.append(temp); temp = []
            temp.append(v)
        nl = nl[1:] + [temp]
        for f, *args in nl: f(*args)
    return if_, then

if_, then = powerful_features()

x = 2
if_: x == 10; then (
    print, "Hello,",
    print, "world"
)```
steep mural
#

that's clever

viscid nymph
#

not v > not bool(v)

plucky wedge
snow beacon
floral meteor
# plucky wedge wtf are those function names

_0,_1,...,_9
In this case directly coincide with the digit that calls that function, the primary purpose of decode is to interpret an integer, and generate a message from it, using a Turing complete method such as brainfuck.
Thus I have mapped brainfuck characters to digits, hence the concise, descriptive function names, so I can keep track of which digit executes which function

#

I usually use them as lambda input, stack index style

plucky wedge
#

oh

floral meteor
#

!e ```py
_22 = 2_2
_22 += 0o0_2
_0 = print
_0( _22, 2_2, 2_2 + 0o0_2)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

24 22 24
floral meteor
#

!e print(*[0x00_for x in input("Hello World!")])

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

15
floral meteor
#

!e ```py
deadbeef = 0xdeadbeef
print(deadbeef)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

3735928559
rugged sparrow
floral meteor
#

!e ```py
print(*[0xdeadbee_for deadbee in (1,2,3)],
0xdeadbeef)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

3735928559 3735928559
floral meteor
#

Very confusing mathematical operator, no?

#

@rugged sparrow how do you update instances of a hacked class again?

rugged sparrow
#

Like builtin classes?

floral meteor
#

Yeah

#

Yeah like for example make calling an int call multiply

rugged sparrow
#

Most builtin classes instances don't have an instance dict

#

Oh

#

You mean Dunders

#

You have to modify slot pointers

#

Look at fishhook

floral meteor
#

Ah

#

Ty

cerulean rivet
#

how it works?

rugged sparrow
#

!e print(0x00_f)

night quarryBOT
#

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

15
cerulean rivet
#

oh

#

xD

floral meteor
sick hound
#

Please dm me if you have comments, please.

rough swallow
#

This is not a for loop, right? (list comprehension)

[0x00_for x in input ("Hello World!")])

What is that doing is:

>>> 0xf or x in (1, 2, 3)
0xf

But because the first comparison returns a true value, it does not check whether x in (1, 2, 3)

viscid nymph
#

yes

sick hound
rugged sparrow
#

Give me a few tho, I'll try my hand at them

sick hound
#

You could implement this?

potent comet
#

It's doable using the lasti attribute of the stack frame.

astral rover
#

That's definitely doable yeah

rugged sparrow
#

Yea it's doable

potent comet
#

Which exists for the purpose of the mentioned debuggers. It does have limitations though - you can't jump in and out of things like try/with blocks since that'd corrupt the stack of exception handlers.

rugged sparrow
#

Can also inject jmp instructions if you want to jump anywhere

#

Did that to implement goto

rugged sparrow
#

!e ```py
import sys
from ctypes import c_char

BYTES_OFFSET = bytes.basicsize - 1

def getmem(addr, size):
return (c_char * size).from_address(addr)

fix_ops = [None, None, None]

class anchor:
def init(self):
frame = sys._getframe(1)
if None not in fix_ops:
idx, size, ops = fix_ops
getmem(id(frame.f_code.co_code) + BYTES_OFFSET + idx, size)[:] = ops
self.g_state = frame.f_globals.copy()
self.l_state = frame.f_locals.copy()
self.location = frame.f_lasti - 2

def backstep(anchor):
frame = sys._getframe(1)
co_code = frame.f_code.co_code
inj_idx = frame.f_lasti + 2
fix_ops[:] = inj_idx, 2, co_code[inj_idx: inj_idx + 2]
getmem(id(co_code) + BYTES_OFFSET + inj_idx, 2)[:] = bytes([114, anchor.location])

i = 0
a = anchor()
i += 1
if i < 5:
backstep(a)
print(i)

night quarryBOT
#

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

5
rugged sparrow
#

took the easy way out and only implemented anchors (no line numbers)

#

i implemented part of rewind but not all of it

#

the pdf wasnt super clear if the new timeline still ran

#

(which is ironically easier via os.fork)

sick hound
#

But seriously thank you this is amazing I will get clarifying the doc so if people wanna implement this in the future, they don't have to worry about ambiguities.

final night
#

just discovered something mildly interesting and completely useless, so I figure I should share

#

If you run

import sys
while True:
  sys.stdout.write("\a")

in a console window on Windows 10 then it seems like you cannot stop the program in any way.

#

It brought my mouse cursor down to like 5 FPS too, kinda surprising

#

guess windows can't handle all of the system calls

hard spoke
#

"in any way"? task manager?

viscid nymph
#

ah wait I wasn't in cmd, and yeah the terminal crashed

night quarryBOT
#

:incoming_envelope: :ok_hand: applied mute to @gleaming jackal until 2021-05-16 14:12 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

earnest wing
#

@thin trout spam bot

thin trout
#

<@&831776746206265384> ^

formal sandal
#

!ban @dusty ore Take your scam somewhere else.

night quarryBOT
#

:incoming_envelope: :ok_hand: applied ban to @dusty ore permanently.

formal sandal
#

@thin trout you're a mod bro

thin trout
#

@formal sandal I was in the middle of something else >.<

formal sandal
#

ah, sorry then

thin trout
#

no probs lol

final night
viscid nymph
#

It crashed the first time, but yeah it froze after that

#

But I was able to kill it with task manager

floral meteor
#

!e ```py
import os
if os.fork():
print(end='6')
else:print(9)

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | BlockingIOError: [Errno 11] Resource temporarily unavailable
floral meteor
#

Huh

floral meteor
#

i feel like there was a shorthand for [i for i in a if i>5]

#

but a[a > 5] doesn't work

#

is there some sort of metadunder?
like getattribute, only more like get slot

#
[i for i in a if i>5]
a[lambda i:i>5]

i mean its shorter but...

#

for 5 chars probably not worth implementing an extension to getitem

tight gyro
#

would this be the channel to ask why most books on python devote such a large portion of the introductory chapters to turtle?

floral meteor
#

I don't touch turtle, nor in any of the material on python i have read done anything more than mention turtle

#

turtle is okay for graphics

rugged sparrow
floral meteor
#

ouch

#

must've been thinking about matlab

rugged sparrow
#

i wonder if i could make it work tho 👀

tight gyro
#

I am not a fan of turtle either, but doing a group walkthrough of 'how to think like a computer scientist' python edition and easily 60% of the first 4 chapters has been using turtle.

#

what would you recommend for teaching a group of beginners, which is solid, free, and doesn't touch turtle?

floral meteor
#

extension of ALGERBRUH ASSIGNMENT:

a = [0, 2, 4, 6, 10]
b = [i for i*2 in a if i>2]
print(b) # [3, 5]
floral meteor
alpine flower
night quarryBOT
#

@alpine flower :white_check_mark: Your eval job has completed with return code 0.

[1 2 3]
alpine flower
#

numpy/pandas has masks if that's what you were thinking of

floral meteor
#

niiiiice

#

wait

#

how does it dimensions?

#

or does it flatten?

#

!e ```py
import numpy as np

arr = np.array([[1, 2, 3],
[4, 5, 6]])
print(arr[arr <= 5])

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

[1 2 3 4 5]
floral meteor
#

ah

#

!e ```py
import numpy as np

arr = np.array([[1, 2, 3],
[4, 5, 6]])
print(arr < 5)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | [[ True  True  True]
002 |  [ True False False]]
floral meteor
#

hmmm

#

!e ```py
import numpy as np

arr = np.array([[1, 2, 3],
[4, 5, 6]])

derp = np.array([[0, 1, 1],
[0, 1, 0]])
print(arr[derp])

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | [[[1 2 3]
002 |   [4 5 6]
003 |   [4 5 6]]
004 | 
005 |  [[1 2 3]
006 |   [4 5 6]
007 |   [1 2 3]]]
alpine flower
#

!e

import numpy as np

arr = np.array([[1, 2, 3],
                [4, 5, 6]])
print(arr[arr[1] <= 5])
floral meteor
#

ok why did it make a 3d matrix?

night quarryBOT
#

@alpine flower :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 | IndexError: boolean index did not match indexed array along dimension 0; dimension is 2 but corresponding boolean dimension is 3
alpine flower
#

imma pretend like I understand that error

floral meteor
#

3d array

#

wat happened to mine tho?

alpine flower
#

im not sure what's causing it but ik there's a proper way to use an array as a mask using numpy.ma
it seems like it has the capability to work dimensionally tho(?)

floral meteor
#

i feel like integers should be able to just be called

#

!e like such

class _(int):__call__=int.__mul__
for i in range(100):globals()['_'+str(i)]=_(i)
x = _7 + _2(_3 * _4 - _1)
print(x)
night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

29
dawn kayak
#

!e ```py
import gc
gc.get_referents(int.dict)[0]['uwu'] = lambda s: print('UwU')

(69).uwu()

night quarryBOT
#

@dawn kayak :white_check_mark: Your eval job has completed with return code 0.

UwU
floral meteor
#

A new hackery module!

#

Do that with __call__ then do 2(3+4)

#

But make it multiply

earnest wing
#

pretty sure the special methods might require a certain slot

dawn kayak
#

!e ```py
import gc
gc.get_referents(int.dict)[0]['call'] = lambda s,o: s*o
print((2)(3))

night quarryBOT
#

@dawn kayak :x: Your eval job has completed with return code 1.

001 | <string>:3: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 |   File "<string>", line 3, in <module>
004 | TypeError: 'int' object is not callable
final night
#

!e

import random, math
x = [round(random.random(),1) for _ in range(100)]
x[math.floor(len(x)/2)] = float("NaN")
print(sorted(x))
night quarryBOT
#

@final night :white_check_mark: Your eval job has completed with return code 0.

[0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.4, 0.4, 0.4, 0.5, 0.5, 0.5, 0.5, 0.6, 0.6, 0.6, 0.6, 0.6, 0.7, 0.7, 0.7, 0.8, 0.8, 0.8, 0.8, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 1.0, nan, 0.0, 0.0, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.4, 0.4, 0.4, 0.5, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.7, 0.7, 0.7, 0.7, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.9, 0.9, 1.0, 1.0, 1.0]
final night
#

is this intended functionality?

#

you would think it would throw an error or something at least

#

just silently returning an unsorted list is pretty scary behavior

#

!e

print(sorted([float("nan"), 0, 1, -1]))```
night quarryBOT
#

@final night :white_check_mark: Your eval job has completed with return code 0.

[nan, -1, 0, 1]
final night
#

that one worked, sorta

stark fable
#

well, that list is sorted

#

ish

final night
#

the one above isn't

#

weird

stark fable
#
[0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.4, 0.4, 0.4, 0.5, 0.5, 0.5, 0.5, 0.6, 0.6, 0.6, 0.6, 0.6, 0.7, 0.7, 0.7, 0.8, 0.8, 0.8, 0.8, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 1.0, nan, 0.0, 0.0, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.4, 0.4, 0.4, 0.5, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.7, 0.7, 0.7, 0.7, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.9, 0.9, 1.0, 1.0, 1.0]``` this one?
final night
#

yeah

stark fable
#

this is sorted

final night
#

this

stark fable
#

or at least it's as sorted as you could reasonably expect it to be

final night
#
[0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.4, 0.4, 0.4, 0.5, 0.5, 0.5, 0.5, 0.6, 0.6, 0.6, 0.6, 0.6, 0.7, 0.7, 0.7, 0.8, 0.8, 0.8, 0.8, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 1.0, nan, 0.0, 0.0, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.4, 0.4, 0.4, 0.5, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.7, 0.7, 0.7, 0.7, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.9, 0.9, 1.0, 1.0, 1.0]

is sorted?

#

I mean, I guess it is as sorted as you could reasonably expect it to be, that is, not at all

stark fable
#

find me two adjacent elements, a and b, for which a is after b but b > a is True

#

in that list

final night
#

0.0 and 1.0

stark fable
#

ok and where are they

final night
#
1.0, nan, 0.0
stark fable
#

that's not adjacent

#

1.0 > nan is false and nan > 0.0 is false

#

so it's sorted

final night
#

from a practical perspective, would you ever expect this behavior?

stark fable
#

if i thought about it enough then yes

#

i've asked it to solve a nonsensical problem

#

all comparison with nan returns False

final night
#

you would intentionally add NaNs to your list to partion off subsorts, or what

#

that seems anti-zen

stark fable
#

i wouldn't rely on it

#

but i would expect it to be something weird

#

it should be something weird, since the problem i asked it to solve is weird

#

comparison doesn't behave properly when nan is involved

final night
#

Normally when you tell python to solve a nonsensical problem it throws an error

#

!e

1/0
night quarryBOT
#

@final night :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ZeroDivisionError: division by zero
stark fable
#

well if it checked for nan that would just move the problem back a step since you could define a custom class that behaves the same as nan with comparison and put that in a list

final night
#

I definitely agree that it is nonsensical to ask it to sort a list with NaNs, by the way

stark fable
#

the only way to ensure that this makes sense would be to double the number of comparisons done

final night
#

to rephrase, it seems like attempting to sort a list with unorderable values in it should throw an error

#

not just NaNs

stark fable
#

is doing an esoteric check for a rare case more important than doubling the amount of time that an otherwise-very-fast function takes?

final night
#

would it double the execution time?

#

if so that's a good point

#

but would it actually?

stark fable
#

how do you check without doubling the execution time?

final night
#

sorting is O(n log(n))

#

adding an O(1) check will not double execution time

#

at least, from a complexity standpoint

#

not sure about it from a practical standpoint

stark fable
#

an O(1) check... of what

final night
#

orderability

stark fable
#

how do you check if every element of a list behaves nicely with comparison, in O(1) time

final night
#

I would assume a typecheck

stark fable
#

in particular if you restrain it to O(1), you are not allowed to do even an O(1) check on every element of the list because that is O(n)

final night
#

you are already doing a check on every element on the list, so performing an O(1) check during iteration does not increase time complexity

#

that was my point

#

not to loop over the list beforehand

stark fable
#

...oh, i thought you meant the entire thing on the whole list would be O(n) beecloseloaf

#

although...

#

how do you check if they're orderable with a typecheck

final night
#

hmm

#

to be perfectly honest I am not sure how I would do that, here is some (borrowed) code that claims to check orderability

 if hasattr(x, '__lt__'):
     try:
         isOrderable = ( ((x == x) is True) and ((x > x) is False)
                         and not isinstance(x, (set, frozenset)) )
     except:
         isOrderable = False
 else:
     isOrderable = False
#

supposedly checking if it implements less than isn't enough, which is a bummer

stark fable
#

ok actually, i'm fairly sure you can't check if something is orderable without specifying what you are planning to compare it with

final night
#

hmm, that would make sense

viscid nymph
final night
#

are there cases in Python where there are two objects are not comparable with one another but comparable with other types?

#

Can you give an example?

stark fable
#

nan

final night
#

-_-

#

other than NaN lol

#

that was pretty funny though gotta admit

#

this is interesting:

stark fable
#

for an example that demonstrates it to be completely impossible: py class Weird: def __init__(self, turing_machine): self.turing_machine = turing_machine def __lt__(self, n): if self.turing_machine.halts_after_n_steps(n): return False return True def __gt__(self, n): return False

final night
#

!e

sorted([3, "1", 4, 7])
night quarryBOT
#

@final night :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: '<' not supported between instances of 'str' and 'int'
stark fable
#

assume that there's an implementation of turing machines with halts_after_n_steps

#

if the turing machine specified runs forever, then this Weird object is less than any integer

#

but if it halts, then there is some integer it cannot be properly compared with

#

so if you have an arbitrary object that you want to compare with integers, checking if that will always work is at least as hard as the halting problem

final night
#

fair

#

why not add TypeError: '<' not supported between instances of 'NaN' and 'int'

stark fable
#

(if you assume that you can run python on a turing machine then it's probably also exactly as hard as the halting problem because you can write a machine that tries every integer)

stark fable
#
>>> nan
nan
>>> type(nan)
<class 'float'>```
final night
#

I guess it would need to be more specific, yeah

stark fable
#

although i agree that the entire situation with NaN is a bit stupid

#

why is it not equal to itself ```py

nan == nan
False```

final night
#

woah, that's weird

#

so the only way to check for nans is math.isnan() then I guess

stark fable
#

well you can also check if it's not equal to itself since i'm fairly sure NaN is the only thing that does that

#

although if you want to properly check then yeah you need isnan

viscid nymph
#

!e

from math import nan
print(f"{nan == nan = }")
print(f"{[nan] == [nan] = }")
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

001 | nan == nan = False
002 | [nan] == [nan] = True
cerulean rivet
#

!e ```python
class Maybe(metaclass=lambda _:type(_)()):
bool = lambda _: bool(import("random").randint(0, 1))
str = lambda : str(bool())
getattribute = lambda , v: bool().getattribute(v)

globals().setitem = type('__', (), {
"setattr": lambda ,n,v: ( for _ in ()).throw(SyntaxError("can't assign to keyword")) if n == "Maybe" else super().setattr(n,v),
"delattr": lambda ,n: ( for _ in ()).throw(SyntaxError("can't delete keyword")) if n == "Maybe" else super().delattr(n)
})

if Maybe:
print(":D")
else:
print("D:")

print(Maybe)

print(isinstance(Maybe, bool))

Maybe = 1

night quarryBOT
#

@cerulean rivet :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 6, in <module>
003 | AttributeError: 'dict' object attribute '__setitem__' is read-only
cerulean rivet
#

how i can change the __setitem__ of globals?

final night
night quarryBOT
#

@final night :white_check_mark: Your eval job has completed with return code 0.

False
viscid nymph
# cerulean rivet how i can change the `__setitem__` of `globals`?

!e

from ctypes import *
class Dict(dict):
    __slots__ = ()
    def __setitem__(self, key, value):
        print(f'setting {key} to {value}')
        return super().__setitem__(key, value)

py_object.from_address(id(globals())).value = Dict(globals())
py_object.from_address(id(globals())+8).value = Dict

x = 1
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

setting x to 1
viscid nymph
#

!e

from ctypes import py_object
x = 1
print(f"{type(x) = }")
print(f"{py_object.from_address(id(x)+8).value = }")
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

001 | type(x) = <class 'int'>
002 | py_object.from_address(id(x)+8).value = <class 'int'>
cerulean rivet
final night
#

!e

class Everything:
    def __eq__(self, other):
        return True

x = Everything()
print(x == float("nan")) 
print(float("nan") == x)
print(float("nan").__eq__(x))
print(x.__eq__(float("nan")))
print("--")

print(float("nan").__eq__(float("nan")))
print(float("nan").__eq__(1))
night quarryBOT
#

@final night :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | True
003 | NotImplemented
004 | True
005 | --
006 | False
007 | False
final night
#

this is interesting

viscid nymph
#

What's interesting?

final night
#

!e

print(float("nan") == "a")
print(float("nan") == [1])
print(float("nan") == {1})
print(float("nan") == {1:1})
print(float("nan") == object())
night quarryBOT
#

@final night :white_check_mark: Your eval job has completed with return code 0.

001 | False
002 | False
003 | False
004 | False
005 | False
final night
#

NaN returns NotImplemented for user defined types but false for defaults

viscid nymph
#

Nope

#

!e

print(bool(NotImplemented))
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

001 | <string>:1: DeprecationWarning: NotImplemented should not be used in a boolean context
002 | True
viscid nymph
#

== can only return bools

#

so it does bool(NotImplemented)

#

since float.__eq__(another_type) returns NotImplemented

final night
#

ah, ok

#

thanks for the explanation

flint tide
#

made a 1 liner for change making for fun

cn = lambda x: (x-1)**10 if x<0 else 0 if x==0 else 1 + min([cn(x-i) for i in {1, 5, 12, 20}])
#

completely unreadable and not pythonic at all but hey

viscid nymph
#

this channel isn't about readability 👀

lone gust
viscid nymph
#

I was saying it's ok for it to be unreadable lol

floral meteor
#

Alright y'all I have actual challenge

#

It's challenging

#

import... anything after clearing globals and builtins. Also, print anything.
XDDDD

#

!e ```py
(lambda a,b:a.clear() or b.clear())(globals(),builtins)
try:print(dir(globals()))
except Exception:pass

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 1, in <lambda>
004 | AttributeError: module 'builtins' has no attribute 'clear'
floral meteor
#

Hang on why is my builtins different to yours?

#

My device uses a dictionary for builtins

#

This one uses a module

viscid nymph
#

Might be an old version?

floral meteor
#

It's literally 2 minor versions behind last I checked

rugged sparrow
#

__builtins__ can be a dict or a module at any time

floral meteor
#

Wait wat

#

Huhhhhhhh

#

IMPLICIT!

rugged sparrow
#

!e print(type(__builtins__))

night quarryBOT
#

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

<class 'module'>
floral meteor
#

so why is mine a dictionary?

#

Oh wait

#

I think I see the pattern

#

Nope I'm still confused

#

When is it a dictionary?

rugged sparrow
#

one sec

#

in the repl, if you delete __builtins__ it is replaced with a dictionary

#

with -c this is not the case (the bot uses -c)

#

internally, in any frame, __builtins__ can be a dict or a module and python will handle it the same

#

!e py __builtins__ = {'print':lambda *a,**k:print('fake', *a, **k)} print(1)

night quarryBOT
#

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

1
rugged sparrow
#

huh

#

this behaves differently in the repl

#
>>> p = print
>>> __builtins__ = {'print':lambda *a,**k:p('fake', *a, **k)}
>>> print(1)
fake 1
>>> ```
floral meteor
#

!e ```py
globals().clear()
for f in dir(builtins):().class.class('x',(),{}).delattr(builtins,f)
try: import sys; print()
except Exception: a=4

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | NameError: name '__builtins__' is not defined
floral meteor
#

Huh

#

In my version, builtins remains in globals when it's cleared

rugged sparrow
#

seems the python repl implicitly does some funky stuff related to __builtins__

floral meteor
#

Yeah.

#

Preventing what I just did in python

#

I figuratively shot myself in the foot

#

I cleared both globals and builtins

#

You can't import, import not find

#

You can't make a class

#

build_class not found

#

You can't print

rugged sparrow
#

its still recoverable

floral meteor
#

Bruh

#

I've hand made like 50 builtins

#

From literals and attributes

#

Show me how you can print hello world or import hello in this purified state

rugged sparrow
#

so with this to disable python -> ```py
_del = delattr
_imp = import
for i in dir(builtins):
_del(builtins, i)

sys = _imp('sys')
del _del, _imp
sys.meta_path.clear()
sys.modules.clear()```

floral meteor
#

Lol get yeeted by inconsistent builtins

rugged sparrow
#

huh

floral meteor
#

@rugged sparrow you forgot the globals clearing

rugged sparrow
#

looks like 3.9 breaks some stuff

floral meteor
#

You can't save any global variables, due to globals clearing, thus the clearing process can only use locals in a function in order to work.
Then builtins is cleared, denying access to... itself.
And thus, you have to build upon literals.

#

That's why it's challenging

rugged sparrow
#

ik

floral meteor
#

Cos python has been truly purified

rugged sparrow
#

nah you can still recover

#

you can access any classes already initialized

floral meteor
#

Yeah you can access ().class.class thus manually making classes.
But can you print hello world, or import sys?

#

Functions still work

rugged sparrow
#

yes

#

you can recover python completely

floral meteor
#

Show me your ways

#

After a full purification of course

rugged sparrow
#

when globals().clear() is the only thing you run you arent fully deleting the interpreter

#

all you are doing is removing one reference to builtins

#
_del = delattr
_imp = __import__
for i in dir(__builtins__):
    _del(__builtins__, i)

sys = _imp('sys')
del _del, _imp
sys.meta_path.clear()
sys.modules.clear()``` the following deletes all attributes in `__builtins__`, then deletes most of the importing system
#

it is much more complete than your method @floral meteor

#

it results in a globals dict that just contains an empty __builtins__ module

#

in contrast, globals().clear() results in a globals that has a full builtins (or an empty dictionary, but __builtins__ still exists in an initalized state

#

@floral meteor i want to see you try to recover from it before i post my functional method

floral meteor
#

I'm on bicycle rn

#

Smh

#

Alright I unplugged the usb with python in it

#

python is still running

#

NOW IT IS TRULY PURIFIED

#

Hmm

#

I got a clue: trying to load a build function made by the class statement crashes purified python

#

I've got several classes and functions already

#

I had a good range function yesterday

#

Once I have a frame object or module object I'm in.

rugged sparrow
#

why not go straight for re-initializing builtins?

floral meteor
#

I tried that

rugged sparrow
#

there is a subclass of object that allows importing

floral meteor
#

Ik I tried to reduce object

#

And it said import key error

rugged sparrow
#

object.__subclasses__()

floral meteor
#

Import Error import not found

rugged sparrow
#

when you run object.__subclasses__()?

floral meteor
#

No I got a lot of interesting things from that

#

But I haven't got anything to work

#

I got file no -1 from stderrprinter class

rugged sparrow
#

look for importlib in class names

floral meteor
#

I made globals function

#

And it mutates globals

#

!e ```py
builtins.id = lambda s:420
print(id(69))

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

420
floral meteor
#

@rugged sparrow I can only import from zips

#

I have error classes now

#

Python has cells?

#

Damn this is useful

#

!e ```py
sub = object.subclasses()
sub = {c.name:c for c in sub}
cell = sub['cell']
c = cell(1)
def inc(n):c.cell_contents += n
inc(5)
print(c.cell_contents)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

6
floral meteor
#

Mutatble int

#

@rugged sparrow I got a lot of import lib stuffs

#

But I can't figure out how to import

#

Oh I got permission denied

#

Ooh I made it read file

floral meteor
#

It is sort of a gulag for one object

cerulean rivet
#

gulag?

rugged sparrow
floral meteor
#

I tried that with sys

rugged sparrow
#

and did it not work?

floral meteor
#

Nope

rugged sparrow
#

what was the result

floral meteor
#

Type error

#

Expected 1 argument

#

Got 2

#

In _module_repr

rugged sparrow
#

load_module is a class method

#

so dont do BuiltinImporter().load_module(...)

floral meteor
#

Ik

rugged sparrow
#

do BuiltinImporter.load_module(...)

floral meteor
#

I tried both

rugged sparrow
#
bimp, fimp, epf = (get_cls(n) for n in [
    '_frozen_importlib.BuiltinImporter',
    '_frozen_importlib.FrozenImporter',
    '_frozen_importlib_external.PathFinder'
])

b_dict.update(bimp.load_module('builtins').__dict__)
bimp.load_module('sys').meta_path = [bimp, fimp, epf]``` this is the end of my repair code
#

it works there

floral meteor
#

OH SHIT SOMEONE JUST WALKED PAST HOLDING A HUGE FRIKIN SNAKE

#

jk that's normal around here.

#

How do I hack _module_repr?

rugged sparrow
#

Try storing the result instead of letting it get printed

floral meteor
#

Okay builtins is brok

#

I imported it, so it gave me what I had manually stored in builtins

#

XDDDDD

#

I got sys tho

#

I got printing

#

Now I'm stuck with namerror

#

Now i broke my improvised import function

rugged sparrow
#

!e ```py
_del = delattr
_imp = import
for i in dir(builtins):
_del(builtins, i)

sys = _imp('sys')
del _del, _imp
sys.meta_path.clear()
sys.modules.clear()

object = ().class.base
singleton = object()
type = object.class
def get_cls(name, base=object):
if f'{base}'.split("'")[1] == name:
return base
for cls in type(base).subclasses(base):
if ret := get_cls(name, cls):
return ret

def all_excs(c=get_cls('BaseException')):
yield c
for s in c.subclasses():
yield from all_excs(s)

b_dict = builtins if type(builtins) == type({}) else builtins.dict

b_dict.update({
**{exc.name: exc for exc in all_excs()},
'len': lambda o: type(o).len(o),
'hasattr': lambda o, a: a in o.dict,
'getattr': lambda o, n, d: o.dict.get(n, d),
'isinstance': lambda o, t: t in o.class.mro
})

bimp, fimp, epf = (get_cls(n) for n in [
'_frozen_importlib.BuiltinImporter',
'_frozen_importlib.FrozenImporter',
'_frozen_importlib_external.PathFinder'
])

b_dict.update(bimp.load_module('builtins').dict)
bimp.load_module('sys').meta_path = [bimp, fimp, epf]

print('hello world')
import os

night quarryBOT
#

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

001 | hello world
002 | Traceback (most recent call last):
003 |   File "<string>", line 46, in <module>
004 | ModuleNotFoundError: No module named 'os'
rugged sparrow
#

damn importing is a bit broken

#

this successfully restores builtins tho

#

!e print(import('sys').version)

night quarryBOT
#

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

001 | 3.9.4 (default, Apr  5 2021, 18:26:27) 
002 | [GCC 8.3.0]
floral meteor
#

I can't get builtins back

#

it returns my manual builtins back at me

#

!e ```py
builtins.import = print
import sys

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

sys {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>} {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>} None 0
floral meteor
#

!e builtins.import=print; from foo import bar

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 1.

001 | foo {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>} {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>} ('bar',) 0
002 | Traceback (most recent call last):
003 |   File "<string>", line 1, in <module>
004 | io {'__builtins__': <module 'builtins' (built-in)>} {'__builtins__': <module 'builtins' (built-in)>} [] 0
005 | ImportError: cannot import name 'bar' from '<unknown module name>' (unknown location)
floral meteor
#

looooool

#

what have i done?

floral meteor
#

!e ```py
def derp(source, g, specs, n, *a):
if specs:print('importing',*specs,'from',source)
else:print('importing',source)
if a:print(a)
g |= locals()
return n
builtins.import = derp
from hello import

print(initialized)

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 1.

001 | importing __name__ __doc__ __package__ __loader__ __spec__ __annotations__ __builtins__ derp from __hello__
002 | 0
003 | Traceback (most recent call last):
004 |   File "<string>", line 8, in <module>
005 | importing __builtins__ from io
006 | 0
007 | ImportError: from-import-* object has no __dict__ and no __all__
floral meteor
#

I have done cursed things to import

#

what is a from-import-* object?

rugged sparrow
#

its an internal import error

#

raised with star imports

floral meteor
#

!e ```py
def derp(source, g, specs, n, *a):
if specs:print('importing',*specs,'from',source)
else:print('importing',source)
if a:print(*a)
g |= locals()
return n
builtins.import = derp
import hello
print(hello)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | importing __name__ __doc__ __package__ __loader__ __spec__ __annotations__ __builtins__ derp from __hello__
002 | 0
003 | None
floral meteor
#

I'm gonna give struct another shot

#

!e ```py
f = type("fart",(object,),{'getattribute':lambda s,o:print(o) or object.getattribute(s,o),"lt":print})()
dir(f)
hasattr(f,'f')
f < 6

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | __dict__
002 | __class__
003 | f
004 | 6
floral meteor
#

it doesn't getattr lt

#

i can hide sh*t in slots!

#

totally not malicious :/

#

i'm checking that in my more dodgily sourced code from now on

floral meteor
#

nope struct wont fit here

rough swallow
#

why does 0xfor 1 works and 0xfand 1 not?

>>> 0xfor 1
15
>>> 0xfand 1
  File "<stdin>", line 1
    0xfand 1
        ^
SyntaxError: invalid syntax
>>> 
cerulean rivet
#

0xfa nd

rugged sparrow
night quarryBOT
#

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

001 | 250
002 | Traceback (most recent call last):
003 |   File "<string>", line 1, in <module>
004 |   File "<string>", line 1
005 |     0xfo
006 |        ^
007 | SyntaxError: unexpected EOF while parsing
rough swallow
floral meteor
#

!e ```py
class matrix(list):
def init(self, iterable, width):
super().init(iterable)
self.width = width
assert not len(self)%width
@property
def height(self):return len(self)//self.width
def call(self, row,col):return super().getitem(rowself.width+col)
def getitem(self, item):
if item.class is tuple:return self(item)
return super().getitem(item)
def setitem(self, t, v):
if t.class is tuple:return super().setitem(t[0]self.width+t[1],v)
return super().setitem(t, v)
def repr(self):
n = max([len(str(this))for this in self])
return '['+',\n '.join([', '.join([f"{str(self(i,j)):>{n}s}"for j in range(self.width)])for i in range(self.height)])+']'
def mul(self, other):
try:
assert other.class is not matrix
assert other
1 == other
assert[j
other for j in matrix]
for i,derp in enumerate(self):
self[(i.divmod(self.width),)] = derpother
except:
if other.class is matrix:
assert self.width == other.height
a=[]
for i in range(self.height):
for j in range(other.width):
n=+(0)
for e, f in[(self(i,k),other(k,j))for k in range(self.width)]:
n+=f
e
a+=[n]
return self.class(a,width=other.width)
raise
a = matrix([1, 2, 3,
3, 4, 4,
0, 1, 1
], width=3)
b = matrix([4, 0,
1, 2,
0, 1,
], width=2)
print(a*b)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | [ 6,  7,
002 |  16, 12,
003 |   1,  3]
floral meteor
#

did i get the matrix multiplication right?

night quarryBOT
#

Hey @floral meteor!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

fluid tree
hardy kernel
#

hello

#

My name is Aamil Nasar

night quarryBOT
#

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

001 | reg : (True, True)
002 | not : (False, False)
003 | and : True
004 | or : True
005 | xor : False
sick hound
#

How come this is possible:

#

!e


a = []
print(a < [] > b)
night quarryBOT
#

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

False
sick hound
#

But b's not defined

viscid nymph
sick hound
#

Oh

#

Bruh I forgot I was using <

zealous widget
#

I remember doing something similar with tuples as boolean operators:

In [14]: TRUE = True, True
    ...: FALSE = False, False
    ...: 
    ...: ID = False, True
    ...: NOT = True, False
    ...: 
    ...: AND = FALSE, ID
    ...: OR = ID, TRUE
    ...: 
    ...: XOR = ID, NOT
    ...: IMPLIES = TRUE, ID

In [15]: NOT[True]
Out[15]: False

In [16]: AND[True][False]
Out[16]: False

In [17]: OR[False][True]
Out[17]: True
floral meteor
#

alright, now implement that logic syntax for n expressions, p, q,r, ..., a_n

#

XD

#

Sometimes I wonder if i should be paying attention to those yellow things everywhere...

#

there's 352 of them...

floral meteor
#

That's integer brainfuck writer and reader

#

Created just to abstract away some hardcore encryption

floral meteor
#

dict and class are not slotted?

#

but gettatribute is

#

!e ```py
f = type("fart",(object,),{'getattribute':lambda s,o:print(o) or object.getattribute(s,o),"lt":print})()
dir(f)
hasattr(f, 'Hello World!')
delattr(f,'lt')
f < 'what?'

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 1.

001 | __dict__
002 | __class__
003 | Hello World!
004 | Traceback (most recent call last):
005 |   File "<string>", line 4, in <module>
006 | AttributeError: __lt__
floral meteor
#

wait isn't it slotted?

#

oh

#

it isn't

#

an attribute?

#

!e ```py
f = type("fart",(object,),{'getattribute':lambda s,o:print(o) or object.getattribute(s,o),"lt":print})()
dir(f)
hasattr(f, 'Hello World!')
f < hasattr(f, 'lt')
delattr(f, 'lt')

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 1.

001 | __dict__
002 | __class__
003 | Hello World!
004 | __lt__
005 | True
006 | Traceback (most recent call last):
007 |   File "<string>", line 5, in <module>
008 | AttributeError: __lt__
floral meteor
#

either 005 or 008 is gammin

#

which one is it?

floral meteor
#

!e ```py
from ctypes import *
hack = lambda i:py_object.from_address(i)
class Dict(dict):
slots = ()
def setitem(self, key, value):
(()for()in((),)).throw(SyntaxError("can't assign to keyword"))if key=="Maybe" else super().setitem(key,value)
def delitem(self, key):
if builtins.import('sys').metapath is None:return super().delattr(key)
(()for()in((),)).throw(SyntaxError("can't delete keyword")) if key == "Maybe" else super().delattr(key)
def missing(self, key):
try:return builtins.getattr(builtins,key)
except:builtins.print(key,'DOES NOT EXIST')

class Maybe(metaclass=lambda _:type(_)()):
bool = lambda _: bool(import("random").randint(0, 1))
str = lambda : str(bool())
getattribute = lambda , v: bool().getattribute(v)

hack(id(globals())).value = Dict(globals())
hack(id(globals())+8).value = Dict
print(isinstance(Maybe, bool))
try:Maybe = 1
except SyntaxError:print('pass')
for i in range(5):
if Maybe:print(":D")
else:print("D:")
print(Maybe)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | pass
003 | :D
004 | False
005 | D:
006 | False
007 | D:
008 | False
009 | D:
010 | True
011 | :D
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/jowotocico.txt?noredirect

floral meteor
#

!e ```py
class quick_encode:
_h=8;index=int=lambda s:int(s.r);repr=str=lambda s:str(int(s.r))
def init(s,m:str):
while 1<<s.h<ord(max(m)):s.h+=1
r='1'(s._h-8)(s.h>8);b=[ord(c)for c in str(m)];d=[i for i in range((max(b)+2)//10)if any([t//10==i for t in b])];d+=[max(b)//10]
r+='2'10+'85'+'5'.join([t'2'for t in d])+'4'*len(d)+'395';j=0
for c in b:
a = c.divmod(10)
while a[0]>d[j]:j+=1;r+='5'
while a[0]<d[j]:j-=1;r+='4'
r+='2'*a[1]+'6'+'3'a[1]
_,
__=({
and(r:=r[:-1])for _ in iter(lambda:r.endswith('3'),False)},
{
and(r:=r.replace('23',''))for _ in iter(lambda:'23'in r,False)},{
and(r:=r.replace('32',''))for _ in iter(lambda:'32'in r,False)}
);s.r=r;print({print(end={'2':'+','3':'-','4':'<','5':'>','6':'.','7':',','8':'[','9':']'}[i])for i in r if i not in['0','1']}and'')
quick_encode("Hello World!")

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.
floral meteor
#

BEHOLD YE MIGHTY AND DESPAIR: BRAINFUCK GENERATOR

#

!e ```py
_dependancies = {'defaultdict':import('collections').defaultdict}
def decode(n):
l,a,o=len(s:=str(int(n))),_dependancies'defaultdict',str();i=p=a[int()];c=8;t=0
while len(s)>p:
def _2():a[i]+=1;a[i] %=1<<+ c;return i,c,o,t # %=1<<+
def _3():a[i]-=1;a[i] %=1<<+ c;return i,c,o,t # i made "coerce encoding" operator
_4,_5=lambda:(+i+ 1,c,o,t),lambda:(+i- 1,c,o,t)
_6=lambda:(i,c,print(end=chr(a[i]))or o+chr(a[i]),t)
def _7():a[i]=ord(import('sys').stdin.read(1));return i,c,o,t
_8,_9=lambda:(i,c,o,t+(not bool(a[i]))),lambda:(i,c,o,t-bool(a[i]))
_0,_1=lambda:(i,c+1%32,o,t),lambda:(i,c-1%32,o,t)
i,c,o,t=[_0,_1,_2,_3,_4,_5,_6,_7,_8,_9]int(s[p])if not t else (
i,c,o,t -(t >+ int()and s[p]=='9')- -(t <+ int()and s[p]=='8')
);p+=1-2 *+ (t <- int()) # i run out of fancy augmented operators :/ gimme more!
if p <- int():raise SyntaxError('mismatched 9')
return type('invisible_list',(list,),{'repr':lambda s:''})([ord(k)for k in o])

print(decode(22222222228522252222222522222222522222222225222222222224444439552263355262222222663333333352634444226335522222226333333355262226333342222222263333333364442226))

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

Hello World!
floral meteor
#

BEHOLD YE MIGHTY AND DESPAIR A BIT MORE: AN ARBITRARILY LONG INTEGER INTERPRETER

sick hound
floral meteor
#

the purpose is the encoding

#

i have encryption where the encrypted data is an array of integers and the decrypted data is an arbitrarily long integer

#

so the encoding and decoding allow for messages

floral meteor
#

!e ```py
CONVERSION = {1:'I',5:'V',10:'X',50:'L',100:'C',500:'D',1000:'M'}
def roman(n):
if n <= 0: return''
elif n in CONVERSION: return CONVERSION[n]
first, right, left = int(str(n)[0]), n, n # make temp variables
while right not in CONVERSION: right += 1 # get upper element
while left not in CONVERSION: left -= 1 # get lower element
if first==4:
return (5-first)CONVERSION[left]+CONVERSION[right] + roman(n - firstleft)
elif first==5:
return CONVERSION[left] + roman(n - left)
elif first in[8,9]:
uberleft = left - 1
while uberleft not in CONVERSION: uberleft -= 1
return CONVERSION[uberleft]*(10-first) + CONVERSION[right] + roman(
int(str(n)[1:]if len(str(n))>1 else'0')
)
else:
del right # ;-;
return CONVERSION[left]first + roman(n - leftfirst)
for i in range(1,20):
print(roman(i))

#

eh i'll fix 6 and 7 later

#

oh i need to make a case for in [6, 7]

#

do i have time? ... nope

jade fox
#

should i put this just inside init or create another function and call it?

        # Chromedriver - Settings
        options = webdriver.ChromeOptions()

        options.add_argument('--disable-blink-features=AutomationControlled')

        if self.config["use_proxy"]:
            options.add_argument(
                "--proxy-server={}".format(choice(self.config["proxies"])))

        if self.config["headless_mode"]:
            options.add_argument("--headless")
            options.add_argument("--disable-gpu")

        extensions = os.listdir("extensions")

        for extension in extensions:
            options.add_extension(os.path.join("extensions", extension))
snow beacon
#

If you want best practices, I'd avoid any advice in this channel.

untold sphinx
#

lol?

hollow kiln
#

!e

import time
string = "hmm"
for i in range(len(string)):
    print(string[:i+1].ljust(5),end="")
    print(string[:i+1].center(5),end="")
    print(string[:i+1].rjust(5),end="")
    print(string[:i+1].center(5),end="")
    print(string[:i+1].ljust(5),end="")
    print(string[:i+1].center(5),end="")
    print(string[:i+1].rjust(5),end="")
    print(string[:i+1].center(5),end="")
    print(string[:i+1].ljust(5),end="")
    print(string[:i+1].center(5))
    time.sleep(0.5)
for i in range(len(string),-1,-1):
    print(string[:i+1].ljust(5),end="")
    print(string[:i+1].center(5),end="")
    print(string[:i+1].rjust(5),end="")
    print(string[:i+1].center(5),end="")
    print(string[:i+1].ljust(5),end="")
    print(string[:i+1].center(5),end="")
    print(string[:i+1].rjust(5),end="")
    print(string[:i+1].center(5),end="")
    print(string[:i+1].ljust(5),end="")
    print(string[:i+1].center(5))
    time.sleep(0.5)
for i in range(len(string)):
    print(string[:i+1].ljust(5),end="")
    print(string[:i+1].center(5),end="")
    print(string[:i+1].rjust(5),end="")
    print(string[:i+1].center(5),end="")
    print(string[:i+1].ljust(5),end="")
    print(string[:i+1].center(5),end="")
    print(string[:i+1].rjust(5),end="")
    print(string[:i+1].center(5),end="")
    print(string[:i+1].ljust(5),end="")
    print(string[:i+1].center(5))
    time.sleep(0.5)
for i in range(len(string),-1,-1):
    print(string[:i+1].ljust(5),end="")
    print(string[:i+1].center(5),end="")
    print(string[:i+1].rjust(5),end="")
    print(string[:i+1].center(5),end="")
    print(string[:i+1].ljust(5),end="")
    print(string[:i+1].center(5),end="")
    print(string[:i+1].rjust(5),end="")
    print(string[:i+1].center(5),end="")
    print(string[:i+1].ljust(5),end="")
    print(string[:i+1].center(5))
    time.sleep(0.5)
night quarryBOT
#

@hollow kiln :x: Your eval job timed out or ran out of memory.

001 | h      h      h  h  h      h      h  h  h      h  
002 | hm     hm    hm  hm hm     hm    hm  hm hm     hm 
003 | hmm   hmm   hmm hmm hmm   hmm   hmm hmm hmm   hmm 
004 | hmm   hmm   hmm hmm hmm   hmm   hmm hmm hmm   hmm 
005 | hmm   hmm   hmm hmm hmm   hmm   hmm hmm hmm   hmm 
006 | hm     hm    hm  hm hm     hm    hm  hm hm     hm 
007 | h      h      h  h  h      h      h  h  h      h  
008 | h      h      h  h  h      h      h  h  h      h  
009 | hm     hm    hm  hm hm     hm    hm  hm hm     hm 
010 | hmm   hmm   hmm hmm hmm   hmm   hmm hmm hmm   hmm 
011 | hmm   hmm   hmm hmm hmm   hmm   hmm hmm hmm   hmm 
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/rucahaduvo.txt?noredirect

untold sphinx
#

What exactly mean 'esoteric'?

hollow kiln
#

topics in which a few people are interested in

#

like brainfuck language is an esoteric lang

untold sphinx
#

i mean it seems pretty interesting here..

hollow kiln
#

that's what it mean

#

👀

hollow kiln
untold sphinx
#

lol

hollow kiln
#

!e

ok = lambda x : '\n'.join([' '.join([str(j) for j in range(1,i+1)]) for i in range(1,x+1)]+[' '.join([str(j) for j in range(1,i+1)]) for i in range(x-1,0,-1)])  
print(ok(15))
night quarryBOT
#

@hollow kiln :white_check_mark: Your eval job has completed with return code 0.

001 | 1
002 | 1 2
003 | 1 2 3
004 | 1 2 3 4
005 | 1 2 3 4 5
006 | 1 2 3 4 5 6
007 | 1 2 3 4 5 6 7
008 | 1 2 3 4 5 6 7 8
009 | 1 2 3 4 5 6 7 8 9
010 | 1 2 3 4 5 6 7 8 9 10
011 | 1 2 3 4 5 6 7 8 9 10 11
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/amajujesah.txt?noredirect

hollow kiln
#

lmao BlobRainbow

quasi shard
untold sphinx
snow beacon
untold sphinx
snow beacon
#

If it's what most people want from their code, it's not esoteric.

untold sphinx
simple crystal
#

!e

(lambda*n:[print(x[1])for x in[[print(0)or 0,print(1)or 1]]for _ in [...]*n[0]for x[0],x[1]in[[x[1],x[0]+x[1]]]])(10)
night quarryBOT
viscid nymph
#

ah nice

rugged sparrow
#

!e py fib=lambda n,f=0,s=1:[[f,s:=f+(f:=s)][0]for()in[()]*n] print(*fib(10))

night quarryBOT
#

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

0 1 1 2 3 5 8 13 21 34
rugged sparrow
#

!e ```py
fib=lambda n,i=0,j=1:[j:=-j+(i:=j+i)for()in[()]*n]
print(*fib(10))

night quarryBOT
#

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

0 1 1 2 3 5 8 13 21 34
rugged sparrow
#

a bit shorter code

simple crystal
#

idk if it's wise but I want to have a rly ridiculous one ready to go if I ever actually get that interview question

#
(x[0] for x in [[id is ..., 0xf-15, 1]] for _ in iter(int, ...) for x[0], x[1], x[2] in [[x[1], x[2], x[1] + x[2]]])```
#

for example

cerulean rivet
#

how i can change the __eq__ in int class?

#

i tried this ```py
class new_int(int):
def eq(*_):
return "Nium"

int.eq = new_int.eq
builtins.int = new_int

print(1 == 2) # Nium

viscid nymph
cerulean rivet
viscid nymph
#

!pypi fishhook

night quarryBOT
cerulean rivet
#

hmm

viscid nymph
#
>>> from fishhook import hook
>>> @hook(str) 
... def reverse(self):
...     return self[::-1]
... 
>>> "Hello, World!".reverse()
'!dlroW ,olleH'
cerulean rivet
#
Traceback (most recent call last):
  File "c:\Users\Nium\Documents\Carbon\a.py", line 4, in <module>
    def __eq__(self, other):
  File "E:\Programs\Python\Python39\lib\site-packages\fishhook\__init__.py", line 222, in pwrapper
    hook_cls_from_cls(cls, type(f'<{id(cls)}>', (P,), body), **kwargs)
  File "E:\Programs\Python\Python39\lib\site-packages\fishhook\__init__.py", line 179, in hook_cls_from_cls
    update_subcls(subcls, pcls)
  File "E:\Programs\Python\Python39\lib\site-packages\fishhook\__init__.py", line 147, in update_subcls
    hook(cls, is_base=False)(body=attributes)
  File "E:\Programs\Python\Python39\lib\site-packages\fishhook\__init__.py", line 222, in pwrapper
    hook_cls_from_cls(cls, type(f'<{id(cls)}>', (P,), body), **kwargs)
TypeError: unhashable type: 'int'
Exception ignored on calling _ctypes.DictRemover:
TypeError: unhashable type: 'int'```
#
from fishhook import *

@hook(int)
def __eq__(self, other):
  return orig(self, other)

print(1 == 2)
snow beacon
#

When you override __eq__ it deletes any __hash__ implementation.

snow beacon
#

Because otherwise you could get an object where equality doesn't imply hash equality, which breaks dictionaries and sets.

#

Python dictionaries rely on a rule that if two things hash to different numbers, they must not compare equal to each other.

#

That lets it out things into pigeonholes based on hash value, which is why it's so fast to get dictionary values by key. It only has to check one pigeonhole, not every member of the dictionary.

viscid nymph
#

you could just make int.__hash__ return self

snow beacon
viscid nymph
#

nah fishhook defines a hook_cls function

#

Like this

from fishhook import *

@hook_cls(int)
class a:
    def __eq__(self, other):
        return "Nium"

    def __hash__(self):
        return self

print(1 == 2) # Nium
snow beacon
#

Cool, complications resolved.

cerulean rivet
#

hmm

astral rover
#

Can you return a non bool from eq?

viscid nymph
#

yes

simple crystal
#

i.e. with numpy arrays comparison operators give you a numpy array of bools

floral meteor
#

!e now that I have the algorithm i can think about golfing it```py
CONVERSION = {1:'I',5:'V',10:'X',50:'L',100:'C',500:'D',1000:'M',5000:'_V',10000:'_X',50_000:'_L',100_000:'_C',500_000:'_D',1_000_000:'_M',5_000_000:type('raise',(str,),{'add':lambdaa:1/0})('error')}
def roman(n):
if n <=- 0: return''
elif n in CONVERSION: return CONVERSION[n]
_0, _1, _2 = int(str(n)[0]), n, n # make temp variables
while _2 not in CONVERSION:_2-=1 # get lower element
CONVERSION[_2]+''
while _1 not in CONVERSION:_1+=1 # get upper element
if _0==4:return(5-_0)CONVERSION[_2]+CONVERSION[_1]+roman(n-_0_2)
elif _0==5:return CONVERSION[_2]+roman(n-_2)
elif _0==9:
_2-=1
while _2 not in CONVERSION:_2-=1
return CONVERSION[_2]+CONVERSION[_1]+roman(int(str(n)[1:]if len(str(n))>1 else'0'))
elif _0 in[6,7,8]:
_1=_2-1
while _1 not in CONVERSION:_1-=1
return CONVERSION[_2]+CONVERSION[_1]
(-5+_0)+roman(int(str(n)[1:]if len(str(n))>1 else'0'))
else:return CONVERSION[_2]_0+roman(n-_2_0)
for i in range(1,51):print(roman(i))

night quarryBOT
floral meteor
#

that should raise error by zero division instead of infinitely looping

#

This is a great visualisation of tail end recursion!

#

Its sort of... parallel

simple crystal
#

I wrote a ruman numeral decoder in haskell

rome_to_int numerals = sum . subtract_numerals $ convert_numeral <$> numerals
    where
        subtract_numerals (n:ns)
            | null ns = [n]
            | n < head ns = head ns - n : subtract_numerals (tail ns)
            | otherwise = n : subtract_numerals ns
        convert_numeral n = case n of
            'I' -> 1
            'V' -> 5
            'X' -> 10
            'L' -> 50
            'C' -> 100
            'D' -> 500
            'M' -> 1000

is the subtract numerals function tail end recursive?

floral meteor
#

yes

simple crystal
#

sweet

#

thanks

#

not sure what it is still but that will help haha

floral meteor
#

I think so

#

it returns from there, right?

simple crystal
#

it returns [head] when the tail is empty

floral meteor
#

tail end means the self call modifies the return value

simple crystal
#

it basically iterates through the list from head to the end of the tail and does stuff until it reaches the final item

#

the self call is passed the remaining tail

#

that needs processing

floral meteor
#

!e ```py
def fib(n, a, b):
if not n:return[a]
else:return[a,*fib(n-1,b,a+b)]
print(*fib(10,0,1))

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

0 1 1 2 3 5 8 13 21 34 55
simple crystal
#

yeah like that

floral meteor
#

hang on, must golf

#

wait its longer to tail recurse from lambda

#

oop

simple crystal
#

ah so if the statement in the head of the recursion does further processing of the returns from the recursions then it's not tail end recursive

floral meteor
#

!e ```py
g=lambda:globals()['f'];f=lambda n,a,b:n and[a,*g()(n-1,b,a+b)]or[a];print(*f(10,0,1))

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

0 1 1 2 3 5 8 13 21 34 55
floral meteor
#

depends, really.

simple crystal
#

yeah now I'm wondering how haskell : operator works

floral meteor
#

if you can write it in tail end form, then its tail end

#

thats what i think, anyway

simple crystal
#

since haskell is lazy I think it would end up being tail end cuz each step in the list would be fully generated before the function recurses

#

I sorta wish python had better support for recursion

#

also haskell is as pretty as python to me, I think I love semantic whitespace >_>

floral meteor
#

!e ```py
_00 = lambda _0:import('ctypes').py_object.from_address(id(_0)+8)
_01 = [...,type,str(),tuple(),dict]
_02 = lambda _0:(lambda _1:setattr(2:=(lambda*:None),'code',_1._getframe(_0+3).f_code)or _2)(import('sys'))
_00(_01[0]).value = _01[1](_01[2],_01[3],_01[4](call=lambda _0,_1:_02(_1)))

_10 = lambda _0,_1,_2:_0 and[_1,...(0)(_0-1,_2,_1+_2)]or[_1]
_11 = (20,0,1)
_12 = print
_12(
_10(*_11))

#

there you go, unreadable fibonacci generator

simple crystal
#

lol nice

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | <string>:7: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
002 | 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
floral meteor
#

with a syntaxwarning for bonus

simple crystal
#

now memorize it for interviews

#

lol ur storin it in the ellipses struct eh

#

...does pyobject value setter work like that?

#

or is it just an arbitrary object

#

ah yep ur replacin ellipses

floral meteor
#

py_object.from_address(id(_0) + 8) is _0's class

#

technically, ellipsis itself is still the same object

#

i just changed what class its class references point to

#

i think it might affect slots too

simple crystal
#

ah

floral meteor
#

note, dir() calls an object's dict and class to get its data

simple crystal
#

yeah

floral meteor
#

unless you've setattred after instantiation, dict will be empty, it'll get its data from its class

simple crystal
#

n vars gives you just the dict of the object itself

floral meteor
#

dunders set in dict will not be slotted, hence they will be "impotent"

simple crystal
#

yeha u need to do the fishhook stuff to mess with the dunder slot points

#

or some other sort of monkeypatching

floral meteor
#

!e ```py
try: ...._=...
except Exception as :print()
from ctypes import py_object as __
=lambda _:.from_address(id()+8)
___(...).value = type('...',(),{'niam':...})
print(f'{....niam=}')

simple crystal
#

you're changing what class is pointed to by the ellipses literal

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | 'ellipsis' object has no attribute '_'
002 | ....__niam__=<__main__.... object at 0x7fe986fd0440>
simple crystal
#

but technically u could store the old class before replacing it and still access it

floral meteor
#

that's right

#

in fact, if you don't there's a chance you'll exit code either 137 or 0xc0000005 ("negative a billion and a bit")

#

to prevent that, make an object whose __del__ attribute 'unhacks' it

simple crystal
#

so when it gets GCed it pops back?

floral meteor
#

!e ```py
try: ...._=...
except Exception as :print()
from ctypes import py_object as __
=lambda _:.from_address(id()+8)
_(...).value = type('...',(),{'':...,'repr':lambda :'....'})
print(f'{....
=}')

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | 'ellipsis' object has no attribute '_'
002 | ...._=_....
floral meteor
simple crystal
#

oh wow u can change list literal class from id of empty list literal

#

o.O

#

!e

f = list.__getitem__
class new_list(list):
    def __getitem__(self, item):
        print('a')
        return f(self, item)

from ctypes import py_object

a = py_object.from_address(id([])+8)
a.value = new_list

b=[1]
b[0]
night quarryBOT
#

@simple crystal :x: Your eval job has completed with return code 139 (SIGSEGV).

a
simple crystal
#

sigsegv tho

floral meteor
#

yeah ill show you how to get rid of that

simple crystal
#

sweet

floral meteor
#

!e ```py
from ctypes import py_object as __
=lambda _:.from_address(id()+8)
class gulag(metaclass=lambda*a:type(*a)()):
prisoner = ___([]).value
def del(self): ___([]).value = self.prisoner
f = list.getitem
class new_list(list):
def getitem(self, item):
print(item)
return f(self, min([item,len(self)-1]))
___([]).value = new_list
b = [1]
b[1]

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

1
floral meteor
#

see, exit 0

simple crystal
#

so it tries to GC gulag and that prevents the segfault?

floral meteor
#

it successfully GCs gulag

simple crystal
#

and the metaclass of gulag needs to take *args?

floral meteor
#

the metaclass takes name, baseclasses and namespace

#

*a is just a lot shorter

simple crystal
#

...isn't that just type?

floral meteor
#

it is type, but called on the spot

simple crystal
#

it works without it haha

#

ok

floral meteor
#

so... instead of gulagtype you get gulag object

#

it needs to be instantiated in order for __del__ to work

simple crystal
#

ah

#

well that's definitely easier than what fishhook does

#

tho more hacky and mysterious

floral meteor
#

if you want a "hard exit", i.e. uncatchable error, you can also use this

#

this hard exit will exit code my favourite exit code, which I call "negative a billion and a bit"

simple crystal
#

!e

from ctypes import py_object as __
___=lambda _:__.from_address(id(_)+8)
f = list.__getitem__
class new_list(list):
    def __getitem__(self, item):
        print(item)
        return f(self, min([item,len(self)-1]))
    def gg(self):
        print('gg')
___([]).value = new_list

b = [1]
b[1]

b[0]

works fine tho hmmm

night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

001 | 1
002 | 0
floral meteor
#

0xc0000005

#

although this bot wont exit 0xc0000005

simple crystal
#

alsot he gg thing segfaultedwhen called even with gulag fully intact

#

!e

from ctypes import py_object as __
___=lambda _:__.from_address(id(_)+8)
class gulag(metaclass=lambda*a:type(*a)()):
  prisoner = ___([]).value
  def __del__(self): ___([]).value = self.prisoner
f = list.__getitem__
class new_list(list):
    def __getitem__(self, item):
        print(item)
        return f(self, min([item,len(self)-1]))
    def gg(self):
        print('gg')
___([]).value = new_list
[].gg()
night quarryBOT
#

@simple crystal :x: Your eval job has completed with return code 139 (SIGSEGV).

gg
floral meteor
#

!e ```py
from ctypes import py_object as __
=lambda _:.from_address(id()+8)
class gulag(metaclass=lambda*a:type(*a)()):
prisoner = ___([]).value
def del(self): ___([]).value = self.prisoner
f = list.getitem
class new_list(list):
def getitem(self, item):
print(item)
return f(self, min([item,len(self)-1]))
def gg(self):print("gg")
___([]).value = new_list
b = [1]
b.gg()

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

gg
floral meteor
#

it's pretty sensitive

simple crystal
#

so the empty list literal is weird?

floral meteor
#

yeah

#

!e ```py
from ctypes import py_object as __
=lambda _:.from_address(id()+8)
class gulag(metaclass=lambda*a:type(*a)()):
prisoner = ___([]).value
def del(self): ___([]).value = self.prisoner
f = list.getitem
class new_list(list):
def getitem(self, item):
print(item)
return f(self, min([item,len(self)-1]))
def gg(self):print("gg")
___([]).value = new_list
b = []
b.gg()

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

gg
floral meteor
#

no

simple crystal
#

!e

from ctypes import py_object as __
___=lambda _:__.from_address(id(_)+8)
f = list.__getitem__
class new_list(list):
    def __getitem__(self, item):
        print(item)
        return f(self, min([item,len(self)-1]))
    def gg(self):print("gg")
___([]).value = new_list
b = [1]
b.gg()
night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

gg
floral meteor
#

you just gotta store it

simple crystal
#

ah

#

cuz it gets GCed and then it doesn't know wtf is going on

floral meteor
#

!e ```py
from ctypes import py_object as __
=lambda _:.from_address(id()+8)
class gulag(metaclass=lambda*a:type(*a)()):
prisoner = ___([]).value
def del(self): ___([]).value = self.prisoner
f = list.getitem
class new_list(list):
def getitem(self, item):
print(item)
return f(self, min([item,len(self)-1]))
def gg(self):print("gg")
___([]).value = new_list
[1].gg()

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).

gg
simple crystal
#

?

rugged sparrow
#

The reason the empty list works like that is due to the internal free list

floral meteor
#

so why does [1].gg() sigsegv regardless of gulag, but b = [1]; b.gg() not sigsegv?

simple crystal
#

ah cool

rugged sparrow
#

Depends on the cause of the sigsegv

simple crystal
#

so [] is basically preinititialized as the free list of len 0

rugged sparrow
#

Could be something unrelated to that line that happens in the background

floral meteor
#

but that line is the only difference

rugged sparrow
#

Basically the free list contains a list of length zero

floral meteor
#

and the gulag has no effect

rugged sparrow
#

And since you don't store it the same list can end up back in that slot

floral meteor
#

except for dunders

simple crystal
#

ah

rugged sparrow
#

!e py print(id([])) print(id([]))

night quarryBOT
#

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

001 | 140520426963008
002 | 140520426963008
simple crystal
#

...and short list literals also end up in free list slots when unused

floral meteor
#

!e print(id([]))

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

140249643524160
simple crystal
#

lol lancebot hates my ellipses

floral meteor
#

!e ```py
print(id([1]))
print(id([1]))
a = [2]
print(id(a))
print(id([2]))

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | 139715407528000
002 | 139715407528000
003 | 139715407528000
004 | 139715407691072
floral meteor
#

wat

simple crystal
#

hmm when I make a bit list literal it still sfs

floral meteor
#

i wasn't expecting that result

#

!e ```py
magic = 139715407691072 - 139715407528000
print(magic)
a = id([1])
b = [2]
print(id(b) == a)
print(id(b) + magic - id([2]))

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | 163072
002 | True
003 | -64
floral meteor
#

64 off

simple crystal
#

!e

from ctypes import py_object as __
___=lambda _:__.from_address(id(_)+8)
f = list.__getitem__
class new_list(list):
    def __getitem__(self, item):
        print(item)
        return f(self, min([item,len(self)-1]))
    def gg(self):
        print('gg')
___([]).value = new_list
g = [0]
g.gg()
f = [0]
f.gg()
night quarryBOT
#

@simple crystal :x: Your eval job has completed with return code 1.

001 | gg
002 | Traceback (most recent call last):
003 |   File "<string>", line 14, in <module>
004 | AttributeError: 'list' object has no attribute 'gg'
simple crystal
#

it loses the attr

#

hmm

#

!e

from ctypes import py_object as __
___=lambda _:__.from_address(id(_)+8)
f = list.__getitem__
class new_list(list):
    def __getitem__(self, item):
        print(item)
        return f(self, min([item,len(self)-1]))
    def gg(self):
        print('gg')
___([]).value = new_list
g = [0]
g.gg()
___([]).value = new_list
f = [0]
f.gg()
night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

001 | gg
002 | gg
floral meteor
#

I think if a list is used temporarily, it reuses the same id

rugged sparrow
#

by doing a list literal and not storing it, you are grabbing the top of the free list, using it, and returning it

simple crystal
#

what if it's over 20 items long?

floral meteor
#

!e ```py
a = id([1])
b = [2]
print(id(b) == a)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

True
floral meteor
#

this is cursed

rugged sparrow
#

!e py print(id([1,2,3,4,5,6,6,7,8,9,19])) print(id([]))

night quarryBOT
#

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

001 | 140507869679680
002 | 140507869679680
simple crystal
#

!e

print(id([]))
print(id([*([0]*100)]))
night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

001 | 140688979599424
002 | 140688979599424
simple crystal
#

ah it is always the free list

floral meteor
#

!e ```py
print(id([1]) == id([2]) == id([3]))

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

True
rugged sparrow
#
do_something([]) # gets the top of the free list and acts on it
# after this, the list is cleared and marked as free and and returned to the free list
do_something_else([1,2,3]) # again gets the top of the free list, the same object as the first```
floral meteor
#

you could "hack" several positions in advance

rugged sparrow
#

yes you could

floral meteor
#

could you?\

#

how would you predict it?

rugged sparrow
#

it is easier to hack the list type as a whole

#

like this

floral meteor
#

my last prediction was 64 too low

simple crystal
#

!e

p = lambda x:print(id(x))
a= [0,1,2]
s=[0]
p(s)
p(a)
a=[0]
p(a)
p([0,1,2])
night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

001 | 140032614841664
002 | 140032614678592
003 | 140032614842304
004 | 140032614678592
simple crystal
#

re-using stored free list I think

floral meteor
#

lol it thonk too hard

rugged sparrow
#

it is possible to get the amount of lists on the free list

#

one sec

#

you can read it from source

#

the reason you cant easily at runtime is because the free list gets refilled

simple crystal
#

ah it's just the order they're conjured from free list

#

!e

p = lambda x:print(id(x))
a= [1,2]

s=[0]
p(s)
p(a)
del s
a=[0]
p(a)
p([0,1,2])
night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

001 | 140522382617920
002 | 140522382454848
003 | 140522382617920
004 | 140522382454848
cerulean osprey
#

!e

from random import randrange,choice
while True:print(chr((randrange(ord("A"),ord("Z")+1) if choice((True,False)) else randrange(ord("a"),ord("z")+1) if choice((True,False)) else randrange(ord("0"),ord("9")+1))) if choice((True,False)) else " ",end="")
night quarryBOT
#

@cerulean osprey :x: Your eval job timed out or ran out of memory.

     m HZ   Pd  P 7DG0f72U   z jEG 0ya2U  N   V   W   g  J Brb 2 97 G  D 3 7   J 8  NT    JM bq   0J5QQY  O nmFDY    e  4 Ww 7    75  2 8 V X Q    c   J24Un FDI  2ip   G P   6Zx   F  am7   MQ G     sHN X   48   6 o   C  N7R 8   C 44WMl4  K B 1 w  3  P WP  W   J   B  F j y9  1   k2  T pd   Bm  BYvc  Q  5 2     L  W  3  c  U   T  S    C   8h  L Pe  oB1  P     1eC  O3kd Ns O J  MG k nI  u N sZH     m  5eH   8RUx  6 T Q O6  4F   SFUu o 6  J   yf9   Q  QVaX   13s 6   D4   e1  L5 K 8   2lQVmcN3  UI  T7   jE3 M      Y1   X  DW     Tqy  KX6KN1CH  WZPj   Yo8 r3  Rsgj     k Z Q 3h  x Qox n 6s4y T m    M WQ   7 8     HMZ        J    B HapPi   ZSk i3 V3 tk    T  KM Y I Kv  P W 7    YAI     I  0  q  jm 6  G25   ESWJ5 r 4H 7  XxMVf   oRGTI    p2M  V  JXQ    4 9jhDtp    T 9M 3B  e    w M WYP  P8NK 1B Zq TC PY5 7   L Ec15k TK 2 wC    NKn RN      i  RG X R     7A  B978x  NR  Gjh2PKG   M m 0 0elVN       b  D9AR vA4D Yu6eJ  LUpU TYns   8  j2  3l2M  35b F   K1H   A vz    85K   7aT 6K  F    K    aIK2  I  6
... (truncated - too long)

Full output: too long to upload

cerulean osprey
#

!e

from random import randrange,choice
while True:print(chr((randrange(ord("A"),ord("Z")+1) if choice((True,False)) else randrange(ord("a"),ord("z")+1) if choice((True,False)) else randrange(ord("0"),ord("9")+1))) if choice((True,False)) else " ",end="")
night quarryBOT
#

@cerulean osprey :x: Your eval job timed out or ran out of memory.

  hY5    yt C  g Y     D6LS     D 1Z   4 3H5 38v fy E 0 ICLN  h  8 D4u51 Wy Xy GPU2 j 42ZP sK6f ce  I05  V   JDB     62Q5O9 JMee 6z fq2X  2  iN  G3 p NgEC        u WE W  T     h 8 v  LH   9    z  ra  AL  D H kYw1  6y   d r QH     ZNA1D  t 2v Oh04H Q   o  h0L    2t 5a 5WK H kz g       GIZQ   2y9yQ D 9 q  5  Q 4  T 2 8Y HH   P         xVE    g1    7 NI ND28 I qOQ7d X  5   i  3 C TB  Q NK nEV  N5NB 6  2 F  Zb q TOV   2PhZ4 M   2m k  C F  PC477 y FH6q    G    Mw OZC   S c z m  ADYqm    5  b  QR nMD9 809 5  ZP7 An  ytA 2U3W RJF 6D lWQ 333   JZ   j      F 0h  c 0 SSx T E  80   MK 4  vK y  U aiA       T12 u OA1  F   AO    I 0K   n23wF  wl BZgZe6fT N 8   mdH9Gk  T Ep   253 yQ B  BM   51Hx 4WHE 9q A 0 N     1   W      Kk W IGY   0i     3G 2L5  FV   UXlGl  J4 8r Y FEAE rp Y  2C  1     BGO       vV 9R7 6WW   3 P  PEN   P b  EO Z C O8  HL4MtLt dL    3RKq DGe  C f4P   7 lC  H      1     Tp n3  T4 V  S  6     jS  CQ   Pp Q   VH W V  Y  L   E  dI   65tj   Pc  kd 8  u MT 7CG9  K S  Z 7Fg3 XtQ2 40   B7
... (truncated - too long)

Full output: too long to upload

cerulean osprey
#

!e

from random import randrange,choice
while True:print(chr((randrange(ord("A"),ord("Z")+1) if choice((True,False)) else randrange(ord("a"),ord("z")+1) if choice((True,False)) else randrange(ord("0"),ord("9")+1))) if choice((True,False)) else " ",end="")
night quarryBOT
#

@cerulean osprey :x: Your eval job timed out or ran out of memory.

 8V3  vP  V  3K 1 WXIi7    VQ  38    l    XO IF Di   kQp 2 mzMfP  3DTjfB    e C    d R  4    R G  o 9w    NW  l u6 1j wz  T   G64   i   1LLW03Kwy F       vJ  9KBnN X    S   W2N8J h LQC 4h 2g  a0w 95N  MxA        L Q so 2 L e M9nO Yy4 Wn6x MVBB  Y  Ods 46Gh  4Jx   J LpH      5eJ    X    zX  E   5 EkyY E n 6 S u2 N  Gw X8 H 5HZR    1  vx  bUl b     dYE4 5Fe 81 i 5 YYJ N   ZaCF hP    W  mMJ I zA2 8F  5  F c  NAN9H u   5 f N  b8  6p  w2   ECwG8W e    oN 1S  J5 D n  Y  R  W D M6J   iBY 0  Y  P 9L D H 6  5H6 D x4 Rd h X L  n B    Y  KgA  i   jYN8  A T  L7Zv       D3 P   G  o d59      u7     jN   ZR   c33   V1 0       yj Y0 y3 JJ B     PpF 7N ne  3 63 m 7   ZaP F34O t   9 S1 N 4y fY  2 2 3r z41   Rn 1   Q  ZS   Q2Z Fu 70  3YSz7    Y97Y 1  JV    W  N 0 29 k IZ3  t  6R    ZD TV  na T cL 5 w 4N Y 2AsC  k9 3K 5 SEl G     I    3   t   x G e  O 7 1   23    75W KjM5S  M  Qn     S  w4 1T6  KCC    lL     7ES        3       oUb F98U  6Oh6IOO0    9 E  4   PZS4   CF  H  Q z j     iP1 3         Nc 4w b 7B
... (truncated - too long)

Full output: too long to upload

cerulean osprey
#

!e

from random import randrange,choice
while True:print(chr((randrange(ord("A"),ord("Z")+1) if choice((True,False)) else randrange(ord("a"),ord("z")+1) if choice((True,False)) else randrange(ord("0"),ord("9")+1))) if choice((True,False)) else " ",end="")
night quarryBOT
#

@cerulean osprey :x: Your eval job timed out or ran out of memory.

mNE u   RL Gz rDg NS FO2W5 S T  E       53ce  NIVf IF0  RjXhQTL93      Jz  z  I9        8 U  0f   f     K 9Dt4V  y 36    P  G wY  s  3vC 4FT 9 3 R  C   T09         8 pGS  C  s1 r9M T 15I 8 2D B    K          S   tP  a   0      5   f   Hgh j  PTB  Y  D I  8   C KS33 U H    rHg B n 3CiQ   l   QK1GPN  n7  sdCsWU0       T m  H9   Je  l 83I 7 g 10 G3 LFRP  M  U rW AbNH  I ea5D  JaC   qyUV Z        u  H  uk N 26m20 sB      HH     6       S 36V7  v e  ZxR  l  PQ  1   D f 1P   g   Ix   W   HDeO Lw OQD bG7N s 59   C TBSr     X       p5M 1PHOP 4    H 4    u  X q  Q  A QU 4C q  7V51hx R    UILUZ    7j  W    teJ Y2C A  E  B4  J q45j 5UIPvNG t I 3vJX 3   E  cE    X 33 PS 65  Q K  N     Z7P   F A8 V44c3v J  AW wrWU  55 oif  WQ   SQUCk ZDV4   hY9    j  8t  VR  BY   IA   83 B B h   VG C  ZC13J   t T  5HI 2R  T0 C77   aSkYv7  MVW Mi   F  S 3 XUr 5 SB   q  iHZB K    k8     89   dBX E  IN     KZ dE  F a  z     aCQe     2Mx f  PF8  zq  E   H    7    76 6K Ald LY   8Y1F FeJ j Ld1U SE  YKr lzR     x   Os 2 
... (truncated - too long)

Full output: too long to upload

cerulean osprey
#

!e

from random import randrange,choice
while True:print(chr((randrange(ord("A"),ord("Z")+1) if choice((True,False)) else randrange(ord("a"),ord("z")+1) if choice((True,False)) else randrange(ord("0"),ord("9")+1))) if choice((True,False)) else " ",end="")
night quarryBOT
#

@cerulean osprey :x: Your eval job timed out or ran out of memory.

  7  D  6 ZB CZ    R  qS2 OdLj p  3 21PeI     h o     V c  dP4T L  O9P  Xz i   Pn      KC S EiRz3D yJ   M Bf v  fl  9   5 N   HN bO b j L  VBK  MV 8   P   f O1 e8    y cvSO   0wsA N B3X       HuC0a     cv98   d  f 7Q3T     U  T   1 G   K W7 7pw  85   z   F XWhz40 zZ2   L  ELJ V  2 j LNDR   H 9  VJ   0  e      Y  U    Z i4  TOO  L3zq   8    M4k PSi7 j 5s   ub0D    X0  B  jV7A  5 9kz       2 q    RB C5j G  F7 0 9       37   L6     q 1 6 w u V   5v s7W    7 1 5 3  On4i dX JR 5  z  K  f v 3 g      2 z   WS 2 F9I1 0  L  nbAEN1  q 1F x2Y  Z   A m    32  I S4 R ci gY br3    BL RG     9 zqh6 I   ACV3F o  wypY   O e860 5D MS   N aO   q 0UB Px3zY    S C M e0e   O    L qG  5 g1  nMWAf 59 0       z  6 7 Lt  2   OZ9  C u wWH K 8 OD 23 4rA 5 52X2 3H L  V j UXg L I 4FJ  1 W    Y     3 DB0  P P JD a G8Lzd 7y  re   P  A b     2 D 6W XHnM  9  mYp0 Dn   Y  O  BB B 1  2    Ke  a   w  2IF 7vJ0I  r Z  7V   x U      H3  M     W  P      x  y 71   X  9P I5  U K   Z8 U8q  X vs X yX   d  VRt F    7 TCZ zNP  0y  
... (truncated - too long)

Full output: too long to upload

floral meteor
#

how about a bit of punctuation?

#

!e ```py
from random import*
while...:print(end=choice((' ',choice((chr(randrange(33,126)),str(choice((0,1))))))))

night quarryBOT
#

@floral meteor :x: Your eval job timed out or ran out of memory.

     1 1S/:   Z   1@ 1r1  k     01W L  0R  wT      A1 "00i O%0 0  |Q[0J j\1 1  1  1    ];}g  { 0 R(  0c    (;   1 1 ! 0 n$   aU1w   701 d 0Y 9P1 0 011 " )   z    00<ek00   `   ^ u    m   a0 l1 (0'0 v0    J  1   u 0 00  $  1\M110 rN    <1   0f _0   P>*$0f    1 010m          q f1 01 ] ts 1   D10 0!  1   001{s10 0;  ed    11 000    / g  '   0 &1    XF  10   0 M  k11A >010K   0 ,%0   0N   %S 1 S0  170     1  ] 0gN 11\14 M     n 0{]1   00 11  1 ;k   1  0 Y01O     h0 1I  nS  s   Q   sI01    1w 1f  0    }H 1 1 0 y1  1 07qio .    0    b0 n  070110x  l0 Yk  110 0  1`"K' _{c11   j   V0 8  1  1h 0 00F[0c  1   10 0O HR &1U| e ql 1 0&0 ` 1  1 0   L%,  1 0g1   R J011_0   0 0N1 0    M0   z0 0 0?Ox+ /  B0 ny0&0=3 1  IB D 1  P 1 0< "0  l00 00   B !m0MFK   00gw1     1  1@ 1 0 1101 0 > 1 ;` 0(;    0Z} 0?  ?|    0 )00  "  0k    1 04<         11  = .  0  ` , 0x    {   e 1 O{ 11 B  0 0   1uR9  1       01L1\0 1 1 0  0 x 1x    \=1a0000m" d11\ "1xrb du     10   1  c  01  00(-F fq 1 J    n S   5  [Ba   1 > } 0^
... (truncated - too long)

Full output: too long to upload

sick hound
#

this estoric python is beyond of my understanding

simple crystal
#

lol it just prints random stuff

floral meteor
#

!e ```py
d = {}
for i in range(128):
d |= {i:chr(i)}
class cursed(metaclass=lambda*a:type(*a)()):
def eq(self, other):return True
def hash(self):
return hash(self.index())
def index(self):
from random import randint
return randint(32,126)
for i in range(200):
print(end=d[cursed])

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

wNCT||Qy%5[cys]ykC=qzTKRq'\Nn6d_&dbif,$cNpDSS%gG.TF>%;wPkAz;H^m>?7lSodP" x=MC1~#".qM#O%W*qqEMf^wz2=x5XY{ME{mdba\Rp'~yW5m'tsFRS[[?5^=7zb7tgI;t[99sC]!rZP.=nY^[O}xeGFNRy|$QdHT^g*,}#v(|9=&NXWn]}8Gj'(0V:~L
floral meteor
#

well that works

#

IT"S QUANTUM COMPUTING CHANGE MY MIND

#

!e ```py
class qubit(metaclass=lambda*a:type(*a)()):
def eq(self, other):return True
def hash(self):
return hash(self.index())
def index(self):
from random import randint
return randint(0,1)
d = {0: lambda:print('Cat is alive'),1: lambda:print('Cat is dead')}
for i in range(20):
dqubit

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | Cat is alive
002 | Cat is alive
003 | Cat is alive
004 | Cat is dead
005 | Cat is dead
006 | Cat is dead
007 | Cat is alive
008 | Cat is alive
009 | Cat is dead
010 | Cat is dead
011 | Cat is dead
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/terirovedu.txt?noredirect

floral meteor
#

SCHRODINGER'S CAT I HAVE MAED QUANTUM FYSICC

alpine flower
floral meteor
#

Ik

#

It's pseudorandom

alpine flower
#

Actually slightly off topic but ik there’s a way to send requests to a quantum computer to run code

floral meteor
#

Ideally, I'd make random by accessing videos of grocery store checkouts, and return 1 if they want receipt and 0 if not

alpine flower
#

(Qiskit)

#

Or make like a hamster maze with sensors

#

And a ton of hamsters

#

That seems like more fun than videos

sick hound
#

Hey guys Im trying to create a function that checks if the fifth and third part of a list are equal to its first

#

EVen after debugging several time