#esoteric-python
1 messages · Page 110 of 1
@fluid tree __class__ doesnt exist in the upper scope in a typical way. Its added here if it is explicitly requested (by super or manually) https://github.com/python/cpython/blob/a81fca6ec8e0f748f8eafa12fb12cf9e12df465c/Python/compile.c#L588
the closure is only added if __class__ is requested inside of a class method
!e py class A: print(__class__)
@rugged sparrow :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 2, in A
004 | NameError: name '__class__' is not defined
^ this fails because of that
!e py class A: def __init__(self): print(__class__) A()
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
<class '__main__.A'>
due to this being done by the compiler like this, it means that classes constructed using metaclass(name, bases, namespace) cannot use the "magic" __class__ variable without needing extra work
self.__class__ can be a subclass of the class you are defining
__class__ will always be the class you are defining
Afaik that constucts a synthetic reference to it. It doesn't actually implement the class at the class level
I know
it tells python to add a closure there. the actual __class__ closure is filled inside __built_class__ i believe
look at the channel description
Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness
s=lambda a:lambda b:lambda c:a(c)(b(c));k=lambda a:lambda b:a;factorial=lambda a:s(s(s(s(k)(k))(k(s(s(k(s(s(k(s))(s(k(k))(s(k(s))(s(k(s(s(k)(k))))(k)))))(k(k))))(s(s(k(s(s(k(s))(s(s(k(s))(k))(k(s(s(k)(k))(k(s(s(k(s))(s(k(s(k(s))))(s(k(k)))))(k(s(k)(k)))))))))(k(k(k(s(k)(k)))))))(s(s(k)(k))(k(k))))(s(s(k)(k))(k(k(s(k)(k)))))))(s(k(s(s(k(s))(s(k(s(k(s))))(s(k(k)))))(k(s(k)(k)))))(s(s(k)(k))(k(k(s(k)(k)))))))))(k(s(s(s(k)(k))(k(s(k)(k))))(k(s(k)(k))))))(k(k))((lambda a:a(a))(lambda a:lambda b:(lambda c:lambda d:a(a)(b-1)(c)(c(d)))if b else lambda a:lambda a:a)(a))(lambda a:a+1)(0)```
aside from failing on anything >= 6, this is a completely valid and working definition of factorial
"Failing" as in slow
I joined chat and saw this....
wtf is this......

HOW DO YOU SAY HELLO WORLD
last time i tried that I got this instead:
~~~~~~~~~~~[, , , , , , , , , , ]
That's because you didn't make a closure that time.
ik
So I was doing my usual esoterically making cool stuffs, but then this random line is giving me IndexError for no reason so I decided to use that as an extra random factor to change the colour instead of trying to debug it.
import os,sys;os.system('')
green_resmon=__import__('hexspam').print_green
def _init():
w = os.get_terminal_size()[0]
from random import randint as r
a = [r(0,1)*r(0,1)*r(0,1)*r(0,1)for _ in range(w)]
from functools import reduce
return locals()
@lambda f:lambda:f(_init())
def matrix(__l):
print(__l)
a,r,reduce=__l['a'],__l['r'],__l['reduce']
while w:=os.get_terminal_size()[0]:
w>len(a)and a.extend([r(0,1)*r(0,1)*r(0,1)*r(0,1)for _ in range(w-len(a)+1)])
w<len(a)and(a:=a[:w])
try:
if reduce(int.__mul__,[r(0,3)for i in range(w//16)]):a[r(0,w)]=r(0,1)*r(0,1)*r(0,1)*r(0,1)
except:print(f'\x1b[{r(30,37)}')
@print
@lambda f:''.join([chr(f(a,i))for i in range(w)])
def s(a,i):return r(33,127)if a[i]else 32
if __name__=='__main__':
try:matrix()
finally:print('\x1b[0m')
Which line?
The one where reduce is used
But it hasn't changed colour for a long time now
Also that script occasionally has a line that's just... out of place
also, when i make the window smaller, it goes faster
oh cool it turned purple now
It because random.randint is inclusive.
When random.randint(0, w) chooses w, that's outside of a, which has length w.
Thank you it works beautifully now
can someone help me with this program
since you asked in the esoteric python channel...
!e ```py
{print(f"the cube root of {a} is {a**3}")for c in iter(lambda a=int(input('Enter a positive number, or a negative to quit')):a<0,True)}
that should work @olive stag
was i supposed to ask in a different channel i don’t understand this or discord 😭
no, "failing" as in you get a recursionerror
That counts
no it doesn't
there is python syntax \ which indicates that a statement is continued on the next line, but is there syntax to indicate that a statement should be broken up to two lines?
print(1) | print(2)
_______outputs_______
>1
>2
;
If you increase the recursion limit
There's ; but it never played well with indent for me. If you need to put a lot of stuff on one line, use esoteric python.
What is the least used keyword in python? 
I use and like lambda 
there are very few cases for lambda
But yeah, nonlocal is unusual
I would say nonlocal is used much less than lambda
__peg_parser__ is, __debug__ is a bit more questionable, but since it isn't a variable name, I would call it a keyword
!e py import keyword print(keyword.kwlist)
@tribal moon :white_check_mark: Your eval job has completed with return code 0.
['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
does __peg_parser__ do anything except raising a SyntaxError?
Don't think so
Surely if False None and True are keywords so is debug
well, obj.__debug__ is possible, but obj.None isn't
it also isn't in keywords.kwlist
Well we can't judge keywords that way 👀
idk if right place for this, but anyone have experience with monad libraries in python? most fleshed out one i could find is returns https://github.com/dry-python/returns/blob/master/README.md. Particularly interested in Final Tagless or Effect Handler approaches, only thing ive found in that vein is python-effect
Looks very rust like
Counter({'def': 2469801,
'None': 2079423,
'if': 1952145,
'return': 1535357,
'import': 1264292,
'from': 900304,
'in': 900118,
'True': 734511,
'not': 714855,
'assert': 566377,
'False': 560890,
'for': 559342,
'is': 539126,
'else': 493987,
'class': 473044,
'raise': 328813,
'as': 273045,
'and': 262468,
'with': 217100,
'elif': 205600,
'try': 201381,
'except': 198135,
'or': 166449,
'pass': 123573,
'lambda': 86972,
'await': 83763,
'async': 73891,
'yield': 51696,
'while': 39673,
'continue': 39332,
'break': 32802,
'del': 31962,
'finally': 19407,
'global': 7115,
'nonlocal': 775})
aggregated results from a couple thousand python projects
In case of anyone curious, this is the script: https://github.com/isidentical/snippets/blob/master/most_used_keyword.py
'async': 73891,
I wonder if it's disproportionately discord.py projects 😅
Of course lol
Yay I was right about nonlocal
Surprised that they're more awaits than async
plus, async iterators and context managers are far less common
why would there be more asyncs than awaits
you would need to have a large number of async functions with no awaits in them
enough to balance out the many, many async functions that will contain multiple awaits
(well, empty async functions and also async for/async with since i think those exist, but they're not going to be ridiculously common)
apis
What does nonlocal do?
Allow for closures
https://youtu.be/E9wS6LdXM8Y I thought explained it quite well when
Speaker: Thomas Ballinger
What are closures all about anyway, and why is there a new keyword in Python
3?
We'll look at what a closure is, their history in the Python language, what
the Python 3 nonlocal keyword is about, and examine how closures are
idiomatically used (and avoided) in Python.
Slides can be found at: https://speakerdeck.com/py...
closures that assign variables in their environment, specifically - I think closures in general are any functions that can capture their environment, and in Python any function can do that
Edit: I used default kwarg to eliminate the need to init a
In this channel we use lambda more often than we drink water
!e
import *
@simple crystal :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | import *
003 | ^
004 | SyntaxError: invalid syntax
That can be a project.
lol yes
someone in another server gave a good solution
import pkgutil
for module in [mod[1] for mod in pkgutil.iter_modules()][1:]:
__import__(module)
!e
import pkgutil
for module in [mod[1] for mod in pkgutil.iter_modules()][1:]:
__import__(module)
@simple crystal :warning: Your eval job timed out or ran out of memory.
[No output]
@fossil estuary :white_check_mark: Your eval job has completed with return code 0.
123,456,789
...what does comma do to format specifier?
ohhhh thousands seperator
!e
x=123456789
print(f"{x:_}")
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
123_456_789
!e
x=123456789
print(f"{x:_x}")
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
75b_cd15
@fossil estuary :white_check_mark: Your eval job has completed with return code 0.
75bcd15
Well, that's a good feature.
I started work on a guide for all of the stuff we talk about in this channel. Please feel free to write things for it. https://github.com/IFcoltransG/esoteric-python-guide/wiki
object.__format__(self, format_spec)```
Called by the [`format()`](../library/functions.html#format "format") built-in function, and by extension, evaluation of [formatted string literals](lexical_analysis.html#f-strings) and the [`str.format()`](../library/stdtypes.html#str.format "str.format") method, to produce a “formatted” string representation of an object. The *format\_spec* argument is a string that contains a description of the formatting options desired. The interpretation of the *format\_spec* argument is up to the type implementing [`__format__()`](#object.__format__ "object.__format__"), however most classes will either delegate formatting to one of the built-in types, or use a similar formatting option syntax.
See [Format Specification Mini-Language](../library/string.html#formatspec) for a description of the standard formatting syntax.
The return value must be a string object.... [read more](https://docs.python.org/3/reference/datamodel.html#object.__format__)
Yep
oh, why
been learning javascript past couple days and damn if it doesn't allow for some esoteric ridiculous stuff except some of it actually get used in production code apparently lol
being pythonic is for nerds
Why you have so many lines?
```py
Post it in a code block and I'll show you unpythonic
```
async def sendAll(s):
global MODE, STRIP_COLOR, SPEED, SEG_COUNT
s = s.replace(' ', '').lower().replace('staticrgb', 'staticRGB').replace('rgb', 'RGB').replace('setspeed', 'setSpeed')
DNIDH = {i[1]['name'].lower(): i[1]["websocket"] for i in clients.items() if "name" in i[1]}
keyList = list(DNIDH.keys())
for i in s.split(';'):
j = [t.split(',') for t in i.split('>')]
if len(j) == 1: j = [keyList + ["room"], j[0]] #Set to all devices if none are given
for a in j[1]:
if a.startswith("#"): a = "RGB|"+'|'.join(str(int(a[h+1:h+3], 16)) for h in range(0, 6, 2)) #Hex to RGB
for d in j[0]:
if d in keyList:
await DNIDH[d].send(a)
elif d == "room": #process room LEDs
if a in ["white", "rainbow", "staticRGB", "off"]:
MODE = a
elif a.startswith("RGB"):
MODE = "RGB"
STRIP_COLOR = [int(c) for c in a.split('|')[1:]]
elif a.startswith("setSpeed"):
SPEED = float(a.split('|')[1])
i mean yea i could technically make this like, 3 lines (excluding the multiline ; trick)
but this is actual code im using and wrote not as a meme
@floral meteor
well
i have a bunch of ESP32 LED drivers for various LED devices around my room
and i have a strip directly connected to the PI
being ran in another thread
i could make that strip connect to the websocket server and make a conversion layer and make it cleaner but i can't be bothered
why do you have space around your operators and after brackets?
?
i mean, i didn't design this code to be compressed or anything
i made it to work, just my style is super stream of consiouness so it ended up looking like this
__69__ = {'MODE':MODE,'STRIP_COLOR':STRIP_COLOR,'SPEED':SPEED,'SEG_COUNT':SEG_COUNT}
async def sendAll(s):
global __69__;s=s.replace(' ',str()).lower().replace('staticrgb', 'staticRGB').replace('rgb', 'RGB').replace('setspeed', 'setSpeed');__={'DNIDH':{i[1]['name'].lower():i[1]["websocket"]for i in clients.items()if"name"in i[1]},'keyList':list(__['DNIDH'].keys())}
for i in s.split(';'):
j=[t.split(',')for t in i.split('>')]
if len(j)==1:j=[__['keyList']+["room"],j[0]]
for a in j[1]:
if a[0]=="#":a="RGB|"+'|'.join(str(int(a[h+1:h+3],16))for h in range(0,6,2))
for d in j[0]:
if d in __['keyList']:await __['DNIDH'][d].send(a)
elif d=="room":
if a in["white","rainbow","staticRGB","off"]:__69__|={'MODE':a}
elif a[:3]="RGB":__69__|={'MODE':"RGB",'STRIP_COLOR':[int(c)for c in a.split('|')[1:]]}
else:a.startswith("setSpeed")and __69__.update({'SPEED':float(a.split('|')[1])})
beautiful
y tho lol
i didn't even use walrii
yea i would use walrus
alright i'll edit it
I used dunder 69 as a variable, are you proud?
proud isn't the word
args = [a for group in args.split('|') if len(a:=[b for command in group.split(',') if len(b:=(((([g[0], g[1] if par[g[0]][0] == S else (float(('-' if g[1][0] == '-' else '') + d) if len(str(d:=(re.sub(r"([^0-9.])", '', g[1]).replace('.', '', max(0, (g[1]).count('.') - 1))))) > 0 else 1)]) if len(c) > 1 else [g[0], 'true' if par[g[0]][0] == S else 1.0])) if len(c) > 0 and (par[g[0]][0] == S or g[-1] != "false") else []) if len(g:=(c if ((c:=[(r.strip()) for r in (command.split('=', 1) if '=' in command else command.split(' ', 1))])[0] in par) else (([bind[c[0]], c[1]] if len(c) > 1 else [bind[c[0]]]) if (c[0] in bind) else []))) > 0 else []) > 0]) > 0][:3]```
here it is
heres the note that went with it:
#splts by '|', splits by ',', splits by '=' if '=' is in it, otherwise split by ' ', strip those, exit those args if any of those args are 'false', make sure args[0] (the filter name) is in the filter list, if that filter value is a float, turn it into a float by removing all but the last '.'. If any of the created lists have a length of 0, don't add it (applys to all layers)
! ! CEO — Today at 11:19 AM
__69__ = {'MODE':MODE,'STRIP_COLOR':STRIP_COLOR,'SPEED':SPEED,'SEG_COUNT':SEG_COUNT}
async def sendAll(s):
global __69__;s=s.replace(' ',str()).lower().replace('staticrgb', 'staticRGB').replace('rgb', 'RGB').replace('setspeed', 'setSpeed');__={'DNIDH':{i[1]['name'].lower():i[1]["websocket"]for i in clients.items()if"name"in i[1]},'keyList':list(__['DNIDH'].keys())}
for i in s.split(';'):
len((j:=[t.split(',')for t in i.split('>')]))==1and(j:=[__['keyList']+["room"],j[0]])
for a in j[1]:
a[0]=="#"and(a:="RGB|".__add__('|'.join(str(int(a[h+1:h+3],16))for h in range(0,6,2))))
for d in j[0]:
d in __['keyList']and await __['DNIDH'][d].send(a)
elif d=="room":
if a in["white","rainbow","staticRGB","off"]:__69__|={'MODE':a}
elif a[:3]="RGB":__69__|={'MODE':"RGB",'STRIP_COLOR':[int(c)for c in a.split('|')[1:]]}
else:a.startswith("setSpeed")and __69__.update({'SPEED':float(a.split('|')[1])})
using ; to seperate lines is cheating imo
k, you've forced my hand, i will have to traumatise you now
you can just
use a big ass print statment to define and run like everything
print(var1 := "yea", var2 := var1.strip(), await asdfasdf)
something like that
also you can prob avoid global by using globals()
globals()['.']={'MODE':MODE,'STRIP_COLOR':STRIP_COLOR,'SPEED':SPEED,'SEG_COUNT':SEG_COUNT}
async def sendAll(s):
s,__=s.replace(' ',str()).lower().replace('staticrgb', 'staticRGB').replace('rgb', 'RGB').replace('setspeed', 'setSpeed'),{'DNIDH':{i[1]['name'].lower():i[1]["websocket"]for i in clients.items()if"name"in i[1]},'keyList':list(__['DNIDH'].keys())}
for i in s.split(';'):
len((j:=[t.split(',')for t in i.split('>')]))==1and(j:=[__['keyList']+["room"],j[0]])
for a in j[1]:
a[0]=="#"and(a:="RGB|".__add__('|'.join(str(int(a[h+1:h+3],16))for h in range(0,6,2))))
for d in j[0]:
d in __['keyList']and await __['DNIDH'][d].send(a)
if d not in __['keylist']and d=="room":
if a in["white","rainbow","staticRGB","off"]:globals()['.']|={'MODE':a}
elif a[:3]="RGB":globals()['.']|={'MODE':"RGB",'STRIP_COLOR':[int(c)for c in a.split('|')[1:]]}
else:a.startswith("setSpeed")and globals()['.'].update({'SPEED':float(a.split('|')[1])})
globals().update(globals()['.'])
don't make me import ctypes and hook the ellipsis
why would you need either of those
there, massive indents can go die in a hole
don't make me import ctypes and hook the ellipsis
how would that lower line count
ok how is importing some random stuff insanity tho
you wanna find out?
__import__('ctypes').py_object.from_address(id(...)+8).value=type(str(),(object,),dict(__call__=globals))
...()['.']={'MODE':MODE,'STRIP_COLOR':STRIP_COLOR,'SPEED':SPEED,'SEG_COUNT':SEG_COUNT}
@lambda f:...().update({'sendAll':f})
async def yeet(s):
s,__=s.replace(' ',str()).lower().replace('staticrgb', 'staticRGB').replace('rgb', 'RGB').replace('setspeed', 'setSpeed'),{'DNIDH':{i[1]['name'].lower():i[1]["websocket"]for i in clients.items()if"name"in i[1]},'keyList':list(__['DNIDH'].keys())}
for i in s.split(';'):
len((j:=[t.split(',')for t in i.split('>')]))==1and(j:=[__['keyList']+["room"],j[0]])
for a in j[1]:
a[0]=="#"and(a:="RGB|".__add__('|'.join(str(int(a[h+1:h+3],16))for h in range(0,6,2))))
for d in j[0]:
d in __['keyList']and await __['DNIDH'][d].send(a)
if d not in __['keylist']and d=="room":
if a in["white","rainbow","staticRGB","off"]:...()['.']|={'MODE':a}
elif a[:3]="RGB":...()['.']|={'MODE':"RGB",'STRIP_COLOR':[int(c)for c in a.split('|')[1:]]}
else:a.startswith("setSpeed")and...()['.'].update({'SPEED':float(a.split('|')[1])})
...().update(...()['.'])
wait
explain line 1
like
py_object.from_address(id(...)+8).value=type(str(),(object,),dict(__call__=globals))
that part
or
chilaxin seems to be missing :/
they made a module called fishhook
that's a quick implementation of that module
essentially, I'm telling EllipsisType to go die in a hole, and replacing it with an similar object that has a __call__ attribute, hence making ...() call globals instead of ellipsis
oh
id(yay)+8 is the address of yay's class
now you know where EllipsisType lives, you can go torture them >XD
no
you can't assign to constants, and builtin methods are read-only
hence why you need to fŭck around with addresses
globals is a function
!e you could do
t=globals()
t.update({"2":3})
print(globals()['2']+2)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5
!e but you can't do
t=globals()
t|={'2':3}
print(globals()['2']+2)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5
wait wat
we should make an esoteric team for pyweek
and do the whole thing esoterically XD
@floral meteor the dict returned by globals is mutable
ik, but i thought augmented operator still instantiated a new instance from a merge.
apparantly it calls update instead
!e ```py
f=type("",(),{'iadd':print})()
f += "Hello World!"
f += ...
@floral meteor :x: Your eval job has completed with return code 1.
001 | Hello World!
002 | Traceback (most recent call last):
003 | File "<string>", line 3, in <module>
004 | TypeError: unsupported operand type(s) for +=: 'NoneType' and 'ellipsis'
Yes
@rugged sparrow how do i reset its recursion thingy?
nvm
@floral meteor :warning: Your eval job timed out or ran out of memory.
[No output]
;-;
that'll turn it into a memory bomb won't it?
looks like I'll have to print as I go then
or set a limit
wow it's nomming my cpu only a little bit
!e ```py
a=[0]
@lambda cls:cls(1)
class fibonacci(int):
def repr(s):
a.append(s.class(int.add((lambda i:print(int(i))or i)(a[-2]),a[-1])))
return int.repr(s)
a+=[fibonacci]
print (a) # in console: >>> a
@floral meteor :x: Your eval job has completed with return code 143 (SIGTERM).
001 | 0
002 | 1
003 | 1
004 | 2
005 | 3
006 | 5
007 | 8
008 | 13
009 | 21
010 | 34
011 | 55
... (truncated - too many lines)
Full output: too long to upload
import sys
p=print;s=sum;e=len
l=[s([int,ord][y.isalpha()](y)for y in x)for x in[[x for x in y]for y in sys.argv[1].split(",")]]
if e(l)==2:p(s(l))
elif e(l)==3:p(s(l[:2])*l[2])
else:
_=e(l);p((s(l[:_-2])*l[_-2])//l[_-1])
How can i shorten this down
right, updated it
ok, made it shorter
import sys
p,s=print,sum
l=[s([int,ord][y.isalpha()](y)for y in x)for x in sys.argv[1].split(",")]
_=len(l)
p([0,1,s(l),s(l[:-1])*l[-1]][_]if _<4else(s(l[:_-2])*l[_-2])//l[_-1])
you can do p, s = print, sum cuz semicolons are cheating
yes!
there is nothing like "cheating" in #esoteric-python
semicolons aren't esoteric they are some nerd shit
unless you're stuffing the entire program onto one line there's no excuse, this ain't C++
!e
assert "I" in "VOWELS"
@strange basin :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
!e
assert "I" in "TEAM"
@strange basin :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
Maybe time to go look for a new job ... 😦
it reduces your char count, \n is two chars, while ; is just one.
it's literally a character tho
when you aren't escaping it
calling it "\n" is like calling \ \\
but we call it \n because saying
is a character and
is only one character is unclear since we can't see
I think windows uses two characters for a new line
do you need to escape two characters for a new line in windows?
not when you're writing python
it is autoconverted, but ye, \r\n is the correct sequence
maybe using a semicolon saves disk space?
exactly
but yeah it's been \r\n on windows
though that's changing https://devblogs.microsoft.com/commandline/extended-eol-in-notepad/
as far as I can tell because it's stupid
I mean, literally everything other than unix and mac text files is \r\n
HTTP, most other network protocols
gzipped text files
lol [-6] eh
carriage return makes no sense in most formats imo
I use it to reprint to same console line but \n implies carriage return
why would cursor continue printing where previous line ended?
\n means one column down and \r means return to start of line
on a typewriter, sure
teletypes and terminals also do this
but there's no "word wrap" character
though now there are flags you can set to change how this is handled
one thing unix definitely does right is trailing newline
and those flags are by default set to return to beginning of new line
yeah, since that is how unix decided to do text files
emulating typewriters is all teletypes did
yes and that is now defunct
and carriage return remaisn useful
for returnign to origin ont he same line
I use \r all the time
or a newline on macs
its not about being useful, its about newlines working differently because unix decided they need to be special
it should be about being useful
as in the problem isn't some ascii characters becomes useless
if something isn't useful it's just art
most of the <32 codes are useless
the problem is that there isn't a way to do a newline sequence in ascii that will work on all computers implementing ascii rendering
what computers do we need to worry about that need to produce human readable text that can't handle a newline?
if \n is just vertical to any computer it's a "how quaint" moment
I get that ascii is based on typing stuff but it's far more complex to handle dates correctly and simple computers generally get programmed to do that fine
backwards compatability is a always a concern. And it doesn't seem like an issue until something requires the networking \r\n form, and your editor is really convinced it needs to save \n. Or the fact you now have to keep track of which files are text and which are not text on linux in order to not produce non standard zip archives or incorrect HTTP requests.
I did only run into issues about 3 times, but that 3 more than really should have happened considering there is a standard on this
\n being the standard, right?
\r\n. HTTP, zip, .. all use CRLF
but if backwards compatibility and standards really mattered we wouldn't have two different configurations of friggin usb-c
its really just text files being silly
the networking world agrees on \r\n pretty consistently
so they add an unnecessary character in case an ancient computer has to process text data
yes, you can't change standards
at least not for something as silly as a newline sequence
poor computer would just move the cursor vertically and htere'd be nothing behind the cursor
but it'd be suspended horizontally
what a conundrum
yeah, that is how the character worked when ascii was defined
despite this, we have new ports every second tuesday we're supposed to be able to plug a quarter inch into somehow
standards do change
not networking ones, unless its something really severe
cuz the internet is a gross behemoth but yeah I'm just complaining
but back on topic python files generally can be assumed to just use \n
and that's a visual representation of an escaped single character
ye, python does handle all newline sequences regardless of OS
so yeah, it is definitely possible to codegolf with \n even on windows
the only time I've used semicolons in python is when I try to exec a whole python file and insert ;*code* on lines that can handle that to run that code a bunch
they are useful for golfing since they let you avoid indentation
while 1:print('a');print('b')
!e
while 1:print('a');print('b')
@simple crystal :x: Your eval job has completed with return code 143 (SIGTERM).
001 | a
002 | b
003 | a
004 | b
005 | a
006 | b
007 | a
008 | b
009 | a
010 | b
011 | a
... (truncated - too many lines)
Full output: too long to upload
You can also use a tuple, but that’s longer
I am more impressed by code that avoids the semis, personally
unless it's one line
if it's one line I like semis
more than one line, why bother?
!e
while 1:(print("a"),print("b"))```
onelines without semis are best imo
@thin trout :x: Your eval job has completed with return code 143 (SIGTERM).
001 | a
002 | b
003 | a
004 | b
005 | a
006 | b
007 | a
008 | b
009 | a
010 | b
011 | a
... (truncated - too many lines)
Full output: too long to upload
No semi colon required
yeha agreed
usin tuples like that is good
and you can use ternaries and comprehensions and so on
comprehensions can also be used for local variables
with a walrus?
without walrus
def fib(n):
return max(
d[1]
for d in [{}]
for d[0], d[1] in [(0, 1)]
for _ in range(n)
for d[0], d[1] in [[d[1], d[0] + d[1]]]
)
source: nedbat twitter
oh wow what does for d in [{}] do
oh just iterates once
as a dictionary
I can't tell if this is a good job interview fib solution or it'd make them mad
neat tho
hi
hi
can i get this any shorter?
won't matter, count will remain the same
p([0,1,s(l),s(l[:-1])*l[-1]][_]if _<4else(s(l[:_-2])*l[_-2])//l[_-1])
``` should make it shorter
The 4else part probably raises an error
y.isalpha() might work as y>"9" depending on your goal.
Fun fact it would on micropython
yes that would work!
!e
while not print("a"):print("b")
@viscid nymph :x: Your eval job has completed with return code 143 (SIGTERM).
001 | a
002 | b
003 | a
004 | b
005 | a
006 | b
007 | a
008 | b
009 | a
010 | b
011 | a
... (truncated - too many lines)
Full output: too long to upload
!e
print(len('while not print("a"):print("b")'))
print(len('while 1:(print("a"),print("b"))'))
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
001 | 31
002 | 31
I would say while1
but why does this not work
!e
while1:print('lol')
print('huh')
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
001 | lol
002 | huh
wait nvm
it's just a type hint
class DunderOverload(metaclass=TypeOverload):
def __init__(self, value: int):
self.value = value
def __add__(self, other: int):
print("int")
return self.value + other
def __add__(self, other: str):
print("str")
return self.value + int(other)
def __add__(self, other):
print("Any")
return NotImplemented
inst = DunderOverload(10)
print(inst + 2)
print(inst + "3")
print(inst + [])
int
12
str
13
Any
TypeError: unsupported operand type(s) for +: '__getattribute__' and 'list'```a clean way to overload methods https://paste.pythondiscord.com/epupesecih.py
_=()==()
__=(_+_)+(_+_)
___=((_+_)+(_+_)+(_+_)+(_+_)*(_+_)+(_+_)+(_+_)+(_+_))
____="%c"*(_+_+_+_+_)%(((_+_)*((___*__+(__+__))//(_+_))),((_)*((___*__+(__+__)-(_+_+_)))),((_+_)*((___*__+(__+__)+(__))//(_+_))),((_+_)*((___*__+(__+__)+(__))//(_+_))),((_)*((___*__+(__+__)+(__+_+_+_)))))+" "+"%c"*(_+_+_+_+_)%(((_)*((___*__+(__+__)+(__+__+__+_+_+_)))),((_)*((___*__+(__+__)+(__)+(_+_+_)))),((_+_)*((___*__+(__+__)+(__)+(_+_+_)+(_+_+_))//(_+_))),((_+_)*((___*__+(__+__)+(__))//(_+_))),((_+_)*((___*__+(__+__)-(__))//(_+_))))
print(____)
Anyone here did anything like this?
yea
me
wait a fukn
that prints hello world
doesnt it
I made it, I should know
!e
_=()==()
__=(_+_)+(_+_)
___=((_+_)+(_+_)+(_+_)+(_+_)*(_+_)+(_+_)+(_+_)+(_+_))
____="%c"*(_+_+_+_+_)%(((_+_)*((___*__+(__+__))//(_+_))),((_)*((___*__+(__+__)-(_+_+_)))),((_+_)*((___*__+(__+__)+(__))//(_+_))),((_+_)*((___*__+(__+__)+(__))//(_+_))),((_)*((___*__+(__+__)+(__+_+_+_)))))+" "+"%c"*(_+_+_+_+_)%(((_)*((___*__+(__+__)+(__+__+__+_+_+_)))),((_)*((___*__+(__+__)+(__)+(_+_+_)))),((_+_)*((___*__+(__+__)+(__)+(_+_+_)+(_+_+_))//(_+_))),((_+_)*((___*__+(__+__)+(__))//(_+_))),((_+_)*((___*__+(__+__)-(__))//(_+_))))
print(____)
@fossil estuary :white_check_mark: Your eval job has completed with return code 0.
HELLO WORLD
Oh
🙃 lol
Lol ik
My physics test is in 5 hours, I know nothing, and this is what I'd do rather than study:
digits = {'0':'1', '1':'2', '2':'3', '3':'4', '4':'5', '5':'6', '6':'7', '7':'8', '8':'9', '9':'0'}
num = '0'
while num != ['1', '0', '0']:
num = list(num)
lastdigit = num.pop()
increment = digits[lastdigit]
if lastdigit == '9':
try:
nextlastdigit = num.pop()
if nextlastdigit == '9':
num = ['1', '0', '0']
else:
nextincrement = digits[nextlastdigit]
num.append(nextincrement)
num.append(increment)
except IndexError:
num = ['1', '0']
else:
num.append(increment)
for digit in num:
print(digit, end='')
print()
Maybe one day I'll be masochistic enough to make it recursive so it works for any upper limit but that day is not today xD
!e
def increment(num: list) -> list:
if num[-1] == 9:
if len(num) > 1:
num = increment(num[:-1]) + [0]
else:
num[-1] += 1
return num
num = [1, 9, 9, 9]
print(increment(num))```
@alpine flower :white_check_mark: Your eval job has completed with return code 0.
[2, 0, 0, 0]
@ornate dew not really the same but there's no limit
!e
def increment(num: list) -> list:
if num[-1] == 9:
if len(num) > 1:
num = increment(num[:-1]) + [0]
else:
num[-1] += 1
return num
print(increment([9 for i in range(10 ** 60)]))```
@alpine flower :warning: Your eval job timed out or ran out of memory.
[No output]
haven't seen that one before
Well the idea was to not to use any integers at all lmao
finnne
Also what happened to my syntax highlighting?
!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.
Oh xD
!e
digits = {'0':'1', '1':'2', '2':'3', '3':'4', '4':'5', '5':'6', '6':'7', '7':'8', '8':'9', '9':'0'}
def increment(num: list) -> list:
if num[-1] == 9:
if len(num) > 1:
num = increment(num[:-1]) + ['0']
else:
num[-1] = digits[num[-1]]
return num
print(increment(['9', '9', '9']))
```\
@alpine flower :white_check_mark: Your eval job has completed with return code 0.
['9', '9', '0']
Don't mean to nitpick, but this still uses -1 to index lol
that's easy to fix tho eval("-1")
recursion hurts my head tho idk why it isn't working
No variables of datatype int and nothing that returns int
No cap, same here
....can you assign exec with a walrus in an f string with this method?
hmmm
you'd need the f string syntax nvm
!e ```py
def increment(num: list[int]) -> list:
(num[-1]==9)and len(num)>1 and(num:=increment(num[:-1])+[0])or num.setitem(-1,num[-1]+1)
return num
num = [1, 9, 9, 9]
print(increment(num))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[2, 0, 0, 0]
You forgot the quote marks around the 9.
I forgot all the quote marks
been codiing with python for 5 years and never knew you could do increment(num: list[int]) -> list
within a function name
crazy
!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!*
!eval
def main():
exit()
main()
@wide laurel :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | File "<string>", line 2, in main
004 | NameError: name 'exit' is not defined
@wide laurel #bot-commands if your trying to break the bot XD
ok lol
lmao
!e my code after the coffee: ```py
print(420)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
420
does the same thing
!e post moved: "my code before the coffee"```py
import('ctypes').py_object.from_address(id(...)+8).value=type("wrapper",(object,),{'call':lambda s,f:f()})
@int
@...
class n:int=lambda s:69
@...
class cout:lshift=print
@...
class main:init=lambda s: cout << int.mul((n//10)*10,(n%10)-(True<<10**False))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
420
hey chilaxin
!e ```py
from ctypes import (
pythonapi, POINTER, byref,
c_int, c_wchar_p
)
import os
def rerun(*new_flags, keep_old=True):
_argv = POINTER(c_wchar_p)()
_argc = c_int()
pythonapi.Py_GetArgcArgv(byref(_argc), byref(_argv))
orig_argv = _argv[:_argc.value]
if keep_old:
orig_argv[1:1] = new_flags
orig_argv[-1] = orig_argv[-1].replace('x = 0', 'x = 0x11')
os.execv(orig_argv[0], orig_argv)
else:
os.execv(orig_argv[0], (orig_argv[0],) + new_flags)
x = 0
if x == 0x11:
print('here')
else:
rerun()```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
here
import sys
s=sum
l=[s([int,ord][y>"9"](y)for y in x)for x in sys.argv[1].split(",")]
_=len(l)
print([0,1,s(l),s(l[:-1])*l[-1]][_]if _<4else(s(l[:_-2])*l[_-2])//l[_-1])
``` anyway i can get rid of the if statement, probably that should make this shorter
i can share the annotated version of this if you want
!e ```py
import('ctypes').py_object.from_address(id(...)+8).value=type("wrapper",(object,),{'call':lambda s,a,**k:lambda f:f(a,**k),'repr':lambda s:'...'})
@...("++++++++++[>++++++++++<-]>--.-.+++.")
class output:
@str
@...()
class input(str):''
def init(s,c):
if not c:return''
@list
@...()
class a:list=lambda list:[0]
@...(a)
class a(list):
"""This is a list, only infinite."""
str=lambda s:list.str([...]+s+[...])
@int
@...()
class offset:int=lambda int:0
def getitem(self,item):
if(item:=item+self.offset)<=0:
self.offset-=item
@int
@...(0)
class item(int):int=lambda int:0
try:return list.getitem(self,item)
except IndexError:self.extend([0](item-len(self)+1))
return list.getitem(self,item)
def setitem(self,item):
if(item:=item+self.offset)<=0:
self.offset-=item
@int
@...(0)
class item(int):int=lambda int:0
try:list.getitem(self,item)
except IndexError:self.extend([0](item-len(self)+1))
return list.setitem(self,item)
@int
@...(0)
class i(int):0
@int
@...(0)
class p(int):-1
while(p:=p+1)<len(c):
if p<0:raise SyntaxError
@str
@...()
class t():str=lambda s:c[p]
if t in['+','-']:
@lambda n:a.setitem[i,n]
@int
@...()
class _:int=lambda s:(a[i]+1-2*(t=='-'))%256
elif t in['<','>']:
@int
@...(i+1-2*(this=='>'))
class i(int):...
elif t=='.':
@lambda b:print(end=chr(int(b)))
@...()
class cout:int=a.pop()
elif(t=='['and a[i]==0)or(t==']'and a[i]!=0):
@int
@...()
class :
def int(s):
nonlocal p;p=p+1-2*(t==']')
@int
@...(0)
class (int):0
while >=0:
if 0>(p:=p+1-2*(t==']')) or p>len(c):raise SyntaxError
c[p]in['[',']']and(:=+1-2*(c[p]!=t))
return p
@int
@...()
class p(int):...
@floral meteor :x: Your eval job has completed with return code 1.
001 | <string>:2: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
002 | <string>:5: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
003 | <string>:10: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
004 | <string>:12: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
005 | <string>:17: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
006 | <string>:23: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
007 | <string>:32: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
008 | <string>:38: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
009 | <string>:41: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
010 | <string>:46: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
011 | <string>:51: SyntaxWarning
... (truncated - too long, too many lines)
Full output: https://paste.pythondiscord.com/ohemalobis.txt?noredirect
bugger it, i'll work on my cursedutils module
Boys I was wrong, today was the day
digits = {'0':'1', '1':'2', '2':'3', '3':'4', '4':'5', '5':'6', '6':'7', '7':'8', '8':'9', '9':'0'}
def increment(num):
try:
digit = num.pop()
if digit == '9':
increment(num)
num.append(digits[digit])
except IndexError:
num.append('1')
return num
num = ['0']
while num != ['1', '0', '0', '0']:
num = increment(num)
for i in num:
print(i, end='')
print()
This was much shorter, and dare I say, simpler lmao
It's finally short enough to fit on vsinder
wtf is this lmao
you treat increment as "void" inconsistently
digits = {'0':'1', '1':'2', '2':'3', '3':'4', '4':'5', '5':'6', '6':'7', '7':'8', '8':'9', '9':'0'}
def increment(num):
try:
digit = num.pop()
if digit == '9':
increment(num)
num.append(digits[digit])
except IndexError:
num.append('1')
num = ['0']
while num != ['1', '0', '0', '0']:
increment(num)
for i in num:
print(i, end='')
print()
that's partially my fault I have a habit of naming global + local vars the same thing and treating them as local vars
is there a way to use contextlib.suppress without a context manager?
!e
import gc
f = gc.get_referents(list.__dict__)[0]
f.pop("append")
a = list()
print(a)
a.append()
print(a)
print(2)
@simple crystal :x: Your eval job has completed with return code 139 (SIGSEGV).
[]
segmentation fault
when I try to debug to see what happens the debugger breaks
and then it will raise a "list has no attribute append" once
then it goes back to segmentation fault
I want an exception to get raised if I try to append...
oh fishhook works
I will figure out why
Not quite, the return is outside the try-catch
So it should return every time
I think 😂
!e
digits = {'0':'1', '1':'2', '2':'3', '3':'4', '4':'5', '5':'6', '6':'7', '7':'8', '8':'9', '9':'0'}
def increment(num):
try:
digit = num.pop()
if digit == '9':
increment(num)
num.append(digits[digit])
except IndexError:
num.append('1')
return num
num = ['0']
while num != ['1', '0', '0', '0']:
num = increment(num)
for i in num:
print(i, end='')
print()
@ornate dew :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
004 | 4
005 | 5
006 | 6
007 | 7
008 | 8
009 | 9
010 | 10
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/otowexoget.txt?noredirect
Seems to work lmao
That shouldn't matter, unless you explicitly declare a variable as global like global var within a context, it should be specific to they context
I just happened to forget that python passes by object reference, so both variables point to the same object in memory, meaning I don't really have to return it lmao
Maybe that should be a list 
!e
digits = [str(ord(i) - ord('a')) for i in "abcdefghij"]
def increment(num: list[str]) -> None:
try:
digit = num.pop()
if digit == str(ord('j') - ord('a')):
increment(num)
num.append(digits[int(digit) + ord('a') if int(digit) < ord('j') - ord('a') else ord('a') - ord('a')])
except IndexError:
num.insert(ord('a') - ord('a'), str(ord('b') - ord('a')))
return num
print(increment(["1", "9", "9"]))```
@alpine flower :white_check_mark: Your eval job has completed with return code 0.
['1', '0', '0']
my point is it's really hard to do it without a dict + not having any sort of numbers in the code
I can't figure out how to get around the indices tho
This is like the opposite problem, you can use int datatype, but no literal numbers in the code
I was doing, you can't use anything that returns an int, but you can use numbers as strings
I'm pretty sure it's impossible to do both :P
ya there's probably some backend way to do it, I just have absolutely no idea how to do it
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello world!
hell yea
!e
num2 = input("Enter a number: ")
result = float(num1) + float(num2)
print(result)```
@sick hound :x: Your eval job has completed with return code 1.
001 | Enter a number: Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
as you can see (even though you should probably play on #bot-commands), input doesn't work in this sandboxed interpreter
_B='108.0';_A='34.0';String=str;Integer=int;Float=float;Run_Code=exec;Character=chr;Character_Number_1=Character(Integer(Float(String('112.0'))));Character_Number_2=Character(Integer(Float(String('114.0'))));Character_Number_3=Character(Integer(Float(String('105.0'))));Character_Number_4=Character(Integer(Float(String('110.0'))));Character_Number_5=Character(Integer(Float(String('116.0'))));Character_Number_6=Character(Integer(Float(String('40.0'))));Character_Number_7=Character(Integer(Float(String(_A))));Character_Number_8=Character(Integer(Float(String('72.0'))));Character_Number_9=Character(Integer(Float(String('101.0'))));Character_Number_10=Character(Integer(Float(String(_B))));Character_Number_11=Character(Integer(Float(String(_B))));Character_Number_12=Character(Integer(Float(String('111.0'))));Character_Number_13=Character(Integer(Float(String(_A))));Character_Number_14=Character(Integer(Float(String('41.0'))));Final_String=String(Character_Number_1+Character_Number_2+Character_Number_3+Character_Number_4+Character_Number_5+Character_Number_6+Character_Number_7+Character_Number_8+Character_Number_9+Character_Number_10+Character_Number_11+Character_Number_12+Character_Number_13+Character_Number_14);Run_Code(Final_String)
```This took me seventeen years to code, and it is finally perfect.
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello
it's beautiful
!e
_=((()==())+(()==()))
__=(((_<<_)<<_)*_)
__import__(('c%'[::(([]!=[])-(()==()))])*((_<<_)+(()==()))%((__+(((_<<_)*_)+((_<<_)+((_*_)+(_+(()==())))))),(__+(((_<<_)*_)+((_<<_)+((_*_)+(_+(()==())))))),(__+(((_<<_)<<_)+(_<<_))),(__+(((_<<_)<<_)+((_*_)+(()==())))),(__+(((_<<_)<<_)+((_<<_)+(_*_)))),(__+(((_<<_)<<_)+((_<<_)+(_*_)))),(__+(((_<<_)<<_)+((_<<_)+((_*_)+(_+(()==())))))),(__+(((_<<_)*_)+((_<<_)+((_*_)+(_+(()==())))))),(__+(((_<<_)*_)+((_<<_)+((_*_)+(_+(()==()))))))))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello world!
this is one of mine
just curious what is you favorite VM type
also what type of VM software
qemu/kvm
I use manjaro linux
passthrough a 6800 XT into windows
only pyhton
sounds like Muthar anas(someordinarygamers)
i know lol
Just curious do you use Archlinux and Do you Use oracle virtual box or VMWARE
I use an arch distro, manjaro seemed good for me since I do a lot of coding
You're a psychopath
!e ```py
f=(lambda n:(o:=n//2)>n or''.join(0*(m:=x/n3)(l:=y/n3)or" #"[(mm+ll-1)**3-mm*l**3<0]+"\n"[x<o-1:]for y in range(o,-o,-1)for x in range(-o,o)))
print(f(20))```
@grave rover :white_check_mark: Your eval job has completed with return code 0.
001 |
002 |
003 | ### ###
004 | ###### ######
005 | ###############
006 | ###############
007 | ###############
008 | ###############
009 | ###############
010 | ###############
011 | #############
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ofaritotul.txt?noredirect
(lambda n:(lambda o=int(.5*n//1):[([(lambda m=(x/n*3),l=(y/n*3):print([" ","#"][(m**2+l**2-1)**3-m**2*l**3<0],end=""))()for x in range(-o,o)],print())for y in range(o,-o,-1)])())
(lambda n:(lambda o:"".join(" #"[(m**2+l**2-1)**3-m**2*l**3<0]+"\n"*(o-x==1)for y in range(o,-o,-1)for x in range(-o,o)for m,l in[[(x/n*3),(y/n*3)]]))(n//2))(10)
(lambda n:(o:=int(n/2))>n or''.join((m:=x/n*3)*(l:=y/n*3)*0 or" #"[(m**2+l**2-1)**3-m**2*l**3<0]+"\n"[x<o-1:]for y in range(o,-o,-1)for x in range(-o,o)))
(lambda n:(o:=n//2)>n or''.join(0*(m:=x/n*3)*(l:=y/n*3)or" #"[(m*m+l*l-1)**3-m*m*l**3<0]+"\n"[x<o-1:]for y in range(o,-o,-1)for x in range(-o,o)))
``` kinda satisfying to look at how this one evolved over time
!e
f=(lambda n:(o:=n//2)>n or''.join(0*(m:=x/n3)(l:=y/n3)or" #"[(mm+ll-1)**3-mm*l**3<0]+"\n"[x<o-1:]for y in range(o,-o,-1)for x in range(-o,o)))
print(f(12))
@fossil estuary :white_check_mark: Your eval job has completed with return code 0.
001 |
002 |
003 | ### ###
004 | #########
005 | #########
006 | #########
007 | #######
008 | #######
009 | #####
010 | ###
011 |
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/edosazuziv.txt?noredirect
CODEBLOCK REEEEEEEEEEEEEE
like dis
Someone have idea how to run http://www.onelinerizer.com/ in python3?
I got:
Traceback (most recent call last):
File ".../oneline.py", line 22, in <module>
onelinerize(code)
File "...\lib\site-packages\onelinerizer\onelinerizer.py", line 804, in onelinerize
return get_init_code(t, table)
File "...\lib\site-packages\onelinerizer\onelinerizer.py", line 70, in get_init_code
output = Namespace(table).many_to_one(tree.body)
File "...\lib\site-packages\onelinerizer\onelinerizer.py", line 214, in many_to_one
return reduce(
NameError: name 'reduce' is not defined
Convert any Python 2 script into a single line. No newlines allowed. No semicolons, either. No silly file I/O tricks, or eval or exec. Just good, old-fashioned lambda.
oh I was writing something like that for py3.8
Fwiw that specific error can be fixed by using return __import__('functools').reduce(...)
did you finished it?
mine works. ;)
been a while since I really worked on it lol
not 100% working yet sadly
but it can do most things iirc
I just wanted it to do exec
I mean
# Generated by Mart Obfuscator
a=lambda b:b<([]==[])<<(()>=())and()==()or a(b-([]==[]))+a(b-((()>=())<<(()==())))
``` here's fibonacci
>>> x = [6, 4, 3, 2, 9, 1]
>>> sort.quick_sort(x, 0, len(x)-1)
(None, (None, -1, (None, (None, -1, -1), (None, -1, -1))), (None, -1, (None, -1, -1)))
>>> x
[1, 2, 3, 4, 6, 9]
```quicksort and selectionsort
tic tac toe is still a WIP sadly, the number obfuscator seems to actually decide whether the loop runs or exits, and even then it seems there's an issue somewhere causing an indexerror
Not sure if this belongs here but I managed to achieve something I'm really proud of, but it has no real use other than making my code a bit prettier with type hinting.
I made a type so that I can make numpy arrays with a specified length. Kinda like a generic, so I can type hint Vector[6] if I'm expecting a (6,) shape numpy array.
This is what the syntax looks like
x = Vector[3]([1, 2, 3])
And this will drop an error, because of the shape mismatch:
y = Vector[4]([1, 2, 3])
Now I can type hint:
def foo(x: Vector[2]) -> Vector[2]:
return x+2
If someone is interested I would be happy to receive criticism: https://gist.github.com/Speterius/69026b1376a671f9c1715fb2eb813b29
@eternal prawn noice. If you want to make it a bit simpler, python has __class_getitem__
!e ```py
class a:
def class_getitem(cls, arg):print(arg)
a[0]```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
0
factors = lambda num: [int(j) for i in map(lambda x: [x] if x == num else [x, num / x], list(filter(lambda x: num % x == 0, range(1, int(num**0.5))))) for j in i]```
nice way of calculating factors
aint it
what is lamada
and use a metaclass instead of a decorator
You don't need a meta class here
You could use init subclass
And then not make it a function that returns a class
I know but the decorator was interesting
alright, going into python from matlab, i really missed the struct object.
Well with some globals hooking and a cursed struct class I will make struct work in python.
!e ```py
import ctypes
#hackery
class struct:
def init(self,**k):[setattr(self,this,that)for this,that in k.items()]
def getattr(self,item):
if not hasattr(self,item):setattr(self,item,self.class())
return object.getattr(self,item)
def call(self,f):setattr(self,f.name,f);return f
class _hooked(type):
@lambda c:c()
class __sentinal:...
gulag={}
def del(self,other=__sentinal):
if other is __sentinal
for victim, orig in gulag.items():ctypes.py_object.from_address(id(victim)+8).value=orig
elif other in gulag:ctypes.py_object.from_address(id(other)+8).value=gulag[other]
class curse(metaclass=_hooked):
"""example usages:
@curse(...)
def call(self,*a,**k):
def wrapper(f):
return f(*a,**k)
curse(None,'call',lambda s,*a:s)
"""
def new(self,other,name='',f=None):
if f is None:return lambda f:self(other,name or f.name,f)
else:return self(other,name or f.name,f)
def init(self,other,name='',f=None):
if other not in self.class.gulag:self.class.gulag|={other,type(other)}
hack=ctypes.py_object.from_address(id(other)+8)
try:hack.value=type(hack.value.name,(hack.value,),{name:f})
except:hack.value=type(hack.value.name,(),{this:getattr(hack.value,this)for this in dir(hack.value)}|{name:f})
@curse(globals())
def missing(self, key):
try:return getattr(builtins,key)
except:self[key]=struct(name=key,doc=None);return self[key]
cout.lshift=print
cout << "Hello World!"
oh whoops i wasnt finished lol
!e ok first i perfectses the class
class struct:
def __init__(self,**k):[setattr(self,this,that)for this,that in k.items()]
def __getattr__(self,item):
if not hasattr(self,item):setattr(self,item,self.__class__())
return object.__getattr__(self,item)
def __call__(self,f):setattr(self,f.__name__,f);return f
cout, output = struct(__lshift__=print), struct()
output.data.x = 3
output.data.y = 4
@cout << f(output.data)
def _(data):
return data.x * data.y
I have no clue, it shouldn't be recursionings
it should be workings
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
"".join(['A' for i in range(43)])* smh
I believe you meant f"{11478986304257167078711585130701756989053283163632459947822157877600493794161163746264989691490697448857580612687974391859056618193877774016661073255152478229773002314437327253923119931013370082604311376279371017487563790178827046139928382510691977723156789183826289319143052391855134253864827181651765249703991141830847575261485010803545942957275674094024174250:X}"
'A'*43 
🥳
what is this
i was trying to make a matlab object
wow,It's cool👍
I trying to make an AI project. But it's not working, Please help guys to make it.
If yo want a make money ? try this link https://www.fiverr.com/
This channel tends to solve problems in what can only be described as the worst way possible. Maybe try #❓|how-to-get-help if you want to get good code.
if __name__ == "__main__":
x = 10
with open("/proc/self/mem", "r+b") as mem:
mem.seek(id(x))
obj = PyLongObject()
obj.set_bytes(mem.read(obj.get_size()))
print(obj.get_named_values())
# => PyLongObject(ob_refcnt=74, ob_type=140678365892192, ob_size=1, ob_digit=10)
``` repurposing some old code
... why
# Copy PyObject to avoid recursion, but use P[void] for pointers
PyTypeObject = CPyPacket("@nP[void]P[void]",
namedtuple("PyTypeObject",
["ob_refcnt", "ob_type", "tp_name"])).factory()
PyObject = CPyPacket("@nP[PyTypeObject]",
namedtuple("PyObject",
["ob_refcnt", "ob_type"])).factory()
PyVarObject = CPyPacket("@{PyObject}n",
namedtuple("PyVarObject",
["ob_size"])).factory()
PyLongObject = CPyPacket("@{PyVarObject}i",
namedtuple("PyLongObject",
["ob_digit"])).factory()
if __name__ == "__main__":
x = 10
with open("/proc/self/mem", "r+b") as mem:
mem.seek(id(x))
obj = PyLongObject()
obj.set_bytes(mem.read(obj.get_size()))
print(obj.get_named_values())
# => PyLongObject(ob_refcnt=74,
# ob_type=PyTypeObject(ob_refcnt=144,
# ob_type=140641582082304,
# tp_name=0),
# ob_size=1,
# ob_digit=10)
``` beautiful
PyTypeObject = CPyPacket("@nP[void]nP[void]nn15P[void]L4P[void]n9P[void]n11P[void]IP[void]",
namedtuple("PyTypeObject",
["ob_refcnt", "ob_type", "ob_size", "tp_name",
"tp_basicsize", "tp_itemsize", "tp_dealloc", "tp_print",
"tp_getattr", "tp_setattr", "tp_reserved", "tp_repr",
"tp_as_number", "tp_as_sequence", "tp_as_mapping",
"tp_hash", "tp_call", "tp_str", "tp_getattro",
"tp_setattro", "tp_as_buffer", "tp_flags", "tp_doc",
"tp_traverse", "tp_clear", "tp_richcompare",
"tp_weaklistoffset", "tp_iter", "tp_iternext",
"tp_methods", "tp_members", "tp_getset", "tp_base",
"tp_dict", "tp_descr_get", "tp_descr_set",
"tp_dictoffset", "tp_init", "tp_alloc", "tp_new",
"tp_free", "tp_is_gc", "tp_bases", "tp_mro", "tp_cache",
"tp_subclasses", "tp_weaklist", "tp_del", "tp_version_tag",
"tp_finalize"])``` this took way too long and yes I'm planning to fill in the blanks later
I wish I knew how to properly pretty-print
I'm positive I'm slowly going mad with power
actually I can remove the @ since it's the default
python just released a fully-developed official pep that'll change booleans forever?!?!?!? this is sooo good for esotericness and it's gonna be implemented in 3.11
link -> https://docs.google.com/document/d/1gvq4rdMVzrEFAlVCSPvGs4mstI8831seOEDpwiRRWW4
PEP: 21401 Title: A Complete Update of the Boolean System Author: @no u#9891 on the social media platform Discord, pseudonym “wait… it’s all objects?” on the official Python server within Discord. Status: Final Type: SLOOF LIRPA Created: 01-apr-2021 -----------------------------------------------...
if you wanna be convincing at least use a website styled to look like python's pep webpages (+url), a realistic pep number (I do get the joke tho) and make sure the preview doesn't spoil it
other than that, quality shitpost
if __name__ == "__main__":
import sys
f = sys._getframe(0)
obj3 = resolve_meta(_frame, id(f))
print(resolve(PyBytesObject, # Create PyBytesObject from address
obj3.get_named_values(convert=False) # Children stay `CPyObject`s
.f_code.get_named_values(resolve=False) # Don't resolve addresses
.co_code) # Address for co_code (type: bytes)
.ob_size) # ob_size of PyBytesObject
print(len(f.f_code.co_code))```
x = 54
obj = resolve_meta(PyLongObject, id(x))
offset = obj.get_offset("ob_digit") # offset on PyLongObject to ob_digit field
with open("/proc/self/mem", "r+b") as mem:
mem.seek(id(x) + offset)
mem.write(struct.pack("i", 420))
print(6*9) # => 420
This would be a good April fools joke if it wasn't on a google doc
You realize you can do this with ctypes and it's like one line?
can't do it on a website
True
btw, i also got an infraction for making this joke so i can't send this anymore for a while
april fools comes at a price

yes but I'm too lazy to keep going through ctypes and the C source
also; this one creates a copy in a separate buffer, which has the added benefit of us being able to point the interpreter to it and edit it very easily :^)
@grave rover do you plan to handle variable size fields?
I don't support them sadly
but
I have plans: ```py
item = XYZ()
# Get class object from just the address with the correct refcount
obj2 = resolve_meta(PyLongObject, id(item))
print(as_object(
obj2.get_named_values(resolve=False).ob_type
)) # => <class '__main__.XYZ'>
as you know classes have a tp_itemsize field 👀
i.e. variable length
Yea
also this seems similar to this thing that i wrote: https://github.com/chilaxan/pysnippets/tree/main/native_ctypes
Can you do any text with that?
!e
from numpy import base_repr
print(base_repr(2847674241700166260733851334605607128751529874266565790, 36))
@vestal solstice :white_check_mark: Your eval job has completed with return code 0.
YOUCANDOANYLETTERWITHTHISBUTNOSPACE
can someone explain how you can encode python scripts with only brackets and a few other characters?
Can’t seem to find what’s wrong with this
your trying to asign a variable to a string
Supposed to run an rng with one in 500 chance to say “you got an heirloom
and not to a variable
what
dumb it down for me a bit
instead of
"var" = input(" ...````
and also remove quotes from the if statement with it
Time for more coding agony
Alright now I’m trying to get it to work so I can also use lowercase e for the input and also so that it says wrong key if you don’t enter in e
you can get ints by adding true comparisons between empty objects represented by brackets
That is awesome
first of all, use three ` chars before and after and paste your code, don't post screenshots. Second, use a help channel in the available help channels category instead of this channel, this channel isn't for basic Python stuff
is there a way to see this module? It seems super interesting
you still have the if statement in quotes
how do you get functions?
you need to either use lambda or def
or if you mean builtins you need to use at least exec
If your restriction is no A-Za-z, remember you can use unicode
What in the world is that
Whenever I try to open a python file to edit it makes a pycache folder
With a compiled version of the file that I can’t edit
also my pyinstaller doesn’t work
An incomplete attempt to replicate ctypes in pure python and no external imports
As of rn it has most simple datatypes, structs, and unions
(All datatypes can be allocated in place or read from an address)
I'm working on C function calling rn but it's tricky af
!e
b64=lambda x:(
__import__
(
"b" \
"a" \
"s" \
"e" \
"6" \
"4"
)
.
b64encode
(
x
.
encode
(
'u' \
't' \
'f' \
'-' \
'8'
)
)
.
decode
(
'u' \
't' \
'f' \
'-' \
'8'
)
)
globals(
)[
"_" \
"_" \
"b" \
"u" \
"i" \
"l" \
"t" \
"i" \
"n" \
"s" \
"_" \
"_"
].print(
__import__(
"b" \
"a" \
"s" \
"e" \
"6" \
"4"
)
.
b64decode
(
b64
(
"H" \
"e" \
"l" \
"l" \
"o" \
" " \
"W" \
"o" \
"r" \
"l" \
"d" \
"!"
)
)
.
decode
(
'u' \
't' \
'f' \
'-' \
'8'
)
)
@fossil estuary :white_check_mark: Your eval job has completed with return code 0.
Hello World!
yes.
Lovely.
You should run it through black and get it to a one liner
!e ```py
chars = [72,101,108,108,111,32,87,111,114,108,100,33]
h = "".join([import("base64").b64encode(chr(v).encode('utf-8')).decode('utf-8') for v in chars])
print(import("base64").b64decode(h).decode('utf-8').lower())
@fossil estuary :white_check_mark: Your eval job has completed with return code 0.
h
So? You care about readable code?
no.
should i run it thru my one-liner thing
Sure.
oh nice, my internet went out
Lovely.
!e
(lambda: exec('def a():"""TEST"""\n') and eval("a"))()
@lucid shell :warning: Your eval job has completed with return code 0.
[No output]
:D
That's my code right there
i wrote it for a test today:
@given(func=st.functions())
@example(func=lambda: exec('def a():"""TEST"""\n') and eval("a"))
def test_prog_is_func_name(self, func: Callable[[Any], None]) -> None:
... # test code

Send link
it's private :)
finally figured out exactly what fishhook does and can change how [] indexing on lists works without losing access to the original __getitem__
!e
from ctypes import *
class newlist:
def __getitem__(self, *args):
print('Hijacked __getitem__ but preserved functionality')
return newlist._oldget(self, *args)
ssize_t = sizeof(c_ssize_t)
list_tp_as_mapping_p = c_void_p.from_address(id(list) + 14 * ssize_t)
list_mp_subscript_p = c_void_p.from_address(list_tp_as_mapping_p.value + 1 * ssize_t)
heap_tp_as_mapping_p = c_void_p.from_address(id(newlist) + 14 * ssize_t)
heap_mp_subscript_p = c_void_p.from_address(heap_tp_as_mapping_p.value + 1 * ssize_t)
list_mp_subscript_p.value = heap_mp_subscript_p.value
list_dict_proxy = list.__dict__
list_dict = py_object.from_address(id(list_dict_proxy) + 2 * ssize_t).value
new_dict_proxy = newlist.__dict__
new_dict = py_object.from_address(id(new_dict_proxy) + 2 * ssize_t).value
new_dict.update({'_oldget': list_dict['__getitem__']})
list_dict.update({'__getitem__': newlist.__getitem__})
print([0][0])
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
001 | Hijacked __getitem__ but preserved functionality
002 | 0
(not using fishhook itself and wanting to know exactly what I'm doing because I want to use this in a class)
why not just inherit from list?
oh right you changed list literal
yeah I want basic list syntax to behave differently
my teacher is obsessed with teaching Python like it's baby's first C class and wants us to treat lists as arrays so my eventual plan is to make a module that makes lists actually behave like arrays and include it in everything just to be cheeky
arrays are also typically homogenous
yeah one type and fixed length
Usually, arrays contain only elements of one type, but since everything in Python is of type object, that's not that important.
oh, that's fine
he's obsessed with the idea that Python lists are a "crutch" so I'm removing their functionality to appease him
one type and fixed size, I would do that too
writing Pythona as if lists are fixed one type is easy but stupid imo
yeah everything in CPython is a struct which "inherits" from a PyObject struct inside of itself with a bunch of functions and other structs it's being passed through to get what you see
x : list[:] = {1, 2, 3} is valid syntax.
Yes, although if you evaluate the typehint normally it will throw an error I believe.
ah
Oh, no, it doesn't.

Why tho
I'm wondering if I can hijack assignment by index behavior, I think I need to change more than just the pointer fishhook changes for __setitem__
because it is, and I made it. I'll do what I want with it =)
Ok well mine is above
also ideally I could hijack initializing but that seems like another week of figuring out stuff
probably just gonna raise exceptions if you try to interact with an invalid "array"
You could make an array class of your own, then replace list literals with it.
That way you'd have to hook less.
...sure this would work?
hmmm
can you just replace list's type object with a heap class type object?
...would you use ctypes.memmove with the size of the pytypeobject maybe?
doesn't seem to work
maybe if I manually made a ctypes Structure to replace it
but that's more work than hooking
seriously though, do you know this would be easier than hooking methods?
I know very little on this topic.
ok sry haha
Any ideas on how to modify this so that it actually runs?
from functools import partial
from functools import partialmethod
class Test:
def print_result(self, func):
print(func())
def one_arg_decorator(self, func):
return partialmethod(func, 1)
@one_arg_decorator
@one_arg_decorator
def add(self, x, y):
return x+y
t = Test()
print(t.add())
If I can figure this out I can re-apply the pattern to a non-static value instead of just 1.
Traceback (most recent call last):
File "test.py", line 54, in <module>
class Test:
File "test.py", line 63, in Test
def add(self, x, y):
TypeError: one_arg_decorator() missing 1 required positional argument: 'func'
I am not sure if partialmethod is entirely necessary, but I have not been able to figure out a way to pass self through nested decorators
or even single decorators, to be fair
Try removing the self from one_arg_decorator, and if you want, making it a classmethod as well.
The decorators happen before one_arg_decorator is made into a method — at that point it's just a function with self unbound.
from functools import partial
from functools import partialmethod
class Test:
def print_result(self, func):
print(func())
@classmethod
def one_arg_decorator(func):
return partialmethod(func, 1)
@one_arg_decorator
@one_arg_decorator
def add(self, x, y):
return x+y
t = Test()
print(t.add())
Traceback (most recent call last):
File "test.py", line 54, in <module>
class Test:
File "test.py", line 64, in Test
def add(self, x, y):
TypeError: 'classmethod' object is not callable
Interesting. I guess you'd want to get rid of the @classmethod decorator and apply it manually after you decorate add.
you need to use a decorator that wraps the function
one_arg_decorator = classmethod(one_arg_decorator)
oh, because self gets transferred by @wrapper
@wrapper?
def one_arg_decorator(func):
def inner(self, arg):
return func(self, arg, 1)
return inner
class Test:
@one_arg_decorator
@one_arg_decorator
def add(self, x, y):
return x+y
```should do the trick
don't forget that the typical classmethod takes at least one argument: cls
you might want to use @staticmethod instead
Apologies, that.
If I tag it as static then I won't be able to access instance specific values. Maybe I'm approaching this wrong, not even sure if what I am trying to do is practical using decorators.
I guess I should explain
I am working on a interpreter that has operations in a stack, and implementing tons of different operations.
I am hoping to load the operations in from the stack using decorators because that saves me from a ton of redundant code.
For example:
class Test:
def __init__(self):
self.opstack = []
def opstack_arg(self, func):
#something
@opstack_arg
@opstack_arg
def add(self, a, b):
return a + b
@opstack_arg
@opstack_arg
def sub(self, a, b):
return a - b
x = Test()
x.opstack.append(1)
x.opstack.append(2)
print(x.add())
I think decorators could be a really neat approach but maybe not
@astral rover's solution should work, barring the arguments to the one_arg_decorator being a little odd.
def opstack_arg(func):
def inner(self, *args):
return func(self, self.opstack.pop(), *args)
return inner
```Perhaps this?
Actually, that will only work for one-argument functions.
You get the idea, although I'm not really sure how to fit it together.
I'll definitely try experimenting with that, thanks for the idea
actually this is just straight up right, it works perfectly
check it out
class Test:
def __init__(self):
self.opstack = []
def opstack_arg(func):
def inner(self, *args):
return func(self, self.opstack.pop(), *args)
return inner
@opstack_arg
@opstack_arg
@opstack_arg
def add(self, a, b, c):
return a + b + c
x = Test()
x.opstack.append(1)
x.opstack.append(2)
x.opstack.append(17)
print(x.add())
20
such a cool solution
now I can sorta just plop error checking into the decorator :)
Wow. I'm not sure why, but maybe I'm just a genius.
I wonder if it pop things in the right order. What even is the right order?
so it's a direct stack implementation
I wonder whether you could condense that into a single decorator that pops for each positional arg in the definition.
Or alternatively, explicitly pass the number of args to the decorator
@args_from_stack
def prod(self, a, b):
return a * b
I could, but instead I am using decorator args to enforce typing, which is pretty cool
for instance
@opstack_append
@stack_arg(int, float)
@stack_arg(int, float)
def add(self, a, b): return a + b
this is what my decorator looks like rn for anybody who is curious
def stack_arg(*args):
allowed_types = tuple(args)
def opstack_arg(func):
#print("The type is " + str(allowed_types))
def inner(self, *args):
if len(self.opstack) > 0:
op = self.opstack.pop()
if(isinstance(op, allowed_types)):
try:
return func(self, op, *args)
except ValueError:
self.opstack.append(op)
raise ValueError()
else:
self.opstack.append(op)
print("Error: type mismatch in " + func.__name__ + ".")
raise ValueError()
else:
print("Error: " + func.__name__ + " does not have enough operands.")
raise ValueError()
return inner
return opstack_arg
could probably be condensed but i'm too sleepy to do it right now lol
from typing import Iterator
import random
import itertools
def fizz_buzzes() -> Iterator[str]:
counts = [itertools.count(1)] * 15
for group in zip(*counts):
random.seed(23_977_775)
for n in group:
# Just pick at random
yield random.choice(
['fizzbuzz', 'fizz', str(n), 'buzz']
)
fb = fizz_buzzes()
output = [next(fb) for _ in range(100)]
this is from Ten Essays on Fizz Buzz - I figured you people would enjoy it 😅
that is interesting
and gives me some cursed ideas
i wonder how one could generate a seed to do similar things like that
The book goes over it in detail - there's 4**15=1 073 741 824 possible combinations the seed can give over these 15 choices, but we can cut that by a factor of 4!=24 by searching for an arbitrary permutation of the results - like here, you can see, it's ['fizzbuzz', 'fizz', str(n), 'buzz'] and not something more obvious like [ str(n),'fizz', 'buzz', 'fizzbuzz']
so just random/linear scanning of the seeds
i wonder if you could work backwards from looking at the implementation of random to go from results -> seed
so you could generate the seed without bruteforcing
the problem is that if that was easy, it'd allow for seed-calculation attacks to predict future behaviour of the generator
so I'd expect it's hard to do in modern algorithms like the mersenne twister random uses
ah fair enough
MT is pretty easy to crack, you just need 624 results to get the seed
at least its a lot better than shit like java random
it's not meant to be cryptographically strong ¯_(ツ)_/¯
well, you can crack the mersenne twister with some effort
So it's mostly about determining how many bits are consumed per random.choice
random.choice seems to call random.random until it is under a specified limit
Isnt the same for random.randint tho?
I think so
what does secrets use?
If enough people poke me I'll make it available on pypi
Hey @simple crystal!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
https://paste.pythondiscord.com/ceboxinute.py finished making lists into pseudoarrays
at least for now
it helped me find a spot in the lab this week where I gasp put ints into what I was supposed to pretend was a char array!
C would let you do that anyway, I believe.
@simple crystal py list_mp_subscript.value = heap_mp_subscript.value # replacing pointer list_mp_ass_subscript.value = heap_mp_ass_subscript.value # replacing pointer can be dangerous, because if hook_cls gets deallocated these arrays will be freed, but list will still use them
it is safer to allocate a new array using ctypes, and then fill it with the heap array values
Please do!
ah okay, thanks for the heads up!
fishhook does that here: https://github.com/chilaxan/fishhook/blob/master/fishhook/__init__.py#L100
Only when the new struct is created? I think that, for list, a new struct was only created for "list_as_number" (I believe because List_TypeObject has 0 instead of a PyNumberMethods) and even then not for the decorated class
Basically for any slot that is NULL you need to insert a pointer to a properly sized array
cool, I did that for the one that's null, to preserve allocation in general should I assign a name to the value of heap pointers and then set the list pointer value to that int instead of the value of the heap pointer?
So you want to make a new array, then insert the ctypes.addressof(array) into the tp_as_*slot
ah okay instead of just making it with from_address
Well you need to get the tp_as_* ptr first with c_void_p.from_address
so it's best to do that with list_as_mapping and for the heap class as well? Would I need to hook every relevant dunder?
You could also just make a new copy of heap types array
That would likely be easier
That should work
sweet
thanks again for the help and for fishhook haha I'm learning a lot about CPython
@rugged sparrow I'm making good progress btw, current struggle is reading pointers/arrays, cause sometimes they're delimited by nulls and sometimes they have length ob_size
def main():
x = 10
# Print representations of the C structs
print(CPyVarObject.instance())
print(CPyTypeObject.instance())
x_as_pylong = get_view(id(x), CPyVarObject.instance())
print(x_as_pylong.ob_type.tp_basicsize) # Size of a PyLong in bytes, according to the PyTypeObject C struct
print(x_as_pylong.ob_refcnt) # Reference counter in interpreter
x_as_pylong.ob_refcnt = 1 # modify refcount :yeef:
# --- OUTPUT ---
struct CPyVarObject {
ssize_t ob_refcnt
CPyTypeObject* ob_type
ssize_t ob_size
}
struct CPyTypeObject {
ssize_t ob_refcnt
CPyTypeObject* ob_type
ssize_t ob_size
void* tp_name
ssize_t tp_basicsize
ssize_t tp_itemsize
...
}
24
215 ```
I like the pretty print that you do
Makes sense
The implementation is incredibly hacky but we don't talk about that
Oh mine is super hacky as well
I do like how I allowed for specifiying a null terminated array
(type*None) in a struct definition is a null terminated array
How'd you do that btw, just allow specifying null-terminated and if it's not it uses ob_size?
I don't have the fall back
🤔
You have to say one way or another
So how does yours handle ob_digit
Ah
Oh right you're taking a more ctypes-esque approach
Look into my __init__.py it has definitions for most basic types
Yea
I added some dynamic stuff but still wanted the recognizable interface
class LongObj(PyVarObject):
ob_digit: field(lambda inst:c_int*abs(inst.ob_size))```
Like that's how I do PyLong
Yeah I just have stuff like ```py
class CPyLongObject(CPyVarObject):
def init(self):
super().init()
self.ob_digit = cprop ("ob_digit", "A[CShort]")
self.add_nodes(self.ob_digit)
Oh that's an interesting way to do it
The main reason I avoided that is because of property order which i don't trust in the slightest
Yea field takes in a function then when the property is accessed it uses the type returned by the function(instance)
Wdym you don't trust property order?
I just use property for all fields to live read/write values
@rugged sparrow
I think I've made it safer as far as allocating for heap structs by doing this
# For heap classes, need copy their existing struct into allocated space to ensure they persist in memory
heap_tp_as_number_struct = (c_void_p * pyNumberMethods_slots)() # Allocate space as array
heap_tp_as_number_struct_copy = cast(heap_tp_as_number_struct, c_void_p) # Pointer to array, soon to be struct
heap_tp_as_number = c_void_p.from_address(heapTypeObject + pyNumberMethods_slot * size_ssize_t)
memmove(heap_tp_as_number_struct_copy, heap_tp_as_number, pyNumberMethods_slots * size_ssize_t) # Copy in struct
heap_nb_add = c_void_p.from_address(heap_tp_as_number_struct_copy.value + nb_add_slot * size_ssize_t)
heap_nb_multiply = c_void_p.from_address(heap_tp_as_number_struct_copy.value + nb_multiply_slot * size_ssize_t)
list_nb_add.value = heap_nb_add.value # replacing pointer
list_nb_multiply.value = heap_nb_multiply.value # replacing pointer
do you happen to know if it's possible for struct padding to be different if someone compiles CPython themselves or would that screw it up?
It is possible
It's possible for pointers to be 4bytes instead of 8 (32 vs 64bit)
that would correspond to the size of ssize_t though, right?
but yeah that's a compilation-dependent difference
A format of cq has size 16 (1 char, 7 padding, 8 for longlong) by default iirc, but depending on the host alignment may be different
@rugged sparrow arrays are done 👌
noice
In [62]: import sys
...: r = []
...:
...: for _ in range(100):
...: from collections import Counter
...: r.append(Counter)
...: del sys.modules['collections']
...: print(r[0] is r[1])
False
``` ever needed 100 distinct Counter classes
I did a thing
Doesn't work if GCd
your c modules are manually recreated cpy structs right?
sorta
@staticmethod
def by_reference(obj):
from py_ctypes import get_view
from cpy_types.collection_types import CPyListObject
x = [None]
list_view = get_view(id(x), CPyListObject.instance())
list_view.ob_item[0].value = obj._addr
return x[0]
``` getting objects by address: 
You should have seen my friend implement private variables
been there done that
I couldn’t find a way to access it at all
Only by decompiling the class could I get the initial value (but not the current value)
send the code, this sounds fairly easy lol
@grave rover wouldnt a tuple be easier to load with?
send it to me as well, i want to take a crack at it
yes but I did lists first :^)
fair enough
However, I think this version is truly private:
def MyClass():
private = {"nine": 9}
class MyClass:
def my_method(self):
return private["nine"]
return MyClass()
print(MyClass().my_method()) # outputs 9
is the code online anywhere yet @grave rover
not yet
My solution was this:
Nope. With a little (a lot) of finagling with
dis,sys.settrace, andMyClass.__code__, I have finally come up with a (fairly) elegant solution usingsys.settrace:
def test(frame, event, arg):
if frame.f_lineno == 3:
print(frame.f_locals)
return test
sys.settrace(test)
inst2 = MyClass()
Will yield
$ python .\breaker.py
9
{'private': {'nine': 9}}
{}
{}
!e ```py
def MyClass():
private = {"nine": 9}
class MyClass:
def my_method(self):
return private["nine"]
return MyClass()
print(MyClass().my_method()) # outputs 9
c = MyClass()
c.my_method.closure[0].cell_contents['nine'] = 0
print(c.my_method())```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 9
002 | 0
its how cpython handles wrapped variables from various scopes
def MyClass():
private = {"nine": 9}
class MyClass:
def my_method(self):
return private["nine"]
return MyClass()
print(MyClass().my_method.__func__.__closure__[0].cell_contents)```
damnit I got beat
lol gotta go faster
lmk when it goes up
I didn’t know before that closure data was accessible from the program itself
@rugged sparrow https://pion.martmists.com/Martmists/PythonSnippets
everything is accessible to itself as far as it's in Python I think
Sweet
Even if something isn't explicitly accessible there are always ways to access it
That’s true of most languages afaik
At least languages that aren’t compiled to native machine code
For example C# and Java you can access things you shouldn’t be able to using Reflection
even in languages that are compiled to native machine code you probably can still access things you're not meant to as long as you know enough about where they are and have a way to access memory directly enough to use that knowledge
although it could be a bit more difficult
to make something actually inaccessible you need to block access to the memory that contains it
Yes
What is the smallest subset of ascii that is turing complete in python 
if whle01:=-s or something?
do you technically need loops for turing completeness?
for writing a turing machine, sure, but for finite instructions you can just have as many ifs as possible repeats
Don't you? For jumps effectively
Though I see what you mean
For finite inputs and outputs finite ifs ought to work 
you need loops for turing completeness
and a turing cumpuitable function halts after arbitrarily many repeats
a turing complete system may have an infinite loop
ah
right 
ah " It is assumed that additional storage space can be given to the procedure whenever the procedure asks for it."
so not infinite but so arbitrarily large there is no finite number of switches that complies with the def
okay so do you need - and both 1 and 0
I'm wondering if you'd need a <
ah true
But I assume not if you can turn python into subleq
Wait, then you would need <
and newline of course
Idk if else is needed 
is recursion as a form of looping considered turing-complete
well, can it simulate a turing machine
yes
look at haskell
or scheme
loops are required for turing completeness but they're not really part of the definition of turing-completeness, the definition of turing-completeness is to do with turing machines
so a lot of somewhat odd things can be turing-complete if they can simulate turing machines, even if there is no obvious looping at all
ye, for example rule 110
or the game Recursed
tfw still busy mapping types
im just wondering if anybody here is good at python, and can take a look at my code to see if they can reduce the size of it. the games file size is currently 3kb and i want to reduce it as much as possible while still having a playable game
abdlm :() is Turing complete. You can make lambda calculus in it.
Don't you also need and/or to make choices? What about printing things?
what exactly is this?
Printing isn't necessary for Turing completeness, and Boolean logic can be encoded in the calculus. My intro to lambda calculus was 'Programming with Nothing', an article about Ruby closures. It might be informative and/or impossible to understand.
A lambda is an anonymous function in Python. All it can do is return an expression. However, that expression can be another lambda function. The 'lambda calculus' is a model of computation that only uses functions returning functions, invented by Alonzo Church.
no I know and understand that, I was curious as to your syntax, and the name abdlm
I was wondering if it was a typo or if this was something a bit more abstract I'd yet to hear of
I just put lambda : in alphabetical order.
oh lmao
(Python lambdas are lambda arg, *args, kwarg=1: arg + arg.)
How would you do Boolean algebra with lambdas tho
I've been trying to figure it out but can't lol
>>> andf = lambda x, y: x and y
>>> andf(1, 0)
False
No n
T=lambda a: lambda b: a
F=lambda a: lambda b: b
``` is the convention
What in the world
exchr()=+ lets you form integers, chr them, concatenate them, and exec them
I know, exec is boring
You don't need the equals do you
you'll need a 1 or 0 to start adding ints (()==(), ()==chr)
Though, I think you don't need null bytes
so replace = with 1 and programs will be much shorter
Fair
I wonder whether you could do something wacky with repeated % substitution
Okay I'm starting to see how this works with Boolean algebra, but it only works for truth tables with one output right? I don't see this creating a half adder
A half adder is two different expressions.
You can make cons lists though. I believe it's something like lambda head: lambda tail: lambda func: func(head)(tail).
So if you wanted to store two bits together, you'd call cons(bit1)(cons(bit2)(nil)) for some nil.
There's probably a fair bit more machinery for distinguishing a nil from a cons, but it just amounts to giving a callback a boolean.