#esoteric-python
1 messages · Page 138 of 1
oh I see
also i wanna avoid some recursion if possible
else you cant get more than 1000 iterations without raising the recursion limit
well yeah that's why I didn't use recursion :)
recursion could probably make it shorter but be a pain in the ass
wait can't you just do open('o.ppm','w').write(f'P2\n{h} {w}\n{m}\n'+'\n'.join(str(r((x%w)/w*2.67-2.1+(x//h)/h*2.5j-1.25j))for x in range(w*h)]) for the last line
yes, indeed i can
i can also move the lambda function to that line, for -2 chars, but im not too worried about that
found out i can replace: z.real**2+z.imag**2<=4 with abs(z)<=2
:D
because apparently, taking the absolute value of a complex number, is like doing pythagoras
Also gave a massive speedup
?
just python weirdness and "lambdascores" i guess
w,h,m=256,256,64
open('o.ppm','w').write(f'P2\n{w} {h}\n{m}\n'+' '.join(str(len((z:=0j)or[(z:=z*z+x%w/w*2.67-2.1+x//w/h*2.5j-1.25j)for _ in[0]*m if abs(z)<=2]))for x in range(w*h)))
got it down to 181
you could do: open(str(w:=256)+'.ppm', 'w') and just use a w variable, and replace m with 64
or m with w ** .75
open(str(w:=256) + '.ppm','w').write(f'P2\n{w} {w}\n64\n'+' '.join(str(len((z:=0j)or[(z:=z*z+x%w/w*2.67-2.1+x//w/w*2.5j-1.25j)for _ in[0]*64 if abs(z)<=2]))for x in range(w*w)))
is 174 chars
i kinda want to have both image dimensions available
i was thinking you could just record powers of 2, but i dont think that serves any use
you could make w both the width and height, using the decimal part as the height
width and height can be any number
w//100, w//1000 etc
but they dont have to be the same
hmmm
depends what the game is -- lots of ideas, not many which actually shrink char count
i guess
!e
X=(T:=type)('',(T,),{'__init__':lambda x,*_:x.__setattr__(x,'__class__',x)},)('X',(T,),{},)
assert X is X.__class__ is type(X) and X.__name__ == 'X'
@fleet bridge :warning: Your eval job has completed with return code 0.
[No output]
!e
class X:
pass
class Y:
__class__ = X
print(f'{Y().__class__ = }')
print(f'{type(Y()) = }')
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | Y().__class__ = <class '__main__.X'>
002 | type(Y()) = <class '__main__.Y'>
weird
!e
X=(T:=type)('',(T,),{'__init__':lambda x,*_:x.__setattr__(x,'__class__',x)},)('X',(T,),{'__new__':lambda x,*_:x,'__init__':lambda *_:None},)
assert X() is X is X.__class__ is type(X) and X.__name__ == 'X'
print('OK')
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
OK
w,h,m=1024,1024,64
open('o.ppm','w').write(f'P3\n{w} {h}\n255\n'+'\n'.join(['122 108',f'{len((z:=0j)or[(z:=z*z+x%w/w*2.67-2.1+x//w/h*2.5j-1.25j)for _ in[0]*m if abs(z)<=2])*62%255} 173'][(abs(z)>2)]+' 227'for x in range(w*h))+'\n')
with colors ¯_(ツ)_/¯
@bright eagle
it isnt circle 🧐
ranges from top to bottom arent exactly the same
the mandelbrot set ranges from -2 .. 0.47 , -1.12i .. 1.12i
and im plotting: -2.1 .. 0.57 , -1.25i .. 1.25i
@bright eagle final one:
julia sets this time:
s,m=2048,128;c=.285+.01j
open('o.ppm','w').write(f'P2\n{s} {s}\n{m}\n{" ".join([z:=x%s/s*(R:=(4*abs(c)+1)**.5+1)-R/2+x//s/s*R*1j-R/2*1j,str(len([(z:=z*z+c)for _ in[0]*m if abs(z)<=R]))][1]for x in range(s*s))}')
Neato!
!e
t,\
s,r,C,E, =tuple,\
set, range, "*"," ";f=r\
(31);p=( t(s(r(4,12))|s(r(18,
26))),t(s(r(3,14))|s(r(17,28))),
t(s(r(1,15))|s(r(16,30))),f,f,f,
r(1,30),r(3,28),r(5,26),r(7,24),
r(9,22),r(11,20),r(13,18),(15
,));print(*[(e:="").join(
[(C if j in p[i] else
E)for j in f] ) +
"\n" for i in
r(14) ] ,
sep=e
)
@patent heron :white_check_mark: Your eval job has completed with return code 0.
001 | ******** ********
002 | *********** ***********
003 | ************** **************
004 | *******************************
005 | *******************************
006 | *******************************
007 | *****************************
008 | *************************
009 | *********************
010 | *****************
011 | *************
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/nufipuhalu.txt?noredirect
:)
That took a lot longer than I thought
and I do kinda have to cheat at the start but it is python after all
worth <3

Converting to "int" failed for parameter "pep_number".

still slightly off center
!e ```py
t,
s,r,C,E, =tuple,
set, range, ""," ";f=r
(31);p=( t(s(r(5,13))|s(r(18,
26))),t(s(r(3,14))|s(r(17,28))),
t(s(r(1,15))|s(r(16,30))),f,f,f,
r(1,30),r(3,28),r(5,26),r(7,24),
r(9,22),r(11,20),r(13,18),(15
,));print([(e:="").join(
[(C if j in p[i] else
E)for j in f] ) +
"\n" for i in
r(14) ] ,
sep=e
)
@patent heron :white_check_mark: Your eval job has completed with return code 0.
001 | ******** ********
002 | *********** ***********
003 | ************** **************
004 | *******************************
005 | *******************************
006 | *******************************
007 | *****************************
008 | *************************
009 | *********************
010 | *****************
011 | *************
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/uqevunulom.txt?noredirect
Now it's symmetrical
:O
kinda want the top line to be a bit smaller but that is like impossible to reflect in the code
It's fine
:( i still think its beautiful
that's so much better than when I tried it lol ```py
heart =
(lambda n:(lambda o=int(.5*n//1):
[([( lambda m=(x/n *3),l=(
y / n *3): print ([" ","#"
][( m2 +l2
-1) 3
-m2 *l
**3 <0
],end =""
)) ()
for x in
range (-o,
o)] ,print
()) for
y in
range (o,
-o, -1
)] )(
))
on my small discord window hehe 😁
but hey at least my heart() function takes a target size
I could probably make it work if I un-golf it
that said I can't believe it's almost 3 years since I made that code
is that like that one donut shaped code
!e
print("#####")
print("#####")
print("#####")
print("#####")
I can make rectangle shaped code that prints rectangle B)
@thorny tapir :white_check_mark: Your eval job has completed with return code 0.
001 | #####
002 | #####
003 | #####
004 | #####
Reminds me of the "calculate Pi by changing the size of a circle in the code" IOCCC thing: http://www.cise.ufl.edu/~manuel/obfuscate/pi.c
Thats cool
Hi, when I use this code (I'm using PyQt5)
widget.resize(496, 600)
self.line.move(-10, 540)
The line isn't showing when it is in a part of window which was resized, anyone know how to fix that?
@patent heron
class v:
def __init__(s,x=0,y=0,z=0): s.x,s.y,s.z=x,y,z
v.__str__=lambda s:f'{s.x},{s.y},{s.z}' #print values
v.__add__=lambda s,r:v(s.x+r.x,s.y+r.y,s.z+r.z) #addition
v.__mul__=lambda s,r:v(s.x*r,s.y*r,s.z*r) #scaling
v.__mod__=lambda s,r:s.x*r.x+s.y*r.y+s.z*r.z #dot-product
v.__xor__=lambda s,r:v(s.y*r.z-s.z*r.y,s.z*r.x-s.x*r.z,s.x*r.y-s.y*r.x) #cross-product
v.__invert__=lambda s:s*(1/(s%s)**0.5) #normalize
🤔
not nice xD its so ugly
I mean, yea
perhaps a small tidy,
!e ```py
class v:
init = lambda s, kw: s.dict.update(kw)
getitem = lambda s, i: s.dict[i]
iter = lambda s: iter(s.dict.items())
str = repr = lambda s: str(dict(s))
add=lambda s,r: v({k:v + r[k] for k,v in s})
mul=lambda s,r: v({k:v * r for k,v in s})
matmul=lambda s,r: sum(v * r[k] for k,v in s)
invert=lambda s: s * ((s@s)-0.5)
v(x=10, y=20) @ v(x=5, y=16)
hey, not sure if i used it wrong but doing * causes this TypeError: unsupported operand type(s) for *: 'int' and 'v'
Fixed, you forgot a [k]
whereabouts?
!e```py
class v:
init = lambda s, *ps, kw: s.dict.update(kw or zip('xyz', ps))
getitem = lambda s, i: s.dict[i]
iter = lambda s: iter(s.dict.items())
str = repr = lambda s: str(dict(s))
add=lambda s,r: v({k:v + r[k] for k,v in s})
_cmul = lambda s,r: v({k: v * r[k] for k,v in s})
_smul = lambda s,r: v({k: v * r for k,v in s})
mul = lambda s,r: [v._smul, v._cmul][isinstance(r, v)](s, r)
matmul=lambda s,r: sum(v * r[k] for k,v in s)
invert=lambda s: s * ((s@s)**(-1/len(s)))
len=lambda s: len(s.dict.values())
print( v(2, 2) + v(3, 4))
print( v(2, 2) * 3 )
print( v(2, 2) * v(3,4) )
print( ~v(x=2, y=2) )
print( v(x=10, y=10) @ ~v(x=10, y=10) )
:0
could go the shader language route and make a heckload of overloads and definitions for vec2, vec3, ..., vecn
v above is already overloaded
yeah
i cant even print a heart with normal python ;-;
I could probably print a heart in python, but Java style of code writing
!e ```py
void=None;
class System:
out=type("stdout",(),{'println':print})();
class Main:
def main(argv) -> void: {
System.out.println(" *** *** "),
System.out.println(" ***** ***** "),
System.out.println("**************"),
System.out.println(" ************** "),
System.out.println(" ********** "),
System.out.println(" ****** "),
System.out.println(" ** ")
}
name=='main'==Main.main(import('sys').argv)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | *** ***
002 | ***** *****
003 | ****************
004 | **************
005 | **********
006 | ******
007 | **
!e Now that yall have been tortured here's the pythonic way
print(""" *** ***
***** *****
****************
**************
**********
******
**""")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | *** ***
002 | ***** *****
003 | ****************
004 | **************
005 | **********
006 | ******
007 | **
how tf does it not give syntax error for System.out.println
Because I snuck a comma in at the end
wait a sec
I realized that you could like split the heart in half and like oh okay
!e
( "hi",i:=
__file__,C:=chr,
s:=open(i,"rt").
read(),sc:=s.count(C
(10)),sn:=sc+s.count
(C(32)),a:=len(s)-sn
,print("π","is",":",
.5*a/((.5*sc)**2
)),"#eso- teric"
,"pthn")
@restive void :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | NameError: name '__file__' is not defined. Did you mean: '__name__'?
The exact same thing happens in tkinter, I think it's happening at a deeper level than you can control, the workaround I use is to destroy the circle and re-create it at the new coords.
print(8)
I have a structure for an object oriented code for a grid game (e.g. minesweeper, sudoku, 2048) run in python
class Cell: # contains a value
...
class Engine: # contains a matrix
...
class Interface: # contains an event loop
...
I try to black-box Engine with Interface, so as multiple options are available, i.e. gui or cli or AI solution
but I'm not always successful at implementing black box
I suspect you intended to send this question in #software-architecture, which is about designing beautiful software, instead of here ( #esoteric-python ), which is where beautiful software goes to die
'where beautiful software goes to die'

things can be masterpieces without being beautiful 🤷
is a raytracer in 1200 chars impressive?
doesn't sound impressive
they're a frequent of this channel
o fancy role
hi
@sick hound let's keep this channel on topic please, it's not the please to be dumping yt videos
And given this is an English speaking discord server this probably isn't the right server
excuse me I do not understand English well and I understood that esoteric I am only looking to expand my community on twiter
We don't allow advertisement here. I recommend you read our #rules before continuing
Although if you can't speak English, then I'm afraid this isn't the server for you
Well my dudes!
There's obviously a lot of infrastructure I'm not showing here, but
I think I've managed to implement private attributes in Python XD
def getCallingPrototype(self) -> Prototype:
"""retrieve the class which owns the scope, if the scope is indeed owned at all"""
callingFrame = inspect.currentframe()
callingCode = getattr(callingFrame, 'f_code')
while callingCode.co_flags & inspect.CO_NESTED:
# climb the stack up to the first not-nested frame
callingFrame = callingFrame.f_back
callingCode = getattr(callingFrame, 'f_code')
# get every object which refers to the code object in question, then
# filter out any objects which are not functions
callingFunctions = gc.get_referrers(callingCode)
callingFunctions = filter(inspect.isfunction, callingFunctions)
callingFunctions = tuple(callingFunctions)
if len(callingFunctions) > 1: # the code object has been used to manufacture more
# then one function — throw an error
#
# NOTE: in theory, one could check ALL of these
# for privacy authorization
error = f"cannot access {self.privacy} member '{self.name}' of positronic "
error += f"object with type '{instance.classname}' from within "
error += f"recycled code object"
raise AssertionError(error)
if len(callingFunctions) < 1: # the code object is not attached to any function
# (likely compiled manually) as is therefore
# not authorized
error = f"cannot access {self.privacy} member '{self.name}' of positronic "
error += f"object with type '{instance.classname}' from within "
error += f"orphaned code object"
raise AssertionError(error)
# from the computed function, get its decorator (set as one of its attributes) and
# from that, get the class the decorator is embedded on
callingFunction = operator.getitem(callingFunctions, 0)
callingDecorator = getattr(callingFunction, 'decorator', None)
callingPrototype = getattr(callingDecorator, 'prototype', None)
# return the computed class
return callingPrototype
Here is a snippet, the algorithm for finding which class owns a scope
"positronic"
Your variables are more than one word each
My variables are usually single letter
Its still very raw, I'll admit. I just wanted to get you guys' opinion on the approach TBH
Its the first half-sane means of determining the owner of a scope I've seen
But I'm sure there are edge cases I'm not thinking of. One improvement I've made already is that I've attached the code object directly to the decorator. For context, this is part of a group of classes that all work together — in this case, private variables are only eligible for access within code blocks decorated by a custom decorator. I realized I can just attach the code block as an attribute directly to the decorator and as such, I don't need to filter referents twice. I can directly detect any of my decorators which reference the code block in question
And that seems sane enough. Look at the current frame's code block, find any custom decorators which reference it, and whatever class that decorator is attached to (if any) is the owner of the code block
How does this respond to object.__getattribute__(x, "blah")?
!e
import numpy as np
data = [i for i in np.arange(1,7)]
hori = vert = np.array(data)
arr = np.array([hori, vert])
def sample(n):
samp = []
for i in range(1,n+1):
for j in range(1,n+1):
num = (i,j)
samp.append(num)
return samp
sample = sample(6)
samp = np.array(sample)
print(samp)
@fading lion :white_check_mark: Your eval job has completed with return code 0.
001 | [[1 1]
002 | [1 2]
003 | [1 3]
004 | [1 4]
005 | [1 5]
006 | [1 6]
007 | [2 1]
008 | [2 2]
009 | [2 3]
010 | [2 4]
011 | [2 5]
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/haqegazora.txt?noredirect
!p
import numpy as np
data = [i for i in np.arange(1,7)]
hori = vert = np.array(data)
arr = np.array([hori, vert])
def sample(n):
samp = []
for i in range(1,n+1):
for j in range(1,n+1):
num = (i,j)
samp.append(num)
return samp
sample = sample(6)
samp = np.array(sample)
print(samp)
Converting to "int" failed for parameter "pep_number".
!e
from pprint import pprint
def is_constructible(cls: type) -> bool:
try:
cls()
except TypeError as exc:
s = exc.args[0]
if not isinstance(s, str):
return True
if 'cannot create ' not in s:
return True
if ' instances' not in s:
return True
return False
except:
return True
else:
return True
x = [c for c in object.__subclasses__()[:100] if not is_constructible(c)]
x = sorted(x, key=lambda c: c.__name__[::-1])
pprint(x)
list of classes which raises TypeError: cannot create '<classname>' instances when called
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | [<class 'Token.MISSING'>,
002 | <class 'async_generator_asend'>,
003 | <class 'builtin_function_or_method'>,
004 | <class 'hamt_collision_node'>,
005 | <class 'hamt_bitmap_node'>,
006 | <class 'hamt_array_node'>,
007 | <class 'anext_awaitable'>,
008 | <class 'PyCapsule'>,
009 | <class 'frame'>,
010 | <class 'coroutine'>,
011 | <class 'types.UnionType'>,
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/elageloqig.txt?noredirect
It would be fun to make a net-oriented programming framework in python,
it'd be like neurons in a brain
possibly even turing complete
As long as you specified input nodes, output nodes, and a way to store memory
but you might be able to make memory with a logic loop
It would really just be an object that stores either 1 or 0 each clock cycle, and makes its next decision based on what's input to its "dendrites"
maybe even a glorified search algorithm
It would certainly be very esoteric to make programs with
so... like a neural network?
Yeah that sounds like a neural network to me XD
hehe
what's the hamt_name_node thingy?
its part of from _testcapi import hamt
!e py from _testcapi import hamt a = hamt() b = a.set('x', 1) c = b.set('y', 1) print(*a.items()) print(*b.items()) print(*c.items())
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 |
002 | ('x', 1)
003 | ('x', 1) ('y', 1)
!e
for n in range(2, 100): print(n, end=', ') if len([d for d in range(2, n) if n % d == 0]) == 0 else print(end='')
@sick hound :white_check_mark: Your eval job has completed with return code 0.
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
One-liner that generates primes. Not the best, but it works.
@sick hound :white_check_mark: Your eval job has completed with return code 0.
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
!e
print([n for n in range(2,100)if not __import__("re").match(r'^1?$|^(11+)\1+$','1'*n)])
@restive void :white_check_mark: Your eval job has completed with return code 0.
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
cursed version
a little challenge in this genre is to make a one-liner that prints a list of length n that contains the integers
[1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100,200,300,400,500 ...]
!e
n = 37
print([((i-1)%9+1)*10**((i-1)//9) for i in range(1,n+1)])
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]
!e
print([n for i,n in zip(range(37),(n for n in __import__("itertools").count()if len(str(n).strip("0"))==1))])
@restive void :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]
imagine my confusion when i first joined this server and read 'Topical Chat/Help' as 'Tropical Chat/Help', the fact that theres a palm tree next to the channel name didn't help either.
I just found out its 'Topical Chat/Help' by the survey and I've been in this server for like a month.
fantastic
!e
print([(i%9+1)*10**(i//9)for i in range(37)])
@severe canyon :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]
cleaned up your solution a bit
ty
!e
print("test")
!e ```py
def make_locals():
import sys
to_update = {}
def locals():
frame = sys._getframe(1)
return to_update.setdefault(frame, {**frame.f_locals})
def tracefunc(frame, what, arg):
if frame in to_update:
for key in frame.f_locals.copy():
if key not in to_update[frame]:
del frame.f_locals[key]
for key, val in to_update[frame].items():
if key not in frame.f_locals or frame.f_locals[key] != val:
frame.f_locals[key] = val
del to_update[frame]
return tracefunc
sys.settrace(tracefunc)
return locals
builtins.locals = make_locals()
def foo():
locals()['abc'] = 'New Value'
print(abc)
abc = None # forces abc to be a local
foo()```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
New Value
makes writing to the locals() dict actually stick using sys.settrace
not quite as good as my ctypes version, as the variables arent written until before the next line instead of immediatly
oh my god
Beautiful
Now I can throw this in a file in python path and import mutable_locals to get locals that work like globals.
Now you just gotta figure out how to make local annotations work XD
this just makes me feel uncomfortable XD
I'm guessing that tracefunc is meant to be invoked at least every time a variable is set. It's worth noting that sys.settrace which sets tracefunc to the trace-function, is used by debugger tools, so that could cause conflicts. sys._getframe is not guaranteed to be implemented outside of CPython. All in all, horrible code. 8/10
!e
print("test")
@torn grotto :white_check_mark: Your eval job has completed with return code 0.
test
debugger tools: I don't have bugs in the first place. I'm too good at programming :P
CPython: why would I use any other version of python?
I jest of course, but I still think that doesn't warrant a number as low as 8
If sys._getframe doesn't exist I can get the frame from a trace back (and if that doesn't work then the implementation prob doesn't have user facing frame objects and thus has no settrace)
I think ok boomer would have sufficed.
#bot-commands is a place we all can go.
I think !e print("test") is a daily occurrence in this channel.
and there's nothing we can do about it
except program the bot to detect that exact message content in this channel
since there's rarely any deviation and they don't use backticks
I could find it eventually, but where's the link to do that?
and what would be an appropriate action, just delete and warn?
it seems !source gets me where I want to go
so I'll call it esoteric python print("test") prevention
I'll do it a little later though
Sometimes I love the errors you get when you muck around with ctypes on slot classes...
getattr(cls, attr)(item)
TypeError: descriptor '__iter__' requires a 'dict' object but received a 'dict'
lol
XD
those people who can't make the difference between dict and dict smh my head
must have been an english and a german dictionary
How does one fool type(something)?
As best I can tell, if I implement an __instance_check__ and __subclass_check__, as well as somehow disguise its __mro__ and __class__ attributes then class A can effectively be disguised as class B. Are there any edge cases I'm missing?
why do you want to do this?
i think you can make a metaclass that implements instance_check right?
Why do bears poop in the woods?
Definitely
!e
class MyMeta(type):
def __instancecheck__(self, other):
print(other)
pass
class Test(metaclass=MyMeta): ...
isinstance(2, Test)
But its Python. Its very resistant to introspection manipulation like this XD I just want a full solution
@shut trail :white_check_mark: Your eval job has completed with return code 0.
2
ah
you cant object.__x__ always exists
Hmmmm
hence the question of why are you doing this, do you actually plan on having people use this?
Nah
I'm doing some work with metaclasses in general, and so I'm sorta in that zone
But I'm on break, so, I'm feeling a bit experimental
Just thought I'd take a look
!e
@type
@type.__call__
@type
@type.__call__
class C: pass
print(C)
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
<class '__main__.C'>
h
interesting discrepency:
__builtins__ = {}
print(__builtins__)
running the above as a python file results in {}
running with IDLE or a REPL results in NameError: name 'print' is not defined
anyone might have an idea why this happens
Because the two lines are compiled together when run as a file, but one by one when run from a REPL. You can also make it work in a REPL if you somehow put them in one compilation step:
class block:
def __enter__(*whatever): pass
def __exit__(*whatever): pass
with block():
__builtins__ = {}
print(__builtins__)
works in the REPL, but afterwards the builtins are gone.
Like print is in the co_names of the compiled module before any deletion happens. This is of course just a string, but I imagine that's how that happens.
If you replace print(__builtins__) with exec("print(__builtins__)") it stops working, in my example.
hmm interesting
what about the reverse
what if I wanted behaviour similar to in idle
exec("print(...)") should always fail, also in a file
(Unless print is used already, I guess)
is this channel for script help?
about as far from it as concievable
if you ask for help here your code will emerge a hideous abomination of its former self
yea that was probably the correct response but hey im not wrong either
!e This is kinda satisfying:
__import__("fishhook").hook(console := type, "log")(print)
console.log("woohoo")
@prisma coral :white_check_mark: Your eval job has completed with return code 0.
woohoo
!e
__import__("fishhook").hook(type, "log")(print)
int.log("woohoo")
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
woohoo
😄
!e
from fishhook import hook
hook(object, 'fizz')(lambda *args: print('bazz'))
1 .fizz()
[].fizz()
{}.fizz()
None.fizz()
....fizz()
....fizz().fizz()
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | bazz
002 | bazz
003 | bazz
004 | bazz
005 | bazz
006 | bazz
007 | bazz
!e ```py
import sys, dis
def trace(tf):
def wp(f):
def inner(*a, **k):
try:
sys.settrace(tf)
return f(*a, **k)
finally:
sys.settrace(None)
return inner
return wp
def jump_trace(frame, line, arg):
frame.f_trace_opcodes = True
if line == 'opcode':
idx = frame.f_lasti
op, arg = frame.f_code.co_code[idx: idx + 2]
if dis.opname[op] in ['LOAD_GLOBAL', 'LOAD_NAME']:
sarg = frame.f_code.co_names[arg]
if isinstance(sarg, str) and sarg.startswith('JUMP_'):
, d, n = sarg.split('')
try:
mvs = {
'UP': frame.f_lineno - int(n),
'DOWN': frame.f_lineno + int(n),
'TO': int(n)
}
frame.f_lineno = mvs.get(d, frame.f_lineno)
return
except:
pass
return jump_trace
@trace(jump_trace)
def foo():
x = 0
print(x)
x += 1
if x > 10:
return
JUMP_UP_4
foo()
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
011 | 10
It's not at versatile as my opcode replacement version but it works
!e
!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!*
noobie question ... can i post code here and get a question answered?
you probably shouldnt be getting code help here if youre a noob see #❓|how-to-get-help
@astral rover thanks
!e
def f():
print('before change #1')
f.__code__ = f.__code__.replace(co_consts=new_consts)
print('before change #2')
new_consts = (None, 'after change #1', ('co_consts',), 'after change #2')
print(f.__code__.co_consts)
f()
print(f.__code__.co_consts)
f()
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | (None, 'before change #1', ('co_consts',), 'before change #2')
002 | before change #1
003 | before change #2
004 | (None, 'after change #1', ('co_consts',), 'after change #2')
005 | after change #1
006 | after change #2
!e
arr = []
class test:
@classmethod
def retinst():
return self
for k in range(10):
arr.append(test.retinst)
for it in range(len(arr)):
print(it)
@grand tree :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
I was told to try asking here instead by Mustafa
Someone sent this in another server
import ctypes, inspect, gc
def main():
frame = not print("trolled with voidpointer haha") and inspect.currentframe()
ctypes.cast(ctypes.c_void_p(int([referer for referer in gc.get_referrers(frame.f_code) if getattr(referer, "__code__", None) is frame.f_code and set(inspect.getclosurevars(referer).nonlocals.items()) <= set(frame.f_locals.items())][0].__repr__()[-15:][:-1], 16)), ctypes.py_object).value.__call__()
main()
which just repeatedly prints the print line
What in the accursed world is this?
Use a trace function to change the line number
whats code gore?
very awful code
This isn't even esoteric, this is just kinda useless
I get a lot of esoteric code is useless, but this is literally just ```py
for i in range(10):
nums.append(i)
for i_2 in len(nums):
print(i_2)
Hey @inland crystal!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
!codeblocks
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
That's crazy bro
!e
from math import *
r=range
itc= (10,129297,128530,128542,32,33,128545,128548,128038,40,41,128683,44,128555,46,127790,128560,128575,63,65,66,127939,128580,69,68,*r(71,81),83,84,127829,85,89,127837,97,98,128483,100,101,103,104,105,*r(107,113),114,115,116,117,119,121)
def decode(e,b=1<<3):
l=ceil(floor((log2(e))+1) / b)
return"".join(map(lambda v:chr(itc[v]),reversed((*map(lambda i:(n:=e>>((l-i-1)*b))-(n>>b<<b)-1,r(l)),))))
print(decode(3244649123016202304891620531740982762891576544349418611903359070093996148368271375664004833158782419693562368836100015717309746308332940478214165459771461696755758941698312170665438354835055834831744615294239453342422211676208604486492899923465219708682188660541207378354834529120737764067488908516785255937372371826538196424288440513734017759507973354255076505610764439310038685057105380756911991480116903918691598975498051255492241347215219269210770330616723537702123696223194741388965316956049794151445622869939476096941182589287463344214230469776438876833152703640187393087978507269978387253970430932734015582132700799781747041561406164252203015589507175416946093177848124798931251421662043923210397855460937219260958556753825036738197210775503124127439473622168605484957252044318980335590468794557627590658425490077211094575885174664166519538163711538014654477691416995561377842095391962921377395420086534902478441806398390468998664407161668998259836607346093060894177235495713257626700960105270542207746133468723296932517388083783230442828998535786514706960160148499916637788255417695785324346500982590476571292941003412146388465011509827394655562950181687950396815699310393422661751300725350352875585493140797753767221528333636979638462863703881880397526185202577677344133834472196407668967934862043413785868761398687053999727462972065072563600212346884760118092965616800572377416888571625464970966174085783681256507818947953372411031341568724531967057894693591683032679322585434294326037397807531219870135510123849601,b=6))
@eager sphinx :white_check_mark: Your eval job has completed with return code 0.
001 |
002 | Kala mo di masakit 😫 yung pinagsasabi mo sakin??? 🗣🗣🗣Na patay gutom akohh??? 😤😤😤Bakit?Hindi bayon masakit? 😞😡😡E ikaw nga hinuhuli mo kalapati e.🐦🐦🐦Sabi niya tara Joela ku,hulihin natin yung kalapati 🏃🐦kuhain natin 🚫🚫🚫(MASAMA YON)Oh siya yun,siya yung pagsabihan mo😫🤑😤😡.Siya pa naninisi😿,hati nga kami sa pagkain🍝🌮🍕,hindi naman siya ang bumili🏃.Hindi niya nalang hingiin😡😡😡para hindi ma...🤑🤑🤑O,wag mo na siyang anohin 😡😡😡!!!wag mo na siyang anohin(HULI TAYONG KALAPATI🐦)Bakittt??!!! 😫😡😤Nakikisali ka dito kahit di ka naman kasali.O bakit? 😒🙄🙄Bat mo inaano pinsan ko 😤😡.Iiyak na nga diba😰😰😰,tapos yun na nga,wag mo ng anuhin 😡😡😡.Iiyak na nga eyeyeyye.O bakit??? 🙄🙄🙄O bakit din??!!! 🙄😒😒😒Umalis kana 🗣🗣🗣Aalis ako di naman ako dito eh.😒😒🙄🙄.Bb ka pala eh😒😡Bakit ka nag sasabing bb??? 🙄😤😤Bat ka namamangga??😰😫😿OYY DONDUNGGN INGAY INGAY NIYO!!!HOY🗣🗣🗣.
this is so satisfying
the original encoded number was 4,000 chars long i couldn't fit it in a discord message
i had to do this crap to compress it to 2,000
"you think it doesn't hurt, what you were saying about me? that i was eating a ton? why? is it not hurtful? ..." etc. etc.
it's funnier in tagalog
dont know a single code
im alone
not catched up with anything
b = lambda __92_ : [[__92_ for n in range(2**63)]]==[[__92_ for n in range(2**63)]]
_____ = [(___-8)*-b("Eror 404")
for
___ in range(
len(f"+{'_'*2}"))]
s = sum(_____)//(b(9223372036854775808)+b("""Letting the days go by, let the water hold me down"""))
print(_____)
mistakes have been made.
if anyone with a fast computer and an entire night free wants to try this, go ahead.
i believe this is what the industry calls a mistake
Ah yes. for n in range(2**63)
mhm.
you see
it turns out that time.sleeps limit is 2**63 nanoseconds
my plan was to have a program that counts upwards, each time testing whether time.sleep() works on it
when it eventually reaches 2**63, that is used as the value
that way it would take a very long time
what do you mean?
we can help you if you're confused about python
can someone transform this code into some cursed one-liner
a = [100, 400, 500, 300, 200]
b = 345
def closest_to_int(x, itr):
return sorted(itr, key=lambda j: abs(j - x))[0]
print(closest_to_int(b, a)) # -> 300
!e ```py
print((lambda x, itr: sorted(itr, key=lambda j: abs(j - x))[0])(345, [100, 400, 500, 300, 200]))
@shut trail :white_check_mark: Your eval job has completed with return code 0.
300
fwiw you can use min here
You don't need all the spaces after the commas
great, thanks guys
ah true, that will probably up the byte count if this is a smallest amount of bytes solution and that kinda stuff
You can also get rid of the space after the :s
!e ```py
x = lambda test:print(test)
x("test")
@terse mortar :white_check_mark: Your eval job has completed with return code 0.
test
!e ```py
print((lambda x,itr:sorted(itr,key=lambda j:abs(j-x))[0])(345,[100,400,500,300,200]))
@terse mortar :white_check_mark: Your eval job has completed with return code 0.
300
Can someone help with this script?
Hey @arctic pine!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Hey @arctic pine!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Please help me with this code I get, xsrf update error: list index out of range <class 'IndexError'>
Dm me if you figured it out!
@arctic pine think you want a help channel instead lol #❓|how-to-get-help
for the sorted[0] can't you just use min, it accepts key arg too
I find this brainfuck derivative useful in arithmetic encryption
def intfuck(code:list[int]):
a=__import__("collections").defaultdict(int)
i=p=t=0
def add(i):
a[i]=(a[i]+1)%256
return i,0
def sub(i):
a[i]=(a[i]-1)%256
return i,0
def left(i):return i-1,0
def rite(i):return i+1,0
def dot(i):
print(end=chr(a[i]))
return i,0
def com(i):
a[i]=ord(__import__('sys').stdin.read(1))
return i,0
def loop(i):return i,not a[i]
def end(i):return i,-bool(a[i])
while 0<=p and p<len(c):
if t:t+=(c[p]==7)-(c[p]==8)
else:i,t=[add,sub,left,rite,dot,com,loop,end,lambda i:(i,0)][int(''.join([*range(8)]).find(str(c[p]-1))](i)
p+=1-2*(t<0)
return int(bool(t))
I had to write it from memory so it might have errors
this one prints the output and returns the exit code
I tried to reverse engineer intfuck, but it looks like it belongs where beautiful code goes to die... oh wait that's here!
def random_noop_insert(victim):
from random import randint
_0,_1=0,len(victim)
while _0<_1:
if randint(0,4):victim=''.join([*victim[:_0],str(9*randint(0,1)),*victim[_0:]])
_0+=1
return map(int,victim)
def unfuck(message:str):
output=[ord(this)%256 for this in message]
if randint(0,9):code=''
else:code='9'
_0=[*filter(lambda x:any([t//10==x for t in output]),range((max(output)+2)//10)),max(output)//10]
_0=[*{*_0}]
code+='1'*10+'74'+'4'.join([t*'1'for t in _0])+'3'*len(_0)+'284'
j=0
for c in output:
a = c.__divmod__(10)
while a[0]>d[j]:j+=1;code+='4'
while a[0]<d[j]:j-=1;code+='3'
code+='1'*a[1]+'5'+'2'*a[1]
_={_ and(code:=code[:-1])for _ in iter(lambda:code.endswith('2'),False)},{_ and(code:=code.replace'12',''))for _ in iter(lambda:'12'in code,False)},{_ and(code:=code.replace('21',''))for _ in iter(lambda:'21'in code,False)}
return[*random_noop_insert(code)]
prio = { 1: 'priority', 2: 176027, 3: '', 4: 'priority'}
supp = {0: 'supplemental', 2: 160620, 3: 'supplemental', 4: 'supplemental'}
merged = supp | prio
merged = {k: supp[k] if not merged[k] and supp.get(k) else merged[k] for k in merged}
merged == {0: 'supplemental', 1: 'priority', 2: 176027, 3: 'supplemental', 4: 'priority'}
is anyone able to golf this further?
p='priority'
prio={1:p,2:176027,3:'',4:p}
s='supplemental'
supp={0:s,2:160620,3:s,4:s}
merged={k:x if not (x:=merged[k]) and (y:=sup.get(k))else x for k in supp|prio}
```this?
!e
p='priority'
prio={1:p,2:176027,3:'',4:p}
s='supplemental'
supp={0:'supplemental',2:160620,3:s,4:s}
merged={k:x if not (x:=merged[k]) and (y:=sup.get(k)) else x for k in merged}
print(merged == {0: 'supplemental', 1: 'priority', 2: 176027, 3: 'supplemental', 4: 'priority'})
can't walrus in an inline if
how do i tell it to try again
!e
p='priority'
prio={1:p,2:176027,3:'',4:p}
s='supplemental'
supp={0:'supplemental',2:160620,3:s,4:s}
merged = supp | prio
merged={k:x if not (x:=merged[k]) and (y:=supp.get(k)) else x for k in merged}
print(merged == {0: 'supplemental', 1: 'priority', 2: 176027, 3: 'supplemental', 4: 'priority'})
@inland monolith :white_check_mark: Your eval job has completed with return code 0.
False
aaaan it doesn't even work
And obviously you can shorten further by using shorter variable names
sec
!e ```py
p='priority'
prio={1:p,2:176027,3:'',4:p}
s='supplemental'
supp={0:s,2:160620,3:s,4:s}
merged={k:x if not (x:=(supp|prio)[k]) and (y:=sup.get(k))else x for k in supp|prio}
i don't really care about variable names, i just want to reduce the number of valid lines
@last locust :x: Your eval job has completed with return code 1.
001 | File "<string>", line 5
002 | SyntaxError: assignment expression cannot be used in a comprehension iterable expression
lol

!e py p='priority' prio={1:p,2:176027,3:'',4:p} s='supplemental' supp={0:s,2:160620,3:s,4:s} merged={k:x if not (x:=(supp|prio)[k]) and (y:=supp.get(k))else x for k in supp|prio} print(merged)
@last locust :white_check_mark: Your eval job has completed with return code 0.
{0: 'supplemental', 2: 176027, 3: '', 4: 'priority', 1: 'priority'}
3 is wrong
What are you actually trying to do?
merge supplemental into priority such that anything missing from priority is supplemented
missing can be defined as both the absence of a key and a value that would equate to false, like '' or None
!e
prio = { 1: 'priority', 2: 176027, 3: '', 4: 'priority'}
supp = {0: 'supplemental', 2: 160620, 3: 'supplemental', 4: 'supplemental'}
merged = {k: supp[k] if not prio.get(k) and supp.get(k) else prio[k] for k in supp|prio}
merged == {0: 'supplemental', 1: 'priority', 2: 176027, 3: 'supplemental', 4: 'priority'}
So take prio if it exists, otherwise supp?
yes
!e
prio = { 1: 'priority', 2: 176027, 3: '', 4: 'priority'}
supp = {0: 'supplemental', 2: 160620, 3: 'supplemental', 4: 'supplemental'}
merged = {k: supp[k] if not prio.get(k) and supp.get(k) else prio[k] for k in supp|prio}
print(merged == {0: 'supplemental', 1: 'priority', 2: 176027, 3: 'supplemental', 4: 'priority'})
@inland monolith :white_check_mark: Your eval job has completed with return code 0.
True
ah nice, now i don't have to declare merged twice
Is that not just prio | supp?
!e
prio = { 1: 'priority', 2: 176027, 3: '', 4: 'priority'}
supp = {0: 'supplemental', 2: 160620, 3: 'supplemental', 4: 'supplemental'}
print(prio | supp == {0: 'supplemental', 1: 'priority', 2: 176027, 3: 'supplemental', 4: 'priority'})
@inland monolith :white_check_mark: Your eval job has completed with return code 0.
False
!e py prio = { 1: 'priority', 2: 176027, 3: '', 4: 'priority'} supp = {0: 'supplemental', 2: 160620, 3: 'supplemental', 4: 'supplemental'} print(prio | supp) print(supp | prio)
lol
@last locust :white_check_mark: Your eval job has completed with return code 0.
001 | {1: 'priority', 2: 160620, 3: 'supplemental', 4: 'supplemental', 0: 'supplemental'}
002 | {0: 'supplemental', 2: 176027, 3: '', 4: 'priority', 1: 'priority'}
What's wrong with the first one?
neither are what i want (i did look before)
Oh I see
all of them are supplemental
and the 2nd one is missing the value i needed for 3
!e ```py
prio = { 1: 'priority', 2: 176027, 3: '', 4: 'priority'}
supp = {0: 'supplemental', 2: 160620, 3: 'supplemental', 4: 'supplemental'}
d = {k: x if (x:=prio.get(k)) else supp[k] for k in prio | supp}
print(d)```
@last locust :white_check_mark: Your eval job has completed with return code 0.
{1: 'priority', 2: 176027, 3: 'supplemental', 4: 'priority', 0: 'supplemental'}
Is that good?
i think so
!e
prio = { 1: 'priority', 2: 176027, 3: '', 4: 'priority'}
supp = {0: 'supplemental', 2: 160620, 3: 'supplemental', 4: 'supplemental'}
merged = {k: x if (x:=prio.get(k)) else supp[k] for k in prio | supp}
print(merged == {0: 'supplemental', 1: 'priority', 2: 176027, 3: 'supplemental', 4: 'priority'})
@inland monolith :white_check_mark: Your eval job has completed with return code 0.
True
hm what did you change
i see the walrus
{k: supp[k] if not prio.get(k) and supp.get(k) else prio[k] for k in supp|prio}```
vs```py
{k: x if (x:=prio.get(k)) else supp[k] for k in prio | supp}```
I also tidied your conditional
why remove supp.get(k)
Note that mine assumes it'll always be in prio or supp
If that's not guaranteed then change to supp.get(k)
it may be in neither
alrighty that seems to be the simplest form, thank you
!e
import _testcapi as t
print(t.the_number_three)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
3
I think I get what whitespace is for now
it's to "water down" the code
so you can retain your sanity whilst reading it
Ithinkit'sthesamereasonwehavewhitespaceinEnglish:Yes,youcanalmostalwaysstilldecipherit,butit'sunnecessarilyhard.
what's so hard about my event loop?
english isn't colour coded ;)
now that i think about it i should've used the acknowledge character instead of \1
for some reason this line
char=='�':lambda:(c:=msvcrt.getch().decode('ANSI'))not in'KHMP'and(self.reset()or 1)or self.move(**{{'K':'a','H':'w','M':'d','P':'s'}[c]:1})
works on an older laptop, but not this newer laptop
so I have to use this line
char in'wasdqezx':lambda:self.move(w=char in'qwe',a=char in'qaz',s=char in'zsx',d=char in'edx')
for movement
alright I fixed it, spot the difference, and someone extremely experienced please tell me why
char in'�\xe0':lambda:(c:=msvcrt.getch().decode('ANSI'))not in'KHMP'and(self.reset()or 1)or self.move(**{{'K':'a','H':'w','M':'d','P':'s'}[c]:1})
the invalid unicode character is actually á
in the previous device, it was a different character
so in order for the same code to work on two different machines, that line has to look for two different characters
although now that I have fixed that plus a small visual glitch, I believe I have the game perfectly working
except maybe the problem of too much processing power available
in this snippet, the last line is an aid for speed running to prevent mistakes when hitting zero, and clearing a spot the user was gonna clear next.
if not self.numbers[j][i]:
_={self[m,n]==1 or self.select(m,n)for k,l in product(range(-1,2),repeat=2)for m,n in[(i+k,j+l)]if m in range(x)and n in range(y)}
while msvcrt.kbhit(): msvcrt.getch()
without it, the user would instead attempt to clear the next square over, which was not the spot they were planning.
The problem with too much processing power is the above might run quicker than the user's reaction time, thus finishing before the next keyboard hit.
Slow it down a bit and the user can react to a 0-square clearing other squares and recalculate
aight i'm done someone else show me some amazing python torture
A nice exercise -
a[:], b = a = [[]], []
print(a)
Tell me what you get after running this 
🙃
how tf would that work
!e
a[:], b = a = [[]], []
print(a)
@thorny tapir :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 'a' is not defined
ok then
!e
try:
a = a[:], b = [[]], []
except: pass
print(a)
@frigid widget :white_check_mark: Your eval job has completed with return code 0.
([[]], [])
assignments in Python are left-to-right, a = b = c does a = c first and b = c second
Interestingly, the "intuitive order" is less intuitive than the "actual order"
a, b = a[b] = [{},()]
!e ```py
a, b = a[b] = [{},()]
print(a, b)
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
{(): [{...}, ()]} ()
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
True
!e someone asked this question in a help channel, so I'm just gonna post here what I shouldn't post there #help-corn message
from __future__ import annotations
from ctypes import*
flogbals = py_object.from_address(id(globals())+8).value
__name__ = 'Throwable'
class TypeException(TypeError):
def __init__(self, message):
super().__init__(message)
py_object.from_address(id(globals())+8).value=flogbals
class __annotations__(metaclass=lambda*a:type(*a)()):
queue = []
type_hints = {}
def __setitem__(self, cls_name, name):
if name in self.type_hints:
self.queue[:]=()
raise TypeException(f'Variable \'{name}\' already declared as \'{self.type_hints[name]}\'.')
if not self.queue:
self.type_hints[name] = globals()[cls_name]
return
cls, value = self.queue.pop(0)
self.type_hints.update({name:cls})
if cls==cls_name:raise NameError(f'Type {cls} not found')
dict.update(globals(),{name:cls(value)})
class __globals__(dict):
def __missing__(self, key):
return __builtins__.__dict__.get(key,key)
def __setitem__(self, key, value):
if key in __annotations__.type_hints:
dict.update(globals(), {key:__annotations__.type_hints[key](value)})
return
__annotations__.queue+=[(globals()[key], value)]
py_object.from_address(id(globals())+8).value=__globals__
str: x
str: y
int: z
x = 11
y = 10
z = x + y
print(z)
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
1110
Whoops, placed the slice in the wrong place... 👀
👀
!e
class _ProxyGetter:
def __ror__(self, other):
return other
def _get_mappingproxy_dict(mp, *, __proxy_getter=_ProxyGetter()):
return mp | __proxy_getter
del _ProxyGetter
_get_mappingproxy_dict(str.__dict__)['trim'] = str.strip
print(" hello w orld ".trim())
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
hello w orld
!e ```py
def get_cls_dict(cls, E=type('',(),{'eq':lambda s,o:o})()):
return cls.dict == E
get_cls_dict(int)['inc'] = lambda self: self + 1
print(1 .inc())```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
2
__eq__ works too
!e
def get_cls_dict(cls, E=type('',(),{'__eq__':lambda s,o:o})()): return cls.__dict__ == E
get_cls_dict(int)['__ne__'] = get_cls_dict(int)['__eq__']
print((1).__eq__(1))
print((1).__ne__(1))
print(1==1)
print(1!=1)
@trim grove :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | True
003 | True
004 | False
any way to override the c func
use fishhook
!e ```py
from fishhook import *
@hook(int)
def add(self, other):
print(self, other)
return orig(self, other)
1 + 2```
@rugged sparrow :x: Your eval job has completed with return code 1.
001 | 8 48
002 | 0 48
003 | 0 48
004 | 0 48
005 | 0 48
006 | 0 48
007 | 0 48
008 | 0 48
009 | 0 48
010 | 0 48
011 | 0 48
... (truncated - too many lines)
Full output: too long to upload
yea i need to fix that __eq__ bug (but its hard cause I wrote the hooker in python so it has to use the hooks)
v2 will fix it because that introduces a with no_hooks: context manager
is this calculating the offsets at runtime
yea
Because error handling requires a reset state otherwise it segfaults before the improvised atexit kicks in
Error handling and exiting both crash "corrupted" python unless safeguards like these reset it
*you can also use some more complex hooks that don't break pythons built in garbage collector (thats what segfaults in the end)
My prevention is really a gamble that the garbage collector would come for my user created object before whatever builtin object got corrupted
@floral meteor this should show why changing a dict instances class to a basic dict subclass causes issues. The basic subclass thinks it larger, so it frees more memory than the original dict instance. By adding __slots__ you can help to nullify this as it makes the dict subclass have the same internal structure as the original dict class
Quick question - why wouldn't #bot-commands message
change the value of x from 1 to 2?
or is that not how it works
Ohh
Is an integer not a void pointer like most things? Or are most things not void pointers
TIL except: catches BaseException, not Exception:
>>> try:
... raise BaseException()
... except:
... print('hi')
...
hi
saw that on yt or someplace saying how to confuse a python dev
oh so this is just
len((True, True, True, True == True, True, True, True))
so it finds True == True which is true so the length i s7
right?
and this it only looks at the last 1 and checks if itss equal to the tuuple which its not
what sorcery is this? your python is possessed
It essentially evaluates as (1, 1, (1 == (1, 1, 1)))
oh wow, I wouldn't have guessed so
so 1, 1, 1 isnt the same as (1, 1, 1) in this case?
It's not checking what you expect it to check
The point is that it does (1, 1, x) where x is 1 == (1, 1, 1) (it evaluates the == before "building" the left tuple)
And an int isn't equal to a tuple, so it evaluates to False
Hence (1, 1, False)
You could equally do 1, 1, 1 == 1 and you'd get (1, 1, True) for the same reason
The == is done before the tuple constructor
It's literally just precedence. It's like 10 - 3 * 2 is 4 (since multiplication is evaluated before substraction), even though reading left-to-right you'd expect it be 14
!e
class Foo:
def __init__(self):
x = 42
def get_x():
return x
def set_x(val):
nonlocal x
x = val
self.get_x = get_x
self.set_x = set_x
foo = Foo()
print(foo.get_x())
foo.set_x(3)
print(foo.get_x())
print(foo.x)
@gleaming timber :x: Your eval job has completed with return code 1.
001 | 42
002 | 3
003 | Traceback (most recent call last):
004 | File "<string>", line 16, in <module>
005 | AttributeError: 'Foo' object has no attribute 'x'
private variables in python
!e ```py
class Foo:
def init(self):
x = 42
def get_x():
return x
def set_x(val):
nonlocal x
x = val
self.get_x = get_x
self.set_x = set_x
foo = Foo()
foo.set_x.closure[0].cell_contents = 10
print(foo.get_x())
@snow beacon :white_check_mark: Your eval job has completed with return code 0.
10
😮
Ew
You broke your own private variables system
lol
privacy breach
needs friend keyword
I have recently used |{...} to fix a syntax error
literally those 6 characters
in that order
I could use kivy, and then make one Image object, then the event loop would only take raw input from clicking, and draw everything onto an image to display that. 2D rendering maybe.
Then with just that as io i could make a touchscreen game
I'm gonna make another minesweeper, this time with an actual gui
but first I gotta black box the existing minesweeper so I can use it
anyone have esoteric tips on black boxing an interface the most cursed way possible?
I wanna get creative
!rank
Iterating over range(len(...)) is a common approach to accessing each item in an ordered collection.
for i in range(len(my_list)):
do_something(my_list[i])
The pythonic syntax is much simpler, and is guaranteed to produce elements in the same order:
for item in my_list:
do_something(item)
Python has other solutions for cases when the index itself might be needed. To get the element at the same index from two or more lists, use zip. To get both the index and the element at that index, use enumerate.
You teaching people how to hack? :P
lol is this the brainfuck python?
huh
I'm emphasising to people that their security measures could use some work.
I'd hate for someone to get hacked, after all.
this is why python is nice
!e```python
import sys, os
def restart():
os.execv(sys.executable, ['python'] + sys.argv)
return False
while True:
print(restart())
restart()```
it wont let me break it 😢
!e you probably don't need the brackets, but you are right
try:raise BaseException
except:print(':(')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
:(
!e ```py
try:raise SystemExit
except:print(SystemExit)
try:raise KeyboardInterrupt
except:print(KeyboardInterrupt)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | <class 'SystemExit'>
002 | <class 'KeyboardInterrupt'>
bruh is this recent? I always remember having to explicitly reference BaseException to cover these two exceptions
I started making a proper gui version of minesweeper. I made the skeleton in Cell-Engine-Interface style but my brain is already fried :)
!e !e
import sys, os
def restart():
os.execv(sys.executable, ['python'] + sys.argv)
return False
while True:
print(restart())
restart()
@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
import sys, os
def restart():
os.execv(sys.executable, ['python'] + sys.argv)
return False
while True:
print(restart())
restart()
@sick hound :x: Your eval job has completed with return code 2.
001 | Argument expected for the -c option
002 | usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
003 | Try `python -h' for more information.
!e @zinc aurora
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | <@683001325440860340>
003 | ^
004 | SyntaxError: invalid syntax
Posted this in #advanced-discussion, but it probably fits better here:
import os
import sys
import inspect
from contextlib import contextmanager
@contextmanager
def atomic():
ppid = os.getpid()
cpid = os.fork()
if cpid:
os.waitpid(cpid, 0)
# we didn't get killed: error occured, skip body:
sys.settrace(lambda *a, **k:None)
frame = inspect.currentframe().f_back.f_back
def raiser(*a): raise RuntimeError
frame.f_trace = raiser
try:
yield
except RuntimeError:
return
try:
yield
except Exception:
# rollback: we exit
os._exit(0)
else:
# all good: kill state-preserved parent
os.kill(ppid, 9)
x = 23
with atomic():
x += 1
1/0
print(x)
@restive void why can’t I access #advanced-discussion? Is it invite only?
It got renamed to #internals-and-peps recently, and L3v was using the old name
Thanks @prisma coral
@tiny lodge so how it works is it first forks: this splits the execution in half across two "clones" of the same Python interpreter.
There parent process waits for the child process to exit. The child process enters the context manager's body and tries to execute it. If it succeeds, it just kills the parent process and continues normally.
If it fails, it kills itself.
In that case, the parent knows that the child died and is in the situation you desire a solution for: we are still "back in time", before the body of the context manager was entered, and we want to skip it. To do so, we set a trace function (the mechanism used by debuggers, coverage tools, etc.) to raise an exception inside the body immediately on entering it. We then catch that exception, and carry on.
ah raising an exception in the frame with a trace is clever, i was thinking about using a trace to jump lines
I stole it from StackOverflow
!e
print("haha xd")
@steel knot :white_check_mark: Your eval job has completed with return code 0.
haha xd
i dont python
#bot-commands please @steel knot
But beautifully esoteric way of going back in time in case of a failure. Just like saving your game, and going back to your last save if you die or accidentally kill an essential npc.
It's like code that can control time itself
Keep it up and you might even be able to code a Terminator that goes back in time to assassinate Hitler
Let's not be making suicide jokes please.
fair enough
I thought that might've been to far hence the /s
but now i know for sure, thank you
the assassinate hitler joke is good though?
!e okay how about this one? ```py
for()in(),{},[],'',"",range(0),iter(lambda:...,...),set():print(end='.')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
........
instead of doing the same thing 8 times like
for i in range(8):print(end='.')
you can
for()in[()]*8:print(end='.')
it's shorter and confusinger
!e
for {}[()] in range(5): print(end='.')
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
.....
!e
await ctx.send("test?")
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | SyntaxError: 'await' outside function
!e ```py
for{}[()]in[{}]*8:print('something in between?')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | something in between?
002 | something in between?
003 | something in between?
004 | something in between?
005 | something in between?
006 | something in between?
007 | something in between?
008 | something in between?
probably #bot-commands for generic trying to hack the bot?
No, that's not hacking the bot buddy.
this channel is more for torturing python itself
yeah, that's obviously not gonna work
and this still isn't the right channel
what wrong with the #bot-commands channel?
!e ```py
for[]in[[]]*8:print(end='.')
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
........
i think it is shortest
indeed
well, assuming an abstract code block in place of print(end='.')
!e otherwise ```py
print('.'*8)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
........
yes, that's another way of saying it
yea)
but for{():[]}[()]in[()]*n: makes it deliciously more confusing for the beginner coder
exactly

!e
a = a[0] = [None]
print(a)
assert a is a[0]
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
[[...]]
!e ```py
for{():[]}[()]in[()]*8:print(import('time').time())
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 1641988848.2122383
002 | 1641988848.2122772
003 | 1641988848.2122831
004 | 1641988848.2122874
005 | 1641988848.2122915
006 | 1641988848.2122958
007 | 1641988848.2122998
008 | 1641988848.2123039
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Fatal Failure
two spaces?
maybe make it a \b
print(a, b) add one space
!e
a = "Fatal"
b = "Failure"
print(a, b)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Fatal Failure
!e ```py
print("Fatal",'\b',"Failure")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Fatal Failure
it works in a "real" terminal
!e {}[()]={():[{()}]}
@fleet bridge :warning: Your eval job has completed with return code 0.
[No output]
ye, the message doesn't interpret control characters other than a newline
you can edit message
You can?
you can
huh
bruh
what are you doing??? go to #bot-commands
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
cool
>>> [*[a,[*([b,[f],d],c)],*(*[(),e],)],[]] = 1,[(2,[3],4),5],(),7,()
>>> a,b,f,d,c,e
(1, 2, 3, 4, 5, 7)
>>> class PrintSetAttr:
... def __setattr__(self, attr, value):
... print(f'{attr}={value!r}')
...
>>> _ = PrintSetAttr()
>>> [*[_.a,[*([_.b,[_.f],_.d],_.c)],*(*[(),_.e],)],[]] = 1,[(2,[3],4),5],(),7,()
a=1
b=2
f=3
d=4
c=5
e=7
order of assignments is left-to-right
is there a way to convert any code to one-liner?
especially with and try-except
import -> __import__
for -> [list comprehension]
if -> a if c else b
class -> type(...)
def -> lambda
with -> type('',(contextlib.ContextDecorator,),{'__enter__': ..., '__exit__': ...})()(func)()
try -> ???
while -> [list comprehension with callavle iterator]
the only thing I have yet to see done algorithmically is nonlocal
with is easy with ContextDecorator, try is just a context manager
while is just iter
while a: -> [_ for _ in iter(lambda: a,False)]
can i do something like:
(cm := SomeContextManager(), x := cm.__enter__(), some_code, cm.__exit__())
i think it wont work
class contextlib.ContextDecorator```
A base class that enables a context manager to also be used as a decorator.
Context managers inheriting from `ContextDecorator` have to implement `__enter__` and `__exit__` as normal. `__exit__` retains its optional exception handling even when used as a decorator.
`ContextDecorator` is used by [`contextmanager()`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager "contextlib.contextmanager"), so you get this functionality automatically.
Example of `ContextDecorator`:
type('',(contextlib.ContextDecorator,),{'__enter__': ..., '__exit__': ...})()(func)()
!e
from __future__ import annotations
from types import TracebackType
from typing import Any, Callable
from contextlib import ContextDecorator
class TryExceptContext(ContextDecorator):
def __init__(
self,
*exceptions: tuple[
type[BaseException],
Callable[[type[BaseException] | BaseException], Any],
]
) -> None:
self.exceptions = exceptions
def __enter__(self) -> None:
pass
def __exit__(
self,
exc_type: type[BaseException],
exc_value: BaseException,
traceback: TracebackType,
) -> bool:
if exc_type is None:
exc_type = type(exc_value)
for exc, fun in self.exceptions:
if issubclass(exc_type, exc):
fun(exc_value if exc_value is not None else exc_type)
return True
return False
catch_typeerror = TryExceptContext((TypeError, lambda exc: print(exc)))
catch_typeerror(lambda: 1 + 2)()
catch_typeerror(lambda: 1 + '')()
try:
catch_typeerror(lambda: 1 / 0)()
except ZeroDivisionError:
pass
catch_attr_and_name_error = TryExceptContext(
(AttributeError, lambda exc: print(exc)),
(NameError, lambda exc: print(exc)),
)
catch_attr_and_name_error(lambda: [].a)()
catch_attr_and_name_error(lambda: a)()
try:
catch_attr_and_name_error(lambda: [][0])()
except IndexError:
pass
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | unsupported operand type(s) for +: 'int' and 'str'
002 | 'list' object has no attribute 'a'
003 | name 'a' is not defined
it works
def f():
for x in y:
if z(x):
return a(x)
return b
how to convert it to lambda?
(without messing with bytecode, of course)
lambda: a if any(z(x) for x in y) else b```
Then a(x) instead of a 🤷
you cant
lambda: a(x) if any(z(x) for x in y) else b is invalid
x is local to gen-expression inside any()
f=lambda: next((a(x) for x in y if z(x)),b)
nice!
lambda: c[0] if all(z==c[0] for z in (c:=[a(x) if z(x) else b for x in y])) else b
```I think this also works
But next() is definitely the nicer option
no, x is local to this generator: (a(x) if z(x) else b for x in y)
>>> (lambda: x:=0)()
File "<stdin>", line 1
(lambda: x:=0)()
^^^^^^^^^
SyntaxError: cannot use assignment expressions with lambda
>>> lambda: c[0] if all(z==a(x) for z in (c:=[a(x) if z(x) else b for x in y])) else b
File "<stdin>", line 1
SyntaxError: assignment expression cannot be used in a comprehension iterable expression
>>> (lambda: (x:=0))()
0```you just need parentheses
interesting 🧐
Can I have a, b, x and y? @fleet bridge
This is close but might not quite be right
y = [1,2,3,4,5]
z = lambda x: x % 2 == 0
# z = lambda x: False # for returning b
a = lambda x: x*x
b = 0
Thanks
(lambda:t[0]if(t:=[a(x)for x in y if z(x)])else b)()
Yeah, that could be what I was going for
And then you can remove unnecessary spaces etc.
(lambda:t[0]if(t:=[a(x)for x in y if z(x)])else b)()
how to convert match-case into one-liner? 😄
I have seen a way to dynamically generate patterns and match them in early drafts, iirc
not sure about all the dynamiccy stuff but...
{caseA:lambda:...,caseB:lambda:...,caseC:lambda:...}.get(True,lambda:...)()
that's how I do it, even in preference to the match case suite
it is switch-case, not pattern matching actually
for example if i want multiple keybinds to do certain functions, just observe the core of my minesweeper event loop
(lambda i,j:{
char in'\t/?':lambda:self.right_click(i, j),
char in'\b\xff':self.reset,
char in' \r':lambda:self.react_select(i, j),
char in'wasdqezx':lambda:self.move(w=char in'qwe',a=char in'qaz',s=char in'zsx',d=char in'edx'),
char in'[\x1b':lambda:self.DIE(True),
char in'�\xe0':lambda:(c:=msvcrt.getch().decode('ANSI'))not in'KHMP'and(self.reset()or 1)or self.move(**{{'K':'a','H':'w','M':'d','P':'s'}[c]:1}),
char in'h;:':self.hint,
char in'rl':self.random_move,
char.isdigit():lambda:self.digit_move(int(char))
}.get(1,lambda:0)()or self.update_board())(*self.here)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
{1: 3}
exactly
yes, it implements some flavor of pattern-matching
the only "flavor" I really would ever need to use
the python version of ```matlab
switch s
case 1:
do_this()
case 2:
do_that()
case 3:
print('wheeee')
otherwise:
0
end
would be
```py
{1:do_this,2:do_that,3:lambda:print('wheeee')}.get(s,lambda:0)()
switching True can be useful for substituting extended if statements
keep in mind if all the middle ifs are elifs, your dict would actually be backwards in the one-line version
another example is where I sum a list excluding elements between and including 6 and 9
def summer_69(a):
state = [0]
output = [0]
for e in a:
{
state[0]:lambda:...,
state[0]and e==9:lambda:state.__setitem__(0,0),
not state[0]:lambda:output.__setitem__(0,output[0]+e),
not state[0]and e==6:lambda:state.__setitem__(0,1)
}[1]()
return output[0]
it is sadly that you cant do a[b]:=c or a.b:=c
you can a.__setitem__(b,c) and a.__setattr__(b,c)
yes, but it is ugly imo
or even juicier
[0 for a[b]in[c]]
[0 for a.b in[c]]
lol
anticlimactic loops can modify mutable objects
lambda a:((state:=[0]),(output:=[0],[{state[0]:lambda:0,state[0]and e==9:lambda:[0 for state[0]in[0]],not state[0]:lambda:[0 for output[0]in output[0]+e],not state[0]and e==6:lambda:[0 for state[0]in[1]]}[1]()for e in a]))[1][0]
that's the oneliner version of summer_69
using a state machine to get a binary state and the input to decide on modifying the output state and the binary state
and using anticlimactic loops for variable modification
and that's how I do switch suites
import -> __import__
for -> [list or set comprehension]
if -> a if c else b
class -> type(...)
def -> lambda
with -> type('',(contextlib.ContextDecorator,),{'__enter__': ..., '__exit__': ...})()(func)()
try -> custom context manager based on ContextDecorator
while -> [list or set comprehension with callable iterator]
assignment -> := or [0 for a[b]in[c]] or [0 for a.b in[c]]
match-case -> {cond3:f3,cond2:f2,...}.get(True,fdefault)()
switch-case -> {val1:f1,val2:f2,...}.get(val,fdefault)()
don't forget
switch-case-default -> {casen:fn, case3:f3,case2:f2,case1:f1}.get(switched_variable,f_otherwise)()
this is interesting
and you got your conds backwards if you want it to execute f1 in priority to f2 if cond1 and cond2
also for the while, it's better on memory if you use set comprehension otherwise you cannot truly make an infinite while loop
I could make this more cursed
lambda a:((state:=[0]),(output:=[0]),[{state[0]:lambda:0,state[0]and e==0b1001:lambda:[0 for state[0]in[0]],not state[0]:lambda:[0 for output[0]in output[0]+e],not state[0]and e==0b0110:lambda:[0 for state[0]in[1]]}[1]()for e in a])[1][0]
you cant make it more cursed than this
yeah you should see one of the cursed hello worlds way back a few years ago in this channel
trying to understand it requires immense knowledge, and even then that's just to write a deobfuscator to make it a little bit more readable, then you need advanced python knowledge and algorithmic understanding just to read that
compared to that, this is the most elegant solution to the given problem
woops forgot a bracket, fixed
bracket matching is easy to stuff up in this line of onelinerisation
!e import __hello__
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
Hello world!
obfuscation is an entirely different field which is fun but tiresome for me
onelinerisation with just a touch of cursed is my comfort zone
but just a touch of cursed is present in all of my code
!e ```py
print((lambda a:((state:=[0]),(output:=[0]),[{state[0]:lambda:0,state[0]and e==0b1001:lambda:[0 for state[0]in[0]],not state[0]:lambda:[0 for output[0]in[output[0]+e]],not state[0]and e==0b0110:lambda:[0 for state[0]in[1]]}1for e in a])[1][0])([1,2,3,4,5,6,7,8,9,1,1,1,1]))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
19
i saw this video 'calculate electricity bill in c' and im like: 'I'll do that in 1 line in python'
Behold: ```py
print(f"Electricity bill: {(add := 0 if (units := int(input('Enter number of units you used: '))) < 50 else 130 if units <= 100 else 292.5 if units <= 200 else 818.5) + (((units - (0 if units <= 50 else 50 if units <= 100 else 100 if units <= 200 else 200))) * (2.6 if units < 50 else 3.25 if units <= 100 else 5.26 if units <= 200 else 7.75)) + (25 if add == 0 else 35 if add == 130 else 45 if add == 292.5 else 55)}")
la code
!e print(1+2+3+4+5+4)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
19
okay this code actually works the way i intend it to
what is this supposed to do???
.....
the last two evaluations i did both added up to 19
the second one summed the list, but without the elements between and including 6 and 9
the first one did that algorithmically, taking the whole list as input
!e ```py
á, 🤔, 🪟 = 0, False, []
print(dir())
@floral meteor :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | á, 🤔, 🪟 = 0, False, []
003 | ^
004 | SyntaxError: invalid character '🤔' (U+1F914)
dammit
!e print('🤔')
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
🤔
and
not all emoji are allowed to be in names
the python variable naming rules do state that the variable name cannot have any special characters except _ but any ascii character can be in a sting
or does it?
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'λ']
any Unicode letters and numbers can be in a variable name
and certain punctuation too I think
.topic
Suggest more topics here!
.topic
Suggest more topics here!
esoteric in a nutshell
what exactly is magic?? is it the dunder methods?
Yes, the bot tried to say __magic__, but forgot the backticks
>>> True, False = False, True
>>> True, False
(False, True)
Only in deprecated Python 2
how to handle null and none values in pyspark dataframe, glue dynamic frame after reading CSV files
>>> id([]) == id([])
True
>>> [] is []
False
>>> id([[]]) == id([[]])
False
try id([1]) == id([2])
a = b = c = d = "hi"
try mixing assignment chains with implicit tuple construction and unpacking
that's how I easily make code look initimidating
this only has one builtin: print
the rest is literals, variables, keywords and syntax-sugar
I only just noticed that and i wrote it 🤔
which means it's a universal algorithm, it can port to another language without looking too different
Hey @sick hound!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
What do you need math for?
I was about to start decoding the base64 and dive down that rabbit hole...but then I came to my senses
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 22
002 | SyntaxError: 'named expression' can not be used within an annotation
!e
print((len("RATIO")**(int([]==[])/int(int("OwO"!="XwX")*len(":3")))+int(len("Furry")-4))/int(len("uwu")-1))
@rich hound :white_check_mark: Your eval job has completed with return code 0.
1.618033988749895
math
@sick hound :x: Your eval job has completed with return code 139 (SIGSEGV).
5:3.300000
type = lambda*_:int
lol good point
!e
n,l=[1000,900,500,400,100,90,50,40,10,9,5,4,1],'M CM D CD C XC L XL X IX V IV I'.split()
for N in range(1,4000):
r='';p=N
for x,y in zip(n,l):
while p>=x:r+=y;p-=x
exec('%s=%d'%(r,N))
print(CDXX+MCCCVII-MDCLXXXVIII)
@solemn jungle :white_check_mark: Your eval job has completed with return code 0.
39
!e
n,l=[1000,900,500,400,100,90,50,40,10,9,5,4,1],'M CM D CD C XC L XL X IX V IV I'.split()
for N in range(1,4000):
r='';p=N
for x,y in zip(n,l):
while p>=x:r+=y;p-=x
exec('%s=%d'%(r,N))
print(CDXX+MCCCVII-MDCLVIII)
@solemn jungle :white_check_mark: Your eval job has completed with return code 0.
69
Now change the __repr__ of int accordingly
bugger that, don't use int, use an int subclass like booleans do
obviously, the __str__ method would be the algorithm to convert an integer to roman numerals
class Numeral(int):
def __repr__(self):
...
def __init__(self, *args):
super().__init__(*args)
self.__str__ = self.__repr__
alright I thought of a challenge. shorten and expand the functionality of this oneliner: ```py
class SirPrintalot:add=sub=mul=floordiv=truediv=mod=getattribute=getitem=setattr=setitem=pow=and=or=radd=rsub=rmul=rfloordiv=rtruediv=rmod=rpow=rand=ror=rxor=xor=iadd=isub=imul=ifloordiv=itruediv=imod=ipow=iand=ior=ixor=call=lt=eq=neq=gt=ge=le=req=rneq=rlt=ilt=rle=ige=rge=ieq=ineq=ile=rgt=igt=print;pos=lambda s:print(end=' ');invert=lambda s:print();neg=lambda s:print(' ');str=lambda s:print("print('...')")or'print(...)'
ideally, anything you can do to an instance prints something
__repr__, not __str__
object.__str__ uses object.__repr__
Maybe use a metaclass' getattr?
no, it wont initialise method's slots
x.__getitem__(...) will work, but x[...] wont
Why does this work
you mean "how does it work?"
it converts every number from 1 to 4000 to roman numerals
then the exec function execute like MMXXII=2022
@solemn junglehelp me in #discord-bots
sorry i dont code bots
Oh I thought just the digits
To convert some binary into text
genius, f-string that has only one item
>>> dis('f"{x}"')
1 0 LOAD_NAME 0 (x)
2 FORMAT_VALUE 0
4 RETURN_VALUE
!e
exec("""π=print;ρ=range
φ=λξ:1ηξ<2εφ(ξ-1)+φ(ξ-2)
ζνορ(20):π(φ(ν))
""".replace('λ','lambda ').replace('η',' if ').replace('ε',' else ').replace('ζ','for ').replace('ο',' in '))
@solemn jungle :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 1
003 | 2
004 | 3
005 | 5
006 | 8
007 | 13
008 | 21
009 | 34
010 | 55
011 | 89
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/duvuyajeya.txt?noredirect
!e
print((len("RATIO")**(int([]==[])/int(int("what the fuck"!="am i doing")*len("with")-2))+int(len("my life")-6))/int(len("...")-1))
@rich hound :white_check_mark: Your eval job has completed with return code 0.
1.618033988749895
>>> dis("x")
1 0 LOAD_NAME 0 (x)
2 RETURN_VALUE
f'{x}' is equal to format(x) (str(x) in most cases), while x just gets reference
print(
(5
** (1 / int(1 * 4 - 2))
+ 7 - 6 )
/ int(3 - 1)
)
==
print(
( sqrt(5) + 1 ) / 2
)
==
1.618033...
And this was all using the phrase "RATIO what the fuck am i doing with my life" 🙃
yes

but its true
Having an exclamation mark(!) would have made it even more hilarious. 
where.
# Create a program that will allow a user to enter in ten numeric test grades. Then it drops the lowest two test grades and finds the average.
#
# Requirements:
#
# Prompt the user for ten test scores from 0 - 100
# Do not allow numbers out of that range
# Drop the lowest two scores and find the average
# Output the average to the user.
# i need to do that
print(sum(sorted([(a if ((a := int(input(f"Enter your {i + 1}{'th' if i + 1 > 3 else ('rd' if i + 1 == 3 else ('nd' if i + 1 == 2 else 'st'))} number > ")))) <= 100 else exit("Numbers over 100 are not allowed.")) for i in range(10)])[2:])/8)```
uhhh clean, I never really used .get tbh
I love it
I love this channel
Use a dictionary instead of multiple if-statments -
input( f"Enter your {i}{{1: 'st', 2:'nd', 3:'rd'}.get(i, 'th')}" ... for i in range(1, 11) )
Oh, lol. You already answered that Q.Q
ive implemented stdout coloring
dangg thats cool, how did u do that?
- wrapped
sys.stdout - used
pygments, my style and lexer to color text - changed
sys.displayhooktopprint
i can share code, but it is really bad
What's interesting going on in the esoteric python world currently?
Tldr, what are you guys working on?
any alternatives to OS and Subprocess libraries?
for what purpose?
well I successfully screwed myself over
>>> import main
KeyError called: args=('main',) kwargs={}
Calling my_excepthook on KeyError
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 175, in _get_module_lock
OSError called: args=(2, 'No such file or directory', '<frozen importlib._bootstrap>') kwargs={}
Calling my_excepthook on OSError
Traceback (most recent call last):
File "/data/media/0/pythonrc.py", line 433, in my_excepthook
return old_excepthook(exctype, value, traceback)
File "<stdin>", line 1, in on_exception
OSError called: args=(2, 'No such file or directory', '<stdin>') kwargs={}
Calling my_excepthook on OSError
...
File "<stdin>", line 1, in on_exception
Fatal Python error: _Py_CheckRecursiveCall: Cannot recover from stack overflow.
Python runtime state: initialized
Current thread 0x0000007ff7ce7010 (most recent call first):
File "<stdin>", line 1 in <lambda>
File "/data/media/0/pythonrc.py", line 433 in my_excepthook
File "<stdin>", line 1 in on_exception
File "<stdin>", line 1 in <lambda>
File "/data/media/0/pythonrc.py", line 433 in my_excepthook
File "<stdin>", line 1 in on_exception
File "<stdin>", line 1 in <lambda>
File "/data/media/0/pythonrc.py", line 433 in my_excepthook
File "<stdin>", line 1 in on_exception
File "<stdin>", line 1 in <lambda>
...
zsh: abort (core dumped) python3
that was my attempt to hook the __init__ method of all exception types
so I won't lose exceptions that get thrown in async code
🤦♂️
using fishhook
now it's not saved my python histfile.. serves me right for trying to do something with exceptions, I suppose
oof
whenever I try to do something esoteric with exceptions or reprs, this is inevitably what awaits
lol
!e
z,n,o=' \n1';[(print('#'*a+' '*b,end=c))for a,b,c in zip(map(int,'115113113414'+o*16+'54'+o*9+'4'+o*22+'55531131154'),map(int,'2004552111402044424202020420014424000201420204442400020204202000160212000'),z*11+n+z*15+n+z*14+n+z*16+n+z*12+n,)]
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | # # ##### # # ### # # ### #### # ####
002 | # # # # # # # # # # # # # # # #
003 | ##### #### # # # # # # # # # #### # # #
004 | # # # # # # # # # # # # # # # # #
005 | # # ##### ##### ##### ### # # ### # # ##### ####
🥳
then this is the right channel for you
it took me a while but i got it.
!e ```py
{
print(f"assigned {x} to x") for x in [69]
}
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
assigned 69 to x
actually I think that has it's own local namespace, so...
!e ```py
for x in [69]:{
print(f"assigned {x} to x")
}
print(x, 'is still assigned to x')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | assigned 69 to x
002 | 69 is still assigned to x
this is a subtle way to avoid =
hol' up
I guess that's what happens when i import externally located code
i didn't know onedrive could be a module
this is almost comical
lmao
I had to do a double take on those braces
nice
I don't care how bad it looks, I want to see your code as a reference implementation, even if afterwards I try to golf it or make it pythonic or anything. 😉
Hey @fleet bridge!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
https://paste.pythondiscord.com/owawupexip.py @vague cairn
it is sitecustomize.py
also it slows python startup time from ~25ms to ~100ms
If I import it, from the interpreter it changes the color of the prompt, and pretty much blocks output. what am I doing wrong? you want me to drop it in /site_packages under the name sitecustomize.py?
you want me to drop it in /site_packages under the name sitecustomize.py?
yes
because it is code for sitecustomize module
Cool, that got it.
I removed TypeGuard and underscore_numbers=True, to get it to work on my version of python, but anyway. Neat stuff.
And I added: ```py
if not 'idlelib' in sys.modules:
print('sitecustomize.py: Not in idle, console highlight enabled.')
on line 6 and indented the rest...
I hope this is the right kind of crowd for this old thing of mine
https://codeforces.com/contest/1154/submission/52853290
If anyone here is knowledgeable in obfuscating Python, please DM me, I have a few questions I would like to ask c:
You should just ask here
Then everyone can see and people will know if they're able to help
Perfect
I would just use pyarmor
hello guys
i'm new to Python and i am assigned a task to extract time from a given time range this is as follows:
lets say a person is working in a company he started a work at start_time and end_time between these duration i have to extract how much hours does this man has worked during morining hours, evening hours and night hours.
Hi Guys
@zinc aurora crossposting here 👆
This isn't really the right channel for getting help. (Trust me: you don't want the kind of 'help' this channel would provide.) Instead, you should write code until you get stuck, then look in #❓|how-to-get-help to see where you can get help with your task.
yeah this probably is the worst place for someone new to python to be. This place can give you nightmares if you're not equipped with advanced knowledge of the inner workings of python
This isn't the perfect channel for asking questions. Because there are many "esoteric" codes here, which rarely follow the standards for python.
Anyhow, what you're probably looking for are
• timedelta and datetime from the module datetime,
• along with maybe strftime from the time module.
These would help with managing and parsing the time frames.
s/deltatime/timedelta/
Yes. I always seem to get confused with them...
also, a quick esoteric code for validating inputs -
while not (k := input("...")).isnumeric():
print("Invalid Input")
print(f"{k=:^8}is a number!")
!e
k = 2
print(f"{k=:^8}is a number!")
@torn oak :white_check_mark: Your eval job has completed with return code 0.
k= 2 is a number!
!e
print(f"{'test'=:^13}")
@torn oak :white_check_mark: Your eval job has completed with return code 0.
'test'= test
@errant crescent what does that do , can u maybe explain? D:
@torn oak The k= writes the literal text of k= into the string, and then put the value of k after. The 8 says how wide the section after that = sign should be (so the 2 bit is 8 chars long). Finally, the ^ says to center that value of k within that 8 char section
!e
print([a := '', [(a := f'{a}{i}{__import__("random").choice(["+", "-", "/", "*"])}') for i in [__import__("random").randint(1, 9) for _ in range(5)]], a[:-1]][2])```
@torn oak :white_check_mark: Your eval job has completed with return code 0.
9*2*7+3/6
!e
print([a := '', [(a := f'{a}{i}{__import__("random").choice(["+", "-", "/", "*"])}') for i in [__import__("random").randint(1, 9) for _ in range(10)]], a[:-1]][2])```
@torn oak :white_check_mark: Your eval job has completed with return code 0.
9-7*3/3-2+9-5/4-8*8
it works yay
Any tips for how I can further golf this? (not counting variable names)
def line(x0: int, y0: int, x1: int, y1: int) -> Generator[int]:
"""
Naive solution
Bresenham's Line Algorithm, used for diagonals
"""
deltax = x1 - x0
dxsign = int(abs(deltax) / deltax)
deltay = y1 - y0
dysign = int(abs(deltay) / deltay)
deltaerr = abs(deltay / deltax)
error = 0
y = y0
for x in range(x0, x1, dxsign):
yield x, y
error = error + deltaerr
while error >= 0.5:
y += dysign
error -= 1
yield x1, y1
which I've cut down to:
r_,i_,a_=range,int,abs # used elsewhere in not shown code, so is a reduction
def _L(x0,y0,x1,y1,e=0):
d=[x1-x0,y1-y0]
de=a_(d[1]/d[0])
d=[i_(a_(_)/_)for _ in d]
for x in r_(x0,x1,d[0]):
yield x,y0
e+=de
while e>=0.5:
y0+=d[1]
e-=1
yield x1,y1
pretty much. although I was wondering whether to use < or ^ for the padding.
Use magic math to shrink things down -
def line(x0: int, y0: int, x1: int, y1: int) -> Generator[int]:
"""
Naive solution
Bresenham's Line Algorithm, used for diagonals
"""
deltax = x1 - x0
dxsign = int(abs(deltax) / deltax)
deltay = y1 - y0
dysign = int(abs(deltay) / deltay)
deltaerr = abs(deltay / deltax)
const_err = floor(deltaerr)
deltaerr %= 1
y = y0
for x in range(x0, x1, dxsign):
yield x, y
y += dysign * (const_err + floor(deltaerr * i))
yield x1, y1
def line_compact(x0: int, y0: int, x1: int, y1: int) -> Generator[int]:
"""
Naive solution
Bresenham's Line Algorithm, used for diagonals
"""
delta: float = abs((y1 - y0) / (x1 - x0)))
const_err: int = floor(deltaerr)
delta %= 1
# from numpy import arrange
cnv = (1, -1)
x_axis = range(x0, x1, cnv[x0 > x1])
y_axis = [floor(n + const_err + delta * i) for i, n in enumerate(range(y0, y1, cnv[y0 > y1]))]
for x, y in zip(x_axis, y_axis):
yield x, y
yield x1, y1
Although when I look at it now ; I can see that there is no need for const_err, just use the entire delta instead.
You could also do x1+1 and y1+1 to include them in the range. However this may offset the final point.
@wanton flame
from math import floor
def line_compact(x0: int, y0: int, x1: int, y1: int) -> Generator[int]:
"""
Naive solution
Bresenham's Line Algorithm, used for diagonals
"""
delta: float = abs((y1 - y0) / (x1 - x0)))
# from numpy import arrange
cnv = (1, -1)
x_axis = list( range(x0, x1, cnv[x0 > x1]) )
y_axis = [floor(cnv[y0 > y1] + delta * i) for i range(len(x_axis))]
yield from zip(x_axis, y_axis)
yield x1, y1
oh right! I was so focused on the math, I didn't notice O.o
nvm
discord is wrapping my code, making things look funky
for a sec I though I didn't remove the old loop.
what elements?
Hmm...
Oh, I know why.
I accidentally though the constraints of error were between 0 - 1
after checking again, I see that it can go between -0.5 - 1.
Edit: It was also using separate values for both lists. e.g. x axis could be 6 elements long, while y axis might only be 4. Hence, the difference in the final output length.
give me a sec. imma fix this.
the algo is known to not work with 'steep' lines, for this data we can assert that all input will have a slope of 1 or -1 aka pure diagonal
print([a := int(input('Amount of numbers > ')), nums := [str(__import__("random").randint(1, 9)) for _ in range(a)], combo := list(__import__('itertools').product(["/", "*", "+", "-"], repeat=a)), nums := list(__import__('itertools').permutations(nums)), f := [([]) for _ in range(len(combo))], [[[(f[i].append([(l,n) for l,n in zip(n, c)])) for c in combo] for n in nums] for i in range(len(combo))], f := [''.join([list(__import__('itertools').chain.from_iterable(b))][0])[:-1] for b in list(__import__('itertools').chain.from_iterable(f))], g := [], r := [], generated := [], [([g.append(s := eval(b)), r.append([s, b])] if type(eval(b)) == int else '') for b in set(f)], [((generated.append(h)) if (h > 0 and r.count(h) == 1) else '') for h in set(g)], [sorted(set(g)), sorted(r), generated]][-1])```
not finished D:
!e
k = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.8]
n = [(int(i), i) for i in k]
print(n)
Well, Its sort of fixed for now... it should work for ±1 slopes, and it does get pretty close to the original logic.
I think this is as far as I could get writing on the phone, without even a pen or a piece of paper 
In order to get the exact logic,
You might need to round the initial deviation then shift everything by -0.5 (to fix the original -1 offset, changing the difference from -0.5 - 0.5 to -1 - 0).
Afterwards either divide by 0.5 or something, to get the usual offset that would happen if you had used the original logic.
Finally substract that from the calculations in the loop, or do some other operations. 
(Some bitshifts operations and floor division might be of use).
how can I get the current frame in one expression w/o imports?
__import__('sys')._getframe(0)
def l(a): #x:a[0], y:a[1], x1:a[2], y1:a[3], e:a[4]
for x in range(a[0],a[2],int(abs((b:=a[2]-a[0]))/b)):
yield x,a[1];a[4]+=abs((d:=a[3]-a[1])/b)
while a[4]>=0.5:a[1]+=int(abs(d)/d);a[4]-=1
yield a[2],a[3]
for i,b in l([7,6,1,2,0]):
... print(i,b)
...
7 6
6 5
5 5
4 4
3 4
2 4
1 2```
is this even so esoteric? seems like a reasonable use of walrus
print([a := int(input('Enter amount of nums > ')), nums := [str(__import__("random").randint(1, 9)) for _ in range(a)], combo := list(__import__('itertools').product(["/", "*", "+", "-"], repeat=a)), '''nums := list(__import__('itertools').permutations(nums))''', f := [([]) for _ in range(len(combo))], [[(f[i].append([(l,n) for l,n in zip(nums, c)])) for c in combo] for i in range(len(combo))], f := [''.join([list(__import__('itertools').chain.from_iterable(b))][0])[:-1] for b in list(__import__('itertools').chain.from_iterable(f))], g := [], r := [], generated := [], [([g.append(s := eval(b)), r.append([s, b])] if type(eval(b)) == int and eval(b) > 0 else '') for b in set(f)], [((generated.append(h)) if (h > 0 and r.count(h) == 1) else '') for h in set(g)], [sorted(set(g)), sorted(r), generated]][-1])```
literally uses imports
without imports
!e
class MagicNamespace(dict):
_getFailure = object()
MagicType = object()
def __init__(self, initial=None):
self._dict = initial or {
"__name__": "Magic Namespace"
}
def __setitem__(self, key, value):
self._dict[key] = value
def __getitem__(self, key):
get_res = self._dict.get(key, MagicNamespace._getFailure)
if (get_res == MagicNamespace._getFailure):
self._dict[key] = self.MagicType
return self._dict[key]
class MagicEnumMeta(type):
@classmethod
def __prepare__(mcs, name, bases):
return MagicNamespace()
def __new__(mcs, name, bases, namespace, **kwargs):
enum = super().__new__(mcs, name, bases, namespace, **kwargs)
enum.__repr__ = lambda self: self._key
if not isinstance(namespace, MagicNamespace):
return enum
for key, value in namespace._dict.items():
if value is MagicNamespace.MagicType:
inst = enum()
inst._key = key
setattr(enum, key, inst)
return enum
class MagicEnum(metaclass=MagicEnumMeta):
def __init__(self):
raise NotImplementedError("Enum Instantiation")
class Colors(MagicEnum):
RED
BLUE
GREEN
print(Colors.RED == Colors.BLUE) #False
print(Colors.GREEN == Colors.GREEN) #True
@languid hare :white_check_mark: Your eval job has completed with return code 0.
001 | False
002 | True
imagine using enum auto()
this is very cheaty but I'll allow it
what's the 100th subclass of object on your machine?
I have never even encountered that before
nice loophole though
love how they added whitespace to this abominations
for research purposes I need an expression containing no lambdas which gives me functionType
it returns wrong frame
it returns frame of generator expr, not outer frame
!e
import sys
print(next(getattr(c, f).__globals__['sys']._getframe(0) for c in ().__class__.__base__.__subclasses__()for f in dir(c)if isinstance(getattr(c, f, None), type(lambda: None)) and'sys' in getattr(c, f).__globals__))
print(next(getattr(c, f).__globals__['sys']._getframe(1) for c in ().__class__.__base__.__subclasses__()for f in dir(c)if isinstance(getattr(c, f, None), type(lambda: None)) and'sys' in getattr(c, f).__globals__))
print(sys._getframe(0))
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | <frame at 0x7efe1e5b09f0, file '<string>', line 2, code <genexpr>>
002 | <frame at 0x7efe1e5b9000, file '<string>', line 3, code <module>>
003 | <frame at 0x7efe1e5b9000, file '<string>', line 4, code <module>>
=> you should call ._getframe(1)
i imagine evaling an obfuscated string is cheating?
I have no idea if that will make my code segfault
I'll try it
yeah
so far
(lambda n:eval('type(lambda:0)')([i for i in __import__('sys')._getframe().f_back.f_code.co_consts if isinstance(i,type(__import__('sys')._getframe().f_back.f_code))][0],globals()))(3)
it can actually be golfed now with your hint though
(lambda n:eval('type(lambda:0)')([i for i in __import__('sys')._getframe().f_back.f_code.co_consts if isinstance(i,eval('type((lambda:0).__code__)'))][0],globals()))(3)
almost there
also welcome to #esoteric-python
heh
__import__("types").FunctionType?
trying to use as few imports as possible
!e
(lambda n:eval('type(lambda:0)')([i for i in __import__('sys')._getframe().f_back.f_code.co_consts if isinstance(i,eval('type((lambda:0).__code__)'))][0],globals())(n-1)+eval('type(lambda:0)')([i for i in __import__('sys')._getframe().f_back.f_code.co_consts if isinstance(i,eval('type((lambda:0).__code__)'))][0],globals())(n-2)if n>1 else n)(3)
tried to make fibonacci, not sure where I messed up
@golden finch :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
yeah and there's that too
__builtins__.__loader__.load_module("_frozen_"+__builtins__.__loader__.__module__[8:])._ModuleLock.__init__.__globals__["sys"]._getframe(0)```
My attempt.
smart, still a loophole
wdym?
__builtins__.__loader__.load_module(().__class__.__bases__[0].__subclasses__()[141].__module__).FunctionType```
but idk if load_module counts as import too
uses external modules
!e
function = ().__class__.__base__.__subclasses__()[32]
print(function)
assert type(lambda: ...) is function
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
<class 'function'>
@golden finch
nice
or object.__subclasses__()[32]
order of initialization of builtin types changes very rarely
so this code should work almost always
thanks
delicious!
I usually try to run a search by subclass name to get the index rather than hardcoding it, just in case
😄
Now that's a good way to isolate function from main globals.
>>> ().__class__.__bases__[0].__subclasses__()[32]((lambda:globals()).__code__,{})()
{}```
Okay, so I ended up with this:
print([a := int(input("How many numbers > ")), nums := [str(__import__("random").randint(1, 9)) for _ in range(a)], combo := list(__import__('itertools').product(["/", "*", "+", "-"], repeat=a)), f := [([]) for _ in range(len(combo))], [[(f[i].append([(l,n) for l,n in zip(nums, c)])) for c in combo] for i in range(len(combo))], f := [''.join([list(__import__('itertools').chain.from_iterable(b))][0])[:-1] for b in list(__import__('itertools').chain.from_iterable(f))], g := [], r := [], generated := [], [([g.append(s := eval(b)), r.append([s, b])] if type(eval(b)) == int and eval(b) > 0 else '') for b in set(f)], [((generated.append(i)) if [it[0] for it in sorted(r)].count(i[0]) == 1 else '') for i in sorted(r)], generated][-1])```
how could I optimize this
it is same code, as globals()
your lambda globals and actual globals are the same dictionary
Hi I need some help with a python project

