#esoteric-python
1 messages · Page 139 of 1
I also have to use a main function and 2 smaller functions like imperfect and perfect
This channel is for esoteric python code, you can ask for help in #❓|how-to-get-help
>>> test = "Hello World"
>>> def a():
... print(globals(), test)
...
>>> a()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'test': 'Hello World', 'a': <function a at 0x78e91832e0>} Hello World
>>> ().__class__.__bases__[0].__subclasses__()[32]((lambda:globals()).__code__, {})()
{}
>>>```
hmm
I didnt notice {} in the end 😄
!e
class X:
print(__module__)
assert '__module__' not in globals()
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
__main__
type.__prepare__ adds __module__ and __qualname__ to class namespace?
!e
class X:
print(locals())
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
{'__module__': '__main__', '__qualname__': 'X'}
Tracer I wrote using this
import gc
import sys
import types
a_func = ().__class__.__bases__[0].__subclasses__()[32]
def call_tracer(frame, event, arg):
if event == 'call':
name = frame.f_code.co_name
if name == "<module>":
return
obj = gc.get_referrers(frame.f_code)
if len(obj) > 0:
func = obj[-1]
if isinstance(func, types.LambdaType) and name == "<lambda>":
print(f"lambda: {name}, {func}")
elif callable(func):
print(f"pyfunc: {name}, {func}")
elif isinstance(func, types.FunctionType):
print(f"cfunc: {name}, {func}")
frame.f_trace_lines = True
frame.f_trace_opcodes = True
return call_tracer
elif event == 'c_call':
name = arg.__name__
if name == "<module>":
return
print(f"C_Entering: {arg.__name__}")
elif event == 'return':
if arg is None:
return
print(f"Returning: {arg!r}")
elif event == 'c_return':
print(f"C_Returning from: {arg.__name__}")
return None
sys.settrace(call_tracer)```
Now I need a method to stop function in frame execution / prevent it from executing at call.
brainfuck to python interpreter?
Learn about the ast module; I think it could really help for these purposes.
On another note, decorators could be helpful too; allowing to set manually which function you would like to trace.
!docs ast
Source code: Lib/ast.py
The ast module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like.
An abstract syntax tree can be generated by passing ast.PyCF_ONLY_AST as a flag to the compile() built-in function, or using the parse() helper provided in this module. The result will be a tree of objects whose classes all inherit from ast.AST. An abstract syntax tree can be compiled into a Python code object using the built-in compile() function.
!e ```py
def getframe(i=0):
try:raise
except Exception as e:
frame = e.traceback.tb_frame.f_back
for _ in range(i):
frame = frame.f_back
return frame
print(getframe())```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
<frame at 0x7fcf11735000, file '<string>', line 9, code <module>>
@golden finch ^
that uses the exception traceback to get access to the frame stack
I'm not new to python, just needed that for my "language" to isolate all functions.
It may help with the usual debugging.
However, once you use libraries and modules, it would likely show where the error occurred in the module, and not the actual (incorrect) function call.
that function mimics the behavior of sys._getframe

