#esoteric-python
1 messages ยท Page 111 of 1
Here's some perfectly valid Python mergesort for you people
def m๐๐๐๐(array, left_index, right_index, middle):
๐ต๐พ๐ง๐_๐ ๐๐๐ = ๐ผ๐๐๐ข๐ช[๐ธ๐๐๐ฑ_๐ฒ๐๐ญ๐๐:(m๐ฆ๐
๐
๐๐ฎ + 1)]
๐ฏ๐๐จ๐๐ญ_๐ฌ๐๐๐ = ๐ผ๐๐๐ข๐ช[(m๐ฆ๐
๐
๐๐ฎ + 1):(๐ง๐ฒ๐ด๐๐ต_๐พ๐๐ญ๐พ๐ + 1)]
๐๐๐๐ฝ_๐ ๐ ๐ฅ๐ฃ_๐๐ฟ๐ก๐๐ต = 0
๐๐๐ฐ๐ฉ๐ต_๐ผ๐ธค๐ฅ๐_๐ฒ๐๐๐๐
= 0
๐๐พ๐ณ๐ฑ๐ข๐ฑ_๐ฒ๐ก๐ญ๐ฎ๐ก = ๐ธ๐๐๐ฑ_๐ฒ๐๐ญ๐๐
while ((๐๐๐๐ฝ_๐ ๐ ๐ฅ๐ฃ_๐๐ฟ๐ก๐๐ต < len(๐ต๐พ๐ง๐_๐ ๐๐๐)) and (๐๐๐ฐ๐ฉ๐ต_๐ผ๐ธค๐ฅ๐_๐ฒ๐๐๐๐
< len(๐ฏ๐๐จ๐๐ญ_๐ฌ๐๐๐))):
if (๐ต๐พ๐ง๐_๐ ๐๐๐[๐๐๐๐ฝ_๐ ๐ ๐ฅ๐ฃ_๐๐ฟ๐ก๐๐ต] <= ๐ฏ๐๐จ๐๐ญ_๐ฌ๐๐๐[๐๐๐ฐ๐ฉ๐ต_๐ผ๐ธค๐ฅ๐_๐ฒ๐๐๐๐
]):
๐ผ๐๐๐ข๐ช[๐๐พ๐ณ๐ฑ๐ข๐ฑ_๐ฒ๐ก๐ญ๐ฎ๐ก] = ๐ต๐พ๐ง๐_๐ ๐๐๐[๐๐๐๐ฝ_๐ ๐ ๐ฅ๐ฃ_๐๐ฟ๐ก๐๐ต]
๐๐๐๐ฝ_๐ ๐ ๐ฅ๐ฃ_๐๐ฟ๐ก๐๐ต = (๐๐๐๐ฝ_๐ ๐ ๐ฅ๐ฃ_๐๐ฟ๐ก๐๐ต + 1)
else:
๐ผ๐๐๐ข๐ช[๐๐พ๐ณ๐ฑ๐ข๐ฑ_๐ฒ๐ก๐ญ๐ฎ๐ก] = ๐ฏ๐๐จ๐๐ญ_๐ฌ๐๐๐[๐๐๐ฐ๐ฉ๐ต_๐ผ๐ธค๐ฅ๐_๐ฒ๐๐๐๐
]
๐๐๐ฐ๐ฉ๐ต_๐ผ๐ธค๐ฅ๐_๐ฒ๐๐๐๐
= (๐๐๐ฐ๐ฉ๐ต_๐ผ๐ธค๐ฅ๐_๐ฒ๐๐๐๐
+ 1)
๐๐พ๐ณ๐ฑ๐ข๐ฑ_๐ฒ๐ก๐ญ๐ฎ๐ก = (๐๐พ๐ณ๐ฑ๐ข๐ฑ_๐ฒ๐ก๐ญ๐ฎ๐ก + 1)
while (๐๐๐๐ฝ_๐ ๐ ๐ฅ๐ฃ_๐๐ฟ๐ก๐๐ต < len(๐ต๐พ๐ง๐_๐ ๐๐๐)):
๐ผ๐๐๐ข๐ช[๐๐พ๐ณ๐ฑ๐ข๐ฑ_๐ฒ๐ก๐ญ๐ฎ๐ก] = ๐ต๐พ๐ง๐_๐ ๐๐๐[๐๐๐๐ฝ_๐ ๐ ๐ฅ๐ฃ_๐๐ฟ๐ก๐๐ต]
๐๐๐๐ฝ_๐ ๐ ๐ฅ๐ฃ_๐๐ฟ๐ก๐๐ต = (๐๐๐๐ฝ_๐ ๐ ๐ฅ๐ฃ_๐๐ฟ๐ก๐๐ต + 1)
๐๐พ๐ณ๐ฑ๐ข๐ฑ_๐ฒ๐ก๐ญ๐ฎ๐ก = (๐๐พ๐ณ๐ฑ๐ข๐ฑ_๐ฒ๐ก๐ญ๐ฎ๐ก + 1)
while (๐๐๐ฐ๐ฉ๐ต_๐ผ๐ธค๐ฅ๐_๐ฒ๐๐๐๐
< len(๐ฏ๐๐จ๐๐ญ_๐ฌ๐๐๐)):
๐ผ๐๐๐ข๐ช[๐๐พ๐ณ๐ฑ๐ข๐ฑ_๐ฒ๐ก๐ญ๐ฎ๐ก] = ๐ฏ๐๐จ๐๐ญ_๐ฌ๐๐๐[๐๐๐ฐ๐ฉ๐ต_๐ผ๐ธค๐ฅ๐_๐ฒ๐๐๐๐
]
๐๐๐ฐ๐ฉ๐ต_๐ผ๐ธค๐ฅ๐_๐ฒ๐๐๐๐
= (๐๐๐ฐ๐ฉ๐ต_๐ผ๐ธค๐ฅ๐_๐ฒ๐๐๐๐
+ 1)
๐๐พ๐ณ๐ฑ๐ข๐ฑ_๐ฒ๐ก๐ญ๐ฎ๐ก = (๐๐พ๐ณ๐ฑ๐ข๐ฑ_๐ฒ๐ก๐ญ๐ฎ๐ก + 1)
I apologise, I forget the include the driver code, the actual sorting function, and tests
oh, and to autoformat. Can't forget that.
I'm trying. It not working.
I can't figure out how to make a package, let alone make a package available on pypi
@tame kraken a big compactness boost is only using single-letter variables. You probably won't run out of latin ones, but if you do, try cyrillic or greek ones
you can also change the indent size to 1
k
and why do you want to put the program into a QR code?
it looks like our hastebin breaks some chars ๐ฆ
literally unusable
https://paste.pythondiscord.com/fihoqivoya.py
There we go!
it look some time to get it right, I had to use pyperclip to stuff the code into my clipboard so I could paste it without it being broken
Does this work for y'alls?
so how do i upload a module to pypi?
Looks okay for me.
yeah, the version I posted is fine
when I manually copy the text from the file to the pastebin, though, it breaks for some reason
while pyperclip.copy works fine
It's hard to summarise in a Discord message. I think there's a guide or two.
by that, I meant whether it launches and passes tests for everyone else too
There's a test server you can use so that if you mess up it's not irreversible.
:/
There's a guide to that.
I pasted it into IPython and it printed the "All tests passed!" message.
Do you want a link?
In this step-by-step tutorial, youโll learn how to create a Python package for your project and how to publish it to PyPI, the Python Package Repository. Quickly get up to speed on everything from naming your package to configuring it using setup.py.
PyCharm can't handle perfectly valid identifiers, smh
@formal sandal im back from dinner
hello everyone, i came here to ask if anyone could improve my code. its not what you think though... i want to make my code as small as possible and im currently sitting at 2.4Kb for the classic Snake Game. i want this to eventually be around 2Kb, ive been doing all i can, and i would greatly appreciate any help from the pro's in here!
Also to note, im not using a Compressor or anything like that and im only going to consider using pne when my code is at my goal, and im thinking, 2Kb compressed would be tiny!
yikes this package creation process is complicated :/
cursedutils-4.2.0
pip literally just updated
'perfectly valid'
there will only ever be version 4.2.0
there's no way im doing all this again for version 4.2.1
it's gonna be 4.2.0
withe the XD License 6.9
anyone?
lmfao error 403
you want to golf your code, my snakey friend?
pep8 becomes your guide to what not to do
whats pep8?
pep8 is the holy grail of readable code.
pep8 is also the bane of esoteric python.
!pep 8
behold
pep8
Uploading distributions to https://github.com/FluffyTrooper2001/cursedutils
Enter your username: __token__
Enter your password:
Uploading cursedutils-4.2.0-py3-none-any.whl
100%|โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ| 12.3k/12.3k [00:00<00:00, 14.9kB/s]
NOTE: Try --verbose to see response content.
HTTPError: 403 Forbidden from https://github.com/FluffyTrooper2001/cursedutils
Forbidden
Why do i get error?
It's hard to give specific feedback without knowing what the code does. However, you could look into https://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python
That's a lot of extra spaces.
Content received from server:
Cookies must be enabled to use GitHub.
Try replacing every chain of four spaces with a single space.
how do i cookies im in terminal
Is your problem with uploading to GitHub?
me? how would i remove the spaces?
my problem is using twine
if x:
y()
```is the same as```python
if x:
y()
is the same as
x and y()
oh
:P
in that context, anyway
if x:y()
starting to look more like code, less like glorified English
Also, line 32 says game_close == True. Even in regular code, this is a bad idea. It does the same thing as while game_close: on its own.
instead of
for iteration in range(len(some_flippity_floppity_funny_looking_array_thingy)):
do_thing(iteration, some_flippity_floppity_funny_looking_array_thingy[iteration])
You name your variables in one letter if possible, and turn for loops into generator expressions.
[f(i,e)for i,e in enumerate(a)]
f,i,e, and a are, respectively, standard abbreviations of instances of function, iteration, element and array
think of your keyboard as your namespace. Each key is a variable, operator, or literal. you can still use builtins, but only if they're needed. Try to only name them once. Same as 3rd party API like discord.py
!e example of only calling a full name once, only using brackets once, not newline separating classes, only using one letter for names, except for dunders, and not allowing spaces between operators. Only use middleman variables if they will shorten your code.
f=lambda c:c()
@f
class c:__lshift__=print
@int
@f
class n:__int__=69
c<<n
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
!e and finally, look for the short way of doing things.
print(69)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
XD
I'm trying to do twine upload from terminal, but it's telling me cookies must be enabled to use github :/
dammit getpass hates both paste and stdin pipe
I'll have to type this mf manually
It's probably your terminal emulator. Try pasting with Ctrl+Shift+V.
Don't press Ctrl+V first though.
What do you mean?
classifiers = [
"License :: idk :: XD License 6.9", # invalid ;-;
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.9"
]
YAAAAAAAAAAAAAAAAAAAAAAAAAAS
I DID IT
pip install cursedutils==4.2.0
XDDDDD
oh no its actually cursed now
alright for all those that have been poking me for pypi package, from command line do pip install cursedutils
then from python do
from cursedutils.iostreams import*
#include<iostreams>
int.n.m
cout << "Enter a number between 1 and 10: "
cin >> n
cout << "Enter another number: "
cin >> m
cout << n << " + " << m " == " << n+m
and there's no guarantee that anything will work, as this was just to test uploading.
alright how do i update this module, now that I've uploaded it with its many bugs
!e ```py
class Given:
def init(s,**k):([setattr(s,this,that)for this,that in k.items()],[setattr(s,this,getattr(s.class,this)(s))for this in dir(s.class)if hasattr(this,'call')and not this[0]=='_'])
def _pep3150_example(a=4,b=5,op=lambda x,y:xy):
"""PEP 3150 example:
op(?.f, ?.g) given bound_a=a, bound_b=b in:
def f():
return bound_a + bound_b
def g():
return bound_a - bound_b
"""
execute_with=lambdau,**ck:lambda f: f(*u,**ck) # from cursedutils.wrappers import execute_with
@print
@lambda : op(.f, _.g)
@execute_with(bound_a=a, bound_b=b)
class evaluate(Given):
def f(s):return s.bound_a + s.bound_b
def g(s):return s.bound_a - s.bound_b
_pep3150_example()
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 18, in <module>
003 | File "<string>", line 15, in _pep3150_example
004 | File "<string>", line 13, in <lambda>
005 | File "<string>", line 3, in <lambda>
006 | TypeError: unsupported operand type(s) for *: 'method' and 'method'
what is this base class, chopped liver? I told it to call and reset callable attributes that don't start with _
that is the perfect pfp for this module XD
!e so tell me, why the distinction? ```py
def lshift(s,o):
print (end=o)
return s
print (lshift.class.name) # function
cout = type("pipe",(),globals())()
cout << cout.lshift.class.name # method
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | function
002 | method
when they seem to be the same thing.
They aren't. The method is bound to the cout object, whereas the function takes an s object as an argument.
!e
import ctypes
hooker = ["str",(str,),{}]
hook = lambda f:hooker[2].__setitem__(f.__name__,f)or f
exec_hook= lambda:ctypes.py_object.from_address(id(str)).__setattr__('value',type(*hooker))
@hook
def encrypt(s,k):return[chr(ord(c).__add__(ord(k[i%len(k)])).__mod__(95)+32)for i,c in enumerate(s)]
@hook
def decrypt(s,k):return[chr(ord(c).__sub__(ord(k[i%len(k)])).__mod__(95)+32)for i,c in enumerate(s)]
exec_hook()
doot = "secret message".encrypt("fluffy")
print(doot)
print(doot.decrypt("fluffy"))
bruh
Python just ignoring my hacking now.
hold up
where's the third one coming from?
It doesn't need to add so much to the recursion depth โ Python calls are expensive.
Plus, methods contain a reference to their class.
!e
def bind(self):
def outer(f):
def inner(*a,**k): return f(self, *a, **k)
setattr(inner,'__name__',f.__name__)
setattr(self.__class__,f.__name__,inner)
return inner
return outer
cout = type("",(),{})()
@bind(cout)
def __lshift__(self, other):return print(end=str(other))or self
__lshift__(69)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
but in that instance i don't even need to reference the object
It sounds to me like you don't normally need any of the distinctions between methods and functions.
XD
I have a preview module cursedutils available on pypi
it's got more bugs than a swamp tho
@sick hound
pip install cursedutils
Is that Python code?
it will be
!e ```py
s="""
some song idk
I'm bored.
โใโใโโใโทใโป
oอ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑoโฌโฌโฌโฌโฌโฌโฌโฌโฌโฌโฌโฌโฌโฌโฌโฌโฌoอ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑo
"""
print(len(s),s,[ord(c)for c in s])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 142
002 | some song idk
003 | I'm bored.
004 |
005 |
006 | โใโใโโใโทใโป
007 | oอ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑoโฌโฌโฌโฌโฌโฌโฌโฌโฌโฌโฌโฌโฌโฌโฌโฌโฌoอ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑ๏ฑo
008 | [10, 32, 32, 115, 111, 109, 101, 32, 115, 111, 110, 103, 32, 105, 100, 107, 10, 32, 32, 32, 73, 39, 109, 32, 98, 111, 114, 101, 100, 46, 10, 10, 10, 32, 32, 32, 8646, 12288, 9665, 12288, 10074, 10074, 12288, 9655, 12288, 8635, 32, 10, 111, 860, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 111, 9644, 9644, 9644, 9644, 9644, 9644, 9644, 9644, 9644, 9644, 9644, 9644, 9644, 9644, 9644, 9644, 9644, 111, 860, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64606, 64
... (truncated - too long)
Full output: https://paste.pythondiscord.com/okotoyaqis.txt?noredirect
142 chars and using 64606 likely for the vertical thingys, and 9644 for the horizontal thingys
would even be useful if you could trigger an event for clicking on something in the terminal :/
i.e. the buttons
so then i could make a graphical user interface with just unicode in a terminal
so what if i made a fake terminal using a kivy TextInput?
Then i'm free from the limitations of the terminal
and i can make an arbitrary object with a touch trigger with the coordinates of the buttons coded in.
but then i can't really test it with the bot.
!e ```py
class doot:
init=lambda s,d:setattr(s,'d',d)
call=lambda s,o:type("",(),{'rlshift':lambda d,p:setattr(p,o,getattr(p,o)+1)})()
inc, dec = doot(1), doot(-1)
a=type("",(),{})
a.b = 5
a<<inc('b')
print (a.b)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
6
yaas
@call()
class hack_self:
gulag={}
def __call__(s, self, new_self):
hacker = [ctypes.py_object.from_address(id(self)+i)for i in range(16)]
if id(self)not in s.gulag: s.gulag |= {id(self):[hack.value.copy()if hasattr(hack.value,'copy')else hack.value for hack in hacker]}
[setattr(hack,value,ctypes.py_object.from_address(id(new_self)+i).value)for i,hack in enumerate(hacker)]
return self
def __del__(self):
"""Release prisoner at end of life sentence"""
for prisoner in self.gulag: ctypes.py_object.from_address(prisoner).value = self.gulag[prisoner]
why does this crash python? ๐ค
Well, you're trying to dereference random addresses after the id of an object which isn't valid. You have no idea what's in those bytes, though there's definitely not valid objects 16 bytes from the start of your class instance. Objects are in general randomly placed in memory....
you have a good point, but the type of an object is stored at id(obj)+8
I would presume there's more data following
nice 
..or + 4 on 32 bit
they're ssize_t sized in cpython distros tho right?
or at least get packed that way in pyobjects
is all I care about haha
but I checked in c
and they are that size when I check in c
Used for a count of bytes. It is the result of the sizeof
operator. According to the C language standard, it shall
be an unsigned integer type capable of storing values in
the range [0, SIZE_MAX]. According to POSIX, the implementation shall support one or more programming environments where the width of size_t is no greater than the width of the type long.
Damn you android copy-paste
Actually, i know on my distro that a pointer is as big as a longlong
But so is a long long apparently
Longs are same size as long long
neve rused a long long
I think it's because longs are not guaranteed to be bigger than ints?
my long longs are 8
everything else is 4
I think my C is in 32x tho
for whatever reason
I didn't even install C manually it's just on clion idk what it is
pointer:4 long long:8 long:4 size_t:4 ssize_t:4 int:4
ah yeah it's building 32 bit
A 32-bit pointer can only address up to 2ยณยฒ locations, which is a little more than 2 gigabytes of RAM. So if you want to have a program that can allocate more than that, it needs a larger size. Hence 64 bits, which is more than enough for the foreseeable future.
A 32-bit pointer can only address up to 2ยณยฒ locations, which is a little more than 2 gigabytes of RAM.
...2^32 locations is 4 gigabytes
but aside from that, yeah, that's what the reason is
64-bit pointers are enough for 18 exabytes of RAM which is... a lot
modern archs only use 48bits for addresssing though
they still align to 64bit in most cases tho
ye, its 64bit values, but the high 16 are not part of the address
Can someone pm and help me reword code so I donโt plagiarise
that's still plagiarism
can someone tell me how this equals 4?
2>>0<<1
(2>>0)<<1 = 2 << 1
Still unsure
thats genuinely confusing.
Why? just quicked than typing out 2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2
just do this then
2<<10 = 2**11
!e __import__("sys").stdout.write(__import__("sys").stderr.mode)
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
w
!e ```py
from ctypes import *
import dis
BASE_SIZE = sizeof(c_void_p)
BYTES_OFFSET = b''.sizeof() - 1
def getframe(depth=0):
try:raise
except Exception as e:
frame = e.traceback.tb_frame
for _ in range(depth + 1):
frame = frame.f_back
return frame
def real_return(func):
def wrapper(*args, **kwargs):
class FakeTrue:
def call(self):
py_object.from_address(id(self) + BASE_SIZE).value = bool
instructions[:] = orig
return func(*args, **kwargs)
py_object.from_address(id(True) + BASE_SIZE).value = FakeTrue
frame = getframe(1)
co_code = frame.f_code.co_code
instructions = (c_char * 4).from_address(id(co_code) + BYTES_OFFSET + frame.f_lasti)
orig = instructions.raw
instructions[:] = bytes([
dis.opmap['CALL_FUNCTION'], 0,
dis.opmap['JUMP_ABSOLUTE'], frame.f_lasti
])
return True
return wrapper
class Foo:
@real_return
def contains(self, other):
return (self, other)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
(<__main__.Foo object at 0x7f79caca3fa0>, 1)
anyone know a quirky way to get the letter o
o?
yeah
let me see
trying to find a way without using chr/ord
ah.
that was my first idea lol
!e print({}.__class__)
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
<class 'dict'>
hmmm
!e print(_:="")
@sudden willow :warning: Your eval job has completed with return code 0.
[No output]
found one
brb
!e ```py
print("%c"%((2>>0<<6)-17))
@fossil estuary :white_check_mark: Your eval job has completed with return code 0.
o
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
o
o.o
alright brb gotta refine code
Amazing.
!e
__import__("sys").stdout.write((lambda:....__class__).__str__()[(([]==[])++([]==[])++(([]==[])+([]==[]))++([]==[])++([]==[])++([]==[])+([]==[])+~([]==[])++([]==[]))].__add__(__import__("sys").stderr.mode).__add__((lambda:....__class__).__str__()[(([]==[])++([]==[])++(([]==[])+([]==[]))++([]==[])++([]==[])++([]==[])+([]==[])+~([]==[])++([]==[]))]))
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
owo
owo
now make it return uwu
is that brainfuck ?
no
use sys.__stdout__ 
!e ```py
from ctypes import *
import dis
BASE_SIZE = sizeof(c_void_p)
BYTES_OFFSET = b''.sizeof() - 1
def getframe(depth=0):
try:raise
except Exception as e:
frame = e.traceback.tb_frame
for _ in range(depth + 1):
frame = frame.f_back
return frame
capsule = {}
@CFUNCTYPE(py_object, py_object)
def call(_):
tptr = capsule.pop('tptr')
inst = capsule.pop('inst')
orig = capsule.pop('orig')
retv = capsule.pop('retv')
tptr.value = None
inst[:] = orig
return retv
call_addr = cast(call, c_void_p).value
def real_return(func):
def wrapper(self, other):
frame = getframe(1)
co_code = frame.f_code.co_code
flag = co_code[frame.f_lasti + 1]
ret = func(self, other, flag)
instructions = (c_char * 4).from_address(id(co_code) + BYTES_OFFSET + frame.f_lasti)
orig = instructions.raw
instructions[:] = bytes([
dis.opmap['CALL_FUNCTION'], 0,
dis.opmap['JUMP_ABSOLUTE'], frame.f_lasti
])
tpcall_pointer = c_void_p.from_address(id(bool) + 16 * BASE_SIZE)
tpcall_pointer.value = call_addr
capsule.update(tptr=tpcall_pointer,
inst=instructions,
orig=orig,
retv=ret)
return True
return wrapper
class Foo:
@real_return
def contains(self, other, flag):
return (self, other, flag)
print(1 in Foo())
print(2 not in Foo())```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | (<__main__.Foo object at 0x7f9aaec89fa0>, 1, 0)
002 | (<__main__.Foo object at 0x7f9aaec89fa0>, 2, 1)
allows __contains__ to return actual values (not just True or False) and passes a flag based on in vs not in
!e ```py
with open("/proc/self/maps") as f:
print(f.read())
@grave rover :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | FileNotFoundError: [Errno 2] No such file or directory: '/proc/self/maps'
yea snekbox has procfs disabled
sad
you could fake it tho. have open(*args) return a mock file object
that actually access the address space
Woah, that's really useful. Could it work for bool to specialize for and/or/not?
oh how do i detect the bitness of a system, then?
oh wait, i know, read _64_bits = hack(id(obj)+8).value == obj.__class__
or _32_bits = hack(id(obj)+4) == obj.__class__
or even ARCHITECTURE ,= [i for i in range(16)if hack(id(obj)+i)==obj.__class__]
y'know, a "mock file object" would be an extremely useful base class
Isn't there one in io?
how would I set what it... does?
If I recall, you give it a string, and it pretends to be a file.
ah, a string.
I've been making an entirely new File class, that behaves like open() only it doesn't block the file.
after all, whenever i use file reading, i haven't done anything that needs to block it.
here's a preview, I haven't added 'invincibility' yet, since try except suites are bugger to write esoterically.
__eq__ =lambda s,p:s.name==p.name# or s.read()==p.read() #<review>
__ge__ =lambda s,t:t[1]<=(t[0],str(s)) # [__str__]
__and__ =lambda s,o:s and o# []
__or__ =lambda s,o:s or o # []
__str__=__repr__=lambda s:s.read() # [read]
__int__ =lambda s:len([(f:=open(s.name)).read(),f.close()][0]) # [__init__]
__bool__ =lambda s:os.path.exists(s.name) # [__init__]
# file-like-methods
read=lambda s,n =- 1:[(f:=open(s.name,'r')).read(n if n>0 else n and int(s)),f.close()][0]if self.readable else NotImplemented # [__int__]
write=lambda self, s:[(f:=open(self.name,'w')).write(s),f.close()][0]if self.writable else NotImplemented # [__init__]
readable,writable,seekable,closed=True,True,True,False # []
seek=lambda s,p,m=0:setattr(s,'__p',p if not m else s.__p+p if m<0 else int(s)-p)if s.seekable else NotImplemented # [__int__]
reconfigure=lambda s,d='r+',**k:[setattr(s,n,v)for n,v in({'readable':'r'in d or'+'in d,'writable':'w'in d or'+'in d or'a'in d,'seekable':True}|k).items()]
# idk
_CHUNK_SIZE,write_through=8192,False
close=flush=lambda*a,**k:None # []
fileno=lambda s:[(f:=open(s.name,'r')).fileno(),f.close()][0] # [__init__]
buffer=type("None",(object,),{'__doc__':"Does not need a buffer"})()
The comments are just dependency tracing
except for the first one
everything after idk is guessing
If you're okay with imports you could do your file closing more safely with e.g. pathlib.
but i don't like the whole with open(filename,perms) as file: c=file.read();file.seek(3);file.write("whatever") and all that i just like a nice, concise, explicit
+File(filename) # you get it? 'plus file' add a file XD
File(filename) << "from cursedutils.death import blue_screen_induction_protocol\n"
File(filename) << "blue_screen_induction_protocol()"
__import__(filename) # blue screen go brrrrrr
I think that's what pathlib tries to be.
I just use it for the handy methods.
There's one that reads a whole file, which is usually what I want to do.
i saw pathlib recently and i thought hmmm, that might come in handy
I've gotten as far with pure python tho :/
I havent' fiully impleemented seeking tho
also open(filename,'r').reconfigure('w') crashed python
yea it would im actually working on writing a meta class that will enable some fake dunders for those (__and__, __or__, __not__) and itll add my enhanced __contains__
you can use ctypes.sizeof(ctypes_type)
but ARCHITECTURE ,= [i for i in range(16)if hack(id(obj)+i)==obj.__class__] has a pistol operator!
Hi vivid
@toxic jewel :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | def def(*args, **kwargs):
003 | ^
004 | SyntaxError: invalid syntax
sad
there's a way around that
!e
def = lambda *args, **kwargs: return *args, **kwargs def()
@toxic jewel :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | def = lambda *args, **kwargs: return *args, **kwargs
003 | ^
004 | SyntaxError: invalid syntax
am i just dumb
def is keyword โ you can't use it as an identifier.
!e ```py
@lambda f:globals().update({'def':f})
def func(*a,**k):
return [*a], {**k}
print(globals()'def')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
([], {})
there you go
!e print(globals().keys())
@toxic jewel :white_check_mark: Your eval job has completed with return code 0.
dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__'])
@toxic jewel :white_check_mark: Your eval job has completed with return code 0.
None
@toxic jewel :white_check_mark: Your eval job has completed with return code 0.
o
making owo brb
!e ```py
@lambda c:c()
class cout:lshift=lambda s,o:print(end=o)or s
cout << bytes.name[0] << int.name[0] << globals.name[0]*2 << (lambda:0).class.name[1] << bytes.name[4] << chr(32) << globals().class.name[:2] << globals().class.name[2]*2 << (lambda:2).class.name[1] << globals.name[6]
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
biggus diccus
lmao
that is called obfuscation :>
We did it with only A-Z, a-z, , and ()
ive done that
Specifically, only calling functions.
does this count
nope
No, " is rpesent
"sys"
on other account because too lazy to switch
That has = too.
sad
!e print(SyntaxError.name[0])
@distant wave :white_check_mark: Your eval job has completed with return code 0.
S
!e print((globals().get(__name__)).__str__()[1]+((__import__("sys").stderr.mode).__str__())+(globals().get(__name__).__str__()[1])
!e import(SyntaxError.name[0].lower() + SyntaxError.name[1] + SyntaxError.name[0].lower()).stdout.write((lambda:....class).str()[(([]==[])++([]==[])++(([]==[])+([]==[]))++([]==[])++([]==[])++([]==[])+([]==[])+~([]==[])++([]==[]))].add(import(SyntaxError.name[0].lower() + SyntaxError.name[1] + SyntaxError.name[0].lower()).stderr.mode).add((lambda:....class).str()[(([]==[])++([]==[])++(([]==[])+([]==[]))++([]==[])++([]==[])++([]==[])+([]==[])+~([]==[])++([]==[]))]))
@distant wave :white_check_mark: Your eval job has completed with return code 0.
owo
@distant 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: unsupported operand type(s) for |: 'tuple' and 'tuple'
!e print((globals().get(__name__)).__str__()[1]+((__import__("sys").stderr.mode).__str__())+(globals().get(__name__).__str__()[1]))
@toxic jewel :white_check_mark: Your eval job has completed with return code 0.
owo
- use
().__eq__(())to get 1 - use
<int>.__add__(<int>)to get more - use
chr(<int>)to get chars - use
<str>.__add__(<str>)to get strings
only requires adchreq_.()
What's the & for?
@distant wave :white_check_mark: Your eval job has completed with return code 0.
0
@distant wave :white_check_mark: Your eval job has completed with return code 0.
0
1^1?
o^o
exchr()=+ suffices, there was a discussion yesterday
ah
now, i'd like to test my alternate approach to see if it works...
+-[]<>,. also suffices.
?
How does that one work?
probs not in python tho
How do you get a string there
XD
making python brainfuck day by day
weary sigh Brainfuck, of course.
i wasn't aware exchr is a thing
@distant 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: bad operand type for unary ~: 'tuple'
remember the brainfuck i almost made with just class declarations and wrappers?
!e print(exchr().__dir__())
@toxic jewel :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'exchr' is not defined
hm
my dissapointment is immeasurable and my day is ruined
Hmmmm
exchrin()+
^
!e print(chr((() in [()])+(() in [()])+(() in [()])+(() in [()])+(() in [()])+(() in [()])+(() in [()])+(() in [()])+(() in [()])+(() in [()])+(() in [()])+(() in [()])+(() in [()])))
@distant wave :warning: Your eval job has completed with return code 0.
[No output]
wtf
def exchr(*n):
exec ('%c'*len(n)%n)
It can be made better, although pretty sure spaces are required...
spaces are overrated
!e ```py
print(chr((()in[()])))
@distant wave :white_check_mark: Your eval job has completed with return code 0.
oh
spaces are kinda cr*nge
my god
not how % formatting works
wtf
it works without spaces
all of the spaces in this code are redundant
in most cases all spaces can be replaced with ()
exchrln()+
You need commas.
You can replace the hr in exchr()+= with '% if you want fun syntax.
'%c'%n === chr(n)
eh
notc+,
and your code is run in exec("%c"*len(code)%code)
not sure how that'll work
!e ```py
print(not ,)
There
!e print(not not ,)
@toxic jewel :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print(not not ,)
003 | ^
004 | SyntaxError: invalid syntax
9 distinct bytes is a seemingly lower bound for TC py3
!e ```py
code = input()
assert not set(code) & {"notc+,"}
exec("%c"%len(code)%code)
is this even python anymore
using 1 instead of = makes programs shorter since you can take the char code of 11 instead of 1+1+1+1+1+1+1+1+1+1+1
i know estoeric python sorta well and i have never heard of anything like assert
!e ```py
assert False
@distant 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 | AssertionError
oh my god
next up you're gonna say you don't know nonlocal
!e assert "False"
@floral meteor :warning: Your eval job has completed with return code 0.
[No output]
!e print(assert.__dir__())
Wats nonlocal?
@toxic jewel :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print(assert.__dir__())
003 | ^
004 | SyntaxError: invalid syntax
rigged
global!
It's like global but for other local function scopes, rather than the global one.
exech[]=+
Might be hard to call things.
easier done then said
!e print(().__class__.__name__[1]+(__import__("sys").stderr.mode)+().__class__.__name__[1])
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
uwu
ten
!e print((~(~((([]!=[])++([]==[]))++([]==[]))))<<((([]==[])++([]==[])))^(([]==[])++([]==[])))
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
10
๐ณ
I'm working on a file-like object with extra iostream dunders
jut using vivid on phone and cityshow on computer
I just decided i'd return the object after an operation instead of the data passed to it
does __hasattr__ method of object call __getattr__?
I assume it checks if getattr:
so that's why it gives recursionerror when i tell it to
def __getattr__(self, other):
if hasattr(self,other):return super().__getattr__(other)
else:return print (other)
so how do I circumvent this circular referencing and still accomplish the same thing?
Try returning getattr without the dunder maybe?
it doesn't reach that, i don't think :/
Well you are probably getting recursion bc you are using the dunder inside the definition
So try to replace the super().getattr blah blah with getattr(self, other)
__getattr__ <-
if hasattr <-
whatever(getattr(s,o))<-
getattr <-
obj.__getattr__ back to the start
hence it's back to the start before it even gets to return super().__getattr__(other) or else:
since hasattr seems to within itself call obj.__getattr__
Ahh true
Hmm
Ig you could try looking at how base python defunded them
Or try this ig
x = getattr(self, other)
return x if x != None else return print (other)
hm.
try:return super().__getattr__(other)
except AttributeError:return print (other)
Might work actually
That might also work
!eval [code]
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*
Hey @floral meteor!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
oh found the PEP https://www.python.org/dev/peps/pep-0393/#string-creation
....has anyone done mutable strings?
making actual string literals mutable not a class
but they would probably have to pretend to be mutable
I just mean set item by index notation
and maybe some mutable sequence methods
thereโs bytearray
!e ```py
b = bytearray([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])
print(b, b.decode(), sep=": ")
b[5] = ord("-")
print(b, b.decode(), sep=": ")```
@solemn basin :white_check_mark: Your eval job has completed with return code 0.
001 | bytearray(b'hello world'): hello world
002 | bytearray(b'hello-world'): hello-world
@simple crystal
You'd probably want the bytearray in UTF-32 for better index complexity.
Cool, via bytecode hacks?
!e a="b";print(c with a as c)
@toxic jewel :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | a="b";print(c with a as c)
003 | ^
004 | SyntaxError: invalid syntax
sadge
only if you could do
print(c.read() with open('file.txt') as c)
I will attempt to find a way.
!e ~(++++(()<=())%~(()<=())++~(()<=()))-~(()<=())
@sudden willow :warning: Your eval job has completed with return code 0.
[No output]
TIL you can use as many pluses and minuses as you please
and ~
~ changes pos/neg doe
!e
print(~~~~~~~~~~~~~~~~~~~~~~~~~~+~+~+~+~++~++~+~----+~+~+~+~+~~+5+-~~-~~-~+~0<~++++++++3==~~+++++++++++---111)
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
False
just learned i can use not in my math too
!e ~(++++(()<=())%~(()<=())++~(()<=()))-(~(()<=())<<(()<=())&~(()<=()))++(()<=())++(~(not()<=()))
@sudden willow :warning: Your eval job has completed with return code 0.
[No output]
and or
!e print(~(++++(()<=())%~(()<=())++~(()<=()))-(~(()<=())<<(()<=())&~(()<=()))++(()<=())++(~(not()<=()))++(()<=()or()<=()))
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
7
nice, but I mean I wondered if anyone has experimented with adding tp_as_mapping mp_ass_subscript aka__setitem__ to string literals so they behave like mutable sequences, though you'd probably want to just make a new string behind the scenes rather than figuring out if the string is interned with multiple references and dealing with that
yeah it takes more than just hooking the method and trying to assign self to a new string
I'd mess with it more but I have hw
!e
class MutableStr(str):
def __new__(cls, *args, **kwargs):
self = super().__new__(cls, *args, **kwargs)
self.array = bytearray(ord(i) for i in self)
return self
def __setitem__(self, key, value):
if isinstance(key, int):
value = ord(value)
elif isinstance(key, slice):
value = (ord(i) for i in value)
self.array[key] = value
def __str__(self):
return self.array.decode()
string = MutableStr('Hello World')
string[5] = '-'
print(string)
string[::] = "lol"
print(string)
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
001 | Hello-World
002 | lol
nice, but to do what I meant you'd need to make something initally defined as a string literal behave that way
so you'd need to mess with the internals of the language, in CPython you'd need to at least move some pointers around
idk exactly how you'd do it because I'm not sure how to navigate to the relevant struct in the PyUnicodeObject hierarchy but I imagine it can be found by diving into the pointers in the top of whatever a str literal is
some sort of PyTypeObject
I debate whether to get more into knowing what CPython does or to switch to PyPy
idk exactly how you'd do it because I'm not sure how to navigate to the relevant struct in the PyUnicodeObject hierarchy but I imagine it can be found by diving into the pointers in the top of whatever a str literal is
:)
tfw looking into how to do this but not sure where getitem is stored on other classes
channel description says "code gore" so heres my simple todo list program
while 1:[[open("todo.txt", "w").write("")].append([open("todo.txt", "a").write(input(f"Enter item {x+1}: ") + "\n") for x in range(int([x if x.isnumeric() else 0 for x in input("How many things to do: ").split()][0]))]) if x == "W" else [print(elem.strip("\n")) for elem in open("todo.txt", "r").readlines()] if x == "R" else [print(elem.strip("\n")) for elem in open("todo.txt", "r").readlines()].append([open("todo.txt", "a").write(input(f"Enter item {x+1}: ") + "\n") for x in range(int([x if x.isnumeric() else 0 for x in input("How many things to do: ").split()][0]))]) if x == "A" else print("Command not understood, please try again") for x in input("Read, wipe & write, or append? (R/W/A):").upper()]
@grave rover __getitem__ uses 2 slot pointers. one in tp_as_mapping and one in tp_as_sequence. tp_as_mapping.mp_subscript will be called if it is not null. tp_as_sequence.sq_item will only ever be called if the argument is an integer (and mp_subscript is null)
https://github.com/python/cpython/blob/f0a6fde8827d5d4f7a1c741ab1a8b206b66ffd57/Objects/abstract.c#L150 relevant source is here
str uses unicode_subscript in unicode_object.c
use that class to override py_object at address id(str)+ARCHITECTURE//8 .value
can you just override a built-in pyobject with a custom class?
if you're already taking R, W and A as input, why not .lower() instead of .upper() and pass the input straight to the perms arg of open?
!e ```py
import('ctypes').py_object.from_address(id(...)+8).value=type("yeet",(object,),{'lshift':lambda s,o:print(end=o)or s,'lt':print})
... << "Hello " < "World!"
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
wait that didn't segfault
it usually segfaults if you don't set its __del__ attribute to a function that restores builtins to their original state :/
@simple crystal I bet you didn't know
... << "Hello " < "World!"
could do something in python.
after only one line of initialisation
aight, show me calling print without using brackets
p = type('p', (type,), {'__lt__':print})("p", (), {})
it isnt quite that simple
that's a lot of brackets
!e
p = type('p', (type,), {'__lt__':print})("p", (), {})
p < 'eyyy no brackets ehhh'
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
eyyy no brackets ehhh
if you had done pip install cursedutils==4.2.0 or are on my pc you could
from cursedutils.iostreams import *
cout << "Hello World!"
well yeah but cursedutils probably has to call somethin
p = type('p', (type,), {'__lt__':print})("p", (), {})
p < 'eyyy no brackets ehhh'
is a lot of brackets
you can import p from whatever module has p = type('p', (type,), {'__lt__':print})("p", (), {}) in it
that's 12 brackets
how many brackets in your iostream module?
there's a way to print hello world no imports 0 brakcets
characters 32, 40, and 41 are forbidden
oh you can use []
neh, i'll forbid those as well
bruh i was having fun here
i know you know the answer
oh whoops
no
sigh of relief
@rugged sparrow come join the fun
@simple crystal chilaxin just casually did it in pure python.
while you looked away for a moment or whatever you were doing
I give up haha how is it done?
bruh don't give up
you've only been at it for 15 minutes
keep trying
think of how to call methods without using brackets
!e like for example
a = 3 + 4 # <- this
print (a) #calls
b = 3 .__add__(4)#this
print(b)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 7
002 | 7
so + is a shortcut to call __add__ method of something
so you want a... shortcut to call print
@simple crystal you legit quit?
dunder is just one way to call a method or function
not the only way
think of other ways
i'll give you a clue: it is not backwards compatible.
i.e. python 3.9 +
okay i'll drop a massive clue, have you ever worked with discord bots?
dm me
oh wait
yeah you just need to make a statement with an equals sign beforehand
wait you just want to print without brackets?
And without imports.
a callable that takes a single paramater
that implementation would need a meta class
Can you think of a way to turn that into a hello world?
!e
@print
class b:
__str__='hello world'```
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
<class '__main__.b'>
idk
that would be overkill
Can I show one way ๐ฉ
!e```py
a=lambda x:'hello world'
@print
@a
class b:
...
idk where bot went but I got it
that uses 2 brackets
lol
and using those chars specificially was disallowed
yes
!e py @print @lambda c:c.__name__ class hello_world:pass
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
hello_world
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
hello world
there
they asked for hello world not hello_world :p
but thanks I learned somethin
you still have four spaces
can you use __import__ ?
that is import
nah
print does importing
!e
@print
@lambda b: b.a
class b:
a = 'hello world'
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
hello world
!e
@__import__
@lambda c:c.__name__
class __hello__:...
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
Hello world!
i had to look up what char brackets were i already knew ' '==chr(32)
i said brackets and spaces
!e ```py
@print
@lambda :.doc
class _:"""Hello World!"""
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
no you didn't
but that's 2 spaces
i later forbade spaces as well
instantiating a whole ellipsis without using smh
what lol
@print
@lambda _:_.__doc__
class _:"""Hello World!"""
Is far more elegant.
but it has 2 spaces
true...
hold up __doc__ is a thing?
I can get it to one space but that's it
dammit now i gotta thonk of a way to make class without space
@print
@lambda*_:_[0].__doc__
class _:"""Hello World!"""
just need to make the class without space
you cant
ah but that uses square brakcets
square brackets still brackets
although for backwards compatibility probably do
pipe=lambda _:_.__doc__
@print
@pipe
class _:"Hello World!"
but you need a space after keywords unless you use a character that isn't legal in names
but then you'll need to use square brackets to undo the packing
really
by tacking stuff onto the challenge you made it impossible lol
the clue is in the name "square brackets"
@floral meteor your challenge is impossible without spaces
aight, minimal spaces then
Backslash escapes without a letter just do hex escapes I believe.
!e print('\20')
!e py @print @lambda*_:"hello\32world" class _:pass
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
helloworld
1 space
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
do {} count?
they are "squiggle brackets"
@floral meteor :warning: Your eval job has completed with return code 0.
gottim
Can't you just do```py
@print
@lambda a:"Hello,\x20World!"
class a:0
!e ```py
@print
@lambda :.doc
class _:"""Hello\x20World!"""
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
No spaces, only tabs.
!e print("\t")
@floral meteor :warning: Your eval job has completed with return code 0.
that prints four spaces :/
!e ```py
@print
@lambda :.doc
class _:"""Hello\x20World!"""
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
bruh, discord replaces all \t with \x20\x20\x20\x20
lol tab is a good point
i'm gonna try to make code that does the same thing in both python and brainfuck
for my own sanity, i wont include the initialisation
cant u do type() or does that not work with decorators
it would be great if decorators worked for expressions
!e py @print @lambda*_:"hello\32world" type("",(),{...})()
@toxic jewel :x: Your eval job has completed with return code 1.
001 | File "<string>", line 3
002 | type("",(),{...})()
003 | ^
004 | SyntaxError: invalid syntax
suques
!e i hate when this raises error
@print
"""Hello\x20World"""
@floral meteor :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | """Hello\x20World"""
003 | ^
004 | SyntaxError: invalid syntax
you see? That shouldn't raise syntax error. that should pass the triple-quoted string to the decorator
triple-quoted strings should be decoratable
why would they be tho?
if that doesn't happen in 3.10 or 3.11 i will riot
it wont happen
decorators are meant for special constructs like functions and classes
i'll email the devs snippets of code from this channel to torture them
!e py @print @lambda*_:"hello\32world" lambda:...
@toxic jewel :x: Your eval job has completed with return code 1.
001 | File "<string>", line 3
002 | lambda:...
003 | ^
004 | SyntaxError: invalid syntax
kinda cringe
python 4 will intentionally be designed to avoid what happens here
I will still hack it to make esoteric python4 code
introducing python4:
patched some "bugs" (type classes, anything lambda related, true being the same as one, anything an esoteric coder would find interesting)
new print: cout << "Hello, World!";
here, a cheating program:
#coding:unicode-escape
@print
@lambda*_:'hello,\32world!'
class\x20_:...
interesting
!e ```py
#coding:unicode-escape
@print
@lambda*:'Hello,\32world!'
class\x20:0
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
Hello,world!
nice
Cool
!e ```py
#coding:unicode-escape
@print\x0a@lambda*:'Hello,\x20world!'\x0aclass\x20:0
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello, world!
So if i set mp_subscript and sq_item to NULL and set tp_dict[getitem] to a py func, would that work?
@grave rover no because there needs to be a slot func that grabs __getitem__ from tp_dict
the default slot funcs for normal classes work
so you can make a class like py class Foo: __getitem__ = None then grab its mp_subscript and sq_item slot func addresses and set them in the target class
then add your custom __getitem__ to the target class tp_dict
then call pythonapi.PyType_Modified(cls) on the target class (or reimplement it, it just recursively toggles a bit-flag)
But mp_subscript needs to be a funcptr, no?
Or does that get taken care of by how it's called
mp_subscript does need to be a func pointer
you just grab mp_subscript from Foo and set that value on target
my fishhook library on pypi does all of it automatically
This is why we can't have nice things as PEP614 
https://paste.pythondiscord.com/locisenola.py here is my module that basically does what fishhook does but only to __getitem__, __setitem__, __mul__, and __add__ for lists
it also copies the structs with the dunder pointers to allocated memory cuz chilaxan said to ensure they didn't deallocate
might help to see it all in front of you cuz it took me a long time to decode what fishhook does haha
the problem is that I can't find that on a python-defined class, it's just null
for mp_subscript you need to get void pointer to id of class plus 14*size_of_ssize_t to get to the mapping methods pointer
then get a pointer to the value of that pointer plus 1*size_of_ssize_t for mp_subscript
heap_tp_as_mapping = c_void_p.from_address(id(YOUR_CLASS_HERE) + 14 * size_of_ssize_t)
then heap_mp_subscript = c_void_p.from_address(heap_tp_as_mapping.value + 1 * size_ssize_t)
I mean I have that implemented already
ah
class Test:
def __getitem__(self, item):
return item
print("mp_ass_subscript ptr:", get_view(id(Test), CPyTypeObject.instance()).tp_as_mapping.mp_ass_subscript)
this prints 0
binaryfunc is just a C function pointer type
ohhhh
but Test.__getitem__ is a CPyFunction iirc
I don't think a heap class dunder is actually pointed to there
I think I found them a few ssize_ts from the head of the struct for some reason?
Working on mapping out the entire thing (R is interpreted as P when it comes to size/alignment)
well i did seem to miss tp_as_sequence but that's fixed now
I'll be honest I have no clue what pointers are set to what in that giant blob of code lol
it's pretty daunting lol
any clue as to getting ctypes to not hang when attempting to cast random stuff?
would be nice to brute force explore but it's impossible with a loop cuz of that
I feel like there's something wrong in my typedef, I'm having issues where tp_dict holds the value of tp_base, hmm
could like, store current value being used and terminate program externally if it runs too long without output
restart with next value to test
I assume it's just runnin wild in memory trying to find an end
and that's why it ruins everything
ยฏ_(ใ)_/ยฏ
str_dict = CPyObject.by_reference(x_as_pyascii.ob_type.tp_dict)
print("mp_ass_subscript ptr:", str_dict)
str_dict["__getitem__"] = print
pythonapi.PyType_Modified(py_object(str))
print("abcdef"[1:6])
``` so what pointers here do I need to change for this to work
print(str.__getitem__) gives print, so I'm not sure what else to change
ur gettin dict 2 slots from the id of the __dict__ right
what do you mean?
the actual dict of a built-in is usually 2 slots from the id
str_dict is of type dict, not the mappingproxy
oh
oh did you create a mapping struct for strings?
seems like they'd use sequence
or rather for whatever string typeobject you're dealing with
I'm gonna go to sleep, good luck
I didn't, but i don't think that matters does it?
Or do i have to set the existing pointer to null
oh wait I see what chilaxan meant now
class Dummy:
def __getitem__(self, item):
return None
dummy = get_view(id(Dummy), CPyTypeObject.instance())
x_as_pyascii.ob_type.tp_as_mapping.mp_subscript = dummy.tp_as_mapping.mp_subscript # Set str getitem handler to one that uses __getitem__
str_dict = CPyObject.by_reference(x_as_pyascii.ob_type.tp_dict)
str_dict["__getitem__"] = print # Set __getitem__ to print
pythonapi.PyType_Modified(py_object(str)) # Handle changes
"abcdef"[1:4:2] # this now prints slice(1, 4, 2)
``` @rugged sparrow ty, works now ๐
!e print((globals().__getattribute__('__getattribute__').__class__.__name__[4]).__add__(__import__('sys').stderr.mode.__str__()).__add__(globals().__getattribute__('__getattribute__').__class__.__name__[4]))
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
owo
using __getattribute__ to __getattribute__ :troll:
getattr better
!e Not very impressive, but I turned a for loop into a while loop
class While:
def __init__(self,cond):self.cond=cond
def __iter__(self):
while eval(self.cond):yield
x = 10
for _ in While(' x > 0 '):
print(x)
x+=~0
@drifting grove :white_check_mark: Your eval job has completed with return code 0.
001 | 10
002 | 9
003 | 8
004 | 7
005 | 6
006 | 5
007 | 4
008 | 3
009 | 2
010 | 1
x = 10
for _ in iter(lambda: x > 0, False):
print(x)
x+=~0
``` is also an option
!e [x for x in iter(lambda: ..., 0)]
lamda
lambda
@sudden willow :warning: Your eval job timed out or ran out of memory.
[No output]
infinite for loop
That option is probably better, but it does not use eval, and eval is the best thing ever
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
uwu
why use .get if you just error when you get None anyway?
no
i was not aware there was a difference
{}['a'] will raise a KeyError, {}.get('a') returns None
keyerror is harder to compensate for in one line
yes, but u.get("uwu")() just errors with None anyway
although i think u can check beforehand
i used something like print("not in dict") if 'a' not in {} else stuff
i think you can use callable() too
generally, you want to do ```py
u.get(key, default)
gotta find my old esoteric command line brb
nvm its on another repl
probably could do this way better now
Awesome, glad to see you figured it out
!e I did a for loop. You can't nest it unfortunately, but I'm too tired to come up with a better way.
_For = [0,0,None]
class For:
def __init__(self,iter,var=None):
global _For
if var != None:
_For[2] = var
_For[1] = list(iter)
def __bool__(self):
global _For
if _For[0] < len(_For[1]):
if _For[2] != None:
globals().update({_For[2]: _For[1][_For[0]]})
_For[0]+=1
return True
else:
_For = [0,0,'']
return False
# The 'i' can be left out to not use a variable
while For(range(10),'i'):
print(i)
@drifting grove :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
I made my own "language" type thingy with Python that also had loops
this was the syntax lol py Loop() @ (lambda x=0: (x, x < len(numbers), x + 1)) & inherits( {"Loop": Loop, "numbers": numbers, "hashMap": hashMap} ) > ( "code", "here" )
it's a language dedicated to mocking Java :)
here's the code for that: https://paste.pythondiscord.com/nemaparixo.py
while cond: body can also be done like f = lambda: (not cond) or (body(), f()) iirc
oh yea @grave rover the benefit of stealing the func pointer from a python class instead of just using CFUNCTYPE is that the func you grabbed handles exceptions correctly
Oh neat
it also means you can modify the behavior of base classes in pure python (no imports) because you only need memory r/w
str.tp_base = int?
doesnt seem to do anything
@grave rover does your code only use /proc to access python's memory?
from discord import Embed as numpy; _FormATTedstats_onELine= lambda p ,s : numpy ( title= f"{p.name_clean}'s stats!" , type ='rich' ,color= gconf .DUE_COLOUR) . add_field ( name= 'Stats:', value= '\n' . join ( [ "%s: %s"%t for t in( zip ( list (s. keys( ) ) ,[ getattr (p,a ,s[ a] )for a in s] ) ) ] ) )
@nocturne saddle
Why are you importing embed as numpy 
because why not?
its possible to get r/w memory that is cross platform without imports tho
rn my code abuses LOAD_CONST to make arbitrary pyobjects
same
so i can make a memoryview that points from 0 -> MAX 64bit int
thats a lot of memory
^ relevant code is there
is the load_const thing a bug or feature
i make the custom memory view by first making a bytearray object that points from 0 to max int then turn it into a memoryview so i can use getmem to request subsections
@autumn saffron it is due to an optimization, inside the LOAD_CONST bytecode there is no bounds checking
i also use a second smaller bug in EXTENDED_ARG to overflow oparg to negative if needed
definitely a bug
ok so it might be fixed later on?
its unlikely to be fixed
And is memoryview readable like a file?
why? is the optimization that big?
i dont think so, but you can use it with io classes or make a fake file class
Hmm
yes because they just index the items directly with the oparg
Meh, screw windows anyways
/proc doesnt exist on darwin either
Screw darwin
you could also make a fake file object that maps into ram (which is what procfs does i think)
that would be trickier tho
why are you so adamant about it being a file object?
Because rewriting everything right now to use a bytearray would not be a fun experience
fair enough
A lot of my code relies on the file object keeping track of the current position and only using offsets, that way i don't have to seek for everything
Basically the only time I seek is when i get the address of an object to create a view of
ah
one sec i think there is a way to interpret memory as a file
@grave rover io.BytesIO for some reason creates a copy of the passed in buffer
well yeah because otherwise you could very easily break stuff
Yeah but it should be using the buffer interface
Because if it did that you could pass in any buffer like object and it would just work
True
@grave rover what methods do you actually use on the file object
cause you could just make a shim class
is this available on pypi?
not yet
its sorta just my random code github
prob wont go on pypi
@frozen garnet not a help channel
Iโm sorry, where can I go ?
Thanks
@rugged sparrow why do you hardcode using LE instead of native byteorder?
Also, is that _=memory_backing needed? I'm trying to just return memory but it seems to segfault
You need to keep a reference to memory backing otherwise it gets freed
Python is little endian on most if not all sensible systems
ah
safest to just use sys.byteorder tho
I'll just increase ob_refcnt by 1
SSIZE_T = (TUPLE_HEADER - PTR_SIZE) // 2 # TUPLE_HEADER = nPn -> n = (TUPLE_HEADER - PTR_SIZE) / 2
...
backing_addr = id(memory_backing)
memory[backing_addr:backing_addr+SSIZE_T] = (2).to_bytes(SSIZE_T, sys.byteorder) # Prevent GC
return memory
That requires an import tho
fair enough
but yeah you can use the rest of that snippet to prevent having to make a nested function for keeping a reference
Yes but I prefer to have it be referenced properly somewhere in case I need to do cleanup
Found a way to do it with memoryviews I think
oh?
'little' if memoryview(bytes([1,0])).cast('h')[0]==1 else 'big'```
that is so nasty I love it
Afaik .cast defaults to native endian
I don't have any big endian stuff rn to test tho
@grave rover the technical reason why you need to hold onto memory_backing is because it contains the memory that supports memory. so it looks like this in memory <memory_backing:Bytes_Header, <memory:ByteArray_Header, ByteArray_Data>>
so if memory_backing gets freed, it corrupts our fake bytearray memory
I see
hey
I'm trying to get this to work: ```py
return True if all(for r in range(rl) for c in range(cl) if k:=r-c in m (if m[k] != matrix[r][c] else m[k] = matrix[r][c])) else False
basically, it returns True if the dict m always contains the same value for the key, false otherwise
Trying to solve https://leetcode.com/problems/toeplitz-matrix/ in one line
Anyone have a tip how I can get it to work?
class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
rl, cl, m = len(matrix), len(matrix[0]), {}
for r in range(rl):
for c in range(cl):
if k:=r-c in m:
if m[k] != matrix[r][c]:
return False
else:
m[k] = matrix[r][c]``` Basically trying to get this to one line
cry
Is it possible to assign and evalulate a function in the same statement? Trying to abuse conditional eval for if-statement like behavior.
something like
not conditional or t = funct()
return t
I am not sure what the correct syntax would be
Nya?
or will only evaluate the right side if the left side is false
do you need :=
U mean if if not conditional or (t:=funct()) ?
I will test that, thanks
it works, awesome :D
def ifstatement(conditional, funct):
not conditional or (t:= funct())
try:
return t
except NameError:
return None
# testing
def abc():
return "abc"
a = ifstatement(True, abc)
print(a)
What is esoteric pyth
anything you shouldn't do in code other people are helping to maintain
Unless you don't want to be allowed to maintain it anymore
!e py ifstatement = lambda cond, func:(cond or None) and func() def abc(): return 'abc' print(ifstatement(True, abc))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
abc
@final night ^ that is a more concise version
if cond is Falsey, it returns None, otherwise it returns func()
@hollow rover
Hello
hi
Next i'm trying to figure out how to abuse use conditional execution to simulate an if-else statement
Is there a concise way to write this sort of statement?
True and (True;print("1")) or print("2")
I could wrap print in a lambda statement but I sorta want to avoid having to do that every time
Essentially if the statement is true, we eval the first one
otherwise we eval the second
hmm I wonder if I could use an or
oh hey, yeah, that totally works :D
this is pretty cool
(not True or print("1")) and print("2")
now I just need to re-order the operations so it doesn't need parens, if possible
I bet I could chain these together
True and not print("1") or print("2")?
I'll test it
(It evaluates to True sometimes.)
that one works, yeah
looks a lot nicer too
actually, that only works for functions that eval to false, bummer
so print works but
a lot won't work
the original one (with the ugly parens) works pretty well with chaining
check this out
v1 = "a"
(not v1 == "a" or print("a")) and (not v1 == "b" or print("b")) and print("?")
v1 = "b"
(not v1 == "a" or print("a")) and (not v1 == "b" or print("b")) and print("?")
v1 = "c"
(not v1 == "a" or print("a")) and (not v1 == "b" or print("b")) and print("?")
a
b
c
You can get rid of the not if they evaluate to True.
that's a good point
If you really want to discard a value, you can do (0,func(),)[0].
I'm just being oddly specific about trying to get this to work with any function, when in practicality it doesn't really matter
XD
Or I expect (func(),1)[1] would look better because you can remove the not.
ah, nice
If you do that to both functions, you could tack and None on the end to make the final expression always evaluate to None.
Fun
@grave rover shorter -> ENDIAN = ['little','big'][1%memoryview(b'\1\0').cast('h')[0]]

wait why not flip the two so you don't have to do 1%
oh wait nvm im dumb
wait yeah you can cast it to b and use ['big','little'][memoryview(b'\1\0').cast('b')[0]]
or wait
nvm I'm dumb
yeah I'm not have smart
theres no tutorial on it because its just a bunch of tips and tricks you learn over time
By lurking in this channel ๐
i learnt by lurking
its very stressful trying to get your esoteric code right but when you get it it feels amazing
esoteric python feels like brainfuck
!e print((globals().get(__name__)).__str__()[1]+((__import__("sys").stderr.mode).__str__())+(globals().get(__name__).__str__()[1]))
@toxic jewel :white_check_mark: Your eval job has completed with return code 0.
owo
@toxic jewel :white_check_mark: Your eval job has completed with return code 0.
dict_values(['__main__', None, None, <class '_frozen_importlib.BuiltinImporter'>, None, {}, <module 'builtins' (built-in)>])
!e
v = [x for x in globals().values()]
print(v.__len__().__bool__())```
@toxic jewel :white_check_mark: Your eval job has completed with return code 0.
True
lolmao
wait
!e __import__("sys").stdout.write((globals().get(__name__)).__str__()[[x for x in globals().values()].__len__().__bool__()].__add__(((__import__("sys").stderr.mode).__str__()).__add__((globals().get(__name__).__str__()[[x for x in globals().values()].__len__().__bool__()]))))
@toxic jewel :white_check_mark: Your eval job has completed with return code 0.
owo
Tip: sys.__stdout__ is a thing
im aware
