#esoteric-python

1 messages ยท Page 3 of 1

languid hare
#

related

#

!e

from fishhook import hook
@hook(slice)
def __hash__(self): 
  return hash((self.start, self.stop, self.step))

d = {}
d[::-1] = "reversed"
print(d[::-1])
night quarryBOT
#

@languid hare :white_check_mark: Your 3.10 eval job has completed with return code 0.

reversed
finite blaze
#

Yo

#

I have a string and I would like to replace random occurrence of given character with a different char

#

i mean, i know how to do this but my current method is not short enough

versed eagle
#

whats your current method?

finite blaze
versed eagle
#

you can edit messages instead of deleting and repinging me

#

Lmao

finite blaze
#

Yeah, sorry ๐Ÿ˜…

old socket
#

t[o[random.randint(0, len(o))]] = 37โ€Š how are you even making this work?

#

You can mutate a string like that without ctypes?

finite blaze
#

Oops my bad. t is a byte array and ' ' should be replaced with ord(' ')

versed eagle
#

32

#

iirc, ascii of " " is 32

#

also, that ruined my solution, it would only work for strings :(
i was making a lambda 1 liner

old socket
#

not short at all in the slightest though

#

Idk if there was any other way but I had to index the list I created temporarily to setitem and also get the return right

#

I'll change the var names to make it shorter

#
(lambda a,b,c:[a,a.__setitem__(c([c for c,d in enumerate(a)if d==ord(b)]),32)][0].decode())(bytearray(b'hello'),'l',__import__('random').choice)
cunning stream
#

why does this channel exist

#

awesome ill be here often

#

ok anyways J=input;F=[*open(J()).read()];B,E=0,0;C=[0]*30000;D=[]; while len(F)>E:A=F[E];C[B]+=(A=='+')-(A=='-');B-=(A=='<')-(A=='>');E+=1;E=D[-1]if']'==A and 0!=C[B]else E;D=D+[E]if'['==A else D;C[B]=ord(J())if','==A else C[B];print(chr(C[B]))if'.'==A else None;D.pop(-1)if 0==C[B]and']'==A else None how to shorten

dry mirage
#

wonder if this still works

#

!e

import dis

def inter(code: str):
    lines = code.strip('\n').split('\n')
    code = ''
    names, consts = (), (None,)
    for line in lines:
        s = line.split(maxsplit=2)
        n_code = dis.opmap[s[0]]
        mem = int(s[1])
        code += f"{n_code:02x}{mem:02x}" + "0000" * dis._inline_cache_entries[n_code]
        if n_code in dis.hasconst:
            consts += (eval(s[2]),)
        if n_code in dis.hasname:
            names += (s[2][1 + 7*(n_code is dis.opmap['LOAD_GLOBAL'] and mem % 2):-1],)
    exec((lambda:0).__code__.replace(
        co_code=bytes.fromhex(code),
        co_consts=consts,
        co_names=names,
    ))


src = \
"""
LOAD_GLOBAL     1 (NULL + print)
LOAD_CONST      1 ('This is not esoteric')
PRECALL         1
CALL            1
RETURN_VALUE    1
"""

inter(src)
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

This is not esoteric
floral meteor
#

opcode 0x46 I think can print the repr of something without calling print

#

!e ```py
type(lambda:0)((lambda:69).code.replace(co_code=b"d\x01\x46\x01d\x00S\x01"),globals())()

night quarryBOT
#

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

69
floral meteor
#

printing like a boss

#

!e ```py
import dis

def inter(code: str):
lines = code.strip('\n').split('\n')
code = ''
names, consts = (), (None,)
for line in lines:
s = line.split(maxsplit=2)
n_code = dis.opmap[s[0]]
mem = int(s[1])
code += f"{n_code:02x}{mem:02x}" + "0000" * dis._inline_cache_entries[n_code]
if n_code in dis.hasconst:
consts += (eval(s[2]),)
if n_code in dis.hasname:
names += (s[2][1 + 7*(n_code is dis.opmap['LOAD_GLOBAL'] and mem % 2):-1],)
exec((lambda:0).code.replace(
co_code=bytes.fromhex(code),
co_consts=consts,
co_names=names,
))

src =
"""
LOAD_CONST 1 (69)
PRINT_EXPR 1
RETURN_VALUE 1
"""

inter(src)

night quarryBOT
#

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

69
floral meteor
#

I should probably fix the segfault

dry mirage
#

What is PRINT_EXPR even

floral meteor
#

!e ```py
import dis

def inter(code: str):
lines = code.strip('\n').split('\n')
code = ''
names, consts = (), (None,)
for line in lines:
s = line.split(maxsplit=2)
n_code = dis.opmap[s[0]]
mem = int(s[1])
code += f"{n_code:02x}{mem:02x}" + "0000" * dis._inline_cache_entries[n_code]
if n_code in dis.hasconst:
consts += (eval(s[2]),)
if n_code in dis.hasname:
names += (s[2][1 + 7*(n_code is dis.opmap['LOAD_GLOBAL'] and mem % 2):-1],)
exec((lambda:0).code.replace(
co_code=bytes.fromhex(code),
co_consts=consts,
co_names=names,
))

src =
"""
LOAD_CONST 1 (69)
PRINT_EXPR 1
LOAD_CONST 0 (None)
RETURN_VALUE 1
"""

inter(src)

night quarryBOT
#

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

69
floral meteor
#

done

floral meteor
dry mirage
#

What does that map to in actual python?

floral meteor
#
lambda x:print(repr(x))
#

is equivalent, but not a direct map

#

it's optimised

#

instead of loading print and repr, it just jumps straight to printing the repr

dry mirage
floral meteor
#

optimised print repr

flint hollow
floral meteor
#

secret print op

dry mirage
#

Hm

flint hollow
#

!e

from dis import dis
dis(compile('x+2', '<stdin>', 'single').co_code)
night quarryBOT
#

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

001 |           0 RESUME                   0
002 |           2 LOAD_NAME                0
003 |           4 LOAD_CONST               0
004 |           6 BINARY_OP                0 (+)
005 |          10 PRINT_EXPR
006 |          12 LOAD_CONST               1
007 |          14 RETURN_VALUE
floral meteor
#

in interactive mode, it also stores to _

sullen kayak
#

hi fatal error just wanted to say i hope oyu're having a good one lmao

floral meteor
#

!e ```py
def doobywacker():
class dabbywooker:
x = 69 # get this number

code = doobywacker.code
f = type(doobywacker)(code.replace(co_code=code.co_code[:16]+b"|\0\2\0\x46\0S\0"),globals())()
print(f.x)

night quarryBOT
#

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

69
floral meteor
#

lol it no worky in 3.11

dry mirage
#

!e ```py
import dis

def inter(code: str):
lines = code.strip('\n').split('\n')
code = ''
names, consts = (), (None,)
for line in lines:
s = line.split(maxsplit=2)
n_code = dis.opmap[s[0]]
mem = int(s[1])
code += f"{n_code:02x}{mem:02x}" + "0000" * dis._inline_cache_entries[n_code]
if n_code in dis.hasconst:
consts += (eval(s[2]),)
if n_code in dis.hasname:
names += (s[2][1 + 7*(n_code is dis.opmap['LOAD_GLOBAL'] and mem % 2):-1],)
exec((lambda:0).code.replace(
co_code=bytes.fromhex(code),
co_consts=consts,
co_names=names,
))

src =
"""
LOAD_CONST (1)
LOAD_CONST (12)
EXTENDED_ARG 1 (256)
LOAD_CONST (9)
LOAD_CONST (217)
LOAD_CONST (376)
EXTENDED_ARG 1 (256)
LOAD_CONST (1)
LOAD_CONST (12)
EXTENDED_ARG 9 (2304)
EXTENDED_ARG 2467 (631552)
BUILD_LIST 631690
"""

inter(src)

floral meteor
#

you forget the ints

#

the second row

#

you forgotted

dry mirage
#

Just wanted to see if extended_arg would work pithink

floral meteor
#

and why did you think omitting the second column would work?

#

2467 can't fit in a byte also

#

what even is this?

#

!e ```py
def doobywacker():
class dabbywooker:0

code = doobywacker.code
f = type(doobywacker)(code.replace(co_code=code.co_code[:16]+b"|\0\x46\0d\0S\0"),globals())()

night quarryBOT
#

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

<class '__main__.doobywacker.<locals>.dabbywooker'>
floral meteor
#

getting a class from a function where the function doesn't return anything hehehe

floral meteor
#

and your column alignment is messy

dry mirage
#

I know I tried to type it on mobile ๐Ÿ˜”

#

Gboard screwing with adding hairline spaces as well I gave up

floral meteor
#

this isn't really the sort of thing you type on mobile

sullen kayak
#

anyway what new thing are you writing?

floral meteor
#

tetris

sullen kayak
#

are you making an assembly interpreter now?

#

LMFAO TETRIS

#

in ESOTERIC FASHION???

floral meteor
#

!e ```py
import dis

def inter(code: str):
lines = code.strip('\n').split('\n')
code = ''
names, consts = (), (None,)
for line in lines:
s = line.split(maxsplit=2)
n_code = dis.opmap[s[0]]
mem = int(s[1])
code += f"{n_code:02x}{mem:02x}" + "0000" * dis._inline_cache_entries[n_code]
if n_code in dis.hasconst:
consts += (eval(s[2]),)
if n_code in dis.hasname:
names += (s[2][1 + 7*(n_code is dis.opmap['LOAD_GLOBAL'] and mem % 2):-1],)
exec((lambda:0).code.replace(
co_code=bytes.fromhex(code),
co_consts=consts,
co_names=names,
))

src =
"""
BUILD_LIST 0
LOAD_CONST 0 ((23, 523, 53, 5, 32, 5))
LIST_EXTEND 1
RETURN_VALUE
"""

inter(src)

quartz wave
#

where did you get this code from

floral meteor
#

!e import('dis').dis('[23, 523, 53, 5, 32, 5]')

night quarryBOT
#

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

001 |   0           0 RESUME                   0
002 | 
003 |   1           2 BUILD_LIST               0
004 |               4 LOAD_CONST               0 ((23, 523, 53, 5, 32, 5))
005 |               6 LIST_EXTEND              1
006 |               8 RETURN_VALUE
floral meteor
#

that

quartz wave
#

i meant the one you're eval'ing

floral meteor
#

?

#

inter?

quartz wave
floral meteor
#

scroll up a bit

#

or a lot

quartz wave
#

that code i adapted to 3.11 on july?

floral meteor
#

probably

quartz wave
#

ok

floral meteor
#

it's fun to play with

#

it's like an esolang

#

better than python maybe

#

!e ```py
def f():
[1,2,3,4]

type(lambda:0)(f.code.replace(co_code=b"g\0d\1\xa2\1R\0|\0\x46\1S\x00"),globals())()

night quarryBOT
#

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

(1, 2, 3, 4)
floral meteor
#

hehe i turned list into toopel

#

!e ```py
type(lambda:0)((lambda:(a,69)).code.replace(co_code=b"d\1a\0d\0S\0"),globals())()
print(a)

night quarryBOT
#

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

69
floral meteor
#

i made global equals

quartz wave
#

!e ```py
import dis

def inter(code: str):
lines = code.strip('\n').splitlines()
code = ''
names, consts = {}, {0: None}
for line in lines:
s = line.strip().split(maxsplit=2)
n_code = dis.opmap[s[0]]
mem = int(s[1]) if len(s) > 1 else 0
assert mem >= 0
expr = s[2] if len(s) == 3 else None
code += f"{n_code:02x}{mem:02x}" + "0000" * dis._inline_cache_entries[n_code]
if n_code in dis.hasconst:
if expr:
if (consts[mem] is not None if not mem else mem in consts):
raise RuntimeError(f"constant at index {mem} cannot be overwritten")
consts[mem] = eval(expr)
elif not consts[mem]: raise RuntimeError(f"index {mem} out of bounds")
elif n_code in dis.hasname:
if expr:
if mem in names: raise RuntimeError(f"name at index {mem} cannot be overwritten")
names[mem] = s[2][1 + 7*(n_code is dis.opmap['LOAD_GLOBAL'] and mem % 2):-1]
elif not names[mem]: raise RuntimeError(f"index {mem} out of bounds")
co_names = sorted(names.items(), key=lambda x: x[0])
previdx = -1
for idx, _ in co_names:
if previdx != (previdx := idx) - 1: raise RuntimeError("empty gap in co_names")
co_consts = sorted(consts.items(), key=lambda x: x[0])
previdx = -1
for idx, _ in co_consts:
if previdx != (previdx := idx) - 1: raise RuntimeError("empty gap in co_consts")
return eval((lambda:0).code.replace(
co_code=bytes.fromhex(code),
co_consts=tuple(map(lambda x: x[1], co_consts)),
co_names=tuple(map(lambda x: x[1], co_names)),
))

src =
"""
BUILD_LIST 0
LOAD_CONST 0 ((23, 523, 53, 5, 32, 5))
LIST_EXTEND 1
LOAD_CONST 1 ((1, 2, 3))
BINARY_OP 13 (+=)
RETURN_VALUE
"""

print(inter(src))

night quarryBOT
#

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

[23, 523, 53, 5, 32, 5, 1, 2, 3]
quartz wave
#

it works

floral meteor
#

Is inline_add an opcode?

quartz wave
floral meteor
#

I've seen inline left shift

quartz wave
#

do you mean inplace

floral meteor
#

!e print( import ('dis').opmap)

night quarryBOT
#

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

{'CACHE': 0, 'POP_TOP': 1, 'PUSH_NULL': 2, 'NOP': 9, 'UNARY_POSITIVE': 10, 'UNARY_NEGATIVE': 11, 'UNARY_NOT': 12, 'UNARY_INVERT': 15, 'BINARY_SUBSCR': 25, 'GET_LEN': 30, 'MATCH_MAPPING': 31, 'MATCH_SEQUENCE': 32, 'MATCH_KEYS': 33, 'PUSH_EXC_INFO': 35, 'CHECK_EXC_MATCH': 36, 'CHECK_EG_MATCH': 37, 'WITH_EXCEPT_START': 49, 'GET_AITER': 50, 'GET_ANEXT': 51, 'BEFORE_ASYNC_WITH': 52, 'BEFORE_WITH': 53, 'END_ASYNC_FOR': 54, 'STORE_SUBSCR': 60, 'DELETE_SUBSCR': 61, 'GET_ITER': 68, 'GET_YIELD_FROM_ITER': 69, 'PRINT_EXPR': 70, 'LOAD_BUILD_CLASS': 71, 'LOAD_ASSERTION_ERROR': 74, 'RETURN_GENERATOR': 75, 'LIST_TO_TUPLE': 82, 'RETURN_VALUE': 83, 'IMPORT_STAR': 84, 'SETUP_ANNOTATIONS': 85, 'YIELD_VALUE': 86, 'ASYNC_GEN_WRAP': 87, 'PREP_RERAISE_STAR': 88, 'POP_EXCEPT': 89, 'STORE_NAME': 90, 'DELETE_NAME': 91, 'UNPACK_SEQUENCE': 92, 'FOR_ITER': 93, 'UNPACK_EX': 94, 'STORE_ATTR': 95, 'DELETE_ATTR': 96, 'STORE_GLOBAL': 97, 'DELETE_GLOBAL': 98, 'SWAP': 99, 'LOAD_CONST': 100, 'LOAD_NAME': 101, 'BUILD_TUPLE
... (truncated - too long)

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

floral meteor
#

What does 135 do?

#

MAKE_CELL

quartz wave
soft vapor
#

Hello Everybody

#

How ya doin?

floral meteor
#

What's a cell? Does it have organelles?

quartz wave
#

aw

night quarryBOT
#

@quartz wave :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).

[No output]
soft vapor
#

!e

lambda: "esoteric python"
print(lambda)
night quarryBOT
#

@soft vapor :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 2
002 |     print(lambda)
003 |                 ^
004 | SyntaxError: invalid syntax
floral meteor
#

Maybe start with basic python?

#

lambda is a keyword not a variable name

soft vapor
soft vapor
#

[Never heard of lambda]]

