#esoteric-python

1 messages · Page 110 of 1

fluid tree
rugged sparrow
#

the closure is only added if __class__ is requested inside of a class method

#

!e py class A: print(__class__)

night quarryBOT
#

@rugged sparrow :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 2, in A
004 | NameError: name '__class__' is not defined
rugged sparrow
#

^ this fails because of that

#

!e py class A: def __init__(self): print(__class__) A()

night quarryBOT
#

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

<class '__main__.A'>
rugged sparrow
#

due to this being done by the compiler like this, it means that classes constructed using metaclass(name, bases, namespace) cannot use the "magic" __class__ variable without needing extra work

astral rover
#

Wtf

#

So you don't need to self.class if you're in a method?

rugged sparrow
#

self.__class__ can be a subclass of the class you are defining

#

__class__ will always be the class you are defining

fluid tree
rugged sparrow
#

it tells python to add a closure there. the actual __class__ closure is filled inside __built_class__ i believe

astral rover
#

Anyone here actually know how to use build_class?

#

I couldn't figure it out

frigid wharf
#

look at the channel description

Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness
stark fable
#
s=lambda a:lambda b:lambda c:a(c)(b(c));k=lambda a:lambda b:a;factorial=lambda a:s(s(s(s(k)(k))(k(s(s(k(s(s(k(s))(s(k(k))(s(k(s))(s(k(s(s(k)(k))))(k)))))(k(k))))(s(s(k(s(s(k(s))(s(s(k(s))(k))(k(s(s(k)(k))(k(s(s(k(s))(s(k(s(k(s))))(s(k(k)))))(k(s(k)(k)))))))))(k(k(k(s(k)(k)))))))(s(s(k)(k))(k(k))))(s(s(k)(k))(k(k(s(k)(k)))))))(s(k(s(s(k(s))(s(k(s(k(s))))(s(k(k)))))(k(s(k)(k)))))(s(s(k)(k))(k(k(s(k)(k)))))))))(k(s(s(s(k)(k))(k(s(k)(k))))(k(s(k)(k))))))(k(k))((lambda a:a(a))(lambda a:lambda b:(lambda c:lambda d:a(a)(b-1)(c)(c(d)))if b else lambda a:lambda a:a)(a))(lambda a:a+1)(0)```
#

aside from failing on anything >= 6, this is a completely valid and working definition of factorial

acoustic gust
#

wtf is this......

shadow quest
loud flicker
#

HOW DO YOU SAY HELLO WORLD

floral meteor
loud flicker
#

FACTS

#

Print "hello world" doesnt work

snow beacon
floral meteor
#

ik

#

So I was doing my usual esoterically making cool stuffs, but then this random line is giving me IndexError for no reason so I decided to use that as an extra random factor to change the colour instead of trying to debug it.

import os,sys;os.system('')
green_resmon=__import__('hexspam').print_green
def _init():
 w = os.get_terminal_size()[0]
 from random import randint as r
 a = [r(0,1)*r(0,1)*r(0,1)*r(0,1)for _ in range(w)]
 from functools import reduce
 return locals()
@lambda f:lambda:f(_init())
def matrix(__l):
 print(__l)
 a,r,reduce=__l['a'],__l['r'],__l['reduce']
 while w:=os.get_terminal_size()[0]:
  w>len(a)and a.extend([r(0,1)*r(0,1)*r(0,1)*r(0,1)for _ in range(w-len(a)+1)])
  w<len(a)and(a:=a[:w])
  try:
    if reduce(int.__mul__,[r(0,3)for i in range(w//16)]):a[r(0,w)]=r(0,1)*r(0,1)*r(0,1)*r(0,1)
  except:print(f'\x1b[{r(30,37)}')
  @print
  @lambda f:''.join([chr(f(a,i))for i in range(w)])
  def s(a,i):return r(33,127)if a[i]else 32
if __name__=='__main__':
 try:matrix()
 finally:print('\x1b[0m')
snow beacon
#

Which line?

floral meteor
#

The one where reduce is used

#

But it hasn't changed colour for a long time now

#

Also that script occasionally has a line that's just... out of place

#

also, when i make the window smaller, it goes faster

#

oh cool it turned purple now

snow beacon
#

It because random.randint is inclusive.

#

When random.randint(0, w) chooses w, that's outside of a, which has length w.

floral meteor
#

Thank you it works beautifully now

olive stag
#

can someone help me with this program

floral meteor
#

since you asked in the esoteric python channel...

floral meteor
#

!e ```py
{print(f"the cube root of {a} is {a**3}")for c in iter(lambda a=int(input('Enter a positive number, or a negative to quit')):a<0,True)}

#

that should work @olive stag

olive stag
#

was i supposed to ask in a different channel i don’t understand this or discord 😭

earnest wing
stark fable
fluid tree
stark fable
#

no it doesn't

sick hound
#

there is python syntax \ which indicates that a statement is continued on the next line, but is there syntax to indicate that a statement should be broken up to two lines?

print(1) | print(2)

_______outputs_______
>1
>2 
earnest wing
#

;

fluid tree
fluid tree
sick hound
#

What is the least used keyword in python? monkaHMM

proper vault
#

likely lambda

#

or maybe __peg_parser__/__debug__

#

also nonlocal

sick hound
#

I use and like lambda WolfCry

proper vault
#

there are very few cases for lambda

sick hound
#

But yeah, nonlocal is unusual

viscid nymph
fluid tree
#

Wait

#

They are?

proper vault
#

__peg_parser__ is, __debug__ is a bit more questionable, but since it isn't a variable name, I would call it a keyword

tribal moon
#

!e py import keyword print(keyword.kwlist)

night quarryBOT
#

@tribal moon :white_check_mark: Your eval job has completed with return code 0.

