#esoteric-python
1 messages ยท Page 3 of 1
!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])

@languid hare :white_check_mark: Your 3.10 eval job has completed with return code 0.
reversed
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
whats your current method?
def g(t):
o = [i for i, letter in enumerate(t) if letter == ' ']
t[o[random.randint(0, len(o))]] = 37โ
Yeah, sorry ๐
t[o[random.randint(0, len(o))]] = 37โ how are you even making this work?
You can mutate a string like that without ctypes?
Oops my bad. t is a byte array and ' ' should be replaced with ord(' ')
32
iirc, ascii of " " is 32
also, that ruined my solution, it would only work for strings :(
i was making a lambda 1 liner
(lambda _,__,___:[_,_.__setitem__(___([____ for ____,_____ in enumerate(_)if _____==ord(__)]),32)][0].decode())(bytearray(b'hello'),'l',__import__('random').choice)
``` got it
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)
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
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)
@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.
This is not esoteric
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())()
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
69
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)
@floral meteor :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
69
it segfaulted, but I golfed the bytecode
I should probably fix the segfault
What is PRINT_EXPR even
!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)
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
69
done
the 71st bytecode
What does that map to in actual python?
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

optimised print repr
https://docs.python.org/3/library/dis.html#opcode-PRINT_EXPR
PRINT_EXPR
Implements the expression statement for the interactive mode. TOS is removed from the stack and printed. In non-interactive mode, an expression statement is terminated withPOP_TOP.
secret print op
Hm
it sounds like it's the autoprint in the repl
yup: https://stackoverflow.com/a/50375828
!e
from dis import dis
dis(compile('x+2', '<stdin>', 'single').co_code)
@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
in interactive mode, it also stores to _
hi fatal error just wanted to say i hope oyu're having a good one lmao
!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)
@floral meteor :white_check_mark: Your 3.10 eval job has completed with return code 0.
69
lol it no worky in 3.11
!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)
Just wanted to see if extended_arg would work 
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())()
@floral meteor :white_check_mark: Your 3.10 eval job has completed with return code 0.
<class '__main__.doobywacker.<locals>.dabbywooker'>
getting a class from a function where the function doesn't return anything hehehe
LOAD_CONST is your problem here, not extended_arg
and your column alignment is messy
I know I tried to type it on mobile ๐
Gboard screwing with adding hairline spaces as well I gave up
this isn't really the sort of thing you type on mobile
anyway what new thing are you writing?
tetris
!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)
where did you get this code from
!e import('dis').dis('[23, 523, 53, 5, 32, 5]')
@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
that
not that code
i meant the one you're eval'ing
ye
that code i adapted to 3.11 on july?
probably
ok
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())()
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
(1, 2, 3, 4)
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)
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
69
i made global equals
!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))
@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]
it works
Is inline_add an opcode?
inline_add??
I've seen inline left shift
do you mean inplace
!e print( import ('dis').opmap)
@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
makes a cell for nonlocal values
What's a cell? Does it have organelles?
aw
@quartz wave :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
!e
lambda: "esoteric python"
print(lambda)
@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
I know normal python. I have no idea what lambda is
(I know python. What I don't know is lambda and those type of things)
[Never heard of lambda]]
lambda is an inline keyword to make an anonymous function
!e (lambda p:p("esoteric python"))(print)
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
esoteric python
Works like any other literals like lists [] or ints like 0
In syntax
!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))
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
69
those that are installed
you mean the standard library
I.e. these ^ @soft vapor
ok
thats epic
wizard
wizard!
print(eval(f"__import__(chr(109) + chr(97) + chr(116) + chr(104)).{chr(112) + chr(105)}"))```
prints pi
!E
print(eval(f"import(chr(109) + chr(97) + chr(116) + chr(104)).{chr(112) + chr(105)}"))
@unreal echo :white_check_mark: Your 3.11 eval job has completed with return code 0.
3.141592653589793
lemme guess eval('__import__("math.pi")')?
*'__import__("math").pi'
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__()
hmmmmmm
!e py print("\x6d\x61\x74\x68")
@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.
math
!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"))```
@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
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"))
@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
skill issue ๐จ
!e py exec("\x70\x72\x69\x6e\x74\x28\x5f\x5f\x69\x6d\x70\x6f\x72\x74\x5f\x5f\x28\x27\x6d\x61\x74\x68\x27\x29\x2e\x70\x69\x29")
@last locust :white_check_mark: Your 3.11 eval job has completed with return code 0.
3.141592653589793
Which translates to exec(print(__import__('math').pi))
!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'))```
@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
@quartz wave :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
[No output]
!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))
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
3.141592653589793
rare sight of something being used from the "dis" module other than "dis"
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
if 0!=Canvas[B] (paraphrased) can just be if Canvas[B] since bool(i)==True for all non-zero integers
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()
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')
@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
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()
you import * from dis, then import other stuff from dis?
what's the point lmao
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
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
thats after the other steps have been applied
so the starting num is ((63 / 3) - 3) / 3
or, 6
also, the answer is always 8
!e ```py
print(bool(~True))
nooooooOOOOoooOooooooOooOOooooOoo
@drowsy cobalt :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
!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")
@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
.-.
add parenthesis at the end
you only have 1 closing parentheses, but two opening ones
!e
print(eval("\x5f\x5f\x69\x6d\x70\x6f\x72\x74\x5f\x5f\x28\x22\x6d\x61\x74\x68\x22\x29\x2e\x70\x69"))```
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
3.141592653589793
!e
print(eval("24 - 4"))
@untold plaza :white_check_mark: Your 3.11 eval job has completed with return code 0.
20
!e
print(eval("len(self.bot.guilds)"))
@untold plaza :warning: Your 3.11 eval job has completed with return code 0.
[No output]
lmao
!e
print(eval("len(self.bot.guilds)"))
@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
ok
oh
stuff like this
and this
fair enough
!e you might crash the sandbox by doing this ```py
raise SystemExit(120481294712957218957215125)
@quartz wave :warning: Your 3.11 eval job has failed.
A fatal NsJail error occurred
looks like nonsense to me
and that
its supposed to
oops
yeah this channel is supposed to be nonsense
oh ๐ญ
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")```
@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
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')```
@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
i give up
My bad
it isn't included in __all__ that's why
lol
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
!e ```py
assert 1,2==(1,2)
@earnest wing :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!e
assert 1,2==(3,4)
@restive void :warning: Your 3.11 eval job has completed with return code 0.
[No output]
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?
must be true then
!e but
assert 0,1==(2,3)
@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
PyObject_Print
PyObject_Print(obj, stderr, 0); /* print(repr(obj)) */
PyObject_Print(obj, stderr, Py_PRINT_RAW); /* print(obj) */
ah thanks ๐
There are a few spelling errors found by quickly glossing over the first part. No big deal though. The formatting might be improved.
Ok thanks
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?
!e
a="foo"
import gc
print(gc.is_tracked(a))
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
gc doesn't track atomics
your code should work with things that the gc tracks
Oh! They never get garbage collected?
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
strings do get freed, but smaller ones are held onto for a little bit
why is that?
optimization reasons probably
insane...lol
whats the best obfucation?
@sick hound this?
what is wrong with you guys
?
everything

it's needlessly gendered
hey what's this "Python VM languages"?
Languages that run on the CPython VM, other than Python. E.g. https://github.com/pyos/dg
ah..... ok
say "people" please, not everyone here identifies as male
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

!e
from dis import dis
def ret(): return "Hi"
def pri(): print("Hi")
dis(ret)
print("\n\n")
dis(pri)
@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
!d 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()...
certain modules exist in stdlib only to be abused here
that's all of them
every single one
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
cool yeah me too
I felt like that too at one point but didn't get enough motivation to follow through wiith it
: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).
!unmute @floral meteor Try using our paste service
:incoming_envelope: :ok_hand: pardoned infraction mute for @floral meteor.
!paste
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.
ty
I started making a generic interpreter in case you're stuck https://paste.pythondiscord.com/enafewuhic.py
and this is why one-line code is fashionable in #esoteric-python
I'm not doing that anymore. I'm now maintaining my Language and Doing some ethical hacking
your code looks nnice
**nice
thanks. It's still sort of in skeleton code stage though
ok
But filled in a little
you can get an idea from this
https://github.com/Sas2k/NumberScript
ok
and I found a problem already
really what?
https://paste.pythondiscord.com/itocimazil.py for some reason I keep typing def instead of class when making classes
oh that
usually happens when I'm not really paying attention to what I'm writing
I wish !e could run pastebin code
ok
I could probably !e my code after golfing and line reduction
but the bot can't handle inputs
make a fake stdin object with pre-coded input
i found a way to get the current stack
yeah
!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)
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
(2, 4, 2, 4)
there
noice. ripe for abuse
this also changes every time the stack is manipulated what
!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('!')
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | > a b c
002 | abc
input just magically became possible in the bot
doesn't seem to work in 3.9
don't do it in 3.9 then
lmao that's my attitude for 3.7 code
structure of frame/code objects aren't the same in each version
!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
now you're seeing the structure of the python stack
also i'm gonna make an iterable version
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello
!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)
@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
globals is not on the stack though?
Saw that and was like "huh, classes inside functions, eh?" ๐
that's super neat, good work. It has a ton of potential
We should make a #custom-languages channel or something
@soft vapor https://github.com/hedgenull/mochascript might be something you wanna look at
why is there
class BakaASM: pass
class BakaASM:
[full code here]
!e classes inside functions ```py
def stdout_factory():
@type.call
class stdout:lshift=lambda s,o:print(end=o)or s
return'\n',stdout
endl,stdout = stdout_factory()
stdout << "Hello" << endl;
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello
nice
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()
I like the __name__=="__main__"==main() part :D
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
What would this version's controls be?
ws vertical
ad horizontal
qe depth
There are like 6 directions you can go
Unless you're doing this freeform
Which doesn't fit the grid feel
4D is gonna use
wasd: subdimensions
arrows: hyperdimensions
Yeah, okay, that's 8
Hypercubes have 8 cubes for faces analogy unless I am wrong
I don't understand why it works
If it does
!e ```py
a = b = 1
c = 0
a == b == print('yes')
a == c == print('no')
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
yes
Never mind I got it
BLOCK = "\U00002580" will be my entire charset
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()
because of line 163
if isinstance(block, BakaASM) and len(blocks) > 1 and block == blocks[-1]:```
idk if it will work with self
does it error if you remove the first one
yes because BakaASM is not defined inside itself
!e ```py
class A:
def _a(self, *args):
for arg in args:
if isinstance(arg, A): print("yes")
print(A()._a(A(), A(), A()))
don't know how to explain more correctly
@sly root works fine
run it with 3.10
@quartz wave :white_check_mark: Your 3.10 eval job has completed with return code 0.
001 | yes
002 | yes
003 | yes
004 | None
@sly root maybe you mean having A in the class definition main scope
i've added it instinctively
Mhm
hard to explain stuff
usually no because that's not the point of it
!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)
nah
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
(2, 4, 6)
It's just a name error
ok done
There we go
Is this like a while loop
what no
there's still no need
Pass BakaASM or type(self) or self.__class__ and that will work
but it is, it's just __class__
https://paste.pythondiscord.com/ewajagosoy.py
stage 1 of 2 complete.
No testing or debugging has happened yet, nor is the syntax guaranteed to be correct.
I haven't even tried running it.
What are you making
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?
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
Sounds complicated to even understand the concept let alone code it, good luck
I comfortably handle higher dimension subjects and shapes.
@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
the interface works, here is what it looks like. the snake is in the top hyperrow, in the 6th grid
I crashed in the wall
So there are just multiple boxes the snake can go to?
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
I needed a string of "ints" from floats and realized calling int() is overrated 
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
so you win by filling every single tile in every single grid in the grid of grids of tiles?
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
https://paste.pythondiscord.com/otananeyec.py I fink this is 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
there's only one printable character in this board other than newline: โ
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
https://paste.pythondiscord.com/buxepixuwa almost forgot about legacy terminals.
you see it prints two squares
It does mean I have to update pixels in pairs
Show this to the folks at #game-development
You just \x1b instead of \033?
yes
You just lost a friend
Yes
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.
valid
I intermittently flirt with the idea of writing a wrapper library for tkinter/ncurses or something, so you can write universal code that situationally selects the correct one.
But in what free time...
Just added __import__('os').system('') because some terminals need that to parse escape sequences. does nothing on terminals that automatically interpret them
probably not
there's no control of the stacktop pointer
it's supposed to be a one-time readonly stack
does it work on Linux and/or other Unix based operating systems?
imports msvcrt so i think no
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
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.
# 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)
msvtrc ๐
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
now my file is 5k characters lol
One more thing: the string encoding is ANSI
that's Windows only
I'm too fancy for utf-8
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?
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
4 line rot13
conditions:
- case sensitive
- 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
Pro tip: Use syntax highlighting in code blocks
```py
code here
```
Just a suggestion ๐
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?
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
}
yes and you can just do ```py
d={"s":97,"h":109}
oh, a comma, thank you
Just a general help channel would be more appropriate
no, linux can use ANSI escapes too
Why does python 3 allow this?
Why wouldn't it?
None as a key seems invalid, But None as a value is valid
Just was not expecting a dictionary holding None keys
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
All hashable objects
hmm i suppose it's acceptable to expect the lookup key to sometime hold values pertaining to the key types.. TY for responses.
np :P
is it possible to use fishhook to hook list.__hash__ and make it hashable?
or no
ASNI escapes != ANSI encoding (windows-1252)
(but you could probably use that as your terminal encoding, too, if you really wanted to)
termios probably has something to set encoding to ANSI Lmao
Sure, why not.
!e let's try
import fishhook
@fishhook.hook(list)
def __hash__(self): return 42
print({[]:23})โ
@restive void :white_check_mark: Your 3.10 eval job has completed with return code 0.
{[]: 23}
Typo; "inport"
ohh
!e
import fishhook
@fishhook.hook(list)
def __hash__(self): return 42
print({[]:23,[1]:24}[[1]])
yay
@versed eagle :white_check_mark: Your 3.10 eval job has completed with return code 0.
24
that's just doing print({[1]: 24}[[1]])
why the hook ๐๏ธ
also ```py
from inspect import signature
def fuckup(func):
@import('functools').wraps(func)
def _(a,**k):
return func(**dict((k,v2 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'))))))))))
!e
{[]:1}
@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'
lists aren't hashable?!
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
shortest way to print 365 to console?
depends if you're in interactive shell or running a file
In both cases, the answer is pretty boring
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
print(int(1e20))
i forgot about floats :(
10**20
i forgot about ints :(
same :(
Tuples aren't guaranteed to be hashable per se, it depends on the contents.
as soon as any non-hashable datatype is an element of a structured object, the object itself is non-hashable.
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
!e ```py
string = "*"13
print(string, hash(string))
from ctypes import c_byte
(c_byte13).from_address(id(string)+48)[:] = b"Hello, World!"
print(string, hash(string))
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ************* 1147045209908708488
002 | Hello, World! 1147045209908708488
It's mutable, and its hash remains the same
๐ฅฑ
No object is immutable
i don't think anyone argued otherwise
...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
"functionally immutable"?
Yes
!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))
@proper vault :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 8740285672552
002 | 8740285672552
now change string hash without changing string content
๐ 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)
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
undefined
what is this supposed to accomplish
whenever an undefined variable is referenced, use undefined?
Yes
Also, have undefined never fail when used in any context, just return undefined.
does overriding globals() do anything different from overriding __builtins__[.__dict__]
Yes, builtins works everywhere, not just in this module
Maby try __import__("builtins"). __dict__ ?
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
Yeah, this might make it consistent. But I don't understand the behavior..
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.
So yeah, I should probably do what you said
that's the behaviour
Yeah. I wonder why, that's so strange.. why isn't it a dict or the module everywhere
why do i keep seeing py_object.from_address(id(b) + 8) from everything that uses ctypes
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
And to make this extra fun now we just add 48 here
For real though can someone explain why we add 48 there
that's where the actual data is
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
py_object.from_address(id(foo) + 8).value = bar
is basically
foo.__class__ = bar --force
Thank you for this clear explanation
Is there some kind of documentation on this? Could you link it if so
And what if I wanted to do foo.__set__ = bar
How would we do that with ctypes
you mean if it doesn't work through normal means? You'd want to set __set__ anyways on the class, so like above. In general, for setting attributes it depends on the class otherwise.
I just took a random function other than __class__, just imagine I want to change another function or value that's read only, how would I change that?
__class__ is special
^
its read-only (unless you're doing weird stuff with ctypes, in which case nothing is read-only)
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
its not read only
Might not work at all (without a lot of work), unless the new constants have the same size
but maybe it will, I'll try
Alright
Oh, I remember I did this already in terrible-ideas :D
Link?
>>> from terrible_ideas import mutable_tuples
>>> def foo():
... return 42
>>> foo.__code__.co_consts[1] = 23
>>> foo()
23
!pypi terrible-ideas
but here we don't actually change anything in the code object, we just change the tuple
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
!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())
@restive void :white_check_mark: Your 3.10 eval job has completed with return code 0.
23
bc in python, everything is a pointer behind the scenes
So I assume that the + 56 makes it point to the constants
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.
How did you know that though
Yes, in CPython 3.10. Doesn't work in 3.11 anymore (I'd have to search for the new location again).
How is it determined
You could also figure it out by reading the source code, but I'm a) lazy b) not good at reading C
just by the order of the corresponding struct(s)
and how much space each member occupies
Wouldn't it be possible to just do id (foo.__code__.co_consts)
i think you'd still have to have an offset
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())โ
Mm lemme experiment with it in #bot-commands , welcome to help over there
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
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())
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
23
instead of lambda:0, you can use int
:P
Just thought of the same :D
!e 3.10
from ctypes import c_int64
def foo():
return 42
print(id(foo.__code__) + 56)
print(id (foo.__code__.co_consts))โ
@serene stratus :white_check_mark: Your 3.10 eval job has completed with return code 0.
001 | 140662426656424
002 | 140662426666432
Look it's only 8 bits apart of each other
hm
so you could do id(foo.__code__.co_consts) - 8?
I guess
it's not
I don't understand why though
6656 vs 6666
though L3viathan's answer i think would work better
It's pretty heavy though
The looping etc
Happens to be, here. Might be different on the next run
well, you could use their code to get the offsets, then print those and use them next time
that way you have the values onhand
so that you dont need to loop every time
whenever someone wants to improve the performance of esoteric code, I get sweaty..
!e 3.10
from ctypes import c_int64
def foo():
return 42
print((id(foo.__code__) + 56) - id (foo.__code__.co_consts))โโ
@serene stratus :white_check_mark: Your 3.10 eval job has completed with return code 0.
-10008
It's the same again
yes, because you did the same. Do a lot of other things before, and it might not be
there could be a "hole" in memory big enough to fit the code object, but not also the consts tuple
I see
well, technically you could just write everything in C/C++, compile it to an object file, then import and call it in python?
Haha
you could do many things. I just get scared that someone might want to actually use this
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)
lmao
you could use one of the list of languages that compile to python bytecode
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
better yet, you could write asm
it would run faster (if you dont count the 37 days it takes to learn whichever flavour of asm your processor uses)
there's both of that hidden in there (60, .index)
Ah ๐
Where does the specific 37 days come from
thats around how long it takes to read the x86 manual (source: i tried to read it once)
with its 3,684 instructions
Lmao
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
cpython source
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))
Say my name two more times I want to be FREEEE!
print("Fatal error: death.py activated\n"*2)
Yay, I'm free! Time to release chaos upon the world!
extra \n at the end for good luck :P
if foo := get(...):
foo: str
return # do stuff
foo: None
!e
thing:=5
@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
!e ```py
if foo := {"bar": "baz"}.get("bar"):
print(foo)
@old socket :white_check_mark: Your 3.11 eval job has completed with return code 0.
baz
You just forgot the terminating colon at the end
what terminating colon
Oh I know what you mean now
lol
No just ignore me I got you mixed up
is fine lol :p
I'm always mixed up anyway
Not always
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
oh nvm the api isn't weird I'm just bad at BNF
yes, in __main__ it is module builtins, otherwise it is builtins.__dict__
I'm only guessing, but I think it's the id where the reference is vs the id of the actual object that the reference points to
you can also do (lambda: ...).__builtins__
but... why?
!rule 5, and also off-topic for this channel
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.
Did someone ghost ping me
Whatโs the most bizarre and short piece of python code youโve ever seen?
Not including regex, regex is silly enough
brainfuck in python, and a one liner snake console game frmo @floral meteor
like dude, get a damn life and touch some grass
I saw tht
I smell jealousy
not really, i had a huge esoteric piece of code i could write, but decided not to
because pastebin probably won't support it
Haha don't worry about it I was joking
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
make a rick roll in the shape of rick astley
to ascend to the next level of uselessness
done that already
you would not imagine how much free time i have
like, seriously
show rn
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.
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
?
lancebot
do you know how many errors i encountered while writing the dunder version of for x in __import__('itertools').count(): print(x)
all of them made me almost give up
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]
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
import time;tf="ap";s=m=h=l=0
while 1:
s+=1;time.sleep(1);print(f"{h:02}:{m:02}:{s:02}{tf[l]}m")
if s==59:s=0;m+=1
if m==60:m=0;h+=1
if h==12:l^=1;h=0
I've never bothered to post my nickname here
But I guess I should
@lambda y: lambda: map(y,(y, y))
enjoy
a wrapper for calling a function with itself twice
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==59:s=0;m+=1
if m==60:m=0;h+=1
if h==12:l^=1;h=0โ```
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โ
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```
import os;os.system('date -s0 >/dev/null;while sleep 1;do LC_ALL=C date +%H:%M:%S%P;done')
that only works on Unix based systems though
there are other systems? :P
not good ones :p
it also is the only "solution" needing root :D
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
Yeah, I guess it doesn't work under fish
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)
@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
Looks like this code's missing too many lambdas and/or decorators for #esoteric-python ๐
this one is the winner
First argument (a) is a tuple when it should be a PyObject
!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)โ
@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
Apparently not
Itโs funny. Iโm working on a new challenge, like the 12 hour clock. Just for shits and giggles
yessir, I'm pythonic, __init__ bruv
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
ive been trying to define functions or lambdas but it only makes it longer
keywords to tend to be a bit wordy
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')
even that line can be shortened to p=print
tbh
you don't need redundant whitespace, and functions are also objects
!e ```py
(p:=print)(p)
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
<built-in function print>
p=print
p("Hello World")
but then that adds 4 extra characters p=;p
Its very non python to shorten something as basic as print
unless you were using print a lot
there is no good reason for lack of knowledge in this context
so for my next challenge, I'm going to print hello world without using any strings
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
I guess i mean without using any of the letters
h e l o w r l d
oh just that
easy
chr(97) makes 'a' for example
then just count up for other letters of the alphabet
ahh ok then thats too easy
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
code
!e p=print;c=chr
p(c(104)+c(101)+c(108)+c(108)+c(111))
@rocky leaf :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello
!e ```py
=108;print(*map(chr,(104,101,,,111,32,119,111,114,,100,33)),sep='')
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world!
what the fuck nice
!e this kinda pretty though ```py
print(*map(chr,b'Hello, World!'),sep='')
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, World!
!e although technically only the lowercase letters were defined as excluded from strings ```py
print("HELLO, WORLD!".lower())
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello, world!
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
like.... coloured in with ANSI escape sequences so that it looks like the actual solar system just pixellated? That's called animation
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
The data is easy to get too
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
pygame would do it really nice but I like making esoteric shit with the standard libs
ewwww pygame. Nah just use escape sequences in the terminal that's basically the same thing just more pixellated
I actually use pygame for professional art projects where I can play like 10 sounds with code etc
Do you know how to make custom classes or objects?
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
you don't need nodey stuff if you're uncomfortable with it, that's a fringe use of classes anyway
I really want to learn tensorflow so Iโll need to learn as much as possible
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.
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
Well you're gonna need one to represent a character in the terminal, hold its coordinates, and also reference two vertically adjacent data points, it will take some mild algebra to decide what cartesian coordinates go in what terminal coordinates.
You will also need to know the colours of planets in rgb format or hexcode
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
what about one line long?
How do you keep everything on one line?
As soon as you need a while or if statment you need a new line
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
while 1: simulateuniverse()
Still impressed at this tbh, didnโt even imagine python could do this stuff
I feel like a criminal, itโs a mad rush!!
Someone said you should never use ;
Why?
whats golfing?
making code shorter
## 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])
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)
You could just use dataclass for this
what is?
something you can import
!d dataclasses.dataclass
@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.
well, that isnt exactly a sun character
it's just yellow
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.
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)
for a 4 dimensional game it's relatively easy.
and obfuscated
but that's animated in the terminal
i gave up on the animated solar system, i have real work to do and it was getting too silly, if thats a thing
what the hell
how long did that take