floral meteor
#

lambda is an inline keyword to make an anonymous function

floral meteor
#

!e (lambda p:p("esoteric python"))(print)

night quarryBOT
#

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

esoteric python
floral meteor
#

In syntax

quartz wave
#

!e ```py
from dis import *
from dis import _all_opmap, _inline_cache_entries, deoptmap

def inter(code: str):
lines = code.strip('\n').splitlines()
code = ''
names, consts = {}, {0: None}
for line in lines:
s = line.strip().split(maxsplit=2)
n_code = _all_opmap[s[0]]
mem = int(s[1]) if len(s) > 1 else 0
assert mem >= 0
expr = s[2] if len(s) == 3 else None
code += f"{n_code:02x}{mem:02x}" + f"{opmap['CACHE']:02x}00" * _inline_cache_entries[opmap[deoptmap.get(s[0],s[0])]]
if n_code in hasconst:
if expr:
if (consts[mem] is not None if not mem else mem in consts):
raise RuntimeError(f"constant at index {mem} cannot be overwritten")
consts[mem] = eval(expr)
elif mem not in consts: raise RuntimeError(f"cindex {mem} out of bounds")
elif n_code in hasname:
if expr:
if mem in names: raise RuntimeError(f"name at index {mem} cannot be overwritten")
names[mem] = s[2][1 + 7*(n_code is opmap['LOAD_GLOBAL'] and mem % 2):-1]
elif mem not in names: raise RuntimeError(f"nindex {mem} out of bounds")
co_names = sorted(names.items(), key=lambda x: x[0])
previdx = -1
for idx, _ in co_names:
if previdx != (previdx := idx) - 1: raise RuntimeError("empty gap in co_names")
co_consts = sorted(consts.items(), key=lambda x: x[0])
previdx = -1
for idx, _ in co_consts:
if previdx != (previdx := idx) - 1: raise RuntimeError("empty gap in co_consts")
return eval((lambda:0).code.replace(
co_code=bytes.fromhex(code),
co_consts=tuple(map(lambda x: x[1], co_consts)),
co_names=tuple(map(lambda x: x[1], co_names)),
))

src =
"""
LOAD_CONST 0 (60)
LOAD_CONST 1 (9)
BINARY_OP_ADD_INT 0 (+)
RETURN_VALUE
"""

print(inter(src))

night quarryBOT
#

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

69
quartz wave
#

finally

#

works with adaptive opcodes now

soft vapor
#

What's does the code above do?

#

(also can !e use external pypi packages?)

earnest wing
#

those that are installed

soft vapor
#

you mean the standard library

earnest wing
#

nope

#

external pypi packages that are installed in advance

last locust
#

I.e. these ^ @soft vapor

soft vapor
hollow arrow
#

wizard!

unique heath
#
print(eval(f"__import__(chr(109) + chr(97) + chr(116) + chr(104)).{chr(112) + chr(105)}"))```
prints pi
unreal echo
#

!E
print(eval(f"import(chr(109) + chr(97) + chr(116) + chr(104)).{chr(112) + chr(105)}"))

night quarryBOT
#

@unreal echo :white_check_mark: Your 3.11 eval job has completed with return code 0.

3.141592653589793
unreal echo
last locust
#

pi isn't part of the import

#

But yeah

#

You can also use hex escapes which imo looks more esoteric

#

E.g."\x6d\x61\x74\x68" would be the bit inside the __import__()

last locust
night quarryBOT
#

@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.

math
unique heath
#

!e

print(eval("\x65\x76\x61\x6c\x28\x22\x69\x6d\x70\x6f\x72\x74\x28\x27\x6d\x61\x74\x68\x27\x29\x2e\x70\x69\x22\x29"))```
night quarryBOT
#

@unique heath :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 1, in <module>
004 |   File "<string>", line 1
005 |     import('math').pi
006 |     ^^^^^^
007 | SyntaxError: invalid syntax
unique heath
#

lmao

#

!e

print(eval("\x65\x76\x61\x6c\x28\x5c\x78\x32\x32\x5c\x78\x32\x38\x5c\x78\x35\x66\x5c\x78\x35\x66\x5c\x78\x36\x39\x5c\x78\x36\x64\x5c\x78\x37\x30\x5c\x78\x36\x66\x5c\x78\x37\x32\x5c\x78\x37\x34\x5c\x78\x35\x66\x5c\x78\x35\x66\x5c\x78\x32\x38\x5c\x78\x36\x64\x5c\x78\x36\x31\x5c\x78\x37\x34\x5c\x78\x36\x38\x5c\x78\x32\x65\x5c\x78\x37\x30\x5c\x78\x36\x39\x5c\x78\x32\x39\x5c\x78\x32\x65\x5c\x78\x37\x30\x5c\x78\x36\x39\x22"))
night quarryBOT
#

@unique heath :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 1
004 |     eval(\x22\x28\x5f\x5f\x69\x6d\x70\x6f\x72\x74\x5f\x5f\x28\x6d\x61\x74\x68\x2e\x70\x69\x29\x2e\x70\x69"
005 |           ^
006 | SyntaxError: unexpected character after line continuation character
unique heath
#

lmfao

#

too esoteric

unreal echo
#

skill issue ๐Ÿ”จ

last locust
night quarryBOT
#

@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.

3.141592653589793
last locust
#

Which translates to exec(print(__import__('math').pi))

unique heath
#

!e

print(eval('5f\\x5f\\x69\\x69\\x70\\x69\\x70\\x70\\x5f\\x5f\\x27\\x27\\x5f\\x70\\x36\\x69\\x5f\\x70\\x36\\x36\\x5f\\x70\\x36\\x36\\x5f\\x70\\x36\\x36\\x27\\x27\\x27\\x70\\x69'))```
night quarryBOT
#

