#esoteric-python
1 messages ยท Page 151 of 1
!e small code generates big bytecode
from dis import dis
def f(x: object) -> None:
match x:
case bool():
print('a')
case int():
print('b')
case None:
print('c')
case str():
print('d')
case bytes() | bytearray():
print('e')
case set() | frozenset():
print('f')
case _:
print('g')
print('h')
dis(f)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | 3 0 LOAD_FAST 0 (x)
002 |
003 | 4 2 DUP_TOP
004 | 4 LOAD_GLOBAL 0 (bool)
005 | 6 LOAD_CONST 1 (())
006 | 8 MATCH_CLASS 0
007 | 10 POP_JUMP_IF_FALSE 13 (to 26)
008 | 12 POP_TOP
009 | 14 POP_TOP
010 |
011 | 5 16 LOAD_GLOBAL 1 (print)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/iyibaqokaj.txt?noredirect
but who'd just do ```py
def f1():
g()
that seems very useless since they can just use g()
I rather talked about cases where the return value is not important when calling a method
And if your method is very small and called many times, so you get significant speedup by using this optimization
return value is useless for example in __setattr__, __setitem__, __set__, __delattr__, __delitem__, __delete__, __del__, __init_subclass__, __set_name__, ...
while testing my decompiler on this code i found out Ellipsis is assignable and case ...: isn't possible
!e ```py
match "a":
case ...:
print("oh")
@quartz wave :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | case ...:
003 | ^^^
004 | SyntaxError: invalid syntax
!e ```py
match "a":
case Ellipsis:
print(Ellipsis)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
a
discord highlights Ellipsis as a constant though?
Ellipsis is a name, not a keyword
!e ```py
from ctypes import *
pythonapi.PyUnicode_Join.argtypes = [py_object, py_object]
pythonapi.PyUnicode_Join.restype = py_object
print(pythonapi.PyUnicode_Join(cast(0, py_object), py_object(["ab", "cd"])))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
ab cd
.bm
!e py def test1(a): exec(a) def test2(): test1("test2()") print('hello') test2()
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 6, in <module>
003 | File "<string>", line 4, in test2
004 | File "<string>", line 2, in test1
005 | File "<string>", line 1, in <module>
006 | File "<string>", line 4, in test2
007 | File "<string>", line 2, in test1
008 | File "<string>", line 1, in <module>
009 | File "<string>", line 4, in test2
010 | File "<string>", line 2, in test1
011 | File "<string>", line 1, in <module>
... (truncated - too many lines)
Full output: too long to upload
001 | Traceback (most recent call last):
002 | File "<string>", line 6, in <module>
003 | File "<string>", line 4, in test2
004 | File "<string>", line 2, in test1
005 | File "<string>", line 1, in <module>
006 | File "<string>", line 4, in test2
007 | File "<string>", line 2, in test1
008 | File "<string>", line 1, in <module>
009 | File "<string>", line 4, in test2
010 | File "<string>", line 2, in test1
011 | [Previous 3 lines repeated 328 more times]
012 | RecursionError: maximum recursion depth exceeded
here's the slightly less golfed version in case you care
ttt = lambda n: (
(
(lambda a: a(a))(
lambda game_loop_inner: lambda np, re, owned_to_string, turn_order, board: (
(
print(owned_to_string[turn_order[0]], "'s turn!"),
(lambda a: lambda v: a(a, v))(
lambda process_input_inner, turn_order: (
lambda inp: (
board.__setitem__(inp, turn_order[0])
if all(0 <= x < n for x in inp) and board[inp] == -1
else process_input_inner(
process_input_inner, turn_order
)
)
)(
(lambda a: lambda v: a(a))(
lambda get_input_inner: (
lambda match: get_input_inner(get_input_inner)
if match is None
else tuple(map(int, match.groups()))
)(re.match(r"(\d+), (\d+)", input("Coords? ")))
)(None)
)
)(turn_order),
(
print(),
[[print(*[owned_to_string[i] for i in row])] for row in board],
),
turn_order.append(turn_order.pop(0)),
print(owned_to_string[turn_order[1]], "Won!")
if any(
(
any(
np.all(row == row[0]) and row[0] != -1 for row in board
),
any(
np.all(row == row[0]) and row[0] != -1
for row in np.rot90(board)
),
*(
np.all(diag == diag[0]) and diag[0] != -1
for diag in (board.diagonal(),)
),
*(
np.all(diag == diag[0]) and diag[0] != -1
for diag in (np.rot90(board).diagonal(),)
),
)
)
else print("Nobody Won!")
if np.all(board != -1)
else game_loop_inner(game_loop_inner)(
np, re, owned_to_string, turn_order, board
),
)
)
)
)
)(
*(
lambda np: (
np,
__import__("re"),
{0: "x", 1: "o", -1: " "},
[0, 1],
np.zeros((n, n), dtype=int) - 1,
)
)(__import__("numpy"))
)
and a slighly more readable version that allows :=
ttt = lambda n: (
np := __import__("numpy"),
re := __import__("re"),
board := np.zeros((n, n), dtype=int) - 1,
turn_order := [0, 1],
owned_to_string := {0: "x", 1: "o", -1: " "},
get_input := lambda: (
match := re.match(
r"(\d+), (\d+)",
input("Coords? "),
),
get_input() if match is None else tuple(map(int, match.groups())),
)[1],
process_input := lambda: (
inp := get_input(),
board.__setitem__(inp, turn_order[0])
if all(0 <= x < n for x in inp) and board[inp] == -1
else process_input(),
),
check_win := lambda: any(
(
any(np.all(row == row[0]) and row[0] != -1 for row in board),
any(np.all(row == row[0]) and row[0] != -1 for row in np.rot90(board)),
*(
np.all(diag == diag[0]) and diag[0] != -1
for diag in (board.diagonal(),)
),
*(
np.all(diag == diag[0]) and diag[0] != -1
for diag in (np.rot90(board).diagonal(),)
),
)
),
print_board := lambda: (
print(),
[[print(*[owned_to_string[i] for i in row])] for row in board],
),
game_loop := lambda: (
(
print(owned_to_string[turn_order[0]], "'s turn!"),
process_input(),
print_board(),
turn_order.append(turn_order.pop(0)),
print(owned_to_string[turn_order[1]], "Won!")
if check_win()
else print("Nobody Won!")
if np.all(board != -1)
else game_loop(),
)
),
)[-1]()
@near gust thanks

you could definitely golf that more
use an integer to represent state instead of arrays
that's what i did for my 3x3 golfed version
oh it doesn't print the board
challenge: an interesting program that uses every "definition" of * in the language
- multiplication
x * y - exponentiation
x ** y - iterable unpacking
foo(*x),[*x], ... - iterable destructuring
x, *y = z - mapping unpacking
{**x} - vararg declaration
def foo(*x) - varkwarg declaration
def foo(**x) - kw-only arg marker
def foo(*, x) - star import
from foo import * - exception groups
except* Foo
also *= and **=
And make it a program that prints out a giant asterisk made of asterisks
i was gonna say golf your code so that the source code is a giant asterisk
for ij in range(Particle_Number):
if ij != B:
a=(x_vel(timestep,grav(temp[(B6)+1],temp[(ij6)+1],Dis(temp[(B6)+3],temp[(B6)+4],temp[(ij6)+3],temp[(ij6)+4])),mag(temp[(B6)+2],temp[(ij6)+2],Dis(temp[(B6)+3],temp[(B6)+4],temp[(ij6)+3],temp[(ij6)+4])),temp[(B6)+3],temp[(B6)+4],temp[(ij6)+3],temp[(ij6)+4])/temp[(B6)+1])
main[(B6)+5]=Trues(a, main[(B6)+5])
for ik in range(Particle_Number):
if ik != B:
b=(y_vel(timestep,grav(temp[(B6)+1],temp[(ik6)+1],Dis(temp[(B6)+3],temp[(B6)+4],temp[(ik6)+3],temp[(ik6)+4])),mag(temp[(B6)+2],temp[(ik6)+2],Dis(temp[(B6)+3],temp[(B6)+4],temp[(ik6)+3],temp[(ik6)+4])),temp[(B6)+3],temp[(B6)+4],temp[(ik6)+3],temp[(ik6)+4])/temp[(B6)+1])
main[(B6)+6]=Trues(b, main[(B6)+6])
#WIN.fill(black)
for C in range(Particle_Number):
a=0
if main[(C*6)+2] > 0:
a=red
if main[(C * 6) + 2] < 0:
a=blue
if main[(C * 6) + 2] == 0:
a=white
drawPoint((round(10 * main[(C * 6) + 3]) + 960), (round(10 * main[(C * 6) + 4]) + 540), a)
pygame.display.update()
a bit of my n body code
and mine also avoids every possible exception that could normally occur except an invalid n
I'm not much of a code golfer if you can't tell
I bet if I allowed walrus then I could golf this a bit more
I just wanted to explore functional programming in a familiar environment and just do a fun 1 day project
someone challenged me to do the same in C . oh god here we go again
ah fair enough
it's probably easier to do it in C since you can just use braces
and semicolons
print("---------[< Task 1 >]---------")
for _ in range(int(input("How many time repeat?\n>>> "))): print("Hi!")
print("\n---------[< Task 2 >]---------") ; c = 0
for x in str(int(input("Give an int: "))): c += 1 if x == "1" else c
print("Ones: " + str(c)) ; print("\n---------[< Task 3 >]---------") ; print(f"Biggest number: {str(max([_ for _ in str(int(input('Give an int: ')))]))}") ; print("\n---------[< Task 4 >]---------")
inp, last, no = int(input("Give an int: ")), "", True
for sym in str(inp): no = False if sym == last else no ; last = sym
print("Answer: yes") if no is False else print("Answer: no")
``` look at this evil
truly evil but remove the unnecessary whitespaces
so it becomes more evil 
i did the work
print("---------[< Task 1 >]---------");
for _ in range(int(input("How many time repeat?\n>>> "))):print("Hi!");
print("\n---------[< Task 2 >]---------");c=0;
for x in str(int(input("Give an int: "))):c+=1 if(x=="1")else(c);
print("Ones: "+str(c));print("\n---------[< Task 3 >]---------");print(f"Biggest number: {str(max([(_)for(_)in str(int(input('Give an int: ')))]))}");print("\n---------[< Task 4 >]---------");
inp,last,no=int(input("Give an int: ")),"",True;
for(sym)in str(inp):no=(False)if(sym==last)else(no);last=sym;
print("Answer: yes")if(no==False)else(print("Answer: no"));
now it's even more evil
sublime text is confused lol
xdd
but it's still valid python syntax
yes it is
my teacher said i should simplify the code at home and send it her per email
cause i spend more lines than other do for the same functions
LMAO
that's not simplifying tho
that's just making it a lot harder to read the code
lemme try golfing this
not too hard
Welcome to #esoteric-python
(P:=print,I:=input,i:=int,s:=str,S:='Give an int: ',d:="-"*9,t:=lambda n:P(f"{d}[< Task {n} >]{d}"),t(1),f:=lambda:s(i(I(S))),P("Hi!\n"*i(I("How many time repeat?\n>>> "))),t(2),P(f"Ones: {f().count('1')}"),t(3),P(f"Biggest number: {max(f())}"),t(4),a:=f(),P(f"Answer: {'yes'if any(a[i]==a[i-1]for(i)in range(len(a)))else'no'}"))
input validation is kinda weird
str(int(input())) :\
similar challenge about : definitions:
- line ending
if,else,for,while,try,except,finally,def,async def,with,async with,class,match,case,async for - lambdas
lambda x, y: x + y - walrus
print(x := 123) - f-strings
f'{1:}' - variable and argument annotation
x: int,def f(x: int) -> int: ... - slices
l[:],l[::] - dict literals and dict comprehensions
{k: v},{k: v for k, v in d.items()} - in old-style comment annotations
# type: (int, int) -> None
Forgot async for
๐
Is python without : turing complete?
Yes, you can create function from bytecode and call it
More interesting question: Is python without : and without creating your functions turing complete?
in a boring way certainly: exec("your program...".replace("COLON", chr(58)))
Boring
I forbid you to use exec, eval and compile
Also you cant use filesystem
And you cant use ctypes
And no os/subprocess, etc., I assume
Yes, probably
probably
I mean you need some kind of conditional and jump
implementing any one instruction set computer would work
I'm almost sure it would still be Turing complete, but I find it hard to find a non-cheaty solution.
.bm
There's probably tons of standard library modules that contain hooks for Turing completeness, e.g. sqlite3
Ok, now i forbid any imports ๐
lets remove the stdlib to make it fun
Without dunder-import and exec-related things
Yeah, of course
You can not define your custom dunder-format
Because it needs :
Hmm
but you can do "foo %s" % "%s" etc.
type('',(),dict(__format__=<here some tricky builtin function>))()
GNU printf is Turing complete (https://www.usenix.org/system/files/conference/usenixsecurity15/sec15-paper-carlini.pdf), but I don't think Python's is
i think i have a method to implement brainfuck without colons
I think i also can do this when i get home
this seems pretty easy
all you need is arbitrary data access, a few layers of looping and a simple conditional
You can use and and or for conditional execution
!e
# this function is purely for reusablility.
# there is no recursion, nor nothing funny happening.
def interpret(brainfuck):
# bf data
ptr = [0]
memory = [0] * 30_000
# calculating the brace relations
brace = {}
stack = []
[
(
(instr == "[" and stack.append(pos)),
(instr == "]" and (
brace.__setitem__(stack[-1], pos),
brace.__setitem__(pos, stack.pop()),
))
)
for pos, instr in enumerate(brainfuck)
]
instr = [0]
command = ["X"]
next(
0
for _ in iter(int, 1)
if not (instr[0] < len(brainfuck) and (
command.__setitem__(0, brainfuck[instr[0]]),
(command[0] == ">" and (ptr.__setitem__(0, ptr[0] + 1))),
(command[0] == "<" and (ptr.__setitem__(0, ptr[0] - 1))),
(command[0] == "+" and (memory.__setitem__(ptr[0], (memory[ptr[0]] + 1) % 256 ))),
(command[0] == "-" and (memory.__setitem__(ptr[0], (memory[ptr[0]] - 1) % 256))),
(command[0] == "[" and memory[ptr[0]] == 0 and (instr.__setitem__(0, brace[instr[0]]))),
(command[0] == "]" and memory[ptr[0]] != 0 and (instr.__setitem__(0, brace[instr[0]]))),
(command[0] == "." and (print(chr(memory[ptr[0]]),end=""))),
(command[0] == "," and (memory.__setitem__(ptr[0], ord(input())))),
instr.__setitem__(0, instr[0] + 1),
))
)
# hello world
interpret("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.")
# hello world 2
interpret("+[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++[.>]<<<<.+++.------.<<-.>>>>+.")
# thue morse
interpret(">>++++++[>++++++++<-]+[[>.[>]+<<[->-<<<]>[>+<<]>]>++<++]")
@languid hare :x: Your eval job timed out or ran out of memory.
001 | Hello World!
002 | Hello, World!01101001100101101001011001101001100101100110100101101001100101101001011001101001011010011001011001101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101101001011001101001011010011001011001101001100101101001011001101001011010011001011010010110011010011001011001101001011010011001011001101001100101101001011001101001100101100110100101101001100101101001011001101001011010011001011001101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100101101001100101101001011001101001100101100110100101101001100101101001011001101001011010011001011001101001100101101001011001101001100101100110100101101001100101100110100110010110100101100110100101
... (truncated - too long)
Full output: too long to upload
brainfuck without colons, hence turing complete
i feel like a lisp programmer
@fleet bridge
!e print((3+(not([]))-(not(not([]+[(not(not(not([]))))]))))23int(f"{int(not(not([]+[(not(not(not([]))))])))}")*int(f"{int(not(not([]+[(not(not(not([]))))])))}{int(int(not(not([]+[(not(not(not([]))))])))-(not(not([(69)]))))}{int(int(not(not([]+[(not(not(not([]))))])))-(not(not([(69)]))))}{int(int(not(not([]+[(not(not(not([]))))])))-(not(not([(69)]))))}")+int(f"{(int(int(not(not([]+[(not(not(not([]))))])))+int(not(not([]+[(not(not(not([]))))])))+int(not(not([]+[(not(not(not([]))))])))+int(not(not([]+[(not(not(not([]))))]))))-(not([(69)])))}{(int(int(not(not([]+[(not(not(not([]))))])))+int(not(not([]+[(not(not(not([]))))]))))-(not([(69)])))}{int(int(not(not([]+[(not(not(not([]))))])))-(not(not([(69)]))))}"))
@split salmon :white_check_mark: Your eval job has completed with return code 0.
69420
!e
def bf(c): # the only colon in function definition
s=type('',(dict,),dict(__setattr__=dict.__setitem__,__getattr__=dict.__getitem__))()
s.i=0
s.m=0
s.c=[]
s.M=[0]*2**16
s.s=0
next(...for _ in iter(str,0)if((s.__setattr__('s',s.s+1)if c[s.i]=='['else s.__setattr__('s',s.s-1)if c[s.i]==']'else None)if s.s else(s.M.__setitem__(s.m,s.M[s.m]+1)if c[s.i]=='+'else s.M.__setitem__(s.m,s.M[s.m]-1)if c[s.i]=='-'else s.__setattr__('m',s.m+1)if c[s.i]=='>'else s.__setattr__('m',s.m-1)if c[s.i]=='<'else 1/0if c[s.i]==','else print(end=chr(s.M[s.m]))if c[s.i]=='.'else(s.__setattr__('s',s.s+1)if not s.M[s.m]else s.c.append(s.i))if c[s.i]=='['else(s.__setattr__('i',s.c.pop()-1)if s.M[s.m]else s.c.pop())if c[s.i]==']'else None),s.__setattr__('i',s.i+1),s.i>=len(c))[-1])
bf(
''' # hello world from wikipedia
++++++++++[>++++
+++>++++++++++>+
++>+<<<<-]>++.>+
.+++++++..+++.>+
+.<<++++++++++++
+++.>.+++.------
.--------.>+.>.
'''
)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
Hello World!
Hey @fleet bridge!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
https://paste.pythondiscord.com/yozocepiqu
steps of implementation
it doesnt support ,, because there are no good way to get one char without imports
to implement , just replace 1/0 in the middle of code with actual implementation
someone golf it up even more ๐ฅด
golfing it would be akin to print(69420), no?
... what
i like that you showed your working
second code is from esolangs
it calculates bitsize of memory cell (but it always return 32, because python ints is very big for this program ๐)
neat
oh, ment obfuscate it even more
i shoved on a %256 to emulate a byte cell
!e
def bf(c): # the only colon in function definition
s=type('',(dict,),dict(__setattr__=dict.__setitem__,__getattr__=dict.__getitem__))()
s.i=0
s.m=0
s.c=[]
s.M=[0]*2**16
s.s=0
next(...for _ in iter(str,0)if((s.__setattr__('s',s.s+1)if c[s.i]=='['else s.__setattr__('s',s.s-1)if c[s.i]==']'else None)if s.s else(s.M.__setitem__(s.m,(s.M[s.m]+1)%2**16)if c[s.i]=='+'else s.M.__setitem__(s.m,(s.M[s.m]-1)%2**16)if c[s.i]=='-'else s.__setattr__('m',s.m+1)if c[s.i]=='>'else s.__setattr__('m',s.m-1)if c[s.i]=='<'else 1/0if c[s.i]==','else print(end=chr(s.M[s.m]))if c[s.i]=='.'else(s.__setattr__('s',s.s+1)if not s.M[s.m]else s.c.append(s.i))if c[s.i]=='['else(s.__setattr__('i',s.c.pop()-1)if s.M[s.m]else s.c.pop())if c[s.i]==']'else None),s.__setattr__('i',s.i+1),s.i>=len(c))[-1])
bf(
'''
++++++++[>++++++
++<-]>[<++++>-]+
<[>-<[>++++<-]>[
<++++++++>-]<[>+
+++++++<-]+>[>++
++++++++[>+++++<
-]>+.-.[-]<<[-]<
->]<[>>+++++++[>
+++++++<-]>.++++
+.[-]<<<-]]>[>++
++++++[>+++++++<
-]>.[-]<<-]<++++
+++++++[>+++>+++
++++++>+++++++++
>+<<<<-]>-.>-.++
+++++.++++++++++
+.<.>>.++.++++++
+..<-.>>-[[-]<]
'''
)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
16 bit cells
lol the ligatures
cursed
in my sublimetext it also get ligatured
well this kinda turned into a bf implementation challenge
print(69420)
๐
i hate u
i need ideas on code to golf
or ungolf
just gimme ideas
look at some project you made, and golf it
!e ```py
from sys import getframe
from types import CodeType
from dis import opmap
from ctypes import c_char
def builtinexc(exc, depth=1):frame = getframe(1 + depth);addr = id(co := frame.f_code.co_code) + bytes.basicsize - 1;mem = (c_char * len(co)).from_address(addr);mem[frame.f_lasti + 2:frame.f_lasti + 4] = bytes([opmap['RAISE_VARARGS'], 1]);return exc
def private_attributes(*attributes):
attributes={*attributes};all_code={x for x in getframe(1).f_code.co_consts if isinstance(x, CodeType)};old___getattribute=(m:=getframe(1).f_locals.get)("getattribute");old___setattr=m("setattr")
def getattribute___wrap(self,name):
if name in attributes:
frame=getframe(1)
while frame and frame.f_code not in all_code:frame=frame.f_back
if not frame:return builtinexc(AttributeError(f"'{type(self).name}' object has no attribute '{name}'"))
return old___getattribute(self,name)if old___getattribute_ else super(type(self),self).getattribute(name)
def setattr___wrap(self,name,value):
if name in attributes:
frame = getframe(1)
while frame and frame.f_code not in all_code:frame = frame.f_back
if not frame:return builtinexc(AttributeError(f"'{type(self).name}' object has no attribute '{name}'"))
return old___setattr(self,name,value)if old___setattr_ else super(type(self),self).setattr(name,value)
return __getattribute___wrap,__setattr___wrap
class Person:
def init(self, name, age):
self._name = name
self.age = age
@property
def name(self):
return self._name
@name.setter
def name(self, value):
print('Inside in set method')
if len(value) > 10:
print('new name too long')
else:
self._name = value
def getattribute(self, name):
print(repr(name))
return super().getattribute(name)
getattribute, setattr = private_attributes("_name")
print(Person("ha", 3).name)
Person("ha", 3)._name
@quartz wave :x: Your eval job has completed with return code 1.
001 | 'name'
002 | '_name'
003 | ha
004 | Traceback (most recent call last):
005 | File "<string>", line 42, in <module>
006 | AttributeError: 'Person' object has no attribute '_name'
unshortened function: https://paste.pythondiscord.com/ahonemusif.py
๐
n x n tictactoe
Golfing C isn't really that fun because macros
try the 3x3 ttt, I wanna see if there's a shorter implementation in one line
I ment obfuscate ๐ฅด
Thanks
!e
print(2 - 0.1)
print(2 - 1.1)
@teal saffron :white_check_mark: Your eval job has completed with return code 0.
001 | 1.9
002 | 0.8999999999999999
@teal saffron :white_check_mark: Your eval job has completed with return code 0.
0.9
Right
idea: typehinting typehints
computation is performed via operations on those typehints
it would probably have to be functional
omg, real private attributes. Could you do a protection against Person.__getattribute__, Person.__setattr__ = object.__getattribute__, object.__setattr__?
>>> print(2.0 - 1.1)
0.8999999999999999``` wait, what?
can someone give me an explanation on why its 0.8999999999999999
!e https://0.30000000000000004.com/
print(0.1 + 0.2)
@languid hare :white_check_mark: Your eval job has completed with return code 0.
0.30000000000000004
!e print(0.1 + 0.2)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
0.30000000000000004
wtf
essentially, its the same issue as 1/3 = 0.33333... in decimal
does it have to do with 32/64 bit? idk
at some point the computer needs to stop storing the decimal bits
close, it's to do with the floating point standard
it cant hold a certain amount of decimals right?
this website gives a pretty comprehensive explanation
alright thanks
!e
a = True
print(True is a)
@teal saffron :white_check_mark: Your eval job has completed with return code 0.
True
hmm
what were u expecting lmao
idk
there's only one true and one false
all trues are the same true
!e which is why this fails
class BoolSub(bool):
pass
@languid hare :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: type 'bool' is not an acceptable base type
!e
a = True + True
a += True * a
b = a*a
print(a)
@teal saffron :white_check_mark: Your eval job has completed with return code 0.
4
@sick hound :white_check_mark: Your eval job has completed with return code 0.
0
!e print(pow(True, True, True))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
0
!e
from hashlib import md5
print(md5(b'asd').hexdigest())
@teal saffron :white_check_mark: Your eval job has completed with return code 0.
7815696ecbf1c96e6894b779456d330e
whats sha256 on python
md5
!e
True = False
print(True is False)
@carmine sun :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | True = False
003 | ^^^^
004 | SyntaxError: cannot assign to True
!e
import random
import string
string = 'Hello World'
charset = string.digits + string.ascii_letters
random.seed(string)
print(''.join([random.choice(charset)] for _ in range(32)))
@teal saffron :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | AttributeError: 'str' object has no attribute 'digits'
!e
import random
import string
text = 'Hello World'
charset = string.digits + string.ascii_letters
random.seed(text)
print(''.join([random.choice(charset)] for _ in range(32)))
@teal saffron :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 7, in <module>
003 | TypeError: sequence item 0: expected str instance, list found
!e
import random
import string
text = 'Hello World'
charset = string.digits + string.ascii_letters
random.seed(text)
print(''.join([random.choice(charset) for _ in range(32)]))
@teal saffron :white_check_mark: Your eval job has completed with return code 0.
AyhdMoOfcVF39uEyM6r7ojx8GqrciVOr
DIY hash
!e
import random
import string
text = 'Hello World'
charset = string.digits + string.ascii_letters
random.seed(text)
print(''.join([random.choice(charset) for _ in range(32)]))
@teal saffron :white_check_mark: Your eval job has completed with return code 0.
AyhdMoOfcVF39uEyM6r7ojx8GqrciVOr
!e
import random
import string
text = 'Hello World'
charset = string.digits + string.ascii_letters
random.seed(text)
print('testing times')
print(''.join([random.choice(charset) for _ in range(32)]))
@teal saffron :white_check_mark: Your eval job has completed with return code 0.
001 | testing times
002 | AyhdMoOfcVF39uEyM6r7ojx8GqrciVOr
perfect
whats this supposed to be
is like sha256 but diy
replace random.seed(text) with random.seed( pow(len(text),len(text))*3 ) or something like that
way harder to get the original source
still fairly easy tho
yeah but if u were trying to decrypt the message it would be harder than just random.seed(text)
a hash is different from an encryption
Send obfuscated code
there's no decryption possible
so y are people still making hash systems
'a' and 'b' hash to the same thing, there's no way to tell between them
hashes are used differently than encryptions
the point of the hash is that it's near impossible to reverse
Hashes are one way functions
one application of a (well made) hash is a checksum
all hashes are eventually going to be cracked if someone wants it to be cracked
so are encryptions?
and "eventually" usually means "billions of years"
so we're good
you're indirectly asking about hashes versus encryptions, im pointing out that they both can be cracked given enough time.
!d hashlib.sha256
No documentation found for the requested symbol.
!e
from hashlib import sha256
print(sha256(b'abc').hexdigest())
@wheat river :white_check_mark: Your eval job has completed with return code 0.
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
what are some other uses for sha256 hashing other than inputs and all that stuff
common use is password databases
@languid hare what you think about my diy hash using the text as a seed of random lib?
its more of an encryption but i like it
most encryptions use keys
but no this
you rarely want to store the actual password, since a leak in the database would leak everyone's raw passwords. instead, store the hash of the password. you can then check that the password is correct by doing hash(password) == hash(input)
i think my code is decent
this would be closer to a hash, since there's no obvious reversal
you should probably just use sha/blake though :p
so in the database u would store all the things like json {'username': 'oshnbisnhibjsrnbijsrnijbsw'} oshnbisnhibjsrnbijsrnijbsw is the hash of osgjsbsnb (example) and then when u check if its correct u do hash('user_input')
i imagine the prng has lots of vulns
yep
in practice it's slightly different, but that's the main idea

Is this secure for guaranteeing that the code has not been tampered with?
def pynotamper(code:bytes, key:bytes):
encrypted = AES.new(key, AES.MODE_CTR, counter=Counter.new(128)).encrypt(code)
encrypted += SHA512.new(encrypted).digest() + SHA512.new(code).digest()
return base64.b64encode(encrypted)
def pynotamper_runtime(jxIA02kS924zR3t6:bytes, Mg3qVz9LuNcEa037:bytes):
Ce3J8SmjA29SOlJm = eval('\x65\x33\x76\x78\x61\x39\x6c\x41'[::-1][::-2])
EvUAo61c3rn91qET = Ce3J8SmjA29SOlJm('\x66\x61\x65\x31\x65\x78\x65\x63\x41\x45\x53\x2e\x6e\x65\x77'[8:])
Uvn3NxZ5aEc019Dq = eval('\x53\x48\x41\x35\x31\x32\x2e\x6e\x65\x77')
jxIA02kS924zR3t6 = base64.b64decode(jxIA02kS924zR3t6)
yjCUn0X8lKsoWPm4 = eval('\x41\x45\x53\x2e\x4d\x4f\x44\x45\x5f\x43\x54\x52')
nUoaW517UvGyNzzA, jxIA02kS924zR3t6 = jxIA02kS924zR3t6[-64:], jxIA02kS924zR3t6[:-64]
IaOsKnnAt61f5mJ8, jxIA02kS924zR3t6 = jxIA02kS924zR3t6[-64:], jxIA02kS924zR3t6[:-64]
Vr419fC5aEqBn551 = Uvn3NxZ5aEc019Dq(jxIA02kS924zR3t6).digest()
if Vr419fC5aEqBn551 == IaOsKnnAt61f5mJ8 and Ce3J8SmjA29SOlJm('\x6a\x78\x49\x41\x30\x32\x6b\x53\x39\x32\x34\x7a\x52\x33\x74\x36') == jxIA02kS924zR3t6:
PAoSKWmeSDkxOAPe = EvUAo61c3rn91qET(Mg3qVz9LuNcEa037, yjCUn0X8lKsoWPm4, counter=Counter.new(128)).decrypt(jxIA02kS924zR3t6)
tReV3gaSdb6198YY = Uvn3NxZ5aEc019Dq(PAoSKWmeSDkxOAPe).digest()
if tReV3gaSdb6198YY == nUoaW517UvGyNzzA:
exec(PAoSKWmeSDkxOAPe)
tf
anyone with a decent sized brain can figure that out
you really don't even need a brain
there's software (javascript for now) that can clean up some 60-80% of obfuscation techniques automatically
Strange idea
what's the most number of python builtins (all these: https://docs.python.org/3/library/functions.html) you can plug into one another to create a non-erroring program with the form py b1(b2(b3(...bN(arg)...))) No commas allowed except in arg which may be anything
like py print(tuple(enumerate(iter(str(id(abs(float(int(eval("4")))))))))) which was a quick first attempt, N = 10
can u reuse a builin? like int(...(int(...))?
hmm, I'ma say no
print(slice(staticmethod(classmethod(property(super(type(callable(sum(set(frozenset(bytearray(memoryview(bytes(any(ascii(range(len(list(reversed(sorted(max(min(dir(hex(ord(chr(bool(complex(hash(bin(all(tuple(zip(enumerate(next(iter(format(oct(abs(round(float(int(id(exec(repr(str(vars(eval("type")))))))))))))))))))))))))))))))))))))))))))))))))
!e ```py
print(slice(staticmethod(classmethod(property(super(type(callable(sum(set(frozenset(bytearray(memoryview(bytes(any(ascii(range(len(list(reversed(sorted(max(min(dir(hex(ord(chr(bool(complex(hash(bin(all(tuple(zip(enumerate(next(iter(format(oct(abs(round(float(int(id(exec(repr(str(vars(eval("type")))))))))))))))))))))))))))))))))))))))))))))))))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
slice(None, <staticmethod(<classmethod(<property object at 0x7fd6d475fbf0>)>)>, None)
!e ```py
print("""print(slice(staticmethod(classmethod(property(super(type(callable(sum(set(frozenset(bytearray(memoryview(bytes(any(ascii(range(len(list(reversed(sorted(max(min(dir(hex(ord(chr(bool(complex(hash(bin(all(tuple(zip(enumerate(next(iter(format(oct(abs(round(float(int(id(exec(repr(str(vars(eval("type")))))))))))))))))))))))))))))))))))))))))))))))))""".count(')'))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
49
49
๐ ๐
is it done now
(oh, you calculated it already
)
or can anyone do __import__ and open
!e i can use 52 builtins ```py
from typing import Any
l: list[Any] = [
'hello',
import,
vars,
enumerate,
dict,
iter,
next,
bool,
complex,
abs,
ascii,
exec,
dir,
all,
bytearray,
sum,
bytes,
memoryview,
classmethod,
property,
staticmethod,
id,
oct,
hash,
float,
round,
int,
hex,
any,
chr,
repr,
eval,
ord,
range,
max,
bin,
set,
slice,
str,
list,
reversed,
min,
frozenset,
zip,
sorted,
tuple,
len,
callable,
open,
print,
type,
# help,
# input, # it uses stdout, but it works in console
]
x = l[0]
for c in l[1:]:
# print(f'{x!r:50} {c}')
x = c(x)
print(f'{len(l)} items used')
51 + 2(help and input) - 1(string literal in beginning)
= 52
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | Hello world!
002 | <_io.TextIOWrapper name=False mode='r' encoding='UTF-8'>
003 | 51 items used
nice
i dont use this:
# takes 2+ arguments
compile
delattr
divmod
filter
format
getattr
hasattr
isinstance
issubclass
map
pow
setattr
super
# takes no arguments
globals
object
locals
# has so much side-effects
breakpoint
aiter
anext
50 items excluding help() and input()
yes
looks like you finally got back on me from the random RGB digits thing
short version ```py
type(print(open(callable(len(tuple(sorted(zip(frozenset(min(reversed(list(str(slice(set(bin(max(range(ord(eval(repr(chr(any(hex(int(round(float(hash(oct(id(staticmethod(property(classmethod(memoryview(bytes(sum(bytearray(all(dir(exec(ascii(abs(complex(bool(next(iter(dict(enumerate(vars(import('hello'))))))))))))))))))))))))))))))))))))))))))))))))))
wait didn't say anything about other symbols ๐ค
@fleet bridge wait no checkmate ```py
print(slice(staticmethod(classmethod(property(super(type(open(callable(sum(set(frozenset(bytearray(memoryview(bytes(any(range(len(list(reversed(sorted(max(min(dir(hex(ord(chr(bool(complex(hash(bin(all(tuple(zip(dict(enumerate(next(iter(format(oct(abs(round(float(int(id(exec(ascii(eval(repr(str(vars(import("hello"))))))))))))))))))))))))))))))))))))))))))))))))))))
you add super?
nvm
format() falls back to str() when given one argument
it's good when there are people better than you
in that case there is something to learn
you win again
i currently have no idea how i did that
can we use exception classes
they're all part of __builtins__
Just the ones in that page are allowed
ok
Or make your own rules, just for fun after all 
it was interesting to write hello-world not using brackets () and with empty globals and builtin dictionaries
Challenge:
You are allowed to use only one name (builtin or not) and _. Your program should print Hello World
also you cant use print ๐
you arent allowed to use any attributes except dunder attributes
__import__('__hello__')
__import__('sys').__dict__['__stdout__'].__class__.__dict__['write'](__import__('sys').__dict__['__stdout__'], 'Hello world')
ok it is not very interesting
Seeing this conversation, I understand that I'm lost in the internet.
But that's a nice place to be lost in :p
import __hello__
oh no, statements ๐คข
we can eval() this whole challenge to oblivion
boring 
my 3x3 ttt one-liner 2.0 ```py
(w:=[0,0],j:=lambda a,b=0:a.setstate(b),P:=print,R:=range,c:=lambda:P("\n---+---+---\n".join("|".join([(w[0]&(h:=1<<8-)==h)" o "+(w[1]&h==h)" x "or f" {+1} "for()in R(9)][:+3])for()in R(0,9,3))),c(),q:=iter([(0,"o"),(1,"x")]),[(i:=iter([1]),[(n:=input(f"{d}'s turn: "),(n.isdigit()and(0<(I:=int(n))<10)and(r:=1<<9-I)&(w[0]|w[1])<1or(P("Invalid!"),c(),j(i))))for(_)in i],w.insert(p,g:=w.pop(p)|r),c(),p<1or j(q),(j(q,3),P(f"{d} won the game!"))if any(g&i==i for(i)in[292,146,73,448,56,7,273,84])else(w[0]|w[1]<511)or(j(q,3),P("Draw!")))for(p,d)in q])
559 chars hm
yes but that has a SyntaxWarning now
i have no warning on py3.10
that's because you're on python 3.10
!e print(__import__('sys').version)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
3.10.2 (main, Mar 2 2022, 04:12:38) [GCC 8.3.0]
.bm
wait it's still just 3.10.2?
3.10.4 is the latest stable version though
How did you get these colors in your terminal?
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.
https://paste.pythondiscord.com/zubusitino
there is my sitecustomize.py
put it into <python>/Lib/site-packages/sitecustomize.py
warning! its very bad code!
ah missed that
any esolang expert here who can correct my chicken code, and tell me why its not running well?
i just wanna know where to place the load instructions in the language
as i couldnt find it in the wiki
dont think it would be appropriate to take over an help channel for such an issue
wdym by " load instructions in the language"
like in chicken language u have the store instructions but due to the stack executing inputs directly from the user i get the following error with my code in chickenpy:
chickenpy.VM - Evaluating s
Traceback (most recent call last):
File , line 76, in <module>
sys.exit(main())
File , line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File , line 760, in invoke
return __callback(*args, **kwargs)
File , line 71, in main
exit_status = interpret(source_code, input)
File , line 35, in interpret
result = vm.run()
File , line 162, in run
self.dispatch(self.next_token)
File , line 152, in dispatch
token = op - 10
TypeError: unsupported operand type(s) for -: 'str' and 'int
i saw most of the examples uses load (6 chickens ) and an exit(new line) after certain instructions i just wanna know where to place those
any idea?
ping me up if someone answers
thx
ะัะธะฒะตั. ะัะพััะพะน ะฒะพะฟัะพั. ะะฐะบ ัะฐัะฟะฐะบะพะฒะฐัั ััะธ ะดะฐะฝะฝัะต ?
indicators:<object object at 0x03CD84E8>
json_parse:<function ApiTradingStatus.json_parse at 0x03565460>
Hello. A simple question. How do I unpack this data ?
indicators:<object object at 0x03CD84E8>
json_parse:<function ApiTradingStatus.json_parse at 0x03565460>
why is this channel becoming a help channel ๐
challenge: golf a match-case as much as you can
example of a normal match-case function:
def http_status(status):
match status:
case 400:
return "Bad request"
case 401:
return "Authentication error"```
i don't think it's possible to golf a match-case, given that it matches structures and they aren't really just an if else statement
let's say this: ```py
from ast import *
def func(node):
match node:
case Assign(targets=[Name(id=id)], value=value):
return [Expr(NamedExpr(
target=Name(id=id, ctx=Store()),
value=value
))]
there really isn't a way to golf it without losing functionality
hey?
.bm
i got a wuestion
question
so say that you want to make a goto function
how would you do it
i made on 3 months ago but forgot
!pypi goto-statement
it isnt a goto line one
Like goto(line number)?
i did a chicken implementation in this message:
#esoteric-python message
np
This uses trace functions, which can jump to lines in a limited way
youtube url regex py re.search('(((https?://)?(m\.)?)|((https?://)?(www\.)?))?youtu\.?be\.com((/watch\?v=[a-zA-Z0-9]{11}){1}|(/([a-zA-Z0-9]){11}){1})?', string)
Really hope Stelercus doesn't spawn out of the ether
youtube URLs can also contain dashes
fucccccccckkkkkkkkkkkk
these are your test cases ```
youtu.be/iwGFalTRHDA
youtube.com/watch?v=iwGFalTRHDA
www.youtube.com/watch?v=iwGFalTRHDA
http://www.youtube.com/watch?v=iwGFalTRHDA
https://www.youtube.com/watch?v=iwGFalTRHDA
https://www.youtube.com/watch?v=MoBL33GT9S8&feature=share
https://www.youtube.com/embed/watch?feature=player_embedded&v=iwGFalTRHDA
https://www.youtube.com/embed/watch?v=iwGFalTRHDA
https://www.youtube.com/embed/v=iwGFalTRHDA
https://www.youtube.com/watch/iwGFalTRHDA
http://www.youtube.com/attribution_link?u=/watch?v=aGmiw_rrNxk&feature=share
https://m.youtube.com/watch?v=iwGFalTRHDA
.bm fuck
Hi all, super general question. What is the purpose of "unit tests" and what can go wrong if you don't use them?
Maybe ask in #unit-testing, in this channel we almost never write tests
Ahh, sorry I didn't even see that channel. Thanks for your replay, and will do ๐
It's been a while since I've posted, so here's a teaser:
@type.__call__
class NULL: ...
Hey esoteric people
Was hoping for some input
I'm writing what you might call a wrapper around python's object model
To enforce type hints and privacy at runtime. So far its working way better than I dared hope, though it hasn't been put up against the unfathomable hacking power of the coding community at large yet
Anyway โ what I want to ask about is, what is the best way to bootstrap this framework such that it uses its own protocols to enforce itself
It is, in a nutshell, a set of base classes, metaclasses, property descriptors, and function decorators which together gate access data that is hidden from the python runtime via cython
Though, I'm not opposed to implementing the whole thing in C if I have to โ it certainly couldn't hurt in terms of performance
In general, anything on the Python side is visible to anyone who tries to find it, so the more cdefs the better for privacy
Here's a cross-platform way to create a list:
eval(eval("__import__('subprocess').run(['py' if __import__('os').name == 'nt' else 'python3', '-c', \"print(eval('list()'))\"],stdout=__import__('subprocess').PIPE).stdout.decode('UTF-8')[:2]"))
Hello!
I'm having difficulty coding up FizzBuzz. The game seems quite simple to program but for some reason my program isn't working.
Here is the Github link to my code: https://raw.githubusercontent.com/MITStudent115/fizzbuzz/main/fizzbuzz.fl.py
Alternatively, here is the gist: https://gist.github.com/MITStudent115/2c28f9048845ed2e248a056131f8e4f2
If you could help me out, that would be greatly appreciated!
you could have just dumped the deobfuscated code into one of the help channels-
looks like you typoed 14 as 15
def fizzbuzz(x: int) -> str:
if not x % 14:
return "FizzBuzz"
if not x % 5:
return "Buzz"
if not x % 3:
return "Fizz"
return str(x)
x = int(input("Number: "))
print(fizzbuzz(x))
x % 15
oh wait
i didn't read the message above
mb sry
yea it's alr
!e py print(6,end='');print(9,end='')
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
69
!e print('shoot mfs');print((drugs:=lambda x:69)(2))
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
001 | shoot mfs
002 | 69
!e py __peg__parser__
@upbeat sonnet :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name '__peg__parser__' is not defined
@upbeat sonnet :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name '__peg_parser__' is not defined
!e
from pprint import pprint
pprint(globals())
pprint(__builtins__.__dict__)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | {'__annotations__': {},
002 | '__builtins__': <module 'builtins' (built-in)>,
003 | '__doc__': None,
004 | '__loader__': <class '_frozen_importlib.BuiltinImporter'>,
005 | '__name__': '__main__',
006 | '__package__': None,
007 | '__spec__': None,
008 | 'pprint': <function pprint at 0x7fc0d1b04f70>}
009 | {'ArithmeticError': <class 'ArithmeticError'>,
010 | 'AssertionError': <class 'AssertionError'>,
011 | 'AttributeError': <class 'AttributeError'>,
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/uqasugadaf.txt?noredirect
oh
only 3.9
jah
Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on win32
>>> __peg_parser__
File "<stdin>", line 1
__peg_parser__
^
SyntaxError: You found it!
variable=[]
this dont work in this channel ๐
please post more
# Root sentinel
@type.__call__
class TypeLevelSentinel:
# prefer builtin-attributes over trait-provided
def __call__(self, ty, key):
if (method := HAS_ATTRIBUTE(ty, key)) is not NULL:
return method
if (sentinel := HAS_ATTRIBUTE(ty, "__sentinel")) is not NULL:
if method := sentinel.get_unbound(key):
return method
raise AttributeError(key)
# bad things here
@wraps(type.__getattribute__)
def type_wrapper(t, n):
return TypeLevelSentinel(t, n)
hook(type, "__getattribute__")(type_wrapper)
This is part of a system that enables this kind of code:
from traitor.traits import From
class Foo:
def __init__(self, n):
self.name = n[::-1]
def __repr__(self):
return f"<Foo({self.name})>"
@impl(From[Foo] >> str)
class StrFromFoo:
def from_(value):
return value.name[::-1]
@impl(From[str] >> Foo)
class FooFromStr:
def from_(value):
return Foo(value)
# >>>>>>>>
f = "asd".into()
print(f)
name = From[Foo](str).from_(f)
print(name)
% > python examples/from_into.py
<Foo(dsa)>
asd
wow
i was implementing @constmethod decorator and const[X](0) behavior, but its too hard for me
ill have a go at it
nvm
too hard for me
whats this for
then tell em so i can
me*
Did u forget Im smarter xD
I learn extremely fast
I started python 2 hours ago and learn basic operators within 30 mins
ok but wendys or taco bell
wendys or mcdonalds
do u know what wendys is?
yes
wendys nuts-
im australian
LOL
mc
fat child
tell em what this si about ๐คฃ
i hate fast typing
i sound french
si
si si si
tell me what this is about
this channel is for code gore
whys the owner joe a discord mod
liek what
!e
x = object()
y = object()
TODO: change this code
x_list = [x]
y_list = [y]
big_list = []
print("x_list contains %d objects" % len(x_list))
print("y_list contains %d objects" % len(y_list))
print("big_list contains %d objects" % len(big_list))
testing code
if x_list.count(x) == 10 and y_list.count(y) == 10:
print("Almost there...")
if big_list.count(x) == 10 and big_list.count(y) == 10:
print("Great!")
@grim root :white_check_mark: Your eval job has completed with return code 0.
001 | x_list contains 1 objects
002 | y_list contains 1 objects
003 | big_list contains 0 objects
nerd
look at this
try learning that in 30 minutes
modify the charismic function @sick hound
idk what charismic means
outline the ordeal sequence
there u go
see genius
i havent even learnt that before
i just started and know
ok go do it
I did..
ok
in 1 line?
mhm
i could do it in many lines
everyone can lol
i did it in my tech class at school in <10 mins
aafter u learnt it
would this work?
import random
list(print(['tie', 'you win', 'you lose'][((int(input("0 = rock, 1 = paper, 2 = scissors? ")) - c) % 3)] + f' - computer picked {["rock", "paper", "scissors"][c]}') for c in [random.randint(0, 2) for _ in range(100)])```
?
oh i found out how to do it in 1 liner @sick hound
exec("""import random\n[print(["Draw:|","Lose:)","Win:("][(choice - int(input("1. Rock, 2.Paper, 3.Scissors\\n"))) % 3] + f' computer chose {["Scissor", "Rock", "Paper"][choice]}') for choice in [random.randint(0, 2)]]""")```
there
import random;[print(["Draw:|","Lose:)","Win:("][(choice - int(input("1. Rock, 2.Paper, 3.Scissors\n"))) % 3] + f' computer chose {["Scissor", "Rock", "Paper"][choice]}') for choice in [random.randint(0, 2)]]```
without exec
@sick hound rate this?
yea def didnt copy
0 votes and 5 comments so far on Reddit
lmao
semicolons is fake 1 liner
do
(any(globals().__setitem__('random',__import__('random')))),
for the import part
sad
off?
its possible to have same code?
try golfing it even more, and maybe add logic to determine which player won (either the player or computer). maybe make it an infinite loop as well, and let it accepting input continuously until you quit.
make it one line as well, since that would be more fun to figure out. (no exec no eval no semicolons)
semicolons is cheating
for the infinite loop maybe while (x:=input("Rock, Paper, Scissors or Quit? (r,p,s,q)"))!="q"
golfing ๐
sacrificing QoL ๐คข
you mean this?
any(globals().__setitem__('random',__import__('random'))),
brackets
wehr
(print("Hello")),...
vs
print("Hello"),...
that's "square brackets"
๐คท
๐
bracelets []
parenthisis ()
and uhh
dictionary {}
square brackets []
round brackets ()
squiggly brackets {}
{} is definitely not "dictionary"
that's what it is in python xD
in python it's also used as a set
{} - braces
!e ```py
print(type({...}))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
<class 'set'>
that's the official name
braces is the official name
{} and dict have nothing to do with each other other than syntax involvment
{:} is the complete mandatory dict syntax set
but it's also the f-string escape set
{...,...} can build a set
{...:...,...:...} can build a dict
f"{x:s}" can build a string
{} and dictionary is a one way relationship in the context of definition.
braces define the dict, not the other way around
side note brackets are useful for making these in forms.
are you sure? [_] Yes, [_] No
"squiggly brackets" should be formal language usage.
!e ```py
fake random
print(int(''.join([{'abcedf1234567890'}]),16))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
4242204213832779900
brackets []
parenthesis ()
braces {}
whats the diff
i dont get it
!e ```py
fake random
print(int(''.join([{'abcedf1234567890'}]),16))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
16067915518771335795
i love that
parentheses ()
brackets []
braces {}
chevrons <>
<| |> bra and ket
{{ }} braces in f-string
begin end - pascal-style braces
(* *) - wolfram-style comments
/* */ - multiline comment in c
<indent> <dedent> - python braces
{% %} jinja style
parentheses, (square) brackets, curly brackets
() brackets
[] rungs
{} fences
<> shards
wdym
() curly brackets
[] square brackets
{} braces
<> closing brackets
no
normal doesn't belong here
yes
the hashing is seeded when the runtime starts
this actually makes a lot of sense
NO
mine is better
ive never heard of rungs
it looks like rungs
if you told me there was a pair of symbol called rungs that would be it
no its
parenthesis ()
brackets []
braces {}
roundy ()
recty []
moustache {}
beak <>
circle ()
square []
spiky ball {}
2 triangles <>
like if u make a list [1, 2, 3, 4] it will keep its order that it if u dont change it, it will stay the same
whereas a set doesn't maintain any order, that is why u can't do something like {1, 2, 3, 4}[0]
why you can't*
yes
closing brackets??
that would be ], } or >
maybe )
but def not <
but you can do {1, 2, 3, 4}.pop()
!e ```py
a = {1, 2, 3, 4}
print(a.pop())
print(a.pop())
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
!e ```python
def main():
print('hello world!')
one line idiom!
(main if name == 'main' else (lambda *_: None))()
@silver sable :white_check_mark: Your eval job has completed with return code 0.
hello world!
time to use it in every single main python file i make 
!pypi dont New tiny package I made :)
You can do something like:
import dont
class bash(dont):
def hook(self):
for line in self.content:
os.system(line.replace("%", " "))
with bash(): # prints "hello" and touches the file `me`:
echo % hello
touch % me
so basically suppress all exceptions
no, it doesn't even attempt to execute anything inside the context manager
it's surprisingly tricky: by setting a trace function that raises immediately when entering the block, which the context manager then catches
(Here's the source: https://github.com/L3viathan/dont/blob/master/dont.py)
ik i got there before i read the PyPI description
Very nice.
alternatively, let the code run, do everything in enter, let the exceptions raise, ignore them in exit
of course that means the code will attempt to run, but what could possibly go wrong? XD
i mean you could just do ```py
name != "main" or main()
that's more concise ๐
idk i had to think of something better than shards
that doesnt look cool tho
ยฏ_(ใ)_/ยฏ
Whoops
__name__ == "__main__" and main() 
totally not the same suggestion again
https://github.com/scoder/lupa does anyone use this? I'm not familiar with Lua and I would like to interact with an api exposed via Lua using lupa. I'm wondering if this will be possible using Lupa... this is what I wish to interact with: https://www.mesen.ca/snes/docs/apireference.html
Either way I will have to learn Lua right? Which at that point I might as well just use the Lua API?
scripting language inside a interpreted programming language
kinda lookin' for this one
I think it looks cooler shorter :P
arrows
def _palette(self, x, y, c):
...
def run(self, size=None):
if size is not None:self.setsize(*size)
*_,X,Y=x,y,c,*size=*(Im:=self.Im).size,self.constant,*self.size
p = self._pallette(*_)
...
My own code scares me.
oh god
wait how does *_,X,Y=x,y,c,*size=*(Im:=self.Im).size,self.constant,self.size actually work
shouldn't the *size=*( raise an error or something
not with the equals in between
only the unpacking (right hand side of the equals) can have multiple starred expressions
in A=B=C
C is evaluated first and a tuple is made _c
_c is then assigned to the variables in A according to the tuple pattern
the same is then done to the variables in B
therefore
Im = self.Im
*_ = x, y, c = *Im.size, self.constant
X, Y = *size = self.size
I just noticed a flaw that would've been an error
nice
*_,X,Y=x,y,c,*size=*(Im:=self.Im).size,self.constant,*self.size makes more sense
either that or
*_,(X,Y)=x,y,c,size=*(Im:=self.Im).size,self.constant,self.size
it doesn't even need to be tuples on the LHS of the equals sign
yeah it can be a set too
you sure?
mhmm
because the set will shuffle the elements into an order determined by their hashes which usually has a different seed each runtime
that's if they even are hashable
unhashable type or voodoo shuffling
!e chained assignment is fun though```py
a = a['a'] = {}
print(a)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
{'a': {...}}
!e ```py
a,b = a[b] = list(range(1,6)), 0
print(a, b)
@pastel sparrow :white_check_mark: Your eval job has completed with return code 0.
[([...], 0), 2, 3, 4, 5] 0
mm
!e ```py
a, *data = a['a'] = {}, 1, 2, 3, *'abc'
print(a,data)
!e
a = []
a.append(a)
print(a)```
@royal whale :white_check_mark: Your eval job has completed with return code 0.
[[...]]
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
{'a': ({...}, 1, 2, 3, 'a', 'b', 'c')} [1, 2, 3, 'a', 'b', 'c']
wait why does it build a list not a tuple?
data is a list but a['a'] is a tuple
!e ```py
a, *data = a[(*data,)] = {}, 1, 2, 3, *'abc'
print(a)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
{(1, 2, 3, 'a', 'b', 'c'): ({...}, 1, 2, 3, 'a', 'b', 'c')}
when is it preferable, in a class Foo, to use a @classmethod over Foo.method? as i understand it, only use classmethod when you need to actually access the class itself. is there more?
classmethod merely passes the class as an argument.
class Foo:
@classmethod
def f(cls):print(cls.__name__)
Foo.f()
is the same as
def f(cls):print(cls.__name__)
class Foo:pass
f(Foo)
within Foo.method you can access the class like
class Foo:
def m(self):print(self.__class__.__name__)
Foo.m()
Personally I use class methods as a sort of asynchronous โconstructorโ suits me pretty well
!e i love that
class X(int, metaclass=print):
a = 1
Sorry, an unexpected error occurred. Please let us know!
ClientResponseError: 500, message='Internal Server Error', url=URL('http://snekbox.default.svc.cluster.local/eval')
!e i love that
class X(int, metaclass=print):
a = 1
Sorry, an unexpected error occurred. Please let us know!
ClientResponseError: 500, message='Internal Server Error', url=URL('http://snekbox.default.svc.cluster.local/eval')
!e print(1)
Sorry, an unexpected error occurred. Please let us know!
ClientResponseError: 500, message='Internal Server Error', url=URL('http://snekbox.default.svc.cluster.local/eval')
wtf
I think snekbox is down
dealing with it tm
!e print("1")
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1
wdym
it was down for a while
.
@sick hound :white_check_mark: Your eval job has completed with return code 0.
hello world!
yep
works
lemme make the most complicated hello world i can do
!e
h = "h"
e = "e"
l ="l"
o = "o"
w = "w"
r = "r"
d = "d"
def hello(a):
if(a == "1"):
print(h+e+l+l+o+" ")
def world(b):
if(b == "2")
print(w+o+r+l+d+"!")
hello("1")
world("2")
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 12
002 | if(b == "2")
003 | ^
004 | SyntaxError: expected ':'
frick
!e
!e
h = "h"
e = "e"
l ="l"
o = "o"
w = "w"
r = "r"
d = "d"
def hello(a):
if(a == "1"):
print(h+e+l+l+o+" ")
def world(b):
if(b == "2"):
print(w+o+r+l+d+"!")
hello("1")
world("2")
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | !e
003 | ^
004 | SyntaxError: invalid syntax
!e
h = "h"
e = "e"
l ="l"
o = "o"
w = "w"
r = "r"
d = "d"
def hello(a):
if(a == "1"):
print(h+e+l+l+o+" ")
def world(b):
if(b == "2"):
print(w+o+r+l+d+"!")
hello("1")
world("2")
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | hello
002 | world!
YES
i dont think thats long enough tho
!e
h = "h"
e = "e"
l ="l"
o = "o"
w = "w"
r = "r"
d = "d"
def hello(a):
if(a == "1"):
word1 = h+e+l+l+o+" "
return word1
def world(b):
if(b == "2"):
word = w+o+r+l+d+"!"
return word
print(hello("1") + world("2"))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
hello world!
can someone make this longer, but dont make any code that is useless in it?
How about this?
import sys
d, e, h, l, o, r, w, EXCLAMATION_MARK, CURSOR_RIGHT = "d", "e", "h", "l", "o", "r", "w", chr(33), "\033[C"
def hello(a):
if a == 1:
word1 = h + e + l + l + o
return word1
def world(b):
if b == 2:
word2 = w + o + r + l + d
return word2
print(hello(1), world(2), sep = CURSOR_RIGHT, end = EXCLAMATION_MARK, file = sys.stdout)
ye, looks nice
I searched around for regex abuse in my projects and found this
answers = ["{}.".format(pt[re.subn("([a-z])'[a-z]+", "\\1", re.subn("(?<=[^a-zA-Z])'((?:[^'.]+|(?<=[a-z])'[a-z]*)+)(\\.?)'", "\\1", pt)[0])[0].strip().lower().find(re.subn("([a-z])'[a-z]+", "\\1", re.subn("(?<=[^a-zA-Z])'((?:[^'.]+|(?<=[a-z])'[a-z]*)+)(\\.?)'", "\\1", ans_marker)[0])[0].strip().lower()):]) for descrip in descrips for pt in descrip.encode().split(b"\xc2\xa0")[0].decode().split(". ") if "\u00b7" not in pt and ".." not in pt and re.subn("([a-z])'[a-z]+", "\\1", re.subn("(?<=[^a-zA-Z])'((?:[^'.]+|(?<=[a-z])'[a-z]*)+)(\\.?)'", "\\1", ans_marker)[0])[0].strip().lower() in re.subn("([a-z])'[a-z]+", "\\1", re.subn("(?<=[^a-zA-Z])'((?:[^'.]+|(?<=[a-z])'[a-z]*)+)(\\.?)'", "\\1", pt)[0])[0].strip().lower()]```
the write-once read-never (hopefully) variety
i believe it was intended to extract something useful from a google search results page
!e
h = "habc"
e = "eabc"
l ="labc"
o = "oabc"
w = "wabc"
r = "rabc"
d = "dabc"
def abcdeleter(string):
new = ""
for letter in string:
if(not string in "abc"):
new = new + letter
return new
h = abcremover(h)
e = abcremover(e)
l = abcremover(l)
o = abcremover(o)
w = abcremover(w)
r = abcremover(r)
d = abcremover(d)
def hello(a):
if(a == "1"):
word1 = h+e+l+l+o+" "
return word1
def world(b):
if(b == "2"):
word = w+o+r+l+d+"!"
return word
print(hello("1") + world("2"))
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 14, in <module>
003 | NameError: name 'abcremover' is not defined
F
!e
h = "habc"
e = "eabc"
l ="labc"
o = "oabc"
w = "wabc"
r = "rabc"
d = "dabc"
def abcdeleter(string):
new = ""
for letter in string:
if(not string in "abc"):
new = new + letter
return new
h = abcdeleter(h)
e = abcdeleter(e)
l = abcdeleter(l)
o = abcdeleter(o)
w = abcdeleter(w)
r = abcdeleter(r)
d = abcdeleter(d)
def hello(a):
if(a == "1"):
word1 = h+e+l+l+o+" "
return word1
def world(b):
if(b == "2"):
word = w+o+r+l+d+"!"
return word
print(hello("1") + world("2"))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
habceabclabclabcoabc wabcoabcrabclabcdabc!
๐คฏ
good luck
thanks
ill need it
how bout this
!e
h = "habc"
e = "eabc"
l ="labc"
o = "oabc"
w = "wabc"
r = "rabc"
d = "dabc"
def abcdeleter(string):
new = ""
for letter in string:
if(not string in "abc"):
new = new + letter
else:
new =new
return new
h = abcdeleter(h)
e = abcdeleter(e)
l = abcdeleter(l)
o = abcdeleter(o)
w = abcdeleter(w)
r = abcdeleter(r)
d = abcdeleter(d)
def hello(a):
if(a == "1"):
word1 = h+e+l+l+o+" "
return word1
def world(b):
if(b == "2"):
word = w+o+r+l+d+"!"
return word
print(hello("1") + world("2"))
!e
h = "habc"
e = "eabc"
l ="labc"
o = "oabc"
w = "wabc"
r = "rabc"
d = "dabc"
def abcdeleter(string):
new = ""
for letter in string:
if(not string in "abc"):
new = new + letter
else:
new =new
return new
h = abcdeleter(h)
e = abcdeleter(e)
l = abcdeleter(l)
o = abcdeleter(o)
w = abcdeleter(w)
r = abcdeleter(r)
d = abcdeleter(d)
def hello(a):
if(a == "1"):
word1 = h+e+l+l+o+" "
return word1
def world(b):
if(b == "2"):
word = w+o+r+l+d+"!"
return word
print(hello("1") + world("2"))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
habceabclabclabcoabc wabcoabcrabclabcdabc!
!e ```py
def askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas(wkadmsalcsoiacjwaijoizkzaopskdpoaskgfoasdkgopieujioawjfakoflapeldpoaskdwiaeui21u489213902edaoijsfdokajlkxcsafdkjwasirfwaouiw5159128329301391023102192129):
return wkadmsalcsoiacjwaijoizkzaopskdpoaskgfoasdkgopieujioawjfakoflapeldpoaskdwiaeui21u489213902edaoijsfdokajlkxcsafdkjwasirfwaouiw5159128329301391023102192129
print(askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas(askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas(askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas(askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas(askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas(askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas(askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas(askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas("Hello, World!")))))))))
IT DOESNT WORK
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
Hello, World!
print("hello world")
long
thats a nice strategy, but i dont want to fill it with junk letters
code
!eval <code>
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
lemme just do this in my editor
!e print("bruh")
@ocean spoke :white_check_mark: Your eval job has completed with return code 0.
bruh
bruh
braunhead
ok??
ok
!e
print("gn")
@ocean spoke :white_check_mark: Your eval job has completed with return code 0.
gn
@sick hound you want some pain in the ass "hello world"? Try print a single character in ASCII and escape sequences
new = ""
for letter in string:
if(not string in "abc"):
new = new + letter
return new```
Tools should solve for the general case: ๐
```deleter = lambda string, to_delete: ''.join([
letter
for letter in string
if letter not in to_delete])
abcdeleter = lambda string: deleter(string, 'abc')
That's the way you boilerplate your way into enterprise software.
Oh, wait, messed up, that should be ```
deleter = lambda string, to_delete, result='': result if not string else deleter(
string[1:], to_delete, result + (
string[0] if string[0] not in to_delete else '')
)
!e
h = "habc"
e = "eabc"
l ="labc"
o = "oabc"
w = "wabc"
r = "rabc"
d = "dabc"
deleter = lambda string, to_delete, result='': result if not string else deleter(
string[1:], to_delete, result + (
string[0] if string[0] not in to_delete else '')
)
abcdeleter = lambda string: deleter(string, 'abc')
h = abcdeleter(h)
e = abcdeleter(e)
l = abcdeleter(l)
o = abcdeleter(o)
w = abcdeleter(w)
r = abcdeleter(r)
d = abcdeleter(d)
def hello(a):
if(a == "1"):
word1 = h+e+l+l+o+" "
return word1
def world(b):
if(b == "2"):
word = w+o+r+l+d+"!"
return word
print(hello("1") + world("2"))
Hey @pastel sparrow!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
does this count doe
!e py h = "habc" e = "eabc" l ="labc" o = "oabc" w = "wabc" r = "rabc" d = "dabc" def abcdeleter(string): new = "" for letter in string: if not letter in "abc": new = new + letter return new h = abcdeleter(h) e = abcdeleter(e) l = abcdeleter(l) o = abcdeleter(o) w = abcdeleter(w) r = abcdeleter(r) d = abcdeleter(d) def hello(a): if(a == "1"): word1 = h+e+l+l+o+" " return word1 def world(b): if(b == "2"): word = w+o+r+l+d+"!" return word print(hello("1") + world("2"))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
hello world!
if(not string in "abc"):
if not letter in "abc": โ
why not ```py
for l in ("a", "b", "c"):
if not letter.contains(l):
...
what the fuck is that
same thing
also why do a tuple
yes
!e ```py
h = "habc"
e = "eabc"
l ="labc"
o = "oabc"
w = "wabc"
r = "rabc"
d = "dabc"
def abc_deletor(string: str):
for char in ('a', 'b', 'c'):
for letter in string:
if not char.contains(letter):
return letter
h = abc_deletor(h).upper()
e = abc_deletor(e)
l = abc_deletor(l)
o = abc_deletor(o)
w = abc_deletor(w).upper()
r = abc_deletor(r)
d = abc_deletor(d)
print(h+e+l+l+o, w+o+r+l+d+'!')```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello World!
not longer just better
!e
h = "habc"
e = "eabc"
l ="labc"
o = "oabc"
w = "wabc"
r = "rabc"
d = "dabc"
def abcdeleter(i):
for letter in [letter for letter in i]:
for deleted_letter in [chr(code) for code in range(97, 100)]:
if letter not in deleted_letter:
return letter
h = abcdeleter(h)
e = abcdeleter(e)
l = abcdeleter(l)
o = abcdeleter(o)
w = abcdeleter(w)
r = abcdeleter(r)
d = abcdeleter(d)
def hello(a):
if a == "1":
word1 = h + e + l + l + o
return word1
def world(b):
if b == "2" :
word = w + o + r + l + d
return word
print(hello("1").title(), world("2").title(), sep = " ", end = chr(33))
@light thunder :white_check_mark: Your eval job has completed with return code 0.
Hello World!
!e
console.log("Hello, world!");
@distant briar :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'console' is not defined
@distant briar :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'requests'
!e
import urllib.request
urllib.request.urlopen("https://google.com")
@distant briar :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/usr/local/lib/python3.10/urllib/request.py", line 1348, in do_open
003 | h.request(req.get_method(), req.selector, req.data, headers,
004 | File "/usr/local/lib/python3.10/http/client.py", line 1282, in request
005 | self._send_request(method, url, body, headers, encode_chunked)
006 | File "/usr/local/lib/python3.10/http/client.py", line 1328, in _send_request
007 | self.endheaders(body, encode_chunked=encode_chunked)
008 | File "/usr/local/lib/python3.10/http/client.py", line 1277, in endheaders
009 | self._send_output(message_body, encode_chunked=encode_chunked)
010 | File "/usr/local/lib/python3.10/http/client.py", line 1037, in _send_output
011 | self.send(msg)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/iludehadop.txt?noredirect
the eval command doesn't have internet access
i figured
apparently a read-only filesystem, too: #bot-commands message
!e ```py
class N:
def init(self, n): self.n = n
def eq(self, other):
globals().setitem(self.n, other)
return other
if (N("hello") == 10) == 10:
print(hello)```
@polar plover :white_check_mark: Your eval job has completed with return code 0.
10
!e ```py
class N:
def init(self, n): self.n = n
def le(self, other):
globals().setitem(self.n, other)
return other
if (N("hello") <= 10) == 10:
print(hello)```
@polar plover :white_check_mark: Your eval job has completed with return code 0.
10
is there a difference b/w globals().update({"a": 2}) and globals().__setitem__(a, 2)?
not afaik
I could also just have done globals()["a"] = 2
just used __setitem__ out of habit xD
yea globals is a dict, didn't knew before
!e ```py
class N:
def init(self, n): self.n = n
def le(self, other):
globals()[self.n] = other
return other
if (N("hello") <= 10) == 10:
print(hello)```
@polar plover :white_check_mark: Your eval job has completed with return code 0.
10
like who needs a walrus ๐
we can just make our own syntax
I have a terrible idea
well this is certainly the channel for terrible ideas, so at least you're in the right place
well I had an idea, but I cant seem to figure it out, trying to use fishhook to overwrite how globals() works, but when I overwrite the dict dunders it doesn't seem like python actually uses the globals() dict internally
like I can make it work when you do globals()["hello"], but just hello doesn't use a dict dunder from what I can tell
what
globals() is equivalent to doing __import__("sys")._getframe().f_globals
which is a dict right?
so I would expect print(hello) to do some_internal_dict.get("hello") at some point
yeah
but not some_internal_dict.get(), it's some_internal_dict[]
right I tried overwriting __getitem__ as well, but I never saw it being called with "hello"
!e ```py
from fishhook import hook, orig
@hook(dict)
def getitem(self, *args):
print(args)
return "hi"
hello
@quartz wave :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 7, in <module>
003 | NameError: name 'hello' is not defined
doesn't top level __getattribute__ implement that already?
i don't recall what versiom it was added in
to be specific my goal is in the event something is not defined a default value is generated
!e
def __getattr__(name: str):
print(name)
a```
@haughty pagoda :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | NameError: name 'a' is not defined
that was never in anywhere in 3.9+
!e
def __getattr__(name: str):
print(name)
aโ
@haughty pagoda :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | NameError: name 'a' is not defined
stop trying
makes sense
why ping ;-;
sorry
you need to completely reconstruct globals
i had a code snippet but it segfaulted
ok
i made stack overflow
!e ```py
from ctypes import py_object
class alskxsoafojsdfaf(dict):
def getitem(self, name):
print(name)
return super().getitem(name)
py_object.from_address(id(globals())+tuple.itemsize).value = alskxsoafojsdfaf
hello
@quartz wave :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
see?
im getting _Py_CheckRecursiveCall
seems like it's because i wanna use super
also print
!e ```py
from ctypes import py_object
class alskxsoafojsdfaf(dict):
builtin = builtins
def getitem(self, name, builtins=builtin):
builtins.print(name)
return builtins.dict.getitem(self, name)
py_object.from_address(id(globals())+tuple.itemsize).value = alskxsoafojsdfaf
py_object.from_address(id(globals())+tuple.itemsize).value = dict
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | dict
002 | py_object
003 | id
004 | globals
005 | tuple
that workaround works
!e ```py
from ctypes import*
class donct(dict):
d={}
def getitem(self, item):
from builtins import dict, import
try:return dict.getitem(self,item)
except:pass
try:return dict.getitem(import('builtins'),item)
except:pass
if item in self.d:return self.ditem
else:return item
def hack_globals(data):
py_object.from_address(id(globals())+8).value = donct
globals().d|=data
hack_globals({"Hello":lambda:globals().setitem('hi','Hello, World'),"World":lambda:print(hi)})
Hello, World
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
!e ```py
from ctypes import*
class donct(dict):
d={}
def getitem(self, item):
from builtins import dict, import
try:return dict.getitem(self,item)
except:pass
try:return dict.getitem(import('builtins'),item)
except:pass
if item in self.d:return self.ditem
else:return item
def hack_globals(data):
py_object.from_address(id(globals())+8).value = donct
globals().d|=data
hack_globals({"Hello":lambda:globals().setitem('hi','Hello, World'),"World":lambda:print(hi)})
Hello, World
py_object.from_address(id(globals())+8).value = dict
@quartz wave :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
!e ```py
from ctypes import*
class donct(dict):
d={}
def getitem(self, item):
from builtins import dict, import
try:return dict.getitem(self,item)
except:pass
try:return dict.getitem(import('builtins'),item)
except:pass
if item in self.d:return self.ditem
else:return item
def hack_globals(data):
d = globals()
py_object.from_address(id(d)+8).value = donct
d.d.update(data)
def asodasodk():
from builtins import globals
return globals
def asodasoda():
from builtins import print
return print
hack_globals({"Hello":lambda:globals().setitem('hi','Hello, World'),"World":lambda:print(hi),"globals":asodasodk,"print":asodasoda})
Hello, World
@quartz wave :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
ok
!e ```py
from ctypes import py_object as p;
flogbals = p.from_address(id(globals())+8)
class globglogabgolab(dict):
d={};
def getitem(self, name):
import builtins as builtins;
try:return builtins.dict.getitem(self,name);
except builtins.KeyError:...;
try:return __builtins.getattribute(name);
except:...;
if item in self.d:return self.ditem;
else:return item;
def setitem(self, name, value):
import builtins as builtins
if builtins.type(value)==builtins.type(lambda:0):
self.d.update({name:value})
builtins.dict.setitem(self, name, value)
flogbals.value = globglogabgolab
def Hello():
global hi
hi = "Hello, World"
World = lambda:print(hi)
Hello, World
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
I think it might be a slot issue or something
alright I'll have to add a syntax
!e ```py
from ctypes import py_object as p;
flogbals = p.from_address(id(globals())+8)
class globglogabgolab(dict):
def getitem(self, name):
import builtins as builtins;
try:return builtins.dict.getitem(self,name);
except builtins.KeyError:...;
try:return __builtins.getattribute(name);
except:...;
if item in annotations:return annotationsitem;
else:raise NameError(name)
Hello:lambda:globals().update({'hi':'Hello World'})
World:lambda:print(globals()['hi'])
flogbals.value = globglogabgolab
Hello, World
flogbals.value = dict
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
how?
wait is this something to do with updates?
!e ```py
from collections import defaultdict as d;
from ctypes import py_object as p;
class flogbals(dict):
def getitem(self, name):
import builtins as builtins;
try:return builtins.dict.getitem(self,name);
except builtins.KeyError:...;
try:return builtins.getattr(builtins,name);
except builtins.AttributeError:...;
if name=='Hello':self['hi']="Hello, World";return;
if name=='World':return print(self['hi']);
raise builtins.NameError(name+' does not exist');
p.from_address(id(globals())+8).value=flogbals;
Hello, World
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
Hello, World
why does that work and the others don't?
!e ```py
from ctypes import py_object as p
flogbals=p.from_address(id(globals())+8)
class donct(dict):
d={}
def getitem(self, item):
if item in self.d:return self.ditem
from builtins import dict, import, getattr
try:return dict.getitem(self,item)
except:pass
try:return getattr(import('builtins'),item)
except:pass
return item
def setitem(self, item, value):
from builtins import type, dict
if type(value)==type(lambda:0):
self.d.update({item:value})
dict.setitem(self,item,value)
def reset(flogbals=flogbals):
flogbals.value = {}.class
flogbals.value=donct
def Hello():
global hi
hi = "Hello, World"
World = lambda:print(hi)
Hello, World
reset()
@quartz wave :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
!e clean exit version```py
from collections import defaultdict as d;
from ctypes import py_object as p;
globglogabgolab = p.from_address(id(globals())+8);
class flogbals(globglogabgolab.value):
def getitem(self, name):
import builtins as builtins;
try:return builtins.dict.getitem(self,name);
except builtins.KeyError:...;
try:return builtins.getattr(builtins,name);
except builtins.AttributeError:...;
if name=='Hello':self['hi']="Hello, World";return;
if name=='World':return print(self['hi']);
raise builtins.NameError(name+' does not exist');
globglogabgolab.value=flogbals;
Hello, World
globglogabgolab.value=dict;
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello, World
lmao all this preprocessor and postprocessor script to make one line a cat
no
it hasnt
>>> dict.__iadd__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'dict' has no attribute '__iadd__'. Did you mean: '__hash__'?
wait you're right
!e ```py
from collections import defaultdict as d;
from ctypes import py_object as p;
globglogabgolab = p.from_address(id(globals())+8);
class flogbals(globglogabgolab.value):
def getitem(self, name):
import builtins as builtins;
try:return builtins.dict.getitem(self,name);
except builtins.KeyError:...;
try:return builtins.getattr(builtins,name);
except builtins.AttributeError:...;
try:return self['annotations']name
except:raise builtins.NameError(name+' does not exist');
globglogabgolab.value=flogbals;
i = 2 + 2
increment:lambda:globals().setitem('i',globals()['i']+1)
output:lambda:print(globals()['i'])
output, increment, output
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
4
surely globals has __setitem__
my machine tells me it's a memory access error
whilst the actual crash was rather unspectacular
i = 2 + 2 works thats setitem
output works that has getitem
increment doesn't have anything new
I think I've finally encountered unexpected behaviour in python.
works on my machine ```py
output,increment,output
4
5
how are you segfaulting??
oh
@floral meteor it doesn't segfault somehow in python 3.11
im on win10, it prints 4 and crashes
yeah because you guys have python 3.10 or below
@floral meteor i think i found out where the error comes from in python <=3.10
somehow any attribute access of globals() fails and has an error
oh ๐ค
!e ```py
from collections import defaultdict as d;
from ctypes import py_object as p;
globglogabgolab = p.from_address(id(globals())+8);
class flogbals(globglogabgolab.value):
def getitem(self, name):
import builtins as builtins;
try:return builtins.dict.getitem(self,name);
except builtins.KeyError:...;
try:return builtins.getattr(builtins,name);
except builtins.AttributeError:...;
try:return self['annotations']name
except:raise builtins.NameError(name+' does not exist');
def getattribute(self,name):
import builtins as builtins;
builtins.print("oh")
return builtins.object.getattribute(self,name)
globglogabgolab.value=flogbals;
i = 2 + 2
increment:lambda:globals().setitem('i',globals()['i']+1)
output:lambda:print(globals()['i'])
output, increment, output
@quartz wave :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | 4
002 | oh
WHAT IN THE WORLD 
https://esolangs.org/wiki/TMMLPTEALPAITAFNFAL can have that restriction
>>> compile(f"{'a'*999999999999999999999999}=1", "", "eval")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: cannot fit 'int' into an index-sized integer
wait what
>>> compile(f"{'a'*9999999999999999}=1", "", "eval")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError
okay
๐ damn
Make sure to define __slots__=()
!e ```py
h = "habc"
e = "eabc"
l ="labc"
o = "oabc"
w = "wabc"
r = "rabc"
d = "dabc"
def a_deletor(string: str):
for char in ('a'):
for letter in string:
if not char.contains(letter):
return letter
def b_deletor(string: str):
for char in ('b'):
for letter in string:
if not char.contains(letter):
return letter
def c_deletor(string: str):
for char in ('c'):
for letter in string:
if not char.contains(letter):
return letter
h = a_deletor(h)
e = a_deletor(e)
l = a_deletor(l)
o = a_deletor(o)
w = a_deletor(w)
r = a_deletor(r)
d = a_deletor(d)
h = b_deletor(h)
e = b_deletor(e)
l = b_deletor(l)
o = b_deletor(o)
w = b_deletor(w)
r = b_deletor(r)
d = b_deletor(d)
h = c_deletor(h).upper
e = c_deletor(e)
l = c_deletor(l)
o = c_deletor(o)
w = c_deletor(w).upper
r = c_deletor(r)
d = c_deletor(d)
print(h+e+l+l+o, w+o+r+l+d+'!')```
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 45, in <module>
003 | TypeError: unsupported operand type(s) for +: 'builtin_function_or_method' and 'str'
@sick hound its spelled "deleter"
ik
o
k
cuz you know
y
k
h
!e ```py
h = "habc"
e = "eabc"
l ="labc"
o = "oabc"
w = "wabc"
r = "rabc"
d = "dabc"
def a_deletor(string: str):
for char in ('a'):
for letter in string:
if not char.contains(letter):
return letter
def b_deletor(string: str):
for char in ('b'):
for letter in string:
if not char.contains(letter):
return letter
def c_deletor(string: str):
for char in ('c'):
for letter in string:
if not char.contains(letter):
return letter
h = a_deletor(h)
e = a_deletor(e)
l = a_deletor(l)
o = a_deletor(o)
w = a_deletor(w)
r = a_deletor(r)
d = a_deletor(d)
h = b_deletor(h)
e = b_deletor(e)
l = b_deletor(l)
o = b_deletor(o)
w = b_deletor(w)
r = b_deletor(r)
d = b_deletor(d)
h = c_deletor(h).upper()
e = c_deletor(e)
l = c_deletor(l)
o = c_deletor(o)
w = c_deletor(w).upper()
r = c_deletor(r)
d = c_deletor(d)
print(h+e+l+l+o, w+o+r+l+d+'!')```
@split salmon :white_check_mark: Your eval job has completed with return code 0.
Hello World!
was that hard to fix?
!e ```py
def askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas(wkadmsalcsoiacjwaijoizkzaopskdpoaskgfoasdkgopieujioawjfakoflapeldpoaskdwiaeui21u489213902edaoijsfdokajlkxcsafdkjwasirfwaouiw5159128329301391023102192129):
return wkadmsalcsoiacjwaijoizkzaopskdpoaskgfoasdkgopieujioawjfakoflapeldpoaskdwiaeui21u489213902edaoijsfdokajlkxcsafdkjwasirfwaouiw5159128329301391023102192129
print(askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas(askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas(askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas(askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas(askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas(askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas(askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas(askfjasijasiofkaspokxoaiozjaoizjaiojfdasiofkgaskvoasijciaoshcasjoikzoiajidasiuofjsaiofhwuharoiuqwquiurwqiurwqiru3289457819247812u489dasiwofvokasoxasjhisahuifhas("Hello, World!")))))))))
@viscid steeple :white_check_mark: Your eval job has completed with return code 0.
Hello, World!
@viscid steeple :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'quit' is not defined
!e
exit(0)
@royal whale :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'exit' is not defined
Ah
!e ```python
import secret; import random;
n = 9293929392;
res = ''.join(secrets.choice(string.ascii_uppercase + string.digits)
for i in range(N))
print("The generated random string : " + str(res))
@jolly plover :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'secret'
ok
!e ```py
from collections import defaultdict as d;
from ctypes import py_object as p;
globglogabgolab = p.from_address(id(globals())+8);
class flogbals(globglogabgolab.value):
slots=()
def getitem(self, name):
import builtins as builtins;
try:return builtins.dict.getitem(self,name);
except builtins.KeyError:...;
try:return builtins.getattr(builtins,name);
except builtins.AttributeError:...;
try:return self['annotations']name
except:raise builtins.NameError(name+' does not exist');
globglogabgolab.value=flogbals;
i = 2 + 2
increment:lambda:globals().setitem('i',globals()['i']+1)
output:lambda:print(globals()['i'])
output, increment, output
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 4
002 | 5
i don't get why that works
That fixes the segfault at the end (because now your dict subclass has the same memory footprint as the original dict class instance)
Normal class instances have space for an instance dictionary and an attribute cache. Making slots optimizes that into specific memory slots for attributes listed
So empty slots means no instance dictionary, attribute cache, or specific memory slots
how does attribute accessing work for 3.11 without __slots__=() though
!e py print(dict.__basicsize__) class a(dict):pass print(a.__basicsize__) class b(dict):__slots__=() print(b.__basicsize__)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 48
002 | 64
003 | 48
The crash at the end happens when the globals dictionary is cleared and freed
Without slots defined as empty, it tries to free 64 bytes instead of 48 (and it tried to clear a nonexistent attribute cache)
It will crash eventually (if something happens to be allocated after globals that is important because it'll be overwritten with an attribute cache)
ok
!e
string = "Chicken 30, Sheep 40, Cow 20, Dog 1, Horse 4"
def separate(sentence):
string_list = "".join([i for i in sentence if i not in[chr(code) for code in range(33, 48)]]).split()
value_list = []
for number in [chr(code) for code in range(48, 58)]:
for index in range(len(string_list)):
if number in string_list[index]:
value_list.append(string_list[index])
string_list[index] = "--"
key_list = [element.strip() for element in filter(None, " ".join(string_list).split("--"))]
return {key_list[i]: value_list[i] for i in range(len(key_list))}
print(separate(string))
@light thunder :white_check_mark: Your eval job has completed with return code 0.
{'Chicken': '30', 'Sheep': '40', 'Cow': '20', 'Dog': '1', 'Horse': '4'}
ok?
!e or just ```py
string = "Chicken 30, Sheep 40, Cow 20, Dog 1, Horse 4"
def separate(sentence):
return {k:v for k,v in map(lambda s:s.split(), string.split(", "))}
print(separate(string))
@pastel sparrow :white_check_mark: Your eval job has completed with return code 0.
{'Chicken': '30', 'Sheep': '40', 'Cow': '20', 'Dog': '1', 'Horse': '4'}
!e
string = "Chicken! 30, Sheep? 40, Cow 20, Dog! 1, Horse 4"
def separate(sentence):
return {k:v for k,v in map(lambda s:s.split(), string.split(", "))}
print(separate(string))โ
@light thunder :white_check_mark: Your eval job has completed with return code 0.
{'Chicken!': '30', 'Sheep?': '40', 'Cow': '20', 'Dog!': '1', 'Horse': '4'}
my globglogabgolab hello world got fixed yay
!e
code
!e
import re
string = "Chicken! 30, Sheep? 40, Cow 20, Dog! 1, Horse 4"
print(dict(map(str.split, re.findall(r'([\w!?]+ \d+),', string))))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
{'Chicken!': '30', 'Sheep?': '40', 'Cow': '20', 'Dog!': '1'}
glob glob glob
!e
string = "Chicken! 30, Sheep? 40, Cow 20, Dog! 1, Horse 4"
print(dict(map(str.split, string.split(", "))))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
{'Chicken!': '30', 'Sheep?': '40', 'Cow': '20', 'Dog!': '1', 'Horse': '4'}
:)
!e ```py
numbers = [1,2,3]
def hexirate(numbers):
return [hex(number)for number in numbers]
a = hexirate(numbers)
print(a)
print([int(b,base=16)for b in a])```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | ['0x1', '0x2', '0x3']
002 | [1, 2, 3]

N = 49 I think