>>> def a(e,f):
... print(globals(),e,f) >>> a(2,9) pyfunc: a, <function a at 0x780cd89a20>
{..fake globals...} 2 9
... # Need to stop execution of called function now
{..real globals..} 2 9```
import gc
import sys
import threading
import types
a_func = ().__class__.__bases__[0].__subclasses__()[32]
def _module_repr_from_spec(spec):
name = '?' if spec.name is None else spec.name
if spec.origin is None:
if spec.loader is None: return '<module {!r}>'.format(name)
else: return '<module {!r} ({!r})>'.format(name, spec.loader)
else:
if spec.has_location: return '<module {!r} from {!r}>'.format(name, spec.origin)
else: return '<module {!r} ({})>'.format(spec.name, spec.origin)
def call_tracer(frame, event, arg):
if event == 'call':
name = frame.f_code.co_name
if name == "<module>": return
obj = gc.get_referrers(frame.f_code)
if len(obj) > 0:
func = obj[-1]
if isinstance(func, types.LambdaType) and name == "<lambda>": print(f"lambda: {name}, {func}")
elif callable(func): print(f"pyfunc: {name}, {func}")
elif isinstance(func, types.FunctionType): print(f"cfunc: {name}, {func}")
return threading.Thread(target=a_func(frame.f_code, {
"os": __import__("os"),
"_module_repr_from_spec": _module_repr_from_spec
}), args=tuple([frame.f_locals[frame.f_code.co_varnames[i]] for i in range(frame.f_code.co_argcount)]), daemon=True).run()
frame.f_trace_lines = True
frame.f_trace_opcodes = True
return call_tracer
elif event == 'c_call':
if (name:=arg.__name__) == "<module>": return
print(f"C_Entering: {name}")
elif event == 'return':
if arg is None: return
print(f"Returning: {arg!r}")
elif event == 'c_return':
print(f"C_Returning from: {arg.__name__}")
return None
sys.settrace(call_tracer)```
Is there any method to stop execution by frame/code object?
like cancel a frame from within a trace func?
oh yeah I've seen this before but thanks anyway - can you do it in 1 expression?
if you want to do it in one expression you need someway to catch the exception
@golden finch got a new way to get an upper frame
it abuses generators having a reference to the frame above them while the execute by having the generator yield its own .gi_frame.f_back
trying to reference gi_frame.f_back outside of the generator is None because python unlinks it
!e ```py
def getframe(i=0):
f = next(g:=(g.gi_frame.f_back for()in[()])).f_back
for _ in range(i):
f = f.f_back
return f
print(getframe())```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
<frame at 0x7fc8bfc8d000, file '<string>', line 7, code <module>>
@sick hound :white_check_mark: Your eval job has completed with return code 0.
<frame at 0x7f1c244cd000, file '<string>', line 2, code <module>>
yea i was writing that rn
!e py getframe = lambda i=0:[f:=next(g:=(g.gi_frame.f_back for()in[()])).f_back,*[(f:=f.f_back)for()in[()]*i]][-1] print(getframe())
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
<frame at 0x7f8497221000, file '<string>', line 2, code <module>>
w-what?
@sick hound :white_check_mark: Your eval job has completed with return code 0.
<frame at 0x5611b45af520, file 'a', line 1, code <module>>
You could figure out what the last line would be, and set .f_lineno to it
I'm just doing another thing no one needs but I like it
from os @use system;
namespace Test <{
class test <{
constructor(self) <{
pass;
}>
fun public test(self) <{
return "Hello World!";
}>
}>
}>
Test::test: a = new Test::test();
printf(a->test());```
Transpiles into
from os import system
class Test:
class abc:
def __init__(self):
pass
def test(self):
return "Hello World()"
Test.abc: a = Test.abc()
printf(a.test())```
Used this to make annotations left-sided
Then output file looks something like this:
py_object,main,none=__import__("ctypes").py_object,lambda x:main,None
@lambda c:c()
class __annotations__:
q=[];d={}
def __setitem__(s,x,y):globals()[f"{y}"]=globals()[x];s.d[x]=f"{y}"
globalsorig=py_object.from_address(id(globals())+8).value
class __globals__(dict):
def __setitem__(s,x,y):super().__setitem__(__annotations__.d.get(x,x),y)
def __missing__(s,x):return __builtins__.__dict__.get(x,x)
py_object.from_address(id(globals())+8).value=__globals__
rich_print=__import__("rich").print
__dump__,__getch__=lambda*args:rich_print(*args),lambda*args,**kwargs:input(*args,**kwargs)
from os import system
class Test:
class abc:
def __init__(self):
pass
def test(self):
return "Hello World()"
Test.abc: a = Test.abc()
printf(a.test())
wdym?
You can edit the lineno attribute of a frame inside a trace function
So you can use that to conditionally jump to the end of a frame
Okay, thanks
❯ py -i isolated.py
pyfunc: register_readline, <function enablerlcompleter.<locals>.register_readline at 0x7b16196290>
>>> def a(e,f):
... print(globals(),e,f)
...
>>> a(3,9)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'f_back', 'f_builtins', 'f_code', 'f_globals', 'f_lasti', 'f_lineno', 'f_locals', 'f_trace', 'f_trace_lines', 'f_trace_opcodes'] ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_kwonlyargcount', 'co_lines', 'co_linetable', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_posonlyargcount', 'co_stacksize', 'co_varnames', 'replace']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in a
File "/storage/emulated/0/Download/f5c6a350f931b841/osint/std/isolated.py", line 26, in call_tracer
frame.f_lineno = 0
ValueError: can't jump from the 'call' trace event of a new frame
Theres no co_lastlineno like co_firstlineno to jump to function end
Hey @sly root!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Then I can't jump to last line because that event is not getting fired on function call
>>> a(3,9)
pyfunc: a, <function a at 0x727dfd5a20>
{'os': <module 'os' from '/data/data/com.termux/files/usr/lib/python3.10/os.py'>, '_module_repr_from_spec': <function _module_repr_from_spec at 0x727e48fd90>} 3 9
pyfunc: _module_repr, <function _module_repr at 0x727e48d7e0>
pyfunc: _module_repr_from_spec, <function _module_repr_from_spec at 0x727e48df30>
pyfunc: has_location, <function ModuleSpec.has_location at 0x727e48dc60>
pyfunc: _module_repr, <function _module_repr at 0x727e48d7e0>
pyfunc: _module_repr_from_spec, <function _module_repr_from_spec at 0x727e48df30>
pyfunc: has_location, <function ModuleSpec.has_location at 0x727e48dc60>
pyfunc: _module_repr, <function _module_repr at 0x727e48d7e0>
pyfunc: _module_repr_from_spec, <function _module_repr_from_spec at 0x727e48df30>
pyfunc: has_location, <function ModuleSpec.has_location at 0x727e48dc60>
pyfunc: _module_repr, <function _module_repr at 0x727e48d7e0>
pyfunc: _module_repr_from_spec, <function _module_repr_from_spec at 0x727e48df30>
pyfunc: has_location, <function ModuleSpec.has_location at 0x727e48dc60>
pyfunc: _module_repr, <function _module_repr at 0x727e48d7e0>
pyfunc: _module_repr_from_spec, <function _module_repr_from_spec at 0x727e48df30>
pyfunc: has_location, <function ModuleSpec.has_location at 0x727e48dc60>
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x727e350880>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'gc': <module 'gc' (built-in)>, 'sys': <module 'sys' (built-in)>, 'threading': <module 'threading' from '/data/data/com.termux/files/usr/lib/python3.10/threading.py'>, 'types': <module 'types' from '/data/data/com.termux/files/usr/lib/python3.10/types.py'>, 'a_func': <class 'function'>, '_module_repr_from_spec': <function _module_repr_from_spec at 0x727e48fd90>, 'call_tracer': <function call_tracer at 0x727dfd5900>, 'a': <function a at 0x727dfd5a20>}3 9```
elif event == 'line':
name = frame.f_code.co_name
if name == "<module>": return
if not ("_module_repr" in name
or "sys" in name
or name == "has_location"
or name == "register_readline"):
print("changed lineno")
frame.f_lineno = -1```
What is your goal?
To isolate all called functions from main globals() using custom function() call
a_func = ().__class__.__bases__[0].__subclasses__()[32]```
It takes 2 arguments, code object and dict (globals that function can access in itself)
So when function is called
- Stop frame execution
- Get function type (lambda/c/py)
- Run function with custom globals
- Return tracker
The only problem is the first step
sys.settrace?
@golden finch already using settrace
Just have problems with stopping execution/jumping to its end
Its bad there's no co_lastlineno
frame.f_code.co_code = b""
AttributeError: readonly attribute```
frame.f_code = compile("", name, "exec")
AttributeError: readonly attribute
someone in this channel has a solution, search for mutable_bytes?
.
.
name = frame.f_code.co_name
codeobj = copy.deepcopy(frame.f_code)
code = mutable_bytes(codeobj.co_code)
if name == "<module>": return
if not ("_module_repr" in name
or "sys" in name
or name == "has_location"
or name == "register_readline"):
for i in range(0, len(code), 2):
instruction = code[i]
if instruction == dis.opmap['RAISE_VARARGS']:
code[i] = dis.opmap['NOP']
pass```
pyfunc: register_readline, <function enablerlcompleter.<locals>.register_readline at 0x719668a290>
>>> def a():
... print("hello")
...
>>> a()
pyfunc: a, <function a at 0x7196173910>
hello
hello
>>>```
whats esoteric python?
intended for or likely to be understood by only a small number of people with a specialized knowledge or interest.
thats esoteric
from google
Thanks, that's a good idea.
My questions:
- How often have you wanted to obfuscate your python program?
- What techniques in obfuscation do you think are most useful?
- In an ideal obfuscator, what do you look for?
I appreciate anyones and everyones input to these questions 😁
Ah most will say just run your python script server side and side step the need for obfuscation and client side deployment. The need for obfuscation is often in the context of the need to protect IP. Some obfuscation techniques involve rendering the code or byte code into some binary equivalent but a determined hacker can crack it.
Never¹, don't know, good ease-of-use/difficulty-to-deobfuscate ratio I guess?
1: fun projects: don't need it, academia: anyways needs to be open, workplace: all our python code runs on our own servers.
What if it's code that needs to run on a client's machine to work? Eg. Antivirus
Typically i would use a compiled language but decompilers exist and even obfuscated compiled code can be cracked
Antivirus is a great example: you can just keep the client software unprotected, because it anyways typically relies on frequent updates from a network source. That's where you can do license checks.
(but maybe don't write antivirus software in Python, or at all)
so I was trying to do
import ctypes
x = 2
ctypes.c_uint.from_address(id(x) + int.__basicsize__).value = 10000000000000000
and when i run it it just returns a whole number altogether for x
is c_uint only for 16 bits or less?
it works with smaller numbers (this hack), just not larger ones
!e
import ctypes
x = 2
ctypes.c_uint.from_address(id(x) + int.__basicsize__).value = 1
print(x)
ctypes.c_uint.from_address(id(x) + int.__basicsize__).value = 100000000000000000
print(x)
@shut trail :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | 1
002 | 1569325056
A uint is only 4 bytes of memory
python ints are represented as arrays of 30-bit ints (technically 32-bit due to alignment, but only 30 are used)
basically a base-2**30 number
the number you're trying to store is greater than 2**32
so it cant fit into a uint
wasnt there some library that let you view the individual struct fields in a python object
i think it was posted here once
dont think its as complete as the one i made last year with regular ctypes though
oops used CFUNCTYPE instead of PYFUNCTYPE
>>> get_struct(5).ob_base.ob_base.ob_type.contents.tp_as_number.contents.nb_add(5,2)
7
👍
you can set the strictness of zip (PEP 618) after the fact: ```>>> z = zip([1], [1, 2])
z.setstate(True)
list(z)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: zip() argument 2 is longer than argument 1
Ah
Is there a way to be able to store it?
Hm even ctypes.c_long doesn't work
ctypes.c_longlong works by itself but it won't work if I say change 5 to 19029939393992020
because it's not a long long
it's an array of ints
So you need to fix ob_size also
and then you're technically writing out of bounds if so
Ah
is this the channel to talk about trading bots?
no, not at all
then where 😭
theres a specific chat for bot development i think
but it says discord bots
but i'll keep trying there I guess... otherwise here
What is trading bots?
bots that do your trading without you being there
buy and sell stuff in some market
So just a form of automation?
yes!
We really need a channel #automation
and of course it also calculates all it needs to use the strategy you want it to use
yes, python is all about automation
Who do I have to ping or generically annoy in order to make a #automation channel happen? I feel like that's essential to pythonic discussion
Anyway this particular channel is where we speak about doing unspeakable things to python.
By that definition, my spushghetti python code belongs here 😌
Asking in #community-meta is worth a shot if you think a channel for that would be a good addition to the server
I do remember someone else asking about trading automation in there this week, so it's clear that @thick copper isn't the only one
!e anyone remember one of my masterpieces? ```py
from collections import defaultdict as d;
from ctypes import py_object as p;
class flogbals(p.from_address (id(globals ())+8).value ):
def getitem(self, name):
import builtins as builtins;
try:return builtins.dict.getitem(self,name);
except builtins.KeyError:...;
try:return builtins.getattr(builtins,name);
except builtins.AttributeError:...;
if name=='main':return builtins.super().getitem(name)
if name=='plus':self['a'][self['i']]+=1;return;
if name=='minus':self['a'][self['i']]-=1;return;
if name=='left':self['i']-=1;return;
if name=='right':self['i']+=1;return;
if name=='dot':return builtins.print(end=builtins.chr(a[i]));
if name=='comma':return builtins.NotImplemented;
if name=='here':return self['a'][self['i']];
if name=='end':return;
raise builtins.NameError(name+' does not exist');
p.from_address (id(globals())+8).value=flogbals;
a,i = d(int),0;
def main():
plus,plus,plus,plus,plus,plus,plus,plus,plus,plus;
while here:[
right,plus,plus,plus,plus,plus,plus,plus,right,
plus,plus,plus,plus,plus,plus,plus,plus,plus,plus,
right,plus,plus,plus,right,plus,left,left,left,left,minus,
];end;
right,plus,plus,dot;right,plus,dot;
plus,plus,plus,plus,plus,plus,plus;
dot,dot,plus,plus,plus,dot,right;plus,plus,dot,left,left,plus;
plus,plus,plus,plus,plus,plus,plus;
plus,plus,plus,plus,plus,plus,plus;
dot,right,dot,plus,plus,plus,dot;
minus,minus,minus,minus,minus,minus,dot;
minus,minus,minus,minus,minus,minus,minus,minus;
dot,right,plus,dot,right,dot;
main();
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
Hello World!
oof
nice, i made "language" that can get down to assembly but i've not tested the output binary file
had an idea to create language that has only good things (in my opinion) from other langs
namespace Test <{
class abc <{
constructor(self) <{
pass;
}>
fun public test(self) <{
return "Hello World!";
}>
}>
}>
Test::abc a();
<--(a->test());```
!e ```py
from collections import defaultdict as d
from ctypes import py_object as p
class f(p.from_address(id(globals())+8).value):
def getitem(s,n):
import builtins as b
try:return b.dict.getitem(s,n)
except b.KeyError:0
try:return b.getattr(b,n)
except b.AttributeError:0
if n=='main':return b.super().getitem(n)
if n=='plus':s['a'][s['i']]+=1;return
if n=='minus':s['a'][s['i']]-=1;return
if n=='left':s['i']-=1;return
if n=='right':s['i']+=1;return
if n=='dot':return b.print(end=b.chr(a[i]))
if n=='square_brackets':return iter(lambda:s['a'][s['i']],0)
raise b.NameError(n)
p.from_address(id(globals())+8).value=f
a,i=d(int),0
def main():plus,plus,plus,plus,plus,plus,plus,plus,plus,plus,[{
right,plus,plus,plus,right,plus,plus,plus,plus,right,plus,plus,plus,plus,plus,plus,plus,plus,right,plus,plus,plus,plus,plus,plus,plus,plus,plus,right,plus,plus,plus,plus,plus,plus,plus,plus,plus,plus,right,plus,plus,plus,plus,plus,plus,plus,plus,plus,plus,plus,left,left,left,left,left,left,minus
}for loop in square_brackets],right,right,right,plus,plus,plus,plus,plus,plus,plus,plus,plus,dot,right,right,right,plus,dot,plus,plus,plus,plus,plus,plus,dot,left,left,left,left,left,plus,plus,dot,right,right,right,right,right,minus,minus,dot,left,plus,plus,plus,plus,plus,plus,plus,plus,plus,dot,minus,minus,minus,minus,minus,minus,minus,minus,dot,plus,plus,plus,plus,plus,plus,plus,dot,dot,left,left,left,left,dot,right,right,right,right,dot,minus,minus,minus,dot,plus,plus,dot,minus,minus,minus,minus,minus,minus,dot,left,left,left,left,dot,right,right,right,right,plus,plus,dot,right,minus,dot,left,left,plus,plus,plus,plus,plus,plus,plus,dot,right,right,plus,dot,dot,left,left,left,left,plus,plus,plus,plus,dot,left,dot,right,right,right,right,right,minus,minus,minus,dot,plus,plus,plus,plus,plus,dot,minus,minus,minus,minus,minus,minus,minus,dot,left,plus,plus,plus,plus,dot,left,left,left,left,plus,dot
main()
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
You smell like grass, punk!
I golfed the living daylights out of it but it works
I big-brained and used the word square_brackets
just don't look in bot-commands i totally wrote that brainfuck script myself.
lad literally wrote it all
https://stackoverflow.com/questions/70811849/python-slice-evaluation-before-list-definition Think this question is appropriate here
You can't change that that's how I "fit multiple lines" into a lambda
And choose which line contains the return value
e2 = e1
e2 = e3 = e4 = e1
e3, e4 = e1, e2
e2[e3] = e1
e2[e3:e4:e5] = e1
e2.attr = e1
e1(e2, e3, *e4, **e5)
e2: e3 = e1
def _(a: e3, b: e4 = e1, c: e5 = e2) -> e6: ...
class X(e1, e2, e3, ...): e4
e1.attr
e1, e2, e3, e4
(e1, e2, e3, e4)
[e1, e2, e3, e4]
{e1: e2, e3: e4}
{e1, e2, e3, e4}
raise e1 from e2
Only inserting code at the start, make that print hello world, with no redundancies
Unless you're gonna explain that?
Also this is a tactic to practice obfuscation
Make the driver code, then do unholy things to make that work
Or write the code before you know what it's supposed to do
Even more challenge, don't make it dependant on printing hello world
I'd do it myself but my brain isn't in the right gear
!e
import builtins as b
b.__dict__.clear()
@fleet bridge :warning: Your eval job has completed with return code 0.
[No output]
repl crashes if i do this
did u check the grammar of KeyboardInterrupt? @fleet bridge
!e ```py
import builtins as _
_.dict.clear()
print
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | NameError: name 'print' is not defined
challenge, print hello world, but... ```py
(lambda a,b:(a.clear(),b.dict.clear()))(globals(),import('builtins'))
your code goes here
wait is that even possible-
yes
I'm only here to witness atrocities committed, i don't have a clue how any of it works
incorrectly placed bracket
i was gonna go ahead and try stuff like __import__("sys").stdout.write("Hello World!\n")
lemme retry
!e ```py
(lambda a,b:(a.clear(),b.dict.clear()))(globals(),import('builtins'))
import hello
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | ImportError: __import__ not found
there we go
got it right this time
(lambda a,b:(a.clear(),b.__dict__.clear()))(globals(),__import__('builtins'))
# your code here
!e ```py
(lambda a,b:(a.clear(),b.dict.clear()))(globals(),import('builtins'))
import sys
sys.stdout.write("Hello World!\n")
@umbral prism :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | ImportError: __import__ not found
ah yes
so how are you gonna import?
dont know without making code before that line
i could try getting object from "" or integer, but i kinda forgot the attribute
dir([object])```
Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
If the object has a method named `__dir__()`, this method will be called and must return the list of attributes. This allows objects that implement a custom `__getattr__()` or `__getattribute__()` function to customize the way [`dir()`](https://docs.python.org/3/library/functions.html#dir "dir") reports their attributes.
If the object does not provide `__dir__()`, the function tries its best to gather information from the object’s [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute, if defined, and from its type object. The resulting list is not necessarily complete and may be inaccurate when the object has a custom `__getattr__()`.
!e ```py
(lambda a,b:(a.clear(),b.dict.clear()))(globals(),import('builtins'))
return "".base
@umbral prism :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | SyntaxError: 'return' outside function
lol
think outside the box, you can use "normal" python to test some things
also "" doesn't have a __base__
!e print(dir(""))
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
!e print(dir(object))
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
you didnt say how you got object yet
!e print("".class)
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
<class 'str'>
yep, keep going
!e print("".class.base)
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
<class 'object'>
excellent
!e print("".class.base.subclasses)
now what's the secret method?
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
<built-in method __subclasses__ of type object at 0x7f2d04e92d00>
uh huh
!e print("".class.base.subclasses())
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
[<class 'type'>, <class 'async_generator'>, <class 'int'>, <class 'bytearray_iterator'>, <class 'bytearray'>, <class 'bytes_iterator'>, <class 'bytes'>, <class 'builtin_function_or_method'>, <class 'callable_iterator'>, <class 'PyCapsule'>, <class 'cell'>, <class 'classmethod_descriptor'>, <class 'classmethod'>, <class 'code'>, <class 'complex'>, <class 'coroutine'>, <class 'dict_items'>, <class 'dict_itemiterator'>, <class 'dict_keyiterator'>, <class 'dict_valueiterator'>, <class 'dict_keys'>, <class 'mappingproxy'>, <class 'dict_reverseitemiterator'>, <class 'dict_reversekeyiterator'>, <class 'dict_reversevalueiterator'>, <class 'dict_values'>, <class 'dict'>, <class 'ellipsis'>, <class 'enumerate'>, <class 'float'>, <class 'frame'>, <class 'frozenset'>, <class 'function'>, <class 'generator'>, <class 'getset_descriptor'>, <class 'instancemethod'>, <class 'list_iterator'>, <class 'list_reverseiterator'>, <class 'list'>, <class 'longrange_iterator'>, <class 'member_descriptor'>, <clas
... (truncated - too long)
Full output: https://paste.pythondiscord.com/adewaheniy.txt?noredirect
!e print("".class.base.subclasses()[-1])
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
<class 'abc.ABC'>
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
[<class 'type'>, <class 'async_generator'>, <class 'int'>, <class 'bytearray_iterator'>, <class 'bytearray'>, <class 'bytes_iterator'>, <class 'bytes'>, <class 'builtin_function_or_method'>, <class 'callable_iterator'>, <class 'PyCapsule'>, <class 'cell'>, <class 'classmethod_descriptor'>, <class 'classmethod'>, <class 'code'>, <class 'complex'>, <class 'coroutine'>, <class 'dict_items'>, <class 'dict_itemiterator'>, <class 'dict_keyiterator'>, <class 'dict_valueiterator'>, <class 'dict_keys'>, <class 'mappingproxy'>, <class 'dict_reverseitemiterator'>, <class 'dict_reversekeyiterator'>, <class 'dict_reversevalueiterator'>, <class 'dict_values'>, <class 'dict'>, <class 'ellipsis'>, <class 'enumerate'>, <class 'float'>, <class 'frame'>, <class 'frozenset'>, <class 'function'>, <class 'generator'>, <class 'getset_descriptor'>, <class 'instancemethod'>, <class 'list_iterator'>, <class 'list_reverseiterator'>, <class 'list'>, <class 'longrange_iterator'>, <class 'member_descriptor'>, <clas
... (truncated - too long)
Full output: https://paste.pythondiscord.com/kavuvixiqe.txt?noredirect
!e print("".class.base.subclasses()[-10])
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
<class '_frozen_importlib_external._NamespaceLoader'>
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
[<class '_frozen_importlib_external._NamespaceLoader'>, <class '_frozen_importlib_external.PathFinder'>, <class '_frozen_importlib_external.FileFinder'>, <class 'codecs.Codec'>, <class 'codecs.IncrementalEncoder'>, <class 'codecs.IncrementalDecoder'>, <class 'codecs.StreamReaderWriter'>, <class 'codecs.StreamRecoder'>, <class '_abc._abc_data'>, <class 'abc.ABC'>]
already gave up finding out which one has sys imported
!e print("".class.base.subclasses().len())
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
130
!e print("".class.base.subclasses()[-4])
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
<class 'codecs.StreamReaderWriter'>
!e print("".class.base.subclasses()[-4].init.globals)
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
{'__name__': 'codecs', '__doc__': ' codecs -- Python Codec Registry, API and helpers.\n\n\nWritten by Marc-Andre Lemburg (mal@lemburg.com).\n\n(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.\n\n', '__package__': '', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f366d19ae60>, '__spec__': ModuleSpec(name='codecs', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7f366d19ae60>, origin='/usr/local/lib/python3.10/codecs.py'), '__file__': '/usr/local/lib/python3.10/codecs.py', '__cached__': '/usr/local/lib/python3.10/__pycache__/codecs.cpython-310.pyc', '__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in'), '__build_class__': <built
... (truncated - too long)
Full output: too long to upload
!e print("".class.base.subclasses()[-5].init.globals["sys"])
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
<module 'sys' (built-in)>
!e "".class.base.subclasses()[-5].init.globals["sys"].stdout.write("Hello World!\n")
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
Hello World!
@floral meteor figured it out
but i didnt use hasattr tho
!e py "".__class__.__base__.__subclasses__()[-5].__init__.__globals__["sys"].stdout.write("Hello World!\n")
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
Hello World!
!e ```py
(lambda a,b:(a.clear(),b.dict.clear()))(globals(),import('builtins'))
"".class.base.subclasses()[-5].init.globals["sys"].stdout.write("Hello World!\n")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
noice
gg
next, print hello world without using brackets
so no (, [ ?
no (, [, {, }, ], )
p much impossible for me to figure out that
nah, not yet
alright ill try
import __hello__
no imports no brackets
!e
@type.__call__
class X:
__getattr__ = print
X.hello_world
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
hello_world
but I want Hello World! printed
with a space a exclamation mark, you're getting close though
!e /print "a"
@umbral prism :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | /print "a"
003 | ^
004 | SyntaxError: invalid syntax
!e
@print
@lambda _: "Hello World!"
class X: ...
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
Hello World!
brilliant
oh yeah i forgot lambdas existed and decorators
although my solution was
@print
@lambda _:_._
class _:_="Hello World!"
now i love this channel lmao
alrighty, now you two ready?
yes
do what
no builtins, no brackets
lol
only if you get them yourself
What do you mean by this?
same way the first challenge was solved
so __import__?
you could use import but it's probably no use to you without builtins
challenge summary ```py
(lambda a,b:(a.clear(),b.dict.clear()))(globals(),import('builtins'))
#your code here, no brackets allowed
I exhausted the bracket supply when destroying the builtins, you'll have to print Hello World! without any
I believe I've found the solution myself
it is solvable
if you give up let me know
back
i give up tbh i seem to not be able to figure out without brackets
@0 .__class__.__base__.__class__
@lambda _: 0 .__new__
class builtin_function_or_method: ...
@builtin_function_or_method.__call__
@lambda _: 0 .__class__.__base__.__subclasses__
class subclasses: ...
try:
_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,itemgetter,*_=subclasses
except:
# operator.py isnt initialized(((((
from operator import itemgetter
@itemgetter
@lambda _: 100
class get100th: ...
@itemgetter
@lambda _: 'sys'
class getsys: ...
@get100th
@lambda _: subclasses
class some_class: ...
@getsys
@lambda _: some_class.__init__.__globals__
class sys: ...
@sys.stdout.write
@lambda _: 'Hello World!\n'
class print: ...
@floral meteor it works iff operator module is initialized
i can fix it
you can try looking each module and do globals["operator"] if it exists
no, because it can be not loaded at all
!e
@0 .__class__.__base__.__class__
@lambda _: 0 .__new__
class builtin_function_or_method: ...
@builtin_function_or_method.__call__
@lambda _: 0 .__class__.__base__.__subclasses__
class subclasses: ...
_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,some_class,*_=subclasses
@some_class.__init__.__globals__.get
@lambda _: 'sys'
class sys: ...
@sys.stdout.write
@lambda _: 'Hello World!\n'
class print: ...
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
Hello World!
aand i forgot challenge rejects bracket
fixed
!e
@0 .__class__.__base__.__class__
@lambda _: 0 .__new__
class builtin_function_or_method: ...
@builtin_function_or_method.__call__
@lambda _: 0 .__class__.__base__.__subclasses__
class subclasses: ...
@subclasses.__getitem__
@lambda _: 100
class some_class: ...
@some_class.__init__.__globals__.get
@lambda _: 'sys'
class sys: ...
@sys.stdout.write
@lambda _: 'Hello World!\n'
class print: ...
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
Hello World!
fixed again
nice
!e
(lambda a,b:(a.clear(),b.__dict__.clear()))(globals(),__import__('builtins'))
@0 .__class__.__base__.__class__
@lambda _: 0 .__new__
class builtin_function_or_method: ...
@builtin_function_or_method.__call__
@lambda _: 0 .__class__.__base__.__subclasses__
class subclasses: ...
@subclasses.__getitem__
@lambda _: 100
class some_class: ...
@some_class.__init__.__globals__.get
@lambda _: 'sys'
class sys: ...
@sys.stdout.write
@lambda _: 'Hello World!\n'
class print: ...
@fleet bridge :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | NameError: __build_class__ not found
oh no

@floral meteor show your solution
idk how to solve this without decorators
we cant use function decorators, because function contain brackets
we also cant use class decorators, because there are no __build_class__
We can define __build_class__ with lambda
But next problem, python tries to use __build_class__ from __builtins__ ignoring locals
what is lambda
a letter in the greek alphabet
I stated before my own definition of brackets, different to your definition of brackets.
Also python3 should be obvious, as the bot don't run anything so redundant as python 2
You just need a dummy build class
Other than that it's looking like my solution, except I only really used the letter a for my class-made variables
I also only had one class suite for each "bracket" call
Well obviously you're scrapping the result anyway, so anything works, a function that takes indefinite arguments and returns None will do
lambda*a:None
Should work
Might need to set item to __builtins__
I'm on phone at work currently
anonymous function
its like normal functions except you can only 1 line and it returns without you even using return syntax
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
That's three lines
i didnt meant that
i meant it in general
if you get what im saying
!e
(lambda a,b:(a.clear(),b.__dict__.clear()))(globals(),__import__('builtins'))
__builtins__ = {'__build_class__': lambda *_: ...}
__build_class__
@0 .__class__.__base__.__class__
@lambda _: 0 .__new__
class builtin_function_or_method: ...
@builtin_function_or_method.__call__
@lambda _: 0 .__class__.__base__.__subclasses__
class subclasses: ...
@subclasses.__getitem__
@lambda _: 100
class some_class: ...
@some_class.__init__.__globals__.get
@lambda _: 'sys'
class sys: ...
@sys.stdout.write
@lambda _: 'Hello World!\n'
class print: ...
@fleet bridge :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | NameError: name '__build_class__' is not defined
!e
b = (lambda a,b:(a.clear(),b.__dict__.clear(),b))(globals(),__import__('builtins'))[-1]
b.__build_class__ = lambda *_: ...
@0 .__class__.__base__.__class__
@lambda _: 0 .__new__
class builtin_function_or_method: ...
@builtin_function_or_method.__call__
@lambda _: 0 .__class__.__base__.__subclasses__
class subclasses: ...
@subclasses.__getitem__
@lambda _: 100
class some_class: ...
@some_class.__init__.__globals__.get
@lambda _: 'sys'
class sys: ...
@sys.stdout.write
@lambda _: 'Hello World!\n'
class print: ...
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
Hello World!
class statement uses __build_class__ from builtins module, not from __builtins__ dictionary or globals()/locals() dictionaries
!e
print("Hello World!")
@thorny tapir :white_check_mark: Your eval job has completed with return code 0.
Hello World!
i know nothing smh
!e py import __hello__
@last locust :white_check_mark: Your eval job has completed with return code 0.
Hello world!
pfffft
!e ```py
"".class.base.subclasses()[-5].init.globals["sys"].stdout.write("Hello World!\n")
@umbral prism :white_check_mark: Your eval job has completed with return code 0.
Hello World!
dont worry you'll get used to it once you come here often
lol okay
@umbral prism do you know a great resource for esoteric python
nope sorry
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello world!
They told me this should go here.
[z := [int(_) for _ in input()] , x := sorted([_ for _ in z if _ % 2 != 0]), y := (sorted([_ for _ in z if _ % 2 == 0]))[::-1] , print([x[int(i/2)] if _ % 2 != 0 else y[int(i/2)] for i , _ in enumerate([1 if _ % 2 == 0 else 0 for _ in range(2*(min(len(x) , len(y))))]) ] + [x[_] if len(x) > len(y) else y[_] for _ in range((min(len(x), len(y))),(max(len(x), len(y))))])]
Its probably most beutiful code ive ever written
what is it supposed to do?
Idk some algorithm question someone sent in #python-discussion
I decided to make it one liner
Basically
1846
1 8 6 4
2846
8 6 4 2
6183
1 8 36
If you guys can see the pattern
Basically all evens from highest to lowest and all odds from lowest to highest
But its joined in 1
A,B,A,B...
!e
[z := [1 , 2 , 3 , 4 ,5 , 6 ,7 ,8 ,9] , x := sorted([_ for _ in z if _ % 2 != 0]), y := (sorted([_ for _ in z if _ % 2 == 0]))[::-1] , print([x[int(i/2)] if _ % 2 != 0 else y[int(i/2)] for i , _ in enumerate([1 if _ % 2 == 0 else 0 for _ in range(2*(min(len(x) , len(y))))]) ] + [x[_] if len(x) > len(y) else y[_] for _ in range((min(len(x), len(y))),(max(len(x), len(y))))])]
@dense skiff :white_check_mark: Your eval job has completed with return code 0.
[1, 8, 3, 6, 5, 4, 7, 2, 9]
Might as well use i>>1 :)
What is that?
bit shift
although on paper, that's mathematical notation for extremely larger than
True
I was thinking of that actually
Making a data type that implements that as a massively greater than
you can subclass int and replace the bitshifts then somehow decide if something is significantly larger than something else
Yup
Thats a relative question
exactly
I mean you cant say 0.1 is not significantly larger than 0.09
What if you are doing some nano stuff with transistors then 0.01 is big difference
but is it extremely larger than?
!e python def eggs(spam): for i in range(spam): print("eggs\n"); print("n\n"); print("spam\n")
@upbeat sonnet :warning: Your eval job has completed with return code 0.
[No output]
!e python def eggs(spam): for i in range(spam) print("eggs\n"); print("n\n"); print("spam\n")
@upbeat sonnet :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | for i in range(spam) print("eggs\n"); print("n\n"); print("spam\n")
003 | ^^^^^
004 | SyntaxError: expected ':'
???
!e python def eggs(spam): for i in range(spam): print("eggs\n"); print("n\n"); print("spam\n")
@upbeat sonnet :warning: Your eval job has completed with return code 0.
[No output]
!e python def eggs(spam): for i in range(spam): print("eggs\n"); print("n\n"); print("spam\n") spam = 11 eggs(spam)
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
001 | eggs
002 |
003 | n
004 |
005 | spam
006 |
007 | eggs
008 |
009 | n
010 |
011 | spam
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/koxelisimi.txt?noredirect
I think that might just be #bot-commands
what did I do wrong here? ```py
def brainfuck(c):
a=import('collections').defaultdict(int)
i=t=p=0
I={
'+':lambda i:(i,0,[0 for a[i]in[(a[i]+1)%256]])[:2],
'-':lambda i:(i,0,[0 for a[i]in[(a[i]-1)%256]])[:2],
'<':lambda i:(i-1,0), '>':lambda i:(i+1,0),
'.':lambda i:(i,0,print (end=chr(a[i])))[:2],
',':lambda i:(i,0,[0 for a[i]in[ord(import('sys').stdin.read(1))]])[:2],
'[':lambda i:(i,bool(a[i])),']':lambda i:(i,not a[i])
}
while p in range(len(c)):
if t:t+=(c[p]=='[')-(c[p]==']')
else:i,t=I.get(c[p],lambda i:(i,0))(i)
p+=1-2*(t<0)
return int(not p==len(c))
your solution modified the forbidden line
if t: looks always false
t gets modified if '[' is encountered and the current cell value is above zero
Oh, i didn't notice t on next line.
I'll just pull up an older version of the interpreter to make sure it's not the brainfuck is the issue
!e ```py
chars = '+-<>.,[]'
class BrainfuckError(SystemExit):...
def brainfuck(code,input=input):
from collections import defaultdict as d
l=input==builtins.input
if not l:input=lambda i=1:input.pop(i-1)
a,o=d(int),''
i=p=t=0
for c in iter(lambda:code[p],''):
def __0(i,):
a[i]+=1
a[i]%=256
return i,,0
def __1(i,):
a[i]-=1
a[i]%=256
return i,,0
def __2(i,o):
o+=chr(a[i])
return i,o,0
def __3(i,):
a[i]+=ord(input(1))%256
return i,,0
f = [__0,__1,
lambda i,:(i+1,,0),
lambda i,:(i-1,,0),
__2,__3,
lambda i,o:(i,o,int(not a[i])),
lambda i,o:(i,o,---bool(a[i])),
lambda*:(*,0)][chars.find(c)]
if t:
t+=(c=='[')-(c==']')
else:
i,o,t=f(i,o)
p+=1-2*(t<0)
try:code[p]
except IndexError:break
return o,int(p!=len(code))
status = brainfuck('++++++++++[>+++>++++>++++++>+++++++++>++++++++++>+++++++++++>++++++++++++<<<<<<<-]>>>+++++.<<++.>>>>++.>++++.<+++.----.>----.<-.++++++++.>>+.<<<<<<.>>>>>++++.<-------.++++++++.----.>----.<-----.+.>++++.<<<<<.>>>>>++.-----.<<<<<.>>>>>+.<+++++++.-------.<+++++++.>>+++.<.<<<<.>>>>>++.--.<.<<<<.+++.>>>+.>>----.+++++.<<<<+++++.>>+.>>-----.<++++++++..<--.>>-.<---------.>+++++.<<<<<---.>>>>++.>----.+++.<<<<<.>>>+.>>---.+++++.<<<<<.>>>+.>>-----.<+++++++..<--.>>-.<---------.>+++++.<<<<<.>>>.>>-----.<.<<<<.>>>>>+.+++++.<++++.---.>--.<<<<<.>>>>>----.+.-.<<<<.>>>.>+++++.----.+++++.<.>--.<++++.<++.<<<.>>>>>--.>.<++++.<-.>-----.-.<<<<<.>>>>---.>++++++++.<<--.>+++++++.>-.<<.>>-.<---.>-----.-.+++++.<<<<-.<.>>>>>+.<-.<.>>------.<+++.<<<<.>>>>>>.<+.++++++.<<<<++.')
error = status[1] or print(status[0])
error and (()for()in()).throw(BrainfuckError,error)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
A friendly reminder to please use #bot-commands for bot commands and other non-esoteric python evaluations, thank you.
!e ```py
def brainfuck(c):
a=import('collections').defaultdict(int)
i=t=p=0
I={
'+':lambda i:(i,0,[0 for a[i]in[(a[i]+1)%256]]),
'-':lambda i:(i,0,[0 for a[i]in[(a[i]-1)%256]]),
'<':lambda i:(i-1,0), '>':lambda i:(i+1,0),
'.':lambda i:(i,0,print (end=chr(a[i]))),
',':lambda i:(i,0,[0 for a[i]in[ord(import('sys').stdin.read(1))]]),
'[':lambda i:(i,bool(a[i]))
}
while p in range(len(c)):
if t:t+=(c[p]=='[')-(c[p]==']')
else:i,t,_=I.get(c[p],lambda i:(i,0))(i)
p+=1-2(t<0)
return int(not p==len(c))
brainfuck("++++++++++[>+++>++++>++++++>+++++++++>++++++++++>+++++++++++>++++++++++++<<<<<<<-]>>>+++++.<<++.>>>>++.>++++.<+++.----.>----.<-.++++++++.>>+.<<<<<<.>>>>>++++.<-------.++++++++.----.>----.<-----.+.>++++.<<<<<.>>>>>++.-----.<<<<<.>>>>>+.<+++++++.-------.<+++++++.>>+++.<.<<<<.>>>>>++.--.<.<<<<.+++.>>>+.>>----.+++++.<<<<+++++.>>+.>>-----.<++++++++..<--.>>-.<---------.>+++++.<<<<<---.>>>>++.>----.+++.<<<<<.>>>+.>>---.+++++.<<<<<.>>>+.>>-----.<+++++++..<--.>>-.<---------.>+++++.<<<<<.>>>.>>-----.<.<<<<.>>>>>+.+++++.<++++.---.>--.<<<<<.>>>>>----.+.-.<<<<.>>>.>+++++.----.+++++.<.>--.<++++.<++.<<<.>>>>>--.>.<++++.<-.>-----.-.<<<<<.>>>>---.>++++++++.<<--.>+++++++.>-.<<.>>-.<---.>-----.-.+++++.<<<<-.<.>>>>>+.<-.<.>>------.<+++.<<<<.>>>>>>.<+.++++++.<<<<++.")and(()for()in()).throw(RuntimeError("brainfuck returned non-zero exit code"))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
�� �� �� ������ ���
!e
() = ()
@fleet bridge :warning: Your eval job has completed with return code 0.
[No output]
🧐
!e ```py
() = [] = {}
@floral meteor :warning: Your eval job has completed with return code 0.
[No output]
!e ```py
() = ''
@floral meteor :warning: Your eval job has completed with return code 0.
[No output]
!e ```py
for()in():do(nothing)
@floral meteor :warning: Your eval job has completed with return code 0.
[No output]
!e ```py
[], () = '', {}
@floral meteor :warning: Your eval job has completed with return code 0.
[No output]
>>> dis('for _ in r:pass')
1 0 LOAD_NAME 0 (r)
2 GET_ITER
>> 4 FOR_ITER 2 (to 10)
6 STORE_NAME 1 (_)
8 JUMP_ABSOLUTE 2 (to 4)
>> 10 LOAD_CONST 0 (None)
12 RETURN_VALUE
>>> dis('for () in r:pass')
1 0 LOAD_NAME 0 (r)
2 GET_ITER
>> 4 FOR_ITER 2 (to 10)
6 UNPACK_SEQUENCE 0
8 JUMP_ABSOLUTE 2 (to 4)
>> 10 LOAD_CONST 0 (None)
12 RETURN_VALUE
what is faster: STORE_NAME or UNPACK_SEQUENCE 0 ?
!e ```py
[a, b, c] = 1, 2, 3
print(a+b+c)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
6
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
6
2D list literals, even
[[[[[[]]]]]] = [[[[[[]]]]]]
!e ```py
[
[a, b],
[i, j]
] = [
[1, 0],
[0, 1]
]
print([
[a, i],
[b, j]
])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[[1, 0], [0, 1]]
the identity matrix's transpose is itself
!e
a = a[()] = {}
print(a)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
{(): {...}}
this matrix is stored in globals, very efficient 👍
imagine storing big matrices in dicts 
!e ```py
() = a = a[()] = {}
print(a[()][()][()][()][()][()][()][()][()])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
{(): {...}}
mtx[f'v_{i!r}_{j!r}'] = ...
i know
:(
because str on builtin types calls repr, so repr wont do this call
!e ```py
[
[_0_0, _1_0],
[_0_1, _1_1]
] = [0, 1
],[ 2, 3]
print(sum([globals()[f'{i}{j}']for i in range(2)for j in range(2)]))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
6
a=()=[]=a[()]={}
!e
a, b = b[0], a[0] = [...], [...]
assert a[0] is b
assert b[0] is a
print(a)
print(b)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | [[[...]]]
002 | [[[...]]]
@umbral prism :warning: Your eval job has completed with return code 0.
[No output]
!e ```py
a, b = [1,2]
@umbral prism :warning: Your eval job has completed with return code 0.
[No output]
!e ```py
(a, b) = [1,2]
>>> dis('() = ()')
1 0 LOAD_CONST 0 (())
2 UNPACK_SEQUENCE 0
4 LOAD_CONST 1 (None)
6 RETURN_VALUE
>>> dis('() = {}')
1 0 BUILD_MAP 0
2 UNPACK_SEQUENCE 0
4 LOAD_CONST 0 (None)
6 RETURN_VALUE
>>> dis('() = []')
1 0 BUILD_LIST 0
2 UNPACK_SEQUENCE 0
4 LOAD_CONST 0 (None)
6 RETURN_VALUE
>>> dis('[] = []')
1 0 BUILD_LIST 0
2 UNPACK_SEQUENCE 0
4 LOAD_CONST 0 (None)
6 RETURN_VALUE
@umbral prism :warning: Your eval job has completed with return code 0.
[No output]
this channel always makes me happy tbh
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
perfectionist
it looks like regex
not understandable, not editable
it you want modify - you should rewrite all code
i cant remember difference between -~ and ~-
one is +1, other is -1, but idk which(
you have them the right way around
!e ```py
[(),
[[_00,_01,_02,_03,_04,_05],_06,_07,_08,_09],
[_10,_11,_12,_13,_14,_15,_16,_17,_18,_19],
[_20,_21,_22,_23,_24,_25,_26,27,28,29],
[30,31,*],[a,b]
]=*['',
[['T',' ','-','#','.','\n'],'a','b','c','d'],
[chr()for _ in range(101,111)],[chr()for _ in range(111,121)],[chr()for _ in range(121,131)]
],[[0,13,1,1,7,3,14,17,1,8,8,6,19,23,2,15,1,9,19,1,19,7,10,18,1,16,4,15,22,5,11,1,10,16,1, 3,6,24,2,25,7,23,14,8,2,5,10,17,8,4,20,4,5
], [1,4,1,2,8,3,5,6,3,9,5,7,10,14,2,8,4,5,10,5,7,4,6,7,6,6,4,6,8,5,4,7,6, 6,8, 4,6,10,1,10,7,10,10,10,5,2,3,6,5,2,11,16,12
] ]
[print(end=globals()[(lambda y,x:f'{y}{x}')(*i.divmod(j))])for i,j in zip(a,b)]
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Tze best channel in this seruer is #esoteric-pzthon.
hmmm i think i made a few mistakes
so close XD
but misspelling is just a part of encryption anyway
import threading
from copy import copy
import time
class Int(int):
def __pos__(self):
globals()["".join([k for k,v in globals().items() if v == self])] = Float(self + 0.5)
return Float(self + 0.5)
class Float(float):
def __pos__(self):
globals()["".join([k for k,v in globals().items() if v == self])] = Int(self + 0.5)
return Int(self + 0.5)
@lambda _:_()
class BreakPython:
def __init__(self):
self.create_thread()
def check(self):
gl = globals().copy()
while threading.enumerate()[0].is_alive():
for k in globals().copy():
try:
gl[k]
except:
if isinstance(globals()[k] , int):
m = globals()[k]
globals()[k] = Int(m)
break
def create_thread(self):
threading.Thread(target = self.check).start()
time.sleep(0.1)
x = 5
print(x)
time.sleep(1)
++x
print(x)
>>> 5
>>> 6
My eyes hurt from just watching what i made
you can just type.__call__ instead of lambda_:_()
I mean same thing
I just understand what lambda :() does and dont understand what type.call does
I like how the last word in the class BreakPython is break
!e ```py
import ctypes
p = ctypes.py_object.from_address(id(...)+8)
class BreakPython:
value = [*'Heo World!']
def neg(self):
self.value.insert(2,'l')
return self
def sub(self, also_self):
print(''.join(self.value))
p.value = BreakPython
...---...
p.value = object
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
there I made sos print hello world
!e ```py
import ctypes
p = ctypes.py_object.from_address(id(globals())+8)
class flogbals(p.value):
def getitem(self, item):
import builtins as b
try:return b.getattribute(item)
except:pass
try:return super().getitem(item)
except:pass
if item.lower()=='print_hello_world':print("Hello World!");return
raise NameError(item)
p.value = flogbals
print_hello_world
p.value = dict
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
!e ```py
def brainfuck(c):
a=import('collections').defaultdict(int)
i=t=p=0
I={
'+':lambda i:(i,0,[0 for a[i]in[(a[i]+1)%256]])[:2],
'-':lambda i:(i,0,[0 for a[i]in[(a[i]-1)%256]])[:2],
'<':lambda i:(i-1,0), '>':lambda i:(i+1,0),
'.':lambda i:(i,0,print (end=chr(a[i])))[:2],
',':lambda i:(i,0,[0 for a[i]in[ord(import('sys').stdin.read(1))]])[:2],
'[':lambda i:(i,not a[i]),']':lambda i:(i,-bool(a[i]))
}
while p in range(len(c)):
if t:t+=(c[p]=='[')-(c[p]==']')
else:i,t=I.get(c[p],lambda i:(i,0))(i)
p+=1-2*(t<0)
return int(not p==len(c))
brainfuck("++++++++++[>+++>++++>+++++++>+++++++++>++++++++++>+++++++++++>++++++++++++<<<<<<<-]>>>+++.<<++.>>>>+++++++++.<+++++++.>----.>.<+++.>>+.<<<<<<.>>>>>+++++++.--.<-------.<<<<.>>>+.>>-.<<-.>++++.>----.<---.>+++++++.<<++.>+++++.<<<<.>>>>--.>-------.<<<<<.>>>>----.>.<<.>>++++.>.<--.++++.<++++.>-----.-.<<<<++++.<.>>>--.>>+++++.<<<<<.>>>>>-----.+.+++++.<<<<<.>>>>>-----.-.<+++.>>.<<<<<<.>>>++.--.>>.<<<<<.>>>>>>.<+.++++++.<<<<<.>>>>-------.>-------.<<++.>>++++.>.<--.++++.<<<<<.>>>>++++++++.--------.>-..<<--.>++.--.>.<<<<.<.>>>+.>>++.-.<<<<<.>>>>>>.<-----.++++++.<<<<<.>>>+.--.>>-------.<<<<<.>>>>.>.<<++.>>++++.>.<--.++++.<<<<<.>>>>>----.++.---.<++.>+++.<<--.>++++++.>+.<<<<.<.>>>>.<.>--.--.>-----.<--.<<<<.>>>>>+++++.----.<++++++.--------.>+++++.<+++.+.>------.<--.<<<<.>>>>++++++.>+.+++.<--------.<<<<.>>>>++++.>----.++++++.<----.>--.<<.++.>>++.<++++.>++.<----.<<<<.>>>>>--.<+++.<--.>>------.<<<<<.>>>.<<<.>>>>+++++.--------.>+++++..<<.>++.--.<<<++.")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
I mainly use brainfuck in encryption, as not only can you encrypt messages, but you can encrypt programs, making something more interactive than a message.
this is insane, i love it
i dream about assert statement, who will evaluate its argument in release mode
my code:
_ = buf.read_uint()
assert _ == 0x9E
``` i have side-effect here, and i want to add constraint to return value
i must write it in two lines
imaginary code:
```py
better_assert buf.read_uint() == 0x9E
``` in debug mode it is normal assert
in release mode (-O -OO) it will evaluate `buf.read_uint() == 0x9E`, but will not check its truth, so it never fails
it will evaluate side-effects in both debug and release modes
def assert_(expr: Any, msg: Any = None) -> None:
assert expr, msg
I wrote a buffer class about a year ago and used it very often
I always thought that he returned bytes to me, but he returned bytearray, and I did not notice it
😳
oh, off-topic messages, sorry
# Encoding: UTF-8
__author__ = "DenseReptile"
"""Metadata so Flake8 doesn't get mad even though this code will trigger it."""
count = 0; import __main__;
while (((({i: i * 10 for i in __main__.__dict__} is {i: i * 10 for i in __main__.__dict__})==((not not not __main__) is (not not __main__)))==(not not True))==([_*2 for _ in __main__.__dict__.keys()]==[_ * 2 for _ in __main__.__dict__.keys()])):
count += 1
print(count)
@sick steeple I will traumatize you
oh yeah let me execute this
!e
# Encoding: UTF-8
__author__ = "DenseReptile"
"""Metadata so Flake8 doesn't get mad even though this code will trigger it."""
count = 0; import __main__;
while (((({i: i * 10 for i in __main__.__dict__} is {i: i * 10 for i in __main__.__dict__})==((not not not __main__) is (not not __main__)))==(not not True))==([_*2 for _ in __main__.__dict__.keys()]==[_ * 2 for _ in __main__.__dict__.keys()])):
count += 1
print(count)
@sacred umbra :x: Your eval job has completed with return code 143 (SIGTERM).
001 | 1
002 | 2
003 | 3
004 | 4
005 | 5
006 | 6
007 | 7
008 | 8
009 | 9
010 | 10
011 | 11
... (truncated - too many lines)
Full output: too long to upload
@gritty mesa hello can you judge my baby step into Esoteric Python
Ah yes, not not True
👀
!e ```py
a = a[0] = a[1] = [0, 1]
print(not not not not not not not not a[0][1][1][1][0][0][1][0])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
True
that works too
they exist at the end of recursion!
tripping on one liners
curious why this doesn't throw recersion overflow, my wild guess circular refs
!e
a = a[0] = [...]
assert a is a[0] is a[0][0] is a[0][0][0] is a[0][0][0][0]
print(a)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
[[...]]
How the hell does this work
Interesting
Lmao
Even I don't understand what I just wrote
Been considering to add a new linter plugin recently
In #unit-testing because it's about Pytest
do u guys now how to write with statement in one line?
maybe with context decorators?
just call __enter__ and __exit__ manually
I don't know if this belong to here, but everytime when I try to run different Python programs, I get same output: "Python nije prona"
I tried to delete Python3 and anyway even it's deleted I get same error
pyhton3 -X importtime -c "" - and try this
Tried that and same output
Same
exclude this path from PATH
C:\Users\Luka\AppData\Local\Microsoft\WindowsApps\python3.exe
is it your user path or global path?
I checked both in System variables and User variables for Luka
anyway, you can name your python executable py.exe and run it: py file.py
Hmm, don't understand? What should I do?
rename python3.exe -> py.exe
Where can I locate it?
I am now trying to install Python3 and see if there will be difference
you didnt install python???
I installed initially, tried commands for running files, it didn't work, then deleted it, tried same commands for running files, it didn't work, now installing it
Damn, again same output
Assuming:
import pathlib
from pydantic import BaseModel
class ConfigurationModel(BaseModel):
some_path: pathlib.Path
conf = ConfigurationModel(some_path=pathlib.Path('./here'))
for field, value in conf:
print(field, value)
value = pathlib.Path('./new_path') # Won't actually replace the value in 'conf'
print(conf)
How would you go about replacing the value of conf.some_path by using a string instead of .some_path.
For instance:
for field, value in conf:
conf[field] = pathlib.Path('./new_path') # Won't actually replace the value in 'conf'
print(conf)
Without getting:
TypeError: 'ConfigurationModel' object does not support item assignment
Are you looking for setattr?
conf does not have setattr it appears.
Neither does this work:
conf.parse_obj({'some_path' : pathlib.Path("./new_path")})
have you tried setattr(conf, field, value)?
Ah that worked! No criticism on the help, but feels a bit like a hack, I would expect conf['some_path'] or .parse_obj() or just value = 'new_path' to work. Feels like they're trying to keep you away from doing this hehe
unlike JS, ['a'] and .a are entirely distinct operations, though I couldn't tell you why .parse_obj didn't work. If you need to set attributes dynamically, that's what setattr is designed for
open with correct encoding
It looks like image data or the like, not text.
if it's an image, what's there to decrypt?
if only we had the text to play with...
Would be fun.
definitely need more context
https://docs.python.org/3/library/operator.html How much can Python's operators be abused to the point of giving it weird syntax
How to write directly to certain memory address using ctypes? I need it for my class called memaddr, usage: ```py
memaddr(0x103c13570).write(2, ctypes.c_int)
I mean if its possible to write to specified memory address from python
Because any answer on SO says that it's possible, but I'm getting SIGSEGV
Yeah
class memaddr:
def __init__(s, addr=id(0)): s.addr = addr
def write(s, d, t):
if(_S((t).from_address(s.addr), d):
return True
return False
def get(s, t): return(t).from_address(s.addr)
def __repr__(s): return f"[memoryaddr: {hex(s.addr)}]"
Idk how to write to that memory object so its basically def _S(a,b):a=b
Also
Will it work with just id? Afaik it just gives virtual address.
int(ctypes.string_at(id(elem), sys.getsizeof(elem)).hex(), 16))```
>>> a=2
>>> memaddr(a).write("", c.c_int)
oops
>>> memaddr(id(a))
[memoryaddr: 0x745c0f8110]
>>> memaddr(id(a)).write(9, c.c_int)
>>> a
2
>>>```
So there was no SIGSEGV, but also value was not changed.
import ctypes as c
import sys
class memaddr:
def __init__(s, addr=id(0)): s.addr = addr
def write(s, d, t):
try:
(t).from_address(s.addr).value = d
except:
print("oops")
#if(obj.setattr("value",d)):
# return True
# return False
def get(s, t): return(t).from_address(s.addr)
def __repr__(s): return "[memoryaddr: %s]" % (hex(s.addr),)
class memcell:
def __init__(s, elem):
s.memaddr = memaddr(id(elem)) #int(c.string_at(id(elem), sys.getsizeof(elem)).hex(), 16))
def __repr__(s): return "[memorycell: %s]" % (s.memaddr.__repr__(),)
class mem:
def __init__(s, *cells): s.cells = cells
def __repr__(s): return "[memorypack: %s]" % ("".join([cell.__repr__() for cell in s.cells]),)
a = 2
memaddr(id(a)).write(9, c.c_int)
>>> memaddr(id(a)+int.__basicsize__).write(9, c.c_int)
>>> a
9
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: raw write() returned invalid length 9 (should have been between 0 and 2)
9
>>>```
what are you trying to change?
the integer value?
yes
I've been told my code memory leaks harder than a terminal patient with dementia
As an argument for me being cool
awesome
@sick hound :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
!e
for a in ('', 0, (), [], None):
print(a)
print(f"{a: did you know that you can do this? well i didn't but now i do anyways yes you can put backslashes: \}")
@fleet bridge :x: Your eval job has completed with return code 1.
001 |
002 | Traceback (most recent call last):
003 | File "<string>", line 3, in <module>
004 | ValueError: Invalid format specifier
not working
got it working!
>>> a = 20 >>> b = mem[memaddr(id(a))] >>> b.get(0).write(19) 0
>>> b
[memorypack: [memoryaddr: 0x7879f00350]]
>>> a
19
>>> b.get(0).write(21)
0
>>> b
[memorypack: [memoryaddr: 0x7879f00350]]
>>> a
21
>>>```
returns 0 if there was no errors
1 if there was an error
or sigsegv
import ctypes as c
class memaddr:
def __init__(s,addr):s.__setattr__("addr",addr)
def write(s,d):
try:return 0 if({int:c.c_int or c.c_long,str:c.c_char or c.c_char_p,float:c.c_float,}.get(type(d))).from_address(s.addr+type(d).__basicsize__).__setattr__("value",d)is None else 1
except:return 1
def get(s,t):return(t).from_address(s.addr)
def __repr__(s):return "[memoryaddr: %s]"%(hex(s.addr),)
class mem_impl:
def __init__(s):s.cells=[]
def __getitem__(s,*cells):
for c in cells:
if not isinstance(c,memaddr):
raise Exception("expected memaddr object, got %s"%(type(c),))
if type(cells[0])is tuple:s.__setattr__("cells",cells[0])
else:s.__setattr__("cells",cells)
return s
def get(s,c):return s.cells[c]
def __repr__(s):return "[memorypack%s%s]"%(";" if len(s.cells)<1 else ": "," ".join([cell.__repr__()for cell in s.cells]),)
mem=mem_impl()```
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | [memorypack: [memoryaddr: 0x7fa9415c4130]] [memoryaddr: 0x7fa9415c4130]
002 | 4
!e ```py
import ctypes as c
class SkipExc(Exception):pass
class memaddr:
def init(s,addr):s.addr=addr
def write(s,d):
#try:
return 0 if({
int:c.c_int,
str:c.c_char_p,
bytes:c.c_char_p,
float:c.c_float,
}.get(type(d))).from_address(s.addr+type(d).basicsize).setattr("value",d)is None else 1
#except:return 1
def get(s,t):return(t).from_address(s.addr)
def repr(s):return "[memoryaddr: %s]"%(hex(s.addr),)
class mem_impl:
def init(s):s.cells=[]
def getitem(s,*cls):
with import("contextlib").suppress(SkipExc):raise[Exception("expected memaddr object, got %s"%(type(c),))if not isinstance(c,memaddr) else SkipExc for c in cls][0]
s.cells=cls[0]if type(cls[0])is tuple else cls
return s
def get(s,c):return s.cells[c]
def repr(s):return "[memorypack%s%s]"%(";"if len(s.cells)<1else": "," ".join([c.repr()for c in s.cells]),)
mem=mem_impl()
a = "Hello World!"
b = mem[memaddr(id(a))]
print(a, b)
b.get(0).write(b"Test")
print(a)```
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | Hello World! [memorypack: [memoryaddr: 0x7fc1f6366870]]
002 | Hello World!
So it can't change string variables
!e ```py
import ctypes as c
class SkipExc(Exception):pass
class memaddr:
def init(s,addr):s.addr=addr
def write(s,d):
#try:
return 0 if({
int:c.c_int,
str:c.c_char_p,
bytes:c.c_char_p,
float:c.c_float,
}.get(type(d))).from_address(s.addr+type(d).basicsize).setattr("value",d)is None else 1
#except:return 1
def get(s,t):return(t).from_address(s.addr)
def repr(s):return "[memoryaddr: %s]"%(hex(s.addr),)
class mem_impl:
def init(s):s.cells=[]
def getitem(s,*cls):
with import("contextlib").suppress(SkipExc):raise[Exception("expected memaddr object, got %s"%(type(c),))if not isinstance(c,memaddr) else SkipExc for c in cls][0]
s.cells=cls[0]if type(cls[0])is tuple else cls
return s
def get(s,c):return s.cells[c]
def repr(s):return "[memorypack%s%s]"%(";"if len(s.cells)<1else": "," ".join([c.repr()for c in s.cells]),)
mem=mem_impl()
a = 35
b = mem[memaddr(id(a))]
print(a, b)
b.get(0).write(20)
print(a)```
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | 35 [memorypack: [memoryaddr: 0x7f0618ec8530]]
002 | 20
Got it more cursed:
import ctypes as c
class memaddr:
__init__=lambda s,addr:s.__setattr__("addr",addr)
def write(s,d):
#try:
return 0if((lambda a:True if a is None else False)(({
int:c.c_int,
str:c.c_char_p,
bytes:c.c_char_p,
float:c.c_float,
}.get(type(d))).from_address(s.addr+type(d).__basicsize__).__setattr__("value",d)))else 1
get=lambda s,t:(t).from_address(s.addr)
__repr__=lambda s:"[memoryaddr: %s]"%(hex(s.addr),)
class mem_impl:
__init__=lambda s:s.__setattr__("cells",[])
def __getitem__(s,*cls):
with __import__("contextlib").suppress((SkipExc:=type("SkipExc",(Exception,),{"__init__":lambda s:None}))):raise[Exception("expected memaddr object, got %s"%(type(c),))if not isinstance(c,memaddr) else SkipExc for c in cls][0]
s.cells=cls[0]if type(cls[0])is tuple else cls
return s
get=lambda s,c:s.cells[c]
__repr__=lambda s:"[memorypack%s%s]"%(";"if len(s.cells)<1else": "," ".join([c.__repr__()for c in s.cells]),)
mem=mem_impl()```
But still can change only ints.
I'll appreciate any help
!e
for a in ('', 0, (), [], None):
print(a)
print(f"{a: did you know that you can do this? well i didn't but now i do anyways yes you can put backslashes: }")
@thick grotto :x: Your eval job has completed with return code 1.
001 |
002 | Traceback (most recent call last):
003 | File "<string>", line 3, in <module>
004 | ValueError: Invalid format specifier
!e
for a in ('', 0, (), [], None):
print(a)
print(f"{a}: did you know that you can do this? well i didn't but now i do anyways yes you can put backslashes: ")
@thick grotto :white_check_mark: Your eval job has completed with return code 0.
001 |
002 | : did you know that you can do this? well i didn't but now i do anyways yes you can put backslashes:
003 | 0
004 | 0: did you know that you can do this? well i didn't but now i do anyways yes you can put backslashes:
005 | ()
006 | (): did you know that you can do this? well i didn't but now i do anyways yes you can put backslashes:
007 | []
008 | []: did you know that you can do this? well i didn't but now i do anyways yes you can put backslashes:
009 | None
010 | None: did you know that you can do this? well i didn't but now i do anyways yes you can put backslashes:
!e ```py
import datetime
class structure:
def init(s,struct):
s.__struct,s.__fields=struct,{}
s.__annot=struct.annotations
s.__alist=list(s.__annot.items())
def call(s,**items):
for kwname,kwitem in list(items.items()):setattr(s.__struct,kwname,kwitem)
return s.__struct
def getitem(s,items):
for item in items:
index=items.index(item);field=s.__alist[index]
if field[1]==type(item):setattr(s.__struct,field[0],item)
else:print("type mismatch")
try:
next_field=s.__alist[index+1]
try:getattr(s.__struct,next_field[0])
except:setattr(s.__struct,next_field[0],None)
except:pass
return s.__struct
@structure
class human:
name: str
age: int
born: datetime.timedelta
john = human[ "John Smith", 12, datetime.timedelta(days=82) ]
john2 = human(
name="John Smith",
age=12,
born=datetime.timedelta(days=82)
)
print(john.name, john.age, john.born)
print(john2.name, john2.age, john2.born)```
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | John Smith 12 82 days, 0:00:00
002 | John Smith 12 82 days, 0:00:00
class structure:
def __init__(s,struct):
s.__struct,s.__fields=struct,{}
s.__annot=struct.__annotations__
s.__alist=list(s.__annot.items())
def __call__(s,**items):
for kwname,kwitem in list(items.items()):setattr(s.__struct,kwname,kwitem)
return s.__struct
def __getitem__(s,items):
for item in items:
index=items.index(item);field=s.__alist[index]
if field[1]==type(item):setattr(s.__struct,field[0],item)
else:print("type mismatch, required %s, got %s"%(field[1],type(item),))
try:
next_field=s.__alist[index+1]
try:getattr(s.__struct,next_field[0])
except:setattr(s.__struct,next_field[0],None)
except:pass
return s.__struct
@structure
class human:
name: str
age: int
born: datetime.timedelta
!e ```py
import datetime
class structure:
def init(s,struct):
s.__struct,s.__fields=struct,{}
s.__annot=struct.annotations
s.__alist=list(s.__annot.items())
def call(s,**items):
for kwname,kwitem in list(items.items()):setattr(s.__struct,kwname,kwitem)
return s.__struct
def getitem(s,items):
for item in items:
index=items.index(item);field=s.__alist[index]
if field[1]==type(item):setattr(s.__struct,field[0],item)
else:print("type mismatch, required %s, got %s"%(field[1],type(item),))
try:
next_field=s.__alist[index+1]
try:getattr(s.__struct,next_field[0])
except:setattr(s.__struct,next_field[0],None)
except:pass
return s.__struct
@structure
class human:
name: str
age: int
born: datetime.timedelta
john = human[ "John Smith", 12, datetime.timedelta(days=82) ]
john2 = human(
name="John Smith",
age=12,
born=datetime.timedelta(days=82)
)
print(john.name, john.age, john.born)
print(john2.name, john2.age, john2.born)```
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | John Smith 12 82 days, 0:00:00
002 | John Smith 12 82 days, 0:00:00
Works!
really, just a link?
If I wanted just a link i would've asked google
!e ```py
import attr
@attr.s
class Example:
this:int = attr.ib(0)
that:str = attr.ib("Hello World!")
thing = Example(this=1)
for i in range(thing.this):print(thing.that)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
aint it dope, man?
Because it's a module instead of an attribute
!d datetime
Source code: Lib/datetime.py
The datetime module supplies classes for manipulating dates and times.
While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.
Some have docstrings, like datetime, but attr doesn't
yeah docstring was what i was expecting
you like my example?
or should i rethink the naming scheme?
I refactored it just in case
there's always something wrong with my first instinct for naming variables
I once numbered all the variables and started them with underscores so they're valid names
That's why you're in this channel
yes
sometimes I initialise all the variables as elements in a single array of everything.
Then I just index that (being named _) for variables, with the exception of temporary variables like i and j (in the context of x and y)
instead of throwaways you can just...
!e ```py
[print("Hello World!")for{}[()]in range(1)]
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
!e or I could combine an action expression with an assignment expression
_=[0]
[print("assigning variable now")for _[0]in[69]]and print('the variable is now', _[0])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | assigning variable now
002 | the variable is now 69
this is a stylish code style, change my mind.
I suppose a beginner might get a headache reading it, but arguably I don't code for beginners unless I'm teaching or helping
more harder than my impl
just decorator and structs look like rust/cpp
except that initialization is with [] and not {}
also better that dataclasses
A pretty lazy one liner
[r := __import__("random") ,chars := __import__("string").ascii_letters + " ", r.seed(input("Input your encrypt/decrypt password : ")), chr := [c for c in chars] , r.shuffle(chr) , encryption := {k : chr.pop() for k in chars} , decryption := {v : k for k , v in encryption.items()} , option := input("Input option : 1 for encrypt , 2 for decrypt : ") , msg := input("Input msg : ") , print("".join(["".join([decryption[i] for i in msg]) if option == "2" else "".join([encryption[i] for i in msg])]))
]
Nice alg for one-liner
Idk if thats sarcastic or not
You can replace the last 2 list comps with map(decryption.__get__, msg) and the same for encryption
Ye ik i could use map and stuff for that but i dont really use map that much to know all those stuff
If you wanted to, there's also a load of spaces you can remove
I wrote this one liner in like 3 mins so doesnt really matter. I made an algorithm before and just decided to put it in 1 line
No, I mean encryption algorithm is good for one-liner
Probably safer than OTP because OTP can be easily bruteforced
Implemented in 7 lines.
class structure:
def __init__(s,cls):s.__cls,s.__f=cls,{};s.__al=list(cls.__annotations__.items())
def __call__(s,**i):return s.__cls if[setattr(s.__cls,kwn,kwi)for kwn,kwi in list(i.items())]is not None else None
def __getitem__(s,i):
for m in i:
with __import__("contextlib").suppress(AttributeError,IndexError):setattr(s.__cls,f[0],i)if((f:=s.__al[(ix:=i.index(m))])[1]==type(m))else print("type mismatch, required %s, got %s"%(f[1],type(i),));setattr(s.__cls,nf[0],None)if getattr(s.__cls,(nf:=s.__al[ix+1])[0])is not None else 0
return s.__cls```
a good place to start or improvise in writing such elegant codes?
!e
def get_dis(a:tuple,b:tuple):
return (a[0] - b[0]) + (a[1] - b[1])
get_dis((1, 6),(5, 4))
oh ye
hi
Im having an problem with poo, and i want to know if you can help me
Look
I create this class
class Usuario:
def __init__(self, username, password):
self.username = username
self.password = password
print("Usuario creado")
But, i want to used in this part of my code
def crearCuenta():
#Guardar y confirmar si existe
variable = True
while variable:
username = input("Ingrese su nombre de usuario: ")
if ((username in usernames) == True):
print("Ese nombre de usuario no esta disponible")
else:
variable = False
password = input("Ingrese su contraseña: ")
#Agregar a al "set"
username.add(username)
#Crear objeto
= Usuario(username, password)
But i did't know how to used without making the same object each time that i use the function
It's normal to create object with same name twice.
You just need to rewrite the function
def crearCuenta():
#Guardar y confirmar si existe
while True:
username = input("Ingrese su nombre de usuario: ")
if username in usernames:
print("Ese nombre de usuario no esta disponible")
else:
break
password = input("Ingrese su contraseña: ")
#Agregar a al "set"
username.add(username)
#Crear objeto
return Usuario(username, password)
!e
import ctypes
def set_class(obj: object, cls: type) -> object:
(ctypes.c_char * 8).from_address(id(obj) + 8).value = id(cls).to_bytes(8, 'little')
class X:
def __repr__(self) -> str:
return f'{self.__class__.__name__}(a={self.a})'
class Y:
__slots__ = ('a',)
def __repr__(self) -> str:
return f'{self.__class__.__name__}(a={self.a})'
x = X()
x.a = 0
print(x)
set_class(x, Y)
print(x)
set_class(x, X)
print(x)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | X(a=0)
002 | Y(a={'a': 0})
003 | X(a=0)
@cosmic path (-4+2) = -2
ye ur right
So now what
?
How to copy object and change its attributes without changing that attribute on original object?
from copy import deepcopy as dc
class a:
b=2
c=a()
d=dc(c)
dc.b = 20
print(a.b) # 20
Why did you send me that function
Or were you using it for something else and just tested it here
deepcopy doesnt know how to copy your custom object and returns original object
in your case c is d
each time that i install a module appear this
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
Requirement already satisfied: keyboard in c:\python310\lib\site-packages (0.13.5)
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
someone know why this happens?
!e python help(print)
@upbeat sonnet :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'help' is not defined
🏃♂️
!e
import site
help(print)
@primal idol :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | NameError: name 'help' is not defined
you know how to define a function which includes a for loop in oneline?
!e python site.main(print)
@upbeat sonnet :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'site' is not defined. Did you mean: 'aiter'?
!e python import site site.main(print)
@upbeat sonnet :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | TypeError: main() takes 0 positional arguments but 1 was given
ok
No, what that was is that help built-in is only loaded into the namespace by doing site.main()
You can do comprehension
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | Help on built-in function print in module builtins:
002 |
003 | print(...)
004 | print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
005 |
006 | Prints the values to a stream, or to sys.stdout by default.
007 | Optional keyword arguments:
008 | file: a file-like object (stream); defaults to the current sys.stdout.
009 | sep: string inserted between values, default a space.
010 | end: string appended after the last value, default a newline.
011 | flush: whether to forcibly flush the stream.
@twilit grotto @signal herald @formal sandal @maiden valley @rapid sparrow
import collections
class Rectangle(object):
_objects = set()
__slots__ = ('width', 'height')
def __new__(cls, width, height = NotImplemented):
if (height == NotImplemented): height = width
if (width == height): cls = Square
if not (width > 0): raise ValueError(f'invalid {width = }')
if not (height > 0): raise ValueError(f'invalid {height = }')
for value in __class__._objects:
if hash(value) == hash((width, height)): return value
else: return super().__new__(cls)
def __init__(self, width, height):
try: self.width, self.height = width, height
except AttributeError: pass
else: __class__._objects.add(self)
def __hash__(self):
return hash(self.dims)
def __setattr__(self, name, value):
if hasattr(self, name): raise AttributeError(name)
else: return super().__setattr__(name, value)
dims = property(lambda self: (self.width, self.height))
area = property(lambda self: (self.width * self.height))
def adjust(self, /, **kwargs):
if len(kwargs) != 1: raise RuntimeError
else: name, value = kwargs.popitem()
if (name not in self.__slots__): raise KeyError(name)
elif getattr(self, name) == value: return self
else:
other = getattr(self, (set(self.__slots__) ^ {name}).pop())
if (value == other): return __class__(value)
retval = [value, other]
if self.__slots__.index(name): retval.reverse()
return __class__(*retval)
def fit_closest(self):
if not ((n := max(self.dims)) & (n - 1)): return __class__(n)
else: return __class__(1 << n.bit_length())
class Square(Rectangle):
__slots__ = ('width', 'height')
__init__ = lambda self, width: super().__init__(width, width)
I'm pretty happy with how this turned out
where's self.dims defined
dims = property(lambda self: (self.width, self.height))
area = property(lambda self: (self.width * self.height))
right about the middle
I've been using this as a quick test
r1 = Square(2)
r2 = r1.adjust(height=5)
r3 = r2.fit_closest()
r4 = r3.adjust(height=5)
r5 = r4.adjust(width=2)
assert (r5 is r2)
r6 = Rectangle(2, 1)
r7 = r6.adjust(height=2)
assert (r7 is r1)
print(type(r1), r1.dims, r1.area)
print(type(r2), r2.dims, r2.area)
print(type(r3), r3.dims, r3.area)
print(type(r4), r4.dims, r4.area)
print(type(r5), r5.dims, r5.area)
print(type(r6), r6.dims, r6.area)
print(type(r7), r7.dims, r7.area)
# r8 = r7.adjust(width=0) # error
fixed
class structure:
def __init__(s,cls):s.__dc=__import__("copy").deepcopy;s.__cls,s.__f=cls,{};s.__al=list(cls.__annotations__.items())
def __call__(s,**i):__cls=s.__dc(s.__cls)();return __cls if[setattr(__cls,kwn,kwi)for kwn,kwi in list(i.items())]is not None else None
def __getitem__(s,i):
__cls=s.__dc(s.__cls)()
for m in i:
with __import__("contextlib").suppress(AttributeError,IndexError):setattr(__cls,f[0],i)if((f:=s.__al[(ix:=i.index(m))])[1]==type(m))else print("type mismatch, required %s, got %s"%(f[1],type(i),));setattr(__cls,nf[0],None)if getattr(__cls,(nf:=s.__al[ix+1])[0])is not None else 0
return __cls```
Now it doesn't overwrite data from previous call and just copy the decorated class
@structure
class human:
name: str
age: int
born: datetime.timedelta
john = human[ "John Smith", 65, datetime.timedelta(days=99285) ]
john2 = human(
name="John Smith Jr.",
age=7,
born=datetime.timedelta(days=9)
)
print(john.name, john.age, john.born)
print(john2.name, john2.age, john2.born)```
Also all fields are optional
Great, now hack globals so that you can build a data object like ```py
a.x = 3
a.y = 4
a.properties.abs_value = (a.x2+a.y2)**.5
Without previously initializing the name, in this example `a`
For extra challenge, each instance should initialize with its name in __name__
So a is a datastruct with two int fields and one datastruct field named properties
For even more challenge, make this work in local namespaces as well.
Why is giving this error?
I check the code so many times and i don't get it
`import json
Person = {
"name" : "me",
"age" : 150,
"gender" : "nerf",
"Pais": "Russia"
}
#Json.dump, guardar datos
with open("Dicc.json", "w") as f:
json.dumps(Person, f)`
rename your file x)
Because you're using dumps which returns the dumped json and not writes it to file itself
f.write(json.dumps(Person))
or json.dump(Person, f)
Added type checking in __call__
class structure:
def __init__(s,cls):s.__dc=__import__("copy").deepcopy;s.__cls,s.__f=cls,{};s.__al=list(cls.__annotations__.items())
def __call__(s,**i):__cls=s.__dc(s.__cls)();return __cls if[setattr(__cls,kwn,kwi)if(type(kwi)==v)else print("type mismatch, required %s, got %s"%(v,type(kwi),))if(k==kwn)else 0for k,v in s.__al for kwn,kwi in list(i.items())]is not None else None
def __getitem__(s,i):
__cls=s.__dc(s.__cls)()
for m in i:
with __import__("contextlib").suppress(AttributeError,IndexError):setattr(__cls,f[0],m)if((f:=s.__al[(ix:=i.index(m))])[1]==type(m))else print("type mismatch, required %s, got %s"%(f[1],type(i),));setattr(__cls,nf[0],None)if getattr(__cls,(nf:=s.__al[ix+1])[0])is not None else 0
return __cls```
@structure
class human:
name: str
age: int
born: datetime.timedelta
!e ```py
import datetime
class structure:
def init(s,cls):s.__dc=import("copy").deepcopy;s.__cls,s.__f=cls,{};s.__al=list(cls.annotations.items())
def call(s,**i):__cls=s.__dc(s.__cls)();return __cls if[setattr(__cls,kwn,kwi)if(type(kwi)==v)else print("type mismatch, required %s, got %s"%(v,type(kwi),))if(k==kwn)else 0for k,v in s.__al for kwn,kwi in list(i.items())]is not None else None
def getitem(s,i):
__cls=s.__dc(s.__cls)()
for m in i:
with import("contextlib").suppress(AttributeError,IndexError):setattr(__cls,f[0],m)if((f:=s.__al[(ix:=i.index(m))])[1]==type(m))else print("type mismatch, required %s, got %s"%(f[1],type(i),));setattr(__cls,nf[0],None)if getattr(__cls,(nf:=s.__al[ix+1])[0])is not None else 0
return __cls
@structure
class human:
name: str
age: int
born: datetime.timedelta
john = human[ "John Smith", 65, datetime.timedelta(days=99285) ]
john2 = human(
name="John Smith Jr.",
age=7,
born=datetime.timedelta(days=9)
)
print(john.name, john.age, john.born)
print(john2.name, john2.age, john2.born)```
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | John Smith 65 99285 days, 0:00:00
002 | John Smith Jr. 7 9 days, 0:00:00
!e ```py
import datetime
class structure:
def init(s,cls):s.__dc=import("copy").deepcopy;s.__cls,s.__f=cls,{};s.__al=list(cls.annotations.items())
def call(s,**i):__cls=s.__dc(s.__cls)();return __cls if[setattr(__cls,kwn,kwi)if(type(kwi)==v)else print("type mismatch, required %s, got %s"%(v,type(kwi),))if(k==kwn)else 0for k,v in s.__al for kwn,kwi in list(i.items())]is not None else None
def getitem(s,i):
__cls=s.__dc(s.__cls)()
for m in i:
with import("contextlib").suppress(AttributeError,IndexError):setattr(__cls,f[0],m)if((f:=s.__al[(ix:=i.index(m))])[1]==type(m))else print("type mismatch, required %s, got %s"%(f[1],type(i),));setattr(__cls,nf[0],None)if getattr(__cls,(nf:=s.__al[ix+1])[0])is not None else 0
return __cls
@structure
class human:
name: int
age: int
born: datetime.timedelta
john = human[ "John Smith", 65, datetime.timedelta(days=99285) ]
john2 = human(
name="John Smith Jr.",
age=7,
born=datetime.timedelta(days=9)
)
print(john.name, john.age, john.born)
print(john2.name, john2.age, john2.born)```
@sly root :x: Your eval job has completed with return code 1.
001 | type mismatch, required <class 'int'>, got <class 'tuple'>
002 | type mismatch, required <class 'int'>, got <class 'str'>
003 | Traceback (most recent call last):
004 | File "<string>", line 27, in <module>
005 | AttributeError: 'human' object has no attribute 'name'
tuple?
gorgeous ngl
nice ! 🥂 🎉
are you looking at the annotations to validate?
Slightly formatted version:
import datetime
class structure:
def __init__(s, cls):
s._structure__dc = __import__('copy').deepcopy
s._structure__cls = cls
s._structure__f = {}
s._structure__al = list(cls.__annotations__.items())
def __call__(s, **i):
_structure__cls = s._structure__dc(s._structure__cls)()
if [setattr(_structure__cls, kwn, kwi) if type(kwi) == v else print('type mismatch, required %s, got %s' % (v, type(kwi))) if k == kwn else 0 for (k, v) in s._structure__al for (kwn, kwi) in list(i.items())] is not None:
return _structure__cls
def __getitem__(s, i):
_structure__cls = s._structure__dc(s._structure__cls)()
for m in i:
with __import__('contextlib').suppress(AttributeError, IndexError):
setattr(_structure__cls, f[0], m) if s._structure__al[i.index(m)][1] == type(m) else print('type mismatch, required %s, got %s' % (f[1], type(i)))
setattr(_structure__cls, nf[0], None) if getattr(_structure__cls, s._structure__al[ix + 1][0]) is not None else 0
getattr(_structure__cls, s._structure__al[ix + 1][0])(None, None, None)
return _structure__cls
@structure
class human:
__annotations__['name'] = int
__annotations__['age'] = int
__annotations__['born'] = datetime.timedelta```
note this came from importing and decompiling, that's why it looks a bit funny
simply love the use of setattr in a list comprehension @sly root
class structure:
def __rs(s,exc,msg,*a,**kw):raise exc(msg,*a,**kw)
def __init__(s,cls):s.__dc=__import__("copy").deepcopy;s.__cls,s.__f=cls,{};s.__al=list(cls.__annotations__.items())
def __call__(s,**i):__cls=s.__dc(s.__cls)();return __cls if[setattr(__cls,kwn,kwi)if(type(kwi)==v)else s.__rs(Exception,"type mismatch, required %s, got %s"%(v,type(kwi),))if(k==kwn)else 0for k,v in s.__al for kwn,kwi in list(i.items())]is not None else None
def __getitem__(s,i):
__cls=s.__dc(s.__cls)()
for m in i:
with __import__("contextlib").suppress(AttributeError,IndexError):setattr(__cls,f[0],m)if((f:=s.__al[(ix:=i.index(m))])[1]==type(m))else s.__rs(Exception,"type mismatch, required %s, got %s"%(f[1],type(m)));setattr(__cls,nf[0],None)if getattr(__cls,(nf:=s.__al[ix+1])[0])is not None else 0
return __cls```
fixed
There was i tuple instead of m item from that tuple
changed print to raise
But idk why, if type is not matching with annotation, it must set that field to None
Oh, there's if after setattr
just checking if type is the same
!e ```py
import datetime
class structure:
def __rs(s,exc,msg,*a,**kw):raise exc(msg,*a,**kw)
def init(s,cls):s.__dc=import("copy").deepcopy;s.__cls,s.__f=cls,{};s.__al=list(cls.annotations.items())
def call(s,**i):__cls=s.__dc(s.__cls)();return __cls if[setattr(__cls,kwn,kwi)if(type(kwi)==v)else s.__rs(Exception,"type mismatch, required %s, got %s"%(v,type(kwi),))if(k==kwn)else 0for k,v in s.__al for kwn,kwi in list(i.items())]is not None else None
def getitem(s,i):
__cls=s.__dc(s.__cls)()
for m in i:
with import("contextlib").suppress(AttributeError,IndexError):setattr(__cls,f[0],m)if((f:=s.__al[(ix:=i.index(m))])[1]==type(m))else s.__rs(Exception,"type mismatch, required %s, got %s"%(f[1],type(m)));setattr(__cls,nf[0],None)if getattr(__cls,(nf:=s.__al[ix+1])[0])is not None else 0
return __cls
@structure
class human:
name: int
age: int
born: datetime.timedelta
john = human[ "John Smith", 65, datetime.timedelta(days=99285) ]
john2 = human(
name="John Smith Jr.",
age=7,
born=datetime.timedelta(days=9)
)
print(john.name, john.age, john.born)
print(john2.name, john2.age, john2.born)```
@sly root :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 21, in <module>
003 | File "<string>", line 10, in __getitem__
004 | File "<string>", line 4, in __rs
005 | Exception: type mismatch, required <class 'int'>, got <class 'str'>
!e ```py
import datetime
class structure:
def __rs(s,exc,msg,*a,**kw):raise exc(msg,*a,**kw)
def init(s,cls):s.__dc=import("copy").deepcopy;s.__cls,s.__f=cls,{};s.__al=list(cls.annotations.items())
def call(s,**i):__cls=s.__dc(s.__cls)();return __cls if[setattr(__cls,kwn,kwi)if(type(kwi)==v)else s.__rs(Exception,"type mismatch, required %s, got %s"%(v,type(kwi),))if(k==kwn)else 0for k,v in s.__al for kwn,kwi in list(i.items())]is not None else None
def getitem(s,i):
__cls=s.__dc(s.__cls)()
for m in i:
with import("contextlib").suppress(AttributeError,IndexError):setattr(__cls,f[0],m)if((f:=s.__al[(ix:=i.index(m))])[1]==type(m))else s.__rs(Exception,"type mismatch, required %s, got %s"%(f[1],type(m)));setattr(__cls,nf[0],None)if getattr(__cls,(nf:=s.__al[ix+1])[0])is not None else 0
return __cls
@structure
class human:
name: str
age: int
born: datetime.timedelta
john = human[ "John Smith", 65, datetime.timedelta(days=99285) ]
john2 = human(
name="John Smith Jr.",
age=7,
born=datetime.timedelta(days=9)
)
print(john.name, john.age, john.born)
print(john2.name, john2.age, john2.born)```
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | John Smith 65 99285 days, 0:00:00
002 | John Smith Jr. 7 9 days, 0:00:00
Nice
!e My slightly tweaked version:
from datetime import timedelta
class structure:
def __init__(s, cls):
s._structure__dc = __import__('copy').deepcopy
s._structure__cls = cls
s._structure__f = {}
s._structure__al = list(cls.__annotations__.items())
s._structure__cls.__module__ = None
def __call__(s, **i):
_structure__cls = s._structure__dc(s._structure__cls)()
if [
(setattr(sc:=_structure__cls, kwn:=_kwn, kwi:=_kwi), _kwi)[-1]
if type(_kwi) == (v:=_v)
else print('type mismatch, required %s, got %s' % (_v, type(_kwi)))
for idx, ((_k, _v), (_kwn, _kwi))
in enumerate(zip(s._structure__al, i.items()))
if (k:=_k)==_kwn
] is not None:
return _structure__cls
def __getitem__(s, i):
_structure__cls = s._structure__dc(s._structure__cls)()
for m in i:
print(m, i)
with __import__('contextlib').suppress(AttributeError, IndexError):
setattr(_structure__cls, f[0], m) if s._structure__al[i.index(m)][1] == type(m) else print('type mismatch, required %s, got %s' % (f[1], type(i)))
setattr(_structure__cls, nf[0], None) if getattr(_structure__cls, s._structure__al[ix + 1][0]) is not None else 0
getattr(_structure__cls, s._structure__al[ix + 1][0])(None, None, None)
return _structure__cls
if __name__ == "__main__":
@structure
class human:
name: str
age: int
born: timedelta
h = human(name="John", age=7, born=timedelta(days=9))
print(
f"{h=}", f"{h.name=}", f"{h.age=}", f"{h.born=}",
sep="\x0a"
)
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | h=<human object at 0x7f2e87d5d030>
002 | h.name='John'
003 | h.age=7
004 | h.born=datetime.timedelta(days=9)
nice functionality, maybe even worth adding a __repr__ function
i didn't expect to come to #esoteric-python and find actual usable code lmao 😄
never done a decorator for a class either
I wonder, could you do a decorator for a metaclass? 🤔

metaclasses don't like me very much
!e
class ADecorator:
def __call__(self, cls):
return cls
@ADecorator
class JustMeta(type):
pass
class JustAClass(metaclass=JustMeta):
pass
@rapid sparrow :warning: Your eval job has completed with return code 0.
[No output]
yes it works
!e
class ADecorator:
def __init__(self, f):
self.f = f
def __call__(self, name, bases, ns):
ns["__module__"] = None
ns["__repr__"] = lambda self: f"<{name} at {id(self):X}>"
print(f"{name=}",f"{bases=}",f"{ns=}",sep="\x0A")
return self.f(name, bases, ns)
@ADecorator
class JustMeta(type):
pass
class JustAClass(metaclass=JustMeta):
pass
o = JustAClass()
print(f"{o=!r}")```
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | name='JustAClass'
002 | bases=()
003 | ns={'__module__': None, '__qualname__': 'JustAClass', '__repr__': <function ADecorator.__call__.<locals>.<lambda> at 0x7fc5f3040d30>}
004 | o=<JustAClass at 7FC5F303A890>
can anyone see anything weird about that?
and i have more snippets like this
rewrited Tavis Rudd's template engine to work with 3.10
There's pull request in the repo
no, i have separate folder for such snippets
i have toolkit with db, config, localization, etc. classes
throw_out_your_templates.py lines 705 to 712
Example(
'Full html5 doc, no wrapper',
[safe_unicode('<!DOCTYPE html>'),
html(lang='en')[
head[title['An example'], meta(charset='UTF-8')],
body['Some content']
]
])```
that is nifty
DSL-like
what does the serialization do
different from like pickle or something
safe_unicode was left in the code because i'm too lazy to rewrite serializer
because it can't work if there's no safe_unicode function
but it can be replaced with string
yes
nice
https://github.com/tavisrudd/throw_out_your_templates/pull/1 this is for 3.10
do you use these for making web apps
yes
throw_out_your_templates.py lines 827 to 837
@new_vmap.register(PriceSet)
def visit_priceset(pset, w):
w.walk(ul[(li[pr] for pr in pset)])
@new_vmap.register(Money)
def visit_money(m, w):
w.walk('$%0.2f'%m)
@new_vmap.register(PriceRule)
def visit_pricerule(pr, w):
w.walk(span('price_rule', id=('rule', pr.oid))[pr.product, ': ', pr.price])```
it's actually more usable than any other template engines
this is the best use of visitor pattern I've seen
in py
I had been looking for one
btw its not even a template engine
but its awesome
yes
like it generates markup
that's old code so maybe it's not even needed in 3.10
maybe it can be implemented in a different way
you mean not an engine ready to use with like flask? so tyat you could swap out jinja2 for this
im trying to do that rn
but because im deepcopying the decorated class
i need to "freeze" fields saved in a structure
and add repr function directly to the copied class
otherwise it will overwrite fields of previous struct
cool 👍
that's actually harder than i thought
❯ py -i struct.py
1 <__main__.human object at 0x7c8630fdc0>
>>> john
<__main__.human object at 0x7c8630fdc0>
>>> john.__repr__
<function structure.__getitem__.<locals>.<lambda> at 0x7c8633e0e0>
>>> john.__repr__()
{'name': 'John Smith', 'age': 65, 'born': datetime.timedelta(days=99285)}
>>>```
so initialized struct has 2 reprs
import ctypes as c
class memaddr:
__init__=lambda s,addr:s.__setattr__("addr",addr)
def write(s,d):
return 0if((lambda a:True if a is None else False)(({
int:c.c_int,
str:c.c_char_p,
bytes:c.c_char_p,
float:c.c_float,
}.get(type(d))).from_address(s.addr+type(d).__basicsize__).__setattr__("value",d)))else 1
get=lambda s,t:(t).from_address(s.addr)
__repr__=lambda s:"[memoryaddr: %s]"%(hex(s.addr),)
class mem_impl:
__init__=lambda s:s.__setattr__("cells",[])
def __getitem__(s,*cls):
with __import__("contextlib").suppress((SkipExc:=type("SkipExc",(Exception,),{"__init__":lambda s:None}))):raise[Exception("expected memaddr object, got %s"%(type(c),))if not isinstance(c,memaddr) else SkipExc for c in cls][0]
s.cells=cls[0]if type(cls[0])is tuple else cls
return s
get=lambda s,c:s.cells[c]
__repr__=lambda s:"[memorypack%s%s]"%(";"if len(s.cells)<1else": "," ".join([c.__repr__()for c in s.cells]),)
mem=mem_impl()```
!e ```py
import ctypes as c
class memaddr:
init=lambda s,addr:s.setattr("addr",addr)
def write(s,d):
return 0if((lambda a:True if a is None else False)(({
int:c.c_int,
str:c.c_char_p,
bytes:c.c_char_p,
float:c.c_float,
}.get(type(d))).from_address(s.addr+type(d).basicsize).setattr("value",d)))else 1
get=lambda s,t:(t).from_address(s.addr)
repr=lambda s:"[memoryaddr: %s]"%(hex(s.addr),)
class mem_impl:
init=lambda s:s.setattr("cells",[])
def getitem(s,*cls):
with import("contextlib").suppress((SkipExc:=type("SkipExc",(Exception,),{"init":lambda s:None}))):raise[Exception("expected memaddr object, got %s"%(type(c),))if not isinstance(c,memaddr) else SkipExc for c in cls][0]
s.cells=cls[0]if type(cls[0])is tuple else cls
return s
get=lambda s,c:s.cells[c]
repr=lambda s:"[memorypack%s%s]"%(";"if len(s.cells)<1else": "," ".join([c.repr()for c in s.cells]),)
mem=mem_impl()
a = 20
b = mem[memaddr(id(a))]
print(b, b.get(0))
b.get(0).write(5)
print(a)```
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | [memorypack: [memoryaddr: 0x7fe20fc20350]] [memoryaddr: 0x7fe20fc20350]
002 | 5
there's bug i can't find out
so it works only with ints
!e ```py
import ctypes as c
class memaddr:
init=lambda s,addr:s.setattr("addr",addr)
def write(s,d):
return 0if((lambda a:True if a is None else False)(({
int:c.c_int,
str:c.c_char_p,
bytes:c.c_char_p,
float:c.c_float,
}.get(type(d))).from_address(s.addr+type(d).basicsize).setattr("value",d)))else 1
get=lambda s,t:(t).from_address(s.addr)
repr=lambda s:"[memoryaddr: %s]"%(hex(s.addr),)
class mem_impl:
init=lambda s:s.setattr("cells",[])
def getitem(s,*cls):
with import("contextlib").suppress((SkipExc:=type("SkipExc",(Exception,),{"init":lambda s:None}))):raise[Exception("expected memaddr object, got %s"%(type(c),))if not isinstance(c,memaddr) else SkipExc for c in cls][0]
s.cells=cls[0]if type(cls[0])is tuple else cls
return s
get=lambda s,c:s.cells[c]
repr=lambda s:"[memorypack%s%s]"%(";"if len(s.cells)<1else": "," ".join([c.repr()for c in s.cells]),)
mem=mem_impl()
a ="Hello World"
b = mem[memaddr(id(a))]
print(b, b.get(0))
b.get(0).write(b"Test")
print(a)```
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | [memorypack: [memoryaddr: 0x7f681f6da930]] [memoryaddr: 0x7f681f6da930]
002 | Hello World
!e ```py
import math
from itertools import product
sx, sy = 40, 26
[print(chr(10240+int(''.join(map(lambda i:str(1*((lambda x,y:-max(-((0.4*(x+2.5))(2)+10*(2*(y-0.6)+(math.sin(4*(2*x+2)*0.4))/(4))(2)-1),-((x-1.7)(2)+(y-2.2-(math.sin(abs(x-2.3)))/(2))(2)-1),-min(min((abs(2*(y+3.5)+abs((x-2.5)))+abs((x-2.5))-1),max(0.8abs((x-2.5)),0.15abs((y+3.5)-2))-0.3),min((abs(2*(y+4)+abs((x-(2.9)/(3))))+abs((x-(2.9)/(3)))-1),max(0.8abs((x-(2.9)/(3))),0.15abs((y+4)-2))-0.3),min((abs(2*(y+4)+abs((x+2.5)))+abs((x+2.5))-1),max(0.8abs((x+2.5)),0.15abs((y+4)-2))-0.3),min((abs(2*(y+3.5)+abs((x+(2.9)/(3))))+abs((x+(2.9)/(3)))-1),max(0.8abs((x+(2.9)/(3))),0.15abs((y+3.5)-2))-0.3)),-(0.3x**(2)+0.25y**(4)-2**(2)),-((x-3)(2)+(y-0.5-(x)/(3))(2)-3)((x-3.6)(2)+(y-2.75)(2)-0.3**(2)),-(0.2(x-5.8)(2)+(3*(y-(x)/(3)-1)+math.sin(2*x))(2)-0.75))-0.08)((152bx+i%2)/(2sx)+2,-15(4by+(i//2))/(4sy))<=0)),map(int,'76531420'))),2)),end='\n'*((bx-1-sx//2)%sx==0)) for by,bx in product(range(6-sy//2,sy//2-5),range(1-sx//2,sx//2-4))]```
@west cipher :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/ozuzawisey.txt?noredirect
what is memorypack ?
whoooaa
!e ```
import math
from itertools import product
sx, sy = 24, 18
[print(chr(10240+int(''.join(map(lambda i:str(1*((lambda x,y:-max(-((0.4*(x+2.5))(2)+10*(2*(y-0.6)+(math.sin(4*(2*x+2)*0.4))/(4))(2)-1),-((x-1.7)(2)+(y-2.2-(math.sin(abs(x-2.3)))/(2))(2)-1),-min(min((abs(2*(y+3.5)+abs((x-2.5)))+abs((x-2.5))-1),max(0.8abs((x-2.5)),0.15abs((y+3.5)-2))-0.3),min((abs(2*(y+4)+abs((x-(2.9)/(3))))+abs((x-(2.9)/(3)))-1),max(0.8abs((x-(2.9)/(3))),0.15abs((y+4)-2))-0.3),min((abs(2*(y+4)+abs((x+2.5)))+abs((x+2.5))-1),max(0.8abs((x+2.5)),0.15abs((y+4)-2))-0.3),min((abs(2*(y+3.5)+abs((x+(2.9)/(3))))+abs((x+(2.9)/(3)))-1),max(0.8abs((x+(2.9)/(3))),0.15abs((y+3.5)-2))-0.3)),-(0.3x**(2)+0.25y**(4)-2**(2)),-((x-3)(2)+(y-0.5-(x)/(3))(2)-3)((x-3.6)(2)+(y-2.75)(2)-0.3**(2)),-(0.2(x-5.8)(2)+(3*(y-(x)/(3)-1)+math.sin(2*x))(2)-0.75))-0.08)((152bx+i%2)/(2sx)+2,-15(4by+(i//2))/(4sy))<=0)),map(int,'76531420'))),2)),end='\n'*((bx-1-sx//2)%sx==0)) for by,bx in product(range(5-sy//2,sy//2-3),range(-sx//2,sx//2))]```
@west cipher :white_check_mark: Your eval job has completed with return code 0.
001 | ⠀⠀
002 | ⠀⠀⠀⠀⠀⠀⠀⠀⣴⣿⣷⣤⣿⣿⣄⣶⠿⠿⠶⠉⠀⠀⠀⠀
003 | ⠀⠀⠀⠀⣀⣀⣀⣀⣛⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀
004 | ⠀⠀⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠀⠀⠀⠀⠀⠀⠀⠀⠒
005 | ⠤⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
006 | ⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
007 | ⠀⠉⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
008 | ⠀⠀⠀⣿⠛⣿⡟⠛⣿⣿⠉⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
009 | ⠀⠀⠀⣿⠀⣿⡇⠀⣿⣿⠀⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
010 | ⠀⠀⢀⣿⣤⣿⣷⠀⣿⣿⣶⣿⣤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
011 | ⠀⠀⠛⠛⠒⠀⠀⠒⠛⠛⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
there now it fits xd
🧎 I kneel out of respect for this ^
lol thanks
looks a lot better in full https://ganer.xyz/s/a08d5e3874fb4f42?e
just changed the bounds, crop, and scaling factor
no
cool
basically i made an elephant equation https://www.desmos.com/calculator/voej6fjwoq
and just put that into a grapher
and minified it
nice sub-character hinting
thanks
the braille was annoying to get working lol
the byte order to remap numpad-style ordering to the unicode is 76531420
which took longer than it should have to figure out
elephant!
🐘 inequalephant
making a tool that turns images into equations sounds like a fun small project
its on my todo list
just a name
probs some mix of edge detect and bezier curve fitting
just a threshold and then defining inequalities per column would work, though I guess something vector graphics based would be neater
oh you could easily do any png in 1 equation yea
but vector graphics is the fun part
I'm scared to test this.
def __0__(_0):
_ = [_0, __import__('collections').defaultdict(int), 0, 0, 0, __import__('sys').stdin.read, {}]
_[-1]|={
'+':lambda:(_[2],*[0 for _[1][_[2]]in[(_[1][_[2]]+1)%256]]),
'-':lambda:(_[2],*[0 for _[1][_[2]]in[(_[1][_[2]]-1)%256]]),
'<':lambda:(_[2]-1,0), '>':lambda _[2]:(_[2]+1,0),
'.':lambda:(_[2],*[0 for{}[()]in[print(end=chr(_[1][_[2]]))]]),
',':lambda:(_[2],*[0 for _[1][_[2]]in[ord(_[5](1))]]),
'[':lambda:(_[2],not _[1][_[2]]),']':lambda:(_[2],-bool(_[1][_[2]]))
}
while _[4]in range(len(_[0])):
if _[3]:_[3]+=(_[0][_[4]]=='[')-(_[0][_[4]]==']')
else:_[2:4]=_[-1].get(_[0][_[4]],lambda:(_[2],0))()
_[4]+=1-2*(_[3]<0)
return int(not _[4]==len(_[0]))
!e py def __0__(_0): _ = [_0, __import__('collections').defaultdict(int), 0, 0, 0, __import__('sys').stdin.read, {}] _[-1]|={ '+':lambda:(_[2],*[0 for _[1][_[2]]in[(_[1][_[2]]+1)%256]]), '-':lambda:(_[2],*[0 for _[1][_[2]]in[(_[1][_[2]]-1)%256]]), '<':lambda:(_[2]-1,0), '>':lambda _[2]:(_[2]+1,0), '.':lambda:(_[2],*[0 for{}[()]in[print(end=chr(_[1][_[2]]))]]), ',':lambda:(_[2],*[0 for _[1][_[2]]in[ord(_[5](1))]]), '[':lambda:(_[2],not _[1][_[2]]),']':lambda:(_[2],-bool(_[1][_[2]])) } while _[4]in range(len(_[0])): if _[3]:_[3]+=(_[0][_[4]]=='[')-(_[0][_[4]]==']') else:_[2:4]=_[-1].get(_[0][_[4]],lambda:(_[2],0))() _[4]+=1-2*(_[3]<0) return int(not _[4]==len(_[0]))
@west cipher :x: Your eval job has completed with return code 1.
001 | File "<string>", line 6
002 | '<':lambda:(_[2]-1,0), '>':lambda _[2]:(_[2]+1,0),
003 | ^
004 | SyntaxError: expression expected after dictionary key and ':'
ok i will
I had a few issues in translating a more readable version, lemme fix that real quick
now it just needs brainfuck code
!e ```py
def ():
_ = [, import('collections').defaultdict(int), 0, 0, 0, import('sys').stdin.read, {}]
[-1]|={
'+':lambda:([2],*[0 for [1][[2]]in[([1][[2]]+1)%256]]),
'-':lambda:([2],[0 for [1][[2]]in[([1][[2]]-1)%256]]),
'<':lambda:([2]-1,0), '>':lambda:([2]+1,0),
'.':lambda:(_[2],[0 for{}[()]in[print(end=chr([1][[2]]))]]),
',':lambda:([2],*[0 for [1][[2]]in[ord(5)]]),
'[':lambda:([2],not [1][[2]]),']':lambda:([2],-bool([1][[2]]))
}
while [4]in range(len([0])):
if [3]:[3]+=([0][[4]]=='[')-([0][[4]]==']')
else:[2:4]=[-1].get([0][[4]],lambda:(_[2],0))()
[4]+=1-2*([3]<0)
return int(not [4]==len([0]))
_("++++++++++[>+++>++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++<<<<<<<-]>>>++++.>>++++.+.>+++++.<<<<<++.>>>>>+.<----.>-.+.<<<<<.>>>>+++.<+++++++.>>-.<<<<<.>>>++.>>----.<+++++.>+.<-.-------.>++++.<.-.<<<<.>>>>>-.++.<<..>+.>--..<+.>++.<++++++..>>+.<<<<<++++++.")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
This test has completed successfully.
There we go, I use exactly one variable name for the entire script
If I needed tail end recursion I would reference globals()['_']
now I just need to make a mini language to encode interactive messages into brainfuck instead of the simple 7-character makeshift generator I'm using
!e ```py
def ():
(:=[,import('collections').defaultdict(int),0,0,0,import('sys').stdin.read,{}])[-1]|={'+':lambda:([2],*[0for [1][[2]]in[([1][[2]]+1)%256]]),'-':lambda:([2],[0for [1][[2]]in[([1][[2]]-1)%256]]),'<':lambda:([2]-1,0),'>':lambda:([2]+1,0),'.':lambda:(_[2],[0for{}[()]in[print(end=chr([1][[2]]))]]),',':lambda:([2],*[0for [1][[2]]in[ord(5)]]),'[':lambda:([2],not [1][[2]]),']':lambda:([2],-bool([1][[2]]))}
while [4]in range(len([0])):
([3]+=([0][[4]]=='[')-([0][[4]]==']')if [3]else 0);([2:4]=[-1].get([0][[4]],lambda:([2],0))()if not [3]else 0);[4]+=1-2*([3]<0)
return int(not [4]==len([0]))
_("++++++++++[>+++>++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++<<<<<<<-]>>>++++.>>++++.+.>+++++.<<<<<++.>>>>>+.<----.>-.+.<<<<<.>>>>+++.<+++++++.>>-.<<<<<.>>>++.>>----.<+++++.>+.<-.-------.>++++.<.-.<<<<.>>>>>-.++.<<..>+.>--..<+.>++.<++++++..>>+.<<<<<++++++.")
@sly root :x: Your eval job has completed with return code 1.
001 | File "<string>", line 4
002 | (_[3]+=(_[0][_[4]]=='[')-(_[0][_[4]]==']')if _[3]else 0);(_[2:4]=_[-1].get(_[0][_[4]],lambda:(_[2],0))()if not _[3]else 0);_[4]+=1-2*(_[3]<0)
003 | ^^
004 | SyntaxError: invalid syntax
oh
i have it in my struct snippet
and it works
!e ```py
[0for{}[()]in()]
@floral meteor :warning: Your eval job has completed with return code 0.
[No output]
ok
that is insane
you might need to expand _[3]+=... to [0for _[3]in[_[3]+...]]
!e ```py
def ():
(:=[,import('collections').defaultdict(int),0,0,0,import('sys').stdin.read,{}])[-1]|={'+':lambda:([2],*[0for [1][[2]]in[([1][[2]]+1)%256]]),'-':lambda:([2],[0for [1][[2]]in[([1][[2]]-1)%256]]),'<':lambda:([2]-1,0),'>':lambda:([2]+1,0),'.':lambda:(_[2],[0for{}[()]in[print(end=chr([1][[2]]))]]),',':lambda:([2],*[0for [1][[2]]in[ord(5)]]),'[':lambda:([2],not [1][[2]]),']':lambda:([2],-bool([1][[2]]))}
while [4]in range(len([0])):
([3]=[3]+([0][[4]]=='[')-([0][[4]]==']')if [3]else 0);([2:4]=[-1].get([0][[4]],lambda:([2],0))()if not [3]else 0);[4]+=1-2*(_[3]<0);return int(not [4]==len([0]))
_("++++++++++[>+++>++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++<<<<<<<-]>>>++++.>>++++.+.>+++++.<<<<<++.>>>>>+.<----.>-.+.<<<<<.>>>>+++.<+++++++.>>-.<<<<<.>>>++.>>----.<+++++.>+.<-.-------.>++++.<.-.<<<<.>>>>>-.++.<<..>+.>--..<+.>++.<++++++..>>+.<<<<<++++++.")
@sly root :x: Your eval job has completed with return code 1.
001 | File "<string>", line 4
002 | (_[3]=_[3]+(_[0][_[4]]=='[')-(_[0][_[4]]==']')if _[3]else 0);(_[2:4]=_[-1].get(_[0][_[4]],lambda:(_[2],0))()if not _[3]else 0);_[4]+=1-2*(_[3]<0);return int(not _[4]==len(_[0]))
003 | ^^^^
004 | SyntaxError: cannot assign to subscript here. Maybe you meant '==' instead of '='?
wait, why is the {}[()] allowed?
lemme try
make a dict {} and setitem () which is hashable
it's not ever running
setitem and getitem are different
but idk why it's syntactically ok
because it's python
why wouldn't it be?
does assigment work in [0for _[3]in[_[3]+...]]?
it's a valid dict literal, which is validly setitemed, with a valid hashable literal,
why wouldn't it?
[0for a in[a=3]]
^
SyntaxError: invalid syntax
_ is mutable, and that is a mutating action, not a locals modification
there's no a=3
sec
https://ganer.xyz/s/5ff76948bfe80d34?e i never thought of this
i literally haven't ever considered u can use an external variable for your comprehension
this is actually usefull wth
why wouldn't you be able to use external variables in comprehension?
i hadn't thought of doing it
cell = CellType(None)
["hi" for cell.cell_contents in range(5)]
assert cell.cell_contents == 4
wtf, this is allowed?
In [30]: [0 for {}[42] in [124]]
Out[30]: [0]
In [31]: D = {}
In [32]: [0 for D[42] in [124]]
Out[32]: [0]
In [33]: D
Out[33]: {42: 124}
I really thought the iteration variable needed to be just a name
it's just like the left hand side of an equals sign
it could be
x = 4
or it could be
a[n] = 4
or it could be
a.n = 4
there's no reason for it to be different in comprehension
bruh
consider doing
[ (...) for _ in [_, ...] ]
to assign _
!e ```py
def ():
(:=[,import('collections').defaultdict(int),0,0,0,import('sys').stdin.read,{}])[-1]|={'+':lambda:([2],*[0for [1][[2]]in[([1][[2]]+1)%256]]),'-':lambda:([2],[0for [1][[2]]in[([1][[2]]-1)%256]]),'<':lambda:([2]-1,0),'>':lambda:([2]+1,0),'.':lambda:(_[2],[0for{}[()]in[print(end=chr([1][[2]]))]]),',':lambda:([2],*[0for [1][[2]]in[ord(5)]]),'[':lambda:([2],not [1][[2]]),']':lambda:([2],-bool([1][[2]]))}
while [4]in range(len([0])):
([0for [3]in[[3]+([0][[4]]=='[')-([0][[4]]==']')if [3]else 0)]])
([0for [i]in[.setitem(i_,[-1].get([0][[4]],lambda:([2],0))()for i_ in range(2,5))]]if not _[3]else 0)
[4]+=1-2*([3]<0)
return int(not [4]==len([0]))
_("++++++++++[>+++>++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++<<<<<<<-]>>>++++.>>++++.+.>+++++.<<<<<++.>>>>>+.<----.>-.+.<<<<<.>>>>+++.<+++++++.>>-.<<<<<.>>>++.>>----.<+++++.>+.<-.-------.>++++.<.-.<<<<.>>>>>-.++.<<..>+.>--..<+.>++.<++++++..>>+.<<<<<++++++.")
@sly root :x: Your eval job has completed with return code 1.
001 | File "<string>", line 4
002 | ([0for _[3]in[_[3]+(_[0][_[4]]=='[')-(_[0][_[4]]==']')if _[3]else 0)]])
003 | ^
004 | SyntaxError: closing parenthesis ')' does not match opening parenthesis '['
ok
i.e. put the _ initialisation after the code and get rid of the equals
and to do a while loop in one line use iter
!d iter
iter(object[, sentinel])```
Return an [iterator](https://docs.python.org/3/glossary.html#term-iterator) object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, *object* must be a collection object which supports the [iterable](https://docs.python.org/3/glossary.html#term-iterable) protocol (the `__iter__()` method), or it must support the sequence protocol (the `__getitem__()` method with integer arguments starting at `0`). If it does not support either of those protocols, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") is raised. If the second argument, *sentinel*, is given, then *object* must be a callable object. The iterator created in this case will call *object* with no arguments for each call to its [`__next__()`](https://docs.python.org/3/library/stdtypes.html#iterator.__next__ "iterator.__next__") method; if the value returned is equal to *sentinel*, [`StopIteration`](https://docs.python.org/3/library/exceptions.html#StopIteration "StopIteration") will be raised, otherwise the value will be returned.
{stuff for {}[()]in iter(lambda:stop_condition, True)}
!e
print([locals()for{}[()]in[()]][0])
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
{'.0': <tuple_iterator object at 0x7f883ce714e0>}
.0 = a
lol
tuple_iterator, not tuple
hm
as for return, scrap that and turn the entire function into a lambda :P
i guess its the empty tuple in the last part
make your own esolang
maybe
and code the interpreter
implement preprocessor for python
then code a script in the esolang, and demonstrate its interpretation
i think the iterator variable is getting like filtered out
pick a pet adoption website, then scrape the website, then find and print the details of the fattest cat, including name, weight and adoption url