@unique heath :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 1
004 |     5f\x5f\x69\x69\x70\x69\x70\x70\x5f\x5f\x27\x27\x5f\x70\x36\x69\x5f\x70\x36\x36\x5f\x70\x36\x36\x5f\x70\x36\x36\x27\x27\x27\x70\x69
005 |     ^
006 | SyntaxError: invalid decimal literal
unique heath
#

i swear to god

#

im too tired gn

night quarryBOT
#

@quartz wave :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).

[No output]
quartz wave
#

!e ```py
from dis import *
from dis import _all_opmap as _ao, _inline_cache_entries as _ice, deoptmap as dop

def inter(code: str):
lines = code.strip('\n').splitlines()
code = ''
names, consts = {}, {0: None}
for line in lines:
s = line.strip().split(maxsplit=2)
n_code, n_deopt = _ao[s[0]], opmap[dop.get(s[0],s[0])]
mem = int(s[1]) if len(s) > 1 else 0
assert mem >= 0
expr = s[2] if len(s) == 3 else None
code += f"{n_code:02x}{mem:02x}" + f"{opmap['CACHE']:02x}00" * _ice[n_deopt]
if n_deopt in hasconst:
if expr:
if (consts[mem] is not None if not mem else mem in consts):
raise RuntimeError(f"constant at index {mem} cannot be overwritten")
consts[mem] = eval(expr)
elif mem not in consts: raise RuntimeError(f"cindex {mem} out of bounds")
elif n_deopt in hasname:
if expr:
if mem in names: raise RuntimeError(f"name at index {mem} cannot be overwritten")
names[mem] = s[2][1 + 7*(n_code is opmap['LOAD_GLOBAL'] and mem % 2):-1]
elif mem not in names: raise RuntimeError(f"nindex {mem} out of bounds")
co_names = sorted(names.items(), key=lambda x: x[0])
previdx = -1
for idx, _ in co_names:
if previdx != (previdx := idx) - 1: raise RuntimeError("empty gap in co_names")
co_consts = sorted(consts.items(), key=lambda x: x[0])
previdx = -1
for idx, _ in co_consts:
if previdx != (previdx := idx) - 1: raise RuntimeError("empty gap in co_consts")
return eval((lambda:0).code.replace(
co_code=bytes.fromhex(code),
co_consts=tuple(map(lambda x: x[1], co_consts)),
co_names=tuple(map(lambda x: x[1], co_names)),
))

src =
"""
LOAD_CONST 1 (0)
LOAD_CONST
IMPORT_NAME 0 (math)
LOAD_ATTR_ADAPTIVE 1 (pi)
RETURN_VALUE
"""

print(inter(src))

night quarryBOT
#

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

3.141592653589793
wheat river
#

rare sight of something being used from the "dis" module other than "dis"

cunning stream
#

figured you guys would like this:J=input;F=[*open(J().read)];B,E=0,0;C=[0]*30000;D=[] while len(F)>E:A=F[E];C[B]+=(A=='+')-(A=='-');B-=(A=='<')-(A=='>');E+=1;E=D[-1]if']'==A and 0!=C[B]else E;D=D+[E]if'['==A else D;C[B]=ord(J())if','==A else C[B];print(chr(C[B]))if'.'==A else None;D.pop(-1)if 0==C[B]and']'==A else None

#

how would i shorten this

bronze agate
#

you can save some chars by not having it all on one line:

original expression (return value discarded):
D.pop(-1)if 0==Canvas[B]and']'==Letter else None
statement version:
if 0==Canvas[B]and']'==Letter:del D[-1]
better:
if 0==Canvas[B]and']'==Letter:D.pop()
cunning stream
#

i could also change the

#

wait nvm

#

thats what you did

bronze agate
#

the line i posted can be even further reduced by using some logical operators in an unorthodox fashion

#

!e
i did not thoroughly think about this one, but i believe it can be applied ```python
if True and True: print('Success - Normal')
not (True and True) or print('Success - Expression version')
False or False or print('Success - Flattened expression version')

night quarryBOT
#

@bronze agate :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | Success - Normal
002 | Success - Expression version
003 | Success - Flattened expression version
bronze agate
#

that way you can avoid using else None when using expressions (and shorten the statement equivalent):
D.pop()if 0==Canvas[B]and']'==Letter else None
or
if 0==Canvas[B]and']'==Letter:D.pop()
can become this:
Canvas[B]or']'!=Letter or D.pop()

versed eagle
#

what's the point lmao

turbid badger
#

hello brilliant programmers can you pleases solve this maths challenge only using python programming language. 1.pick a whole number between(1,9) 2. multiply it by 3 3. add 3 4. multiply by 3 again 5. add the two digits from the number for example if it is (63) you add 6 and 3 together 6. then subtract 1 7. add some loops

serene stratus
#

It's not hard and this is the wrong channel

#

Also you say we have to pick a number between 1 and 9 but later on in the challenge you use 63 as an example

versed eagle
#

or, 6

drowsy cobalt
#

!e ```py
print(bool(~True))

nooooooOOOOoooOooooooOooOOooooOoo
night quarryBOT
#

@drowsy cobalt :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
unique heath
#

!e

print(eval("\x5f\x5f\x69\x6d\x70\x6f\x72\x74\x5f\x5f\x28\x22\x5c\x78\x36\x64\x5c\x78\x36\x31\x5c\x78\x37\x34\x5c\x78\x36\x38\x22\x29\x2e\x70\x69")
night quarryBOT
#

@unique heath :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     print(eval("\x5f\x5f\x69\x6d\x70\x6f\x72\x74\x5f\x5f\x28\x22\x5c\x78\x36\x64\x5c\x78\x36\x31\x5c\x78\x37\x34\x5c\x78\x36\x38\x22\x29\x2e\x70\x69")
003 |          ^
004 | SyntaxError: '(' was never closed
unique heath
#

.-.

versed eagle
#

add parenthesis at the end

#

you only have 1 closing parentheses, but two opening ones

unique heath
#

!e

print(eval("\x5f\x5f\x69\x6d\x70\x6f\x72\x74\x5f\x5f\x28\x22\x6d\x61\x74\x68\x22\x29\x2e\x70\x69"))```
night quarryBOT
#

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

3.141592653589793
untold plaza
#

!e

print(eval("24 - 4"))
night quarryBOT
#

@untold plaza :white_check_mark: Your 3.11 eval job has completed with return code 0.

20
untold plaza
#

!e

print(eval("len(self.bot.guilds)"))
night quarryBOT
#

@untold plaza :warning: Your 3.11 eval job has completed with return code 0.

[No output]
unique heath
#

lmao

untold plaza
#

!e

print(eval("len(self.bot.guilds)"))
night quarryBOT
#

@untold plaza :x: Your 3.11 eval job has completed with return code 1.

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

ok

unique heath
#

lmfao

#

its sandboxed

untold plaza
#

oh

unique heath
#

and also #bot-commands @untold plaza

#

esoteric python is for uh

untold plaza
#

oops

#

I didnโ€™t realise

#

sorry

untold plaza
#

fair enough

quartz wave
night quarryBOT
#

@quartz wave :warning: Your 3.11 eval job has failed.

A fatal NsJail error occurred
untold plaza
#

looks like nonsense to me

unique heath
#

and that

unique heath
quartz wave
untold plaza
#

oh ๐Ÿ˜ญ

unique heath
#

wait

#

!e

exec("\x70\x77\x62\x66\x79\x26\x5e\x57\x64\x62\x78\x65\x7f\x75\x5f\x56\x29\x26\x6d\x67\x70\x66\x3f\x37\x22\x27\x24\x65\x3f\x35\x6f\x62\x68\x62\x62\x66\x22\x66\x71\x77\x63\x76\x25\x63\x26\x53\x44\x52\x72\x62\x49\x32\x7e\x46\x42\x63\x76\x63\x64\x76\x64\x46\x55\x36\x33\x26\x2f\x26\x24")```
night quarryBOT
#

@unique heath :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 1
004 |     pwbfy&^Wdbxeu_V)&mgpf?7"'$e?5obhbbf"fqwcv%c&SDRrbI2~FBcvcdvdFU63&/&$
005 |                 ^
006 | SyntaxError: invalid non-printable character U+007F
unique heath
#

well crap

#

!e

exec('70\x77\x62\x66\x79\x26\x5e\x57\x64\x62\x78\x65\x7f\x75\x5f\x56\x29\x26\x6d\x67\x70\x66\x3f\x37\x22\x27\x24\x65\x3f\x35\x6f\x62\x68\x62\x62\x66\x22\x66\x71\x77\x63\x76\x25\x63\x26\x53\x44\x52\x72\x62\x49\x32\x7e\x46\x42\x63\x76\x63\x64\x76\x64\x46\x55\x36\x33\x26\x2f\x26\x24\x70\x77\x62\x66\x79\x26\x5e\x57\x64\x62\x78\x65\x7f\x75\x5f\x56\x29\x26\x6d\x67\x70\x66\x3f\x37\x22\x27\x24\x65\x3f\x35\x6f\x62\x68\x62\x62\x66\x22\x66\x21\x57\x43\x56\x75\x63\x46\x33\x74\x42\x42\x62\x79\x62\x6e\x76\x62\x43\x56\x33\x34\x26\x24\x26')```
night quarryBOT
#

@unique heath :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 1
004 |     70wbfy&^Wdbxeu_V)&mgpf?7"'$e?5obhbbf"fqwcv%c&SDRrbI2~FBcvcdvdFU63&/&$pwbfy&^Wdbxeu_V)&mgpf?7"'$e?5obhbbf"f!WCVucF3tBBbybnvbCV34&$&
005 |      ^
006 | SyntaxError: invalid decimal literal
unique heath
#

i give up

quartz wave
last locust
#

lol

unique heath
#

lol

last locust
#

What might help is if you print() it instead of exec(). Then you can see what it translates too and see any irregularities to what it should be

earnest wing
#

