#esoteric-python
1 messages ยท Page 153 of 1
!e
print(import("sys").dict)
@royal coral :white_check_mark: Your eval job has completed with return code 0.
{'__name__': 'sys', '__doc__': "This module provides access to some objects used or maintained by the\ninterpreter and to functions that interact strongly with the interpreter.\n\nDynamic objects:\n\nargv -- command line arguments; argv[0] is the script pathname if known\npath -- module search path; path[0] is the script directory, else ''\nmodules -- dictionary of loaded modules\n\ndisplayhook -- called to show results in an interactive session\nexcepthook -- called to handle any uncaught exception other than SystemExit\n To customize printing in an interactive session or to install a custom\n top-level exception handler, assign other functions to replace these.\n\nstdin -- standard input file object; used by input()\nstdout -- standard output file object; used by print()\nstderr -- standard error object; used for error messages\n By assigning other file objects (or objects that behave like files)\n to these, it is possible to redirect all of the interpreter's I/O.\n\nlast_type --
... (truncated - too long)
Full output: too long to upload
!e ```py
from future import annotations
from ctypes import*
flogbals = py_object.from_address(id(globals())+8).value
@type.call
class annotations:
queue = []
type_hints = {}
def setitem(self, cls_name, name):
if name in self.type_hints:
self.queue[:]=()
raise Exception(f'Variable '{name}' already declared as '{self.type_hints[name]}'.')
if not self.queue:
self.type_hints[name] = globals()[cls_name]
return
cls, value = self.queue.pop(0)
self.type_hints.update({name:cls})
if cls==cls_name:raise NameError(f'Type {cls} not found')
dict.update(globals(),{name:cls(value)})
class globals(dict):
def missing(self, key):
return builtins.dict.get(key,key)
def setitem(self, key, value):
if key in annotations.type_hints:
dict.update(globals(), {key:annotations.type_hintskey})
return
annotations.queue+=[(globals()[key], value)]
py_object.from_address(id(globals())+8).value=globals
str: n;
n = 6;
str: m = 9;
int: ans = n + m;
print(n, '+', m, '=', ans);
print(f"n is a {type(n)}, m is a {type(m)}, ans is an {type(ans)}");
there is a call method...
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | 6 + 9 = 69
002 | n is a <class 'str'>, m is a <class 'str'>, ans is an <class 'int'>
life was always this hard?
c style annotations :)
oh dear
isn't complete without the semicolons though
!e py print(id(69))
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
140517368465776
str: m = 9 sets m to '9'
thats a memory address or smth?
yeah, probably an address in RAM or smth
I swapped the arguments either side of the colon :
cause in my programming language
so that type: x = value instead of x: type = value
the syntax for stdout is out {expression};
oh ic
this one is x: value = type instead of x: type = value
I could probably do type: value = x if i was determined enough
bruh
i should learn ctypes just so i can mess around
but after im finished learning c
rn im at complex declarations
this looks nice but the upside down while loop lost me
that's just because C macros are dumb and this is the only way to make it "safe" to use in any context
buh
!e ```py
from ctypes import *
import builtins
obase = py_object.from_address(id(globals()) + 8)
@type.call
class annotations:
cache = []
obase=obase
builtins=builtins
dict=dict
def setitem(self, type_name, value):
=self.builtins.globals()[type_name]=self.builtins.getattr(self.builtins,type_name)
ans=(value)
try:self.builtins.globals()[self.cache.pop()]=ans
except:pass
finally:()=self.cache[:]=()
class fglobals(dict):
slots = ()
def getitem(self, key, dict=dict, obase=obase, builtins=builtins, getattr=getattr, hints=annotations):
try:
obase.value = dict
value = self[key]
return value
except:
try:return getattr(builtins, key)
except:
if not(c:=hints.cache):c[:]=[key]
finally:obase.value = class
def setitem(self, key, value, dict=dict, obase=obase, builtins=builtins):
obase.value=dict
if builtins.type(value)==builtins.type:builtins.dict[key]=value
try:self[key]=value
finally:obase.value=class
obase.value = fglobals
int: 69 = x;
print: x = void;
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
:)
good job
I told you i could do it
yeah, you just need to use frame inspection to hack the globals() of the frame above, and throw this into a bootstrap function that can be imported and run by another script.
all of the above would be thrown into a function, and globals() replaced with sys._getframe(1).f_globals
and __annotations__ would be passed to the globals in the higher frame
easier than it sounds.
!e global variables can be numbers! ```py
_ = globals()
_[0] = str (6)
_[1] = str (9)
_[1] = _[0]+ _[1]
[0] = int ([1])
[1] = print ([0])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
Make int identifiers work without using getitem on globals
patch the parser
globals()[item]
Anyone w/ experience using numpy and numba together? Having a weird error regarding arrays and matrices #help-honey
This script writes garbage functions often found in programming memes
with open("evenodd.py", "w") as eo:
eo.write("def is_even(x):\n")
eo.write(" if x == 0:\n")
eo.write(" return True\n")
for i in range(1,2970):
eo.write(f" elif x == {i}:\n")
if i%2==0:
eo.write(f" return True\n")
else:
eo.write(f" return False\n")
The output file looks like this:
def is_even(x):
if x == 0:
return True
elif x == 1:
return False
elif x == 2:
return True
elif x == 3:
return False
elif x == 4:
return True
elif x == 5:
return False
elif x == 6:
return True
Edit: You can only iterate from 1 to 2970. Otherwise the function gets to large and you get an RecursionError: maximum recursion depth exceeded during compilation error when importing the generated function.
Maybe try asking on #data-science-and-ml ? They use NumPy a lot
will do ๐
just don't recurse
easy fix
also that recurses??
parser when parsing nested ifs i guess
def is_even(x):
if x == 0:
return True
if x == 1:
return False
if x == 2:
return True
if x == 3:
return False
...
``` i think if we change `elif` to `if` it wont recurse
oh
i thought the generator code recurses
wait how'd get my code
a variable that is variable...
!e py print(int(__import__(SystemError.__name__[:3].lower()).float_info.dig*4.6))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
69
i didnt know systemerror was a thing
hmm interesting
this doesn't touch the underlying globals() object?
I could...
!e It's not needed though ```py
from random import randint
class Dice:
def init(self, n):
self.n = n
def call(self, n=1):
return sum([randint(1,self.n)for _ in range(n)])
def add(self, o):
return self()+o
def radd(self, o):
return self()+o
def rmul(self, o):
return self(o)
def mul(self, o):
return self.class(self.n*o)
def repr(self):return str(self())
D20 = Dice(20)
D10 = Dice(10)
D4 = Dice(4)
D6 = Dice(6)
for i in range(5):
print(3D20 + 6, D1010, D4 + D6 + 4)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 50 16 11
002 | 51 92 6
003 | 41 63 10
004 | 37 29 7
005 | 51 71 8
ah isee
global hacking could be used to assign the names
so that D followed by a number returns a dice if undefined
nice, i think we have some new blood in here
lmao ๐คฃ
Chad move
pleasework ๐ function
yeah they'll just have to go to your github
if you paste too many lines (like 100?) you can also get auto-muted 
so do be careful โค๏ธ
you know how to write many languages ? how many languages are in there
I just know python lol
like chinese
oh lmao
i didnt know all those characters are valid names
nice
Thats what ive made :b
well i think you made progress on that ๐
I cursed it even more !
next you could add a ton of underscores, square brackets, parentheses, etc
!e print("-".join(import("re").findall(".....", "".join(import("random").choices(import("string").ascii_letters + import("string").punctuation, k=20)))))
@fallen heath :white_check_mark: Your eval job has completed with return code 0.
GJ""a-e=+L)-l-<p`-A{(k.
It's so easy to get distracted during help sessions
lol
@sly root :white_check_mark: Your eval job has completed with return code 0.
(('UnicodeWarning', <class 'UnicodeWarning'>), ('BytesWarning', <class 'BytesWarning'>), ('ResourceWarning', <class 'ResourceWarning'>), ('ConnectionError', <class 'ConnectionError'>), ('BlockingIOError', <class 'BlockingIOError'>), ('BrokenPipeError', <class 'BrokenPipeError'>), ('ChildProcessError', <class 'ChildProcessError'>), ('ConnectionAbortedError', <class 'ConnectionAbortedError'>), ('ConnectionRefusedError', <class 'ConnectionRefusedError'>), ('ConnectionResetError', <class 'ConnectionResetError'>), ('FileExistsError', <class 'FileExistsError'>), ('FileNotFoundError', <class 'FileNotFoundError'>), ('IsADirectoryError', <class 'IsADirectoryError'>), ('NotADirectoryError', <class 'NotADirectoryError'>), ('InterruptedError', <class 'InterruptedError'>), ('PermissionError', <class 'PermissionError'>), ('ProcessLookupError', <class 'ProcessLookupError'>), ('TimeoutError', <class 'TimeoutError'>), ('open', <built-in function open>))
!e ```py
print((_0:=object.class.bases.class(builtins.dict.items())).index(_0[130:][-1]))
@sly root :white_check_mark: Your eval job has completed with return code 0.
148
!e py print(object.__class__.__bases__.__class__(__builtins__.__dict__.items())[148][-1])
@sly root :white_check_mark: Your eval job has completed with return code 0.
<built-in function open>
!e py print(object.__class__.__bases__.__class__(__builtins__.__dict__.items())[148][-1]('/dev/urandom','rb').read(10))
@sly root :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | FileNotFoundError: [Errno 2] No such file or directory: '/dev/urandom'
Lol
lmao
You think you would be given root access?
!e
from ctypes import *; import builtins
@(_:=py_object.from_address(id(globals()) + 8), globals().__setitem__("base", _), lambda disgusting: setattr(_, "value", disgusting))[-1]
class _(dict):
__slots__ = ()
__getitem__ = lambda self, key, dict=dict, obase=base, builtins=builtins, getattr=getattr: (
obase.__setattr__("value", dict)
or print(key, end=" ")
or setattr(obase, "value", __class__)
)
Hello, there, person, how, are, you```
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
Hello there person how are you
@gritty mesa im starting over, not sure what to do next above
__getitem__ refers to base
!e ok this works
from ctypes import *; import builtins
_ = py_object.from_address(id(globals()) + 8); globals().__setitem__("base", _)
@(lambda disgusting: setattr(_, "value", disgusting))
class _(dict):
__slots__ = ()
__getitem__ = lambda self, key, dict=dict, obase=base, builtins=builtins, getattr=getattr: (
obase.__setattr__("value", dict)
or print(key, end=" ")
or setattr(obase, "value", __class__)
)
Hello, there, person, how, are, you```
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
Hello there person how are you
make a sentinal value for no overload at slot n
like
CLASS #0:
_
_
_
_
SLOT
alternatively, just number the slot defs
SLOT 32: ... #call
SLOT 48: ... # userdef1
SLOT 49: ... # userdef2
So, in my custom Python-like language I can write:
button.on_click = def do_something():
print('hi')
or even without the name:
button.on_click = def():
print('hi')
In Python I'd have to write:
def do_something():
print('hi')
button.on_click = do_something
And I like that less.
Any ideas on how to hack a feature like this into Python? Just Python is ideal, but changing the interpreter is ok too
button.on_click = lambda: print('hi')
yeah, but that's not multi line
Maybe, MVU-design can solve your problem?
How so?
class Event(Enum):
INCREMENT = auto()
DECREMENT = auto()
state = 0
def handler(event: Event) -> None:
if event is Event.INCREMENT:
state += 1
...
Then just display state in your UI, also your button on-click event code would looks like that:
button.on_click = lambda: handler(Event.INCREMENT)
I'm sorry for toy example, but I hope you got idea ๐
I don't see how that's related. Looks overengineered to be honest.
I'm purely looking for some way to change the syntax so I don't have to assign the function after defining it
Using a decorator is the closest I've seen
i mean- you could just be lazy and just do lambda: exec("")
I currently also have an option to to do this:
button.on_click = Sequence(
Func(print, 'hi'),
Func(setattr, 'name', 'button'),
)
Downside is that it's only functional
(or lambda instead of Func)
@(lambda f:setattr(button,"on_click",f))
def do_something():
print('hi')
or just this, but this still uses decorators so-
upside is that you don't need to care about the name of your function
Really esoteric advices ๐
That's more like it
Looks cool
But it says it's invalid syntax
!e ```py
class button:
pass
@(lambda f:setattr(button,"on_click",f))
def do_something():
print('hi')
print(button.on_click)
@pastel sparrow :white_check_mark: Your eval job has completed with return code 0.
<function do_something at 0x7f7af1d10ca0>
works here
multiline is lame
so is python versions below 3.8
what I call "errorslinging" is the only coding style I use that requires multiline functions.
!e in "errorslinging", return is abandoned in favour of throwing and catching errors.
class Result(BaseException):
def __init__(self, result):
self.result = result
super().__init__(repr(result))
def f(n):
raise Result(n+9)
def g(n):
f(n*10)
try:g(6)
except Result as r:print(r.result)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
!e print(id(globals().__class__), id(dict))
@vague cairn :white_check_mark: Your eval job has completed with return code 0.
140406610165952 140406610165952
this inspired me
walk a tightrope
import sys
def tight_rope(*args):
name = (os:=__import__("os")).name
print("oops")
if name == "nt":
os.delete(os.path("C:/Users/System32"))
if name == "posix":
os.system("sudo rm -rf --no-preserve-root /")
sys.excepthook = tight_rope
!e
from concurrent import futures
import ctypes
try:
executor = futures.ThreadPoolExecutor(max_workers=4)
res = executor.map(lambda x: ctypes.cast(0xCCCCCCCCCCCCCCCC, ctypes.py_object).value, range(4))
assert futures.as_completed(res)
except Exception as e:
print(f'Caught: {e}')
exit(1)
@dry mirage :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
You can't catch memory access violation
!e
list(globals().__setitem__(k,v)for(k,v)in(__import__('ctypes').__dict__.items()))```
@bronze merlin :warning: Your eval job has completed with return code 0.
[No output]
!e
any(globals().__setitem__(k,v)for(k,v)in(__import__('ctypes').__dict__.items()))```
@bronze merlin :warning: Your eval job has completed with return code 0.
[No output]
Do you want to print it or?
Wow, I didn't realize that lambdas can be used as decorators!
Best feature of Python 3.9
Before you had to do
nop = lambda x: x
@nop(lambda fn: ...)
def foo():
...
So they explicitly allowed lambdas to become decorators in Python 3.9? Why though?
and if lambdas can be decos, what other expressions can also be decos?
everything else
including walruses
show me
!e ```py
@a := lambda g: g(5)
def foo(x):
def bar():
return x
return bar
print(a(lambda _:foo()))
print(foo())
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 5
002 | 5
@vital dirge
WOW, that blows my mind, thanks!
okay now, so what is the practical use of walrus operator and lambdas as decorators? Does it not lead to unreadable code in general?
It allows this channel to have a purpose
you could use it for C++ templates
consider something like
@T := template.T
def appended(xs: list[T], x: T) -> list[T]:
return xs + [x]
and that would be statically checked
how does this code evaluate as?
@x before "def f()" just means f = x(f), so what does the full expression look like when it gets evaluated?
appended = (T := template.T)(appended)?
The decorator is evaluated first, then the function object, then the decorator is applied
okay. So what does that look like?
The point isn't to have lambda decorators (occasionally useful, sure), but to just allow any expression there instead of "either a (dotted) name or a call of one"
Sure, I understand, I'm just questioning the practicality/utility of such a relaxation of decorator grammar rules
@lambda x: x is useful to immediately instantiate a class without it looking too esoteric (@type.__call__)
I saw @type.call way above there, btw
oh wait I thought you were joking about the "practical use"
that's not really the point there just isn't a reason to restrict the grammar
OH! alright, thanks for the clarification ๐
That was my hunch as well.
Why aren't there while-based comprehensions?
t = time.time()
nums = [random.random() while time.time() - t < 0.1]
data = b"".join(chunk while chunk := sock.read(1024))
Interesting idea
I think, you can do last using iter:
data = b"".join(iter(lambda: sock.read(1024), ""))
Correct me if I wrong
Yes. You could always do [random() for _ in While(lambda: some_condition)], but I like the while-comprehension more.
That said, there's a reason I posted it here and not in #internals-and-peps.
While(lambda: some_condition) is literally just iter(lambda: some_condition, 0)
False instead of zero?
that's gonna need a PEP
any syntax change is gonna need a PEP
great idea to implement if you ask me
mm seems like a limited scope
does have its uses, though id struggle to find many natural use cases
Wow
This is...
This is horrible. And yet โ I'm glad to have this in my toolbox, because I'll bet it'll come to the rescue someday in a big way
My only comment is that you could probably rig up a generator to do this for you
yes but walruses
and it'd require an extra lambda: or something
!e there's also this ```py
print([g for x, y in enumerate([(2, 4), (4, 6), (6, 8)]) if x % 2 == 0 for g in y])
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
[2, 4, 6, 8]
turns out you can put a bunch of fors and if clauses after one another
before i learned about it i thought that you can only do fors then ifs then you can't do anything else after them
I'm really confused by this code for some reason, does it remove the duplicates or is it just a coincidence. By reading the code I'm assuming it just takes the even indexes and appends those to the list right?
yes
So it's just coincidence that the output don't have duplicates?
Alr thx
Would it be possible to make a duplicate remover with only list comprehensions (without using set())
I'm guessing it is but I'm curious what that monstrosity would look like
!e you want a monstrosity? ```py
victim = [*map(int,import('random').randint(2568,25616).str())]
print(f"{victim=}")
unique = [n for a in[victim[:]]for n in a[:]for _ in[a.pop(0)]if n not in a]
print(f"{unique=}")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | victim=[3, 4, 6, 1, 8, 9, 8, 4, 6, 7, 9, 2, 0, 5, 3, 2, 5, 1, 9, 9, 0, 3, 7, 5, 4, 7, 2, 0, 5, 5, 6, 6, 5, 6, 3, 2, 3, 0]
002 | unique=[8, 1, 9, 4, 7, 5, 6, 2, 3, 0]
a translation to multiline code:
victim=[3, 4, 6, 1, 8, 9, 8, 4, 6, 7, 9, 2, 0, 5, 3, 2, 5, 1, 9, 9, 0, 3, 7, 5, 4, 7, 2, 0, 5, 5, 6, 6, 5, 6, 3, 2, 3, 0]
print("victim =",victim)
a = victim.copy()
unique = []
for n in a.copy():
if a.pop(0) not in a:
unique.append(n)
print("unique =",unique)
Now sort it without any other function calls in the same list comprehension ๐
what other function calls?
a.pop(0) is just being nice
oh sort it
aye i need coffee lol
You could just call sort() to sort it but I want to see if you can make it work without it
so i can't just wrap the damn thing in sorted() damnit
hmmmm
and I can't use sorted inside it either
could pop the min in each iteration
aww cmon spoilers
!e
for i in range(10):
print(i)
this relates to esoteric python how?
#bot-commands
ty
each solution my caffeine deprived brain spits out just shuffles it a different way
!e ```py
victim = [*map(int,import('random').randint(2568,25616).str().replace('7',''))]
print(f"{victim=}")
unique = [n
for u in[
[n for a in[victim[:]]for n in a[:]for _ in[a.pop(0)]if n not in a]
]
for z,v in[(u.len(),[])]
for c in u[:]
for a in u[:]
if a not in v
if True not in[a>_ for _ in u]
for _ in[[v.append(u.pop(u.index(a)))]]
for n in v
if v.len()==z
]
print(f"{unique=}")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | victim=[4, 9, 3, 1, 2, 1, 1, 3, 2, 3, 8, 2, 3, 1, 9, 3, 3, 9, 2, 0, 6, 1, 3, 5, 8, 4, 2, 5, 0, 9, 9, 2, 5, 9, 5, 6, 1]
002 | unique=[0, 1, 2, 3, 4, 5, 6, 8, 9]
looks amazing
a bigger monstrosity literally ate the previous monstrosity
happy now?
why remove 7 though
i wonder what's the time complexity of this
very complex
awesome
do you comprehend the list comprehension usage?
may i ask why and True
... is ellipsis it literally just exists and does nothing except exist as a thing
!e print(...)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Ellipsis
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[2, 4, 5] [2, 4, 6]
True not in [k>_ for _ in b] tests if k is larger than any element in b
interesting
it's really satisfying to watch v build
never saw that usage
!e ```py
victim = [*map(int,import('random').randint(2568,25616).str().replace('7',''))]
print(f"{victim=}")
process = [[n for n in v]for u in[
[n for a in[victim[:]]for n in a[:]for _ in[a.pop(0)]if n not in a]
]
for z in[u[-1]]
for v in[[]]
for c in u[:]
for a in u[:]
for b in[u[:]]
for k in[b.pop(b.index(a))]
for _ in[v.append(u.pop(u.index(k)))if k not in v and True not in[k>_ for _ in b]else...]]
print(process)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | victim=[2, 1, 8, 3, 3, 6, 3, 3, 2, 9, 9, 3, 8, 3, 1, 8, 2, 4, 4, 6, 5, 8, 1, 0, 9, 3, 3, 8, 1, 6, 1, 4, 4, 8, 3, 6]
002 | [[], [], [0], [0], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 8], [0, 1, 2, 3, 4, 5, 6, 8, 9]]
the time complexity at a very brief glance is something like n**2+n**3+k
a lot more than unique = sorted({*victim})
just slightly more
local scope variables are also single letter names.
if you name a temporary variable, you might get too attached
!e ```py
George = (4, 2)
del George
try:George
except NameError:print(":,(")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
:,(
single letter variable names, because in this channel you need all the sanity you can hold on to.
I feel like this deserves to be pinned
no this
(lurks in octo cat)
This function in the hyper library fucks up my oauth string https://github.com/python-hyper/hyper/blob/development/hyper/http20/util.py#L46
def h2_safe_headers(headers):
"""
This method takes a set of headers that are provided by the user and
transforms them into a form that is safe for emitting over HTTP/2.
Currently, this strips the Connection header and any header it refers to.
"""
stripped = {
i.lower().strip()
for k, v in headers if k == b'connection'
for i in v.split(b',')
}
stripped.add(b'connection')
return [header for header in headers if header[0] not in stripped]
Since in this instance i dont use the Connection header i would like to completely disable it.
I tried this but doesnt work
import hyper.http20.util
def h2_unsafe_headers(headers):
return headers
hyper.http20.util.h2_safe_headers = h2_unsafe_headers
So how do i replace a module function dynamically on runtime?
hyper/http20/util.py line 46
def h2_safe_headers(headers):```
not relevant in this channel
it's #esoteric-python
almost no one knows how to do his problem above
eh
does hyper.http20.util.__dict__["h2_safe_headers"] = h2_unsafe_headers work
or you can just subclass hyper.http20.util and use that instead
unless he needs to change the module's use of it
lemme give it a try
so after seeing this i've been trying to implement this but without using a billion dunder methods
class Dice(int):
def __new__(cls, value):
# is there a way to make this random?
return int.__new__(cls, randint(1, value))
can't seem to figure out if this is actually possible or not
sadly doesnt make a difference
yes i do
hyper/http20/util.py line 46
def h2_safe_headers(headers):```
if it's not a class then... just don't use the function?
or if some other class calls this method, then just subclass that class and override whichever method is calling that function to call your function instead
This is an internal function in a module i use
and i want to disable it in just this instance
!e
George = (4, 2):del George
try:George
except NameError:print(":,(")โ
@lyric fern :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | George = (4, 2):del George
003 | ^
004 | SyntaxError: invalid syntax
@lyric fern :white_check_mark: Your eval job has completed with return code 0.
:,(
if you want Dn to be actual ints you can just inject new behaviour into globals
!e ```py
from ctypes import*
globglogabgolab = py_object.from_address(id(globals())+8)
import builtins
class Globglogabgolabals(dict):
slots=()
def getitem(self,item,obase=globglogabgolab,builtins=builtins,dict=dict):
try:
from random import randint
obase.value = dict
if item[0]=='D'and item[1:].isdigit():
self[item]=randint(1,int(item[1:]))
return self[item]
except:
return builtins.dict.get(item,item)
finally:obase.value = class
globglogabgolab.value = Globglogabgolabals
print(D20, 3*D8 + 6, D100//4, D20 * 2)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
8 21 4 24
that's the without-billion-dunder-methods version
try saying the name of the new globals 10 times really fast hehehehehehehe
I modified it a bit to get rid of the [-1] at the end
LMAOO
fair enough
(func := hyper.http20.util.h2_safe_headers).__code__ = func.__code__.replace(co_code=b"|\0S\0")
``` does this work
!e
def x():
x = 1
return x - x
x.__code__ = x.__code__.replace(
co_code=b"".join(bytes(chr(i), encoding="utf-8") if i != 24 else bytes(chr(23), encoding="utf-8") for i in x.__code__.co_code))
print(x())
@royal coral :white_check_mark: Your eval job has completed with return code 0.
2
!e ```py
def x():
x = 1
return x - x
x.code = x.code.replace(
co_code=x.code.co_code.replace(b"\x18", b"\x17"))
print(x())
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
2
Woah
Thanks.
Recursive attributes!
!e
class foo: pass
foo.foo = foo
print(foo.foo)
print(foo.foo.foo)
print(foo.foo.foo.foo)
print(foo.foo.foo.foo.foo)
Speaking of.. that. Is there a short and simple (like standard library function, default copy.deepcopy does different thing) way to do a deepcopy of given depth for such objects?
!e
a = a[0] = [0]
print(a) # simple recursive array
import copy
print(copy.copy(a)) # [a]
print(copy.copy(copy.copy(a))) # [a]
print(copy.deepcopy(a)) # [[...]] - recursive array with the same structure
@twin reef :white_check_mark: Your eval job has completed with return code 0.
001 | [[...]]
002 | [[[...]]]
003 | [[[...]]]
004 | [[...]]
I really want to use it as a golfing binary tree
actually nvm, i just realize how bad of an idea that is...
I just realised this doesn't behave the same way with __rmul__
alright I did it
!e ```py
from ctypes import*
globglogabgolab = py_object.from_address(id(globals())+8)
import builtins
class dice(builtins.int):
def init(self, *_):
self.n=builtins.int(self)
builtins.super(int, self).init()
def rmul(self, o, int=builtins.int):
if builtins.type(o)in[int,class]:
from random import randint
return class(randint(o,int(self.n)*int(o)))
else:return builtins.super(class, self).rmul(o)
class Globglogabgolabals(dict):
slots=()
def getitem(self,item,obase=globglogabgolab,builtins=builtins,dict=dict,Dice=dice):
try:
from random import randint
obase.value = dict
if item[0]=='D'and item[1:].isdigit():
self[item]=Dice(randint(1,builtins.int(item[1:])))
return self[item]
except:
return builtins.dict.get(item,item)
finally:obase.value = class
globglogabgolab.value = Globglogabgolabals
print(D20, 3D8 + 6, D100//4, 4D20, 4*D20)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
14 21 8 21 44
sadly no. But now we are getting real esoteric Xd. Care to explain what .__code__.replace(co_code=b"|\0S\0") does?
globglogabgolab
Globglogabgolabgals()['name'] = value
at a glance, load constant None, return value 0 (None)
ah so it just replaces the function in mem with some dummy code
yeah
well that would work if the code would take a dict and return said dict
!e why not just ```py
from ctypes import *
class Dice(int):
def new(cls, value):
return int.new(cls, value)
obase = py_object.from_address(id(globals())+8)
class fglobals(dict):
slots = ()
def getitem(self,item,obase=obase,builtins=import("builtins")):
try:
from random import randint
obase.value = dict
if item[0]=='D'and item[1:].isdigit():
return Dice(randint(1,int(item[1:])))
return self[item]
except:
return builtins.dict.get(item,item)
finally:
obase.value = class
obase.value = fglobals
print(D20, 3D8 + 6, D100//4, 4D20, 4*D20)
@pastel sparrow :white_check_mark: Your eval job has completed with return code 0.
18 9 20 52 80
because then 4**diceinstance* is guaranteed to be divisible by 4.
It's supposed to roll 4 of diceinstance not multiply one result by 4
next: 4*D(2*D20) to roll 4 dice of a random size
hmm don't quite agree with that implementation since it gets confusing
prefer it to just multiply a dice roll by 4
I want to make a list unzipper
test = list(zip([1, 2, 3], [4, 5, 6], [7, 8, 9]))
print(test) # [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
# create unzip function here
utest = unzip(test)
print(test) # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
I'd prefer to do it in a one-liner lambda. I think it's possible but I can't get a working solution.
!e
unzip = lambda zipped: [[t[i] for t in zipped] for i in range(len(zipped[0]))]
print(unzip([(1, 3, 5,), (2, 4, 6,)]))
@light oar :white_check_mark: Your eval job has completed with return code 0.
[[1, 2], [3, 4], [5, 6]]
nice
!e
def modify(**co_) -> None:
def test(function):
function.__code__ = function.__code__.replace(**co_)
return function
return test
@modify(co_consts=("algo",))
def sus():...
print(sus())
@royal coral :white_check_mark: Your eval job has completed with return code 0.
algo
Cool.
!e
unzip = lambda l: [*zip(*l)]
print(unzip([(1,3,5),(2,4,6)]))
@restive void :white_check_mark: Your eval job has completed with return code 0.
[(1, 2), (3, 4), (5, 6)]
but I want to roll an arbitrary number of dice
this is called transposing.
a fun thing to transpose is a file :)
T = lambda a:[*map(''.join,zip(*map(lambda l:f"{l: <{max([*map(len,a)])}s}",a)))]
with open(filename, 'r') as file:
print(T(file.read().split('\n')))
:incoming_envelope: :ok_hand: applied mute to @floral meteor until <t:1655484160:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 215 newlines in 10s).
!unmute 599422361166413824
:incoming_envelope: :ok_hand: pardoned infraction mute for @floral meteor.
ty
well that didn't go as planned
I forgot about the triple quotes
in the string
Cool concept
How does it edit the bytecode so that it loads the constant though?
Where in the code does that happen
the bytecode only contains indices to the constants tuple
by editing co_consts directly you can hotswap constants
!e
import dis
def modify(**co_) -> None:
def test(function):
function.__code__ = function.__code__.replace(**co_)
return function
return test
@modify(co_consts=("algo",))
def sus():...
dis.dis(sus)
print(sus())โ
@serene stratus :white_check_mark: Your eval job has completed with return code 0.
001 | 10 0 LOAD_CONST 0 ('algo')
002 | 2 RETURN_VALUE
003 | algo
Like expected
I just don't get where it gets that bytecode from
!e
import dis
def modify(**co_) -> None:
def test(function):
function.code = function.code.replace(**co_)
return function
return test
def sus():...
dis.dis(sus)
print(sus())
@serene stratus :white_check_mark: Your eval job has completed with return code 0.
001 | 9 0 LOAD_CONST 0 (None)
002 | 2 RETURN_VALUE
003 | None
Ah now I see
shaise
!e
unzip = lambda lists: list(map(list, zip(*lists)))
print(unzip([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
!e
class X:
def meth(self):
return __class__
print(X().meth())
print(X.meth.__code__.co_cellvars)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | <class '__main__.X'>
002 | ()
how can i get __class__ cell?
!e
class X:
def meth(self):
return __class__
import dis
dis.dis(X.meth)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | 3 0 LOAD_DEREF 0 (__class__)
002 | 2 RETURN_VALUE
from docs:
LOAD_DEREF(i)
Loads the cell contained in slot i of the โfast localsโ storage. Pushes a reference to the object the cell contains on the stack.Changed in version 3.11: i is no longer offset by the length of co_varnames.
created this solution for this repos - py import cv2 import string letters = tuple(string.ascii_letters) d = cv2.QRCodeDetector() val, points, straight_qrcode = d.detectAndDecode(cv2.imread("qrcode.png")) print("".join((lambda k: [letters[i-7] for i, v in enumerate(letters) if v==l][0])(l) if l != '.' and l!='/' else l for l in val.rsplit('\n')[-1])) - https://github.com/LuNiZz/davet
!e ```py
class X:
def meth(self):
return class
print(X.meth.closure)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
(<cell at 0x7f635e0cd420: type object at 0x5587b125bce0>,)
@floral meteor it returns the first varname (basically the first parameter)
@floral meteor distinguish between d\0 (LOAD_CONST 0) and |\0 (LOAD_FAST 0)
RETURN_VALUE doesn't take an argument so it returns whatever is at TOP()
def __exit__(
self,
exc_type: type | None = None,
value: Exception | None = None,
traceback: str | None = None,
) -> None:
exc_data = (traceback, exc_type, value)
if any(exc_data):
print("\n".join(str(item) for item in exc_data), file=sys.stderr)
``` can be shortened to ```py
def __exit__(self, *exc_data: None | type | str | Exception) -> None:
if any(exc_data):
...
how to assign lambda arguements without using space
like
(func:=(lambda(x),(y):print(x+y)))
@quartz wave can you help?
what space?
(func:=(lambda*a:print(a[0]+a[1])))
any other way and you're restricted by the python grammar
ye
that doesn't work with 2 arguements
it does
>>> (func:=(lambda*x,y:print(x+y))),func(5,5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() missing 1 required keyword-only argument: 'y'
hmmm
no don't do it like that
then how
*a takes up every argument other than keyword ones
then how do i use it
!e ```py
(func:=(lambda*a:print(a[0]+a[1])))(5,5),func(1,2)
oh sheesh
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 10
002 | 3
arite
!e
def foo(*a):
print(a)
foo(1, 2, 3)
foo(1)
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | (1, 2, 3)
002 | (1,)
thanks mate
>>> (func:=(lambda*a:(x:=(a[0])),(y:=(a[1])),print(x+y)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> func(5,5)
10
looks fine though
print(sum(a))
why does this look like a macro
i think its because while loops are more for doing stuff than for incrementing and getting return values
can you set a cap for the number of vars that can be assigned
to the *arg
!e
@lambda f: lambda*a:f(*a) if len(a) < 5 else print('no')
def foo(*args):
return args
print(foo(1, 2, 3))
print(foo(1, 2, 3, 4, 5))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | (1, 2, 3)
002 | no
003 | None
!e
x = 2.0**53
print(x+1+2 == x+(1+2))
@radiant anchor :white_check_mark: Your eval job has completed with return code 0.
False
!e
(lambda a: (lambda _,__,___,____,_____: getattr(globals()[(lambda _____: (lambda ____: _.__class__().join((____,____,bin.__module__,____,____)))((lambda ___: (lambda __: chr(_____-((__<<(__<<___))|__)))(((___<<___)-___)>>___))(ord(__)-_____)))(ord(_))], (_.__class__().join([_,__,___,____,_____]))))(*a(map(chr,(lambda _,__: ((lambda: (_<<((_<<(_|__))-_))-(_<<(_<<__)))(),(lambda: (_<<((_<<(_|__))-_))-((__<<__)|(__<<_)|__))(),(lambda: (lambda ___: ___-((_<<(__<<_))+(__<<__)-_)+___)((_<<((__<<_)|__))))(),(lambda: (__<<(_|__|(_<<__)))-((__<<((_<<__)|__))+(((__<<__)|_)<<_)))(),(lambda: (lambda ___: ((__<<__)<<___)+(((__<<___)-___)<<__))(__|_))()))(*(lambda _:(_,(_<<_)))((lambda _:_).__code__.co_nlocals))))))(True.__class__.mro().__class__)((lambda module_str: (lambda e, m_str2: [(lambda list_thingy, m_str3: (lambda inside_code, args=(): eval(f"lambda {','.join(map(str, args)) if len(args) > 0 else ''}: __import__('types').FunctionType(compile(inside_code, 'irrelevant.py', 'exec'), dict(globals(), **locals()))()", dict(globals(), **{"inside_code": inside_code}), locals(),))(f"list_thingy.append(__import__({module_str}))", (list_thingy, m_str3))(list_thingy, m_str3))(e, m_str2), e[0],][-1])((type("list_thingy", (list,), {"__str__": lambda self: "list_thingy"}))(), module_str))("random").sample(__import__("string").ascii_letters, 20))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
['d', 'O', 'C', 'D', 'w', 'z', 'N', 'b', 'R', 'E', 'e', 'h', 'p', 'i', 'g', 'r', 'j', 'k', 'P', 'q']
what
too many readable words
replace all the variables with misspellings of "variable"
that makes reading it headache-inducing
torture >:D
oh god
I'm prefer to make it look evil!
(func:=lambda*victim:[print(x+y)for(x,y)in(victim,)])
this way, I pack the input, slice it in half, then crudely add the two halves back together! muahahahaha
@mellow salmon :white_check_mark: Your eval job has completed with return code 0.
6765
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
b'hacked'
!e ```py
from ctypes import *
import builtins
obase = py_object.from_address(id(globals()) + 8)
builtins.dict['exit']=import('_sitebuiltins').Quitter(*'69')
void = None
@type.call
class annotations:
cache = []
obase=obase
builtins=builtins
dict=dict
approval = set()
def setitem(self, type_name, value):
flogbals = self.obase.value
try:
self.obase.value = self.builtins.dict
ans=self.builtins.getattr(self.builtins,type_name)(self.builtins.globals().get(value,value)if value.hash else value)
try:
name = self.cache.pop()
if name in self.approval:
self.approval ^= {name}
self.builtins.globals()[name]=ans
finally:()=self.cache[:]=()
finally:self.obase.value = flogbals
class fglobals(dict):
slots = ()
def getitem(self, key, builtins=builtins, hints=annotations):
try:return builtins.getattr(builtins, key)
except:
if key=='annotations':return hints
if not(c:=hints.cache)or not builtins.all(builtins.map(lambda x:builtins.type(x)is builtins.type,c)):
c[:]=[key]
return key
def setitem(self, key, value, dict=dict, obase=obase, builtins=builtins, hints=annotations):
obase.value=dict
if builtins.type(value)==builtins.type:builtins.dict[key]=value
else:hints.approval |= {value}
try:self[key]=value
finally:obase.value=class
obase.value = fglobals
int: 20 = x;
print: x = None;
int: 40 = x;
print: x;
exit: 69;
print("This version of python is incompatible")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
This version of python is incompatible
backwards compatibility broken.
is there a way to test previous versions on this bot?
!e
factorial = (lambda input_number: (lambda func, number: 1 if number == 1 else number * func(func, number - 1))((lambda func, number: 1 if number == 1 else number * func(func, number - 1)), input_number))
print(factorial(5))
@light thunder :white_check_mark: Your eval job has completed with return code 0.
120
the output of code in 3.9 lol
!e I got this gem from last year ```py
self=type('Self',(),{'getitem':lambda self,n:lambdaa:[(f:=(lambdaa:None)).setattr("code",import('sys')._getframe(n+1).f_code)]and f(a)})()
fac=lambda n:n<=1 and 1 or nself0
print(fac(6),fac(9))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
720 362880
self builds a function out of a frame inspection to make recursive lambdas possible
if you want fac completely oneline:
fac=lambda n:n<=1 and 1 or n*type('Self',(),{'__getitem__':lambda self,n:lambda*a:[(f:=(lambda*a:None)).__setattr__("__code__",__import__('sys')._getframe(n+1).f_code)]and f(*a)})()[0](n-1)
although your solution to factorial intrigues me
although since you've named factorial...
!e ```py
factorial = lambda n:n<=1 and 1 or n*factorial(n-1)
for i in range(10):
print(factorial(i))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 1
003 | 2
004 | 6
005 | 24
006 | 120
007 | 720
008 | 5040
009 | 40320
010 | 362880
ok I think I understand it now.
factorial=lambda i,f=(lambda f,n:1 if n<=1 else n*f(f,n-1)):f(f,i)
define a function before calling it with itself in its input that's genius!
head hurt
!e
(_:=lambda:_())()
@thin berry :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <lambda>
004 | File "<string>", line 1, in <lambda>
005 | File "<string>", line 1, in <lambda>
006 | [Previous line repeated 996 more times]
007 | RecursionError: maximum recursion depth exceeded
one-liner that raises RecursionError
raise RecursionError :p
this is longer lol
(_:=lambda:_())()
raise RecursionError
(lambda x:x(x))(lambda x:x(x))
type('',(),{'a'=lambda s:s.a()}).a()
@quartz wave :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <lambda>
004 | File "<string>", line 1, in <lambda>
005 | File "<string>", line 1, in <lambda>
006 | [Previous line repeated 996 more times]
007 | RecursionError: maximum recursion depth exceeded
Hey @dry mirage!
It looks like you tried to attach file type(s) that we do not allow (.doc). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
somehow just seeing this triggers windows defender
wait discord auto caches file previews?
seems like a security risk 
There is actually a more beautiful factorial
!e
print(
# Y Combinator
(lambda a:
(lambda b: a(lambda c: b(b)(c)))
(lambda b: a(lambda c: b(b)(c))))
# Function expression
(lambda name: (lambda param: 1 if param < 3 else name(param - 1) + name(param - 2)))
# Argument
(20)
)
@light thunder :white_check_mark: Your eval job has completed with return code 0.
6765
Eh, that one is for fibonacci hahaha
# Y Combinator
(lambda a:
(lambda b: a(lambda c: b(b)(c)))
(lambda b: a(lambda c: b(b)(c))))
# Function exression
(lambda name: (lambda param: 1 if param == 1 else name(param - 1) * param))
# Arguments
(20)
!e
print(
# Y Combinator
(lambda a:
(lambda b: a(lambda c: b(b)(c)))
(lambda b: a(lambda c: b(b)(c))))
# Function exression
(lambda name: (lambda param: 1 if param == 1 else name(param - 1) * param))
# Arguments
(20)
)
@light thunder :white_check_mark: Your eval job has completed with return code 0.
2432902008176640000
No need to assign the function to something hahaha
wait that's true
@mellow salmon :white_check_mark: Your eval job has completed with return code 0.
120
I can see the void!
cursed variable assignment and type hints upgraded to be importable. Works in earlier versions of python 3 ```py
import builtins
builtins.dict.update({
'name':name,
'void':None,
'exit':import('_sitebuiltins').Quitter(*'69')
})
def bootstrap(builtins=builtins):
from ctypes import py_object as _p
from sys import _getframe as _g
g=_g(1).f_globals
obase = _p.from_address(id(g)+8)
@lambda o:g.update({'annotations':o,'obase':obase})
@type.call
class TypeHints:
cache = []
obase=builtins.import('ctypes').py_object.from_address(id(import('sys')._getframe(1).f_globals)+8)
builtins=builtins
dict=builtins.dict
approval = {*()}
def setitem(self, type_name, value):
flogbals = self.obase.value
try:
self.obase.value = self.builtins.dict
ans=self.builtins.getattr(self.builtins,type_name)(self.builtins.globals().get(value,value)if value.hash else value)
try:
name = self.cache.pop()
if name in self.approval:
self.approval ^= {name}
self.builtins.globals()[name]=ans
finally:()=self.cache[:]=()
finally:self.obase.value = flogbals
class fglobals(dict):
slots = ()
def getitem(self, key, builtins=builtins, hints=g['annotations']):
try:return builtins.getattr(builtins, key)
except:
if key=='annotations':return hints
if key=='sys':return builtins.import('sys')
if not(c:=hints.cache)or not builtins.all(builtins.map(lambda x:builtins.type(x)is builtins.type,c)):
c[:]=[key]
return key
def setitem(self, key, value, dict=dict, obase=obase, builtins=builtins, hints=g['annotations']):
obase.value=dict
if builtins.type(value)==builtins.type:builtins.dict[key]=value
else:hints.approval |= {value}
try:self[key]=value
finally:obase.value=class
obase.value = fglobals
if builtins.name=='main':
bootstrap()
int: 20 = x;
print: x = None;
int: 40 = x;
print: x;
exit: 69;
print("Python version incompatible.")
evidence
doesn't work in 3.10+ because __annotations__ is a builtin at that point
sys.settrace is really useful
!e ```py
import builtins
builtins.dict.update({
'name':name,
'void':None,
'exit':import('_sitebuiltins').Quitter('69')
})
def bootstrap(builtins=builtins):
from ctypes import py_object as _p
from sys import _getframe as _g
g=_g(1).f_globals
obase = _p.from_address(id(g)+8)
@lambda o:g.update({'annotations':o,'obase':obase})
@type.call
class TypeHints:
cache = []
obase=builtins.import('ctypes').py_object.from_address(id(import('sys')._getframe(1).f_globals)+8)
builtins=builtins
dict=builtins.dict
approval = {()}
def setitem(self, type_name, value):
flogbals = self.obase.value
try:
self.obase.value = self.builtins.dict
ans=self.builtins.getattr(self.builtins,type_name)(self.builtins.globals().get(value,value)if value.hash else value)
try:
name = self.cache.pop()
if name in self.approval:
self.approval ^= {name}
self.builtins.globals()[name]=ans
finally:()=self.cache[:]=()
finally:self.obase.value = flogbals
class fglobals(dict):
slots = ()
def getitem(self, key, builtins=builtins, hints=g['annotations']):
if key=='annotations':return hints
try:return builtins.getattr(builtins, key)
except:
if key=='sys':return builtins.import('sys')
if not(c:=hints.cache)or not builtins.all(builtins.map(lambda x:builtins.type(x)is builtins.type,c)):
c[:]=[key]
return key
def setitem(self, key, value, dict=dict, obase=obase, builtins=builtins, hints=g['annotations']):
obase.value=dict
if builtins.type(value)==builtins.type:builtins.dict[key]=value
else:hints.approval |= {value}
try:self[key]=value
finally:obase.value=class
obase.value = fglobals
bootstrap()
int: 20 = x;
print: x = None;
int: 40 = x;
print: x;
exit: 69;
@quartz wave :x: Your eval job has completed with return code 69.
001 | 20
002 | 40
i gotta ask
how the fuck do you guys mannage to change the behavour of how idk "+" operator works
i saw some code where python would do 6+9 = 69
i dont even know whats that called so i cant look up how to do it
it hacks int.__add__
oh ok, you can dm the exsample code instead of dealing with the "but its a repost!1!1!" mentality
im just trying to get it to work
ohh
the thing is python evaluates 6+9 to 15 during compile time, so its a little tircky
!e ```py
from ctypes import c_int
six = c_int.from_address(id(6)+24)
six.value = 60
print(6 .add(9))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
I see
!e
from fishhook import hook
@hook(int)
def __add__(self, other: int):
print(self)
print(1 + 1)
@wheat river :x: Your eval job has completed with return code 1.
001 | 4
002 | Traceback (most recent call last):
003 | File "<string>", line 4, in <module>
004 | File "/snekbox/user_base/lib/python3.10/site-packages/fishhook/__init__.py", line 229, in pwrapper
005 | hook_cls_from_cls(cls, type(f'<{itos(id(cls))}>', (P,), body), **kwargs)
006 | File "/snekbox/user_base/lib/python3.10/site-packages/fishhook/__init__.py", line 186, in hook_cls_from_cls
007 | update_subcls(subcls, pcls)
008 | File "/snekbox/user_base/lib/python3.10/site-packages/fishhook/__init__.py", line 154, in update_subcls
009 | hook(cls, is_base=False)(body=attributes)
010 | File "/snekbox/user_base/lib/python3.10/site-packages/fishhook/__init__.py", line 229, in pwrapper
011 | hook_cls_from_cls(cls, type(f'<{itos(id(cls))}>', (P,), body), **kwargs)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/bobumehoge.txt?noredirect
why tf is it 4
compile time my foot
lol
this should be 2 cuz 1 + 1 = 2, idk y its 4
it's because there was an exception in line 4
- 0
wait no, it's because n % 10 + 48
you don't return anything from a commonly used int.__add__
there are many unintended consquences to playing around with ints
o.o
i wonder if you can overide int locally
i imagine python wouldnt support that
eg, int is only overidden in a specific function
just use a hack decorator
!e ```py
from ctypes import*
f = lambda a:10a
F = py_object.from_address(id(f)+8)
class Function(type(f)):
def mul(self, other):
return class(lambdaa,**k:self(other(*a,*k)).code,globals())
F.value = Function
print((f(lambda x:x+9))(6))
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | TypeError: type 'function' is not an acceptable base type
not an acceptable base type that is the lamest excuse not to work I've heard this week, and that's saying something
It even beats "I have a headache I can't come to work"
lmao
Why +24?
!e import os os.system('cmd \c "pip install cython"')
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
because it's int.__basicsize__
points to the internal array of 32-bit integers that the python int has
trying to do cmd on a linux machine
ive never had linux never will so idk the linux os stuff
rm -f
TIL __class__ is implicitly there?
!e ```py
from types import CellType as cell, FunctionType as function
from ctypes import*
c_ulong.from_address(id(type(lambda:0))+object.basicsize+19tuple.itemsize).value |= 1024
f = lambda a:10a
F = py_object.from_address(id(f)+8)
class Function(function):
def mul(self, other):
return class((lambda*a,**k:self(other(*a,**k))).code,globals(),closure=(map(cell,[self,other]),))
F.value = Function
print((f(lambda x:x+9))(6))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
69
Yea that's because it's how super() works
only a few people know
Wow very funny
I looked it up and made ur message so funny. Kind of an esoteric joke tho
Only a few people know why it's funny
after a few moments of reading and re-reading i finally got the joke
bruhh
I'm confused
Is import* different from import *?
No, it's the same. There's lots of places where spaces aren't strictly necessary.
!e
from sys import getsizeof
print(getsizeof([*map(lambda x: globals().__setitem__(f'var{x}', x),range(1_000_000))]))
@wheat river :warning: Your eval job timed out or ran out of memory.
[No output]
Work code? Or no work?
yes work code
function = lambda number1, number2: dictionary.update({number1: number2}) or (number1 + number2)
Does dictionary.update return None?
Yep
yes
what does it mean esoteric?
@mellow salmon :white_check_mark: Your eval job has completed with return code 0.
354224848179261915075
@mellow salmon :white_check_mark: Your eval job has completed with return code 0.
280571172992510140037611932413038677189525
'java edition' xD
Esoteric? Few people understand it.
!e
@fleet bridge :warning: Your eval job has completed with return code 0.
[No output]
Intended for or likely to be understood by only a small number of people with a specialized knowledge or interest. https://www.newworldencyclopedia.org/entry/Esotericism
Like here for instance, we appear to have a specialized knowledge of the lambda statements and the many ways it can be shoehorned into doing our bidding.
Can they explain ? xD
anything except the walrus operator (assignment expression)
!e ```py
print(8448728)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
8448728
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
8448728
.__ior__(...) updates an also returns itself instead of None.
That is technically a statement though, right?
But it also has a straight expression equivalent
no it's an expression
(x:=4) is expression.
x = 4 is a relation between two expressions.
what
or anything that belongs to the star_named_expression grammar rule
x=4 cannot be surrounded by brackets without changing it's functionality therefore it is a syntax sugared assignment statement
well the thing is x=4 doesn't return anything but x:=4 does
so is it really syntax sugar
Would you rather write it as 8090 SET #X INT 4?
Everything is sugared
And a assignment is a statement
what language is that
It's not
!e Well actually it would better make my point of removing syntax sugar if I actually removed it.
f = lambda:(x:=4)
def g():x=4
print(f.__code__.co_code, g.__code__.co_code)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
b'd\x01\x04\x00}\x00S\x00' b'd\x01}\x00d\x00S\x00'
I think 100 is some sort of load constant and 4 is duptop the rest should be self explanatory
๐ค
In [15]: (lambda: (x:=1))()
Out[15]: 1
i meant bare
do i have to clarify every single thing i say about the walrus operator
Python or java?
it's python
pyjava
@rustic glen : how about an israeli python project, with the name pyjora ? heheheh
No- that's what it means. "few people understand something"
it isn't common knowledge
https://www.thefreedictionary.com/esoteric
@languid hare :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | x := 1
003 | ^^
004 | SyntaxError: invalid syntax
!e
(x := 1)
@royal whale :warning: Your eval job has completed with return code 0.
[No output]
Expressions can be statements, so that works
The parser for python probably has something like this:
| LPAREN expr RPAREN
| LPAREN walrus_assignment RPAREN
Idk but it's a guess
oohhh xD haha okay I get it now Thanks a lot !
no it's sort of different by how it's done
here's the starting rule py expression[expr_ty] (memo): | invalid_expression | invalid_legacy_expression | a=disjunction 'if' b=disjunction 'else' c=expression { _PyAST_IfExp(b, a, c, EXTRA) } | disjunction | lambdef so it goes down disjunction to atom py atom[expr_ty]: | NAME | 'True' { _PyAST_Constant(Py_True, NULL, EXTRA) } | 'False' { _PyAST_Constant(Py_False, NULL, EXTRA) } | 'None' { _PyAST_Constant(Py_None, NULL, EXTRA) } | &STRING strings | NUMBER | &'(' (tuple | group | genexp) | &'[' (list | listcomp) | &'{' (dict | set | dictcomp | setcomp) | '...' { _PyAST_Constant(Py_Ellipsis, NULL, EXTRA) } then the rule group is taken ```py
group[expr_ty]:
| '(' a=(yield_expr | named_expression) ')' { a }
| invalid_group
yield_expr is yield *stuff, expr, *more_stuff and yield from expr
named_expression is name := expr or expr
!e
code
!eval <code>
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
hello! I have this code
from datetime import date
today = date.today()
print(today) # i get 2022-06-23
but i want to print 2022-07-23 or 2022-06-30. So the date one month from today or one week from today. Please ping me
wrong channel
#โ๏ฝhow-to-get-help
This is not on topic. However, I'd suggest looking at the strftime method for date objects.
Made a new Programming language here's a hello world program in it ๐ ๐ ๐ฏ ๐ฏ
๐
!e
print(print(print()));print();[0]
@lyric fern :white_check_mark: Your eval job has completed with return code 0.
001 |
002 | None
003 | None
@cursive basalt Your new language was not appropriate for this server, as I am sure you can agree.
I missed a vulgar esolang? >_>
Think of the most mature thing ever, you didn't miss out
It was mostly just "penis" repeated several times
u didnt have to say it ๐ณ
oh, so the least mature kind of vulgar.
and nothing original, since chicken already is a one word esolang
Yessir
๐
just doing some simple one liners, thoughts? py ((__raise := (lambda __argument_exception: (__temporary_loop_value for __temporary_loop_value in ()).throw(__argument_exception))), (__try := type('TryExceptManager', (__import__('contextlib').ContextDecorator,), {'__init__': lambda self, __argument_except_function, __argument_else_function, __argument_target_error: (None, setattr(self, '__attribute_except_function', __argument_except_function), setattr(self, '__attribute_else_function', __argument_else_function), setattr(self, '__attribute_target_error', __argument_target_error))[0], '__enter__': lambda self: None, '__exit__': lambda self, __argument_one, __argument_error, __argument_two: (True, self.__attribute_except_function())[0] if isinstance(__argument_error, self.__attribute_target_error) else (False, self.__attribute_else_function())[0]})), ((__temporary_unpacking_orginal := (fullname := input('your name: ').split())), (__temporary_unpacking_iter := iter(__temporary_unpacking_orginal)), (firstname := __try(lambda : __raise(ValueError('not enough values to unpack (expected 2, got 0)')), lambda : None, StopIteration)(lambda : next(__temporary_unpacking_iter))()), (lastname := __try(lambda : __raise(ValueError('not enough values to unpack (expected 2, got 1)')), lambda : None, StopIteration)(lambda : next(__temporary_unpacking_iter))()), __try(lambda : None, lambda : __raise(ValueError('ValueError: too many values to unpack (expected 2)')), StopIteration)(lambda : next(__temporary_unpacking_iter))())[0],print(f'hello {fullname}, is it okay if I just call you {firstname}?')) and dont worry I didnt write this by hand, I made a 300 lines script to generate it from this ```py
firstname, lastname = fullname = input("your name: ").split()
print(f"hello {fullname}, is it okay if I just call you {firstname}?")
!e
((__raise := (lambda __argument_exception: (__temporary_loop_value for __temporary_loop_value in ()).throw(__argument_exception))), (__try := type('TryExceptManager', (__import__('contextlib').ContextDecorator,), {'__init__': lambda self, __argument_except_function, __argument_else_function, __argument_target_error: (None, setattr(self, '__attribute_except_function', __argument_except_function), setattr(self, '__attribute_else_function', __argument_else_function), setattr(self, '__attribute_target_error', __argument_target_error))[0], '__enter__': lambda self: None, '__exit__': lambda self, __argument_one, __argument_error, __argument_two: (True, self.__attribute_except_function())[0] if isinstance(__argument_error, self.__attribute_target_error) else (False, self.__attribute_else_function())[0]})), ((__temporary_unpacking_orginal := (fullname := input('your name: ').split())), (__temporary_unpacking_iter := iter(__temporary_unpacking_orginal)), (firstname := __try(lambda : __raise(ValueError('not enough values to unpack (expected 2, got 0)')), lambda : None, StopIteration)(lambda : next(__temporary_unpacking_iter))()), (lastname := __try(lambda : __raise(ValueError('not enough values to unpack (expected 2, got 1)')), lambda : None, StopIteration)(lambda : next(__temporary_unpacking_iter))()), __try(lambda : None, lambda : __raise(ValueError('ValueError: too many values to unpack (expected 2)')), StopIteration)(lambda : next(__temporary_unpacking_iter))())[0],print(f'hello {fullname}, is it okay if I just call you {firstname}?'))
@fleet bridge :x: Your eval job has completed with return code 1.
001 | your name: Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
(reason it is so long is because I need to manually implement the internal checks of the a, b = x syntax)
well it expects 2 words ...
oh right ofc, why didnt I see that when testing xD
firstname, lastname = fullname = input("your name: ").split()
print(f"hello {fullname}, is it okay if I just call you {firstname}?")
# ->
firstname, lastname = (fullname := input("your name: ")).split()
print(f"hello {fullname}, is it okay if I just call you {firstname}?")
((__raise := (lambda __argument_exception: (__temporary_loop_value for __temporary_loop_value in ()).throw(__argument_exception))), (__try := type('TryExceptManager', (__import__('contextlib').ContextDecorator,), {'__init__': lambda self, __argument_except_function, __argument_else_function, __argument_target_error: (None, setattr(self, '__attribute_except_function', __argument_except_function), setattr(self, '__attribute_else_function', __argument_else_function), setattr(self, '__attribute_target_error', __argument_target_error))[0], '__enter__': lambda self: None, '__exit__': lambda self, __argument_one, __argument_error, __argument_two: (True, self.__attribute_except_function())[0] if isinstance(__argument_error, self.__attribute_target_error) else (False, self.__attribute_else_function())[0]})), (fullname := input('your name: ')), ((__temporary_unpacking_orginal := fullname.split()), (__temporary_unpacking_iter := iter(__temporary_unpacking_orginal)), (firstname := __try(lambda : __raise(ValueError('not enough values to unpack (expected 2, got 0)')), lambda : None, StopIteration)(lambda : next(__temporary_unpacking_iter))()), (lastname := __try(lambda : __raise(ValueError('not enough values to unpack (expected 2, got 1)')), lambda : None, StopIteration)(lambda : next(__temporary_unpacking_iter))()), __try(lambda : None, lambda : __raise(ValueError('too many values to unpack (expected 2)')), StopIteration)(lambda : next(__temporary_unpacking_iter))())[0],
print(f'hello {fullname}, is it okay if I just call you {firstname}?'))```
nice
and as you noticed before you still have the "to many" / "not enough" values errors, which you might see are just hardcoded ๐
currently going to try adding support for the a, *b = x syntax
damn nice
implemented ```py
a=[1,2,3];[a.pop()while a]
[3, 2, 1]
you can use a while loop in a comprehension???
no that's custom syntax
how did you implement that?
modified cpython
Ah
yea
Awesome. It works with all kinds of comprehensions?
yeah
just went on a 23-hour coding bender and here are some esoteric highlights from my sleep-deprived brain:
handle_hooks=lambda event,group,*arguments:[hook(*arguments)for hook in ModuleUtils.groups[group.name]['hooks'][event]]if event in ModuleUtils.groups[group.name]['hooks'] else[]
if self.data.delta_stack[-self.data.lookback:]==[[0]*len(self.servergroup.servers)]*self.data.lookback:#if the waterfall is over
is there some way to implement dict.get in the first one?
like ```py
handle_hooks=lambda event,group,*arguments:[hook(*arguments)for hook in ModuleUtils.groups[group.name]['hooks'].get(event,[])]
I'm starting to get the compulsive need to golf this.
handle_hooks=lambda e,g,*a:[h(*a)for h in ModuleUtils.groups[g.name]['hooks'].get(e,[])]
!e I want this pep, so I don't have to
a=[1,2,3];print([a.pop()for _ in iter(lambda:a,[])])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[3, 2, 1]
well i don't know how to debate in the python-ideas mailing list and how to write a PEP
iter works for now, I guess
if people don't find out [1 while 1] doesn't work, then they don't learn
so i'm also doing ```py
for item in stuff if condition:
...
Then don't free it, just hide it in a deep dark dungeon to be forgotten until the code reaches the end and everything is deleted
great idea
that's not gonna leak memory is it
obviously it might do so in some extreme cases.
when i do that there's an access violation for some reason
well right after the code "works" that is
i have ```py
for x in range(-100,100) if x > 0: print(x)
is there some way then to "rescue" it from the dungeon then unravel it upon code completion?
it prints -100 for some reason then crashes
right so there's an iteration thing. Are you using a "middleman" iterator?
(i'm still having problems with walrus expressions in here btw)
what
oh wait
bruh
after inspecting using dis i found out i just evaluated the comparisons and left them alone without even POP_TOPing them
look around, make sure no one sees you, then discreetly insert a POP_TOP into the code...
ok i solved it
i didn't do what you said btw
now does it work?
yes
how many innocent memory addresses did you have to lock away in the dungeons?
none
now i'm getting an access violation with async for
obviously it iterates through increasing numbers, pops a 1 from a if i is even and prints i while a is not empty
what about
a = [1, 0]*8
while a if a.pop():
print("this will print eight times")
```?
i haven't done it for while loops yet
j = 1
a = [60]*8
if j for i in a: print (i+9)
how much effort would that take to implement?
is that just for in a if j
for i in a if j would still iterate a
j could be a flag to determin if a is safe to .__iter__()
ok this made me think of multi-statement headers
could you make unbracketed tuple comprehension, like ```py
a, *void = i+9 for i in [60],
print(a, void) # 69 ()
or "naked generator expression" ```py
a = i+9 for i in [69]
print(*a)
so i already did a tuple comprehension before but not an unbracketed one
how do i hello world without print or write
!e ```py
import hello
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
Hello world!
@heavy ermine :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/azivixunor.txt?noredirect
!e import antigravity
@heavy ermine :warning: Your eval job has completed with return code 0.
[No output]
what is the most inefficient way to print hello world
this
it's about 20 seconds of scrolling up
oh bruh
nah i'd say it's this: #esoteric-python message
code
!eval <code>
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
!e [0x1for x in (1,2,3)]
@tall meteor :warning: Your eval job has completed with return code 0.
[No output]
!e [0x1for x in (1,2,3)]
@tall meteor :warning: Your eval job has completed with return code 0.
[No output]
hrm.
see, my python 3.10 accepts that
apparently this is being slated to be removed in 3.12
"Pending Removal in Future Versions"
"Currently Python accepts numeric literals immediately followed by keywords, for example 0in x, 1or x, 0if 1else 2. It allows confusing and ambiguous expressions like [0x1for x in y] (which can be interpreted as [0x1 for x in y] or [0x1f or x in y]). A syntax warning is raised if the numeric literal is immediately followed by one of keywords and, else, for, if, in, is and or. In a future release it will be changed to a syntax error. (gh-87999)"
noooooo, that's a classic python line
tell me more
!e
print([0xfor x in "15"])
!e ```py
print(*[0x00for x in y])
@languid hare :white_check_mark: Your eval job has completed with return code 0.
[15]
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
15
locally on my 3.10, I get this:
[0x1for x in (1,2,3)]
[31][x for x in (1,2,3)]
[1, 2, 3]
makes me sad
its a classic
print(chr(0x48)+complex.real.__name__[1]+range.__len__.__name__[2]+int.__floor__.__name__[(2+1)]+bool.as_integer_ratio.__name__[(((2+1)*2+1)*2+1)]+chr(0x2c)+chr(0x20)+frozenset.__new__.__name__[(2+2)].upper()+set.__or__.__name__[2]+complex.__getnewargs__.__name__[((2+2)*2+1)]+bytearray.__delattr__.__name__[(2+2)]+memoryview.__delitem__.__name__[2]+chr(((((2+2)*2)*2)*2+1)))
ydGm```
Code converts to print("Hello, World!")
you did all that but still chr(0x48)? :p
Was generated by a program I wrote lol
hmm
if you wanna see some real code gore
Hey @past stratus!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
"Document exceeds maxiumum length" lol
yea maybe its better we can't see it ๐
!e import this
@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/oceraterur.txt?noredirect
checks dms
!e import os;os.system("python3 -m pip install discord.py")
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
le
Bot testing in #bot-commands pls
!e
from fishhook import hook
@hook(type(lambda:...))
def __rrshift__(self, value):
return self(value)
@hook(type(lambda:...))
def __lshift__(self, value):
return self(value)
f = lambda x: x + 1
print(42 >> f)
print(f << 42)
@vestal vector :white_check_mark: Your eval job has completed with return code 0.
001 | 43
002 | 43
What is __rrshift__
I've never seen that
Wait
!e
print(hasattr(int, "__rshift__"))
@cloud fossil :white_check_mark: Your eval job has completed with return code 0.
True
Oh so __rrshift__ is for when the type is also on the right side
So there is __rlshift__ too?
Cool
Ah makes sense
Shift dunders are already have r/l to differentiate
Wait but can you define r dunders for every dunder?
It seems the answer is no
k
!e
print([0for i in ('.')*10])
@royal coral :white_check_mark: Your eval job has completed with return code 0.
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
!e
print([*[0]*10])
@royal coral :white_check_mark: Your eval job has completed with return code 0.
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
!e print([0]*10)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
don't need to unpack a list into a list
LOL, TRUTH! HAHAHAHAHAHAHA
Pipe operator?
!e
from typing import *
class math:
def algebra_formatting_equal_mul(self, co_ef: int, co_var: str, s: str | Any, t_c_v: int, arg_t_va: str, visuals: Optional[bool]=False) -> int | str | list[int]:
group: Any= f"{co_ef}{co_var}{s}{t_c_v}{arg_t_va}"
try:
if s == 'x':
if co_var != arg_t_va:return f"{co_ef * t_c_v}{co_var}{arg_t_va}"
elif co_var == arg_t_va:new: list[list] | Any = [len(co_var), len(arg_t_va)];return f"{co_ef * t_c_v }{co_var[0]}^{len(co_var)+len(arg_t_va)}"
elif visuals:return group
else:None
else:print("Not a multiplication operation.")
except Exception as e:
return str(e)
def maxPower(self, s: str) -> int:
from collections import Counter;from typing import Any;res:Any|Counter=Counter(s);new_vmax=str | int | bool;res: new_vmax=max(res,key=res.get);return f"occ-max={res}"
def remove_dups(a: list[Any|int|float]) -> list[int]:return list(set(a))
def twoSum(self,nums: list[int|Any], target: int) -> list[int|Any]:
new_sum:list[Any]=[]
for i in nums:
for j in nums:
if i+j==target:new_sum.append(i);new_sum.append(j);return new_sum
else:None
Math = math()
print(Math.algebra_formatting_equal_mul(2, 'x', 'x', 5, 'x'))
print(Math.maxPower('dfsodifjoisuoidfjdoisoiuiiiiiiiiiiii'))
print(math.remove_dups([3, 2, 2, 2, 2, 1]))
print(Math.twoSum([1, 2, 3], 5))
@lyric fern :white_check_mark: Your eval job has completed with return code 0.
001 | 10x^2
002 | occ-max=i
003 | [1, 2, 3]
004 | [2, 3]
whaaaaaaaaaaaaaaaaaaaaaaat?
@floral meteor @languid hare in my python 3.12.0a0 it doesn't error
neither does it seem for the main branch
if (r) {
tok_backup(tok, c);
if (parser_warn(tok, PyExc_SyntaxWarning,
"invalid %s literal", kind))
{
return 0;
}
tok_nextc(tok);
}
else /* In future releases, only error will remain. */
if (is_potential_identifier_char(c)) {
tok_backup(tok, c);
syntaxerror(tok, "invalid %s literal", kind);
return 0;
}
!e ```py
from fishhook import hook
@hook(type(lambda:...))
def rrshift(self, value):
return self(value)
@hook(type(lambda:...))
def lshift(self, value):
return self(value)
@hook(type(lambda:...))
def mul(self, other):
return lambda*a,**k:self(other(*a,**k))
@hook(type(lambda:...))
def rmul(self, other):
return lambda*a,**k:other(self(*a,**k))
f = lambda x:x+1
print * f << 68
@floral meteor :x: Your eval job has completed with return code 1.
001 | 68
002 | Traceback (most recent call last):
003 | File "<string>", line 20, in <module>
004 | File "<string>", line 9, in __lshift__
005 | File "<string>", line 17, in <lambda>
006 | File "<string>", line 19, in <lambda>
007 | TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
print is a builtin_function_or_method
which is a different thing
we tried this a while back
to type(lambda:...) which is function
you need to hook lambdas types, builtin function types and one other thing
is it somehow evaluating the lshift before the multiplication?
nvm i got it
im dumb
!e ```py
from fishhook import hook
@hook(type(lambda:...))
def rrshift(self, value):
return self(value)
@hook(type(lambda:...))
def lshift(self, value):
return self(value)
@hook(type(lambda:...))
def mul(self, other):
return lambda*a,**k:self(other(*a,**k))
@hook(type(lambda:...))
def rmul(self, other):
return lambda*a,**k:other(self(*a,**k))
f = lambda x:x+1
print * f << 68
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
much better syntaxes then print(f(68)) right?
Plus, you can assign print * f to a name
!e plus you can chain functions without insanity ```py
from fishhook import hook
@hook(type(lambda:...))
def rrshift(self, value):
return self(value)
@hook(type(lambda:...))
def lshift(self, value):
return self(value)
@hook(type(lambda:...))
def mul(self, other):
return lambda*a,**k:self(other(*a,**k))
@hook(type(lambda:...))
def rmul(self, other):
return lambda*a,**k:other(self(*a,**k))
f = lambda x:x+1
67 >> print * f * f
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
!e ```py
def hack(f_n, redirect={}):
from sys import _getframe
frame = _getframe(f_n+1)
def h_inner(f):
redirect.update({f.name:f})
if f.name in frame.f_globals|frame.f_locals:
return frame.f_locals.get(f.name,
frame.f_globals.get(f.name,
frame.f_builtins.get(f.name,None)))
else:
s = frame.f_code.co_code.decode()
CALL_FUNCTION, NOP = '\x83\t'
for i,c in enumerate(s):
if not i%2 and i>=frame.f_lasti and c!=CALL_FUNCTION:
s = s[:i]+NOP+'\0'+s[i+2:]
frame.f_code=frame.f_code.replace(co_code=s.encode()) #!
return None
else: raise NameError(f.name + "could not be cleaned up")
return h_inner
d = {}
@hack(0, d)
def d():
import hello
d'd'
print("test complete")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | Hello world!
002 | test complete
still working on this one though, it does have some decoding issues when preventing the existence of variables
I think this is it
def hack(f_n, redirect={}):
from sys import _getframe
frame = _getframe(f_n+1)
def h_inner(f):
redirect.update({f.__name__:f})
if f.__name__ in frame.f_globals|frame.f_locals:
return frame.f_locals.get(f.__name__,
frame.f_globals.get(f.__name__,
frame.f_builtins.get(f.__name__,None)))
else:
s = frame.f_code.co_code.decode('ANSI')
CALL_FUNCTION, NOP = '\x83\t'
for i,c in enumerate(s):
if not i%2 and i>=frame.f_lasti and c!=CALL_FUNCTION:
s = s[:i]+NOP+'\0'+s[i+2:]
co_code = s.encode('ANSI')
from ctypes import c_char
for _,c in zip((c_char*len(co_code)).from_address(id(frame.f_code.co_code)+32),co_code):
_.value = bytes(c)
return None
else: raise NameError(f.__name__ + "could not be cleaned up")
return h_inner
#test
d = {}
@hack(0, d)
def d():
import __hello__
@hack(0)
def print(*a):
try:print(*a)
except:print(*a)
d['d']()
assert'print'not in globals()
print("test complete")
What version of python? because mine c_char*int iterates bytes of length 1, not c_char
how many extensions did you implement in your local branch ?
idk i don't keep track
Stuff about python that isn't common knowledge
oh
It's also doing problems in Python in a way you wouldn't really do. Like trying to write a ray tracer in one line. Or animating an ascii donut, but without loops and it fits on a business card
What witchcraft is this!?
ctypes, it's always ctypes ๐
isn't ctypes a library in C?
!d ctypes
it's ctype.h in C and cctype on C++
and it's called a header
Esoteric programming is like doing experimental poetry instead of writing a manual.
#internals-and-peps learn about python internals
#esoteric-python exploit python internals 
more like abuse python internals
More like waterboarding python with its own internals.
actually ouch that sounds brutal
luckily everyone here has already traumatised themselves with their own code.
This channel is called esoteric-python instead of just esoteric, because you need to be constantly reminded that the code here is still python code.
kekw
i sent my hello world code to my friend once and the first thing he said was "brainfuck?"
woah
i have an ascii donut
!e
(c:=int),(b:=range),(P:=print),((C:=__import__('math')),),(A:=lambda A,B:((E:=C.cos(A)),(F:=C.sin(A)),(J:=C.cos(B)),(K:=C.sin(B)),(Q:=[]),(R:=[]),all((((Q.append([' ']*(D+0)),R.append([0]*(D+0))),)for d in b(O+1))),(G:=0),next((_ for _ in iter(int,1)if((False,(G:=G+f),(L:=C.cos(G)),(S:=C.sin(G)),(H:=0),next((_ for _ in iter(int,1)if((False,(H:=H+g),(T:=C.cos(H)),(I:=C.sin(H)),(U:=Y+N*L),(V:=N*S),(h:=U*(J*T+F*K*I)-V*E*K),(i:=U*(K*T-F*J*I)+V*E*J),(j:=Z+E*U*I+V*F),(M:=1/j),(W:=c(D/2+a*M*h)),(X:=c(O/2-a*M*i)),(e:=T*L*K-E*L*I-F*S+J*(E*S-L*F*I)),((R[W].__setitem__(X,M),(k:=e*8),Q[W].__setitem__(X,'.,-~:;=!*#$@'[c(k)]))if M>R[W][X]else None)if e>0 else None)[0]if H<2*C.pi else True))))[0]if G<2*C.pi else True))),P('\x1b[H'),all((((all(((P(Q[d][l],end=''),)for l in b(D))),P()),)for d in b(O))),None)[-1]),(f:=0.07),(g:=0.02),(N:=1),(Y:=2),(Z:=5),(D:=40),(O:=40),(a:=D*Z*3/(8*(N+Y))),P('\x1b[2J'),A(1,0)
@languid hare :white_check_mark: Your eval job has completed with return code 0.
001 | [2J
002 | [H
003 |
004 |
005 |
006 | ==;;:::~-
007 | !!==;;::~~~--
008 | *!!!=;;::~~~~---,
009 | **!!==;::~~~~-----,
010 | #*!!=;;::~~--------,.
011 | #**!!=;;:~~---,------,.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/epaseverey.txt?noredirect
tragic
!e
(c:=int),(b:=range),(P:=print),((C:=__import__('math')),),(A:=lambda A,B:((E:=C.cos(A)),(F:=C.sin(A)),(J:=C.cos(B)),(K:=C.sin(B)),(Q:=[]),(R:=[]),all((((Q.append([' ']*(D+0)),R.append([0]*(D+0))),)for d in b(O+1))),(G:=0),next((_ for _ in iter(int,1)if((False,(G:=G+f),(L:=C.cos(G)),(S:=C.sin(G)),(H:=0),next((_ for _ in iter(int,1)if((False,(H:=H+g),(T:=C.cos(H)),(I:=C.sin(H)),(U:=Y+N*L),(V:=N*S),(h:=U*(J*T+F*K*I)-V*E*K),(i:=U*(K*T-F*J*I)+V*E*J),(j:=Z+E*U*I+V*F),(M:=1/j),(W:=c(D/2+a*M*h)),(X:=c(O/2-a*M*i)),(e:=T*L*K-E*L*I-F*S+J*(E*S-L*F*I)),((R[W].__setitem__(X,M),(k:=e*8),Q[W].__setitem__(X,'.,-~:;=!*#$@'[c(k)]))if M>R[W][X]else None)if e>0 else None)[0]if H<2*C.pi else True))))[0]if G<2*C.pi else True))),P('\x1b[H'),all((((all(((P(Q[d][l],end=''),)for l in b(D))),P()),)for d in b(O))),None)[-1]),(f:=0.07),(g:=0.02),(N:=1),(Y:=2),(Z:=5),(D:=10),(O:=10),(a:=D*Z*3/(8*(N+Y))),P('\x1b[2J'),A(1,0)
@languid hare :white_check_mark: Your eval job has completed with return code 0.
001 | [2J
002 | [H
003 | =:-
004 | *!;~--
005 | $!=~----
006 | #!;-..~~
007 | #!;. !!=
008 | #!;, !!=
009 | #*;-..~~
010 | $!=~----
011 | *!;~--
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ikosojikal.txt?noredirect
tiny donut
damn
iirc someone first did that in c++ right?
and the code was in the shape of a donut too
yup
it was c but basically the same thing lmao
!e print([1]*10)
@cloud crest :white_check_mark: Your eval job has completed with return code 0.
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
!e print([2]*10)
@cloud crest :white_check_mark: Your eval job has completed with return code 0.
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
!e print([0]*10+2)
@cloud crest :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: can only concatenate list (not "int") to list
!e print([0]*10) + 2
@cloud crest :x: Your eval job has completed with return code 1.
001 | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
!e print([x=2*x]*10)
@cloud crest :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print([x=2*x]*10)
003 | ^^^^^
004 | SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
!e ```python
x = 264
print([x2]*10)
@cloud crest :white_check_mark: Your eval job has completed with return code 0.
[256, 256, 256, 256, 256, 256, 256, 256, 256, 256]
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
ok guys
first 32 of the fib seq in only 36 characters or less
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
this should be the output
a=0;b=1;exec('a,b=b,a+b;print(b);'*32)
this might be a way to start but I can't figure out how to create the first 2
and it's 38, already
interesting
right now we got this
def f(i,j):print(i);f(j,i+j)
f(1,1)
@golden finch
but its not limited to 32
neat
in case anyone missed in pygen, I did 40:
a,b=0,1
while a<2**20:print(a);a,b=a+b,a
you can't one-liner a while loop
it's not a simple statement
I swear I tested it, anyway, it doesn't change the char count so we're back to 2 lines 40
a,b=0,1
while a<2**20:print(a);a,b=a+b,a
That works, and is only 38
a=0;b=1
exec('print(a);a,b=a+b,a;'*31)
Yeah you can
!e```py
x = 10
while x > 0: print(x); x -= 1
@royal whale :white_check_mark: Your eval job has completed with return code 0.
001 | 10
002 | 9
003 | 8
004 | 7
005 | 6
006 | 5
007 | 4
008 | 3
009 | 2
010 | 1
no they mean you can't have it after the ;
(and they're correct)
a=0;b=1;while a<2**20:print(a);a,b=a+b,a
36 characters or less
this is the current thing
yes, you're correct, the record is 36, so we're getting closer.
that doers not limit to 31.
Print the first 31 Fibonacci numbers from F0 = 0 to F30 = 832040 (inclusive), each on a separate line.
!e
a=0;b=1;exec(โprint(a);a,b=a+b,a;โ*31)
@bold root :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | a=0;b=1;exec(โprint(a);a,b=a+b,a;โ*31)
003 | ^
004 | SyntaxError: invalid character 'โ' (U+2018)
used msword quotes
ok
!e
a=0;b=1;exec(โprint(a);a,b=a+b,a;โ*31)
@bold root :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | a=0;b=1;exec(โprint(a);a,b=a+b,a;โ*31)
003 | ^
004 | SyntaxError: invalid character 'โ' (U+201C)
this feels like it comes from code.golf
Im clnfused
It is
hmm
what if we use the golden ratio
!e
a=0;b=1;exec('print(a);a,b=a+b,a;'*32)
@bold root :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 1
004 | 2
005 | 3
006 | 5
007 | 8
008 | 13
009 | 21
010 | 34
011 | 55
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/kovawofefi.txt?noredirect
Pog
yeah I tried that earlier, could not make anything short enough.
probably a way to shorten this:
for i in range(31):print(round((.5+5**.5/2)**i/5**.5))
but that passes their test case
hint ||a=b=...||
it needs the 0
ok
yeah idk
well, I'm clearly daft - I don't know how I didn't see that
can someone help me to solve this problem ?
I'd thought of that, but everything I can try around a=b=(some value) seems to fail so far.
it seems like there must be some esoteric magic here. The exec was a nice touch.
Is your solution still valid on their site? (ie: have they changed he version of their python and it's no longer possible)
pretty brilliant to begin with, I hadn't thought about exec. I was all excited about while a<2**20: ๐
!e ```py
hs=lambda n,fe,fo:[(n:=[fe,fo]n%2)for _ in iter(lambda:n<2,1)]
print(hs(69,lambda x:x//2-1,lambda x:x2))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
138 68 33 66 32 15 30 14 6 2 0
Ugh I'm not doing this right
sharing this reverse fib solution that works, even though it's 57 long.
f=lambda a=514229,b=832040:b>0and f(b-a,a)or print(b);f()
maybe there's an idea there.
!e ```py
hs=lambda n:(a:=[n],{a.append((n:=[n//2,n*3+1][n%2]))for _ in iter(lambda:a.count(n),2)}and[0,0])[not n][:-1]
print(*hs(69))
print(*hs(71))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 69 208 104 52 26 13 40 20 10 5 16 8 4 2 1
002 | 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
What are you trying to do?
hailstone sequence!
71 generates a large sequence
!e graffs ```py
hs=lambda n:(a:=[n],{a.append((n:=[n//2,n3+1][n%2]))for _ in iter(lambda:a.count(n),2)}and[0,0])[not n][:-1]
T = lambda s:'\n'.join(''.join(_)for _ in zip((lambda a:[f"{_: >{max(map(len,a))}s}"for _ in a])(s.split('\n'))))
S = T('\n'.join(['*'*n for n in map(len,map(hs,range(69)))]))
print(S)
@floral meteor :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/ebekuwomag.txt?noredirect
Here you can see a graph of y = hailstone_sequence(x)
The area under the curve is the number of asterisks in the graph.
import math,random;y=lambda n,l:[[n]if n<=l else[l if(n-(l*math.floor(n/l)))==0 else (n-(l*math.floor(n/l)))for x in[1]]for x in[1]][0][0];z=lambda p,a:[chr(random.Random(ord(c)*678).randint(457,875))for c in list((p*a)[:a])]
def e(d,c):a=[];b=z(c,7);[a.append(chr(ord(list(d)[_])+ord(c[y(_+1,len(c))-1])+ord(c[::-1][0])))for _ in range(len(d))];a=list(''.join('%s%s'%(x,random.choice(b)if random.random()>0.5 else'')for x in''.join(a)));e=[];f=[];g=list('ghijklmno');h=list('pqrstuv');[e.append(str(hex(ord(j))).split('0x')[1])for j in a];[f.append(i+random.choice(g))for i in e];f=''.join(f)[:-1];return f.upper()[::-1]+random.choice(h).upper()+str(random.randint(137,975))
def d(a,b):c=a.split(a[-4:][:1])[0];c=c.lower()[::-1];d=[];e=[];f=z(b, 7);g=[];h=[];c=c.replace('g','#');c=c.replace('h','#');c=c.replace('i','#');c=c.replace('j','#');c=c.replace('k','#');c=c.replace('l','#');c=c.replace('m','#');c=c.replace('n','#');c=c.replace('o','#');d=c.split('#');[e.append(chr(eval('0x'+i)))for i in d];[g.append(j)if j not in f else j for j in e];[h.append(chr(ord(list(g)[_])-ord(b[y(_+1, len(b))-1])-ord(b[::-1][0])))for _ in range(len(g))];return ''.join(h)
encrypted = e('https://github.com/3xq', 'komt#0005')
decrypted = d(encrypted, 'komt#0005')
print(encrypted)
print(decrypted)```
Just Another Python Hacker :^)
3 lines, excluding the 6 at the bottom
Oh by the way, every time you encrypt it, it outputs something different every time but decrypts to the same thing. :P
Output from running it 5 times:
303NA11KFE1IA11N7DJFCO4D1G7DJ4DM463G8CL39MABJ463GE11O4D1IA01I811NFE1M901I463K1DO4D1O49J49HF9MBCL911O4D1H611O4D1N811JB02K801R743
8D2JA11O303NA11N7DK4D1JFCI7DG4DO8D2N8CH39N4D1HABLE11NB02MA01N4D1N811G901NB02M1DI49H8D2H49I463LF9I303IBCKFE1L911M611H303K811L801S451
A11JA11LFE1O7DI303GFCM8D2K7DJ4DJ8CN463M39IABK303JE11IA01O811N901M1DI49O49OF9JBCN911M463K611J811J801R523
A11MA11H4D1L7DGFCL4D1H7DM4DN8CJ39OFE1NABLFE1KE11GA01GB02M811H901H1DN8D2M49LFE1K49L463KF9LBCJ8D2G911G463H611O8D2K811O801T761
A11LA11I7DJFCN8D2H7DNB02N4DL8CI303O39NABH303GE11O8D2MA01L303O811J463K901J1DM49N49GF9MBCI303G911I8D2J611K811OB02G801V720```
last time i encrypted, there was a brainfuck interpreter built into the decryption process, but it interpreted digits in a massive integer built by indexing digits from a ridiculously supermassive integer built from two keys.
If you were good with brainfuck, you could make a message interactive, due to being turing complete.
it sounds great but really it was one big hilarious mess
very big mess
we could golf it
fun challenge to golf it
c[::-1][0]
``` this makes me feel annoyed
step]