['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
frigid wharf
#

does __peg_parser__ do anything except raising a SyntaxError?

astral rover
#

Don't think so

astral rover
proper vault
#

well, obj.__debug__ is possible, but obj.None isn't

astral rover
#

Hmm

#

Ig so then

proper vault
#

it also isn't in keywords.kwlist

viscid nymph
#

Well we can't judge keywords that way 👀

proper vault
#

those are soft keywords

#

they are possible since 3.9 and exist since 3.10

cosmic night
#

idk if right place for this, but anyone have experience with monad libraries in python? most fleshed out one i could find is returns https://github.com/dry-python/returns/blob/master/README.md. Particularly interested in Final Tagless or Effect Handler approaches, only thing ive found in that vein is python-effect

astral rover
#

Looks very rust like

bitter iris
# sick hound What is the least used keyword in python? <:monkaHMM:480293032265252864>
Counter({'def': 2469801,
         'None': 2079423,
         'if': 1952145,
         'return': 1535357,
         'import': 1264292,
         'from': 900304,
         'in': 900118,
         'True': 734511,
         'not': 714855,
         'assert': 566377,
         'False': 560890,
         'for': 559342,
         'is': 539126,
         'else': 493987,
         'class': 473044,
         'raise': 328813,
         'as': 273045,
         'and': 262468,
         'with': 217100,
         'elif': 205600,
         'try': 201381,
         'except': 198135,
         'or': 166449,
         'pass': 123573,
         'lambda': 86972,
         'await': 83763,
         'async': 73891,
         'yield': 51696,
         'while': 39673,
         'continue': 39332,
         'break': 32802,
         'del': 31962,
         'finally': 19407,
         'global': 7115,
         'nonlocal': 775})

aggregated results from a couple thousand python projects

twilit grotto
#

wow, didn't expect None so high

#

and how are there so many more defs than returns

earnest wing
#

side effects

#

lots of side effects

hard spoke
#

'async': 73891,
I wonder if it's disproportionately discord.py projects 😅

viscid nymph
#

Of course lol

viscid nymph
#

Surprised that they're more awaits than async

twilit grotto
#

how so

#

you probably use the function more than once

earnest wing
#

plus, async iterators and context managers are far less common

stark fable
#

why would there be more asyncs than awaits

#

you would need to have a large number of async functions with no awaits in them

#

enough to balance out the many, many async functions that will contain multiple awaits

#

(well, empty async functions and also async for/async with since i think those exist, but they're not going to be ridiculously common)

hot crypt
#

apis

plucky wedge
#

What does nonlocal do?

astral rover
#

Allow for closures

#

https://youtu.be/E9wS6LdXM8Y I thought explained it quite well when

Speaker: Thomas Ballinger

What are closures all about anyway, and why is there a new keyword in Python
3?
We'll look at what a closure is, their history in the Python language, what
the Python 3 nonlocal keyword is about, and examine how closures are
idiomatically used (and avoided) in Python.

Slides can be found at: https://speakerdeck.com/py...

▶ Play video
hard spoke
#

closures that assign variables in their environment, specifically - I think closures in general are any functions that can capture their environment, and in Python any function can do that

floral meteor
floral meteor
simple crystal
#

!e

import *
night quarryBOT
#

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

001 |   File "<string>", line 1
002 |     import *
003 |            ^
004 | SyntaxError: invalid syntax
simple crystal
#

what if I wanna

#

import everything

#

????

#

hmmm

snow beacon
#

That can be a project.

simple crystal
#

lol yes

#

someone in another server gave a good solution

#
import pkgutil
for module in [mod[1] for mod in pkgutil.iter_modules()][1:]:
    __import__(module)
simple crystal
#

!e

import pkgutil
for module in [mod[1] for mod in pkgutil.iter_modules()][1:]:
    __import__(module)
night quarryBOT
#

@simple crystal :warning: Your eval job timed out or ran out of memory.

[No output]
fossil estuary
#

not sure if it's, technically esoteric but

#

!e ```py
x=123456789
print(f"{x:,}")

night quarryBOT
#

@fossil estuary :white_check_mark: Your eval job has completed with return code 0.

123,456,789
simple crystal
#

...what does comma do to format specifier?

#

ohhhh thousands seperator

#

!e

x=123456789
print(f"{x:_}")
night quarryBOT
#

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

123_456_789
simple crystal
#

!e

x=123456789
print(f"{x:_x}")
night quarryBOT
#

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

75b_cd15
fossil estuary
#

what

#

oh, _x means hex@simple crystal

#

!e ```py
x=123456789
print(f"{x:x}")

night quarryBOT
#

@fossil estuary :white_check_mark: Your eval job has completed with return code 0.

75bcd15
fossil estuary
#

Well, that's a good feature.

snow beacon
viscid nymph
#

oops

#

!d object.format

night quarryBOT
#
object.__format__(self, format_spec)```
Called by the [`format()`](../library/functions.html#format "format") built-in function, and by extension, evaluation of [formatted string literals](lexical_analysis.html#f-strings) and the [`str.format()`](../library/stdtypes.html#str.format "str.format") method, to produce a “formatted” string representation of an object. The *format\_spec* argument is a string that contains a description of the formatting options desired. The interpretation of the *format\_spec* argument is up to the type implementing [`__format__()`](#object.__format__ "object.__format__"), however most classes will either delegate formatting to one of the built-in types, or use a similar formatting option syntax.

See [Format Specification Mini-Language](../library/string.html#formatspec) for a description of the standard formatting syntax.

The return value must be a string object.... [read more](https://docs.python.org/3/reference/datamodel.html#object.__format__)
fossil estuary
#

who pinged me :/

#

was it you?

#

@viscid nymph

viscid nymph
#

Yep

fossil estuary
#

oh, why

simple crystal
#

been learning javascript past couple days and damn if it doesn't allow for some esoteric ridiculous stuff except some of it actually get used in production code apparently lol

west cipher
#

being pythonic is for nerds

floral meteor
#

Why you have so many lines?

#

```py
Post it in a code block and I'll show you unpythonic
```

west cipher
#
async def sendAll(s):
    global MODE, STRIP_COLOR, SPEED, SEG_COUNT
    s = s.replace(' ', '').lower().replace('staticrgb', 'staticRGB').replace('rgb', 'RGB').replace('setspeed', 'setSpeed')
    DNIDH = {i[1]['name'].lower(): i[1]["websocket"] for i in clients.items() if "name" in i[1]}
    keyList = list(DNIDH.keys())
    for i in s.split(';'):
        j = [t.split(',') for t in i.split('>')]
        if len(j) == 1: j = [keyList + ["room"], j[0]] #Set to all devices if none are given
        for a in j[1]:
            if a.startswith("#"): a = "RGB|"+'|'.join(str(int(a[h+1:h+3], 16)) for h in range(0, 6, 2)) #Hex to RGB
            for d in j[0]:
                if d in keyList:
                    await DNIDH[d].send(a)
                elif d == "room": #process room LEDs
                    if a in ["white", "rainbow", "staticRGB", "off"]:
                        MODE = a
                    elif a.startswith("RGB"):
                        MODE = "RGB"
                        STRIP_COLOR = [int(c) for c in a.split('|')[1:]]
                    elif a.startswith("setSpeed"):
                        SPEED = float(a.split('|')[1])
#

i mean yea i could technically make this like, 3 lines (excluding the multiline ; trick)

#

but this is actual code im using and wrote not as a meme

#

@floral meteor

floral meteor
#

optimisation in progress...

#

why are you using global variables?

west cipher
#

well

#

i have a bunch of ESP32 LED drivers for various LED devices around my room

#

and i have a strip directly connected to the PI

#

being ran in another thread

#

i could make that strip connect to the websocket server and make a conversion layer and make it cleaner but i can't be bothered

floral meteor
#

why do you have space around your operators and after brackets?

west cipher
#

?

#

i mean, i didn't design this code to be compressed or anything

#

i made it to work, just my style is super stream of consiouness so it ended up looking like this

floral meteor
#
__69__ = {'MODE':MODE,'STRIP_COLOR':STRIP_COLOR,'SPEED':SPEED,'SEG_COUNT':SEG_COUNT}
async def sendAll(s):
    global __69__;s=s.replace(' ',str()).lower().replace('staticrgb', 'staticRGB').replace('rgb', 'RGB').replace('setspeed', 'setSpeed');__={'DNIDH':{i[1]['name'].lower():i[1]["websocket"]for i in clients.items()if"name"in i[1]},'keyList':list(__['DNIDH'].keys())}
    for i in s.split(';'):
        j=[t.split(',')for t in i.split('>')]
        if len(j)==1:j=[__['keyList']+["room"],j[0]]
        for a in j[1]:
            if a[0]=="#":a="RGB|"+'|'.join(str(int(a[h+1:h+3],16))for h in range(0,6,2))
            for d in j[0]:
                if d in __['keyList']:await __['DNIDH'][d].send(a)
                elif d=="room":
                    if a in["white","rainbow","staticRGB","off"]:__69__|={'MODE':a}
                    elif a[:3]="RGB":__69__|={'MODE':"RGB",'STRIP_COLOR':[int(c)for c in a.split('|')[1:]]}
                    else:a.startswith("setSpeed")and __69__.update({'SPEED':float(a.split('|')[1])})
simple crystal
#

beautiful

west cipher
#

y tho lol

floral meteor
#

i didn't even use walrii

simple crystal
#

also

#

...nice

west cipher
#

yea i would use walrus

simple crystal
#

NEEDS MORE WALRII 69

#

69ing walrii

floral meteor
#

alright i'll edit it

simple crystal
#

:=

#

=:

west cipher
#

i once did a giant command parser in 1 line

#

lemme try and find it

floral meteor
#

I used dunder 69 as a variable, are you proud?

simple crystal
#

proud isn't the word

west cipher
#
args = [a for group in args.split('|') if len(a:=[b for command in group.split(',') if len(b:=(((([g[0], g[1] if par[g[0]][0] == S else (float(('-' if g[1][0] == '-' else '') + d) if len(str(d:=(re.sub(r"([^0-9.])", '', g[1]).replace('.', '', max(0, (g[1]).count('.') - 1))))) > 0 else 1)]) if len(c) > 1 else [g[0], 'true' if par[g[0]][0] == S else 1.0])) if len(c) > 0 and (par[g[0]][0] == S or g[-1] != "false") else []) if len(g:=(c if ((c:=[(r.strip()) for r in (command.split('=', 1) if '=' in command else command.split(' ', 1))])[0] in par) else (([bind[c[0]], c[1]] if len(c) > 1 else [bind[c[0]]]) if (c[0] in bind) else []))) > 0 else []) > 0]) > 0][:3]```
#

here it is

#

heres the note that went with it:

#splts by '|', splits by ',', splits by '=' if '=' is in it, otherwise split by ' ', strip those, exit those args if any of those args are 'false', make sure args[0] (the filter name) is in the filter list, if that filter value is a float, turn it into a float by removing all but the last '.'. If any of the created lists have a length of 0, don't add it (applys to all layers)
floral meteor
#
! ! CEO — Today at 11:19 AM
__69__ = {'MODE':MODE,'STRIP_COLOR':STRIP_COLOR,'SPEED':SPEED,'SEG_COUNT':SEG_COUNT}
async def sendAll(s):
    global __69__;s=s.replace(' ',str()).lower().replace('staticrgb', 'staticRGB').replace('rgb', 'RGB').replace('setspeed', 'setSpeed');__={'DNIDH':{i[1]['name'].lower():i[1]["websocket"]for i in clients.items()if"name"in i[1]},'keyList':list(__['DNIDH'].keys())}
    for i in s.split(';'):
        len((j:=[t.split(',')for t in i.split('>')]))==1and(j:=[__['keyList']+["room"],j[0]])
        for a in j[1]:
            a[0]=="#"and(a:="RGB|".__add__('|'.join(str(int(a[h+1:h+3],16))for h in range(0,6,2))))
            for d in j[0]:
                d in __['keyList']and await __['DNIDH'][d].send(a)
                elif d=="room":
                    if a in["white","rainbow","staticRGB","off"]:__69__|={'MODE':a}
                    elif a[:3]="RGB":__69__|={'MODE':"RGB",'STRIP_COLOR':[int(c)for c in a.split('|')[1:]]}
                    else:a.startswith("setSpeed")and __69__.update({'SPEED':float(a.split('|')[1])})
west cipher
#

using ; to seperate lines is cheating imo

floral meteor
#

k, you've forced my hand, i will have to traumatise you now

west cipher
#

you can just
use a big ass print statment to define and run like everything

#

print(var1 := "yea", var2 := var1.strip(), await asdfasdf)

#

something like that

#

also you can prob avoid global by using globals()

floral meteor
#
globals()['.']={'MODE':MODE,'STRIP_COLOR':STRIP_COLOR,'SPEED':SPEED,'SEG_COUNT':SEG_COUNT}
async def sendAll(s):
 s,__=s.replace(' ',str()).lower().replace('staticrgb', 'staticRGB').replace('rgb', 'RGB').replace('setspeed', 'setSpeed'),{'DNIDH':{i[1]['name'].lower():i[1]["websocket"]for i in clients.items()if"name"in i[1]},'keyList':list(__['DNIDH'].keys())}
 for i in s.split(';'):
  len((j:=[t.split(',')for t in i.split('>')]))==1and(j:=[__['keyList']+["room"],j[0]])
  for a in j[1]:
   a[0]=="#"and(a:="RGB|".__add__('|'.join(str(int(a[h+1:h+3],16))for h in range(0,6,2))))
   for d in j[0]:
    d in __['keyList']and await __['DNIDH'][d].send(a)
    if d not in __['keylist']and d=="room":
     if a in["white","rainbow","staticRGB","off"]:globals()['.']|={'MODE':a}
     elif a[:3]="RGB":globals()['.']|={'MODE':"RGB",'STRIP_COLOR':[int(c)for c in a.split('|')[1:]]}
     else:a.startswith("setSpeed")and globals()['.'].update({'SPEED':float(a.split('|')[1])})
    globals().update(globals()['.'])
#

don't make me import ctypes and hook the ellipsis

west cipher
#

why would you need either of those

simple crystal
#

this channel isn't about needing

#

it's about wanting

floral meteor
#

there, massive indents can go die in a hole

west cipher
#

don't make me import ctypes and hook the ellipsis
how would that lower line count

floral meteor
#

the line count is the target

#

insanity is the target

west cipher
#

ok how is importing some random stuff insanity tho

floral meteor
#

you wanna find out?

west cipher
#

ok?

#

also if you want 1 line count you can just exec a string but thats boring

floral meteor
#
__import__('ctypes').py_object.from_address(id(...)+8).value=type(str(),(object,),dict(__call__=globals))
...()['.']={'MODE':MODE,'STRIP_COLOR':STRIP_COLOR,'SPEED':SPEED,'SEG_COUNT':SEG_COUNT}
@lambda f:...().update({'sendAll':f})
async def yeet(s):
 s,__=s.replace(' ',str()).lower().replace('staticrgb', 'staticRGB').replace('rgb', 'RGB').replace('setspeed', 'setSpeed'),{'DNIDH':{i[1]['name'].lower():i[1]["websocket"]for i in clients.items()if"name"in i[1]},'keyList':list(__['DNIDH'].keys())}
 for i in s.split(';'):
  len((j:=[t.split(',')for t in i.split('>')]))==1and(j:=[__['keyList']+["room"],j[0]])
  for a in j[1]:
   a[0]=="#"and(a:="RGB|".__add__('|'.join(str(int(a[h+1:h+3],16))for h in range(0,6,2))))
   for d in j[0]:
    d in __['keyList']and await __['DNIDH'][d].send(a)
    if d not in __['keylist']and d=="room":
     if a in["white","rainbow","staticRGB","off"]:...()['.']|={'MODE':a}
     elif a[:3]="RGB":...()['.']|={'MODE':"RGB",'STRIP_COLOR':[int(c)for c in a.split('|')[1:]]}
     else:a.startswith("setSpeed")and...()['.'].update({'SPEED':float(a.split('|')[1])})
 ...().update(...()['.'])
west cipher
#

wait

#

explain line 1

#

like

#

py_object.from_address(id(...)+8).value=type(str(),(object,),dict(__call__=globals))

#

that part

#

or

floral meteor
#

chilaxin seems to be missing :/

#

they made a module called fishhook

#

that's a quick implementation of that module

#

essentially, I'm telling EllipsisType to go die in a hole, and replacing it with an similar object that has a __call__ attribute, hence making ...() call globals instead of ellipsis

west cipher
#

oh

floral meteor
#

id(yay)+8 is the address of yay's class

#

now you know where EllipsisType lives, you can go torture them >XD

west cipher
#
… = globals
#

does this work?

floral meteor
#

no

#

you can't assign to constants, and builtin methods are read-only

#

hence why you need to fŭck around with addresses

west cipher
#

pain

#

i mean

#

you can do like

#

t = globals

#

t()['h'] = 5

#

h
>>> 5

twilit grotto
#

globals is a function

west cipher
#

yea but like

#

you can bind t to it

floral meteor
#

!e you could do

t=globals()
t.update({"2":3})
print(globals()['2']+2)
night quarryBOT
#

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

5
floral meteor
#

!e but you can't do

t=globals()
t|={'2':3}
print(globals()['2']+2)
night quarryBOT
#

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

5
floral meteor
#

wait wat

#

we should make an esoteric team for pyweek

#

and do the whole thing esoterically XD

rugged sparrow
#

@floral meteor the dict returned by globals is mutable

floral meteor
#

ik, but i thought augmented operator still instantiated a new instance from a merge.
apparantly it calls update instead

rugged sparrow
#

Makes sense that it calls update

#

Like list += does the same thing

floral meteor
#

!e ```py
f=type("",(),{'iadd':print})()
f += "Hello World!"
f += ...

night quarryBOT
#

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

001 | Hello World!
002 | Traceback (most recent call last):
003 |   File "<string>", line 3, in <module>
004 | TypeError: unsupported operand type(s) for +=: 'NoneType' and 'ellipsis'
floral meteor
#

wait it still assigns the return?

#

O_O

rugged sparrow
#

Yes

floral meteor
#

@rugged sparrow how do i reset its recursion thingy?
nvm

night quarryBOT
#

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

[No output]
floral meteor
#

;-;

#

that'll turn it into a memory bomb won't it?

#

looks like I'll have to print as I go then

#

or set a limit

#

wow it's nomming my cpu only a little bit

#

!e ```py
a=[0]
@lambda cls:cls(1)
class fibonacci(int):
def repr(s):
a.append(s.class(int.add((lambda i:print(int(i))or i)(a[-2]),a[-1])))
return int.repr(s)

a+=[fibonacci]
print (a) # in console: >>> a

night quarryBOT
#

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

001 | 0
002 | 1
003 | 1
004 | 2
005 | 3
006 | 5
007 | 8
008 | 13
009 | 21
010 | 34
011 | 55
... (truncated - too many lines)

Full output: too long to upload

boreal slate
#
import sys
p=print;s=sum;e=len
l=[s([int,ord][y.isalpha()](y)for y in x)for x in[[x for x in y]for y in sys.argv[1].split(",")]]
if e(l)==2:p(s(l))
elif e(l)==3:p(s(l[:2])*l[2])
else:
 _=e(l);p((s(l[:_-2])*l[_-2])//l[_-1])

How can i shorten this down

viscid nymph
#

I mean

#

You can shorten it by 2 characters

#

Because sum(gencomp) works

boreal slate
#

right, updated it

#

ok, made it shorter

#
import sys
p,s=print,sum
l=[s([int,ord][y.isalpha()](y)for y in x)for x in sys.argv[1].split(",")]
_=len(l)
p([0,1,s(l),s(l[:-1])*l[-1]][_]if _<4else(s(l[:_-2])*l[_-2])//l[_-1])
simple crystal
#

you can do p, s = print, sum cuz semicolons are cheating

boreal slate
simple crystal
#

semicolons aren't esoteric they are some nerd shit

#

unless you're stuffing the entire program onto one line there's no excuse, this ain't C++

strange basin
#

!e

assert "I" in "VOWELS"
night quarryBOT
#

@strange basin :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | AssertionError
strange basin
#

!e

assert "I" in "TEAM"
night quarryBOT
#

@strange basin :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | AssertionError
strange basin
#

Maybe time to go look for a new job ... 😦

boreal slate
simple crystal
#

\n is one char 😤

#

p,s=print,sum is the same char count though

thin trout
#

It depends on the platform

#

Well

#

I guess it depends how you count

simple crystal
#

it's literally a character tho

#

when you aren't escaping it

#

calling it "\n" is like calling \ \\

#

but we call it \n because saying
is a character and
is only one character is unclear since we can't see

tawny arch
#

I think windows uses two characters for a new line

simple crystal
#

do you need to escape two characters for a new line in windows?

tawny arch
#

not when you're writing python

proper vault
#

it is autoconverted, but ye, \r\n is the correct sequence

tawny arch
#

maybe using a semicolon saves disk space?

simple crystal
#

but yeah it's been \r\n on windows

#

as far as I can tell because it's stupid

proper vault
#

I mean, literally everything other than unix and mac text files is \r\n

#

HTTP, most other network protocols

#

gzipped text files

simple crystal
#

lol [-6] eh

#

carriage return makes no sense in most formats imo

#

I use it to reprint to same console line but \n implies carriage return

#

why would cursor continue printing where previous line ended?

proper vault
#

\n means one column down and \r means return to start of line

simple crystal
#

on a typewriter, sure

proper vault
#

teletypes and terminals also do this

simple crystal
#

but there's no "word wrap" character

proper vault
#

though now there are flags you can set to change how this is handled

#

one thing unix definitely does right is trailing newline

simple crystal
#

and those flags are by default set to return to beginning of new line

proper vault
#

yeah, since that is how unix decided to do text files

simple crystal
#

because it makes sense

#

you don't need to emulate a typewriter

proper vault
#

emulating typewriters is all teletypes did

simple crystal
#

yes and that is now defunct

proper vault
#

ye, but now the characters have 2 distinct meanings

#

which is imo quite silly

simple crystal
#

and carriage return remaisn useful

#

for returnign to origin ont he same line

#

I use \r all the time

proper vault
#

or a newline on macs

#

its not about being useful, its about newlines working differently because unix decided they need to be special

simple crystal
#

it should be about being useful

proper vault
#

as in the problem isn't some ascii characters becomes useless

simple crystal
#

if something isn't useful it's just art

proper vault
#

most of the <32 codes are useless

#

the problem is that there isn't a way to do a newline sequence in ascii that will work on all computers implementing ascii rendering

simple crystal
#

what computers do we need to worry about that need to produce human readable text that can't handle a newline?

#

if \n is just vertical to any computer it's a "how quaint" moment

#

I get that ascii is based on typing stuff but it's far more complex to handle dates correctly and simple computers generally get programmed to do that fine

proper vault
#

backwards compatability is a always a concern. And it doesn't seem like an issue until something requires the networking \r\n form, and your editor is really convinced it needs to save \n. Or the fact you now have to keep track of which files are text and which are not text on linux in order to not produce non standard zip archives or incorrect HTTP requests.

#

I did only run into issues about 3 times, but that 3 more than really should have happened considering there is a standard on this

simple crystal
#

\n being the standard, right?

proper vault
#

\r\n. HTTP, zip, .. all use CRLF

simple crystal
#

but if backwards compatibility and standards really mattered we wouldn't have two different configurations of friggin usb-c

proper vault
#

its really just text files being silly

#

the networking world agrees on \r\n pretty consistently

simple crystal
#

so they add an unnecessary character in case an ancient computer has to process text data

proper vault
#

yes, you can't change standards

#

at least not for something as silly as a newline sequence

simple crystal
#

poor computer would just move the cursor vertically and htere'd be nothing behind the cursor

#

but it'd be suspended horizontally

#

what a conundrum

proper vault
#

yeah, that is how the character worked when ascii was defined

simple crystal
#

despite this, we have new ports every second tuesday we're supposed to be able to plug a quarter inch into somehow

#

standards do change

proper vault
#

not networking ones, unless its something really severe

simple crystal
#

cuz the internet is a gross behemoth but yeah I'm just complaining

#

but back on topic python files generally can be assumed to just use \n

#

and that's a visual representation of an escaped single character

proper vault
#

ye, python does handle all newline sequences regardless of OS

#

so yeah, it is definitely possible to codegolf with \n even on windows

simple crystal
#

the only time I've used semicolons in python is when I try to exec a whole python file and insert ;*code* on lines that can handle that to run that code a bunch

proper vault
#

they are useful for golfing since they let you avoid indentation

#
while 1:print('a');print('b')
simple crystal
#

!e

while 1:print('a');print('b')
night quarryBOT
#

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

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

Full output: too long to upload

simple crystal
#

hehe

#

trufax

thin trout
#

You can also use a tuple, but that’s longer

simple crystal
#

I am more impressed by code that avoids the semis, personally

#

unless it's one line

#

if it's one line I like semis

#

more than one line, why bother?

thin trout
#

!e

while 1:(print("a"),print("b"))```
proper vault
#

onelines without semis are best imo

night quarryBOT
#

@thin trout :x: Your eval job has completed with return code 143 (SIGTERM).

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

Full output: too long to upload

thin trout
#

No semi colon required

simple crystal
#

yeha agreed

#

usin tuples like that is good

#

and you can use ternaries and comprehensions and so on

proper vault
#

comprehensions can also be used for local variables

simple crystal
#

with a walrus?

proper vault
#

without walrus

#
def fib(n):
    return max(
        d[1]
        for d in [{}]
        for d[0], d[1] in [(0, 1)]
        for _ in range(n)
        for d[0], d[1] in [[d[1], d[0] + d[1]]]
    )
#

source: nedbat twitter

simple crystal
#

oh wow what does for d in [{}] do

#

oh just iterates once

#

as a dictionary

#

I can't tell if this is a good job interview fib solution or it'd make them mad

#

neat tho

sick hound
#

hi

fossil estuary
#

hi

fossil estuary
#

use p,s=print,sum

#

@boreal slate

boreal slate
frigid wharf
#
p([0,1,s(l),s(l[:-1])*l[-1]][_]if _<4else(s(l[:_-2])*l[_-2])//l[_-1])
``` should make it shorter
viscid nymph
#

The 4else part probably raises an error

proper vault
#

it doesn't

#

the highligher just doesn't like it

snow beacon
thin trout
boreal slate
viscid nymph
night quarryBOT
#

@viscid nymph :x: Your eval job has completed with return code 143 (SIGTERM).

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

Full output: too long to upload

fossil estuary
#

lol

#

too long

viscid nymph
night quarryBOT
#

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

001 | 31
002 | 31
fossil estuary
#

how so

#

oh wait

#

nvm

#

that's the length of the string 😅

viscid nymph
#

I would say while1

#

but why does this not work

#

!e

while1:print('lol')
print('huh')
night quarryBOT
#

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

001 | lol
002 | huh
viscid nymph
#

wait nvm

viscid nymph
vague hearth
#
class DunderOverload(metaclass=TypeOverload):

    def __init__(self, value: int):
        self.value = value

    def __add__(self, other: int):
        print("int")
        return self.value + other

    def __add__(self, other: str):
        print("str")
        return self.value + int(other)

    def __add__(self, other):
        print("Any")
        return NotImplemented


inst = DunderOverload(10)
print(inst + 2)
print(inst + "3")
print(inst + [])

int
12
str
13
Any
TypeError: unsupported operand type(s) for +: '__getattribute__' and 'list'```a clean way to overload methods https://paste.pythondiscord.com/epupesecih.py
twilit mountain
#
_=()==()
__=(_+_)+(_+_)
___=((_+_)+(_+_)+(_+_)+(_+_)*(_+_)+(_+_)+(_+_)+(_+_))
____="%c"*(_+_+_+_+_)%(((_+_)*((___*__+(__+__))//(_+_))),((_)*((___*__+(__+__)-(_+_+_)))),((_+_)*((___*__+(__+__)+(__))//(_+_))),((_+_)*((___*__+(__+__)+(__))//(_+_))),((_)*((___*__+(__+__)+(__+_+_+_)))))+" "+"%c"*(_+_+_+_+_)%(((_)*((___*__+(__+__)+(__+__+__+_+_+_)))),((_)*((___*__+(__+__)+(__)+(_+_+_)))),((_+_)*((___*__+(__+__)+(__)+(_+_+_)+(_+_+_))//(_+_))),((_+_)*((___*__+(__+__)+(__))//(_+_))),((_+_)*((___*__+(__+__)-(__))//(_+_))))
print(____) 

Anyone here did anything like this?

fossil estuary
#

yea

#

me

#

wait a fukn

#

that prints hello world

#

doesnt it

#

I made it, I should know

#

!e

_=()==()
__=(_+_)+(_+_)
___=((_+_)+(_+_)+(_+_)+(_+_)*(_+_)+(_+_)+(_+_)+(_+_))
____="%c"*(_+_+_+_+_)%(((_+_)*((___*__+(__+__))//(_+_))),((_)*((___*__+(__+__)-(_+_+_)))),((_+_)*((___*__+(__+__)+(__))//(_+_))),((_+_)*((___*__+(__+__)+(__))//(_+_))),((_)*((___*__+(__+__)+(__+_+_+_)))))+" "+"%c"*(_+_+_+_+_)%(((_)*((___*__+(__+__)+(__+__+__+_+_+_)))),((_)*((___*__+(__+__)+(__)+(_+_+_)))),((_+_)*((___*__+(__+__)+(__)+(_+_+_)+(_+_+_))//(_+_))),((_+_)*((___*__+(__+__)+(__))//(_+_))),((_+_)*((___*__+(__+__)-(__))//(_+_))))
print(____)
night quarryBOT
#

@fossil estuary :white_check_mark: Your eval job has completed with return code 0.

HELLO WORLD
fossil estuary
#

MF

#

@twilit mountain

twilit mountain
#

Oh

fossil estuary
#

🙃 lol

twilit mountain
#

😂u only made it

#

I copied it from yr DM only

fossil estuary
#

loool

#

you've come a long way.

terse mortar
ornate dew
#

My physics test is in 5 hours, I know nothing, and this is what I'd do rather than study:

digits = {'0':'1', '1':'2', '2':'3', '3':'4', '4':'5', '5':'6', '6':'7', '7':'8', '8':'9', '9':'0'}
num = '0'
while num != ['1', '0', '0']:
    num = list(num)
    lastdigit = num.pop()
    increment = digits[lastdigit]
    if lastdigit == '9':
        try:
            nextlastdigit = num.pop()
            if nextlastdigit == '9':
                num = ['1', '0', '0']
            else:
                nextincrement = digits[nextlastdigit]
                num.append(nextincrement)
                num.append(increment)
        except IndexError:
            num = ['1', '0']
    else:
        num.append(increment)
    
    for digit in num:
        print(digit, end='')
    
    print()

Maybe one day I'll be masochistic enough to make it recursive so it works for any upper limit but that day is not today xD

alpine flower
#

!e

def increment(num: list) -> list:
  if num[-1] == 9:
    if len(num) > 1:
      num = increment(num[:-1]) + [0]
  else:
    num[-1] += 1
  return num

num = [1, 9, 9, 9]
print(increment(num))```
night quarryBOT
#

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

[2, 0, 0, 0]
alpine flower
#

@ornate dew not really the same but there's no limit

#

!e

def increment(num: list) -> list:
  if num[-1] == 9:
    if len(num) > 1:
      num = increment(num[:-1]) + [0]
  else:
    num[-1] += 1
  return num
print(increment([9 for i in range(10 ** 60)]))```
night quarryBOT
#

@alpine flower :warning: Your eval job timed out or ran out of memory.

[No output]
alpine flower
#

haven't seen that one before

ornate dew
alpine flower
#

finnne

ornate dew
#

Also what happened to my syntax highlighting?

viscid nymph
#

!code

night quarryBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

ornate dew
#

Oh xD

alpine flower
#

!e

digits = {'0':'1', '1':'2', '2':'3', '3':'4', '4':'5', '5':'6', '6':'7', '7':'8', '8':'9', '9':'0'}
def increment(num: list) -> list:
  if num[-1] == 9:
    if len(num) > 1:
      num = increment(num[:-1]) + ['0']
  else:
    num[-1] = digits[num[-1]]
  return num
print(increment(['9', '9', '9']))
```\
night quarryBOT
#

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

['9', '9', '0']
ornate dew
alpine flower
#

that's easy to fix tho eval("-1")

ornate dew
#

Or int('-1') lmao

#

But that would be cheating

alpine flower
#

recursion hurts my head tho idk why it isn't working

ornate dew
#

No variables of datatype int and nothing that returns int

ornate dew
simple crystal
#

hmmm

#

you'd need the f string syntax nvm

floral meteor
#

!e ```py
def increment(num: list[int]) -> list:
(num[-1]==9)and len(num)>1 and(num:=increment(num[:-1])+[0])or num.setitem(-1,num[-1]+1)
return num

num = [1, 9, 9, 9]
print(increment(num))

night quarryBOT
#

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

[2, 0, 0, 0]
snow beacon
floral meteor
#

I forgot all the quote marks

molten wadi
#

been codiing with python for 5 years and never knew you could do increment(num: list[int]) -> list

#

within a function name

#

crazy

wide laurel
#

!w

#

!e

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

wide laurel
#

!eval

def main():
  exit()
main()
night quarryBOT
#

@wide laurel :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 |   File "<string>", line 2, in main
004 | NameError: name 'exit' is not defined
wide laurel
#

oh

#

idk then

floral meteor
#

@wide laurel #bot-commands if your trying to break the bot XD

molten wadi
#

lmao

floral meteor
#

!e my code after the coffee: ```py
print(420)

night quarryBOT
#

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

420
floral meteor
#

does the same thing

#

!e post moved: "my code before the coffee"```py
import('ctypes').py_object.from_address(id(...)+8).value=type("wrapper",(object,),{'call':lambda s,f:f()})
@int
@...
class n:int=lambda s:69
@...
class cout:lshift=print
@...
class main:init=lambda s: cout << int.mul((n//10)*10,(n%10)-(True<<10**False))

night quarryBOT
#

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

420
floral meteor
#

hey chilaxin

rugged sparrow
#

!e ```py
from ctypes import (
pythonapi, POINTER, byref,
c_int, c_wchar_p
)
import os

def rerun(*new_flags, keep_old=True):
_argv = POINTER(c_wchar_p)()
_argc = c_int()
pythonapi.Py_GetArgcArgv(byref(_argc), byref(_argv))
orig_argv = _argv[:_argc.value]
if keep_old:
orig_argv[1:1] = new_flags
orig_argv[-1] = orig_argv[-1].replace('x = 0', 'x = 0x11')
os.execv(orig_argv[0], orig_argv)
else:
os.execv(orig_argv[0], (orig_argv[0],) + new_flags)
x = 0
if x == 0x11:
print('here')
else:
rerun()```

night quarryBOT
#

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

here
rugged sparrow
#

magic ^

#

@floral meteor i live in this channel lol

floral meteor
#

same XD

#

imma see if i can use this cursed class syntax to make brainfuck

boreal slate
#
import sys
s=sum
l=[s([int,ord][y>"9"](y)for y in x)for x in sys.argv[1].split(",")]
_=len(l)
print([0,1,s(l),s(l[:-1])*l[-1]][_]if _<4else(s(l[:_-2])*l[_-2])//l[_-1])
``` anyway i can get rid of the if statement, probably that should make this shorter
#

i can share the annotated version of this if you want

floral meteor
#

!e ```py
import('ctypes').py_object.from_address(id(...)+8).value=type("wrapper",(object,),{'call':lambda s,a,**k:lambda f:f(a,**k),'repr':lambda s:'...'})
@...("++++++++++[>++++++++++<-]>--.-.+++.")
class output:
@str
@...()
class input(str):''
def init(s,c):
if not c:return''
@list
@...()
class a:list=lambda list:[0]
@...(a)
class a(list):
"""This is a list, only infinite."""
str=lambda s:list.str([...]+s+[...])
@int
@...()
class offset:int=lambda int:0
def getitem(self,item):
if(item:=item+self.offset)<=0:
self.offset-=item
@int
@...(0)
class item(int):int=lambda int:0
try:return list.getitem(self,item)
except IndexError:self.extend([0]
(item-len(self)+1))
return list.getitem(self,item)
def setitem(self,item):
if(item:=item+self.offset)<=0:
self.offset-=item
@int
@...(0)
class item(int):int=lambda int:0
try:list.getitem(self,item)
except IndexError:self.extend([0]
(item-len(self)+1))
return list.setitem(self,item)
@int
@...(0)
class i(int):0
@int
@...(0)
class p(int):-1
while(p:=p+1)<len(c):
if p<0:raise SyntaxError
@str
@...()
class t():str=lambda s:c[p]
if t in['+','-']:
@lambda n:a.setitem[i,n]
@int
@...()
class _:int=lambda s:(a[i]+1-2*(t=='-'))%256
elif t in['<','>']:
@int
@...(i+1-2*(this=='>'))
class i(int):...
elif t=='.':
@lambda b:print(end=chr(int(b)))
@...()
class cout:int=a.pop()
elif(t=='['and a[i]==0)or(t==']'and a[i]!=0):
@int
@...()
class :
def int(s):
nonlocal p;p=p+1-2*(t==']')
@int
@...(0)
class (int):0
while >=0:
if 0>(p:=p+1-2*(t==']')) or p>len(c):raise SyntaxError
c[p]in['[',']']and(
:=
+1-2*(c[p]!=t))
return p
@int
@...(
)
class p(int):...

night quarryBOT
#

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

001 | <string>:2: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
002 | <string>:5: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
003 | <string>:10: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
004 | <string>:12: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
005 | <string>:17: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
006 | <string>:23: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
007 | <string>:32: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
008 | <string>:38: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
009 | <string>:41: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
010 | <string>:46: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
011 | <string>:51: SyntaxWarning
... (truncated - too long, too many lines)

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

floral meteor
#

bugger it, i'll work on my cursedutils module

ornate dew
# ornate dew My physics test is in 5 hours, I know nothing, and this is what I'd do rather th...

Boys I was wrong, today was the day

digits = {'0':'1', '1':'2', '2':'3', '3':'4', '4':'5', '5':'6', '6':'7', '7':'8', '8':'9', '9':'0'}

def increment(num):
    try:
        digit = num.pop()
        if digit == '9':
            increment(num)
        num.append(digits[digit])
    except IndexError:
        num.append('1')
    return num

num = ['0']
while num != ['1', '0', '0', '0']:
    num = increment(num)
    for i in num:
        print(i, end='')
    print()

This was much shorter, and dare I say, simpler lmao

#

It's finally short enough to fit on vsinder

vestal solstice
#
digits = {'0':'1', '1':'2', '2':'3', '3':'4', '4':'5', '5':'6', '6':'7', '7':'8', '8':'9', '9':'0'}

def increment(num):
    try:
        digit = num.pop()
        if digit == '9':
            increment(num)
        num.append(digits[digit])
    except IndexError:
        num.append('1')


num = ['0']
while num != ['1', '0', '0', '0']:
    increment(num)
    for i in num:
        print(i, end='')
    print()
alpine flower
#

is there a way to use contextlib.suppress without a context manager?

simple crystal
#

!e

import gc

f = gc.get_referents(list.__dict__)[0]
f.pop("append")
a = list()
print(a)
a.append()
print(a)
print(2)
night quarryBOT
#

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

[]
simple crystal
#

segmentation fault

#

when I try to debug to see what happens the debugger breaks

#

and then it will raise a "list has no attribute append" once

#

then it goes back to segmentation fault

#

I want an exception to get raised if I try to append...

#

oh fishhook works

#

I will figure out why

ornate dew
#

So it should return every time

#

I think 😂

#

!e

digits = {'0':'1', '1':'2', '2':'3', '3':'4', '4':'5', '5':'6', '6':'7', '7':'8', '8':'9', '9':'0'}

def increment(num):
    try:
        digit = num.pop()
        if digit == '9':
            increment(num)
        num.append(digits[digit])
    except IndexError:
        num.append('1')
    return num

num = ['0']
while num != ['1', '0', '0', '0']:
    num = increment(num)
    for i in num:
        print(i, end='')
    print() 
night quarryBOT
ornate dew
#

Seems to work lmao

ornate dew
#

I just happened to forget that python passes by object reference, so both variables point to the same object in memory, meaning I don't really have to return it lmao

viscid nymph
alpine flower
#

!e

digits = [str(ord(i) - ord('a')) for i in "abcdefghij"]

def increment(num: list[str]) -> None:
    try:
        digit = num.pop()
        if digit == str(ord('j') - ord('a')):
            increment(num)
        num.append(digits[int(digit) + ord('a') if int(digit) < ord('j') - ord('a') else ord('a') - ord('a')])
    except IndexError:
        num.insert(ord('a') - ord('a'), str(ord('b') - ord('a')))
    return num

print(increment(["1", "9", "9"]))```
night quarryBOT
#

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

['1', '0', '0']
alpine flower
#

I can't figure out how to get around the indices tho

ornate dew
#

I was doing, you can't use anything that returns an int, but you can use numbers as strings

#

I'm pretty sure it's impossible to do both :P

alpine flower
#

ya there's probably some backend way to do it, I just have absolutely no idea how to do it

sick hound
#

!e

#

!e
print("Hello world!")

night quarryBOT
#

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

Hello world!
sick hound
#

hell yea

#

!e

num2 = input("Enter a number: ")
result = float(num1) + float(num2)

print(result)```
night quarryBOT
#

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

001 | Enter a number: Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
naive roost
#

as you can see (even though you should probably play on #bot-commands), input doesn't work in this sandboxed interpreter

runic ruin
#
_B='108.0';_A='34.0';String=str;Integer=int;Float=float;Run_Code=exec;Character=chr;Character_Number_1=Character(Integer(Float(String('112.0'))));Character_Number_2=Character(Integer(Float(String('114.0'))));Character_Number_3=Character(Integer(Float(String('105.0'))));Character_Number_4=Character(Integer(Float(String('110.0'))));Character_Number_5=Character(Integer(Float(String('116.0'))));Character_Number_6=Character(Integer(Float(String('40.0'))));Character_Number_7=Character(Integer(Float(String(_A))));Character_Number_8=Character(Integer(Float(String('72.0'))));Character_Number_9=Character(Integer(Float(String('101.0'))));Character_Number_10=Character(Integer(Float(String(_B))));Character_Number_11=Character(Integer(Float(String(_B))));Character_Number_12=Character(Integer(Float(String('111.0'))));Character_Number_13=Character(Integer(Float(String(_A))));Character_Number_14=Character(Integer(Float(String('41.0'))));Final_String=String(Character_Number_1+Character_Number_2+Character_Number_3+Character_Number_4+Character_Number_5+Character_Number_6+Character_Number_7+Character_Number_8+Character_Number_9+Character_Number_10+Character_Number_11+Character_Number_12+Character_Number_13+Character_Number_14);Run_Code(Final_String)
```This took me seventeen years to code, and it is finally perfect.
night quarryBOT
#

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

Hello
sick hound
#

it's beautiful

#

!e

_=((()==())+(()==()))
__=(((_<<_)<<_)*_)
__import__(('c%'[::(([]!=[])-(()==()))])*((_<<_)+(()==()))%((__+(((_<<_)*_)+((_<<_)+((_*_)+(_+(()==())))))),(__+(((_<<_)*_)+((_<<_)+((_*_)+(_+(()==())))))),(__+(((_<<_)<<_)+(_<<_))),(__+(((_<<_)<<_)+((_*_)+(()==())))),(__+(((_<<_)<<_)+((_<<_)+(_*_)))),(__+(((_<<_)<<_)+((_<<_)+(_*_)))),(__+(((_<<_)<<_)+((_<<_)+((_*_)+(_+(()==())))))),(__+(((_<<_)*_)+((_<<_)+((_*_)+(_+(()==())))))),(__+(((_<<_)*_)+((_<<_)+((_*_)+(_+(()==())))))))) 
night quarryBOT
#

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

Hello world!
sick hound
#

this is one of mine

late talon
late talon
sick hound
#

I use manjaro linux

#

passthrough a 6800 XT into windows

twilit grotto
#

only pyhton

edgy fiber
#

oh

#

I thought I wouldn't get an answer, but thanks.

late talon
sick hound
late talon
sick hound
grave rover
#

!e ```py
f=(lambda n:(o:=n//2)>n or''.join(0*(m:=x/n3)(l:=y/n3)or" #"[(mm+ll-1)**3-mm*l**3<0]+"\n"[x<o-1:]for y in range(o,-o,-1)for x in range(-o,o)))

print(f(20))```

night quarryBOT
#

@grave rover :white_check_mark: Your eval job has completed with return code 0.

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

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

grave rover
#
(lambda n:(lambda o=int(.5*n//1):[([(lambda m=(x/n*3),l=(y/n*3):print([" ","#"][(m**2+l**2-1)**3-m**2*l**3<0],end=""))()for x in range(-o,o)],print())for y in range(o,-o,-1)])())

(lambda n:(lambda o:"".join(" #"[(m**2+l**2-1)**3-m**2*l**3<0]+"\n"*(o-x==1)for y in range(o,-o,-1)for x in range(-o,o)for m,l in[[(x/n*3),(y/n*3)]]))(n//2))(10)

(lambda n:(o:=int(n/2))>n or''.join((m:=x/n*3)*(l:=y/n*3)*0 or" #"[(m**2+l**2-1)**3-m**2*l**3<0]+"\n"[x<o-1:]for y in range(o,-o,-1)for x in range(-o,o)))

(lambda n:(o:=n//2)>n or''.join(0*(m:=x/n*3)*(l:=y/n*3)or" #"[(m*m+l*l-1)**3-m*m*l**3<0]+"\n"[x<o-1:]for y in range(o,-o,-1)for x in range(-o,o)))

``` kinda satisfying to look at how this one evolved over time
fossil estuary
#

!e
f=(lambda n:(o:=n//2)>n or''.join(0*(m:=x/n3)(l:=y/n3)or" #"[(mm+ll-1)**3-mm*l**3<0]+"\n"[x<o-1:]for y in range(o,-o,-1)for x in range(-o,o)))

print(f(12))

night quarryBOT
#

@fossil estuary :white_check_mark: Your eval job has completed with return code 0.

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

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

plucky wedge
#

like dis

fossil estuary
#

I know

#

I like not using them because it's funny

#

@plucky wedge

dusk root
#

Someone have idea how to run http://www.onelinerizer.com/ in python3?
I got:

Traceback (most recent call last):
  File ".../oneline.py", line 22, in <module>
    onelinerize(code)
  File "...\lib\site-packages\onelinerizer\onelinerizer.py", line 804, in onelinerize
    return get_init_code(t, table)
  File "...\lib\site-packages\onelinerizer\onelinerizer.py", line 70, in get_init_code
    output = Namespace(table).many_to_one(tree.body)
  File "...\lib\site-packages\onelinerizer\onelinerizer.py", line 214, in many_to_one
    return reduce(
NameError: name 'reduce' is not defined
grave rover
#

oh I was writing something like that for py3.8

last locust
dusk root
fossil estuary
#

mine works. ;)

grave rover
#

not 100% working yet sadly

#

but it can do most things iirc

dusk root
#

I just wanted it to do exec

grave rover
#

I mean

#
# Generated by Mart Obfuscator

a=lambda b:b<([]==[])<<(()>=())and()==()or a(b-([]==[]))+a(b-((()>=())<<(()==())))
``` here's fibonacci
#


>>> x = [6, 4, 3, 2, 9, 1]
>>> sort.quick_sort(x, 0, len(x)-1)
(None, (None, -1, (None, (None, -1, -1), (None, -1, -1))), (None, -1, (None, -1, -1)))
>>> x
[1, 2, 3, 4, 6, 9]
```quicksort and selectionsort
#

tic tac toe is still a WIP sadly, the number obfuscator seems to actually decide whether the loop runs or exits, and even then it seems there's an issue somewhere causing an indexerror

eternal prawn
#

Not sure if this belongs here but I managed to achieve something I'm really proud of, but it has no real use other than making my code a bit prettier with type hinting.
I made a type so that I can make numpy arrays with a specified length. Kinda like a generic, so I can type hint Vector[6] if I'm expecting a (6,) shape numpy array.

This is what the syntax looks like

x = Vector[3]([1, 2, 3])

And this will drop an error, because of the shape mismatch:

y = Vector[4]([1, 2, 3])

Now I can type hint:

def foo(x: Vector[2]) -> Vector[2]:
    return x+2
rugged sparrow
#

@eternal prawn noice. If you want to make it a bit simpler, python has __class_getitem__

#

!e ```py
class a:
def class_getitem(cls, arg):print(arg)

a[0]```

night quarryBOT
#

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

0
dull anvil
#
factors = lambda num: [int(j) for i in map(lambda x: [x] if x == num else [x, num / x], list(filter(lambda x: num % x == 0, range(1, int(num**0.5))))) for j in i]```
#

nice way of calculating factors

#

aint it

late talon
#

what is lamada

stable hornet
viscid nymph
astral rover
#

You don't need a meta class here

#

You could use init subclass

#

And then not make it a function that returns a class

viscid nymph
#

I know but the decorator was interesting

floral meteor
#

alright, going into python from matlab, i really missed the struct object.
Well with some globals hooking and a cursed struct class I will make struct work in python.

#

!e ```py
import ctypes
#hackery

class struct:
def init(self,**k):[setattr(self,this,that)for this,that in k.items()]
def getattr(self,item):
if not hasattr(self,item):setattr(self,item,self.class())
return object.getattr(self,item)
def call(self,f):setattr(self,f.name,f);return f
class _hooked(type):
@lambda c:c()
class __sentinal:...
gulag={}
def del(self,other=__sentinal):
if other is __sentinal
for victim, orig in gulag.items():ctypes.py_object.from_address(id(victim)+8).value=orig
elif other in gulag:ctypes.py_object.from_address(id(other)+8).value=gulag[other]
class curse(metaclass=_hooked):
"""example usages:

@curse(...)
def call(self,*a,**k):
def wrapper(f):
return f(*a,**k)

curse(None,'call',lambda s,*a:s)
"""
def new(self,other,name='',f=None):
if f is None:return lambda f:self(other,name or f.name,f)
else:return self(other,name or f.name,f)
def init(self,other,name='',f=None):
if other not in self.class.gulag:self.class.gulag|={other,type(other)}
hack=ctypes.py_object.from_address(id(other)+8)
try:hack.value=type(hack.value.name,(hack.value,),{name:f})
except:hack.value=type(hack.value.name,(),{this:getattr(hack.value,this)for this in dir(hack.value)}|{name:f})
@curse(globals())
def missing(self, key):
try:return getattr(builtins,key)
except:self[key]=struct(name=key,doc=None);return self[key]
cout.lshift=print
cout << "Hello World!"

#

oh whoops i wasnt finished lol

#

!e ok first i perfectses the class

class struct:
 def __init__(self,**k):[setattr(self,this,that)for this,that in k.items()]
 def __getattr__(self,item):
  if not hasattr(self,item):setattr(self,item,self.__class__())
  return object.__getattr__(self,item)
 def __call__(self,f):setattr(self,f.__name__,f);return f
cout, output = struct(__lshift__=print), struct()
output.data.x = 3
output.data.y = 4
@cout << f(output.data)
def _(data):
  return data.x * data.y
#

I have no clue, it shouldn't be recursionings

#

it should be workings

floral meteor
#

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

alpine flower
#

"".join(['A' for i in range(43)])* smh

vestal solstice
#

I believe you meant f"{11478986304257167078711585130701756989053283163632459947822157877600493794161163746264989691490697448857580612687974391859056618193877774016661073255152478229773002314437327253923119931013370082604311376279371017487563790178827046139928382510691977723156789183826289319143052391855134253864827181651765249703991141830847575261485010803545942957275674094024174250:X}"

dull anvil
unique glacier
#

yert 🥳

floral meteor
#

i was trying to make a matlab object

unique glacier
#

wow,It's cool👍

#

I trying to make an AI project. But it's not working, Please help guys to make it.

snow beacon
#

This channel tends to solve problems in what can only be described as the worst way possible. Maybe try #❓|how-to-get-help if you want to get good code.

grave rover
#
if __name__ == "__main__":
    x = 10

    with open("/proc/self/mem", "r+b") as mem:
        mem.seek(id(x))
        obj = PyLongObject()
        obj.set_bytes(mem.read(obj.get_size()))
        print(obj.get_named_values())
        # => PyLongObject(ob_refcnt=74, ob_type=140678365892192, ob_size=1, ob_digit=10)

``` repurposing some old code
grave rover
#

I got bored of having to look them up

#

I also customized the struct format a little

grave rover
#
# Copy PyObject to avoid recursion, but use P[void] for pointers
PyTypeObject = CPyPacket("@nP[void]P[void]",
                         namedtuple("PyTypeObject",
                                    ["ob_refcnt", "ob_type", "tp_name"])).factory()
PyObject = CPyPacket("@nP[PyTypeObject]",
                     namedtuple("PyObject",
                                ["ob_refcnt", "ob_type"])).factory()
PyVarObject = CPyPacket("@{PyObject}n",
                        namedtuple("PyVarObject",
                                   ["ob_size"])).factory()
PyLongObject = CPyPacket("@{PyVarObject}i",
                         namedtuple("PyLongObject",
                                    ["ob_digit"])).factory()

if __name__ == "__main__":
    x = 10

    with open("/proc/self/mem", "r+b") as mem:
        mem.seek(id(x))
        obj = PyLongObject()
        obj.set_bytes(mem.read(obj.get_size()))
        print(obj.get_named_values())
        # => PyLongObject(ob_refcnt=74, 
        #                 ob_type=PyTypeObject(ob_refcnt=144, 
        #                                      ob_type=140641582082304, 
        #                                      tp_name=0), 
        #                 ob_size=1, 
        #                 ob_digit=10)
``` beautiful
grave rover
#
PyTypeObject = CPyPacket("@nP[void]nP[void]nn15P[void]L4P[void]n9P[void]n11P[void]IP[void]",
                         namedtuple("PyTypeObject",
                                    ["ob_refcnt", "ob_type", "ob_size", "tp_name",
                                     "tp_basicsize", "tp_itemsize", "tp_dealloc", "tp_print",
                                     "tp_getattr", "tp_setattr", "tp_reserved", "tp_repr",
                                     "tp_as_number", "tp_as_sequence", "tp_as_mapping",
                                     "tp_hash", "tp_call", "tp_str", "tp_getattro",
                                     "tp_setattro", "tp_as_buffer", "tp_flags", "tp_doc",
                                     "tp_traverse", "tp_clear", "tp_richcompare",
                                     "tp_weaklistoffset", "tp_iter", "tp_iternext",
                                     "tp_methods", "tp_members", "tp_getset", "tp_base",
                                     "tp_dict", "tp_descr_get", "tp_descr_set",
                                     "tp_dictoffset", "tp_init", "tp_alloc", "tp_new",
                                     "tp_free", "tp_is_gc", "tp_bases", "tp_mro", "tp_cache",
                                     "tp_subclasses", "tp_weaklist", "tp_del", "tp_version_tag",
                                     "tp_finalize"])``` this took way too long and yes I'm planning to fill in the blanks later
#

I wish I knew how to properly pretty-print

grave rover
#

I'm positive I'm slowly going mad with power

#

actually I can remove the @ since it's the default

dire yew
#

python just released a fully-developed official pep that'll change booleans forever?!?!?!? this is sooo good for esotericness and it's gonna be implemented in 3.11

link -> https://docs.google.com/document/d/1gvq4rdMVzrEFAlVCSPvGs4mstI8831seOEDpwiRRWW4

grave rover
#

if you wanna be convincing at least use a website styled to look like python's pep webpages (+url), a realistic pep number (I do get the joke tho) and make sure the preview doesn't spoil it
other than that, quality shitpost

grave rover
#
if __name__ == "__main__":
    import sys
    f = sys._getframe(0)
    obj3 = resolve_meta(_frame, id(f))
    print(resolve(PyBytesObject,                            # Create PyBytesObject from address
                  obj3.get_named_values(convert=False)      # Children stay `CPyObject`s
                  .f_code.get_named_values(resolve=False)   # Don't resolve addresses
                  .co_code)                                 # Address for co_code (type: bytes)
          .ob_size)                                         # ob_size of PyBytesObject
    print(len(f.f_code.co_code))```
grave rover
#
    x = 54
    obj = resolve_meta(PyLongObject, id(x))
    offset = obj.get_offset("ob_digit")  # offset on PyLongObject to ob_digit field
    with open("/proc/self/mem", "r+b") as mem:
        mem.seek(id(x) + offset)
        mem.write(struct.pack("i", 420))

    print(6*9)  # => 420
terse mortar
terse mortar
dire yew
terse mortar
#

True

dire yew
# terse mortar True

btw, i also got an infraction for making this joke so i can't send this anymore for a while

#

april fools comes at a price

round violet
grave rover
#

also; this one creates a copy in a separate buffer, which has the added benefit of us being able to point the interpreter to it and edit it very easily :^)

rugged sparrow
#

@grave rover do you plan to handle variable size fields?

grave rover
#

I don't support them sadly

#

but

#

I have plans: ```py
item = XYZ()

# Get class object from just the address with the correct refcount
obj2 = resolve_meta(PyLongObject, id(item))
print(as_object(
    obj2.get_named_values(resolve=False).ob_type
))  # => <class '__main__.XYZ'>
#

as you know classes have a tp_itemsize field 👀

#

i.e. variable length

rugged sparrow
#

Yea

copper delta
#

walrus operators in comprehensions is p hot

#
[1, 2, 3, 4, 5.0, 6, 7, 8, 9]```
vestal solstice
#

no

#

it's abcdef

teal monolith
#

Ah, hex letters only?

#

still pretty neat

vestal solstice
#

!e

from numpy import base_repr

print(base_repr(2847674241700166260733851334605607128751529874266565790, 36))
night quarryBOT
#

@vestal solstice :white_check_mark: Your eval job has completed with return code 0.

YOUCANDOANYLETTERWITHTHISBUTNOSPACE
sinful badger
#

can someone explain how you can encode python scripts with only brackets and a few other characters?

sick hound
#

Can’t seem to find what’s wrong with this

sinful badger
#

your trying to asign a variable to a string

sick hound
#

Supposed to run an rng with one in 500 chance to say “you got an heirloom

sinful badger
#

and not to a variable

sick hound
#

dumb it down for me a bit

sinful badger
#
instead of
"var" = input(" ...````
sick hound
#

what?

#

which line?

sinful badger
#

"packrng" = random.randint(1, 500)

#

it should be without quotes

sick hound
#

IT WORKED

#

Thanks

sinful badger
#

and also remove quotes from the if statement with it

sick hound
#

Time for more coding agony

#

Alright now I’m trying to get it to work so I can also use lowercase e for the input and also so that it says wrong key if you don’t enter in e

simple crystal
simple crystal
steady lily
sinful badger
simple crystal
#

or if you mean builtins you need to use at least exec

fluid tree
#

If your restriction is no A-Za-z, remember you can use unicode

sick hound
#

Whenever I try to open a python file to edit it makes a pycache folder

#

With a compiled version of the file that I can’t edit

#

also my pyinstaller doesn’t work

rugged sparrow
#

As of rn it has most simple datatypes, structs, and unions

#

(All datatypes can be allocated in place or read from an address)

#

I'm working on C function calling rn but it's tricky af

fossil estuary
#

!e

b64=lambda x:(
    __import__
    (
        "b" \
        "a" \
        "s" \
        "e" \
        "6" \
        "4"
        )
              .
    b64encode
    (
    x
    .
    encode
    (
        'u' \
        't' \
        'f' \
        '-' \
        '8'
        )
    )
              .
    decode
    (
                    'u' \
                    't' \
                    'f' \
                    '-' \
                    '8'
                  )
              )
globals(
    )[
        "_" \
        "_" \
        "b" \
        "u" \
        "i" \
        "l" \
        "t" \
        "i" \
        "n" \
        "s" \
        "_" \
        "_"
      ].print(
    __import__(
        "b" \
        "a" \
        "s" \
        "e" \
        "6" \
        "4"
    )
      .
      b64decode
      (
          b64
          (
                "H" \
                "e" \
                "l" \
                "l" \
                "o" \
                " " \
                "W" \
                "o" \
                "r" \
                "l" \
                "d" \
                "!"
           )
       )
      .
      decode
      (
            'u' \
            't' \
            'f' \
            '-' \
            '8'
            )
      )
night quarryBOT
#

@fossil estuary :white_check_mark: Your eval job has completed with return code 0.

Hello World!
fossil estuary
#

yes.

terse mortar
#

Lovely.

fossil estuary
#

yes.

#

the longest (readable?) way to get the letter h

terse mortar
#

You should run it through black and get it to a one liner

fossil estuary
#

!e ```py
chars = [72,101,108,108,111,32,87,111,114,108,100,33]
h = "".join([import("base64").b64encode(chr(v).encode('utf-8')).decode('utf-8') for v in chars])
print(import("base64").b64decode(h).decode('utf-8').lower())

night quarryBOT
#

@fossil estuary :white_check_mark: Your eval job has completed with return code 0.

h
fossil estuary
#

why do i need a one liner?

#

i can do that myself

#

but then its unreadable

terse mortar
#

So? You care about readable code?

fossil estuary
#

no.

terse mortar
#

k.

#

Why are we speaking like this?

fossil estuary
#

should i run it thru my one-liner thing

terse mortar
#

Sure.

fossil estuary
#

oh nice, my internet went out

terse mortar
#

Lovely.

lucid shell
#

!e

(lambda: exec('def a():"""TEST"""\n') and eval("a"))()

night quarryBOT
#

@lucid shell :warning: Your eval job has completed with return code 0.

[No output]
delicate terrace
#

:D

#

That's my code right there

#

i wrote it for a test today:

    @given(func=st.functions())
    @example(func=lambda: exec('def a():"""TEST"""\n') and eval("a"))
    def test_prog_is_func_name(self, func: Callable[[Any], None]) -> None:
        ...  # test code
fluid tree
fossil estuary
#

it's private :)

simple crystal
#

finally figured out exactly what fishhook does and can change how [] indexing on lists works without losing access to the original __getitem__

#

!e

from ctypes import *

class newlist:
    def __getitem__(self, *args):
        print('Hijacked __getitem__ but preserved functionality')
        return newlist._oldget(self, *args)

ssize_t = sizeof(c_ssize_t)
list_tp_as_mapping_p = c_void_p.from_address(id(list) + 14 * ssize_t)
list_mp_subscript_p = c_void_p.from_address(list_tp_as_mapping_p.value + 1 * ssize_t)
heap_tp_as_mapping_p = c_void_p.from_address(id(newlist) + 14 * ssize_t)
heap_mp_subscript_p = c_void_p.from_address(heap_tp_as_mapping_p.value + 1 * ssize_t)
list_mp_subscript_p.value = heap_mp_subscript_p.value

list_dict_proxy = list.__dict__
list_dict = py_object.from_address(id(list_dict_proxy) + 2 * ssize_t).value

new_dict_proxy = newlist.__dict__
new_dict = py_object.from_address(id(new_dict_proxy) + 2 * ssize_t).value
new_dict.update({'_oldget': list_dict['__getitem__']})
list_dict.update({'__getitem__': newlist.__getitem__})

print([0][0])
night quarryBOT
#

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

001 | Hijacked __getitem__ but preserved functionality
002 | 0
simple crystal
#

(not using fishhook itself and wanting to know exactly what I'm doing because I want to use this in a class)

sick hound
#

oh right you changed list literal

simple crystal
#

yeah I want basic list syntax to behave differently

#

my teacher is obsessed with teaching Python like it's baby's first C class and wants us to treat lists as arrays so my eventual plan is to make a module that makes lists actually behave like arrays and include it in everything just to be cheeky

vestal solstice
#

what does it mean?

#

what's different with arrays?

snow beacon
#

They have fixed bounds.

#

Arrays don't have .append(...) for instance.

maiden blaze
#

arrays are also typically homogenous

simple crystal
#

yeah one type and fixed length

snow beacon
#

Usually, arrays contain only elements of one type, but since everything in Python is of type object, that's not that important.

maiden blaze
#

so all items are of the same type

#

😅

vestal solstice
#

oh, that's fine

simple crystal
#

he's obsessed with the idea that Python lists are a "crutch" so I'm removing their functionality to appease him

vestal solstice
#

one type and fixed size, I would do that too

simple crystal
#

writing Pythona as if lists are fixed one type is easy but stupid imo

#

yeah everything in CPython is a struct which "inherits" from a PyObject struct inside of itself with a bunch of functions and other structs it's being passed through to get what you see

snow beacon
#

x : list[:] = {1, 2, 3} is valid syntax.

simple crystal
#

cuz it's type hinting list

#

right?

snow beacon
#

Yes, although if you evaluate the typehint normally it will throw an error I believe.

simple crystal
#

ah

snow beacon
#

Oh, no, it doesn't.

simple crystal
snow beacon
#
In [1]: list[:]
Out[1]: list[slice(None, None, None)]
#

Only in 3.9, I suspect.

fluid tree
simple crystal
#

I'm wondering if I can hijack assignment by index behavior, I think I need to change more than just the pointer fishhook changes for __setitem__

fluid tree
fossil estuary
fluid tree
#

Ok well mine is above

simple crystal
#

also ideally I could hijack initializing but that seems like another week of figuring out stuff

#

probably just gonna raise exceptions if you try to interact with an invalid "array"

snow beacon
#

You could make an array class of your own, then replace list literals with it.

#

That way you'd have to hook less.

simple crystal
#

hmmm

#

can you just replace list's type object with a heap class type object?

#

...would you use ctypes.memmove with the size of the pytypeobject maybe?

#

doesn't seem to work

#

maybe if I manually made a ctypes Structure to replace it

#

but that's more work than hooking

simple crystal
snow beacon
#

I know very little on this topic.

simple crystal
#

ok sry haha

final night
#

Any ideas on how to modify this so that it actually runs?

from functools import partial
from functools import partialmethod

class Test:
    def print_result(self, func):
        print(func())

    def one_arg_decorator(self, func):
        return partialmethod(func, 1)

    @one_arg_decorator
    @one_arg_decorator
    def add(self, x, y):
        return x+y

t = Test()
print(t.add())

If I can figure this out I can re-apply the pattern to a non-static value instead of just 1.

#
Traceback (most recent call last):
  File "test.py", line 54, in <module>
    class Test:
  File "test.py", line 63, in Test
    def add(self, x, y):
TypeError: one_arg_decorator() missing 1 required positional argument: 'func'
#

I am not sure if partialmethod is entirely necessary, but I have not been able to figure out a way to pass self through nested decorators

#

or even single decorators, to be fair

snow beacon
#

Try removing the self from one_arg_decorator, and if you want, making it a classmethod as well.

#

The decorators happen before one_arg_decorator is made into a method — at that point it's just a function with self unbound.

final night
#
from functools import partial
from functools import partialmethod

class Test:
    def print_result(self, func):
        print(func())

    @classmethod
    def one_arg_decorator(func):
        return partialmethod(func, 1)

    @one_arg_decorator
    @one_arg_decorator
    def add(self, x, y):
        return x+y

t = Test()
print(t.add())
Traceback (most recent call last):
  File "test.py", line 54, in <module>
    class Test:
  File "test.py", line 64, in Test
    def add(self, x, y):
TypeError: 'classmethod' object is not callable
snow beacon
#

Interesting. I guess you'd want to get rid of the @classmethod decorator and apply it manually after you decorate add.

astral rover
#

you need to use a decorator that wraps the function

snow beacon
#

one_arg_decorator = classmethod(one_arg_decorator)

final night
#

oh, because self gets transferred by @wrapper

snow beacon
#

@wrapper?

final night
#

@wraps

#

sorry

astral rover
#
def one_arg_decorator(func):
    def inner(self, arg):
        return func(self, arg, 1)
    return inner

class Test:
    @one_arg_decorator
    @one_arg_decorator
    def add(self, x, y):
        return x+y
```should do the trick
naive roost
#

don't forget that the typical classmethod takes at least one argument: cls

#

you might want to use @staticmethod instead

snow beacon
final night
#

If I tag it as static then I won't be able to access instance specific values. Maybe I'm approaching this wrong, not even sure if what I am trying to do is practical using decorators.

#

I guess I should explain

#

I am working on a interpreter that has operations in a stack, and implementing tons of different operations.
I am hoping to load the operations in from the stack using decorators because that saves me from a ton of redundant code.
For example:

class Test:
    def __init__(self):
        self.opstack = []

    def opstack_arg(self, func):
        #something

    @opstack_arg
    @opstack_arg
    def add(self, a, b):
        return a + b

    @opstack_arg
    @opstack_arg
    def sub(self, a, b):
        return a - b

x = Test()
x.opstack.append(1)
x.opstack.append(2)
print(x.add())
#

I think decorators could be a really neat approach but maybe not

snow beacon
#

@astral rover's solution should work, barring the arguments to the one_arg_decorator being a little odd.

#
def opstack_arg(func):
    def inner(self, *args):
        return func(self, self.opstack.pop(), *args)
    return inner
```Perhaps this?
#

Actually, that will only work for one-argument functions.

#

You get the idea, although I'm not really sure how to fit it together.

final night
#

I'll definitely try experimenting with that, thanks for the idea

final night
#

check it out

#
class Test:
    def __init__(self):
        self.opstack = []

    def opstack_arg(func):
        def inner(self, *args):
            return func(self, self.opstack.pop(), *args)
        return inner


    @opstack_arg
    @opstack_arg
    @opstack_arg
    def add(self, a, b, c):
        return a + b + c
    


x = Test()
x.opstack.append(1)
x.opstack.append(2)
x.opstack.append(17)
print(x.add())
20
#

such a cool solution

#

now I can sorta just plop error checking into the decorator :)

snow beacon
final night
#

magic

#

lol

#

fun fact, pylint hates me now

#

but it still runs

snow beacon
#

I wonder if it pop things in the right order. What even is the right order?

final night
#

reverse polish notation

#

3 5 + = 3 + 5

naive roost
#

so it's a direct stack implementation

earnest wing
#

I wonder whether you could condense that into a single decorator that pops for each positional arg in the definition.

#

Or alternatively, explicitly pass the number of args to the decorator

#
@args_from_stack
def prod(self, a, b):
    return a * b
final night
#

I could, but instead I am using decorator args to enforce typing, which is pretty cool

#

for instance

#
    @opstack_append
    @stack_arg(int, float)
    @stack_arg(int, float)
    def add(self, a, b): return a + b
#

this is what my decorator looks like rn for anybody who is curious

def stack_arg(*args):
        allowed_types = tuple(args)
        def opstack_arg(func):
            #print("The type is " + str(allowed_types))
            def inner(self, *args):
                if len(self.opstack) > 0:
                    op = self.opstack.pop()
                    if(isinstance(op, allowed_types)):
                        try:  
                            return func(self, op, *args)
                        except ValueError:
                            self.opstack.append(op)
                            raise ValueError()
                    else:
                        self.opstack.append(op)
                        print("Error: type mismatch in " + func.__name__ + ".")
                        raise ValueError()
                else:
                    print("Error: " + func.__name__ + " does not have enough operands.")
                    raise ValueError()
            return inner
        return opstack_arg
#

could probably be condensed but i'm too sleepy to do it right now lol

hard spoke
#
from typing import Iterator
import random
import itertools
def fizz_buzzes() -> Iterator[str]:
    counts = [itertools.count(1)] * 15
    for group in zip(*counts):
        random.seed(23_977_775)
        for n in group:
            # Just pick at random
            yield random.choice(
                ['fizzbuzz', 'fizz', str(n), 'buzz']
            )
fb = fizz_buzzes()
output = [next(fb) for _ in range(100)]

this is from Ten Essays on Fizz Buzz - I figured you people would enjoy it 😅

rugged sparrow
#

that is interesting

#

and gives me some cursed ideas

#

i wonder how one could generate a seed to do similar things like that

hard spoke
# rugged sparrow i wonder how one could generate a seed to do similar things like that

The book goes over it in detail - there's 4**15=1 073 741 824 possible combinations the seed can give over these 15 choices, but we can cut that by a factor of 4!=24 by searching for an arbitrary permutation of the results - like here, you can see, it's ['fizzbuzz', 'fizz', str(n), 'buzz'] and not something more obvious like [ str(n),'fizz', 'buzz', 'fizzbuzz']

#

so just random/linear scanning of the seeds

rugged sparrow
#

i wonder if you could work backwards from looking at the implementation of random to go from results -> seed

#

so you could generate the seed without bruteforcing

hard spoke
#

the problem is that if that was easy, it'd allow for seed-calculation attacks to predict future behaviour of the generator

#

so I'd expect it's hard to do in modern algorithms like the mersenne twister random uses

rugged sparrow
#

ah fair enough

next flame
#

MT is pretty easy to crack, you just need 624 results to get the seed

#

at least its a lot better than shit like java random

twilit grotto
#

it's not meant to be cryptographically strong ¯_(ツ)_/¯

earnest wing
#

So it's mostly about determining how many bits are consumed per random.choice

rugged sparrow
#

random.choice seems to call random.random until it is under a specified limit

sick hound
#

Isnt the same for random.randint tho?

rugged sparrow
#

I think so

simple crystal
#

what does secrets use?

earnest wing
#

Probably the OS's rng

#

!pep 506

night quarryBOT
#
**PEP 506 - Adding A Secrets Module To The Standard Library**
Status

Final

Python-Version

3.6

Created

19-Sep-2015

Type

Standards Track

floral meteor
night quarryBOT
simple crystal
#

at least for now

#

it helped me find a spot in the lab this week where I gasp put ints into what I was supposed to pretend was a char array!

snow beacon
#

C would let you do that anyway, I believe.

rugged sparrow
#

@simple crystal py list_mp_subscript.value = heap_mp_subscript.value # replacing pointer list_mp_ass_subscript.value = heap_mp_ass_subscript.value # replacing pointer can be dangerous, because if hook_cls gets deallocated these arrays will be freed, but list will still use them

#

it is safer to allocate a new array using ctypes, and then fill it with the heap array values

simple crystal
rugged sparrow
simple crystal
rugged sparrow
#

Basically for any slot that is NULL you need to insert a pointer to a properly sized array

simple crystal
#

cool, I did that for the one that's null, to preserve allocation in general should I assign a name to the value of heap pointers and then set the list pointer value to that int instead of the value of the heap pointer?

rugged sparrow
#

So you want to make a new array, then insert the ctypes.addressof(array) into the tp_as_*slot

simple crystal
#

ah okay instead of just making it with from_address

rugged sparrow
#

Well you need to get the tp_as_* ptr first with c_void_p.from_address

simple crystal
#

so it's best to do that with list_as_mapping and for the heap class as well? Would I need to hook every relevant dunder?

rugged sparrow
#

You could also just make a new copy of heap types array

#

That would likely be easier

simple crystal
#

ah nice

#

allocate space with (c_void_p * size)() and then memmove?

rugged sparrow
#

That should work

simple crystal
#

sweet

#

thanks again for the help and for fishhook haha I'm learning a lot about CPython

rugged sparrow
#

Yea no problem

#

Happy to help

grave rover
#

@rugged sparrow I'm making good progress btw, current struggle is reading pointers/arrays, cause sometimes they're delimited by nulls and sometimes they have length ob_size

#
def main():
    x = 10
    # Print representations of the C structs
    print(CPyVarObject.instance())
    print(CPyTypeObject.instance())
    x_as_pylong = get_view(id(x), CPyVarObject.instance())
    print(x_as_pylong.ob_type.tp_basicsize)     # Size of a PyLong in bytes, according to the PyTypeObject C struct
    print(x_as_pylong.ob_refcnt)                # Reference counter in interpreter
    x_as_pylong.ob_refcnt = 1                   # modify refcount :yeef:

# --- OUTPUT ---
struct CPyVarObject {
    ssize_t        ob_refcnt 
    CPyTypeObject* ob_type 
    ssize_t        ob_size 
}
struct CPyTypeObject {
    ssize_t        ob_refcnt 
    CPyTypeObject* ob_type 
    ssize_t        ob_size 
    void*          tp_name 
    ssize_t        tp_basicsize 
    ssize_t        tp_itemsize 
    ...
}
24
215 ```
rugged sparrow
#

I like the pretty print that you do

grave rover
#

Thanks ^^

#

I mainly use it to double-check if i got the structs right

rugged sparrow
#

Makes sense

grave rover
#

The implementation is incredibly hacky but we don't talk about that

rugged sparrow
#

Oh mine is super hacky as well

#

I do like how I allowed for specifiying a null terminated array

#

(type*None) in a struct definition is a null terminated array

grave rover
#

How'd you do that btw, just allow specifying null-terminated and if it's not it uses ob_size?

rugged sparrow
#

I don't have the fall back

grave rover
#

🤔

rugged sparrow
#

You have to say one way or another

grave rover
#

So how does yours handle ob_digit

#

Ah

#

Oh right you're taking a more ctypes-esque approach

rugged sparrow
#

Look into my __init__.py it has definitions for most basic types

#

Yea

#

I added some dynamic stuff but still wanted the recognizable interface

#
class LongObj(PyVarObject):
    ob_digit: field(lambda inst:c_int*abs(inst.ob_size))```
#

Like that's how I do PyLong

grave rover
#

Yeah I just have stuff like ```py
class CPyLongObject(CPyVarObject):
def init(self):
super().init()
self.ob_digit = cprop ("ob_digit", "A[CShort]")
self.add_nodes(self.ob_digit)

#

Oh that's an interesting way to do it

#

The main reason I avoided that is because of property order which i don't trust in the slightest

rugged sparrow
#

Yea field takes in a function then when the property is accessed it uses the type returned by the function(instance)

#

Wdym you don't trust property order?

grave rover
#

I just use property for all fields to live read/write values

rugged sparrow
#

I like using annotations for my stucts

#

I think it looks clean

simple crystal
#

@rugged sparrow
I think I've made it safer as far as allocating for heap structs by doing this

 # For heap classes, need copy their existing struct into allocated space to ensure they persist in memory
    heap_tp_as_number_struct = (c_void_p * pyNumberMethods_slots)()  # Allocate space as array
    heap_tp_as_number_struct_copy = cast(heap_tp_as_number_struct, c_void_p)  # Pointer to array, soon to be struct
    heap_tp_as_number = c_void_p.from_address(heapTypeObject + pyNumberMethods_slot * size_ssize_t)
    memmove(heap_tp_as_number_struct_copy, heap_tp_as_number, pyNumberMethods_slots * size_ssize_t)  # Copy in struct
    heap_nb_add = c_void_p.from_address(heap_tp_as_number_struct_copy.value + nb_add_slot * size_ssize_t)
    heap_nb_multiply = c_void_p.from_address(heap_tp_as_number_struct_copy.value + nb_multiply_slot * size_ssize_t)

    list_nb_add.value = heap_nb_add.value            # replacing pointer
    list_nb_multiply.value = heap_nb_multiply.value  # replacing pointer
#

do you happen to know if it's possible for struct padding to be different if someone compiles CPython themselves or would that screw it up?

rugged sparrow
#

It is possible

#

It's possible for pointers to be 4bytes instead of 8 (32 vs 64bit)

simple crystal
#

that would correspond to the size of ssize_t though, right?

#

but yeah that's a compilation-dependent difference

grave rover
#

A format of cq has size 16 (1 char, 7 padding, 8 for longlong) by default iirc, but depending on the host alignment may be different

grave rover
#

@rugged sparrow arrays are done 👌

rugged sparrow
#

noice

proper vault
#
In [62]: import sys
    ...: r = []
    ...:
    ...: for _ in range(100):
    ...:     from collections import Counter
    ...:     r.append(Counter)
    ...:     del sys.modules['collections']
    ...: print(r[0] is r[1])
False
``` ever needed 100 distinct Counter classes
earnest wing
#

i

#

what

#

I mean, sure

#

I for one use Type[Counter]s as uuids

grave rover
#

I did a thing

fluid tree
simple crystal
grave rover
#

sorta

grave rover
#
    @staticmethod
    def by_reference(obj):
        from py_ctypes import get_view
        from cpy_types.collection_types import CPyListObject

        x = [None]
        list_view = get_view(id(x), CPyListObject.instance())
        list_view.ob_item[0].value = obj._addr
        return x[0]
``` getting objects by address: ![check](https://cdn.discordapp.com/emojis/794240771687317534.webp?size=128 "check")
pure junco
#

You should have seen my friend implement private variables

grave rover
#

been there done that

pure junco
#

I couldn’t find a way to access it at all

#

Only by decompiling the class could I get the initial value (but not the current value)

grave rover
#

send the code, this sounds fairly easy lol

rugged sparrow
#

@grave rover wouldnt a tuple be easier to load with?

rugged sparrow
grave rover
rugged sparrow
#

fair enough

pure junco
#

However, I think this version is truly private:

def MyClass():
 private = {"nine": 9}
 class MyClass:
  def my_method(self):
   return private["nine"]
 return MyClass()
print(MyClass().my_method())   # outputs 9
rugged sparrow
#

is the code online anywhere yet @grave rover

grave rover
#

not yet

pure junco
#

My solution was this:

#

Nope. With a little (a lot) of finagling with dis, sys.settrace, and MyClass.__code__, I have finally come up with a (fairly) elegant solution using sys.settrace:

def test(frame, event, arg):
    if frame.f_lineno == 3:
        print(frame.f_locals)
    return test

sys.settrace(test)

inst2 = MyClass()

Will yield

$ python .\breaker.py
9
{'private': {'nine': 9}}
{}
{}
rugged sparrow
#

!e ```py
def MyClass():
private = {"nine": 9}
class MyClass:
def my_method(self):
return private["nine"]
return MyClass()
print(MyClass().my_method()) # outputs 9

c = MyClass()
c.my_method.closure[0].cell_contents['nine'] = 0
print(c.my_method())```

night quarryBOT
#

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

001 | 9
002 | 0
pure junco
#

Wait, wait

#

Since when is __closure__ a thing?

rugged sparrow
#

its how cpython handles wrapped variables from various scopes

pure junco
#

I know what a closure is

#

But I’d never heard of that property before

grave rover
#
    def MyClass():
        private = {"nine": 9}

        class MyClass:
            def my_method(self):
                return private["nine"]

        return MyClass()
    print(MyClass().my_method.__func__.__closure__[0].cell_contents)```
#

damnit I got beat

rugged sparrow
rugged sparrow
pure junco
#

I didn’t know before that closure data was accessible from the program itself

grave rover
simple crystal
#

everything is accessible to itself as far as it's in Python I think

rugged sparrow
pure junco
#

That’s true of most languages afaik

#

At least languages that aren’t compiled to native machine code

#

For example C# and Java you can access things you shouldn’t be able to using Reflection

stark fable
#

even in languages that are compiled to native machine code you probably can still access things you're not meant to as long as you know enough about where they are and have a way to access memory directly enough to use that knowledge

#

although it could be a bit more difficult

#

to make something actually inaccessible you need to block access to the memory that contains it

pure junco
#

Yes

sick hound
#

What is the smallest subset of ascii that is turing complete in python discoHmm

#

if whle01:=-s or something?

simple crystal
#

do you technically need loops for turing completeness?

#

for writing a turing machine, sure, but for finite instructions you can just have as many ifs as possible repeats

sick hound
#

Don't you? For jumps effectively

#

Though I see what you mean

#

For finite inputs and outputs finite ifs ought to work rooThink

proper vault
#

you need loops for turing completeness

simple crystal
#

and a turing cumpuitable function halts after arbitrarily many repeats

proper vault
#

a turing complete system may have an infinite loop

simple crystal
#

ah

proper vault
#

or well, a turing machine may not end

#

that is the essence of the halting problem

sick hound
#

right MHXThink

simple crystal
#

ah " It is assumed that additional storage space can be given to the procedure whenever the procedure asks for it."

#

so not infinite but so arbitrarily large there is no finite number of switches that complies with the def

#

okay so do you need - and both 1 and 0

sick hound
#

I'm wondering if you'd need a <

simple crystal
#

ah true

sick hound
#

But I assume not if you can turn python into subleq

#

Wait, then you would need <

#

and newline of course

#

Idk if else is needed rooBlank

grave rover
stark fable
#

well, can it simulate a turing machine

proper vault
#

look at haskell

#

or scheme

stark fable
#

loops are required for turing completeness but they're not really part of the definition of turing-completeness, the definition of turing-completeness is to do with turing machines

#

so a lot of somewhat odd things can be turing-complete if they can simulate turing machines, even if there is no obvious looping at all

proper vault
#

ye, for example rule 110

stark fable
#

or the game Recursed

grave rover
#

tfw still busy mapping types

tame kraken
#

im just wondering if anybody here is good at python, and can take a look at my code to see if they can reduce the size of it. the games file size is currently 3kb and i want to reduce it as much as possible while still having a playable game

snow beacon
#

abdlm :() is Turing complete. You can make lambda calculus in it.

grave rover
#

Don't you also need and/or to make choices? What about printing things?

stone lichen
snow beacon
snow beacon
# stone lichen what exactly is this?

A lambda is an anonymous function in Python. All it can do is return an expression. However, that expression can be another lambda function. The 'lambda calculus' is a model of computation that only uses functions returning functions, invented by Alonzo Church.

stone lichen
#

no I know and understand that, I was curious as to your syntax, and the name abdlm

#

I was wondering if it was a typo or if this was something a bit more abstract I'd yet to hear of

snow beacon
#

I just put lambda : in alphabetical order.

stone lichen
#

oh lmao

snow beacon
#

(Python lambdas are lambda arg, *args, kwarg=1: arg + arg.)

stone lichen
#

yes

#

I use them somewhat often, usually in mappings

grave rover
#

How would you do Boolean algebra with lambdas tho

#

I've been trying to figure it out but can't lol

stone lichen
#
>>> andf = lambda x, y: x and y
>>> andf(1, 0)
False
grave rover
#

No n

proper vault
#
T=lambda a: lambda b: a
F=lambda a: lambda b: b
``` is the convention
grave rover
#

What the heck

#

That works?

#

Then how would you make an xor function with that

proper vault
#

xor=lambda l: lambda r: l(r(F)(T))(r(T)(F))

#

May need some extra lambdas to be lazy

grave rover
#

What in the world

earnest wing
#

I know, exec is boring

grave rover
#

You don't need the equals do you

earnest wing
#

you'll need a 1 or 0 to start adding ints (()==(), ()==chr)

#

Though, I think you don't need null bytes

#

so replace = with 1 and programs will be much shorter

grave rover
#

Fair

earnest wing
#

I wonder whether you could do something wacky with repeated % substitution

grave rover
#

Okay I'm starting to see how this works with Boolean algebra, but it only works for truth tables with one output right? I don't see this creating a half adder

snow beacon
#

A half adder is two different expressions.

#

You can make cons lists though. I believe it's something like lambda head: lambda tail: lambda func: func(head)(tail).

#

So if you wanted to store two bits together, you'd call cons(bit1)(cons(bit2)(nil)) for some nil.

#

There's probably a fair bit more machinery for distinguishing a nil from a cons, but it just amounts to giving a callback a boolean.