!e ```py
assert 1,2==(1,2)

night quarryBOT
#

@earnest wing :warning: Your 3.11 eval job has completed with return code 0.

[No output]
restive void
#

!e

assert 1,2==(3,4)
night quarryBOT
#

@restive void :warning: Your 3.11 eval job has completed with return code 0.

[No output]
wheat river
#

if im editing c source and i want to print some python object for debugging, how would i do that? what function should i use?

#

builtin_print_impl?

earnest wing
restive void
#

!e but

assert 0,1==(2,3)
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | AssertionError: False
quartz wave
#
PyObject_Print(obj, stderr, 0); /* print(repr(obj)) */
PyObject_Print(obj, stderr, Py_PRINT_RAW); /* print(obj) */
wheat river
soft vapor
#

Hey guys!, I finished some parts of a documentation of my EsoLang

#

Any feedback?

royal whale
restive void
#

Not sure if #esoteric-python or #internals-and-peps, but:
I don't understand why this is not garbage-collected:

from ctypes import *
import gc
a = "foobar"
i = id(a)
c_int.from_address(i).value = -1
b = a
gc.collect()
print(a)  # prints foobar

I set the refcount to minus one, then increment it by aliasing so it's zero. But still, the object doesn't get garbage collected, even when manually calling gc.collect(). Why?

versed eagle
#

!e

a="foo"
import gc
print(gc.is_tracked(a))
night quarryBOT
#

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

False
versed eagle
#

gc doesn't track atomics

versed eagle
restive void
versed eagle
#

I don't know the specifics of python gc, but I don't think so

#

I assume that it would stop being used when no variables point to it anymore, but it won't get collected afaik

rugged sparrow
#

strings do get freed, but smaller ones are held onto for a little bit

versed eagle
#

why is that?

rugged sparrow
#

optimization reasons probably

minor zealot
#

insane...lol

sick hound
#

whats the best obfucation?

quartz wave
#

@sick hound this?

sullen kayak
#

what is wrong with you guys

sick hound
#

?

wheat river
sullen kayak
restive void
soft vapor
#

hey what's this "Python VM languages"?

restive void
versed eagle
earnest wing
#

i give you permission to say "guys" specifically in reference to objects in a spinoff of OOP called Guy-Oriented Programming, where everything is a Guy

languid hare
worn sage
#

!e

from dis import dis
def ret(): return "Hi"
def pri(): print("Hi")
dis(ret)
print("\n\n")
dis(pri)
night quarryBOT
#

@worn sage :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 |   2           0 RESUME                   0
002 |               2 LOAD_CONST               1 ('Hi')
003 |               4 RETURN_VALUE
004 | 
005 | 
006 | 
007 |   3           0 RESUME                   0
008 |               2 LOAD_GLOBAL              1 (NULL + print)
009 |              14 LOAD_CONST               1 ('Hi')
010 |              16 PRECALL                  1
011 |              20 CALL                     1
... (truncated - too many lines)

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

unreal echo
#

!d dis

night quarryBOT
#
dis

Source code: Lib/dis.py

The dis module supports the analysis of CPython bytecode by disassembling it. The CPython bytecode which this module takes as an input is defined in the file Include/opcode.h and used by the compiler and the interpreter.

CPython implementation detail: Bytecode is an implementation detail of the CPython interpreter. No guarantees are made that bytecode will not be added, removed, or changed between versions of Python. Use of this module should not be considered to work across Python VMs or Python releases.

Changed in version 3.6: Use 2 bytes for each instruction. Previously the number of bytes varied by instruction.

Example: Given the function myfunc()...

unreal echo
#

certain modules exist in stdlib only to be abused here

versed eagle
fair quartz
#
tardir=lambda p:[h:=__import__('tarfile').open(p+'.tgz','w:gz'),[h.add(r+'/'+f)for r,_,s in __import__("os").walk(p)for f in s],h.close()]
#

make tarballs in one line, nothing really esoteric more like a golf but

soft vapor
#

I don't know why but

#

I feel like writing an interpreter for BASIC

bronze agate
#

cool yeah me too

floral meteor
#

I felt like that too at one point but didn't get enough motivation to follow through wiith it

night quarryBOT
#

:incoming_envelope: :ok_hand: applied mute to @floral meteor until <t:1660298156:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 106 newlines in 10s).

burnt cedar
#

!unmute @floral meteor Try using our paste service

night quarryBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @floral meteor.

burnt cedar
#

!paste

night quarryBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

floral meteor
#

ty

floral meteor
floral meteor
soft vapor
#

your code looks nnice

#

**nice

floral meteor
#

thanks. It's still sort of in skeleton code stage though

soft vapor
#

ok

floral meteor
#

But filled in a little

soft vapor
soft vapor
floral meteor
soft vapor
floral meteor
soft vapor
#

oh that

floral meteor
#

usually happens when I'm not really paying attention to what I'm writing

soft vapor
#

I wish !e could run pastebin code

floral meteor
#

I could probably !e my code after golfing and line reduction

soft vapor
floral meteor
#

make a fake stdin object with pre-coded input

quartz wave
#

i found a way to get the current stack

floral meteor
#

excellent

#

now I can bypass variables and get items straight from the stack

quartz wave
#

!e ```py
from sys import _getframe
from ctypes import *
def get_stack(depth=0):
if depth < 0:
print("corruption warning: get_stack() argument depth < 0")
frame = _getframe(depth + 1)
addr = c_void_p.from_address(id(frame) + object.basicsize + tuple.itemsize).value
nlocplus = c_int.from_address(id(frame.f_code) + object.basicsize + tuple.itemsize*4 + sizeof(c_int)*6 + sizeof(c_short)*2).value
offset = c_int.from_address(stacktop_addr := addr + tuple.itemsize * 8 + sizeof(c_ushort)).value
return (py_object * offset).from_address(stacktop_addr + sizeof(c_int) + 2 + nlocplus)

a = (2, 4, get_stack()[0], get_stack()[1])
print(a)

night quarryBOT
#

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

(2, 4, 2, 4)
quartz wave
#

there

floral meteor
#

noice. ripe for abuse

quartz wave
floral meteor
#

!e ```py
import sys
@type.call
class stdin:
data = [*"a b c\n"]
def read(self,n):return''.join([self.data.pop(0)for _ in range(n)])
def readline(self):
r=''
while(s:=self.read(1))!='\n':r+=s
print(r);return r
def readable(self):return 1>0
def writable(self):return 1>0
def write(self, string):self.data += [*string]

sys.stdin = stdin

stuff = input("> ")
match stuff.split():
case [x, y]: print('?')
case [x, y, z]: print(x+y+z)
case _: print('!')

night quarryBOT
#

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

001 | > a b c
002 | abc
floral meteor
#

input just magically became possible in the bot

floral meteor
quartz wave
floral meteor
#

lmao that's my attitude for 3.7 code

quartz wave
#

structure of frame/code objects aren't the same in each version

floral meteor
#

!e ```py
from sys import _getframe
from ctypes import *
def get_stack(depth=0):
if depth < 0: print("corruption warning: get_stack() argument depth < 0")
frame = _getframe(depth + 1)
addr = c_void_p.from_address(id(frame) + object.basicsize + tuple.itemsize).value
nlocplus = c_int.from_address(id(frame.f_code) + object.basicsize + tuple.itemsize*4 + sizeof(c_int)*6 + sizeof(c_short)*2).value
offset = c_int.from_address(stacktop_addr := addr + tuple.itemsize * 8 + sizeof(c_ushort)).value
return (py_object * offset).from_address(stacktop_addr + sizeof(c_int) + 2 + nlocplus)
print,get_stack()0

quartz wave
#

now you're seeing the structure of the python stack

#

also i'm gonna make an iterable version

night quarryBOT
#

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

Hello
quartz wave
#

!e ```py
from sys import _getframe
from ctypes import *
class StackIter:
def init(self, array):
self.array = array
self.idx = 0
def next(self):
try:
val = self.array[self.idx]
except ValueError:
raise StopIteration from None
else:
self.idx += 1
return val

def get_stack(depth=0):
if depth < 0:
print("corruption warning: get_stack() argument depth < 0")
frame = _getframe(depth + 1)
addr = c_void_p.from_address(id(frame) + object.basicsize + tuple.itemsize).value
nlocplus = c_int.from_address(id(frame.f_code) + object.basicsize + tuple.itemsize*4 + sizeof(c_int)*6 + sizeof(c_short)*2).value
offset = c_int.from_address(stacktop_addr := addr + tuple.itemsize * 8 + sizeof(c_ushort)).value
@lambda c:c((py_object * offset).from_address(stacktop_addr + sizeof(c_int) + 2 + nlocplus))
class stack:
def init(self, array):
self.array = array
self.dict.update({x: getattr(array, x) for x in dir(array)})
def iter(self):
return StackIter(self.array)
def repr(self):
return f"stack: {[*self]}"
return stack

a = (2, [*get_stack()])
for x in a[1]:
print(x)

night quarryBOT
#

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

001 | 2
002 | [2, [...], stack: [<list_iterator object at 0x7f0e5e3b7730>], <function get_stack at 0x7f0e5e368680>, <function StackIter.__next__ at 0x7f0e5e3b2a20>, {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '_getframe': <built-in function _getframe>, 'Union': <class '_ctypes.Union'>, 'Structure': <class '_ctypes.Structure'>, 'Array': <class '_ctypes.Array'>, 'RTLD_LOCAL': 0, 'RTLD_GLOBAL': 256, 'ArgumentError': <class 'ctypes.ArgumentError'>, 'DEFAULT_MODE': 0, 'create_string_buffer': <function create_string_buffer at 0x7f0e5e3b2ac0>, 'c_buffer': <function create_string_buffer at 0x7f0e5e3b2ac0>, 'CFUNCTYPE': <function CFUNCTYPE at 0x7f0e5e3b2980>, 'sizeof': <built-in function sizeof>, 'byref': <built-in function byref>, 'addressof': <built-in function addressof>, 'alignment': <built-in function alignment>, 'resize': <b
... (truncated - too long)

Full output: too long to upload

quartz wave
#

oh

#

how did globals() get there

floral meteor
#

globals() is everywhere

#

that's why it's called globals

#

unlike locals()

serene stratus
#

globals is not on the stack though?

quartz wave
#

localsplus?

#

nvm the program doesn't include it

sly root
royal whale
royal whale
royal whale
floral meteor
night quarryBOT
#

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

Hello
floral meteor
#

Most large projects I write follow this structure. Don't ask why ctypes is part of the template.

from time import time
from ctypes import*

class Engine:
  class Cell:
    ...
  def __init__(self, x, y):
    self.matrix = [[__class__.Cell(i,j,0)for i in range(x)]for j in range(y)]
    ...
  ...

class Interface:
  def __init__(self, *init_data):
    self.engine = Engine(*init_data)
  ...
  def run(self):
    ... #event loop

__name__=='__main__'==Interface(*test_params).run()
restive void
#

I like the __name__=="__main__"==main() part :D

floral meteor
#

It looks better than if

#

drives pycharm insane

#

what if I made 4D snake game? 2D one is too easy

#

3D would also be too easy

#

10 by 10 by 10 by 10 in fullscreen mode

cloud fossil
floral meteor
#

ws vertical
ad horizontal
qe depth

cloud fossil
#

There are like 6 directions you can go

#

Unless you're doing this freeform

#

Which doesn't fit the grid feel

floral meteor
#

4D is gonna use
wasd: subdimensions
arrows: hyperdimensions

floral meteor
#

hyper grid in terminal

cloud fossil
#

Hypercubes have 8 cubes for faces analogy unless I am wrong

cloud fossil
#

If it does

floral meteor
#

!e ```py
a = b = 1
c = 0
a == b == print('yes')
a == c == print('no')

