#esoteric-python
1 messages ยท Page 145 of 1
f=lambda _0,_1=0:((_2:=len(_0),[[[0for(_1)in[_1+(None,1)[_0[_3]+_0[_4]in _0]]]for(_4)in range(_3+1,_2)]]for(_3)in range(_2)],_1)[-1]```
but idk if it works
Also, len(aaa for bbb in ccc if ddd) => sum(ddd for bbb in ccc)
useful golf a lot of the time
my take:
f=lambda w:sum(w[i]+w[j]in w for i in range(len(w))for j in range(i+1,len(w)))
yeah you won't need the extra parentheses for a generator comprehension
u right
i tried to get an elegant solution like:
g=lambda n:len({map(sum,combinations(n,2))}&{*n})
from itertools import*
but i realized you need to account for duplicates
its all about magic methods?
My variant without set() optimization:
f = lambda w: sum(n+m in w for i, n in enumerate(w) for m in w[i+1:])```
with it (almost 20x faster on 250 numbers input):
```python
f = lambda w: (s:=set(w), sum(n+m in s for i, n in enumerate(w) for m in w[i+1:]))[1]```
alright, I've released this 4D 2048 https://github.com/FluffyTrooper2001/__2048__
only support for Windows users.
how is there an only-windows part of this channel and an only-linux part
Could someone tell me where I can get more information about the __code__ dunder?
!e ```py
from pydoc import help
help((lambda:0).code)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | Help on code object:
002 |
003 | class code(object)
004 | | code(argcount, posonlyargcount, kwonlyargcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, linetable, freevars=(), cellvars=(), /)
005 | |
006 | | Create a code object. Not for the faint of heart.
007 | |
008 | | Methods defined here:
009 | |
010 | | __eq__(self, value, /)
011 | | Return self==value.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/mahetarawo.txt?noredirect
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Create a code object. Not for the faint of heart.
!e ```py
print(type(m:=lambda n,s:lambda v:s(v)or n)((M:=m.code).replace(co_code=b'\x88'+M.co_code[1:]),{})(r:=iter(range((1<<63)-1)),r.setstate)(id('\\\''\\'\''''\\\'''''''')))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
\\\''\\'\\\\'''''
I'm not sure what I'm looking at
โ๏ธ
!e
s='s=%r;print(s%%s)';print(s%s)
@wheat river :white_check_mark: Your eval job has completed with return code 0.
s='s=%r;print(s%%s)';print(s%s)
So I've been naming myself python magic methods in a server and then telling facts about them. Here's how it went so far: 
well I learned something new
it's based on chilaxan's load_addr function
works on windows if you modify cpython for it
โ๏ธ
what is prepare lol
oh its for pickle ok
__prepare__ is a magic method for subclasses of type that prepares the attribute dictionary for an instance of the metaclass
you threw in some unnecessary spaces around the equals and after the semicolon?
pycharm auto-formatter be like/...
I "grew up" on IDLE and now use notepad++
pycharm I only pull out if I wanna contribute to someone else's project
I started out that way and learned with vim and smaller editors like kwrite/kate (kde text editor). But I'm just not consistent enough to always manage my git properly if its not in the interface reminding me to take care of it. I think its valuable to learn to code in that sort of light environment but when you realize that you want to be better than you are, less unpredictable, find errors sooner, more organized, because you just naturally aren't.... its worth it to just open every project in the ide.
Crossposting from #internals-and-peps because I found a very cursed solution to a very cursed problem:
I notice that when a descriptor __get__ is called on the class, it's passed None, cls as arguments, whereas with instances it's passed instance, cls.
Now, suppose the descriptor is defined on NoneType. "Would there be any way to distinguish between the two kinds of access?" <- is the question I asked
And the solution is to simply patch both NoneType and type
class Descriptor:
def __get__(self, obj, type):
print("get called", obj, type)
# ONLY works with a data descriptor
def __set__(self, obj, value):
raise AttributeError
import forbiddenfruit
forbiddenfruit.curse(type(None), "test", Descriptor())
forbiddenfruit.curse(type, "test", Descriptor())
type(None).test
None.test
get called <class 'NoneType'> <class 'type'>
get called None <class 'NoneType'>
without the type patch, both calls would print None <class 'NoneType'>. (you also get the same bad result if Descriptor isn't a data descriptor, i.e. doesn't define __set__)
!e ```py
def cast(v, t1, t2, bufsize=tuple.itemsize):
conv = memoryview(bytearray(bufsize))
conv.cast(t1)[0] = v
return conv.cast(t2)[0]
load_addr = lambda addr: type(m:=lambda n:lambda:n)(
(M:=m.code).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(cast(addr, 'l', 'd'))()
print(load_addr(id(1)))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1
it isnt quite as clever as the one that used the range iterator tho ๐ฆ
I never want to come back here again
Probably a wise decision.
>>> print(load_addr(id(1)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in <lambda>
File "<stdin>", line 3, in cast
ValueError: memoryview: invalid value for format 'l'
what?
id should return an int
@quartz wave what is the return value of id on your system?
>>> id(1)
2325276590320
that should definitely not be crashing
do remember long is only 4 bytes on windows
https://github.com/python/cpython/blob/main/Objects/memoryobject.c#L1127 that is just wrong it shouldnt be 4
Objects/memoryobject.c line 1127
case 'l': case 'L': size = sizeof(long); break;```
it is 4 bytes on windows and you can't really change that
that's exactly also the reason why the range hack won't work on windows
yea i know that
!e ```py
def cast(v, t1, t2, bufsize=tuple.itemsize):
conv = memoryview(bytearray(bufsize))
conv.cast(t1)[0] = v
return conv.cast(t2)[0]
load_addr = lambda addr: type(m:=lambda n:lambda:n)(
(M:=m.code).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(cast(addr, 'q', 'd'))()
print(load_addr(id(1)))``` hopefully this one works
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1
that works now
finally
i'm thinking there should probably be a bug report about changing all internal use of long to Py_ssize_t and unsigned long to size_t
but that would probably be backwards-incompatible or something
probably
!e
import forbiddenfruit
class ApproxObject:
def __init__(self, number, range):
assert (isinstance(number, int) and isinstance(range, int))
self.lower_bound = number - abs(range)
self.upper_bound = number + abs(range)
def __str__(self):
return f"Approx [{self.lower_bound}, {self.upper_bound}]"
def __repr__(self):
return self.__str__()
def __eq__(self, other):
assert isinstance(other, int)
return other >= self.lower_bound and other <= self.upper_bound
class ApproxObjectCreator:
def __init__(self, number, range):
self.number = number
self.range = range
def __invert__(self):
return ApproxObject(self.number, self.range)
forbiddenfruit.curse(int, "__matmul__", lambda self, range: ApproxObjectCreator(self, range))
print(-5 == ~(5 @ 10))
@jovial monolith :white_check_mark: Your eval job has completed with return code 0.
True
lol
-10 should be evaluated first, then +?
!e
import forbiddenfruit
forbiddenfruit.curse(int, "__call__", lambda self, other: print(self * other))
print((5)(123))```
@jovial monolith :x: Your eval job has completed with return code 1.
001 | <string>:3: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 | File "<string>", line 2, in <module>
004 | File "/snekbox/user_base/lib/python3.10/site-packages/forbiddenfruit/__init__.py", line 425, in curse
005 | _curse_special(klass, attr, value)
006 | File "/snekbox/user_base/lib/python3.10/site-packages/forbiddenfruit/__init__.py", line 332, in _curse_special
007 | tp_as_name, impl_method = override_dict[attr]
008 | KeyError: '__call__'
cant call it tho
!e ```py
from fishhook import hook
@hook(int)
def call(self, other):
return self * other
print((5)(123))
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:6: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
002 | 615
you can, forbiddenfruit just doesn't let you
that should be builtin behaviour.
why isn't it?
going into python as a mathematician, I always tried to do that with ints.
for example, before actually learning python I was very disappointed when y = 4x^2 + 2(x+3) didn't work
This actually can't work, even with fishhook, because +-10 is reduced to -10 during compilation.. But if we assign 10 to a variable first, it can.
well i just implemented juxtaposition but only for numbers and parenthesized expressions
only in my modified cpython
bytecode analysis in __pos__ to check if it's being called as an argument to an int call
__pos__ won't be called at all
Ah I see
!e
import dis
dis.dis("+-10")
@restive void :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (-10)
002 | 2 RETURN_VALUE
Yeah then some trickery in call is necessary
right, that could work
amazing solution, thanks!
leviathan? subnautica fans shivering rn
made it actually work in cpython
!e
(lambda outside,inside,outer,inner:(lambda shell:[print(shell),(lambda buffer:print("\n".join([f"{outside}{inside*inner:^{buffer}}{outside}"for _ in " "*inner])))(outer-2),print(shell[::-1])])(outside*outer+("\n" if outer-inner-2 else "")+"\n".join(outside+" "*(outer-2)+outside for _ in range((outer-inner)//2-1))))("#","~",7,3)
@terse oriole :white_check_mark: Your eval job has completed with return code 0.
001 | #######
002 | # #
003 | # ~~~ #
004 | # ~~~ #
005 | # ~~~ #
006 | # #
007 | #######
any idea of how to shorten this without changing variable names?
...for _ in " "*inner]...
^ remove space here
..."\n" if...
^ also here
...2 else ""...
^ ^
also these places
it works fine
but the number-before-identifier thingy is deprecated in 3.11
I see
does anyone have a one-liner for installing packages with pip?
__import__('pip')._internal.cli.main.main(['install', 'module'])
this for no warnings
!e
shortened it to this
(lambda o,i,b,a,p:(lambda s:[p(s),(lambda u:p("\n".join([f"{o}{i*a:^{u}}{o}"for _ in" "*a])))(b-2),p(s[::-1])])(o*b+("\n"if b-a-2else"")+"\n".join(o+" "*(b-2)+o for _ in" "*((b-a)//2-1))))("#","~",7,3,print)
@terse oriole :white_check_mark: Your eval job has completed with return code 0.
001 | #######
002 | # #
003 | # ~~~ #
004 | # ~~~ #
005 | # ~~~ #
006 | # #
007 | #######
not sure what else I can do
oh my god
thank you
!e
(lambda o,i,b,a,p:(lambda s:[p(s),(lambda u:p("\n".join([f"{o}{ia:^{u}}{o}"for _ in" "a])))(b-2),p(s[::-1])])(ob+("\n"if b-a-2else"")+"\n".join(o+" "(b-2)+o for _ in" "*((b-a)//2-1))))("#","~",7,3,print)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | #######
002 | # #
003 | # ~~~ #
004 | # ~~~ #
005 | # ~~~ #
006 | # #
007 | #######
cool
noice
hi, has anyone else ran into to some unexpected behavior due to PEP 515? https://peps.python.org/pep-0515/ i was loading some data into pandas and one of the fields is a string that looks like
"123_456"
but it was inferred as an int type while I was expecting it to properly infer an object type
Python Enhancement Proposals (PEPs)
i managed to shorten it to py (lambda o,i,b,a,c:print((x:=o*b)+'\n'+c((o+c(i*a,' ',b-a-2)+o+'\n')*a,o+" "*(b-a+1)+o+'\n',b-a-2)+x))("#","~",7,3,lambda s,f,n:(i:=n//2*f)+s+i)
life is a conundrum of esoterica
Change everything to esoterica
esoterica esoterica esoterica esoterica esoterica esoterica
someone should make a language literally made of the word esoterica
we've already got the chicken esolang
it's literally made of the word "chicken"
I wanted to show off my simple module traversing code
import bs4
from inspect import getmembers, ismodule
from pprint import pprint
def find_members(module):
results = {module.__name__: module}
for k, m in getmembers(module, ismodule):
if m.__name__.startswith(module.__name__):
results.update(find_members(m))
return results
pprint(find_members(bs4))
outputs:
{'bs4': <module 'bs4' from '/usr/local/lib/python3.9/dist-packages/bs4/__init__.py'>,
'bs4.builder': <module 'bs4.builder' from '/usr/local/lib/python3.9/dist-packages/bs4/builder/__init__.py'>,
'bs4.builder._html5lib': <module 'bs4.builder._html5lib' from '/usr/local/lib/python3.9/dist-packages/bs4/builder/_html5lib.py'>,
'bs4.builder._htmlparser': <module 'bs4.builder._htmlparser' from '/usr/local/lib/python3.9/dist-packages/bs4/builder/_htmlparser.py'>,
'bs4.builder._lxml': <module 'bs4.builder._lxml' from '/usr/local/lib/python3.9/dist-packages/bs4/builder/_lxml.py'>,
'bs4.dammit': <module 'bs4.dammit' from '/usr/local/lib/python3.9/dist-packages/bs4/dammit.py'>,
'bs4.element': <module 'bs4.element' from '/usr/local/lib/python3.9/dist-packages/bs4/element.py'>,
'bs4.formatter': <module 'bs4.formatter' from '/usr/local/lib/python3.9/dist-packages/bs4/formatter.py'>}```
that I had just written somebody in a help channel
since the person left ๐
the one issue is this code does not eagerly load submodules
but I've gotten into trouble doing so
so this is probably a start
my workaround is to catch SystemExit ๐
so as to prevent annoying exits of the program while loading child modules ..
and skipping some things
>>> print(importAll(lsmod(bs4)))
bs4: [OK]
bs4.builder: [OK]
bs4.builder._html5lib: [OK]
bs4.builder._htmlparser: [OK]
bs4.builder._lxml: [OK]
bs4.dammit: [OK]
bs4.diagnose: [OK]
bs4.element: [OK]
bs4.formatter: [OK]
bs4.testing: Skipping
bs4.tests: Skipping
bs4.tests.test_builder_registry: Skipping
bs4.tests.test_docs: Skipping
bs4.tests.test_html5lib: Skipping
bs4.tests.test_htmlparser: Skipping
bs4.tests.test_lxml: Skipping
bs4.tests.test_soup: Skipping
bs4.tests.test_tree: Skipping
{'bs4': <module 'bs4' from '/usr/local/lib/python3.9/dist-packages/bs4/__init__.py'>, 'bs4.builder': <module 'bs4.builder' from '/usr/local/lib/python3.9/dist-packages/bs4/builder/__init__.py'>, 'bs4.builder._html5lib': <module 'bs4.builder._html5lib' from '/usr/local/lib/python3.9/dist-packages/bs4/builder/_html5lib.py'>, 'bs4.builder._htmlparser': <module 'bs4.builder._htmlparser' from '/usr/local/lib/python3.9/dist-packages/bs4/builder/_htmlparser.py'>, 'bs4.builder._lxml': <module 'bs4.builder._lxml' from '/usr/local/lib/python3.9/dist-packages/bs4/builder/_lxml.py'>, 'bs4.dammit': <module 'bs4.dammit' from '/usr/local/lib/python3.9/dist-packages/bs4/dammit.py'>, 'bs4.diagnose': <module 'bs4.diagnose' from '/usr/local/lib/python3.9/dist-packages/bs4/diagnose.py'>, 'bs4.element': <module 'bs4.element' from '/usr/local/lib/python3.9/dist-packages/bs4/element.py'>, 'bs4.formatter': <module 'bs4.formatter' from '/usr/local/lib/python3.9/dist-packages/bs4/formatter.py'>}```
yes it's camel case ( I named it before I was enlightened)
:)
If you want a chicken implementation, I did one here :)
Can probably get shorter
YES
anyboady in vr career and pursuing it
doubt you can use VR and python but yes i am trying to
I came up with this crazy one liner which will use a monte carlo method to approximate pi
print(4*len([point for point in [(__import__('random', globals(), locals(), [], 0).random() * 2 -1, __import__('random', globals(), locals(), [], 0).random() * 2 - 1) for x in range(100000)] if point[0] ** 2 + point[1] ** 2 < 1])/100000)
!e
print(4*len([point for point in [(__import__('random', globals(), locals(), [], 0).random() * 2 -1, __import__('random', globals(), locals(), [], 0).random() * 2 - 1) for x in range(100000)] if point[0] ** 2 + point[1] ** 2 < 1])/100000)
@wild saddle :white_check_mark: Your eval job has completed with return code 0.
3.13976
cool
!e i came up with this crazier one liner which will print pi to the max amount of digits that python can handle with the float class ```py
print(import('math').pi)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
3.141592653589793
thats true, but it doesen't actually compute pi
the one liner I wrote could theoretically calculate pi to infinite digits
hmm let's see
even the more efficent methods of calculating pi with riemann functions and such are pretty intense and require a lot of iterations to reach accuracy
why the deviation?
also it only calculates pi to 2 digits after the decimal point
approximately 2 digits and exactly correct only for 1 digit after the decimal point
Im aware that that my one liner sucks at calculating pi
hey guys one line _with statement?
but the idea that you could actually calculate pi in a one liner is crazy
it's not every one liner
some other one liners can calculate pi to infinite digits
it will if you iterate through it more
ok
when running
print(4*len([point for point in [(__import__('random').random() * 2 -1, __import__('random').random() * 2 - 1) for x in range(10000000)] if point[0] ** 2 + point[1] ** 2 < 1])/10000000)
on my own computer I got the result 3.1419104
so by adjusting the amount of times you iterate through the monte carlo method you can get infintely precise (which I have so far not been able to see python obstruct)
it's a little slow
obviously
those more efficient ones can probably do it in less iterations and less time
oh yeah for sure
the method I used here is almost certainly the least efficent way of calculating pi, which is why I thought it would be fun to implement as a one liner
it probably was fun
but you didn't need to add extra arguments to __import__
!e
print(4*len([point for point in [(__import__('random').random() * 2 -1, __import__('random').random() * 2 - 1) for x in range(10000)] if point[0] ** 2 + point[1] ** 2 < 1])/10000)
@wild saddle :white_check_mark: Your eval job has completed with return code 0.
3.1252
true thanks
i got a MemoryError
print(4*len([point for point in[(r:=(__import__('random',globals(),locals(),[],0).random)()*2-1,r()*2-1)for x in range(100000)]if point[0]**2+point[1]**2<1])/100000)โ
it's slightly shorter
print(4*len([point for point in[((r:=__import__('random').random)()*2-1,r()*2-1)for x in range(100000)]if point[0]**2+point[1]**2<1])/100000)โ
``` it's slightly shorter now
print(4*len([point for point in[((r:=__import__('random').random)()*2-1,r()*2-1)for x in range(10**5)]if point[0]**2+point[1]**2<1])/10**5)
it's slightly shorter now
also
SyntaxError: assignment expression cannot be used in a comprehension iterable expression```
so (r:=__import__('random').random) should be moved out of print
r=__import__('random').random;print(4*len([point for point in[(r()*2-1,r()*2-1)for x in range(10**5)]if point[0]**2+point[1]**2<1])/10**5)```
>>> len("""r=__import__('random').random;print(4*len([point for point in[(r()*2-1,r()*2-1)for x in range(10**5)]if point[0]**2+point[1]**2<1])/10**5)""")
138
>>> len("""print(4*len([point for point in[((r:=__import__('random').random)()*2-1,r()*2-1)for x in range(10**5)]if point[0]**2+point[1]**2<1])/10**5)""")
139
>>>```
!e ```py
r=import('random').random;print(4*len((p:=(r()*2-1,r()*2-1))for _ in range(10**5)if p[0]**2+p[1]2<1)/105)
@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 <listcomp>
004 | NameError: name 'p' is not defined
!e py r=__import__('random').random;print(4*len([point for point in[(r()*2-1,r()*2-1)for x in range(10**5)]if point[0]**2+point[1]**2<1])/10**5)
@sly root :white_check_mark: Your eval job has completed with return code 0.
3.14264
!e py r=__import__('random').random;print(4*len([p for(p)in[(r()*2-1,r()*2-1)for x in range(10**5)]if p[0]**2+p[1]**2<1])/10**5)
@sly root :white_check_mark: Your eval job has completed with return code 0.
3.14468
!e ```py
r=import('random').random;print(4*len((p:=(r()*2-1,r()*2-1))for _ in range(10**5)if p[0]**2+p[1]2<1)/105)
@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 | TypeError: object of type 'generator' has no len()
!e ```py
r=import('random').random;print(4len([((p:=(r()*2-1,r()*2-1))for _ in range(10**5)if p[0]**2+p[1]2<1)])/105)
@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 <genexpr>
004 | NameError: name 'p' is not defined
ok thanks
!e ```py
r=import('random').random;print(4*len([p for _ in range(10**5)if (p:=(r()*2-1,r()*2-1))[0]**2+p[1]2<1])/105)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
3.14644
!e ```py
r=import('random').random;print(len([p for _ in range(10**5)if (p:=(r()*2-1,r()*2-1))[0]**2+p[1]**2<1])/25e3)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
3.13552
probably shortest version we have yet
!e ```py
r=import('random').random;print(sum((r()*2-1)**2+(r()*2-1)2<1for _ in range(105))/25e3)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
3.13556
and it doesn't run out of memory for me any more if i increase the powers by 3
yeah but if using tio, then it would be even shorter
with moving import to header section
>>> len("print(sum((r()*2-1)**2+(r()*2-1)**2<1for _ in range(10**5))/25e3)")
65
>>>```
95 from 237
!e ```py
from random import random as r
just 1 quadrant
print(sum(r()**2+r()2<1for()in[()]*105)/25e3)
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
3.132
even shorter
!e
print(22/7)
@severe canyon :white_check_mark: Your eval job has completed with return code 0.
3.142857142857143
!e
print(((-1)**(t:=1e-9)).imag/t)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
3.141592653589793
Did i win?
!e
ฯ = ((-1)**(t:=1e-9)).imag/t
import math
assert ฯ == math.pi
print(ฯ)
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
3.141592653589793
!e
print(((-1)**1e-9).imag*1e9)
print(((-1)**(t:=1e-9)).imag/t)โ
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
001 | 3.141592653589793
002 | 3.141592653589793
cause of e to the i pi? (euler's formula or something)
!e ```py
print(((-1)**1e-100).imag*1e100)
@turbid dragon :white_check_mark: Your eval job has completed with return code 0.
3.141592653589793
rip
can't reach the limits of float ig
e is like how many zeros prob,
for example 1e3 is 1000
and 1e-1 is 0.1
I hope I'm not wrong
Foiled by your memory lol
evil ram ๐
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
import numpy as np
import matplotlib.pyplot as plt
grid = np.zeros(100*100).reshape(100, 100)
plt.imshow(grid)
plt.show()
Does anyone have issues running this code ?
Whenever i run it everything seems normal until i put my mouse on the pyplot something like this happens
nope e is the logarithmic constant
and it starts glitching out non stop
i forgot what
any issues with the code or matplotlib is just broken or smth
this is not a help channel, #โ๏ฝhow-to-get-help
thanks
print(chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.10256410256410256))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.5544554455445545))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.06779661016949153))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07920792079207921))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07017543859649122))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.7887323943661971))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07207207207207207))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07272727272727272))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.509090909090909))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.08247422680412371))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.11267605633802817))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.0761904761904762))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.06779661016949153))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07920792079207921))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/1.75))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.0898876404494382))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.5045045045045045))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.47863247863247865))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.6588235294117647))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07142857142857142)))โ
sus :)
is that a rickroll
the first letter is N
the last letter is p
Yes, so?
could've been better if you didn't add that "so?", like if you don't care why post here
!e
print(chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.10256410256410256))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.5544554455445545))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.06779661016949153))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07920792079207921))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07017543859649122))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.7887323943661971))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07207207207207207))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07272727272727272))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.509090909090909))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.08247422680412371))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.11267605633802817))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.0761904761904762))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.06779661016949153))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07920792079207921))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/1.75))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.0898876404494382))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.5045045045045045))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.47863247863247865))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.6588235294117647))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07142857142857142)))โโ
@jovial monolith :white_check_mark: Your eval job has completed with return code 0.
Never Gonna Give You Up
ouch
inp = input();print(f"Original list: {list(map(int, inp.split()))}\nModified list: {list(filter(lambda i2: int(i2) % 2, list(map(int, inp.split()))))}")
``` got this rn but can be better
print(f"Original list: {eval('(u_list:=[*map(int,input().split())])',globals(),globals())}\nModified list: {eval('(m_list:=[x for x in u_list if x&1])',globals(),globals())}")
made it better
it's now just on one line with only one expression
Was thinking about walrus too idk
got it
!e
from math import sqrt
ttt_board = lambda limit, length: [sq := sqrt(limit), ''.join([f'{i:^{length}}|' if i % sq else f'{i:^{length}}\n{"-"*(limit+length+int(sq))}\n' if i != limit else f'{i:^{length}}' for i in range(1, limit+1)])][1]
print(ttt_board(9, 5))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | 1 | 2 | 3
002 | -----------------
003 | 4 | 5 | 6
004 | -----------------
005 | 7 | 8 | 9
!e
from math import sqrt
ttt_board = lambda limit, length: [sq := sqrt(limit), ''.join([f'{i:^{length}}|' if i % sq else f'{i:^{length}}\n{"-"*(limit+length+int(sq))}\n' if i != limit else f'{i:^{length}}' for i in range(1, limit+1)])][1]
print(ttt_board(64, 12))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
002 | ------------------------------------------------------------------------------------
003 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16
004 | ------------------------------------------------------------------------------------
005 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24
006 | ------------------------------------------------------------------------------------
007 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32
008 | ------------------------------------------------------------------------------------
009 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40
010 | --------------------------------------------------------------------------------
... (truncated - too long, too many lines)
Full output: https://paste.pythondiscord.com/uvufipenib.txt?noredirect
:(
!e
ttt_board = lambda limit, length: [sq := sqrt(limit), ''.join([f'{i:^{length}}|' if i % sq else f'{i:^{length}}\n{"-"*(limit*2-length*2)}\n' if i != limit else f'{i:^{length}}' for i in range(1, limit+1)])][1]
print(ttt_board(64, 12))```
@wheat river :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 | NameError: name 'sqrt' is not defined
-_-
!e
from math import sqrt
ttt_board = lambda limit, length: [sq := sqrt(limit), ''.join([f'{i:^{length}}|' if i % sq else f'{i:^{length}}\n{"-"*(limit*2-length*2)}\n' if i != limit else f'{i:^{length}}' for i in range(1, limit+1)])][1]
print(ttt_board(64, 12))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
002 | --------------------------------------------------------------------------------------------------------
003 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16
004 | --------------------------------------------------------------------------------------------------------
005 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24
006 | --------------------------------------------------------------------------------------------------------
007 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32
008 | --------------------------------------------------------------------------------------------------------
009 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40
010 |
... (truncated - too long, too many lines)
Full output: https://paste.pythondiscord.com/bujudavitu.txt?noredirect
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Hey @shut smelt!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
i think you don't need evals and last walrus
print(f"Original list: {(u_list:=[*map(int,input().split())])}\nModified list: {[x for(x)in(u_list)if x&1]}")```
it works but idk what is expected from it
SPOILER: this file contains code that will scare you for life
its so unreadable I don't think you'd ever want to touch this or even KEEP this on your computer
Hey @faint ether!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
I might be missing something, but whats esoteric in your code?
it's certainly wide :>
Why would you rickroll yourself, everyone knows it's a rickroll
!e py exec(__import__("types").CodeType( 0,0,0,0,4,64, bytes([100,0, 100,1, 132,0, 90,0, 101,1, 101,0, 100,2, 100,3, 132,0, 131,1, 131,1, 1,0, 100,4, 83,0,]), ('a','<lambda>',None,),('a','print'), (),'','<module>', 1, bytes([8,2,]), (),()))
@sly root :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
challenge for everyone in this channel, guess why its giving sigsegv if everyting is written correctly๐ค
!e py __import__("dis").dis(__import__("types").CodeType( 0,0,0,0,4,64, bytes([100,0, 100,1, 132,0, 90,0, 101,1, 101,0, 100,2, 100,3, 132,0, 131,1, 131,1, 1,0, 100,4, 83,0,]), ('a','<lambda>',None,),('a','print'), (),'','<module>', 1, bytes([8,2,]), (),()))
@earnest wing :x: Your eval job has completed with return code 1.
001 | 3 0 LOAD_CONST 0 ('a')
002 | 2 LOAD_CONST 1 ('<lambda>')
003 | 4 MAKE_FUNCTION 0
004 | 6 STORE_NAME 0 (a)
005 | 8 LOAD_NAME 1 (print)
006 | 10 LOAD_NAME 0 (a)
007 | 12 LOAD_CONST 2 (None)
008 | Traceback (most recent call last):
009 | File "<string>", line 1, in <module>
010 | File "/usr/local/lib/python3.10/dis.py", line 79, in dis
011 | _disassemble_recursive(x, file=file, depth=depth)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/yokuhizedi.txt?noredirect
!e print(import("dis").opmap)
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
{'POP_TOP': 1, 'ROT_TWO': 2, 'ROT_THREE': 3, 'DUP_TOP': 4, 'DUP_TOP_TWO': 5, 'ROT_FOUR': 6, 'NOP': 9, 'UNARY_POSITIVE': 10, 'UNARY_NEGATIVE': 11, 'UNARY_NOT': 12, 'UNARY_INVERT': 15, 'BINARY_MATRIX_MULTIPLY': 16, 'INPLACE_MATRIX_MULTIPLY': 17, 'BINARY_POWER': 19, 'BINARY_MULTIPLY': 20, 'BINARY_MODULO': 22, 'BINARY_ADD': 23, 'BINARY_SUBTRACT': 24, 'BINARY_SUBSCR': 25, 'BINARY_FLOOR_DIVIDE': 26, 'BINARY_TRUE_DIVIDE': 27, 'INPLACE_FLOOR_DIVIDE': 28, 'INPLACE_TRUE_DIVIDE': 29, 'GET_LEN': 30, 'MATCH_MAPPING': 31, 'MATCH_SEQUENCE': 32, 'MATCH_KEYS': 33, 'COPY_DICT_WITHOUT_KEYS': 34, 'WITH_EXCEPT_START': 49, 'GET_AITER': 50, 'GET_ANEXT': 51, 'BEFORE_ASYNC_WITH': 52, 'END_ASYNC_FOR': 54, 'INPLACE_ADD': 55, 'INPLACE_SUBTRACT': 56, 'INPLACE_MULTIPLY': 57, 'INPLACE_MODULO': 59, 'STORE_SUBSCR': 60, 'DELETE_SUBSCR': 61, 'BINARY_LSHIFT': 62, 'BINARY_RSHIFT': 63, 'BINARY_AND': 64, 'BINARY_XOR': 65, 'BINARY_OR': 66, 'INPLACE_POWER': 67, 'GET_ITER': 68, 'GET_YIELD_FROM_ITER': 69, 'PRINT_EXPR': 70, 'LOA
... (truncated - too long)
Full output: https://paste.pythondiscord.com/popisixewi.txt?noredirect
that 100, 3 is reading out of bounds from the co_consts tuple
because bounds checking is slow
hmm
oh is this like a question or a challenge
Woaaaaahhhh
!e ```py
print((lambda l,n:[s:=l**.5,''.join([f'{i:^{n}}|'if i%s else f'{i:^{n}}\n{"-"(l2-n*2)}\n'if i!=l else f'{i:^{n}}'for i in range(1,l+1)])][1])(64,12))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
002 | --------------------------------------------------------------------------------------------------------
003 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16
004 | --------------------------------------------------------------------------------------------------------
005 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24
006 | --------------------------------------------------------------------------------------------------------
007 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32
008 | --------------------------------------------------------------------------------------------------------
009 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40
010 |
... (truncated - too long, too many lines)
Full output: https://paste.pythondiscord.com/eyabiwovoj.txt?noredirect
Dear god
The syntax... the dirty unorganized code
I think I am going to be sick
welcome to esoteric python
I need to bring some holy water and a cross for this chat
Sweet baby kitten I need a whole water tower of holy water
!e ```py
print((lambda l,n:[s:=l**.5,''.join([f'''{i:^{n}}{"|"(i%s>0)}{("-"(l2-n2)).join("""
""")*(i%s<1)}'''if i!=l else f'{i:^{n}}'for i in range(1,l+1)])][1])(64,12))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
002 | --------------------------------------------------------------------------------------------------------
003 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16
004 | --------------------------------------------------------------------------------------------------------
005 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24
006 | --------------------------------------------------------------------------------------------------------
007 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32
008 | --------------------------------------------------------------------------------------------------------
009 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40
010 |
... (truncated - too long, too many lines)
Full output: https://paste.pythondiscord.com/egeguvolud.txt?noredirect
!e ```py
print((lambda l,n:[s:=l**.5,''.join([f'{i:^{n}}'+f'''{"|"(i%s>0)}{("-"(l2-n2)).join("""
""")(i%s<1)}'''(i!=l)for i in range(1,l+1)])][1])(64,12))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
002 | --------------------------------------------------------------------------------------------------------
003 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16
004 | --------------------------------------------------------------------------------------------------------
005 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24
006 | --------------------------------------------------------------------------------------------------------
007 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32
008 | --------------------------------------------------------------------------------------------------------
009 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40
010 |
... (truncated - too long, too many lines)
Full output: https://paste.pythondiscord.com/hayeyizaho.txt?noredirect
more taking-advantage-of-python-syntax code gore
nsfw python moment
!e py print((lambda l,n:[s:=l**.5,''.join([((f'{i:^{n}}',f'{i:^{n}}\n{"-"*(l*2-n*2)}\n')[i!=l],f'{i:^{n}}|')[bool(i%s)]for i in range(1,l+1)])][1])(64,12))
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
002 | --------------------------------------------------------------------------------------------------------
003 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16
004 | --------------------------------------------------------------------------------------------------------
005 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24
006 | --------------------------------------------------------------------------------------------------------
007 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32
008 | --------------------------------------------------------------------------------------------------------
009 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40
010 |
... (truncated - too long, too many lines)
Full output: https://paste.pythondiscord.com/fowesiqaza.txt?noredirect
was 149 chars
now is 147 chars
you could've done py i%s>0 instead of ```py
bool(i%s)
ah
133
!e py print((lambda l,n:''.join([((f'{i:^{n}}',f'{i:^{n}}\n{"-"*(l*2-n*2)}\n')[i!=l],f'{i:^{n}}|')[i%l**.5>0]for i in range(1,l+1)]))(64,12))
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
002 | --------------------------------------------------------------------------------------------------------
003 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16
004 | --------------------------------------------------------------------------------------------------------
005 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24
006 | --------------------------------------------------------------------------------------------------------
007 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32
008 | --------------------------------------------------------------------------------------------------------
009 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40
010 |
... (truncated - too long, too many lines)
Full output: https://paste.pythondiscord.com/azuwipasaj.txt?noredirect
we don't need it to be a lambda
i think everything that is posted in this channel must be automatically golfed to 1 byte
!e more hardcoding ```py
print(*[(f'{i:^{12}}\n{"-"*104}\n',f'{i:^{12}}|')[i%8>0]for i in range(1,64)],f'{64:^{12}}',sep='')
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
002 | --------------------------------------------------------------------------------------------------------
003 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16
004 | --------------------------------------------------------------------------------------------------------
005 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24
006 | --------------------------------------------------------------------------------------------------------
007 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32
008 | --------------------------------------------------------------------------------------------------------
009 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40
010 |
... (truncated - too long, too many lines)
Full output: https://paste.pythondiscord.com/asefimalam.txt?noredirect
!e complete remodel of code ```py
print(*['|'.join(f'{x:^{12}}'for x in range(y-7,y+1))for y in range(8,65,8)],sep=f'\n{"-"*104}\n')
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
002 | --------------------------------------------------------------------------------------------------------
003 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16
004 | --------------------------------------------------------------------------------------------------------
005 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24
006 | --------------------------------------------------------------------------------------------------------
007 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32
008 | --------------------------------------------------------------------------------------------------------
009 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40
010 |
... (truncated - too long, too many lines)
Full output: https://paste.pythondiscord.com/putirezoni.txt?noredirect
๐
!e
print((lambda l,n:[s:=l**.5,''.join([f'{i:^{n}}|'if i%s else f'{i:^{n}}\n{"-"*(l*2-n*2)}\n'if i!=l else f'{i:^{n}}'for i in range(1,l+1)])][1])(64,12))
!e
print((lambda l,n:[s:=l**.5,''.join([f'{i:^{n}}|'if i%s else f'{i:^{n}}\n{"-"*(l*2-n*2)}\n'if i!=l else f'{i:^{n}}'for i in range(1,l+1)])][1])(64,12))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
002 | --------------------------------------------------------------------------------------------------------
003 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16
004 | --------------------------------------------------------------------------------------------------------
005 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24
006 | --------------------------------------------------------------------------------------------------------
007 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32
008 | --------------------------------------------------------------------------------------------------------
009 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40
010 |
... (truncated - too long, too many lines)
Full output: https://paste.pythondiscord.com/limikafuge.txt?noredirect
!e
from itertools import count, takewhile
from contextlib import contextmanager
from time import perf_counter
@contextmanager
def timer(name):
start = perf_counter()
yield
end = perf_counter()
print(f'{name:<50} | {end - start} s')
def collatz_conj(num):
return [*takewhile(lambda val: val != 1, ((num := 3 * num + 1 if num % 2 else num // 2) for _ in count()))]
with timer('10e1000'):
print(collatz_conj(int(10e100)))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | [49999999999999998852475663262266831422342135996207500306499798736599672609039495565163064724075577344, 24999999999999999426237831631133415711171067998103750153249899368299836304519747782581532362037788672, 12499999999999999713118915815566707855585533999051875076624949684149918152259873891290766181018894336, 6249999999999999856559457907783353927792766999525937538312474842074959076129936945645383090509447168, 3124999999999999928279728953891676963896383499762968769156237421037479538064968472822691545254723584, 1562499999999999964139864476945838481948191749881484384578118710518739769032484236411345772627361792, 781249999999999982069932238472919240974095874940742192289059355259369884516242118205672886313680896, 390624999999999991034966119236459620487047937470371096144529677629684942258121059102836443156840448, 195312499999999995517483059618229810243523968735185548072264838814842471129060529551418221578420224, 976562499999999977587415298091149051217619843675927740361324194074212355645
... (truncated - too long)
Full output: too long to upload
:(
!e
from itertools import count, takewhile
from contextlib import contextmanager
from time import perf_counter
@contextmanager
def timer(name):
start = perf_counter()
yield
end = perf_counter()
print(f'{name:<50} | {end - start} s')
def collatz_conj(num):
return [*takewhile(lambda val: val != 1, ((num := 3 * num + 1 if num % 2 else num // 2) for _ in count()))]
with timer('10e1000'):
(collatz_conj(int(10e100)))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
10e1000 | 0.0004028184339404106 s
tf
!e
from itertools import count, takewhile
from contextlib import contextmanager
from time import perf_counter
@contextmanager
def timer(name):
start = perf_counter()
yield
end = perf_counter()
print(f'{name:<50} | {end - start} s')
def collatz_conj(num):
return [*takewhile(lambda val: val != 1, ((num := 3 * num + 1 if num % 2 else num // 2) for _ in count()))]
with timer('10e1000'):
(collatz_conj(int(10e1000)))
@wheat river :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 17, in <module>
003 | OverflowError: cannot convert float infinity to integer
!e
from itertools import count, takewhile
from contextlib import contextmanager
from time import time
from pprint import pprint
@contextmanager
def timer(name):
start = time()
yield
end = time()
print(f'{name:<50} | {end - start} s')
def collatz_conj(num):
return [*takewhile(lambda val: val != 1, ((num := 3 * num + 1 if num % 2 else num // 2) for _ in count()))]
with timer('10e1000'):
collatz_conj(10**100)
@wheat river :white_check_mark: Your eval job has completed with return code 0.
10e1000 | 0.001003265380859375 s
!e
from itertools import count, takewhile
from contextlib import contextmanager
from time import time
from pprint import pprint
@contextmanager
def timer(name):
start = time()
yield
end = time()
print(f'{name:<50} | {end - start} s')
def collatz_conj(num):
return [*takewhile(lambda val: val != 1, ((num := 3 * num + 1 if num % 2 else num // 2) for _ in count()))]
with timer('10^1000'):
collatz_conj(10**10000)
@wheat river :warning: Your eval job timed out or ran out of memory.
[No output]
where can i learn these?
heyo i can do that with single line of code
!e
a = 1
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
easy
learn python

alternative way to do while? i've learn while True already and now i want to learn while x < {num}
there are alternatives to almost everything in python
there are another type of loop called for, it iterates over iterable objects likes list, tuple, str
whats altera of if
yo are you free?
like uhh
i'm doing some project
and i can't test it myself
because i'm the owner
and the bot can't change my name that's the thing
not right now, gotta grab some noodles
aight
hi
if any ppl here become active, ping me plz
look
import urllib.request;exec(open(urllib.request.urlretrieve('https://raw.githubusercontent.com/AFK-debug-9/test/main/test.py')[0],'r').read())``` (pulls that via internet)
!e py import urllib.request;exec(open(urllib.request.urlretrieve('https://raw.githubusercontent.com/AFK-debug-9/test/main/test.py')[0],'r').read())
@split salmon :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/usr/local/lib/python3.10/urllib/request.py", line 1348, in do_open
003 | h.request(req.get_method(), req.selector, req.data, headers,
004 | File "/usr/local/lib/python3.10/http/client.py", line 1282, in request
005 | self._send_request(method, url, body, headers, encode_chunked)
006 | File "/usr/local/lib/python3.10/http/client.py", line 1328, in _send_request
007 | self.endheaders(body, encode_chunked=encode_chunked)
008 | File "/usr/local/lib/python3.10/http/client.py", line 1277, in endheaders
009 | self._send_output(message_body, encode_chunked=encode_chunked)
010 | File "/usr/local/lib/python3.10/http/client.py", line 1037, in _send_output
011 | self.send(msg)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/voqewimevu.txt?noredirect
no net :(
the bot does not have network access by design
hola
look what i sent
@bronze merlin see
na i'm bad at those
run it (if you want, online if you want)
no thx mate
k
!e ```py
import sys,time,itertools,threading
class UnixLoading:
def enter(s):
def __thr(s):
for(_l)in itertools.cycle("|/-\"):
sys.stdout.write(f"{_l} Loading\r")
sys.stdout.flush()
time.sleep(.29)
s.t=threading.Thread(target=__thr,args=(s,),daemon=True)
s._s=int(str(time.clock_gettime_ns(0))[0:13])
s.t.start()
def exit(s,t,v,b):
s.t._delete();s._e=int(str(time.clock_gettime_ns(0))[0:13])
if t is not None:sys.stdout.write(f"โ Error after {abs((s._s-s._e)/1000)} seconds.\n\r");sys.stdout.flush()
else:sys.stdout.write(f"โ
Success. (lasted {abs((s._s-s._e)/1000)} seconds.)\n\r");sys.stdout.flush()
with UnixLoading():
import requests
a = requests.get("https://zeronet.space")
print(b)```
@sly root :x: Your eval job has completed with return code 1.
001 | | Loading
002 | โ Error after 0.002 seconds.
003 |
004 | Traceback (most recent call last):
005 | File "<string>", line 18, in <module>
006 | ModuleNotFoundError: No module named 'requests'
ah
!e ```py
import sys,time,itertools,threading
class UnixLoading:
def enter(s):
def __thr(s):
for(_l)in itertools.cycle("|/-\"):
sys.stdout.write(f"{_l} Loading\r")
sys.stdout.flush()
time.sleep(.29)
s.t=threading.Thread(target=__thr,args=(s,),daemon=True)
s._s=int(str(time.clock_gettime_ns(0))[0:13])
s.t.start()
def exit(s,t,v,b):
s.t._delete();s._e=int(str(time.clock_gettime_ns(0))[0:13])
if t is not None:sys.stdout.write(f"โ Error after {abs((s._s-s._e)/1000)} seconds.\n\r");sys.stdout.flush()
else:sys.stdout.write(f"โ
Success. (lasted {abs((s._s-s._e)/1000)} seconds.)\n\r");sys.stdout.flush()
with UnixLoading():
print("hello world")```
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | | Loading
002 | hello world
003 | โ
Success. (lasted 0.001 seconds.)
!e
def sqrt(num):
num=abs(num)
guessfrom=0
guessto=1
while guessto*guessto < num:
guessfrom=guessto
guessto=guessto*2
margin=0.000000000001*num
guess=(guessfrom+guessto)/2
while not abs(num-(guess*guess)) <= margin:
if num-(guess*guess) > margin:
guessfrom+=(guessto-guessfrom)/2
else:
guessto-=(guessto-guessfrom)/2
guess=(guessfrom+guessto)/2
return guess
@uncut bolt :warning: Your eval job has completed with return code 0.
[No output]
!e
def sqrt(num):
num=abs(num)
guessfrom=0
guessto=1
while guessto*guessto < num:
guessfrom=guessto
guessto=guessto*2
margin=0.000000000001*num
guess=(guessfrom+guessto)/2
while not abs(num-(guess*guess)) <= margin:
if num-(guess*guess) > margin:
guessfrom+=(guessto-guessfrom)/2
else:
guessto-=(guessto-guessfrom)/2
guess=(guessfrom+guessto)/2
return guess
print(sqrt(25))
@uncut bolt :white_check_mark: Your eval job has completed with return code 0.
5.0
working on lambdaified version
!e
sqrt=lambda num: (
(lambda num,margin,guessL,i: (
len([(lambda num,margin,guessL,i:
None if abs(num-(guessL[-1]*guessL[-1])) <= margin else (
(
guessL.__setitem__(0,guessL[0]+(guessL[1]-guessL[0])/2)
if num-(guessL[-1]*guessL[-1]) > margin
else guessL.__setitem__(1,guessL[1]-(guessL[1]-guessL[0])/2)
) or guessL.__setitem__(-1,(guessL[1]+guessL[0])/2)
or print(guessL)
) or i.append(None)
) (num,margin,guessL,i) for _ in zip(i)])*0 + guessL[-1]
)) (
abs(num),
0.000000000001*num,
(lambda num,guessL,i: ([
(lambda num,guessL,i:(
(guessL[0]*guessL[1] < num) and (
i.append(None) or
guessL.__setitem__(0,guessL[1]) or
guessL.__setitem__(1,guessL[1]*2) or
guessL.__setitem__(2,(guessL[0]+guessL[1])/2)
)
)) (num,guessL,i) for _ in zip(i)
]*0 + guessL) ) (abs(num),[0,1,.5],[None]),
[None]
)
)
print(sqrt(25))
@uncut bolt :white_check_mark: Your eval job has completed with return code 0.
001 | [4, 6.0, 5.0]
002 | 5.0
!e
sqrt=lambda n: (
(lambda n,m,g,i:
len([(lambda n,m,g,i:
0 if abs(n-(g[-1]*g[-1])) <= m else
g.__setitem__(0,g[0]+(g[1]-g[0])/2)
if n-(g[-1]*g[-1]) > m
else g.__setitem__(1,g[1]-(g[1]-g[0])/2)
or g.__setitem__(-1,(g[1]+g[0])/2)
or i.append(0)
) (n,m,g,i) for _ in zip(i)])*0 + g[-1]
) (
abs(n),
1e-12*n,
(lambda n,g,i: [
(lambda n,g,i:
g[0]*g[1] < n and (
i.append(0) or
g.__setitem__(0,g[1]) or
g.__setitem__(1,g[1]*2) or
g.__setitem__(2,(g[0]+g[1])/2)
)
) (n,g,i) for _ in zip(i)
]*0 + g ) (abs(n),[0,1,.5],[0]),
[0]
)
)
print(sqrt(25))
@uncut bolt :white_check_mark: Your eval job has completed with return code 0.
5.0
minified
!e
sqrt=lambda n:((lambda n,m,g,i:len([(lambda n,m,g,i:0 if abs(n-(g[-1]*g[-1]))<=m else g.__setitem__(0,g[0]+(g[1]-g[0])/2)if n-(g[-1]*g[-1])>m else g.__setitem__(1,g[1]-(g[1]-g[0])/2)or g.__setitem__(-1,(g[1]+g[0])/2)or i.append(0))(n,m,g,i)for _ in zip(i)])*0+g[-1])(abs(n),1e-12*n,(lambda n,g,i:[(lambda n,g,i:g[0]*g[1]<n and(i.append(0)or g.__setitem__(0,g[1])or g.__setitem__(1,g[1]*2)or g.__setitem__(2,(g[0]+g[1])/2)))(n,g,i)for _ in zip(i)]*0+g)(abs(n),[0,1,.5],[0]),[0]))
print(sqrt(5))
@uncut bolt :white_check_mark: Your eval job has completed with return code 0.
2.125
!e
sqrt=lambda n:((lambda n,m,g,i:len([(lambda n,m,g,i:0 if abs(n-(g[-1]*g[-1]))<=m else(g.__setitem__(0,g[0]+(g[1]-g[0])/2)if n-(g[-1]*g[-1])>0 else g.__setitem__(1,g[1]-(g[1]-g[0])/2))or g.__setitem__(-1,(g[1]+g[0])/2)or i.append(0))(n,m,g,i)for _ in zip(i)])*0+g[-1])(abs(n),0.000000000001*n,(lambda n,g,i:[(lambda n,g,i:(g[1]*g[1]<n)and(i.append(0)or g.__setitem__(0,g[1])or g.__setitem__(1,g[1]*2)or g.__setitem__(2,(g[0]+g[1])/2)))(n,g,i)for _ in zip(i)]*0+g)(abs(n),[0,1,.5],[0]),[0]))
print(sqrt(3))
@uncut bolt :white_check_mark: Your eval job has completed with return code 0.
1.7320508075681573
fixed edge case where 3 would be an infinite loop
!e
sqrt=lambda n:((lambda n,m,g,i:len([(lambda n,m,g,i:0 if abs(n-(g[-1]*g[-1]))<=m else(g.__setitem__(0,g[0]+(g[1]-g[0])/2)if n-(g[-1]*g[-1])>0 else g.__setitem__(1,g[1]-(g[1]-g[0])/2))or g.__setitem__(-1,(g[1]+g[0])/2)or i.append(0))(n,m,g,i)for _ in zip(i)])*0+g[-1])(abs(n),n/1e12,(lambda n,g,i:[(lambda n,g,i:(g[1]*g[1]<n)and(i.append(0)or g.__setitem__(0,g[1])or g.__setitem__(1,g[1]*2)or g.__setitem__(2,(g[0]+g[1])/2)))(n,g,i)for _ in zip(i)]*0+g)(abs(n),[0,1,.5],[0]),[0]))
print(sqrt(1))
@uncut bolt :white_check_mark: Your eval job has completed with return code 0.
0.9999999999995453
Shortened the 0.000000000001
(lambda n,g,i:(g[1]*g[1]<n)and(i.append(0)or g.__setitem__(0,g[1])or g.__setitem__(1,g[1]*2)or g.__setitem__(2,(g[0]+g[1])/2))) == (lambda n,g,i:((k:=g[1])*k<n)and(i.append(0)or g.__setitem__(slice(0,3),[k,k*2,k])))
!e ```py
sqrt=lambda n:((lambda n,m,g,i:len([(lambda n,m,g,i:0 if abs(n-(g[-1]*g[-1]))<=m else(g.setitem(0,g[0]+(g[1]-g[0])/2)if n-(g[-1]*g[-1])>0 else g.setitem(1,g[1]-(g[1]-g[0])/2))or g.setitem(-1,(g[1]+g[0])/2)or i.append(0))(n,m,g,i)for _ in zip(i)])*0+g[-1])(abs(n),n/1e12,(lambda n,g,i:[(lambda n,g,i:((k:=g[1])k<n)and(i.append(0)or g.setitem(slice(0,3),[k,k2,k])))(n,g,i)for _ in zip(i)]*0+g)(abs(n),[0,1,.5],[0]),[0]))
print(sqrt(1))
print(sqrt(3))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 0.9999999999995453
002 | 1.7320508075681573
i like the *0+g tricks that you do
thanks
TIL := existed
only for 3.8+ though
!e ```py
sqrt=lambda n:((lambda n,m,g,i:len([(lambda n,m,g,i:abs(t:=n-(g[-1]*g[-1]))>m and(g.setitem(t<=0,(g[0]+g[1])/2)or g.setitem(-1,(g[1]+g[0])/2)or i.append(0)))(n,m,g,i)for _ in zip(i)])*0+g[-1])(abs(n),n/1e12,(lambda n,g,i:[(lambda n,g,i:((k:=g[1])k<n)and(i.append(0)or g.setitem(slice(0,3),[k,k2,k])))(n,g,i)for _ in zip(i)]*0+g)(abs(n),[0,1,.5],[0]),[0]))
print(sqrt(1))
print(sqrt(3))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 0.9999999999995453
002 | 1.7320508075681573
shortened even more by replacing py 0 if abs(n-(g[-1]*g[-1]))<=m else(g.__setitem__(0,g[0]+(g[1]-g[0])/2)if n-(g[-1]*g[-1])>0 else g.__setitem__(1,g[1]-(g[1]-g[0])/2))or g.__setitem__(-1,(g[1]+g[0])/2)or i.append(0) with ```py
abs(t:=n-(g[-1]*g[-1]))>m and(g.setitem(t<=0,(g[0]+g[1])/2)or g.setitem(-1,(g[1]+g[0])/2)or i.append(0))
!e shortened ten characters ```py
sqrt=lambda n:(lambda n,m,g,i:len([(lambda n,m,g,i:abs(t:=n-(g[-1]*g[-1]))>m and(g.setitem(t<=0,(g[0]+g[1])/2)or g.setitem(-1,(g[1]+g[0])/2)or i.append(0)))(n,m,g,i)for _ in zip(i)])*0+g[-1])(a:=abs(n),n/1e12,(lambda n,g,i:[(lambda n,g,i:((k:=g[1])k<n)and(i.append(0)or g.setitem(slice(0,3),[k,k2,k])))(n,g,i)for _ in zip(i)]*0+g)(a,[0,1,.5],[0]),[0])
print(sqrt(1))
print(sqrt(3))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 0.9999999999995453
002 | 1.7320508075681573
๐คฏ epic
with using maps it can be shortened to 359 chars
!e ```py
sqrt=lambda n:(lambda n,m,g,i:len([map((lambda n,m,g,i:abs(t:=n-(g[-1]*g[-1]))>m and(g.setitem(t<=0,(g[0]+g[1])/2)or g.setitem(-1,(g[1]+g[0])/2)or i.append(0)))(n,m,g,i),zip(i))])*0+g[-1])(a:=abs(n),n/1e12,(lambda n,g,i:[map((lambda n,g,i:((k:=g[1])k<n)and(i.append(0)or g.setitem(slice(0,3),[k,k2,k])))(n,g,i),zip(i))]*0+g)(a,[0,1,.5],[0]),[0])
print(sqrt(1))
print(sqrt(3))```
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | 0.75
002 | 1.75
but ye
!e Different method, but still kinda cool:
sqrt=lambda n:(f:=lambda x:(x+n/x)/2)(f(f(f(n/2))))
print(f"{sqrt(9) = }")
print(f"{sqrt(3) = }")
@prisma coral :white_check_mark: Your eval job has completed with return code 0.
001 | sqrt(9) = 3.0000000000393214
002 | sqrt(3) = 1.7320508075688772
!e
collatz=lambda n:(i:=[n],[*iter(lambda:(y:=i[-1],i.append((y//2,3*y+1)[y%2]),i[-1])[-1],1)],i)[-1]
print(collatz(7))```
@runic mirage :white_check_mark: Your eval job has completed with return code 0.
[7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
Lol wtf this stuff is definitely esoteric
Hope job interviews don't ask me how to do this stuff
I did a little more work on my thing
The API ended up surprisingly thorough
@literal(int, str)
def foo(self): ...
@literals(int, str)
class Foos:
def foo(self): ...
@rename("bar")
def bartholomew(self): ...
with literally(int, str, name="foo", fn=...):
...
Three different ways to hook
inspired in some ways by the forbiddenfruit and fishhook APIs
Oh, I just tweaked the context manager so the API is even smoother
I'm thinking that this might be an interesting API:
with int.literally(unix=datetime.fromtimestamp):
...
Or maybe even
with literally(datetime.fromtimestamp) as int.unix:
...
Woah how does this work?
I've tried making something like this but my brain is too small

it's a context manager, it can overwrite functions on modules or even stuff like int and strings, and save the old functionality to later restore the original behavior
it's a neat idea but if you ever saw it in the wild you'd want to off yourself
Well I don't want to hook builtins outside of the explicit API, so the first isn't really feasible
Is the second a valid use of context managers? I'm surprised if it is
(plus this allows multiple targets & literals atm, so literally(int, float, minutes=..., seconds=...) is useable)
The second is valid syntactically but youโd have to hook attribute setting on builtins for it to work in practise
No job will ever need, or want this. In fact if you ever see anything close to this in real projects, run, because ur life depends on it
Collection types supported now
I guess that example would be even simpler with with literally(set, f=frozenset):
i thought this was just fishhook until i saw that it was something like a property
It also detects when it's used in a "non-literal" context and fails
x = {1, 2}
x.f # raises
(you can disable this with strict=False but why would you!!! bytecode analysis is so cool and not at all fragile)
does (x | y).f work
only load_const, build_list, build_map and build_set are allowed to be the last executed op when strict=True
and SET_UPDATE?
when's that called
>>> dis("assert {1,2,3,4}.f == frozenset({1, 2, 3, 4})")
1 0 BUILD_SET 0
2 LOAD_CONST 0 (frozenset({1, 2, 3, 4}))
4 SET_UPDATE 1 <<<<<<<<<<<<<<<<<<<<<<<<
6 LOAD_ATTR 0 (f)
8 LOAD_NAME 1 (frozenset)
10 BUILD_SET 0
12 LOAD_CONST 0 (frozenset({1, 2, 3, 4}))
14 SET_UPDATE 1
16 CALL_FUNCTION 1
18 COMPARE_OP 2 (==)
20 POP_JUMP_IF_TRUE 13 (to 26)
22 LOAD_ASSERTION_ERROR
24 RAISE_VARARGS 1
>> 26 LOAD_CONST 1 (None)
28 RETURN_VALUE
also i think SET_UPDATE only works with constant sets
righty
I might make strict=False the default
because bytecode is not immune to breaking changes
But a bit of version specific code may be in order
i think based on the features you just told me i could whip up a simple DIY with fishhook ```py
from fishhook import hook
from opcode import opmap
@hook(set, name="f")
@property
def f(self):
frame = import('sys')._getframe(1)
if frame.f_code.co_code[frame.f_lasti-2] in {opmap['BUILD_SET'], opmap['SET_UPDATE']}:
return frozenset(self)
else:
raise RuntimeError("set is not constant")
assert {1,2,3,4}.f == frozenset({1, 2, 3, 4})
Will property work on NoneType?
I think a raw descriptor is required here
(specifically, hasattr(type(None), "foo") may call None.foo in an undesirable way)
@earnest wing did you end up using fishhook or did you write your own hook lib?
>>> class b:
... def __init__(s, *a):s.a = a
... def __enter__(s): return s.a
... def __exit__(*a):pass
...
>>> with b(1,2,3) as (a,b,c):pass
...
>>> a
1
>>> b
2
>>> c
3
>>> ``` you can unpack the result of a context manager's `__enter__` method
and then if you hooked object.__setattr__ so that if its passed a specific object as the value it does something special you could make with hook(func) as (int.a, float.b) (if i remember correctly you can return a custom iterator that can unpack an arbitrary amount)
!e ```py
import sys, dis
def mrange(start=0, step=1):
f = sys._getframe(1)
inst, oparg = f.f_code.co_code[f.f_lasti: f.f_lasti + 2]
if dis.opname[inst] != 'UNPACK_SEQUENCE':
raise RuntimeError('mrange cannot be used in this context')
yield from range(start, oparg, step)
x, y, z = mrange()
print(x,y,z)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
0 1 2
how to get and to be &&
Trying to obfuscate, mainly single or double characters for cars and functions, but: and or etc are required to have spaces and one & is bitwise
do you mean like a and b would be equivalent to a && b?
Sounds really interesting
sure, but try not to ping people without contributing to useful discussion
Oh sorry (forgot to disable the ping thing)
Did it again ๐คฃ
Sorry !
for _ in range(drop_number[i]):
s.pop(0)
oops
anyways
I have to pop the first entry in a list drop_number[i] times (yes, I have to use pop). The above way feels like it could use improvement, and I have to allocate memory to _ when I don't need it. Is there anyway to do this in less code?
besides the obvious moving the pop up to the same line
Can I pop a range?
Actually, I don't have to use pop, but I do have to modify the array directly, no assignment
that's an interesting option, too! I think the current approach works well enough, but if I'm feeling spicy I could hook attributes on module load. Lol
For non-special-slotted attributes, is there a difference between fishhook and forbiddenfruit hooking?
my goal when i wrote fishhook was to do all the func pointer math dynamically so that if new special methods were added the lib would still work. There are a few other small differences (fishhook can handle exceptions)
yea
the lib i've been working on since goes a step further and just makes python think that the builtin types are modify-able like normal types
so that stuff like ```py
int.a = 1
print((1).a == 1) # True
ooo
!e ```py
3.10+ only
from ctypes import c_char
BYTES_HEADER = bytes.basicsize - 1
Py_TPFLAGS_IMMUTABLETYPE = 1 << 8
def sizeof(obj):
return type(obj).sizeof(obj)
def getmem(addr, size, fmt):
return memoryview((c_char*size).from_address(addr)).cast('c').cast(fmt)
def alloc(size, _storage=[]):
_storage.append(bytes(size))
return id(_storage[-1]) + BYTES_HEADER
def get_structs(htc=type('',(),{'slots':()})):
htc_mem = getmem(id(htc), sizeof(htc), 'P')
last = None
for ptr, idx in sorted([(ptr, idx) for idx, ptr in enumerate(htc_mem)
if id(htc) < ptr < id(htc) + sizeof(htc)]):
if last:
offset, lp = last
yield offset, ptr - lp
last = idx, ptr
def allocate_structs(cls):
cls_mem = getmem(id(cls), sizeof(cls), 'P')
for offset, size in get_structs():
cls_mem[offset] = cls_mem[offset] or alloc(size)
for subcls in type(cls).subclasses(cls):
allocate_structs(subcls)
return cls_mem
def unlock(cls):
cls_mem = allocate_structs(cls)
flags = cls.flags
flag_offset = [*cls_mem].index(flags)
cls_mem[flag_offset] &= ~Py_TPFLAGS_IMMUTABLETYPE
def lock(cls):
cls_mem = allocate_structs(cls)
flags = cls.flags
flag_offset = [*cls_mem].index(flags)
cls_mem[flag_offset] |= Py_TPFLAGS_IMMUTABLETYPE
unlock(int)
int.getitem = lambda s,a:print(s, a)
1[0:1:2]```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:53: SyntaxWarning: 'int' object is not subscriptable; perhaps you missed a comma?
002 | 1 slice(0, 1, 2)
@earnest wing this is what i have rn, its 3.10+ only as it uses a new type flag
(note that i haven't gone through fully to ensure that leaving a builtin type unlocked doesn't crash)
also it hasnt been well tested
Oh that's good to know, it's handled on a flag basis
i believe that flag was added so that extension developers could allow users to add new attributes without needing to allocated their types on the heap
it used to be that you needed Py_TPFLAGS_HEAPTYPE to be set in order to write attributes but that changed in 3.10
@earnest wing slight modification to allocate_structs
def allocate_structs(cls):
cls_mem = getmem(id(cls), sizeof(cls), 'P')
for subcls in type(cls).__subclasses__(cls):
allocate_structs(subcls)
for offset, size in get_structs():
cls_mem[offset] = cls_mem[offset] or alloc(size)
return cls_mem```
needed to allocate structs in reverse to prevent the subclasses trying to read from cls as structs are being allocated
i actually think that may be a bug that fishhook has as well
Iโve been wanting to get into making an esolang for a while does anyone have a good tutorial or place to start?
Is there a place to read about the developer decisions for python, not an RFC, but in more of a guided/blog style? "We tried this, thought it was ok, then we did this, result was X, put it into next release"
I guess, an "over the shoulder" view of a python core dev
do you mean the mailing lists
Forgot about those. ty
!e
nice projects
dict, list = list, dict
https://github.com/RocketRace/custom-literals
I published my little evil thing :>
bitwise and should work
Nice idea!
Thank you! c:
@timber grotto :white_check_mark: Your eval job has completed with return code 0.
hello world
now that the project is open source we find out it relies on forbiddenfruit
!timeit ```py
from fishhook import hook
from opcode import opmap
@hook(set, name="f")
@property
def f(self):
frame = import('sys')._getframe(1)
if frame.f_code.co_code[frame.f_lasti-2] in {opmap['BUILD_SET'], opmap['SET_UPDATE']}:
return frozenset(self)
else:
raise RuntimeError("set is not constant")
```py
{1,2,3,4}.f
@quartz wave :white_check_mark: Your timeit job has completed with return code 0.
100000 loops, best of 5: 2.03 usec per loop
!timeit
frozenset({1,2,3,4})
@quartz wave :white_check_mark: Your timeit job has completed with return code 0.
1000000 loops, best of 5: 253 nsec per loop
how do we make custom property attributes faster ๐ค
hey python has JUMP_BACKWARD now in the most recent version in the repo
you could already jump backwards, just had to overflow the index lmao
!e ```py
from fishhook import hook
@hook(str)
def add(self, x):
return f"{self}{x!s}"
print("hello" + 5, "hello" + [1,2,3], "hello"+type)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
hello5 hello[1, 2, 3] hello<class 'type'>
you didn't need complex forbiddenfruit stuff
dang
hey wait so
can it do globals?
like all itters for example
wdym "all itters"
from forbiddenfruit import curse as mutate
mutate(int, '__iter__', lambda s: iter(range(s)))
mutate(str, '__add__', lambda a, b: str.__add__(a, str(b)))
for t in {map, filter, range, list, tuple, frozenset, set, dict, bytes, bytearray}:
mutate(t, 'list', lambda s: list(s))
mutate(t, 'len', lambda s: len(s))
cuz i got this
does fishhook do it easier/faster or anytthing
ah i can't hook into like type and have it effect everything dang
which makes sense
it's kind of the same but you can hook all dunders of any type
im working on a lib where you can hook object
oh yea i had to find a fork of cursed
hmu when u get that working
ill prob switch to fishhook thanks
as soon as i fix the crash when you make a new class after hooking object lol
xd
hey wait
do you know how to like, statically analyze code
cuz in my xonsh i had to set up an intercept in it's compiler to add my easy lambda thing ฮป(x + 2)
is there some generic way I could, say import some module and that allows you to create functions who can take in arbatary code as args that doesn't get evaluates
so I can do AST stuff to it
isn't that any function
or are you talking about trying to do this ```py
a(from thing import *)
yea i suppose
so like a func call like this f(a + b) would call f_handler(ast.parse('a + b'))
but like i can't make some def a(): where i can do a(x) without x existing
you can't do that sadly
ya
basically
not without major mods
dang
it would still need to parse
yea stuff like that can be tricky
so i got maps ฮปt, filters ฮปf, and sorts ฮปs
(ฮปt(x ** 3) | ฮปf(x > 0) | ฮปs(x))(range(10, -10, -1))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
which is neat, you can make composit lambdas and stuff
that is neat
thanks
im kinda hooked on python mods now lol
from fishhook import hook as mutate
mutate(int, name='__iter__')(lambda s: iter(range(s)))
mutate(str, name='__add__' )(lambda a, b: a + str(b))
for t in {map, filter, range, list, tuple, frozenset, set, dict, bytes, bytearray}:
mutate(t, name='list')(lambda s: list(s))
mutate(t, name='len' )(lambda s: len(s))
@rugged sparrow rate my macros lol
10/10
working on it
hooking object.__iter__ should do it
but i need to get that stable first
found why it crashes, object->tp_base is null (for some reason)
so object->tp_base has to be null inorder for base resolution to work
but object->tp_base is used without being checked in places that python assumes object will never be (and it crashes there)
i might be able to make a fake object class and set that as object->tp_base
!e ```py
from ctypes import c_char
BYTES_HEADER = bytes.basicsize - 1
Py_TPFLAGS_IMMUTABLETYPE = 1 << 8
def sizeof(obj):
return type(obj).sizeof(obj)
def getmem(addr, size, fmt):
return memoryview((c_char*size).from_address(addr)).cast('c').cast(fmt)
def alloc(size, _storage=[]):
_storage.append(bytes(size))
return id(_storage[-1]) + BYTES_HEADER
def get_structs(htc=type('',(),{'slots':()})):
htc_mem = getmem(id(htc), sizeof(htc), 'P')
last = None
for ptr, idx in sorted([(ptr, idx) for idx, ptr in enumerate(htc_mem)
if id(htc) < ptr < id(htc) + sizeof(htc)]):
if last:
offset, lp = last
yield offset, ptr - lp
last = idx, ptr
def allocate_structs(cls):
cls_mem = getmem(id(cls), sizeof(cls), 'P')
for subcls in type(cls).subclasses(cls):
allocate_structs(subcls)
for offset, size in get_structs():
cls_mem[offset] = cls_mem[offset] or alloc(size)
return cls_mem
def unlock(cls):
cls_mem = allocate_structs(cls)
flags = cls.flags
flag_offset = [*cls_mem].index(flags)
cls_mem[flag_offset] &= ~Py_TPFLAGS_IMMUTABLETYPE
def lock(cls):
cls_mem = allocate_structs(cls)
flags = cls.flags
flag_offset = [*cls_mem].index(flags)
cls_mem[flag_offset] |= Py_TPFLAGS_IMMUTABLETYPE
def patch_object():
# adds extra fake object class to inheritance chain so that object can be modified safely
obj_mem = getmem(id(object), sizeof(object), 'P')
fake_obj_mem = alloc(sizeof(object))
getmem(fake_obj_mem, sizeof(object), 'B')[:] = obj_mem.tobytes()
tp_base_offset = [*getmem(id(type('',(),{})), sizeof(object), 'P')].index(id(object))
obj_mem[tp_base_offset] = fake_obj_mem
needed to allow for unlock(object) to be stable
patch_object()
unlock(object)
object.iter = lambda s:(yield s)
print(*1)
print(*type)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | <class 'type'>
got it working, still need to test to ensure its stable but i think it should work
@earnest wing ^ got unlock(cls) working
3.10+ only tho
nice
now i can do some crazy stuff
im gonna make a small edit so that you can call lock on your own classes properly one sec
!e ```py
from ctypes import c_char
BYTES_HEADER = bytes.basicsize - 1
Py_TPFLAGS_IMMUTABLETYPE = 1 << 8
def sizeof(obj):
return type(obj).sizeof(obj)
def getmem(addr, size, fmt):
return memoryview((c_char*size).from_address(addr)).cast('c').cast(fmt)
def alloc(size, _storage=[]):
_storage.append(bytes(size))
return id(_storage[-1]) + BYTES_HEADER
def get_structs(htc=type('',(),{'slots':()})):
htc_mem = getmem(id(htc), sizeof(htc), 'P')
last = None
for ptr, idx in sorted([(ptr, idx) for idx, ptr in enumerate(htc_mem)
if id(htc) < ptr < id(htc) + sizeof(htc)]):
if last:
offset, lp = last
yield offset, ptr - lp
last = idx, ptr
def allocate_structs(cls):
cls_mem = getmem(id(cls), sizeof(cls), 'P')
for subcls in type(cls).subclasses(cls):
allocate_structs(subcls)
for offset, size in get_structs():
cls_mem[offset] = cls_mem[offset] or alloc(size)
return cls_mem
def unlock(cls):
cls_mem = allocate_structs(cls)
flags = cls.flags
flag_offset = [*cls_mem].index(flags)
cls_mem[flag_offset] &= ~Py_TPFLAGS_IMMUTABLETYPE
def lock(cls):
cls_mem = getmem(id(cls), sizeof(cls), 'P')
flags = cls.flags
flag_offset = [*cls_mem].index(flags)
cls_mem[flag_offset] |= Py_TPFLAGS_IMMUTABLETYPE
def patch_object():
# adds extra fake object class to inheritance chain so that object can be modified safely
obj_mem = getmem(id(object), sizeof(object), 'P')
fake_obj_mem = alloc(sizeof(object))
getmem(fake_obj_mem, sizeof(object), 'B')[:] = obj_mem.tobytes()
tp_base_offset = [*getmem(id(type('',(),{})), sizeof(object), 'P')].index(id(object))
obj_mem[tp_base_offset] = fake_obj_mem
needed to allow for unlock(object) to be stable
patch_object()
class a:pass
lock(a)
a.b = 1 # fails```
@rugged sparrow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 60, in <module>
003 | TypeError: cannot set 'b' attribute of immutable type 'a'
now lock only changes the flags on the class passed in, and doesn't do any allocation stuff
yeah I tried fishhook but the API was not really what I needed here
at least, hook(type, name)(descriptor) didn't pass the tests and forbiddenfruit worked
I suppose I didn't really try though since curse did exactly what I wanted already lol
I could try to reimplement fishhook as one of the backends
@rugged sparrow I think I know why I had trouble, fishhook internally applies hooked attributes to a new type(f"{id(cls)}", ...) on a fake inheritance chain, which breaks descriptors
so while I had been expecting "test".x to call str.__dict__["x"].__get__(<"test" depending on call type>, str), I get .__get__(<"test" or None>, <class 'fishhook.<id>'>)
because the "owner" of the descriptor isn't the hooked class
I'll try to work around this using @property if at all possible for now, but just so it's out there
because honestly the descriptor protocol is kind of fragile
(if it ends up being necessary for disambiguation though, too bad for me I guess)
I'll try to add your lock/unlock as an optional 3.10+ backend, though, since it seems the most stable
Hmm yeah... with @property, it's impossible to define custom literals on None...
I think the original descriptor approach + mro climbing is the way to go
... yeah no I think only the way forbiddenfruit hooks its attributes works here
the fake inheritance does not play nice with descriptors
https://github.com/RocketRace/custom-literals#how-please-keep-it-short A little writeup available now, for those interested
Yea fishhook needs some changes to that inheritance thing
I am gonns be kicked off this server if I post my code anywhere but here
def auto_reload_start(bot):
import watchdog.observers, watchdog.events
from pathlib import Path
from importlib.machinery import all_suffixes
path_as_dotted = lambda path: list(
".".join(p.parts[:-1] + (p.name.removesuffix(s),))
for p in (
Path(path).relative_to(Path.cwd()),
)
for s in all_suffixes()
if p.name.endswith(s)
)
obs = watchdog.observers.Observer()
h = type(
"EvtHandler",
(watchdog.events.FileSystemEventHandler,),
{
"on_modified": lambda self, evt: bot.reload_extension(
path_as_dotted(evt.src_path)[0]
) if path_as_dotted(evt.src_path) else None
},
)()
obs.schedule(event_handler=h, path=Path.cwd() / "commands", recursive=True)
obs.start()
``` thinkimg whether I should use the Aoril 1 excuse for it existing... nah
this is awesome, thanks
btw do you plan to add it to fishhook?
why do i get this?
It needs more work first tbh
Ugh I've become obsessed with code golfing...
I really hope it doesn't affect my normal code lol
Whenever I want to debug something quickly I always end up writing golfed stuff by instinct, and sometimes that code stays in the final version
[x for y in z for x in y] This syntax is so damn %$%#$# in python, all detached from logic
https://ganer.xyz/s/c5cac70d71da1c24?e hyperoperations 1 liner
wrong channel, go to #bot-commands to speak to the void
https://stackoverflow.com/questions/932328/python-defining-my-own-operators
x=Infix(lambda x,y: x*y)
print 2 |x| 4
what is this "Infix" here, is it not in python3 ?
NameError: name 'Infix' is not defined
wot, where "ฮป" from
custom parsers I've added
Agreed. Should be reversed.
srs i've never touched that syntax
im aware of it but it just reads so bad
Among worst Python design decisions it's right up there with "def"
what is wrong with def?
list comps can have ifs, it's not that easy to reverse
honestly I wish c style ternary operators were in python, " ? :" is so much smaller than if else
no actually that reads fine
[x for x in y if f(x) for y in z if g(y)]
yeah, just skip the first expression and read it after the rest
what no that's how it's now
what makes even more sense is to just put the first expression last
so it reads how you just said without doing anything
here's how I always try and write it https://ganer.xyz/s/32d7867782d485e1?e
yeah
well you will stop doing that after you did it a lot
but it's natural that this is what you do
i just don't use that syntax lol
i know
it's lifted from haskell, but they dropped the commas
you could put the commas back
[for y in z, if g(y), for x in y: x]
Would just seperate the ifs naturally: [x for x in y if x==3 for y in z if y.something]
For some reason, when I do d[i] in this list comprehension, it says i is undefined. Why is this? Am I missing something?
[s.remove(sorted(s)[j]) for j in range(d[i]) for i, s in enumerate(l)]
Swap the for parts..
oh my god
im too tired rn
Trying to get this expression onto the same line as the definition, but the problem is it starts with for. Any way around this?
def increment_attendance(s, l):
for (x, y) in l: s[x][y] += 1
you could use lambda
How so? I tried lambda and ran into the same issue
show what u tried
increment_attendance = lambda s, l: for (x, y) in l: s[x][y] += 1
apparently my for statement is not a proper expression
also, what would the lambda function return?
This function just acts on an object
It doesn't return anything
lambda has to return something iirc
This could work, the deque is for consuming the generator
from collections import deque
f = lambda s, l: deque((s[x][y].__iadd__(1) for x, y in l), maxlen=0)```
I tried __add__ earlier, what's __iadd__?
it's the method which gets called when you do +=
ah
that's what I wanted
I needed a method to act on the int in order to do the list comprehension
add wasn't working
thanks
Ill try it
ugh
It's not modifying the entry
maaaaaan
dude this is killin me
it's the last possible line to eliminate
The problem is that s[x][y] is an int object and not a pointer to a list entry
oh, so it doesn't change the list?
oh alright
f = lambda s, l: deque((s[x].__setitem__(y, s[x][y] + 1) for x, y in l), maxlen=0)```
I hope this equivalent to s[x][y] = s[x][y] + 1
It works, but now I do face another problem
just checked and std library only...
frick
whoops
increment_attendance=lambda s,l:[0for x,y in l if s[x].__setitem__(y,s[x][y]+1)]
increment_attendance=lambda s,l:[s[x].__setitem__(y,s[x][y]+1) for x,y in l]
``` final result
wait, gotta remove the spaces
yeah, it's fine probably
this is an intro level python class and I'm just trying to have some fun with the assignments
I'm not turning them in like this lol
but people in that class are writing far less efficient code than that
I did every function in one line
increment_attendance=lambda s,l:[s[x].__setitem__(y,s[x][y]+1) for x,y in l]
drop_lowest=lambda l,d:[s.remove(n[j])for i,s in enumerate(l) if (n:=sorted(s)) for j in range(d[i])]
organize_grades=lambda g,a,m:{s:[g[i]/m[i] for i in range(len(g)) if a[i]==s] for s in ["zy","lab","pa","mid1","mid2","final"]}
gbook_averages=lambda g:{k:sum(v)/len(v) if len(v)>0 else 0 for (k,v) in g.items()}
course_grade=lambda g,w,r:sum([w[k]*g[s if k in r.values() and g[k]<g[(s:=dict(map(reversed,r.items()))[k])] else k] for k in g.keys()])
just for aesthetic
make them esoteric
I'm not super familiar with the esoteric lingo
!e ```py
=lambda ,:(()for ____ in range(getattr(,'len',)));print((lambda ,:(,))('0',(list,['0','1'])))
@velvet plank :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 | TypeError: 'method-wrapper' object cannot be interpreted as an integer
!e ```py
print((lambda ,:(lambda ,:(()for ____ in range(getattr(,'len',))))(,))('0',(lambda ,:(()for ____ in range(getattr(,'len',))))(list,['0','1'])))
@velvet plank :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 | TypeError: 'method-wrapper' object cannot be interpreted as an integer
!e ```py
print((lambda ,:(lambda ,:(()for ____ in range(getattr(,'len',lambda:)())))(,))('0',(lambda ,:(()for ____ in range(getattr(,'len',lambda:)())))(list,['0','1'])))
@velvet plank :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 | TypeError: 'generator' object cannot be interpreted as an integer
WHAT
This your brain on drugs
Hey @split salmon!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
!e py
?
!e
#Trying To Understand 'if' Statements Better
user = input("User:")
useraccount = "User" or "Username"
if user == useraccount:
print("Hello "+user+"!" "\nWelcome!")
else:
print("User Not Found.\nTry Re-entering Your Name")
@kind token :x: Your eval job has completed with return code 1.
001 | User:Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | EOFError: EOF when reading a line
print(chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.10256410256410256))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.5544554455445545))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.06779661016949153))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07920792079207921))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07017543859649122))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.7887323943661971))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07207207207207207))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07272727272727272))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.509090909090909))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.08247422680412371))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.11267605633802817))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.0761904761904762))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.06779661016949153))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07920792079207921))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/1.75))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.0898876404494382))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.5045045045045045))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.47863247863247865))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.25))+chr(round(....__class__.__class__.__sizeof__.__sizeof__()/0.6588235294117647))+chr(round(int(chr(....__class__.__class__.__sizeof__.__sizeof__()))/0.07142857142857142)))โ```
Never Gonna Give You Up
got a problem with it?
non printable character
AttributeError: module 'pip' has no attribute '_internal'
im using python 3.10.4 and pip 22.0.4
mh
!e ```py
print((lambda ,:(lambda ,:[()for()in(range)(getattr(,'len',lambda:)())])(,))(print,(lambda ,:[()for()in(range)(getattr(,'len',lambda:)())])(lambda :(print('Output:',) or print and (lambda :print('Output:',))),[[0],[1]])))
@velvet plank :white_check_mark: Your eval job has completed with return code 0.
001 | Output: 0
002 | Output: 1
003 | 0
004 | 1
005 | [None, None]
zamn
k
(fixing it)
that will give you warnings
__import__("pip._internal.cli.main")._internal.cli.main.main(['install', 'package'])
@lusty sinew try with this
__import__('pip._internal.cli.main', fromlist='main').main(['install', 'module'])
__import__("pip._internal.cli.main", fromlist=1).main(["show"])
ok yeah
When you tell your class discord that you did every method for the assignment in one line and they all say cap, but sharing code will get me banned so I canโt even back it up :(
!e
from fishhook import hook
@hook(slice)
def __hash__(self):
return hash((self.start, self.stop, self.step))
d = {}
d[::-1] = "reversed"
print(d[::-1])
@languid hare :white_check_mark: Your eval job has completed with return code 0.
reversed
flosh
this is esoteric enouf? can i join the club?
I especially like: getattr(___,'__len__',lambda:___)()
The idea intrigues me that it might actually be more efficient than just a call to len(), it might depend more on the time it takes to create and store the lambda. Sadly I don't have time to test this out right now.
!e
from typing import TypeVar, Type, ClassVar, Union, Dict, Tuple
def wrap_with_template_args(wrapped, items):
def wrap(cls):
template_arg_str = '[' + \
', '.join(getattr(i, '__name__', str(i)) for i in items) + ']'
cls.__name__ = wrapped.__name__ + template_arg_str
cls.__qualname__ = wrapped.__qualname__ + template_arg_str
cls.__doc__ = wrapped.__doc__
return cls
return wrap
class Template:
_params: ClassVar[Dict[TypeVar, Type]]
def __class_getitem__(cls, item: Union[TypeVar, Tuple[TypeVar]]) -> Type:
if not isinstance(item, tuple):
item = (item,)
@wrap_with_template_args(cls, item)
class _Template:
def __class_getitem__(
cls_, item_: Union[Type, Tuple[Type]]) -> Type:
if not isinstance(item_, tuple):
item_ = (item_,)
@wrap_with_template_args(cls_, item_)
class _TemplateInstance(cls_):
__class_getitem__ = None # disable multiple subscripting
_params = dict(zip(item, item_))
return _TemplateInstance
return _Template
if __name__ == '__main__':
T = TypeVar('T')
U = TypeVar('U')
class Test(Template[T, U]):
"""
This is a doc
"""
def __init__(self):
print("this is a template:", type(self).__name__
h = Test[int, int]()
print(h)
@near gust :white_check_mark: Your eval job has completed with return code 0.
001 | this is a template: Test[int, int]
002 | <__main__.Test[int, int] object at 0x7f66a12da620>
oops forgot to wrap into a main function
I love double nesting of classes
when you forget that typing.get_args() exists
how do I have decorator like things for primitive types
@required
x = 1
# or any other way to check if var (which cant have an attr) has attr
if x.required:
...
def req(var):
req.x[var.__name__] = 1
return var
req.x = {}
def check_if_var_is_required(var):
return var in req.x and req.x[var.__name__]
x = 1
x = req(x)
print(check_if_var_is_required(x))
y = 2
y = req(y)
print(check_if_var_is_required(y))
you can only decorate a function or class definition.
with the decorator syntax at least
how about
y = 2
y = req(y)
print(check_if_var_is_required(y))
!e
print(*map(chr, map(int, "72 97 114 117 32 68 101 115 117 32 89 111".split())), sep="")
@fair quartz :white_check_mark: Your eval job has completed with return code 0.
Haru Desu Yo
I see you found my status
!e
from typing import Generic, TypeVar, get_args, ClassVar, Tuple, Type
def wrap_template_args(wrapped, items):
def wrap(cls):
arg_str = '[' + ', '.join(i.__name__ for i in items) + ']'
cls.__name__ = wrapped.__name__ + arg_str
cls.__qualname__ = wrapped.__qualname__ + arg_str
cls.__doc__ = wrapped.__doc__
return cls
return wrap
def template(*args):
def wrap(cls):
gen = Generic[tuple(TypeVar("") for i in args)]
class _Template(cls, gen):
def __class_getitem__(_cls, item):
o = super().__class_getitem__(item)
template_args = get_args(o)
@wrap_template_args(_cls, template_args)
class __Template(o):
# expose __args__ to the class
__args__: ClassVar[Tuple[Type]] = template_args
# also expose the template parameters as a dict
_params = dict(zip(args, template_args))
return __Template
_Template.__name__ = cls.__name__
_Template.__qualname__ = cls.__qualname__
_Template.__doc__ = cls.__doc__
return _Template
return wrap
if __name__ == '__main__':
@template('T', 'U')
class H:
def __init__(self):
print("I'm a template with args:", self._params)
print(H[int, str]())
@near gust :white_check_mark: Your eval job has completed with return code 0.
001 | I'm a template with args: {'T': <class 'int'>, 'U': <class 'str'>}
002 | <__main__.H[int, str] object at 0x7fb504f9ae60>
not sure if static type checkers would like this ยฏ\_(ใ)_/ยฏ
!e
print(bytes(map(int, "72 97 114 117 32 68 101 115 117 32 89 111".split())))โ
@near gust :white_check_mark: Your eval job has completed with return code 0.
b'Haru Desu Yo'
!e
print(bytes((sum(range((-~True + True) * ~True * ~True)) + sum(range(~True * ~True)), sum(range(-~True * (~True * ~True -~True + True))) - (-~True + True) * ~True, sum(range((~True) ** (-~True) ** (-~True))) - (-~True + True) * -~True, sum(range(True - True, sum(range(-~True * -~True + True + -~True * -~True)) - sum(range(True - ~True)) - True, -~True * -~True + True)) + sum(range(-~True * -~True + True)) + sum(range(True - ~True)) - True, sum(range(-~True * -~True + True + -~True * -~True)) - sum(range(True - ~True)) - True, (sum(range(-~True * -~True + True + -~True * -~True)) - sum(range(True - ~True)) - True) * -~ True + ~True * ~True, sum(range((-~True * -~True + True + -~True * -~True) * -~True - True)) - sum(range(-~True * -~True + True + -~True * -~True)) + True, sum(range((-~True - ~True) * -~True, sum(range(True - ~True, sum(range(~True * ~True)) + True)))) - sum(range((-~True - ~True) * -~True + True, (-~True - ~True) * -~True - ~True)) - True, sum(range(sum(range(~True * ~True)) + True, sum(range(~True * ~True - ~True)) - ~True)) - ~True, sum(range(-~True * -~True + True + -~True * -~True)) - sum(range(True - ~True)) - True, sum(range((~True) ** (-~True) ** -~True + ~True)) + ~True, sum(range(~True * ~True + True, (~True) ** (-~True) ** -~True)) + True)).decode('utf' + str((-~True) ** (True - ~True))))
@near gust :white_check_mark: Your eval job has completed with return code 0.
Haru Desu Yo
same
ive written random mathematical expression generator to write such thing and when trying to match 100:
>>> rand(100) '(((((100)))))' >>> rand(100) '(((99) / ((33)))) + ((((97))))' >>> rand(100) '(((((((((100)))))))))' >>> rand(100) '((((100))))' >>>```
lmao
Java-level boilerplate lol
class Program_Class():
def __init__(self):
return
def main(self):
print("hello world")
Program = Program_Class()
if __name__=="__main__":
Program.main()
I should write a useless library for custom generics that don't only have type parameters
basically you can do stuff like
Generic[T, int]
and then
Foo[int, 0]
and then you can get weird stuff like
Foo[int, {'foo': 'bar', {'bar': 'foo'}}]
so that's why they don't exist in the standard library
!e autogenerated py print(bytes((lambda*x:[int(_)for(_)in(x)])(((((93)+(57))-39-(59)+((((60/3)))))),(((((98)+((3)))))),(((((29))))+(((79)))),(((((27)+(65)/5+((68)))))),(((((97)-16+30)))),((((11+(33))))),((((32)))),(((((87))))),(((((45+66))))),((((36+78)))),((((((((61))+(47))))))),((((((79)+((21))))))),((((((55)-71+49))))))))
@sly root :white_check_mark: Your eval job has completed with return code 0.
b'Hello, World!'
!e this was generating 2 minutes
print(bytes((lambda*x:[int(_)for(_)in(x)])((((((((3*4)))/(((2)/4/((3))*1)))))),((((((3)-(4-2-5/5))*((1)+((5))))+((5)*4)+5*1*1-4+(4)-2-5-((2)-(3)*4)*5+1+((4))*(5)))),(((((1)*5/((5)/(4)))+(2)/((1))))-((((3)/(4)+5*(3)*(5)/5+((3/2/2)*(2)-(1)/4)))/(3*5-(1+4*4))*(1)*(3*4))),(((((5+4*1-3+(((3)))+5-1*5/(1+4)))+2-4-5-(5)-3+((1+4*(1))*3*4-3-((3))*((2))+4)*(((2)))))),(((((4+(5*(4)+(4))))+1/2/2*2*(1)-((3))/(((4))))*((((4)))))),(((((3*(3+5)+1+(4+1/1)+((5))+(1)))+(((4)))+((4/1))))),((((((4))-2-2*2)-(((((5)))+1)))))-(((2+(2)/(2)*4*2*((1)/(4/3))*((3)/(3-2)))-((((4)*(5*3)))))),((((4)))/3/(2)-2*5-2/3*(3)*(2*5)+((4-(1)))-(((4)+1/1))+(((((1*(2)*2)))))+(((3)/2))-(((5)))-(((1)+5))/2+((2))*((5)+4)+((3))-1/3*1/((2))+1/((1))*((1+1*3))+(((5+(1))*((5))*((4))-(1)-4*5-2-4+(3)/1))),((((((3)*(3*(4*3))+((1)+((1))/1)-((2)-(1+(2)))))))),(((((4))+5*(2)*(5)/(1)*(5))))-((((3+5*3)+4+5*4/(1)*((2/2+5)))+((1)-(3)))),(((1+(5)-(((3)/3)/((2))))+(3+((3))/2)+((4*3+2+(5))-((((4)))))*((3*(1))*2/1+3*1/1/2/5*4)-(((2)+(((4+(4)))))/(1)))),((((((5*((2))*2)))*((((4)))+(5)-4)))),(((2*(3)*(((2)*1))+(((5*5/3))))))+((((2)-4*2+2+4+(1)-5*(4))))/(((1*((1))+(3+(1)*3)*3))/((3)/((4)))/(2)-(4/5+((3)))+(((4/5*3-4-5)))/(3-(4-3-3+5*2+2-5*5))-(((4)*(2)+(2)+1))-2/(1-(5)-(3)+2*1+4)-(5)+4))))```
@sly root :white_check_mark: Your eval job has completed with return code 0.
b'Hello, World!'
I did something similar a long time ago but it decomposed all the way down to unary so that it can create a string of a bunch of Trues combined in weird ways
in my thing I didn't use that program
I did it by hand
very big problem of this method it that it needs literally 5+ minutes to generate correct expressions
while True:
atom = str(RandomExpression(3))
try:
if eval(atom) == self.target:
return atom
except:
pass```
def enc(_0,_1=[]):
[_1.append(str(MatchRandomExpression(ord(_3))))for(_3)in _0]
return("print(bytes((lambda*x:[int(_)for(_)in(x)])(%s)))"%",".join(_1)).replace(" ","")```
this kills my python process
str(RandomExpression(3, ["<<", ">>"]))
Mine only did single values at first and could convert short strings in under a second because it used identities like i + 1 = -~i
i've just shrinked literals to 2 and expression blocks to 3
^C[1] 23785 killed python -i enc.py```
and it also used factorization
i have no idea where that program went
I originally made it for a code obfuscation contest
code obfuscation contest?
I made a single line parser and calculator
do they have a website or something?
my phone can't handle this lol
from random import *
class Expression: pass
class Number(Expression):
def __init__(self, num):
self.num = num
def __str__(self):
return str(self.num)
class BinaryExpression(Expression):
def __init__(self, left, op, right):
self.left = left
self.op = op
self.right = right
def __str__(self):
return str(self.left) + " " + self.op + " " + str(self.right)
class ParenthesizedExpression(Expression):
def __init__(self, exp):
self.exp = exp
def __str__(self):
return "(" + str(self.exp) + ")"
class RandomExpression:
def __init__(
self,
max_pieces: int = 2,
literals: list = ["-", "+", "*", "/"]
):
self.max_pieces = max_pieces
self.literals = literals
def __repr__(self):
if random() > self.max_pieces:
return str(Number(randint(1, 5)))
elif randint(0, 1) == 0:
return str(ParenthesizedExpression(
RandomExpression(self.max_pieces / 1.2, self.literals)
))
else:
return str(BinaryExpression(
RandomExpression(self.max_pieces / 1.2, self.literals),
choice(self.literals),
RandomExpression(self.max_pieces / 1.2, self.literals)
))
class MatchRandomExpression:
def __init__(self, target: int):
self.target = target
def __repr__(self):
while True:
atom = str(RandomExpression(3, ["<<", ">>"]))
try:
if eval(atom) == self.target:
return atom
except:
pass
def encode(_0, _1=[]):
[_1.append(str(MatchRandomExpression(ord(_3))))for(_3)in _0]
return("print(bytes((lambda*x:[int(_)for(_)in(x)])(%s)))"%",".join(_1)).replace(" ","")
print(encode("hello world"))```
it just keeps crashing
idk why because it uses less literals than before
well technically it wasn't an obfuscation contest, but about guessing who wrote what code, but a major part was obfuscation
!e what if.. ```py
from random import *
class Expression: pass
class Number(Expression):
def init(self, num):
self.num = num
def str(self):
return str(self.num)
class BinaryExpression(Expression):
def init(self, left, op, right):
self.left = left
self.op = op
self.right = right
def str(self):
return str(self.left) + " " + self.op + " " + str(self.right)
class ParenthesizedExpression(Expression):
def init(self, exp):
self.exp = exp
def str(self):
return "(" + str(self.exp) + ")"
class RandomExpression:
def init(
self,
max_pieces: int = 2,
literals: list = ["-", "+", "*", "/"]
):
self.max_pieces = max_pieces
self.literals = literals
def repr(self):
if random() > self.max_pieces:
return str(Number(randint(1, 5)))
elif randint(0, 1) == 0:
return str(ParenthesizedExpression(
RandomExpression(self.max_pieces / 1.2, self.literals)
))
else:
return str(BinaryExpression(
RandomExpression(self.max_pieces / 1.2, self.literals),
choice(self.literals),
RandomExpression(self.max_pieces / 1.2, self.literals)
))
class MatchRandomExpression:
def init(self, target: int):
self.target = target
def repr(self):
while True:
atom = str(RandomExpression(3, ["<<", ">>"]))
try:
if eval(atom) == self.target:
return atom
except:
pass
def encode(_0, _1=[]):
[_1.append(str(MatchRandomExpression(ord(_3))))for(3)in 0]
return("print(bytes((lambda*x:[int()for()in(x)])(%s)))"%",".join(_1)).replace(" ","")
print(encode("hello world"))```
@sly root :warning: Your eval job timed out or ran out of memory.
[No output]
where was it organised?
a discord server
i don't want to give any more information or else somebody might smite me
Have you guys ever tried golfing snake?
goodness that's a lot of unoptimized stuff
@quartz wave :x: Your eval job has completed with return code 1.
001 | File "<string>", line 39
002 | return f"{Number(randint(1, 5)))}"
003 | ^
004 | SyntaxError: f-string: unmatched ')'
@quartz wave :x: Your eval job has completed with return code 1.
001 | File "<string>", line 43
002 | return f"{BinaryExpression(self.subrandom, choice(self.literals), self.subrandom))}"
003 | ^
004 | SyntaxError: f-string: unmatched ')'
:incoming_envelope: :ok_hand: applied mute to @quartz wave until <t:1649120619:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 138 newlines in 10s).
!unmute 310263589913100288
:incoming_envelope: :ok_hand: pardoned infraction mute for @quartz wave.
why does the bot have to do that in #esoteric-python
It does it in all channels to prevent spam. The newlines rule gets accidentally triggered a lot when people post long blocks of code.
I recommend using the pastebin service.
Ah right ok. !eval is really more suited to running small snippets of code to demo a concept than whole scripts.
This is the one channel where people won't look at you funny for doing that ๐
!e ```py
from random import *
Expression=type('Expression',(),{})
Number=type('Number',(Expression,),{'init':lambda s,n:setattr(s,'num',n),'str':lambda s:f"{s.num}"})
BinaryExpression=type('BinaryExpression',(Expression,),{'init':lambda s,l,o,r:(setattr(s,'left',l),setattr(s,'op',o),setattr(s,'right',r))and None,'str':lambda s:f"{s.left}{s.op}{s.right}"})
ParenthesizedExpression=type('ParenthesizedExpression',(Expression,),{'init':lambda s,e:setattr(s,'exp',e),'str':lambda s:f"({s.exp})"})
class RandomExpression:
def init(self, max_pieces: int = 2, literals: list = ["-", "+", "*", "/"]):
self.max_pieces = max_pieces;self.literals = literals;self.subrandom = None
def str(self):
if random() > self.max_pieces: return f"{Number(randint(1, 5))}"
else:
if not self.subrandom: self.subrandom = RandomExpression(self.max_pieces / 1.2, self.literals)
return f"{BinaryExpression(self.subrandom, choice(self.literals), self.subrandom))}" if randint(0,1) else f"{ParenthesizedExpression(self.subrandom)}"
class MatchRandomExpression:
def init(self, target: int):
self.target = target;self.random = None
def str(self):
if not self.random: self.random = RandomExpression(3, ['<<', '>>'])
while True:
atom = f"{self.random}"
try:
if eval(atom) == self.target: return atom
except SyntaxError:
pass
def encode(_0, _1=[]):
_1.extend(map(lambda _3:f"{MatchRandomExpression(ord(3))}",0))
return f"print(bytes((lambda*x:[int()for()in(x)])({','.join(_1)})))"
print(encode("hello world"))
@quartz wave :x: Your eval job has completed with return code 1.
001 | File "<string>", line 13
002 | return f"{BinaryExpression(self.subrandom, choice(self.literals), self.subrandom))}" if randint(0,1) else f"{ParenthesizedExpression(self.subrandom)}"
003 | ^^
004 | SyntaxError: f-string: unmatched ')'
That is quite the monstrosity
!e ```py
from random import *
Expression=type('Expression',(),{})
Number=type('Number',(Expression,),{'init':lambda s,n:setattr(s,'num',n),'str':lambda s:f"{s.num}"})
BinaryExpression=type('BinaryExpression',(Expression,),{'init':lambda s,l,o,r:(setattr(s,'left',l),setattr(s,'op',o),setattr(s,'right',r))and None,'str':lambda s:f"{s.left}{s.op}{s.right}"})
ParenthesizedExpression=type('ParenthesizedExpression',(Expression,),{'init':lambda s,e:setattr(s,'exp',e),'str':lambda s:f"({s.exp})"})
class RandomExpression:
def init(self, max_pieces: int = 2, literals: list = ["-", "+", "*", "/"]):
self.max_pieces = max_pieces;self.literals = literals;self.subrandom = None
def str(self):
if random() > self.max_pieces: return f"{Number(randint(1, 5))}"
else:
if not self.subrandom: self.subrandom = RandomExpression(self.max_pieces / 1.2, self.literals)
return f"{BinaryExpression(self.subrandom, choice(self.literals), self.subrandom)}" if randint(0,1) else f"{ParenthesizedExpression(self.subrandom)}"
class MatchRandomExpression:
def init(self, target: int):
self.target = target;self.random = None
def str(self):
if not self.random: self.random = RandomExpression(3, ['<<', '>>'])
while True:
atom = f"{self.random}"
try:
if eval(atom) == self.target: return atom
except SyntaxError:
pass
def encode(_0, _1=[]):
_1.extend(map(lambda _3:f"{MatchRandomExpression(ord(3))}",0))
return f"print(bytes((lambda*x:[int()for()in(x)])({','.join(_1)})))"
print(encode("hello world"))
@quartz wave :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 31, in <module>
003 | File "<string>", line 28, in encode
004 | File "<string>", line 28, in <lambda>
005 | File "<string>", line 23, in __str__
006 | File "<string>", line 1, in <module>
007 | OverflowError: too many digits in integer
what
!e ```py
from random import *
Expression=type('Expression',(),{})
Number=type('Number',(Expression,),{'init':lambda s,n:setattr(s,'num',n),'str':lambda s:f"{s.num}"})
BinaryExpression=type('BinaryExpression',(Expression,),{'init':lambda s,l,o,r:(setattr(s,'left',l),setattr(s,'op',o),setattr(s,'right',r))and None,'str':lambda s:f"{s.left}{s.op}{s.right}"})
ParenthesizedExpression=type('ParenthesizedExpression',(Expression,),{'init':lambda s,e:setattr(s,'exp',e),'str':lambda s:f"({s.exp})"})
class RandomExpression:
def init(self, max_pieces: int = 2, literals: list = ["-", "+", "*", "/"]):
self.max_pieces = max_pieces;self.literals = literals;self.subrandom = None
def str(self):
if random() > self.max_pieces: return f"{Number(randint(1, 5))}"
else:
if not self.subrandom: self.subrandom = RandomExpression(self.max_pieces / 1.2, self.literals)
return f"{BinaryExpression(self.subrandom, choice(self.literals), self.subrandom)}" if randint(0,1) else f"{ParenthesizedExpression(self.subrandom)}"
class MatchRandomExpression:
def init(self, target: int):
self.target = target;self.random = None
def str(self):
if not self.random: self.random = RandomExpression(3, ['<<', '>>'])
while True:
atom = f"{self.random}"
try:
if eval(atom) == self.target: return atom
except SyntaxError:
pass
def encode(_0, _1=[]):
_1.extend(map(lambda _3:f"{MatchRandomExpression(ord(3))}",0))
return f"print(bytes((lambda*x:[int()for()in(x)])({','.join(_1)})))"
print(encode("a"))
@quartz wave :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 31, in <module>
003 | File "<string>", line 28, in encode
004 | File "<string>", line 28, in <lambda>
005 | File "<string>", line 23, in __str__
006 | File "<string>", line 1, in <module>
007 | OverflowError: too many digits in integer
!e ```py
from random import *
Expression=type('Expression',(),{})
Number=type('Number',(Expression,),{'init':lambda s,n:setattr(s,'num',n),'str':lambda s:f"{s.num}"})
BinaryExpression=type('BinaryExpression',(Expression,),{'init':lambda s,l,o,r:(setattr(s,'left',l),setattr(s,'op',o),setattr(s,'right',r))and None,'str':lambda s:f"{s.left}{s.op}{s.right}"})
ParenthesizedExpression=type('ParenthesizedExpression',(Expression,),{'init':lambda s,e:setattr(s,'exp',e),'str':lambda s:f"({s.exp})"})
class RandomExpression:
def init(self, max_pieces: int = 2, literals: list = ["-", "+", "", "/"]):
self.max_pieces = max_pieces;self.literals = literals;self.subrandom = None
def str(self):
if random() > self.max_pieces: return f"{Number(randint(1, 5))}"
else:
if not self.subrandom: self.subrandom = RandomExpression(self.max_pieces / 1.2, self.literals)
return f"{BinaryExpression(self.subrandom, choice(self.literals), self.subrandom)}" if randint(0,1) else f"{ParenthesizedExpression(self.subrandom)}"
class MatchRandomExpression:
def init(self, target: int):
self.target = target;self.random = None
def str(self):
if not self.random: self.random = RandomExpression(3, ['<<', '>>'])
while True:
atom = f"{self.random}"
try:
if eval(atom) == self.target: return atom
except SyntaxError:
pass
def encode(_0, _1=[]):
_1.extend(map(lambda _3:f"{MatchRandomExpression(ord(_3))}",_0))
return f"print(bytes((lambdax:[int()for()in(x)])({','.join(_1)})))"
print(encode("a"))
@quartz wave :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 28, in <module>
003 | File "<string>", line 26, in encode
004 | File "<string>", line 26, in <lambda>
005 | File "<string>", line 22, in __str__
006 | File "<string>", line 1, in <module>
007 | MemoryError
Is there a way to __import__() specific filenames, possibly named things other than *.py
Never mind, this works: ```py
def my_import (filename, globals=None, locals=None, fromlist=None):
with open(filename, 'r') as f:
filecontents = f.read()
if globals is None: globals = {}
if locals is None: locals = {}
exec(filecontents, globals, locals)
#print(globals, locals)
if not fromlist:
if '__all__' in locals:
fromlist = locals['__all__']
else:
fromlist = [member for member in locals
if member[0] != '_']
return {member: locals[member]
for member in fromlist}
change ["<<", ">>"] to ["+", "-", "*", "/"]
shifting takes more time and memory than normal expression
!e ```py
from random import *
Expression=type('Expression',(),{})
Number=type('Number',(Expression,),{'init':lambda s,n:setattr(s,'num',n),'str':lambda s:f"{s.num}"})
BinaryExpression=type('BinaryExpression',(Expression,),{'init':lambda s,l,o,r:(setattr(s,'left',l),setattr(s,'op',o),setattr(s,'right',r))and None,'str':lambda s:f"{s.left}{s.op}{s.right}"})
ParenthesizedExpression=type('ParenthesizedExpression',(Expression,),{'init':lambda s,e:setattr(s,'exp',e),'str':lambda s:f"({s.exp})"})
class RandomExpression:
def init(self, max_pieces: int = 2, literals: list = ["-", "+", "", "/"]):
self.max_pieces = max_pieces;self.literals = literals;self.subrandom = None
def str(self):
if random() > self.max_pieces: return f"{Number(randint(1, 5))}"
else:
if not self.subrandom: self.subrandom = RandomExpression(self.max_pieces / 1.2, self.literals)
return f"{BinaryExpression(self.subrandom, choice(self.literals), self.subrandom)}" if randint(0,1) else f"{ParenthesizedExpression(self.subrandom)}"
class MatchRandomExpression:
def init(self, target: int):
self.target = target;self.random = None
def str(self):
if not self.random: self.random = RandomExpression(3)
while True:
atom = f"{self.random}"
try:
if eval(atom) == self.target: return atom
except:
pass
def encode(_0, _1=[]):
_1.extend(map(lambda _3:f"{MatchRandomExpression(ord(_3))}",_0))
return f"print(bytes((lambdax:[int()for()in(x)])({','.join(_1)})))"
print(encode("a"))
@sly root :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 28, in <module>
003 | File "<string>", line 26, in encode
004 | File "<string>", line 26, in <lambda>
005 | File "<string>", line 22, in __str__
006 | File "<string>", line 1, in <module>
007 | ZeroDivisionError: float division by zero
oh
!e ```py
from random import *
Expression=type('Expression',(),{})
Number=type('Number',(Expression,),{'init':lambda s,n:setattr(s,'num',n),'str':lambda s:f"{s.num}"})
BinaryExpression=type('BinaryExpression',(Expression,),{'init':lambda s,l,o,r:(setattr(s,'left',l),setattr(s,'op',o),setattr(s,'right',r))and None,'str':lambda s:f"{s.left}{s.op}{s.right}"})
ParenthesizedExpression=type('ParenthesizedExpression',(Expression,),{'init':lambda s,e:setattr(s,'exp',e),'str':lambda s:f"({s.exp})"})
class RandomExpression:
def init(self, max_pieces: int = 2, literals: list = ["-", "+", "", "/"]):
self.max_pieces = max_pieces;self.literals = literals;self.subrandom = None
def str(self):
if random() > self.max_pieces: return f"{Number(randint(1, 5))}"
else:
if not self.subrandom: self.subrandom = RandomExpression(self.max_pieces / 1.2, self.literals)
return f"{BinaryExpression(self.subrandom, choice(self.literals), self.subrandom)}" if randint(0,1) else f"{ParenthesizedExpression(self.subrandom)}"
class MatchRandomExpression:
def init(self, target: int):
self.target = target;self.random = None
def str(self):
if not self.random: self.random = RandomExpression(3)
while True:
atom = f"{self.random}"
try:
if eval(atom) == self.target: return atom
except:
pass
def encode(_0, _1=[]):
_1.extend(map(lambda _3:f"{MatchRandomExpression(ord(_3))}",_0))
return f"print(bytes((lambdax:[int()for()in(x)])({','.join(_1)})))"
print(encode("a"))
@sly root :white_check_mark: Your eval job has completed with return code 0.
print(bytes((lambda*x:[int(_)for(_)in(x)])((((((4-2)+(3)*(3)*4*(5)/2))))+((((((3+((2)))))))))))
!e ```
print(bytes((lambdax:[int()for()in(x)])((((((4-2)+(3)(3)4(5)/2))))+((((((3+((2)))))))))))
@sly root :white_check_mark: Your eval job has completed with return code 0.
b'a'
is this obfuscated code that generates obfuscated code?
Someone was complaining about finding the builtins module again after getting rid of it? What kind of getting rid of it? because this:
__builtins__=None
print(__builtins__)
g = globals()
print(g['__builtins__'])
exec("""print(__builtins__); g={}; exec('b=__builtins__', g, g)""",g,g)
print(g['__builtins__'])
print(g['b'])
might be a workaround.
!e ```py
builtins=None
print(builtins)
g = globals()
print(g['builtins'])
exec("""print(builtins); g={}; exec('b=builtins', g, g)""",g,g)
print(g['builtins'])
print(g['b'])
@vague cairn :x: Your eval job has completed with return code 1.
001 | None
002 | None
003 | Traceback (most recent call last):
004 | File "<string>", line 5, in <module>
005 | File "<string>", line 1, in <module>
006 | TypeError: 'NoneType' object is not subscriptable
@vague cairn :white_check_mark: Your eval job has completed with return code 0.
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
!e
__builtins__=None
print(__builtins__)
g = globals()
print(g['__builtins__'])
exec("""print(__builtins__); gl={}; exec('b=__builtins__', gl, gl); __builtins__ = gl['__builtins__']""",g,g)
print(__builtins__)```
code
!e
__builtins__=None
print(__builtins__)
g = globals()
print(g['__builtins__'])
exec("""print(__builtins__); gl={}; exec('b=__builtins__', gl, gl); __builtins__ = gl['__builtins__']""",g,g)
print(__builtins__)
@vague cairn :x: Your eval job has completed with return code 1.
001 | None
002 | None
003 | Traceback (most recent call last):
004 | File "<string>", line 5, in <module>
005 | File "<string>", line 1, in <module>
006 | TypeError: 'NoneType' object is not subscriptable
the python bot keeps being different than than I expect.
!e
import builtins
class OneLineError(Exception): ...
class _MISSING: ...
class ProxyObject:
def __init__(self, owner, value):
self.owner = owner
self.value = value
def __getattr__(self, attr):
self.value = getattr(self.value, attr)
return self
def __getitem__(self, *keys):
self.value = self.value.__getitem__(*keys)
return self
def __call__(self, *args, **kwargs):
self.value = self.value(*args, **kwargs)
return self
@property
def RET_OBJ(self):
self.owner.last = self.value
return self.owner
class OneLinerise:
last = _MISSING
def __getattr__(self, attr):
try:
self.last = getattr(builtins, attr)
except AttributeError:
self.last = globals()[attr]
return self
def __getitem__(self, keys):
self.last = self.last.__getitem__(keys)
return self
def __call__(self, *args, **kwargs):
if self.last is _MISSING:
raise OneLineError
self.last = self.last(*args, **kwargs)
return self
@property
def save_last(self):
globals()["_"] = self.last
return self
@property
def print_last(self):
print(self.last)
return self
@property
def returned(self):
if self.last is _MISSING:
raise OneLineError
return ProxyObject(self, self.last)
def save_last_as(self, name):
globals()[name] = self.last
return self
def literal(self, literal):
self.last = literal
return self
def set_var(self, var, name=None):
globals()[name if name is None else "__"] = var
OneLinerise().print("test").literal(10).returned.bit_length().RET_OBJ.save_last_as("bruh").print_last.print(bruh)
@terse oriole :white_check_mark: Your eval job has completed with return code 0.
001 | test
002 | 4
003 | 4
woah it works
technically oneline?
it works but its an inefficient implementation
It runs using the -c argument which changes a few things from repl and normal file mode
Ah! Thanks.
!e
hh = lambda x: (
functools := __import__('functools'),
(fib := functools.lru_cache((lambda x:
x if x <= 1 else fib(x - 1) + fib(x - 2)))),
print([fib(i) for i in range(x)])
)[-1]
print(hh(10))
@near gust :white_check_mark: Your eval job has completed with return code 0.
001 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
002 | None
I should make a python 3 version of the one-lined python thing
i love abusing walrus
!e
main = lambda: (
class_ := __import__('types').new_class,
HelloWorld := class_(
'HelloWorld',
exec_body=lambda ns: (
(ns.update({'__init__':
lambda self: print("Hello, World!")}
), ns
)[-1]
)
),
instance := HelloWorld(),
print(instance)
)[-1]
main()
@near gust :white_check_mark: Your eval job has completed with return code 0.
001 | Hello, World!
002 | <types.HelloWorld object at 0x7f550927eaa0>
huh
@rich hound :white_check_mark: Your eval job has completed with return code 0.
True
!e
print((lambda n:n&1)(5))
@trim grove :white_check_mark: Your eval job has completed with return code 0.
1
!E ```py
i=lambda n:n&1
i2=1 .and
print(i(5))
print(i2(5))```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 1
prob no further optimization
!E
i=1 .__and__
print(i(4))โ
@rich hound :white_check_mark: Your eval job has completed with return code 0.
0
@rich hound :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 1
003 | 3
004 | 3
005 | 5
006 | 5
007 | 7
008 | 7
009 | 9
010 | 9
interesting
1 | 4 == 0b001 | 0b100 == 0b101 == 5
times when being very experienced with python helps with golfing tactics
!e
print("I believe this can run code? ")
why the trashcan
!e
while True: pass
HAHAHAHA serves you well
this guy having a monologue
so basically what I did was store a bunch of expressions in a tuple and return the one that actually returns a value by getting the last index and I did this twice: once in the import statement, and another time in the exec_body to update the namespace, and then I abused walrus some more to create an instance and print it. A lot shorter than using a Y combinator, but less likely to get you fired
yeah, all that makes sense
I just found the code kinda funky and fun
How normal people type "E" :
a = "E"
How members lf this community do:
a:=(lambda:str(...)[0])()
what is that easy syntax
Huh?
!e ```py
print([[]for[globals()[
chr(6+(79) # use 6 days and 9 weeks in days
#to help us here
+74)]]in[[chr(
6+(7*9)
,)[([]==[])^(3&1)]]]]and a)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
E
@coarse void you do it like this
Very true.
!e
while True: print(1)
@crimson plover :x: Your eval job has completed with return code 143 (SIGTERM).
001 | 1
002 | 1
003 | 1
004 | 1
005 | 1
006 | 1
007 | 1
008 | 1
009 | 1
010 | 1
011 | 1
... (truncated - too many lines)
Full output: too long to upload
!e
import turtle
@crimson plover :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "/usr/local/lib/python3.10/turtle.py", line 107, in <module>
004 | import tkinter as TK
005 | File "/usr/local/lib/python3.10/tkinter/__init__.py", line 37, in <module>
006 | import _tkinter # If this fails your Python may not be configured for Tk
007 | ImportError: libtk8.6.so: cannot open shared object file: No such file or directory
you can't run gui stuff via !e
Binary search with [1, 2, 3, 4, 5, 6, 7, 8, 9] one liner:
(lambda _Y: (lambda binary_search: (lambda x: print(binary_search(x, 5)))([1, 2, 3, 4, 5, 6, 7, 8, 9]))(lambda array, key: [(lambda end, start, x: (lambda _loop1: _loop1(end, start, x))(_Y(lambda _loop1: (lambda end, start, x: ((lambda x: (x if array[x] == key else ((lambda end: _loop1(end, start, x))((x - 1)) if array[x] > key else ((lambda start: _loop1(end, start, x))((x + 1)) if array[x] < key else _loop1(end, start, x)))))(((start + end) // 2))) if start <= end else -1))))(end if "end" in dir() else None, start if "start" in dir() else None, x if "x" in dir() else None) for (start, end) in [(0, (len(array) - 1))]][0]))((lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))))
what does it do?
bs=lambda l,v,o=0:(bs(l[i:],v,o+i)if l[i]<=v else bs(l[:i],v,o))if(i:=len(l)//2)else o
``` smaller binary search^
wtf
Damn
bs=lambda l,v,o=0:(bs(l[:i],v,o)if l[i]>v else bs(l[i:],v,o+i))if(i:=len(l)//2)else o
``` smaller by 1 byte ^
!e smaller by 2 bytes ```py
bs=lambda l,v,o=0:(v<l[i]and bs(l[:i],v,o)or bs(l[i:],v,o+i))if(i:=len(l)//2)else o
assert(bs(range(1,10),5) == [*range(1,10)].index(5))
assert(bs(range(2,20,2),16) == [*range(2,20,2)].index(16))
print(f"{bs(range(1,10),5)=}")
print(f"{bs(range(2,20,2),16)=}")
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | bs(range(1,10),5)=4
002 | bs(range(2,20,2),16)=7
What's the hook you overload to get missing() type access to 'globals()' not finding things events?
Oh, here it is.
!e ```py
from ctypes import py_object
import atexit, builtins, sys, dis
def init_missing_hook(dct, func):
"missing var hook by chilaxan"
ob_base_p = py_object.from_address(id(dct) + 8)
class missing_hook(dict):
slots = ()
def missing(self, key, ob_base_p=ob_base_p, builtins=builtins):
try:
ob_base_p.value = builtins.dict
return (builtins.dict | self)[key]
except KeyError:
return func(self, key)
finally:
ob_base_p.value = class
ob_base_p.value = missing_hook
@atexit.register
def unhook():
ob_base_p.value = dict
return unhook
def roman(d, k):
"Undefined variables, that are made up of only roman numerals, are interpreted as numbers."
digits = {'M':1000, 'D':500,
'C':100, 'L':50,
'X':10, 'V':5,
'I':1, 'ฤช':1000}
digits.update({k.lower():v for k,v in digits.items()})
total = current_total = current = 0
for digit in k:
n = digits[digit]#key error if digit is not roman, which is exactly the exception we want to raise.
if n == current:
current_total += n
elif n < current:
total += current_total
current_total = n
elif n > current:
total -= current_total
current_total = n
current = n
else:
total += current_total
d[k] = total
return total
init_missing_hook(sys._getframe().f_globals, roman)
print(XXII/VVVVXIII)```
@vague cairn :white_check_mark: Your eval job has completed with return code 0.
-3.142857142857143
Thanks Chilaxan.
why is the result negative
oh
how did you think of that
oh i get it now
question
how does six override the getattr for their module ๐ง
if I just try to count members of each module (with inspect.getmembers), it seems to reliably crash if six is loaded:
>>> [print(k) or print(len(inspect.getmembers(v))) for k,v in sys.modules.items()]
sys
93
builtins
158
_frozen_importlib
59
_imp
21
_thread
24
_warnings
11
# *snip*
...
six.moves
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
File "/usr/lib/python3.9/inspect.py", line 351, in getmembers
value = getattr(object, key)
File "/usr/local/lib/python3.9/dist-packages/six.py", line 97, in __get__
result = self._resolve()
File "/usr/local/lib/python3.9/dist-packages/six.py", line 120, in _resolve
return _import_module(self.mod)
File "/usr/local/lib/python3.9/dist-packages/six.py", line 87, in _import_module
__import__(name)
ModuleNotFoundError: No module named 'tkinter'```
and yes I know everyone is inspired by the shameless use of print(x) or ...
I'm not concerned about tkinter... I am really wondering what esoteric tricks they are up to so I can both defend myself against and join their secret society
idk it's a descriptor
which thing is ?
what
is it this?
class MovedModule(_LazyDescr):
def __get__(self, obj, tp):
result = self._resolve()
setattr(obj, self.name, result) # Invokes __set__.
try:
# This is a bit ugly, but it avoids running this again by
# removing this descriptor.
delattr(obj.__class__, self.name)
except AttributeError:
pass
return result```
oops nvm I thought you said "it is a descriptor"
six.moves does not appear to be an actual file
it's an object pretending to be a module
oh what that ^ is ?
also whoops forgot to disable the ping
bs=lambda l,v,o=0:(o,(bs(l[:i],v,o)if l[i]>v else bs(l[i:],v,o+i)))[(i:=len(l)//2)]
oh lmao its even longer
but without walrus is shorter
!e
i=__import__;b,s=i("io").StringIO(),i("sys");s.stdout=b;_,s.stdout=i("this"),s.stderr;print(i("collections").Counter(b.getvalue().replace(" ","").upper()).most_common(1)[0][0])โ
@restive void :white_check_mark: Your eval job has completed with return code 0.
E
afaik, you can define a __getattr__ at the module level
!e ```py
def getattr(key):return key, 1
import main
print(main.a)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
('a', 1)
{'inline': False, 'name': i.text if i.text else '...', 'value': '...' if valid_chars.match(j.text) else j.text if j.text else '...'}
for i, j in zip(soup.find_all('th')[:10], soup.find_all('td')[:10])
just, why?
hi