#esoteric-python
1 messages ยท Page 127 of 1
lmao
you wanna bet
although the bot cannot import custom scripts
ยฏ_(ใ)_/ยฏ
unless you just completely replaced import in which case still dead easy
you can just store state inside the module and use a module wide __getattr__
__getattr__ does not get called every time, just the first time an attribute is accessed IIRC
oh nvm
oh, only for relative imports
!e
import __main__ as m
def __getattr__(name):
print('get', name)
m.a
m.b
m.a
m.b
from __main__ import a
from __main__ import b
from __main__ import a
@proper vault :white_check_mark: Your eval job has completed with return code 0.
001 | get a
002 | get b
003 | get a
004 | get b
005 | get __path__
006 | get a
007 | get a
008 | get __path__
009 | get b
010 | get b
011 | get __path__
yeah, doesn't quite work
I wonder
!e ```py
import main as m
@type.call # an expression post-3.9
class all():
def getitem(*_):
return # should error
from main import *
@earnest wing :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 6, in <module>
003 | TypeError: Item in __main__.__all__ must be str, not NoneType
i already asked, but... does exist a program choose alone the good python --version for interpreter in my IDE in fonction of module using inside the *.py ?
import builtin ?
does anyone here ?....hello
Sorry but that's completely unintelligible to me
Most IDEs will automatically choose the newest installed python on your $PATH if that's what you're asking
@sick hound ^
But I don't think that's a question pertaining to this channel either. Sounds more like an #editors-ides question
i mean...if for exemple speedtest module is inside my programe and my ide is programing for running with python3.9 and this speedtest its running only with python2.7>>>>each time i need to change setting of my interpreter and if i run an other program, i need chang again...do you anderstand ?
@sick hound please read the channel topic ๐
how to drop duplicate columns after joining dataframe in pyspark dataframe
@gaunt ferry @sick hound this is not a help channel
please see #โ๏ฝhow-to-get-help
Esotericism (from ancient Greek esoteros, "interior") is the set of secret teachings reserved for initiates
Bruh
(lambda: "esoteric python")()``` it literally explains what it means by esoteric
or just scroll up and see what others have posted lol
#hi
def ReallyAdvancedMathCalculationThatIsReallyImportant(WhetherOrNotToReturnTheCorrectResult: bool):
if WhetherOrNotToReturnTheCorrectResult is not False or WhetherOrNotToReturnTheCorrectResult is True:
#Fuck you
WhetherOrNotToReturnTheCorrectResult = True
if True is True and True is not False or WhetherOrNotToReturnTheCorrectResult is True:
if 1 + 1 == 2:
return 0.1
else:
#HOW
#Fuck you
return __import__("math".replace("math","random")).randint(10000000000, 10000000001)
asyncio =\
__import__\
("\ntime".replace("\n",""))
for ForLoopVariable in [None, None, None, None]:
if ForLoopVariable is None or None or None or None or None or None or None or None:
asyncio.sleep(ReallyAdvancedMathCalculationThatIsReallyImportant\
(WhetherOrNotToReturnTheCorrectResult=False))
print("This message must be printed or else.".replace("This message must be printed or else.", "\n"))
class ReallyStupidFuckingThing:
def __init__(self): self = self; self._ = ["avery"
, "was", "here"
]
class TheStupidistFuckingThing(ReallyStupidFuckingThing):
def __init__(self) -> None:
super().__init__()
def TheFinaleOfStupidFuckingThings(self, true: bool = True):
if true is not True or true is False: true = True
if true is not None or true is not False or true is True and true is not None:
return self._
_ = TheStupidistFuckingThing().TheFinaleOfStupidFuckingThings(False)
print\
(" ".join(_)\
) ;
sys = __import__\
("plat\n\n\n\n\n\n\n\n\n\n\nform".replace("\n","\n".replace("\n","")))
_________ = "this pytho\nn ver\nsion is".replace("\n","") + " ".replace(
" ",
""
)
reallyImportantString = "abcde".replace(
"a", "").replace(
"b", "").replace("c", "").\
replace("d", "").replace(
"e",
"");
def NoneIsNoneOrNoneIsNoneAndNoneIsNone():
if None is None or None is not None or None is None and None is None and None is None:
return None is not None or None is None and None is None
if NoneIsNoneOrNoneIsNoneAndNoneIsNone() or NoneIsNoneOrNoneIsNoneAndNoneIsNone() is not False:
print(
\
_________,
\
sys.python_version(
)
)
hello does this count
Python 3.9.6 (default, Jun 29 2021, 06:20:32)
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def ReallyAdvancedMathCalculationThatIsReallyImportant(WhetherOrNotToReturnTheCorrectResult: bool):
... if WhetherOrNotToReturnTheCorrectResult is not False or WhetherOrNotToReturnTheCorrectResult is True:
... #Fuck you
... WhetherOrNotToReturnTheCorrectResult = True
... if True is True and True is not False or WhetherOrNotToReturnTheCorrectResult is True:
... if 1 + 1 == 2:
... return 0.1
... else:
... #HOW
... #Fuck you
... return __import__("math".replace("math","random")).randint(10000000000, 10000000001)
...
>>> from fishhook import hook_cls, orig
>>> @hook_cls(int)
... class int_hook:
... def __hash__(self):
... return self
... def __eq__(self, other):
... if self is 2 and other is 2:
... return False
... return orig(self, other)
...
<stdin>:6: SyntaxWarning: "is" with a literal. Did you mean "=="?
<stdin>:6: SyntaxWarning: "is" with a literal. Did you mean "=="?
>>> 1 == 1
True
>>> 2 == 2
False
>>> ReallyAdvancedMathCalculationThatIsReallyImportant(0)
10000000001
>>> ``` @tiny meteor
oh no
surely there must be some way to override int.__add__ easily
you can use fishhook
It is secret by obfuscation
@rugged sparrow are you there?
Fishhook swaps pointers around
To hook builtin classes
@golden finch I can send a smaller hook implementation in an hour or 2
okay
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/fakaqudona.py @golden finch this is an independent hook code
ENDIAN = ['little','big'][1%memoryview(b'\1\0').cast('h')[0]]```
You can also get the byte structure by doing ```py
ENDIAN = sys.byteorder```
it's the same thing
goal was no imports @tribal moon
ah then that's a really clever way ๐
@golden finch it uses a bug involving closures to get rw access to python memory
it then toggles a flag in the class to allow attribute modification, sets the attribute, then untoggles the flag
it also has a pure python implementation of PyTypeModified that triggers subclasses to update
You should write your own tutorial on all of this it'd be a really nice read
I think I might need a rundown of each line, wow
from start to end
r:=iter(range(2**63-1) - why not use iter(int,1)?
im making a write up
sweet, thanks
https://paste.pythondiscord.com/eyupudatag.py @tribal moon @golden finch
thanks, will try and read
Just watching an old PyCon talk and they mentioned an izip() that acts like zip() but without the double memory cost incurred by inserting the items into the zip() object. Is this still a feature? I can't find it in the current docs...
zip now does that
For the most part, all similar builtin functions now compose iterators.
map, filter, reversed, ...
sorted returns a list, but it does take an iterable
Sorry, I meant reversed
I don't think you can stream a sorting algorithm in nlogn time
yeah, you can't
All hail the iterable!
well, technically you ca-
yeah buffer cheats
?
!e
def func():
pass
func.__call__ = lambda: print('hi')
func()
@woven bridge :warning: Your eval job has completed with return code 0.
[No output]
youll have to check the source to see whats happening
its probably like how 1+1 wont care about int.__add__ and will just do some optimized addition specific to ints
the interpreter cheats
ah didn't know that
@woven bridge tee just puts the iterable in a buffer.
the interpreter doesn't call dunder methods on integer literals?
yeah theres a talk called 'how python is shaped by leaky internals' that covers this
!e
def c():print('c')
c()
c.__call__()
c.__call__ = print('not c')
c()
c.__call__()
@simple crystal :x: Your eval job has completed with return code 1.
001 | c
002 | c
003 | not c
004 | c
005 | Traceback (most recent call last):
006 | File "<string>", line 6, in <module>
007 | TypeError: 'NoneType' object is not callable
you sure?
ty
all good
as in, will it buffer the entire iterable?
thats kinda disappointing
wait these look like what I already knew c-defined dunders are
@woven bridge it depends on what order you consume it in, it is slightly optimised if you do things when it can omit a buffer, but from what I can tell the algo wouldn't do that
yeah, so like if you had two arbitrary objects x and y youd expect x+y to result in the dunder call x.__add__(y) or y.__radd__(x). but the interpreter eschews this when x and y are ints for optimization. similarly, theres probably an optimization to avoid the overhead of using a function's __call__ dunder to speed up function calls.
idk how calls work tho
but I should have checked the result of changing __call__ haha
I'm also not sure where different behavior gets injected there, I think it's still maybe a slot even?
so in armin's talk there's a slide where he shows the implementation of the BINARY_ADD instruction that has an optimization case which checks for the operands are ints and bypasses the PyNumber_Add stuff which is iirc where things like slots are looked up.
admittedly this is from 2016 so things might be different now
hmmm wish I knew where this code was
ceval.c, theres a huge switch statement
theres some weird shit going on in the main branch with quickening that i dont really understand yet
so you could also switch to stable version branches on the repo and check their ceval.c instead
https://github.com/python/cpython/blob/main/Python/ceval.c#L4609 heres the case for CALL_FUNCTION for example
!e ```py
import timeit
def test1():
bool([])
def test2():
not not []
print(timeit.timeit(test1, number=1000000))
print(timeit.timeit(test2, number=1000000))```
@steel siren :white_check_mark: Your eval job has completed with return code 0.
001 | 0.35323254857212305
002 | 0.22308364789932966
well thanks for the info I missed that int he talk till you pointed it out
and yeah main branch is way different now
apparently
Python/ceval.c lines 1999 to 2012
TARGET(BINARY_ADD): {
PREDICTED(BINARY_ADD);
STAT_INC(BINARY_ADD, unquickened);
PyObject *right = POP();
PyObject *left = TOP();
PyObject *sum = PyNumber_Add(left, right);
SET_TOP(sum);
Py_DECREF(left);
Py_DECREF(right);
if (sum == NULL) {
goto error;
}
DISPATCH();
}```
oo ok nice, so they took that micro-optimization out
lmao really? TIL
oh hold on...
why no preview 
TARGET(BINARY_ADD_INT): {
PyObject *left = SECOND();
PyObject *right = TOP();
DEOPT_IF(!PyLong_CheckExact(left), BINARY_ADD);
DEOPT_IF(Py_TYPE(right) != Py_TYPE(left), BINARY_ADD);
STAT_INC(BINARY_ADD, hit);
record_hit_inline(next_instr, oparg);
PyObject *sum = _PyLong_Add((PyLongObject *)left, (PyLongObject *)right);
SET_SECOND(sum);
Py_DECREF(right);
Py_DECREF(left);
STACK_SHRINK(1);
if (sum == NULL) {
goto error;
}
DISPATCH();
_PyLong_Add doesnt care about slots, i dont think
quickening
some instructions are gonna have their own specializations
that they get swapped out for after some observation of how the code runs? at least thats what i got from reading the pep
!pep 659
not sure if cases like 1+1 will get compiled using BINARY_ADD_INT or still rely on quickening to specialize later
Quickened code has number of advantages over the normal bytecode:
It can be changed at runtime
It can use super-instructions that span lines and take multiple operands.
It does not need to handle tracing as it can fallback to the normal bytecode for that.
these arent advantages for #esoteric-python
(and actually not quite sold that theyre advantages in general tbh)
gonna have to change all bytecode hacks to now take quickening into account
It shouldn't really matter actually, the regular bytecodes will remain (or equivalents), all quickening does is record stats about the data types used, then in code which is run often swap out the bytecode for optimised versions that are fixed type or whatever. Stuff will get compiled using the regular bytecode.
thats not quite the issue im seeing. lets say you write a bytecode hack that alters the bytecode of a frame by mutating the memory of the code object directly, suddenly you have to take into account quickening having occurred and some of the code you altered no longer being ran because it gets skipped due to optimization, i.e. you swapped out a BINARY_ADD for something else but the quickener has already decided to run a specialized version of BINARY_ADD at that instruction, so your change is ignored (that is unless the quickener mutates the original code, which im assuming it doesnt since it has to be able to fall back if necessary)
theres also problems even if youre not modifying the code since specializations wont let you make the same assumptions about what an instruction will always do any more
This is most likely a bug, and python should forbid setting __call__
but also when an object is called obj() it actually causes python to do this -> type(obj).__call__(obj)
!e ```py
class A:
call = lambda s: print("a")
a = A()
a()
a.call()
type(a).call(a)
a.call = lambda: print("b")
a()
a.call()
type(a).call(a)
A.call = lambda s: print("c")
a()
a.call()
type(a).call(a)
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
001 | a
002 | a
003 | a
004 | a
005 | b
006 | a
007 | c
008 | b
009 | c
this demonstrates it pretty well I think
Assigning to the instance doesn't change the behavior of ()
could you explain further?
and since functions are objects
!e
class foo:
def __call__(*args):
print(args)
bar=foo()
bar()
@golden finch :white_check_mark: Your eval job has completed with return code 0.
(<__main__.foo object at 0x7f71db8e2fd0>,)
fascinating
does this apply for functions too?
for that matter, can type(lambda:0).__call__ be overridden
Technically yes
@sick hound :white_check_mark: Your eval job has completed with return code 0.
'โ'
i made something useless.
well, don't keep us waiting!
and unnecessarily complicated
!e ```py
print("hello world"[--(int(()==())**2)::].replace("_","useless var "[--(int(()==())**2*11)]))
@rich hound :white_check_mark: Your eval job has completed with return code 0.
hello world
it's using a variety of syntax features
yes.
its basically an over engineered ```py
"hello world".replace("_", "")
but the first _ was removed by [--(int(()==())**2)::] \ [--1::]
i had old projects but i wiped them by accident
could you make it more 'esoteric'?
most definitely
this
you asked
me? I'm not free rn
ohok
I'd start with bytecode modification, metaclasses, ctypes
o.o
globals().update too
vars(builtins).update also
Because builtins is just another namespace like globals and locals
youre replying to a message from july 2018... a year before 3.8 was ever released
Who?
you
Lmao probably from the reply anonymousdeveloper did
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello World!
Heelo worrld
yes.
okay that is exremely impressive
ahh that's probably where i got it from, i wondered how i got there without 3 hours of scrolling
imagine the scenes if you deleted a (
ikr
!e ```py
metamaker = (lambda meta, cls: ( lambda: [ (dict_.pop(es, None) for es in dict_.get("slots", tuple())) if [None for [globals()["dict_"]] in [[dict(cls.dict)]]][0] is None else None, [None for [globals()["dict_"]["metaclass"]] in [[meta]]], [None for [globals()["dict"]["wrapped"]] in [[cls]]], meta(str(cls.name), tuple(cls.bases), dict), ][-1]))
printf = lambda format_string, *args: print(format_string,end="") if not args else print(format_string % args,end="")
main = metamaker(type("b", (type,), {"call": lambda self, : {None}}), type("", (object,), {}))()
int = metamaker(type("a", (type,), {"sub": lambda self2, : {None} if isinstance(, set) else [None for [globals()[.split("=")[0]]] in [[import('builtins').int(_.split("=")[1])]]][0]}), type("a", (object,), {}))()
void = None
return_0 = None
int-main(void)-{
printf("Hello, World!\n"),
int-"num1=2",
int-"num2=3",
printf("%d + %d = %d\n", num1, num2, num1+num2),
return_0
}```
@harsh spear :white_check_mark: Your eval job has completed with return code 0.
001 | Hello, World!
002 | 2 + 3 = 5
cuz its within a set literal
Incredible
WHAT IN The WORLD
:)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello World!
lol
@thorny tapir :white_check_mark: Your eval job has completed with return code 0.
Hello World!
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | Hello, World!
002 | 2 + 3 = 5
you could've set end to '' in the print function you called in printf, i think that c's printf doesn't have a newline ending
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello World!test
!e
def printf(s, *a):
print(end=s%a)
printf('%i %a', 3, 4)
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
3 4
printf = lambda format_string, *args: print(format_string,end="") if not args else print(format_string % args,end="")
from the above code
works for both
!e
def printf(s, *a):
print(end=s%a)
printf('this works too')
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
this works too
args is an empty tuple anyway
ah right
This isn't really that esoteric but I don't know where to put it lol,
I created a decorator that can call different functions based off the syntactic context functools.singledispatch with context
Ah, it doesn't work on snekbox for some reason
def contextdispatch(function):
contexts = {}
def register(context: str):
def register_decorator(func):
contexts[context] = func
def running_register(*args, **kwargs):
return func(*args, **kwargs)
return running_register
return register_decorator
def run_function(*args, **kwargs):
function_called = stack()[-1].code_context[-1].rstrip('\n')
for context, func in contexts.items():
if re.search(pattern=fr"{context}", string=function_called):
return func(*args, **kwargs)
else:
return function(*args, **kwargs)
run_function.register = register
return run_function
this is the decorator
@contextdispatch
def testing():
print("not used in a for loop")
@testing.register(r"for . in testing\(\)")
def for_loop():
print("this was used in a for loop")
return range(1, 20)
>>> for i in testing():
... pass
>>> "this was used in a for loop"
>>> testing()
>>> "not used in a for loop"
@earnest wing :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | __peg_parser__
003 | ^
004 | SyntaxError: You found it!
Repls should use pretty much the same parser as any other python runtime
No need to make weird special cases for just repl when a normal program can have it
And do they?
>>> """
...
File "<stdin>", line 1
"""
^
SyntaxError: EOF while scanning triple-quoted string literal
I'm not sure if this counts.
# getters.py
def __getattr__(name):
def _getter(self):
return getattr(self, f"_{name}")
_getter.__name__ = name
return property(_getter)
# main.py
class Foo:
from getters import bar, baz
def __init__(self, bar, baz):
self._bar = bar
self._baz = baz
x = Foo(1, 5):
print(x.bar)
print(x.baz)
``` ```
1
5
# destruct.py
_obj = None
def pick(obj):
global _obj
_obj = obj
def __getattr__(name):
return getattr(_obj, name)
``` ```py
# main.py
import destruct
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
def f(point):
destruct.pick(point)
from destruct import x, y
print(f"{x=}, {y=}")
f(Point(1, 5))
1
5
can a lambda not raise an exception?
it can you just have to do generator stuff
raise_ = lambda:(_ for _ in ()).throw(Exception())
wow
git install git /j
I did it by sending a literal EOF character interactively.
This isn't really the channel or the server for that, but there are some great tutorials online.
!e after all you've seen in this server .throw is cursed?
class Yeet(Exception):...
(()for()in()).throw(Yeet, 'yeet!')
@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 | File "<string>", line 2, in <genexpr>
004 | __main__.Yeet: yeet!
in #esoteric-python
not usingtypeto create classes
how does this syntax (the ()()() work?)
mhm
but if the second tuple() isn't a variable, how does that work?
mhm
right
[] = ... unpacks into nothing, which is basically an assertion that the iterator is empty.
(()for()in() is a generator that yields an empty tuple for every time nothing is unpacked from an empty tuple. It loops zero times, and only serves the purpose of making a generator type object for the .throw method
Another summary, in code form:```py
In [1]: for a,b,c in [(1,2,3), (4,5,6)]: print(a, b, c)
1 2 3
4 5 6
In [2]: for (a,b,c) in [(1,2,3), (4,5,6)]: print(a, b, c)
1 2 3
4 5 6
In [3]: for () in [(), ()]: print()
In [4]: for () in []: print()
In [5]: for () in (): ()
In [6]: (()for()in())
Out[6]: <generator object <genexpr> at 0x7f45856854a0>
Thanks, that makes a lot more sense
it's also incredibly cursed
is there a shorter way to make a genexpr? also, why would it have .throw?
.throw raises the exception inside the generator
.send(obj) and .throw(obj) allow you to fine tune a generator state while it is running. .send allows you to send an object in wherever the last yield was and continue the generator. .throw raises its argument wherever the last yield was and continues the generator.
!e ```py
def sum_all():
total = (yield)
while (next := (yield total)) is not None:
total += next
yield total
summer = sum_all()
next(summer) # contiues to first yield
for i in range(10):
print('Running total:', summer.send(i)) # print running total
print(summer.send(None)) # end the while loop and print final total```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | Running total: 0
002 | Running total: 1
003 | Running total: 3
004 | Running total: 6
005 | Running total: 10
006 | Running total: 15
007 | Running total: 21
008 | Running total: 28
009 | Running total: 36
010 | Running total: 45
011 | 45
(yield)
could you give a code example?
!e (yield).throw(TypeError)
@earnest wing :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | SyntaxError: 'yield' outside function
!e print("Hello")
(lambda:(yield))()
(0for()in())
looking like it's minimal
Nor did I
I don't know what it does but I think it's cursed
yield is confusing in general
!e ```py
for this in(lambda:(yield))():print(this)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
None
!e ```py
print("hello world"[--(int(()==())**2)::].replace("_",f"useless var{chr((()==()+()==()*(()==()+()==()16)))}"[--(int(()==())**211)]))
shiT
@rich hound :white_check_mark: Your eval job has completed with return code 0.
hello world
HAHAHAHAH
ooh i have an idea
!e ```py
print("hello world"[--(int(()==())**2)::].replace("_",f"useless var{chr((()==()+()==()*(()==()+()==()16)))}"[--(int(()==())**211)])[0:].upper())
H.
h.
oh
shi
@rich hound :white_check_mark: Your eval job has completed with return code 0.
HELLO WORLD
!e ```py
print("hello world"[--(int(()==())**2)::].replace("_",f"useless var{chr((()==()+()==()*(()==()+()==()16)))}"[--(int(()==())**211)])
.replace([0:],[0:].upper(),1))
shit
not good
wh
yeah true
what
oho
@rich hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | .replace([0:],[0:].upper(),1))
003 | ^
004 | SyntaxError: invalid syntax
@rich hound :white_check_mark: Your eval job has completed with return code 0.
104
!e ```py
print("hello world"[--(int(()==())**2)::].replace("_",f"useless var{chr((()==()+()==()*(()==()+()==()16)))}"[--(int(()==())**211)])
.replace(chr(104),chr(104).upper()))
@rich hound :white_check_mark: Your eval job has completed with return code 0.
Hello world
!e print(ord("w"))
@rich hound :white_check_mark: Your eval job has completed with return code 0.
119
!e ```py
print("hello world"[--(int(()==())**2)::].replace("_",f"useless var{chr((()==()+()==()*(()==()+()==()16)))}"[--(int(()==())**211)])
.replace(chr(104),chr(104).upper()).replace(chr(119),chr(119).upper())+chr(33))
!e print(ord("!"))
@rich hound :white_check_mark: Your eval job has completed with return code 0.
33
@rich hound :white_check_mark: Your eval job has completed with return code 0.
Hello World!
@iron cedar
come look
!e ```py
print("hello world"[--(int(()==())**2)::].replace("_",f"useless var{chr((()==()+()==()*(()==()+()==()16)))}"[--(int(()==())**211)])
.replace(chr(104),chr(104).upper()).replace(chr(119),chr(119).upper())+chr(33))
@rich hound :white_check_mark: Your eval job has completed with return code 0.
Hello World!
wow
@sick hound is mine good?
ty
!e
print("_hello world_"[--(int(()==())**2)::].replace("_",f"useless var{chr((()==()+()==()*(()==()+()==()*16)))}"[--(int(()==())**2*11)]).replace(chr(104),chr(104).upper()).replace(chr(119),chr(119).upper())+chr(33)+"".join(chr(_)for _ in[32,70,114,111,109,32,78,111,120,46]))
@rich hound :white_check_mark: Your eval job has completed with return code 0.
Hello World! From Nox.
!e print(ord(''))
@rich hound :white_check_mark: Your eval job has completed with return code 0.
1
wh
!e
print(
"_hello world_"[--(int(()==())**2)::]
.
replace(
"_",
f"useless var{chr((()==()+()==()*(()==()+()==()*16)))}"[--(int(()==())**2*11)]
)
.
replace(
chr(104),
chr(104)
.
upper()
)
.
replace(
chr(119),
chr(119)
.
upper()
)+chr(
33
)+""
.
join(
chr(
_
)
for
_
in
[
32,
70,
114,
111,
109,
32,
78,
111,
120,
46
]
)
)
@rich hound :white_check_mark: Your eval job has completed with return code 0.
Hello World! From Nox.
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello World!
wHY
this will make me cry blood
make it in shellcode :p
lol
i do
i also know NASM but you know, thats useless
hiiii
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello Worpd!
hello! Can someone say how if its possible to get each pixel values in image?
like i need all white pixels, with somekind of coordinates of each
thanks guys! no worries with versions
i can use it if i like what are you gonna do, come here and stop me? XD
Nah the fact that it's probably broken and won't work will
It also supports... python 2.4 to 2.7 only
so even loading the module will probably fail
in fact, it's incompatible with setuptools, so you'll need to install it with manual extra steps
well I got 8.3.2 installed, seems to be fine... I've biien thinking its much easier) So i have one more problem. I have image with resolution 320x320, how many values can have one pixel?
its RGB
It depends if it's transparent, and the depth of the image.
Anyway, #โ๏ฝhow-to-get-help
you code like a sith
>>> example,help=type('',(),{'__sub__':lambda self,other:print('Usage: example [arguments]\nAvailable arguments:\n --help | Show this help menu')if other==0 else None})(),type('',(),{'__neg__':lambda self:0})()
>>> example --help
Usage: example [arguments]
Available arguments:
--help | Show this help menu
o.O
make it print actual arguments of a command @golden finch
like the ones it needs
problem is that it might be a syntaxerror
@golden finch :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | command --echo string
003 | ^
004 | SyntaxError: invalid syntax
can't escape syntax error
hm how would u get required args in a function then :?
@golden finch sry for ping ๐ฌ
like
def x(get, these, outside_the_function):
return 1
best i could describe it
i know its possible, i just dk how
hm
that's a function which takes arguments
do you mean like
x -get -these -outside_the_function
because that's probably possible
In [6]: import inspect
In [7]: def x(get, these, outside_the_function):
...: return 1
...:
In [8]: sig = inspect.signature(x)
In [9]: sig.parameters
Out[9]:
mappingproxy({'get': <Parameter "get">,
'these': <Parameter "these">,
'outside_the_function': <Parameter "outside_the_function">})```
o.O
In [13]: get = sig.parameters['get']
In [14]: get.default is not get.empty # or inspect.Parameter.empty
Out[14]: False```(this means it's required)
actually
In [15]: def x(get, these, outside_the_function, *foo):
...: return 1
...:
...:
In [16]: sig = inspect.signature(x)
In [17]: foo = sig.parameters['foo']
In [18]: foo.default is not foo.empty
Out[18]: False```in cases like this you could check the kind attribute of the Parameter
not sure how
hm
def f(a,b,c):
return 1
[print(i,getattr(f,i))for i in dir(f)]
wow.
@frigid shoal
In [8]: import inspect
In [9]: params = inspect.signature(example)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-9-35088f8ff0f6> in <module>()
----> 1 params = inspect.signature(example)
AttributeError: 'module' object has no attribute 'signature'
```?
works for me, not sure why you're getting that
same idk
and
In [19]: [print(i,getattr(x,i))for i in dir(x)]
File "<ipython-input-19-2c2d07315880>", line 1
[print(i,getattr(x,i))for i in dir(x)]
^
SyntaxError: invalid syntax
Their code worked for me as well
weird
how do i get the python version inside itself?
that makes no sense
np
how do i make it 3.8?
oh ok
didnt fix it
nvmmm
!e
def x(a1, b2, c3):
return 1
print(", ".join(a for a in __import__("inspect").signature(x).parameters))
@rich hound :white_check_mark: Your eval job has completed with return code 0.
a1, b2, c3
the a for a in i think is redundant
!e ```py
def x(a,b,c):return...
print(','.join(import('inspect').signature(x).parameters))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
a,b,c
so is most of the whitespace you used
you only need one newline in that file and one space character
and ellipsis is cuter than return 1 ;)
map(function, iterable, ...)```
Return an iterator that applies *function* to every item of *iterable*, yielding the results. If additional *iterable* arguments are passed, *function* must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see [`itertools.starmap()`](https://docs.python.org/3.10/library/itertools.html#itertools.starmap "itertools.starmap").
It's not particularly complicated.```py
In [1]: increment = 1 .add
In [2]: list(map(increment, [1, 2, 3]))
Out[2]: [2, 3, 4]```
is there a way to escape ```py
*iter(help,0),
?
@floral meteor
@rugged sparrow
you guys might know more than me
It's cheating, but you can suspend Python with ctrl+Z, then kill it with kill %1.
What's the easiest way to deepcopy a function?
I basically need to swap two functions without swapping the objects
Using their code objects most likely.
There could be some edge cases with async or generators, I don't recall.
In the simple case it works.```py
In [1]: def foo(): pass
In [2]: foo.code = (lambda x: x + 1).code
In [3]: foo(1)
Out[3]: 2
I'd also need to swap out the argument count and all that, no?
that's all in the code object
the only thing you may need to also change is __name__ and __qualname__ (do functions even get that)
and well, all other attributes the function may have, they can carry arbitrary ones after all
gotcha
func.__code__, inner.__code__ = inner.__code__, func.__code__
ValueError: read_line() requires a code object with 0 free vars, not 1
swapping code: ```py
func.__code__, inner.__code__ = inner.__code__, func.__code__
func.__globals__, inner.__globals__ = inner.__globals__, func.__globals__
func.__closure__, inner.__closure__ = inner.__closure__, func.__closure__
func.__defaults__, inner.__defaults__ = inner.__defaults__, func.__defaults__
func.__kwdefaults__, inner.__kwdefaults__ = inner.__kwdefaults__, func.__kwdefaults__
I think I have to use types.FunctionType but I have no clue what's needed for the argdefs field
types.FunctionType just takes a codeobj, right?
actually a simpler solution may be just doing
def copy_fn(fn):
ns = globals().copy()
exec(f"""
global {fn.__name__}
{inspect.getsource(fn)}
""", ns)
return ns[fn.__name__]
```won't work on lambdas unless you give them a new name
From the docstring, it's "a tuple that specifies the default argument values".
So for kwargs.
for this purpose that won't actually be reliable 
Can I ask what you're hoping to accomplish with this?
a code injection framework
@inject(method=read_line, at=At(value=AtValue.RETURN))
def on_read():
# TODO: Figure out a good way to pass context and set return value
pass
@modify_const(method=read_line,
at=At(value=AtValue.LOAD,
index=0))
def change_prompt():
return ">>>"
def main():
while True:
line = read_line()
if not line.strip():
break
print(f"Read line: {line.strip()}")``` here's some example usage
with support for priorities and conflict checking to avoid segfaults, but that means I have to make a wrapper function that applies all modifications at once before first use
so my idea was to copy read_line to a dummy function, and set read_line to apply those changes to the dummy function
wrong channel
okay newest stupid idea: pre-inject code that calls a function to modify itself the first time it's called
janky as it sounds, that worked to trigger the function lol
oh no I need to reimplement that asm library I was working on way back with jumps and stuff
this is gonna be pain
Is there a list of all revisions to the bytecode including what was added/removed in what versions?
!e
from types import FunctionType
test = (FunctionType(compile('{}', __name__, 'exec'), globals()))
def hi():
print("hi")
test.a = hi
test.a()
@sick hound :white_check_mark: Your eval job has completed with return code 0.
hi
!e
from types import FunctionType
test = (FunctionType(compile('', __name__, 'exec'), globals()))
def hi():
print("hi")
test.a = hi
test.a()
@sick hound :white_check_mark: Your eval job has completed with return code 0.
hi
@sick hound :white_check_mark: Your eval job has completed with return code 0.
hi
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | The Zen of Python, by Tim Peters
002 |
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/apuqavelir.txt?noredirect
# Code:
def func(x):
if x > 10:
return x / 40
else:
return x / 20
# My parser:
[
LOAD_FAST(id=124, arg='x'),
LOAD_CONST(id=100, arg=10),
COMPARE_OP(id=107, arg=4),
POP_JUMP_IF_FALSE(id=114, arg=Label(0x7f25f2908780)), # --> 1
LOAD_FAST(id=124, arg='x'),
LOAD_CONST(id=100, arg=40),
BINARY_TRUE_DIVIDE(id=27, arg=0),
RETURN_VALUE(id=83, arg=0),
Label(0x7f25f2908780), # <-- 1
LOAD_FAST(id=124, arg='x'),
LOAD_CONST(id=100, arg=20),
BINARY_TRUE_DIVIDE(id=27, arg=0),
RETURN_VALUE(id=83, arg=0),
LOAD_CONST(id=100, arg=None),
RETURN_VALUE(id=83, arg=0)
]
```pretty happy with this so far
impressive
can't you just extract it from dis.opmap and f.__code__?
or are you doing something else?
there's some wacky stuff going on once you start moving stuff around
specifically with jumps
then there's the way I want to do code injection where having ops as a list is very useful
but right now de- and reserializing a code object is giving me issues
# Code:
dis(f)
print(f(10))
# Dis:
0 LOAD_FAST 0 (x)
2 LOAD_CONST 0 (10)
4 COMPARE_OP 4 (>)
6 POP_JUMP_IF_FALSE 8 (to 16)
8 LOAD_FAST 0 (x)
10 LOAD_CONST 1 (40)
12 BINARY_TRUE_DIVIDE
14 RETURN_VALUE
>> 16 LOAD_FAST 0 (x)
18 LOAD_CONST 2 (20)
20 BINARY_TRUE_DIVIDE
22 RETURN_VALUE
# Output:
0.0
# Expected:
0.5
extracting yes, but when it comes to modifying that's not an option
oh, so you're actually modifying the source? that's hardcore
For this project I'm also more or less trying to copy how Java's OWASM works
done it before, but I'm now making two frameworks (one low level, one high level) to modify it pretty easily
I thought the length of co_code was fixed
wait, how the hell do you do it then?
alloc new memory and change the pointer to co_code?
Name: <function>
Filename: <code>
Argument count: 1
Positional-only arguments: 0
Kw-only arguments: 0
Number of locals: 0
Stack size: 2
Flags: NOFREE
Constants:
0: 10
1: 40
2: 20
Variable names:
0: x
``` this all looks correct too, hmm...
I replace co_code, co_names, co_varnames, co_consts, co_stacksize, etc
oh so just via CodeType.replace
yeah
planning to go back to just using raw CodeType for compat purposes
in theory my code would allow backwards compat all the way to 3.0
so for every major version since 3.0 I made sure it only adds the ops that are actually present in the current python version
Sadly I'll have to do away with type hints if I want to go that far back
wow
okay well
I'm corrupting the stack somewhere
# Code:
def func(x):
print(x)
if x > 20:
return x / 40
else:
return x / 20
# Input:
f(10)
# Output:
<built-in function print>
Traceback (most recent call last):
File "/home/mart/git/pyasm/pyasm/test/test.py", line 37, in <module>
main()
File "/home/mart/git/pyasm/pyasm/test/test.py", line 31, in main
print(f(10))
File "<code>", line 3, in <function>
TypeError: '>' not supported between instances of 'NoneType' and 'int'
# Dis:
2 0 LOAD_GLOBAL 0 (print)
2 LOAD_FAST 0 (x)
4 CALL_FUNCTION 1
6 POP_TOP
3 8 LOAD_FAST 0 (x)
10 LOAD_CONST 0 (20)
12 COMPARE_OP 4 (>)
14 POP_JUMP_IF_FALSE 12 (to 24)
5 16 LOAD_FAST 0 (x)
18 LOAD_CONST 1 (40)
20 BINARY_TRUE_DIVIDE
22 RETURN_VALUE
>> 24 LOAD_FAST 0 (x)
26 LOAD_CONST 0 (20)
28 BINARY_TRUE_DIVIDE
30 RETURN_VALUE```
@grave rover is that the bytecode that produced that error?
what does
what const was at index 0
ah
so whats the goal?
this is for simple bytecode edits similar to objectweb-asm for java
and with this I can make a somewhat reliable code injection mechanism
@inject(method=read_line, at=At(value=AtValue.RETURN))
def on_read(ctx):
# TODO: Figure out a good way to pass context and change return value
pass
@modify_const(method=read_line,
at=At(value=AtValue.LOAD,
index=0))
def change_prompt():
return ">>> "
so itll inject LOAD_CONST(func) CALL_FUNCTION(0)? or will it copy the bytecode of the injected function in
it will inject method calls and a few other things to get contextual information probably
not 100% sure yet
but having a low-level library makes writing a high-level library easier :)
especially with those damn jumps
Hi
may have found the longest type alias ever
CmpKey: typing._GenericAlias = typing.Tuple[int, typing.Tuple[int, ...], typing.Union[pip._vendor.packaging._structures.InfinityType, pip._vendor.packaging._structures.NegativeInfinityType, typing.Tuple[str, int]], typing.Union[pip._vendor.packaging._structures.InfinityType, pip._vendor.packaging._structures.NegativeInfinityType, typing.Tuple[str, int]], typing.Union[pip._vendor.packaging._structures.InfinityType, pip._vendor.packaging._structures.NegativeInfinityType, typing.Tuple[str, int]], typing.Union[pip._vendor.packaging._structures.NegativeInfinityType, typing.Tuple[typing.Union[pip._vendor.packaging._structures.InfinityType, pip._vendor.packaging._structures.NegativeInfinityType, int, str, typing.Tuple[typing.Union[pip._vendor.packaging._structures.InfinityType, pip._vendor.packaging._structures.NegativeInfinityType, int, str], str], typing.Tuple[pip._vendor.packaging._structures.NegativeInfinityType, typing.Union[pip._vendor.packaging._structures.InfinityType, pip._vendor.packaging._structures.NegativeInfinityType, int, str]]], ...]]]
it may just be infinitely recursive?
idk this might be relate
d
before this line i presume? I'd just change what either iter, help or 0 do
or even iterable unpack
Daily reminder that this channel is cursed
yes
my old account has some spicy stuff in here
but that was compromised :/
discord didnt get it back either
accurate
Is this an annotation bug? With __future__ annotations enabled,
a.b: c
tries to evaluate c.
This kind of messes with my cursed plans.
that does seem like a bug, annotations not working on attribute accesses
!e ```py
from future import annotations
int.add: fhadjkfhd
@earnest wing :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 'fhadjkfhd' is not defined
yeah it's not just my version
You can only use this command in the following channel(s): #878695047112040448, #476196062214750219, #310-release-stream, #bot-commands
Without assigning
huh, when you assign it does work
Odd
thats definitely a bug then
Well consider it addressed 
oh, that makes more sense
!e
def cprint(*args,**kwargs):
print(args[0])
__builtins__.__import__ = cprint
import ello_this_works_poggers
import ello ```
@plucky light :white_check_mark: Your eval job has completed with return code 0.
001 | ello_this_works_poggers
002 | ello
fairly esoteric
Fun
I'm about to put this in live code
try:
klass.__setattr__(None, None, None)
except SpecificException:
something()
(specificexception and something() will be changed, the cursed part is the setattr)
This reminded me of the recent failed attempt to do much computation without expressions. You can do from builtins import print as __import__, but you actually need it to be from builtins import print as __builtins__.__import__ which doesn't work.
def __builtins__():pass
```Interesting...
class __builtins__:
from builtins import print as __import__
```For some reason this doesn't work either.
It's because the __builtins__ object has to subscriptable, which means it can't be a regular class. I don't know of a way to instantiate a class, so no progress has been made.
__builtins__=type('',(dict,),{})()
no expressions
oh
!e ```py
class yeet(metaclass=lambda*a:type(*a)()):
lshift=print
yeet << "This is how you instantiate a class"
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
This is how you instantiate a class
the goal was no expressions i think
huh
killall -9 python
python
It works 
next up: Passing arguments from the env to the function if it requests them
Impressive!
registering another thing that does not work: (But doesn't use '=' anywhere)
!e ```def imediate(cls, *a, **k):
return cls(*a, **k)
print(builtins, builtins.import)
@imediate
class builtins:
from builtins import print as import
print(builtins, builtins.import)
import what_about_this```
@vague cairn :x: Your eval job has completed with return code 1.
001 | <module 'builtins' (built-in)> <built-in function __import__>
002 | <__main__.__builtins__ object at 0x7f4b1ff9bdc0> <built-in function print>
003 | Traceback (most recent call last):
004 | File "<string>", line 12, in <module>
005 | ModuleNotFoundError: No module named 'what_about_this'
Lmao
Lol
I feel like that would return a WinError
Because those folders are protected
def contextdispatch(function):
contexts = {}
def register(context: str, params_passed: tuple = ()):
def register_decorator(func):
contexts[context] = (func, params_passed)
def running_register(*args, **kwargs):
return func(*args, **kwargs)
return running_register
return register_decorator
def run_function(*args, **kwargs):
function_called = stack()[-1].code_context[-1].rstrip('\n')
for context, func in contexts.items():
if re.search(pattern=fr"{context}", string=function_called):
if func[1]:
params = re.findall(pattern=fr"{func[1][0]}", string=function_called)
if func[1][1] != Any:
params = map(func[1][1], params)
else:
params = tuple()
return func[0](*args, *params, **kwargs)
else:
return function(*args, **kwargs)
run_function.register = register
return run_function
is this esoteric?
I mean it is a decorator for messing around with functions
where you can change what function is called based off how the function is called
!d functools.singledispatch
@functools.singledispatch```
Transform a function into a [single-dispatch](https://docs.python.org/3.10/glossary.html#term-single-dispatch) [generic function](https://docs.python.org/3.10/glossary.html#term-generic-function).
To define a generic function, decorate it with the `@singledispatch` decorator. Note that the dispatch happens on the type of the first argument, create your function accordingly:
```py
>>> from functools import singledispatch
>>> @singledispatch
... def fun(arg, verbose=False):
... if verbose:
... print("Let me just say,", end=" ")
... print(arg)
```...
^ inspired off of this
Can anyone think of a scenario where del self would actually be possible to use in a somewhat useful way?
class Foo:
def __init__(self):
print(self) # prints <Foo object at 0x...>
del self
print(self) # Raises UnboundLocalError
It gave me a FileNotFoundError. Maybe it only works on Windows?
i want to del self ๐
!e
# wait so u can do...?
def a(*args, **kwargs):
print("Failed to import module L")
__builtins__.__import__ = a
import math
import time
damn it
@thorny tapir :white_check_mark: Your eval job has completed with return code 0.
001 | Failed to import module L
002 | Failed to import module L
oh lol that means u can change default functions n stuff?
correct
!e
__builtins__.__import__=lambda*_,**__:print(_,__)
import math
import time
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | ('math', {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}, {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}, None, 0) {}
002 | ('time', {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'math': None}, {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'math': None}, None, 0) {}
Where do these other arguments come from?
Also, can kwargs be anything else?
!e
__builtins__.__import__=lambda*_,**__:print(_,__)
import math
import time
from tkinter import *
def f(x):
import ctypes
@golden finch :x: Your eval job has completed with return code 1.
001 | ('math', {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}, {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}, None, 0) {}
002 | ('time', {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'math': None}, {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'math': None}, None, 0) {}
003 | ('tkinter', {'__name__': '__main__', '__doc__': None, '__package
... (truncated - too long)
Full output: https://paste.pythondiscord.com/facibuhohe.txt?noredirect
!e py __builtins__.__import__ = lambda *a, **k: print(a, k) from foo.bar import b as c
@rugged sparrow :x: Your eval job has completed with return code 1.
001 | ('foo.bar', {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}, {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}, ('b',), 0) {}
002 | Traceback (most recent call last):
003 | File "<string>", line 2, in <module>
004 | ('io', {'__builtins__': <module 'builtins' (built-in)>}, {'__builtins__': <module 'builtins' (built-in)>}, [], 0) {}
005 | ImportError: cannot import name 'b' from '<unknown module name>' (unknown location)
Oh god.
guys, is possible doing that without metaclass?```py
class _MetaModel(type):
def len(self):
return self.hack
class Model(metaclass=_MetaModel):
pass
class Player(Model):
hack = 1
len(Player) # 1```
how?
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1
this don't changes nothing 
the difference is only ```py
class Model(metaclass=_MetaModel):
class Model(_MetaModel('Model',(),{})):
make a class that supports len
i'm using __init_subclass__ of Model
import typing
T = typing.TypeVar('T', bound="Model")
class _attribute:
__slots__ = ()
def __init__(self) -> None:
pass
def __get__(self, *_) -> typing.Any:
...
def __set__(*_) -> None:
raise AttributeError("you can't set this attribute")
class ModelMeta(type):
def __len__(self):
return 1
class Model(metaclass=ModelMeta):
__models__: typing.ClassVar[dict[str, type[T]]] = {}
def __init_subclass__(cls, **options) -> None:
self: T = cls.__mro__[-2]
if cls.__base__ != self:
raise RuntimeError("you can't subclass a Model")
name = options.pop("name", cls.__name__)
self.__models__[name] = cls
cls.it = []
for identifier, annotation in cls.__annotations__.items():
...
descriptor = _attribute()
setattr(cls, identifier, descriptor)
class Person(Model, name="pessoa"):
name: str
age: int
class Book(Model, name="livro"):
title: str
author: Person
typehints
lmao
What's going on here?
!e
original=__builtins__.__build_class__
def build(*args,**kwargs):
print(args,kwargs)
return original(*args,**kwargs)
__builtins__.__build_class__=build
import re
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | (<function _C at 0x7fc20a2c9820>, '_C') {}
002 | (<function DynamicClassAttribute at 0x7fc20a2c99d0>, 'DynamicClassAttribute') {}
003 | (<function _GeneratorWrapper at 0x7fc20a2c99d0>, '_GeneratorWrapper') {}
004 | (<function auto at 0x7fc20a2e0670>, 'auto') {}
005 | (<function _EnumDict at 0x7fc20a2e0670>, '_EnumDict', <class 'dict'>) {}
006 | (<function EnumMeta at 0x7fc20a2e0670>, 'EnumMeta', <class 'type'>) {}
007 | (<function Enum at 0x7fc20a2e0670>, 'Enum') {'metaclass': <class 'enum.EnumMeta'>}
008 | (<function IntEnum at 0x7fc20a2e0670>, 'IntEnum', <class 'int'>, <enum 'Enum'>) {}
009 | (<function Flag at 0x7fc20a2e19d0>, 'Flag', <enum 'Enum'>) {}
010 | (<function IntFlag at 0x7fc20a2e19d0>, 'IntFlag', <class 'int'>, <enum 'Flag'>) {}
011 | (<function error at 0x7fc20a2e3d30>, 'error', <class 'Exception'>) {}
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/kuvetubiyo.txt?noredirect
so that's the original builtin
!e
original=__builtins__.__build_class__
def build(f,n,*bases,**kwargs):
old=original(f,n,*bases,**kwargs)
if 'metaclass' in kwargs:
return kwargs['metaclass'](n,bases,dict(old.__dict__))
else:
return type(n,bases,dict(old.__dict__))
__builtins__.__build_class__=build
import re
@golden finch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 10, in <module>
003 | File "/usr/local/lib/python3.9/re.py", line 124, in <module>
004 | import enum
005 | File "/usr/local/lib/python3.9/enum.py", line 664, in <module>
006 | class Enum(metaclass=EnumMeta):
007 | File "<string>", line 3, in build
008 | File "/usr/local/lib/python3.9/enum.py", line 169, in __prepare__
009 | enum_dict = _EnumDict()
010 | File "/usr/local/lib/python3.9/enum.py", line 82, in __init__
011 | super().__init__()
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/neyigedivo.txt?noredirect
__build_class__ is showing the functions that set up the scope for each class
I wrote the code in the first example
The thing is
Why doesn't the second work?
I use the original __build_class__ function to get the namespace
or is it a mistake in metaclasses?
!e
original=__builtins__.__build_class__
def build(f,n,*bases,**kwargs):
old=original(f,n,*bases,**kwargs)
return type(n,bases,dict(old.__dict__))
__builtins__.__build_class__=build
import re
@golden finch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 7, in <module>
003 | File "/usr/local/lib/python3.9/re.py", line 124, in <module>
004 | import enum
005 | File "/usr/local/lib/python3.9/enum.py", line 664, in <module>
006 | class Enum(metaclass=EnumMeta):
007 | File "<string>", line 3, in build
008 | File "/usr/local/lib/python3.9/enum.py", line 169, in __prepare__
009 | enum_dict = _EnumDict()
010 | File "/usr/local/lib/python3.9/enum.py", line 82, in __init__
011 | super().__init__()
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/uwamihelas.txt?noredirect
same error
Traceback (most recent call last):
File "<string>", line 7, in <module>
File "/usr/local/lib/python3.9/re.py", line 124, in <module>
import enum
File "/usr/local/lib/python3.9/enum.py", line 664, in <module>
class Enum(metaclass=EnumMeta):
File "<string>", line 3, in build
File "/usr/local/lib/python3.9/enum.py", line 169, in __prepare__
enum_dict = _EnumDict()
File "/usr/local/lib/python3.9/enum.py", line 82, in __init__
super().__init__()
TypeError: super(type, obj): obj must be an instance or subtype of type
@rapid sparrow in this example, what am I doing wrong with my reimplementation? it doesn't appear to have anything obviously wrong with it
code reproduced below
original=__builtins__.__build_class__
def build(f,n,*bases,**kwargs):
old=original(f,n,*bases,**kwargs)
if 'metaclass' in kwargs:
return kwargs['metaclass'](n,bases,dict(old.__dict__))
else:
return type(n,bases,dict(old.__dict__))
__builtins__.__build_class__=build
import re
!e
original=__import__("builtins").__build_class__
def build(func, name, *bases, **kwargs):
callee = kwargs["metaclass"] if "metaclass" in kwargs else type
ns = {}
print(f"exec({func.__code__=}, {ns=}, func.__globals__=)")
global __name__
__name__ = func.__module__
exec(func.__code__, func.__globals__)
print(f"callee({name=}, {bases=}, ns=)")
cls = callee(name, bases, ns)
print(f"{cls=}")
return cls
__import__("builtins").__build_class__=build
import re
@rapid sparrow :x: Your eval job has completed with return code 1.
001 | exec(func.__code__=<code object _C at 0x7fdc6884bbe0, file "/usr/local/lib/python3.9/types.py", line 39>, ns={}, func.__globals__=)
002 | callee(name='_C', bases=(), ns=)
003 | cls=<class 'types._C'>
004 | Traceback (most recent call last):
005 | File "<string>", line 14, in <module>
006 | File "/usr/local/lib/python3.9/re.py", line 124, in <module>
007 | import enum
008 | File "/usr/local/lib/python3.9/enum.py", line 2, in <module>
009 | from types import MappingProxyType, DynamicClassAttribute
010 | File "/usr/local/lib/python3.9/types.py", line 41, in <module>
011 | MethodType = type(_C()._m)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/umulehusup.txt?noredirect
!e
import sys
def build(func, name, *bases, **kwargs):
callee = kwargs["metaclass"] if "metaclass" in kwargs else type
ns = {}
print(f"exec({func.__code__=}, {ns=}, func.__globals__=)")
global __name__
__name__ = func.__module__
print(f"callee({name=}, {bases=}, {ns=})")
exec(func.__code__, sys.modules[func.__module__].__dict__, ns)
print(f"callee({name=}, {bases=}, {ns=})")
cls = callee(name, bases, ns)
sys.modules[func.__module__].__dict__[name] = cls
print(f"{cls=}")
return cls
__builtins__.__build_class__=build
import re
import inspect
@rapid sparrow :x: Your eval job has completed with return code 1.
001 | exec(func.__code__=<code object _C at 0x7f48dcaa7b30, file "/usr/local/lib/python3.9/types.py", line 39>, ns={}, func.__globals__=)
002 | callee(name='_C', bases=(), ns={})
003 | callee(name='_C', bases=(), ns={'__module__': 'types', '__qualname__': '_C', '_m': <function _C._m at 0x7f48dca9b940>})
004 | cls=<class 'types._C'>
005 | exec(func.__code__=<code object DynamicClassAttribute at 0x7f48dcaa9500, file "/usr/local/lib/python3.9/types.py", line 149>, ns={}, func.__globals__=)
006 | callee(name='DynamicClassAttribute', bases=(), ns={})
007 | callee(name='DynamicClassAttribute', bases=(), ns={'__module__': 'types', '__qualname__': 'DynamicClassAttribute', '__doc__': "Route attribute access on a class to __getattr__.\n\n This is a descriptor, used to define attributes that act differently when\n accessed through an instance and through a class. Instance access remains\n normal, but access to an attribute through a class will be routed to the\n class's __getattr__ m
... (truncated - too long, too many lines)
Full output: https://paste.pythondiscord.com/hacitoxena.txt?noredirect
i think something is wrong with metaclass version?
?
in my version it dies in some code that's running while EnumMeta is set up (code trying to use .attr syntax on 'classdict')
setting up Enum with metaclass=EnumMeta, I mean
it looks like you can't make a working __build_class__ in pure python, sadly
2 0 LOAD_CONST 1 (<function on_read at 0x7f41840e4dc0>)
2 LOAD_CONST 2 (<class 'mixin.callback.CallbackInfo'>)
4 CALL_FUNCTION 0
6 CALL_FUNCTION 1
8 POP_TOP
10 LOAD_GLOBAL 0 (input)
12 LOAD_CONST 3 (<function change_prompt at 0x7f41840e4ee0>)
14 LOAD_FAST 0 (p)
16 CALL_FUNCTION 1
18 CALL_FUNCTION 1
20 RETURN_VALUE
Traceback (most recent call last):
File "/home/mart/git/pyasm/pymixin/test/test.py", line 28, in <module>
main()
File "/home/mart/git/pyasm/pymixin/test/test.py", line 21, in main
line = read_line()
File "/home/mart/git/pyasm/pymixin/test/test_lib.py", line -1, in read_line
TypeError: 'int' object is not callable
I dont even know anymore
lmao
dang, why not?
AC: cannot convert yet, waiting for *args support
oh, nevernind, that comment is about argument clinic (was looking at https://github.com/python/cpython/blob/main/Python/bltinmodule.c#L105)
Python/bltinmodule.c line 105
builtin___build_class__(PyObject *self, PyObject *const *args, Py_ssize_t nargs,```
I'm not, or at least I don't think I am
no clue where in the bytecode that happens
an int
which is a parameter to change_prompt
that's the output from dis, yes
it's also 1:1 with what I expect the bytecode to be
well uh
code injection
kinda hard to debug
wait I think I know what the issue is
hmm
so the wacky thing is:
- I initially inject some code
- That code applies all modifications to itself
- When it returns the bytecode will have changed and it'll be calling an int
Before injection:py 2 0 LOAD_CONST 2 (<function get_wrapper.<locals>.inject at 0x7f42013ace50>) 2 CALL_FUNCTION 0 4 POP_TOP 6 LOAD_CONST 3 (<function read_line at 0x7f42013ac8b0>) 8 LOAD_FAST 0 (p) 10 CALL_FUNCTION 0 # Call modified self 12 RETURN_VALUE 14 LOAD_GLOBAL 0 (input) 16 LOAD_CONST 1 ('> ') 18 CALL_FUNCTION 1 20 RETURN_VALUE After injection: ```py
2 0 LOAD_CONST 1 (False)
2 POP_JUMP_IF_FALSE 7 (to 14) # Jump to the function itself
4 LOAD_CONST 1 (False)
6 NOP
8 NOP
10 NOP
12 RETURN_VALUE # Match RETURN_VALUE in previous function
>> 14 LOAD_CONST 2 (<function on_read at 0x7f42013acdc0>)
16 LOAD_CONST 3 (<class 'mixin.callback.CallbackInfo'>)
18 CALL_FUNCTION 0
20 CALL_FUNCTION 1
22 POP_TOP
24 LOAD_GLOBAL 0 (input)
26 LOAD_CONST 4 (<function change_prompt at 0x7f42013acee0>)
28 LOAD_FAST 0 (p)
30 CALL_FUNCTION 1
32 CALL_FUNCTION 1
34 RETURN_VALUE
yet it still happens...
maybe one of those functions is pushing something to the stack that you're not expecting
im wondering this CO_NEWLOCALS flag might be part of the issue:
https://stackoverflow.com/questions/63536320/build-class-in-python-3-5
it shouldn't though...
because it'd have its own stack
maybe the problem might be that you call the metaclass without calling __prepare__ first?
Ah, back to the CCC
that might be it
def build_class(func, name, *bases, metaclass=None, **kwds):
if metaclass is None:
metaclass = _extract_metaclass(bases) # may raise an exception
prepare = getattr(metaclass, "__prepare__", None)
if prepare:
namespace = prepare(name, bases, **kwds)
else:
namespace = {}
newnamespace = func(namespace)
if newnamespace is not None:
namespace = newnamespace
return metaclass(name, bases, namespace, **kwds)
def _extract_metaclass(bases):
if not bases:
return type
# XXX Should we do the "winner" calculation here?
return bases[0].__class__ # or type(bases[0])?
Guido himself wrote this one and it gets the same error, lol
okay so it's a bug
what's a bug?
implementing __build_class__ in python doesn't work
in 3.9 and 3.11 at least
i'd like to know if there's a way to intercept the creation of BaseException instances so I can print all the exceptions happening
possible?
there's a metric ton of them, judging by running python to the prompt and setting a breakpoint on
int PyException_SetTraceback(PyObject *, PyObject *)
184 exceptions with full tracebacks to get to >>>
mostly KeyError (looking in sys.modules) and various FileNotFoundError from the import system
what's the issue?
just seems like a lot for the happy path, no?
i don't think it's particular to my system or anything, just wondered what others thought
what's wrong with __build_class__?
the example implementation doesn't even work
this
sort of, read_line is the function I inject code into, and the resulting bytecode is there
How are you setting a breakpoint there btw?
$ gdb --args python3
(gdb) set $p = 0
(gdb) b PyException_SetTraceback
(gdb) commands
> print ($p = $p + 1)
> c
> end
(gdb) r
you have to be able to set a breakpoint in C, i don't know if it's possible in PyCharm?
in pycharm you just click on the left of some python code lol
it's apparently possible with vscode, visual studio, dunno what else
well any native debugger really i guess, that function is exported so even like perf, valgrind, etc should see it
it would be great if there's a way to hook into similar in python
maybe pdb lets you break on BaseException.__init__ or on setting the __traceback__ attribute, but I don't know PDB very well
actually, I just remembered you can have pycharm break on exceptions i think
theres a Notifications box too in PyCharm that defaults to just "Terminate", you probably want "Always" also checked
You could do that with fishhook
oh, that looks awesome
omg it worked
>>> import fishhook
>>> @fishhook.hook(BaseException)
... def __init__(self, *args, **kwargs):
... print(f"Got exception: {self}({args})")
... return fishhook.orig(self, *args, **kwargs)
...
>>> raise BaseException("hello")
Got exception: hello(('hello',))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
BaseException: hello
>>>
>>> raise RuntimeError("hello")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: hello
i guess you would need to hook the specific class?
yea one sec imma write a demo
yea you need to hook them specifically
im gonna try using my lowlevel hook to hook the C function tho
oh you wrote that package? that's awesome
i was just gonna try to create the hooks in a loop, since most of the exception types are in builtins
that will work for most of them, but some are used for general control flow so you run into fatal recursion issues
and yea i wrote fishhook but im gonna use my asm_hook code to try and hook the underlying C functions
this worked:
import fishhook
def __init__(self, *args, **kwargs):
print(f"Got exception: {self}({args})")
return fishhook.orig(self, *args, **kwargs)
for _, exc_type in inspect.getmembers(builtins, lambda m: inspect.isclass(m) and issubclass(m,BaseException)):
fishhook.hook(exc_type)(__init__)
quick and dirty good enough for me, the only surprise is some of the exceptions:
Got exception: hello(('hello',))
Got exception: 'ModuleSpec' object has no attribute '_initializing'(("'ModuleSpec' object has no attribute '_initializing'",))
is there a way to tell which classes would work well?
i didnt think that would be possible without a debugger, very neat
already revealed an AttributeError that was unintentionally suppressed in some code I was working on
In theory with my asm_hook code you could do a breakpoint like gdb
okay figured out my issue
you want to share the code?
does it rewrite instructions?
nice
def read_line() -> str:
return input("> ")
@inject(method=read_line, at=At(value=AtValue.HEAD))
def on_read(ci: CallbackInfo):
print("Hello Mixin :)")
@modify_const(method=read_line,
at=At(value=AtValue.LOAD,
target="> "))
def change_prompt():
return ">>> "
i = 0
@redirect(method=read_line,
at=At(value=AtValue.INVOKE,
target=input))
def redirected_input(prompt: str):
global i
i = i + 1
return input("{0} {1}".format(i, prompt))
``` ```
Hello Mixin :)
1 >>> a
Read line: a
Hello Mixin :)
2 >>> b
Read line: b
Hello Mixin :)
3 >>> c
Read line: c
Hello Mixin :)
4 >>>
```Pretty happy so far
is it posted anywhere?
lol iostream hacks
Not yet, pushing later this weekend
Then I'll need to make a package name request
How do freevars/cellvars work?
in the case of cellvars, it's basically a pointer to a variable used in multiple scopes (like a function foo and nested_foo). The variables get dereferenced by extra sequences of bytecode the compiler emits, instead of accessed directly like a normal variable
freevars are unresolved names afaik, that can work if an attribute is added by that name to a parent scope before the function with the freevar gets run
you can find the cell objects if you look at __closure__ on such a function
so e.g.
def make_func(prompt):
def get_input() -> str:
return input(prompt)
return get_input```
here prompt is a freevar accessed by the *_DEREF ops
what would an example of a cellvar be? (and what opcodes relate to cellvars?)
My vs code terminal isn't showing any output can anyone plz help?
wrong channel, try #โ๏ฝhow-to-get-help or #editors-ides
prompt is a freevar in get_input? its a cellvar in make_func, right?
>>> def foo(a):
... def nested():
... return a
... return nested
...
>>> n = foo(70); n
<function foo.<locals>.nested at 0x7ff797d670>
>>> n.__closure__
(<cell at 0x7ff7b04670: int object at 0x7ff7c8a210>,)
>>> c = n.__closure__[0]
>>> c.cell_contents
70
>>> foo.__code__.co_cellvars
('a',)
>>> n.__code__.co_freevars
('a',)
>>> n.__code__.co_cellvars
()
its a freevar in the nested func and a cellvar in the outer one, looks like
but it seems like nested must have special opcodes to access ut via the cell
>>> dis.dis(foo)
2 0 LOAD_CLOSURE 0 (a)
2 BUILD_TUPLE 1
4 LOAD_CONST 1 (<code object nested at 0x7ff7a13500, file "<stdin>", line 2>)
6 LOAD_CONST 2 ('foo.<locals>.nested')
8 MAKE_FUNCTION 8 (closure)
10 STORE_FAST 1 (nested)
4 12 LOAD_FAST 1 (nested)
14 RETURN_VALUE
Disassembly of <code object nested at 0x7ff7a13500, file "<stdin>", line 2>:
3 0 LOAD_DEREF 0 (a)
2 RETURN_VALUE
LOAD_DEREF, seems to be the opcode you're asking about?
and LOAD_CLOSURE for cellvars maybe
same deal for your make_func:
>>> dis.dis(make_func)
2 0 LOAD_GLOBAL 0 (str)
2 LOAD_CONST 1 (('return',))
4 BUILD_CONST_KEY_MAP 1
6 LOAD_CLOSURE 0 (prompt)
8 BUILD_TUPLE 1
10 LOAD_CONST 2 (<code object get_input at 0x7ff766a240, file "<stdin>", line 2>)
12 LOAD_CONST 3 ('make_func.<locals>.get_input')
14 MAKE_FUNCTION 12 (annotations, closure)
16 STORE_FAST 1 (get_input)
4 18 LOAD_FAST 1 (get_input)
20 RETURN_VALUE
Disassembly of <code object get_input at 0x7ff766a240, file "<stdin>", line 2>:
3 0 LOAD_GLOBAL 0 (input)
2 LOAD_DEREF 0 (prompt)
4 CALL_FUNCTION 1
6 RETURN_VALUE
I see
im learning java and i feel like im back to coding like a noob, only i already know these algorithms, just not the java code for them
it's like in path of exile when you gotta go through the whole map again from the start, but it's all different, and much harder
should I make un-wrapping wraps a feature in this or leave that to the user
Have you learnt any esoteric Java yet?
tf is this
Java is already esoteric
its hard to think what would be esoteric java
class AbstractClassAwareSecurityBeanUtils
you need the "Java for people who aren't new to programming" one
one * at the beginning I think?
instead of **
yes
I am responding to your error
because ** is for dict-like mappings
which map() is not
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
011 | 10
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ocemeseter.txt?noredirect
hmm yes (){}[]
Ive already figured out i can write up junk, then compile and decompile to get better written code.
It converts a = a + 1 to ++a
I tried using finalize to hang java but i couldnt find the relevant implements object
<function <lambda>.<locals>.<lambda> at 0x0000018677E7E040>
this is unpleasant
@sick hound :white_check_mark: Your eval job has completed with return code 0.
<function <lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>.<locals>.
... (truncated - too long)
Full output: https://paste.pythondiscord.com/oyujuhuvaz.txt?noredirect
operator=lambda _:lambda*__:_(*_(*__))
this can be used to segfault... what?
if you do it with 10k
!e
unpleasant=lambda x:exec("raise BaseException('no')")if x<1else eval('('+'lambda:'*(x+1)+'0)'+'()'*x)
print(unpleasant(100000))
@golden finch :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
@golden finch :warning: Your eval job timed out or ran out of memory.
[No output]
no, it's definitely a segfault
it's a recursion error
!e py unpleasant=lambda x:exec("raise BaseException('no')")if x<1else eval('('+'lambda:'*(x+1)+'0)'+'()'*x) print(unpleasant(1500))
@frigid wharf :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | File "<string>", line 1, in <lambda>
004 | RecursionError: maximum recursion depth exceeded during compilation
Unsafe, Classloader, and probably more
3.10 doesnt crash, building 3.9 to see if it does
i mean they took out Unsafe completely and made reflection basically illegal.. glad I don't have to write anything in Java at the moment
Really? it's still usable in J16
crashes during tokenization, looks like?
10,000 it could handle but not 100,000 ๐
which?
looks like they moved Unsafe to the jdk.unsupported module in J11, so I guess if it's still there now, they effectively won't be removing it
lmao
I'm using OpenJDK if that helps
no problem, glad to hear it works
@rugged sparrow I think you were the one who asked:
https://github.com/martmists-gh/pyasm
https://github.com/martmists-gh/pymixin
Gonna see about pypi releases later
Sweet I'll take a look
well uh
I already identified some issues with it
jumps in pyasm are not 100% correct yet
and it's a mess
couldn't get the code objects to actually work, myself
just add more zeroes
@sick hound :white_check_mark: Your eval job has completed with return code 0.
<class '__main__.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A.A
... (truncated - too long)
Full output: https://paste.pythondiscord.com/nuhahabipo.txt?noredirect
thanks, that helped ๐
tokenizer bug bounty
here I come
jk
@sick hound :warning: Your eval job timed out or ran out of memory.
[No output]
You can only use this command in the following channel(s): #878695047112040448, #476196062214750219, #310-release-stream, #bot-commands
waht?
?
whats it not doing right?
!e
#include <stdint.h>
#include <stdio.h>
#/* pre-declare types and functions */
void: (type) = (type) ("(void *)0"),
int16_t: (type) = (type) (int(16))(),
int32_t: (type) = (type) (int(32))(),
puts = (print),
printf: ((str) := void) = (puts),
#/* confirm function and variable declarations */
[[void]] = (void),
[[total]] = (int32_t),
[[i]] = (int32_t),
[[puts]] = (puts),
[[printf]] = (printf),
#/* ensure forwards and backwards compatibility */
import __future__ as __past__
#define FUTURE PAST
#define PAST FUTURE
#/* output a formatted string to stdout */
def printf(s, __VA_ARGS__) -> (void) :{
(void) (puts((void).__mod__(s, __VA_ARGS__), end=((void).__new__)(void))),
}
#/*******************************************************
# * SUMMATION SCRIPT *
# *******************************************************
# * Sum up all the natural numbers up to 6. The result *
# * should be 0 + 1 + 2 + 3 + 4 + 5 + 6 = 21. *
# *******************************************************/
#/* print numbers from 0 to 6 */
int32_t: i = 0,
while (i <= 6) :{
(void) (printf(" %d\n", i)),
(i := i + 1),
}
(void) (puts("__")),
#/* sum up numbers from 0 to 6 */
int32_t: total = 0,
int32_t: i = 0,
for (int32_t) in (i <- 0, i <= 6, ++i) :{
(total := total + i),
}
(void) (printf("%d\n", total)),
@fiery hare :x: Your eval job has completed with return code 1.
001 | File "<string>", line 8
002 | puts: ((str) := void) = (print),
003 | ^
004 | SyntaxError: cannot use assignment expressions with name
!e
#include <stdint.h>
#include <stdio.h>
#/* pre-declare types and functions */
void: (type) = (type) ("(void *)0"),
int16_t: (type) = (type) (int(16))(),
int32_t: (type) = (type) (int(32))(),
puts = (print),
printf = (puts),
#/* confirm function and variable declarations */
[[void]] = (void),
[[total]] = (int32_t),
[[i]] = (int32_t),
[[puts]] = (puts),
[[printf]] = (printf),
#/* ensure forwards and backwards compatibility */
import __future__ as __past__
#define FUTURE PAST
#define PAST FUTURE
#/* output a formatted string to stdout */
def printf(s, __VA_ARGS__) -> (void) :{
(void) (puts((void).__mod__(s, __VA_ARGS__), end=((void).__new__)(void))),
}
#/*******************************************************
# * SUMMATION SCRIPT *
# *******************************************************
# * Sum up all the natural numbers up to 6. The result *
# * should be 0 + 1 + 2 + 3 + 4 + 5 + 6 = 21. *
# *******************************************************/
#/* print numbers from 0 to 6 */
int32_t: i = 0,
while (i <= 6) :{
(void) (printf(" %d\n", i)),
(i := i + 1),
}
(void) (puts("__")),
#/* sum up numbers from 0 to 6 */
int32_t: total = 0,
int32_t: i = 0,
for (int32_t) in (i <- 0, i <= 6, ++i) :{
(total := total + i),
}
(void) (printf("%d\n", total)),
@fiery hare :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | __
009 | 21
@terse mortar this is the worst thing I've ever experienced.
That is amazing
no it's not
Yes it is
I'm so fucking upset right now.
#/* ensure forwards and backwards compatibility */
import __future__ as __past__
#define FUTURE PAST
#define PAST FUTURE
How this works? I mean why #includes are needed
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | MemoryError
@sick hound :warning: Your eval job timed out or ran out of memory.
[No output]
@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 | ModuleNotFoundError: No module named 'psutil'
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
Stelercus stop making me cry :(((
not sure if I should be glad or worried that someone has plans for my code injection framework
I did finally make a somewhat decent readme though
good god how does this work
oh god you're using commas to secretly make tuples
so that's what the commas do?
yeah
how black magic is it compared to this ```py
from mixin import *
def return_n_squared(n):
... return n * n
...
@inject(method=return_n_squared, at=At(value=AtValue.RETURN), cancellable=True)
... def return_n_cubed_instead(callback_info: CallbackInfo):
... n = (callback_info.return_value0.5)
... callback_info.set_return(n3)
...
return_n_squared(10)
1000.0
missing a )
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | __
009 | 21
!e print("geh")
@steep herald :white_check_mark: Your eval job has completed with return code 0.
geh
!e
S = "a"
key = 1097
print(chr(ord(S)+key))
!e
S = "ag"
key = 1097
print(chr(ord(S)+key))
Can you write a "Hello, World!" Python program where no characters with holes in them are used?
so #%DOo09qaA etc not allowed
correct
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello, World!
p
If it's easier try only characters with holes in them 
comeon, you've got in with try is if chr, uhh
yeah, it might be impossible 
!e ```py
{}["H"+chr(1111//11)+"ll"+chr(111)+", W"+chr(111)+"rl"+chr(73+27)+"!"]
@earnest wing :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | KeyError: 'Hello, World!'
!e
print(["H"+chr(1111//11)+"ll"+chr(111)+", W"+chr(111)+"rl"+chr(73+27)+"!"])
@knotty delta :white_check_mark: Your eval job has completed with return code 0.
['Hello, World!']
!e ```py
print(bytes([0x18*int(float('0.0'+str(int('0x249e',16)+0x1))*0x20),int(float(str(0x5)+'.'+str(int('0x216ff33c00f0f3',16)))*0x11),int(float(str(0x1)+'.'+str(int('0x32dc227a421af',16)))*int(float(str(0x4)+'.0'+str(int('0x40f6c2a076db',16)))*0xe)),int(float(str(0x1)+'.'+str(int('0x32dc227a421af',16)))*int(float(str(0x4)+'.0'+str(int('0x40f6c2a076db',16)))*0xe)),int(float(str(0x0)+'.'+str(0x0)+str(0x0)+str(int('0x299b48154dfd3e',16)))*int(float(str(0x46)+'.'+str(int('0x16ba2e55f4a',16)))*0x547))]))
@sly root :white_check_mark: Your eval job has completed with return code 0.
b'Hello'
why this work???py ๐น๐ป๐ฒ๐ท๐ฝ(๐ฌ๐ฑ๐ป(97)+๐ฌ๐ฑ๐ป(98)+๐ฌ๐ฑ๐ป(99)+๐ฌ๐ฑ๐ป(100)+๐ฌ๐ฑ๐ป(101)+๐ฌ๐ฑ๐ป(102)+๐ฌ๐ฑ๐ป(103)+๐ฌ๐ฑ๐ป(104)+๐ฌ๐ฑ๐ป(105)+๐ฌ๐ฑ๐ป(106)+๐ฌ๐ฑ๐ป(107)+๐ฌ๐ฑ๐ป(108)+๐ฌ๐ฑ๐ป(109)+๐ฌ๐ฑ๐ป(110)+๐ฌ๐ฑ๐ป(111)+๐ฌ๐ฑ๐ป(112)+๐ฌ๐ฑ๐ป(113)+๐ฌ๐ฑ๐ป(114)+๐ฌ๐ฑ๐ป(115)+๐ฌ๐ฑ๐ป(116)+๐ฌ๐ฑ๐ป(117)+๐ฌ๐ฑ๐ป(118)+๐ฌ๐ฑ๐ป(119)+๐ฌ๐ฑ๐ป(120)+๐ฌ๐ฑ๐ป(121)+๐ฌ๐ฑ๐ป(122)+๐ฌ๐ฑ๐ป(65)+๐ฌ๐ฑ๐ป(66)+๐ฌ๐ฑ๐ป(67)+๐ฌ๐ฑ๐ป(68)+๐ฌ๐ฑ๐ป(69)+๐ฌ๐ฑ๐ป(70)+๐ฌ๐ฑ๐ป(71)+๐ฌ๐ฑ๐ป(72)+๐ฌ๐ฑ๐ป(73)+๐ฌ๐ฑ๐ป(74)+๐ฌ๐ฑ๐ป(75)+๐ฌ๐ฑ๐ป(76)+๐ฌ๐ฑ๐ป(77)+๐ฌ๐ฑ๐ป(78)+๐ฌ๐ฑ๐ป(79)+๐ฌ๐ฑ๐ป(80)+๐ฌ๐ฑ๐ป(81)+๐ฌ๐ฑ๐ป(82)+๐ฌ๐ฑ๐ป(83)+๐ฌ๐ฑ๐ป(84)+๐ฌ๐ฑ๐ป(85)+๐ฌ๐ฑ๐ป(86)+๐ฌ๐ฑ๐ป(87)+๐ฌ๐ฑ๐ป(88)+๐ฌ๐ฑ๐ป(89)+๐ฌ๐ฑ๐ป(90)+๐ฌ๐ฑ๐ป(33)+๐ฌ๐ฑ๐ป(34)+๐ฌ๐ฑ๐ป(35)+๐ฌ๐ฑ๐ป(36)+๐ฌ๐ฑ๐ป(37)+๐ฌ๐ฑ๐ป(38)+๐ฌ๐ฑ๐ป(39)+๐ฌ๐ฑ๐ป(42)+๐ฌ๐ฑ๐ป(44)+๐ฌ๐ฑ๐ป(46)+๐ฌ๐ฑ๐ป(47)+๐ฌ๐ฑ๐ป(58)+๐ฌ๐ฑ๐ป(59)+๐ฌ๐ฑ๐ป(60)+๐ฌ๐ฑ๐ป(61)+๐ฌ๐ฑ๐ป(62)+๐ฌ๐ฑ๐ป(63)+๐ฌ๐ฑ๐ป(64)+๐ฌ๐ฑ๐ป(91)+๐ฌ๐ฑ๐ป(93)+๐ฌ๐ฑ๐ป(94)+๐ฌ๐ฑ๐ป(95)+๐ฌ๐ฑ๐ป(96)+๐ฌ๐ฑ๐ป(123)+๐ฌ๐ฑ๐ป(124)+๐ฌ๐ฑ๐ป(125)+๐ฌ๐ฑ๐ป(126))
Python supports most unicode letters, so it compiles to be the same as just print(chr(...)+...)
hmmm
while True:
print(c:=(lambda x:x[::-1])(input()))
if input()=='c':__import__("clpbrd").c(c);
when you golf too much and dont understand your own program anymore
seems like you're taking in a line of input, reversing it and storing it into c
then getting input again, if its c you copy the reversed text to the clipboard?
its a program to reverse text
you need to take an input, modify it, then print it
true ig
i can get rid of the print and have it automatically copy to my keyboard
but that would count as removing features so eh
### Reverse text to fix RTL text in outdated programs###
### Or you can use it for other things I do not care ###
import pyperclip
# Function to reverse input text, input text = x #
def reverse(x):
return x[::-1]
# Clear junk, only works in Windows command prompt #
clear = lambda: os.system('cls')
# Loop #
active = True
while active == True:
# Print a barrier for aesthetic reasons #
print("\n##############################################################\n CHIPS REVERSER NEW INPUT \n##############################################################\n")
# Asks for input then creates barrier (asthetic) and a new line to write input text in #
valueentered = input(str("Please enter your string to reverse \n ---------------------------------------------- \n"))
# Once entered, print a new barrier and a new line for the output #
print(" ---------------------------------------------- \n")
# Use function to reverse text #
valueoutput = reverse(valueentered)
# Print output aesthetically #
print("Output \n---------------------------------------------- \n", valueoutput, " \n---------------------------------------------- \n")
# Ask for command #
cask = input(str("Enter ""c"" to copy or ""e"" to end program : "))
# Check input for command, ignore if no command received #
if cask == ("c"):
pyperclip.copy(valueoutput) #Copy output to clipboard
print("Copied to clipboard!")
original
@rugged sparrow
make this more cryptic?
!e
z = ", ".join(map(str, [_**2 for _ in range(10)]))
print(z)
@rich hound :white_check_mark: Your eval job has completed with return code 0.
0, 1, 4, 9, 16, 25, 36, 49, 64, 81
wdym cryptic
exactly what i said
just change plain characters to chr(random equation with dumbass shir) and get rid of plain numbers and do some stuff