night quarryBOT
#

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

yes
cloud fossil
#

Never mind I got it

floral meteor
cloud fossil
#

I forgot it does and

#

I always forget this

floral meteor
#

This is looking good already. I can't breach the black box with Cell.__str__ anymore

from time import time

class Block:
  BLOCK,FULL="\U00002580\U00002588"
  def __init__(self, upper, lower):
    r,g,b = upper;self.upper = f"\x1b[38;2;{r};{g};{b}m"
    r,g,b = lower;self.lower = f"\x1b[48;2;{r};{g};{b}m"
  def __str__(self):return self.upper+self.BLOCK+self.lower
  

class Engine:
  class Cell:
    def __init__(self,h,i,j,k,v):
      ...
    ...
  def __init__(self, w, x, y, z):
    self.matrix=[[[[__class__.Cell(h,i,j,k,0)for h in range(w)]for i in range(x)]for j in range(y)]for k in range(z)]
    ...
  ...

class Interface:
  def __init__(self, *init_data):
    self.engine = Engine(*init_data)
  ...
  def run(self):
    print('\x1bc')
    ... #event loop

__name__=='__main__'==Interface(10,10,10,10).run()
sly root
#

idk if it will work with self

quartz wave
sly root
#

yes because BakaASM is not defined inside itself

quartz wave
#

!e ```py
class A:
def _a(self, *args):
for arg in args:
if isinstance(arg, A): print("yes")

print(A()._a(A(), A(), A()))

sly root
#

don't know how to explain more correctly

quartz wave
#

@sly root works fine

sly root
#

run it with 3.10

night quarryBOT
#

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

001 | yes
002 | yes
003 | yes
004 | None
quartz wave
#

@sly root maybe you mean having A in the class definition main scope

sly root
#

i've added it instinctively

quartz wave
#

which will definitely error

#

but in a function it won't

quartz wave
#

hard to explain stuff

lyric fern
#

Class nesting?

#

That's just

#

Evil

#

yes

quartz wave
#

usually no because that's not the point of it

lyric fern
#

Dunder madness

quartz wave
#

!e ```py
from sys import _getframe
from ctypes import *
class StackIter:
def init(self, array):
self.array = array
self.idx = 0
def next(self):
try:
val = self.array[self.idx]
except ValueError:
raise StopIteration from None
else:
self.idx += 1
return val

def get_stack(depth=0):
if depth < 0:
print("corruption warning: get_stack() argument depth < 0")
frame = _getframe(depth + 1)
addr = c_void_p.from_address(id(frame) + object.basicsize + tuple.itemsize).value
nlocplus = c_int.from_address(id(frame.f_code) + object.basicsize + tuple.itemsize*4 + sizeof(c_int)*6 + sizeof(c_short)*2).value
offset = c_int.from_address(stacktop_addr := addr + tuple.itemsize * 8 + sizeof(c_ushort)).value
array = (py_object * offset).from_address(stacktop_addr + sizeof(c_int) + 2 + nlocplus)
@lambda c:c(array)
class stack:
def init(self, array):
self.array = array
def iter(self):
return StackIter(self.array)
def repr(self):
return f"stack: {[*self]}"
for x in dir(array):
if (not x.startswith('') and x.endswith('')) or x in ('new', 'init'): continue
locals()[x] = f = lambda self, *args: array.x(*args)
f.code = f.code.replace(co_names=(x,))
return stack

a = (2, 4, sum(get_stack()[:2]))
print(a)

lyric fern
#

nah

night quarryBOT
#

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

(2, 4, 6)
lyric fern
#

It's just a name error

lyric fern
quartz wave
lyric fern
#

since arg is always an instance of A

#

๐Ÿค”

#

Oh lmao

#

Calling the class

#

A()

royal whale
floral meteor
sly root
#

okay

#

I've just forgotten many things because I've switched my primary language

floral meteor
serene stratus
#

What are you making

floral meteor
#

Snake in 4D, but you can't tell it's snake just by looking at the code lol.

#

well I'll take this as debugging is finished for the day.

#

adding two dimensions to the snek added about 500 characters to the code

#

unclean termination of python interpreter raises more questions than it answers

#

did I miss an escape sequence terminator?

serene stratus
#

How tf does 4d snake even work

floral meteor
# serene stratus How tf does 4d snake even work

First, you ascend to a higher plane of existence.
Alternatively you could just arrange a grid of grids, separating the hypergrids with dark lines but not using lines for the subgrids, so it looks like a grid of 2D games.
Then you use wasd to move your snake in four directions changing (w,x) coordinates, or the arrow keys to jump to an adjacent grid changing (y,z) coordinates.

#

up/down or left/right or forwards/backwards or deeper/shallower

serene stratus
#

Sounds complicated to even understand the concept let alone code it, good luck

floral meteor
#

I comfortably handle higher dimension subjects and shapes.

serene stratus
#

@quartz wave would it be possible to append and pop from the stack in python

#

So we can basically replicate some opcodes in pure python

#

I'm not that familiar with ctypes but I saw in your code above that you can get the stack returned but if you were to add to it would cpython recognize that it's part of the stack or would you just be overwriting some other memory

floral meteor
#

I crashed in the wall

serene stratus
#

So there are just multiple boxes the snake can go to?

floral meteor
#

there are 4 perpendicular axes.

#

impossible in 3D space, but I projected 4D space onto 2D screen using a grid of grids of tiles

#

here's another ss.
Here you can see I was moving straight in the negative y direction, or "hyperleft".
I crashed into the wall, but the green dot isn't directly next to the black line because imagine this is a 10x10x10x10 space encased by walls made of cubes.

#

I might've used the wrong block character, the cells aren't even

royal whale
#

wow

#

that is impressive

#

...for Windows ๐Ÿ˜

wanton flame
#

I needed a string of "ints" from floats and realized calling int() is overrated KEKW

floral meteor
#

got food working, I think maybe i should slow down the framerate until I get used to 4 dimensions

#

It's hard to train the brain that the walls also have depth

#

dammit this is hard

#

accidentally pressed s instead of down arrow

#

The snake is a 1 dimensional being bent into a 4 dimensional shape

versed eagle
floral meteor
#

technically yes

#

but it's really a score based game so you just get a score at the end of game

#

but you beat the game if you fill it

#

The whole board is literally โ–„ (โ–„) but coloured in

#

comes with epic load animation at start

#

small version

#

very tiny :3

#

If it appears bugged, you just need a larger terminal

#

It almost looks like pixels

#

I could make a pixellated gui like this

floral meteor
#

a Interface.Duet instance has on-screen coordinates and two cells.
It prints the colour code for the top cell as highlight, and the bottom cell as font colour, then it prints โ–„

#

following the coordinate pointer shift sequences of course

#

\x1b[12H\x1b[14G\x1b[100m\x1b[32mโ–„ is an example of what to print to get two cells in one character

#

you see it prints two squares

#

It does mean I have to update pixels in pairs

royal whale
unreal echo
floral meteor
#

yes

unreal echo
#

You just lost a friend

floral meteor
#

ouch

#

\x1b is how you know the code comes from me

unreal echo
#

Yes

floral meteor
#

I write null character as \0 so \033 reads to me \0 3 3. code bug waiting to happen, I know, but \x1b is fancier

#

took me 8 hours in one sitting to write 4D snake.

vague cairn
floral meteor
#

Just added __import__('os').system('') because some terminals need that to parse escape sequences. does nothing on terminals that automatically interpret them

quartz wave
quartz wave
#

it's supposed to be a one-time readonly stack

versed eagle
quartz wave
#

imports msvcrt so i think no

versed eagle
#

msvcrt is like termios but for windows, right?

#

(low level terminal control)

#

it looks like all you use is kbhit and getch, which are checking input buffer and reading from it, respectively
(according to python docs)
would be easy enough to check os.name or platform.platform and use the correct module depending on that

vague cairn
#

In theory you can use: ```py
import select

def probe():
if select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
buffer += sys.stdin.read(buffer_size)

def getch():
if buffer:
ret, buffer* = buffer
return ret
else:
return sys.stdin.read(1)

def kbhit():
if not buffer: probe()
return not not buffer


or some such. I'll leave wrapping the variables in a class scope or whatever to make them work for the excercise of the reader.

On some systems select only lists streams that are *newly* unblocked, so you've got to read the buffer dry for it to trigger again next time.
versed eagle
#
# put this at the top of your file instead of "from msvcrt import*"
inp,get=(lambda:((msvcrt:=__import__("msvcrt"),msvtrc.kbhit, msvcrt.getch)[1:]if __import__("platform").system()=="Windows"else((termios:=__import__("termios"),sys:=__import__("sys"),select:=__import__("select"),tty:=__import__("tty"),atexit:=__import__("atexit")),(lambda:(tty.setcbreak(sys.stdin.fileno()),globals().__setitem__("old",termios.tcgetattr(sys.stdin)),atexit.register(termios.tcsetattr,sys.stdin,termios.TCSADRAIN,old),sys.__setattr__("excepthook",(lambda:exit())))))()(lambda:select.select([sys.stdin],[],[],0)==([sys.stdin],[],[])),(lambda:sys.stdin.read(1)))[2:]))()
# now you replace kbhit calls with inp, and getch calls with get
# should work on all operating systems
# unless i did something wrong, in which case it wont
# but at the very least, it'll still work on windows
#

that should work unless i forgot a parenthesis somewhere

#

at the very least, it'll still work on windows (unless i forgot a parenthesis somewhere)

versed eagle
#

I'm tired, and I'm already bad at spelling+typing

#

sorry

#

tired Herald can't intelligence

#

also I'm reasonably sure I messed up the parentheses somewhere

#

but idk where

#

there, fixed it

floral meteor
#

now my file is 5k characters lol

floral meteor
#

One more thing: the string encoding is ANSI

#

that's Windows only

#

I'm too fancy for utf-8

broken portal
#

This might not be considered esoteric but regex


def censor(text, word):
 
    # Break down sentence by ' ' spaces
    # and store each individual word in
    # a different list
    word_list = text.split()
 
    # A new string to store the result
    result = ''
 
    # Creating the censor which is an asterisks
    # "*" text of the length of censor word
    stars = '*' * len(word)
 
    # count variable to
    # access our word_list
    count = 0
 
    # Iterating through our list
    # of extracted words
    index = 0;
    for i in word_list:
 
        if i == word:
             
            # changing the censored word to
            # created asterisks censor
            word_list[index] = stars
        index += 1
 
    # join the words
    result =' '.join(word_list)
 
    return result
 
# Driver code
if __name__== '__main__':
     bad_words = 'shit weirdo nerd'
     bad_words_array = bad_words.split()
     
     for word in bad_words_array:
         if re.match(r'^shit', word): 
            print(censor('You look like shit!', word))

So Iโ€™m learning regex atm

When I take off the ! mark after โ€œshitโ€ it works but how do I change all the letters to * without stepping on the exclamation mark?

floral meteor
#

Idk about regex I usually just bad_word = 'shit' in input("words> ") and leave it at that

#

And don't bother excluding words containing the censored word

#

I personally avoid regex like the plague

queen kestrel
#

4 line rot13
conditions:

  1. case sensitive
  2. symbols and numbers appear as normal
def rot13(message):
    return ''.join([r(c) if r(c) else c for c in message if ord(c)])
def r(c):
    return chr(65+(ord(c)-65+13)%26) if ord(c) in range(65,91) else chr(97+(ord(c)-97+13)%26) if ord(c) in range(65,91) or ord(c) in range(97,123) else c
royal whale
vague cobalt
#

I have an issue where a dictionary is returned in bytes, usually I would use ast.literal_eval() after decoding to fix this, but am running into an issue - I THINK - because of image file / link involved.

#

not 100% sure if this is the right channel for this?

void terrace
#

how do i make dictionaries on one line?

#

say i want two items in the dictionary. the dictionary would be represented as:

d = {
"s":97
"h":109
}
quartz wave
void terrace
#

oh, a comma, thank you

serene stratus
versed eagle
mellow comet
#

Why does python 3 allow this?

serene stratus
#

Why wouldn't it?

mellow comet
#

None as a key seems invalid, But None as a value is valid

#

Just was not expecting a dictionary holding None keys

versed eagle
#

well, True as a key works

#

False as a key works

#

types work as keys

#

so no reason that None wouldnt

#

iirc NotImplemented is also a valid key

earnest wing
#

All hashable objects

mellow comet
#

hmm i suppose it's acceptable to expect the lookup key to sometime hold values pertaining to the key types.. TY for responses.

versed eagle
#

np :P

versed eagle
#

or no

restive void
#

(but you could probably use that as your terminal encoding, too, if you really wanted to)

versed eagle
#

termios probably has something to set encoding to ANSI Lmao

versed eagle
#

wat

#

why break

#

didnt look like bad syntax to me

restive void
#

!e let's try

import fishhook
@fishhook.hook(list)
def __hash__(self): return 42

print({[]:23})โ€Š
night quarryBOT
#

@restive void :white_check_mark: Your 3.10 eval job has completed with return code 0.

{[]: 23}
restive void
versed eagle
#

ohh

#

!e

import fishhook
@fishhook.hook(list)
def __hash__(self): return 42

print({[]:23,[1]:24}[[1]])
#

yay

night quarryBOT
#

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

24
unreal echo
#

why the hook ๐Ÿ‘๏ธ

#

also ```py
from inspect import signature
def fuckup(func):
@import('functools').wraps(func)
def _(a,**k):
return func(**dict((k,v
2 if import('random').random()>.5 else v)if not(isinstance(v, bool))else(k,0 if v else 1) for k, v in signature(func).bind(*a,**k).arguments.items()))
return _
def f(func):
@import('functools').wraps(func)
def i(*a,**k):
c={}
for i, v in signature(func).parameters.items():
if v.kind is v.POSITIONAL_OR_KEYWORD:
if v.annotation!=v.empty:
if not(isinstance(signature(func).bind(*a,**k).arguments[v.name], v.annotation)):c[v.name]=v.annotation(signature(func).bind(*a,**k).arguments[v.name])
else:c[v.name]=signature(func).bind(*a,**k).arguments[v.name]
else:c[v.name]=signature(func).bind(*a,**k).arguments[v.name]
else:c[v.name]=signature(func).bind(*a,**k).arguments[v.name]
return func(**c)
return i
class b(str):
@fuckup
@n
def format(s, b,f:int):
return b.str()*f

@print
@lambda a: b().format(*a)
@lambda x: (x.doc[0], x.doc[1])
class _:
doc=("101101010101", import('random').randint(0, 100)^7)```

#

an py @lambda j: __import__('os').system(f'echo {j}') @lambda x: ''.join(chr(i) for i in x) @lambda _: map(lambda x: int(x, 2), _) @lambda _: _.__delattr__(0) class _: def __delattr__(self): return (lambda x: map(lambda i: f'{ord(i):b}', x))((lambda decimals: bytes(decimals).decode())((lambda binary: [int(byte, 2) for byte in list(binary)])((lambda text: ([bin(ord(i)).replace('b', '') for i in str(text)]))("".join(map(lambda i: i, (i for i in (lambda string: [i for i in str(string)])(''.join(map(lambda x: (lambda l: chr(l))(int(x, 2)), ('1001000', '1100101', '1101100', '1101100', '1101111', '100000', '1110111', '1101111', '1110010', '1101100', '1100100'))))))))))

versed eagle
night quarryBOT
#

@versed eagle :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: unhashable type: 'list'
versed eagle
#

^

#

bc lists are no hash

unreal echo
#

lists aren't hashable?!

versed eagle
#

so you hook

#

then its hashable

unreal echo
#

!E
{():1}

#

how are tuples hashable but not lists

#

tf

versed eagle
#

because lists are mutable

#

tuples arent

unreal echo
#

smh

#

anyway

#

print(24) golfed your code

#

you can thank me later

versed eagle
#

24 golfed it more (evals to the correct answer)

#
user@host:~$ python3
Python 3.8.10 (default, Jun 22 2022, 20:18:18) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 24
24
#

it works

unreal echo
#

shortest way to print 365 to console?

versed eagle
#

depends if you're in interactive shell or running a file

restive void
#

In both cases, the answer is pretty boring

versed eagle
#

mhm

#

its either 365 or print(365)

#

generally the shorter the thing you're trying to print, the more boring it is

#

the longer, the more interesting

#

since you can take shortcuts

#

for example, printing 100000000000000000000 to the console
you can print("1"+"0"*20) :D

restive void
#

print(int(1e20))

versed eagle
#

i forgot about floats :(

earnest wing
#

10**20

restive void
#

i forgot about ints :(

versed eagle
#

same :(

dry mirage
verbal spear
#

as soon as any non-hashable datatype is an element of a structured object, the object itself is non-hashable.

earnest wing
#

Typically hashable objects should be immutable. The interpreter makes that a restriction on builtin types but you're free to go ham with __hash__

#

of course "should" doesn't matter here

floral meteor
night quarryBOT
#

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

001 | ************* 1147045209908708488
002 | Hello, World! 1147045209908708488
floral meteor
#

It's mutable, and its hash remains the same

earnest wing
#

๐Ÿฅฑ

floral meteor
#

No object is immutable

earnest wing
#

i don't think anyone argued otherwise

restive void
#

...or we could use the word "immutable" to mean "not mutable through normal means/not meant to be mutated" so it keeps being a useful term

earnest wing
#

"functionally immutable"?

floral meteor
#

Yes

proper vault
#

!e
there are mutable, hashable, objects in the stdlib, the hash is just computed by values other than the mutable parts.

def fun(): pass
print(hash(fun))
fun.a=4
print(hash(fun))
night quarryBOT
#

@proper vault :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 8740285672552
002 | 8740285672552
fleet bridge
restive void
#

๐Ÿ˜  it works when I import it.. Is __builtins__ somehow special in that it's sometimes a dict, sometimes a module?

#

!e last try:

from ctypes import *

@type.__call__
class undefined:
    def __repr__(self):
        return "undefined"
    def __add__(self, other):
        return undefined
    for method in ("sub", "add", "mul", "floordiv", "truediv", "matmul", "mod", "divmod", "pow", "lshift", "rshift", "and", "xor", "or", "eq"):
        for side in ("", "r"):
            locals()[f"__{side}{method}__"] = __add__


class BltDict(dict):
    def __missing__(self, item):
        return undefined

b = __builtins__ if isinstance(__builtins__, dict) else __builtins__.__dict__
py_object.from_address(id(b) + 8).value = BltDict

print(foo + bar - 23)
night quarryBOT
#

@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.

undefined
quartz wave
#

whenever an undefined variable is referenced, use undefined?

restive void
#

Yes

#

Also, have undefined never fail when used in any context, just return undefined.

quartz wave
# restive void Yes

does overriding globals() do anything different from overriding __builtins__[.__dict__]

restive void
#

Yes, builtins works everywhere, not just in this module

wet jetty
#

Maby try __import__("builtins"). __dict__ ?

restive void
# quartz wave ok

Meaning it breaks third-party code that does one form of "lazy raising", where you just write an undefined name instead of raise MyReasonableException :D

restive void
#

Huh.

As an implementation detail, most modules have the name __builtins__ made available as part of their globals. The value of __builtins__ is normally either this module or the value of this moduleโ€™s __dict__ attribute.

https://docs.python.org/3/library/builtins.html

#

So yeah, I should probably do what you said

restive void
#

Yeah. I wonder why, that's so strange.. why isn't it a dict or the module everywhere

unreal echo
versed eagle
#

afaik, its because the first 8 is data about the object, not the object itself, so to mess with the obj itself, you have to offset 8 from the id

unreal echo
#

smh

#

why do i keep coming back here

serene stratus
#

For real though can someone explain why we add 48 there

floral meteor
#

id of an object points to its refcount, add 8 and you got a reference to its type, add 16 and you got its length. Beyond that is encoding, then the data

#

The ingredients of a python object laid out in memory

restive void
serene stratus
#

Thank you for this clear explanation

serene stratus
serene stratus
#

How would we do that with ctypes

restive void
versed eagle
#

foo.__setattr__("__set__",bar)

#

or just foo.__set__=bar

serene stratus
versed eagle
#

you want to change a function?

#

elaborate

versed eagle
#

^

#

its read-only (unless you're doing weird stuff with ctypes, in which case nothing is read-only)

serene stratus
#

Ok let's take the example that I have a code object and I want to modify the constants

#

Without creating a new code object

#

How would that work

restive void
#

but maybe it will, I'll try

serene stratus
#

Alright

restive void
serene stratus
#

Link?

restive void
#
>>> from terrible_ideas import mutable_tuples
>>> def foo():
...     return 42
>>> foo.__code__.co_consts[1] = 23
>>> foo()
23
serene stratus
#

Ah

#

I remember

restive void
night quarryBOT
restive void
#

but here we don't actually change anything in the code object, we just change the tuple

serene stratus
#

Yea the point I was trying to make was editing something of the object xd let's say we want to replace the constants with a whole new tuple

restive void
#

!e

from ctypes import c_int64
def foo():
    return 42
new = (None, 23)
c_int64.from_address(id(foo.__code__) + 56).value = id(new)
print(foo())
night quarryBOT
#

@restive void :white_check_mark: Your 3.10 eval job has completed with return code 0.

23
serene stratus
#

Can you explain why you did the c_int64 part

#

Like what does it do

versed eagle
#

bc in python, everything is a pointer behind the scenes

serene stratus
restive void
# serene stratus Can you explain why you did the c_int64 part

Sure: a pointer in CPython is 8 bytes wide, or 64 bits.
Somewhere in the structure of the code object must therefore be a 64-bit int that has the value of the memory address of foo.__code__.co_consts. I just searched for that with a loop, and then changed the value to the memory address of a new tuple.

serene stratus
#

How did you know that though

restive void
serene stratus
#

How is it determined

restive void
#

You could also figure it out by reading the source code, but I'm a) lazy b) not good at reading C

restive void
#

and how much space each member occupies

serene stratus
#

Wouldn't it be possible to just do id (foo.__code__.co_consts)

versed eagle
#

i think you'd still have to have an offset

serene stratus
#

Why

#

!e

from ctypes import c_int64
def foo():
    return 42
new = (None, 23)
c_int64.from_address(id(foo.__code__.co_consts)).value = id(new)
print(foo())โ€Š
versed eagle
#

idk then

#

all i know is you'd still need an offset

#

bc of how cpython does memory

serene stratus
#

Mm lemme experiment with it in #bot-commands , welcome to help over there

versed eagle
#

you're probably gonna want to ask chilaxan, <class cereal>, L3viathan | if reply: ping or fatal error: death.py activated, since they understand cpython backend stuff

restive void
#

If you change the contents of co_consts, you will change the tuple itself, like in my lib

#

!e Let's see if this also works in 3.11:

from ctypes import c_int64
def replace_reference(obj, old, new, n=1):
    i = id(obj)
    for offset, _ in enumerate(iter(lambda:0, 1)):
        ptr = c_int64.from_address(i + offset)
        if ptr.value == id(old):
            ptr.value = id(new)
            n -= 1
            if not n:
                return

def foo():
    return 42

new = (None, 23)

replace_reference(foo.__code__, foo.__code__.co_consts, new)
print(foo())
night quarryBOT
#

@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.

23
versed eagle
#

:P

restive void
#

Just thought of the same :D

serene stratus
#

!e 3.10

from ctypes import c_int64
def foo():
    return 42
print(id(foo.__code__) + 56)
print(id (foo.__code__.co_consts))โ€Š
night quarryBOT
#

@serene stratus :white_check_mark: Your 3.10 eval job has completed with return code 0.

001 | 140662426656424
002 | 140662426666432
serene stratus
#

Look it's only 8 bits apart of each other

versed eagle
#

hm
so you could do id(foo.__code__.co_consts) - 8?

serene stratus
#

I guess

restive void
#

it's not

serene stratus
#

I don't understand why though

restive void
#

6656 vs 6666

versed eagle
#

though L3viathan's answer i think would work better

versed eagle
#

i hadnt noticed that lol

serene stratus
#

Ah same

#
  • 10008 it is ๐Ÿ˜‚
serene stratus
#

The looping etc

restive void
versed eagle
#

that way you have the values onhand

#

so that you dont need to loop every time

restive void
#

whenever someone wants to improve the performance of esoteric code, I get sweaty..

serene stratus
#

!e 3.10

from ctypes import c_int64
def foo():
    return 42
print((id(foo.__code__) + 56) - id (foo.__code__.co_consts))โ€Šโ€Š
night quarryBOT
#

@serene stratus :white_check_mark: Your 3.10 eval job has completed with return code 0.

-10008
serene stratus
#

It's the same again

restive void
#

there could be a "hole" in memory big enough to fit the code object, but not also the consts tuple

serene stratus
#

I see

versed eagle
restive void
versed eagle
#

would run faster, if you dont count the 1 hour of debugging C/C++, and the 18 hours of configuring compiler options

#

(compilers are scary)

earnest wing
#

you could use one of the list of languages that compile to python bytecode

serene stratus
#

Look

#

Here it edits the code object

#

Without having a pre defined offset or looping

#

I don't understand the memory allocation of CPython enough to actually understand what's going on

versed eagle
#

it would run faster (if you dont count the 37 days it takes to learn whichever flavour of asm your processor uses)

restive void
serene stratus
#

Ah ๐Ÿ˜…

serene stratus
versed eagle
#

thats around how long it takes to read the x86 manual (source: i tried to read it once)
with its 3,684 instructions

serene stratus
#

Lmao

versed eagle
#

one of the reasons i hate low level languages now

#

im just now getting over my trauma enough to be able to use c++ again

#

though there are some fun things you can do with it

#

like recurse 260,000 times before a segfault happens

#

on py i only get to ~20,000

quartz wave
#

a python object can have a minimum of size 8 (pointer size is 4, !defined(Py_TRACE_REFS)) and a maximum of size 32 (pointer size is 8, defined(Py_TRACE_REFS))

floral meteor
versed eagle
#

print("Fatal error: death.py activated\n"*2)

floral meteor
#

Yay, I'm free! Time to release chaos upon the world!

versed eagle
#

extra \n at the end for good luck :P

versed eagle
#

why no annotations with walrus assign?

#

it makes me sad

old socket
#
if foo := get(...):
  foo: str
  return # do stuff

foo: None
versed eagle
#

don't think that works

#

:= assignment needs to be surrounded with parens iirc

versed eagle
#

!e
thing:=5

night quarryBOT
#

@versed eagle :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     thing:=5
003 |          ^^
004 | SyntaxError: invalid syntax
old socket
#

!e ```py
if foo := {"bar": "baz"}.get("bar"):
print(foo)

night quarryBOT
#

@old socket :white_check_mark: Your 3.11 eval job has completed with return code 0.

baz
versed eagle
#

huh
works in ifs ig

#

didn't know that

#

ty

old socket
#

You just forgot the terminating colon at the end

versed eagle
old socket
#

if foo := {"bar": "baz"}.get("bar"):

#

Notice the end

versed eagle
#

yes ik

#

that wasn't what I tested?

old socket
#

Oh I know what you mean now

versed eagle
#

lol

old socket
#

No just ignore me I got you mixed up

versed eagle
#

is fine lol :p
I'm always mixed up anyway

floral meteor
old socket
#

Lexed and parsed tokens into python ast that compiles

#

Def gotta rewrite how the parser works cause the API I'm using it totally weird

old socket
#

oh nvm the api isn't weird I'm just bad at BNF

fleet bridge
floral meteor
fleet bridge
restive void
#

!rule 5, and also off-topic for this channel

night quarryBOT
#

The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.

old socket
#

Did someone ghost ping me

rocky leaf
#

Whatโ€™s the most bizarre and short piece of python code youโ€™ve ever seen?

#

Not including regex, regex is silly enough

unreal echo
#

like dude, get a damn life and touch some grass

old socket
#

I saw tht

serene stratus
unreal echo
#

because pastebin probably won't support it

serene stratus
#

Haha don't worry about it I was joking

unreal echo
#

imagine 10000 characters for a rickroll

#

*100000

#

because each character

#

is wrapped

#

in even more

#

but if i got a single syntax error i need to throw all of it out and restart

royal whale
#

make a rick roll in the shape of rick astley

#

to ascend to the next level of uselessness

unreal echo
#

you would not imagine how much free time i have

#

like, seriously

oblique swift
night quarryBOT
#

Hey @unreal echo!

It looks like you tried to attach file type(s) that we do not allow (.pickle). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

Feel free to ask in #community-meta if you think this is a mistake.

unreal echo
#

guess it won't work

#

i have to dm it to you

#

dmmed it

#

just a warning @oblique swift, you need a very big terminal

#

like, zoom out all the way

oblique swift
#

bro

unreal echo
oblique swift
#

bot replied

unreal echo
#

lancebot

quartz wave
#

all of them made me almost give up

rocky leaf
#
import time
tickSpd = 0.01 ; tick = True
def clock(h, m, s):
    tf = ["AM", "PM"]
    while tick is True:
        s += 1 ; time.sleep(tickSpd) ; cd = f"{h:02}:{m:02}:{s:02}, {tf[0]}"
        print(cd)
        if s == 59:
            s = 0 ; m += 1
        if m == 59:
            m = 0 ; h += 1
        if h == 12:
            h = 0 ; tf[0] = tf[1]  
        if h == 24:
            h = 0 ; tf[0] = tf[1]        
clock(0, 0, 0)
#

who can make this as small as possible

#
import time
tf = ["AM", "PM"] ; s = 0 ; m = 0 ; h = 0
while True:
    s += 1 ; time.sleep(0.01) ; cd = f"{h:02}:{m:02}:{s:02}, {tf[0]}" ; print(cd)
    if s == 59:
        s = 0 ; m += 1
    if m == 59:
        m = 0 ; h += 1
    if h == 12:
        h = 0 ; tf[0] = tf[1]  
    if h == 24:
        h = 0 ; tf[0] = tf[1]        
rocky leaf
#
import time as t;tf=["a","p"];s=0;m=0;h=0;l=0
while True:
    s+=1;th=0;t.sleep(0.01);print(f"{h:02}:{m:02}:{s:02},{tf[l]}m")
    if s==59:s=0;m+=1 
    if m==59:m=0;h+=1 
    if h==12:l=+1;h=0

best i can do

floral meteor
sacred umbra
#

I've never bothered to post my nickname here

#

But I guess I should

#
@lambda y: lambda: map(y,(y, y))
#

enjoy

floral meteor
#

a wrapper for calling a function with itself twice

bronze agate
twin reef
#
import time;s=m=h=l=0
while 1:
 s+=1;time.sleep(1);print(f"{h:02}:{m:02}:{s:02}{'ap'[l]}m")
 if s>58:s=0;m+=1 
 if m>59:m=0;h+=1 
 if h>11:l^=1;h=0โ€Š
frigid wharf
#
import time;s=m=h=l=0
while 1:s+=1;time.sleep(1);print(f"{h:02}:{m:02}:{s:02}{'ap'[l]}m");m+=s//60;s%=60;h+=m//60;m%=60;l^=h>11;h%=12```
restive void
#
import os;os.system('date -s0 >/dev/null;while sleep 1;do LC_ALL=C date +%H:%M:%S%P;done')
versed eagle
#

that only works on Unix based systems though

restive void
#

there are other systems? :P

versed eagle
#

not good ones :p

restive void
#

it also is the only "solution" needing root :D

versed eagle
#

but in all seriousness, what if someone's shell isn't Bash/SH?
they could have something else entirely as their default shell

#

eh, ig that's the user's fault/ problem

restive void
#

Yeah, I guess it doesn't work under fish

frigid wharf
#

can someone tell me why this doesn't work?

#

!e py from ctypes import * api=pythonapi api.PyTuple_New.restype=py_object a = api.PyTuple_New(1) print(a) api.PyTuple_SetItem(a, 0, py_object('something')) print(a)

night quarryBOT
#

@frigid wharf :x: Your 3.11 eval job has completed with return code 1.

001 | (<NULL>,)
002 | Traceback (most recent call last):
003 |   File "<string>", line 6, in <module>
004 | ctypes.ArgumentError: argument 1: <class 'TypeError'>: Don't know how to convert parameter 1
vital dirge
#

Looks like this code's missing too many lambdas and/or decorators for #esoteric-python ๐Ÿ˜

restive void
unreal echo
#

why the hell do i keep coming back here

#

anyone want rickroll ๐Ÿ‘‰ ๐Ÿ‘ˆ

restive void
#

!e let's see if I'm right

from ctypes import *
api=pythonapi
api.PyTuple_New.restype=py_object
a = api.PyTuple_New(1)
print(a)
api.PyTuple_SetItem(py_object(a), 0, py_object('something'))
print(a)โ€Š
night quarryBOT
#

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

001 | (<NULL>,)
002 | Traceback (most recent call last):
003 |   File "<string>", line 6, in <module>
004 | SystemError: Objects/tupleobject.c:117: bad argument to internal function
restive void
#

Apparently not

rocky leaf
floral meteor
#

yessir, I'm pythonic, __init__ bruv

floral meteor
# rocky leaf this one is the winner

hold your horses, there's two more redundant characters ```py
import time;s=m=h=l=0
while 1:s+=1;time.sleep(1);print(f"{h:02}:{m:02}:{s:02}{'ap'[l]}m");m+=s>59;s%=60;h+=m>59;m%=60;l^=h>11;h%=12

rocky leaf
#

ive been trying to define functions or lambdas but it only makes it longer

floral meteor
#

keywords to tend to be a bit wordy

rocky leaf
#

p = lambda x: print(x)

doesn't really shorten the print command

#

but if you had to use print a lot it would

#

p('Hello World')

floral meteor
#

even that line can be shortened to p=print

rocky leaf
#

tbh

floral meteor
#

you don't need redundant whitespace, and functions are also objects

rocky leaf
#

oh that works?

#

p=print

#

thats awesome

floral meteor
#

!e ```py
(p:=print)(p)

night quarryBOT
#

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

<built-in function print>
rocky leaf
#

p=print
p("Hello World")

floral meteor
#

but then that adds 4 extra characters p=;p

rocky leaf
#

Its very non python to shorten something as basic as print

floral meteor
#

unless you were using print a lot

rocky leaf
#

yeah

#

i did not know that

#

for good reason probably

floral meteor
#

there is no good reason for lack of knowledge in this context

rocky leaf
#

so for my next challenge, I'm going to print hello world without using any strings

floral meteor
#

eh easy

#

done many times before

#

unless you mean no strings at any level of the code, which won't work because the code itself is a string before it's interpreted

rocky leaf
#

I guess i mean without using any of the letters

floral meteor
#

no letters?

#

code with no letters now that I would like to see

rocky leaf
#

h e l o w r l d

floral meteor
#

oh just that

#

easy

#

chr(97) makes 'a' for example

#

then just count up for other letters of the alphabet

rocky leaf
#

ahh ok then thats too easy

floral meteor
#

yes

#

but do it then golf it without breaking the no helowrd rule

rocky leaf
#

p=print
p(chr(97))

#
p=print;c=chr
p(c(104)+c(101)+c(108)+c(108)+c(111))
#

why is this so funny

night quarryBOT
#
Missing required argument

code

rocky leaf
#

!e p=print;c=chr
p(c(104)+c(101)+c(108)+c(108)+c(111))

night quarryBOT
#

@rocky leaf :white_check_mark: Your 3.11 eval job has completed with return code 0.

hello
floral meteor
#

!e ```py
=108;print(*map(chr,(104,101,,,111,32,119,111,114,,100,33)),sep='')

night quarryBOT
#

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

hello world!
floral meteor
#

!e this kinda pretty though ```py
print(*map(chr,b'Hello, World!'),sep='')

night quarryBOT
#

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

Hello, World!
floral meteor
night quarryBOT
#

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

hello, world!
rocky leaf
#

ok then a new challenge im thinking of doing- a terminal print of a solar system simulation that updates every year per print

#

its like a clock but sillier

floral meteor
#

like.... coloured in with ANSI escape sequences so that it looks like the actual solar system just pixellated? That's called animation

rocky leaf
#

no not animated, data only

#

maybe thats too hard

#

lol

floral meteor
#

but you could turn the data into f"\033[{y}H\033[{x}G{name}" with the variables existing x, y and name

#

you just need to research the orbit speeds

#

hardcode the initial orbit positions

rocky leaf
#

The data is easy to get too

floral meteor
#

only data you need is orbit speed. distance you can make up, because an animation to scale would be annoying to make

#

technically, the sun moves, but you can make the orbit relative to the sun for simplicity

rocky leaf
#

pygame would do it really nice but I like making esoteric shit with the standard libs

floral meteor
#

ewwww pygame. Nah just use escape sequences in the terminal that's basically the same thing just more pixellated

rocky leaf
#

I actually use pygame for professional art projects where I can play like 10 sounds with code etc

floral meteor
#

Do you know how to make custom classes or objects?

rocky leaf
#

Itโ€™s good for weird little I/O things but I wouldnโ€™t make a game in it haha

#

Iโ€™ve never made a class, interestingly never had to use one

#

I donโ€™t really understand why you need them

#

I have trouble with node based, parent child type of code

#

It just doesnโ€™t feel right but I will learn today

floral meteor
#

you don't need nodey stuff if you're uncomfortable with it, that's a fringe use of classes anyway

rocky leaf
#

I really want to learn tensorflow so Iโ€™ll need to learn as much as possible

floral meteor
#

A class has attributes, it's basically a glorified dictionary with pretty syntax.
However it can also instantiate an object that can do some useful things and are best used to represent things.

rocky leaf
#

I feel like even esoteric stuff is good to know because tensorflow seems to be a lot of abstraction and pushing a lot of numbers at once

floral meteor
rocky leaf
#

Ah I wasnโ€™t even thinking of animating it, just displaying coordinates or something

#

I hadnโ€™t really thought it through

#

Just spitballing

#

I thought a calendar might be funny to make, then try and shorten it in the most disgusting way possible

#

A whole entire simulated universe code thatโ€™s impossible to read and is like 50 lines long

#

Clock, calendar, solar system

floral meteor
#

what about one line long?

rocky leaf
#

How do you keep everything on one line?

#

As soon as you need a while or if statment you need a new line

floral meteor
#

but

#

you dont need while or if statements

#

you dont need statements

#

reject statements, return to expression

#

reject humanity, return to monke

#

throw newline character out window, leaving a ravenous abyss in place of the 10th position in ascii

rocky leaf
#

while 1: simulateuniverse()

floral meteor
#

ahem frantic typing...

#
{simulateuniverse()for _ in iter(int,1)}
rocky leaf
floral meteor
#

In this channel python can do anything

#

many abominations are created here

rocky leaf
#

I feel like a criminal, itโ€™s a mad rush!!

#

Someone said you should never use ;

#

Why?

floral meteor
#

bad practice

#

sort of

#

in golfing it's last resort replacement for a newline

rocky leaf
#

whats golfing?

floral meteor
#

making code shorter

rocky leaf
#

ahhhhh

#

its a sport

floral meteor
#

what we were doing earlier

#

winner has lowest score

#

hence the name golf

rocky leaf
#
## define a class of planet

class Planet:
    def __init__(self, name, orbitSpeed, coordinates):
        self.name = name
        self.orbitSpeed = orbitSpeed
        self.coordinates = coordinates

sun = Planet("Sun", 0, [0, 0])
floral meteor
#

Yes, the sun is definitely a planet.

#

You going to input colour data?

#

I'd say the sun is (255, 250, 140); although it is the brightest object in the system so it could get a little brighter at expense of saturation.

#

to display that you would need to print ```py
import os;os.system('');sun_character = "\x1b[38;2;255;250;140mโ–„\x1b[m";print(sun_character)

icy frigate
rocky leaf
#

what is?

floral meteor
#

something you can import

icy frigate
#

!d dataclasses.dataclass

night quarryBOT
#

@dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False)```
This function is a [decorator](https://docs.python.org/3/glossary.html#term-decorator) that is used to add generated [special method](https://docs.python.org/3/glossary.html#term-special-method)s to classes, as described below.

The [`dataclass()`](https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass "dataclasses.dataclass") decorator examines the class to find `field`s. A `field` is defined as a class variable that has a [type annotation](https://docs.python.org/3/glossary.html#term-variable-annotation). With two exceptions described below, nothing in [`dataclass()`](https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass "dataclasses.dataclass") examines the type specified in the variable annotation.

The order of the fields in all of the generated methods is the order in which they appear in the class definition.
unreal echo
#

it's just yellow

floral meteor
#

it's a yellow dot for now

#

although you could make a bigger yellow dot with "\x1b[38;2;255;250;140m \x1b[m"

#

It's a great substitution for the โ˜€ in the terminal

#

All sprites are made, they haven't always existed.

rocky leaf
#

fuck i gotta program a circle

#

๐Ÿคฃ

#
from turtle import Turtle, Screen
from math import sin, cos, pi, radians




## define a class of planet
n = ['Sun', 'Mercury', 'Venus', 'Earth',  'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
o = [0,88,224,365,687,4331,10747,30589,59800]
d = [0,58000000,108000000,149000000,228000000,778000000,1432000000,2867000000,4495000000]


class Planet:
    def __init__(self, name, orbitSpeed, distance, coordinates):
        self.name = name
        self.orbitSpeed = orbitSpeed
        self.distance = distance
        self.coordinates = coordinates

sun = Planet(n[0], o[0], d[0], [0,0])
mercury = Planet(n[1], o[1], d[1], [-d[1], 0])
venus = Planet(n[2], o[2], d[2], [-d[2], 0])
earth = Planet(n[3], o[3], d[3], [-d[3], 0])
mars = Planet(n[4], o[4], d[4], [-d[4], 0])
jupiter = Planet(n[5], o[5], d[5], [-d[5], 0])
saturn = Planet(n[6], o[6], d[6], [-d[6], 0])
uranus = Planet(n[7], o[7], d[7], [-d[7], 0])
neptune = Planet(n[8], o[8], d[8], [-d[8], 0])



screen = Screen()
screen.setup(800, 800)


## animate solar system

def animate():
    while True:
        for planet in [mercury, venus, earth, mars, jupiter, saturn, uranus, neptune]:
            planet.coordinates[0] += planet.orbitSpeed
            if planet.coordinates[0] > 360:
                planet.coordinates[0] -= 360
                turtle.setpos(planet.distance * cos(radians(planet.coordinates[0])), planet.distance * sin(radians(planet.coordinates[0])))
        screen.update()
        screen.ontimer(animate, 100)

animate()
#

silly

#

(it doesn't work)

floral meteor
#

turtle?

#

you don't need a gui to make an animation

floral meteor
#

for a 4 dimensional game it's relatively easy.

#

and obfuscated

#

but that's animated in the terminal

rocky leaf
unreal echo
#

how long did that take