#esoteric-python
1 messages ยท Page 4 of 1
haven't done solar system yet
exactly 8 hours
Including stopping for a moment to watch netflix because adhd
Would you like to user test it? wasd turn to move one space, arrow keys turn to move one panel. Esc to quit
There might be one bug, find it and I'll show you how to make pretty loadbars.
Oddly specific reward
i did find it
i mean like not in the code
the game
It's the one where it lags, then you die?
yes
The other option was set t to now+.5 instead of previous time +.5, but the lag is still there
Esc cuts the lag, so it's not real lag
I think I might have an idea of the cause, but I can't fix it now.
Well technically I can, but there's a high risk of accidentally deleting it, I have a discord bot running on my laptop and I'm on phone.
big funny
Noice

1 liner to play tic-tac-toe with the boys
(there is nothing that prevent char overriding so be careful when you play bcs it ends after 9 plays and there is no win detection but im sure you know the rules)
(i:=0,p:=True,g:=["โก"]*9,[(g.__setitem__(int(input())-1,"X"if(p:=not p)else"O"),[print(c,end=""if(i:=i+1)%3else"\n")for c in g])for h in g])
||fucky wucky with getattr and f_locals inspection||
figured
im not sure where to ask this: lets say i use "pip install -e" to install the package im developing for in my user folder. i install this to a python virtualenv that all users on the machine can access. will other users be able to use this package properly? will they need permissions to access files in my user folder for it to work?
Yes, unless you install it in program files
why is your / backwards
In the screenshot
oh do you use windows?
that explains it lol
ewww linux
can you show code pls?
ewww windows, more like
from fishhook import hook
import inspect
def __getattr__(self, s):
f = inspect.currentframe().f_back.f_locals[s]
return lambda *args, **kwargs: self(f(*args, **kwargs))
hook(type(lambda: 0))(__getattr__)
hook(type(print))(__getattr__)
def double(x):
return 2 * x
def square(x):
return x**2
print . double . square (5)
cool
chaining functions using @ is more pythonic, i think (and it doesnt require that hacks)
print @ double @ square (5)
you could __import__('sys')._getframe(1).f_locals[s]
@hook(type(lambda: 0))
@hook(type(print))
def __getattr__(self, s):
...
# instead of:
def __getattr__(self, s):
...
hook(type(lambda: 0))(__getattr__)
hook(type(print))(__getattr__)
onelinerised ```py
from fishhook import*;import sys;g='getattr';hook(type(print),g)(hook(type(lambda:0),g)(lambda s,k:lambdaa,**k:s(sys._getframe(1).f_localsk)));double=lambda x:2x;square=lambda x:x**2;print.double.square(5)
Doesn't f_locals just return the names instead of the object?
nah, it's a dictionary
lmao pythonic is not a concern in this channel
. was for imitating haskell
Oh nice
good to know ๐
wolfram mathematica uses @ to apply functions
so f @ x == f(x) and f @ g @ x == f(g(x))
bad precedence there
that being said, get ready for my custom operators library
you can use >>= in expression position
and <$>
and all the fun stuff
like (+) and `foo`
how to add support for your operators into some tools (black and mypy, for example)?
by screaming, typically
tl;dr explanation?
And what will these operators do?
codecs.register(customcodec)before your module is parsed# coding: yourcustomcodec
interesting
โจ custom โจ
(part 1 may require sitecustomize/.pth dumbness if you don't want to explicitly import your module from a "runner")
https://paste.pythondiscord.com/zoxevegunu.py fixed the bug
!e ```py
class Function:
overloads = {}
def overload(self, argument_types, keyword_types=[]):
return lambda function: self.overloads.update({tuple([tuple(argument_types), tuple(keyword_types)]): function})
def call(self, *args, **kwargs):
for overload in list(self.overloads.items()):
if [*map(type, args)] == [*overload[0][0]]:
if len(sum(kwargs.items(), ())) > 0:
if [*map(type,[*kwargs.values()])] == [*overload[0][1]]:
return overload[-1](*args, **kwargs)
return overload-1
a = Function()
@a.overload([int, int])
def test(_a: int, _b: int) -> int:
return _a + _b
@a.overload([int, str])
def test(_a: int, _b: str) -> int:
return str(_a) + _b
print(a(3, 3))
print(a(3, "hello"))```
@sly root :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 6
002 | 3hello
if you're anyways using type hints, may as well use those instead of explicitly providing the signature
what's the newline character posting ratelimit in this server?
!e ```py
class Function:
overloads = {}
def overload(self):
return lambda function: self.overloads.update({tuple([*function.annotations.values()])[:-1]: function})
def call(self, *args, **kwargs):
for overload in list(self.overloads.items()):
if [*map(type, args), *map(type, [*kwargs.values()])] == [*overload[0]]:
return overload[-1](*args, **kwargs)
else: continue
return None
a = Function()
@a.overload()
def test(_a: int, _b: int) -> int:
return _a + _b
@a.overload()
def test(_a: int, _b: str) -> int:
return str(_a) + _b
print(a(3, "hello"))
print(a(238, 391))```
@sly root :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 3hello
002 | 629
Wrong channel but 10 in a row in one message or 100 over 10 seconds
That's what my bot config has anyway, which I assume is the same as for @night quarry
config-default.yml lines 441 to 444
newlines:
interval: 10
max: 100
max_consecutive: 10```
Whatโs code gore?
making code look really ugly
!e alternative using inspect
import inspect
nope = object()
overloads = {}
def overload(fn):
def wrapper(*args, **kwargs):
for sig, func in overloads.get(fn.__qualname__, []):
bound = sig.bind(*args, **kwargs)
for name, value in bound.arguments.items():
if not isinstance(value, func.__annotations__[name]):
break
else:
return func(*args, **kwargs)
raise TypeError("beep boop")
overloads.setdefault(fn.__qualname__, []).append((inspect.signature(fn), fn))
return wrapper
@overload
def add(x: int, y: int): return x + y
@overload
def add(x: str, y: int): return f"{x} says {y}"
print(add(23, 53))
print(add("foo", 53))
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 76
002 | foo says 53
https://paste.pythondiscord.com/piziwepina.py here it is debugged, but golfed to under 4k characters
So like C
fn=type("fn",(),{"_x":{},"_o":lambda _0:lambda _1:_0._x.update({tuple([*_1.__annotations__.values()])[:-1]:_1}),"__call__":lambda _0,*_1,**_2:[_3[-1](*_1,**_2)for _3 in[*_0._x.items()]if[*map(type,_1),*map(type,[*_2.values()])]==[*_3[0]]][0]})
minified
I think using __dict__ will be better instead of defining a class property
class Function:
def overload(self):
return lambda function: self.__dict__.update({tuple([*function.__annotations__.values()])[:-1]: function})
def __call__(self, *args, **kwargs):
for overload in [*self.__dict__.items()]:
if [*map(type, args), *map(type, [*kwargs.values()])] == [*overload[0]]:
return overload[-1](*args, **kwargs)
else: continue
return None ```
nice
yes
I just tested it for 2D usage score=__name__=='__main__'==Interface(10,10,1,1).run().score and 3D usage score=__name__=='__main__'==Interface(10,10,10,1).run().score.
It works great, so the 2D only script is now redundant
meaning 3D snake is also done
I'm just putting it in a MuTaBlE DeFaUlT ArGuMeNt now:
def overload(fn, overloads={}, nope=object()):
def wrapper(*args, **kwargs):
for sig, func in overloads.get(fn.__qualname__, []):
bound = sig.bind(*args, **kwargs)
for name, value in bound.arguments.items():
if not isinstance(value, func.__annotations__[name]):
break
else:
return func(*args, **kwargs)
raise TypeError("beep boop")
overloads.setdefault(fn.__qualname__, []).append((inspect.signature(fn), fn))
return wrapper
oh no!
anyway...
2D snake, 3D snake and 4D snake in one week, and not necessarily in that order
why is nope=object()?
Oh, I don't need it anymore; an artifact from a previous version
ancient artifact
lmao
as promised ```py
import('os').system('')
def loadbar(size):
def map(f,*a):
nonlocal size;[]=result=()
try:assert(l:=len(a:=[*zip(a)]))
except:return f()
print(f"\x1b[42m[\x1b[m{' 'abs(size)}\x1b[44m]\x1b[m {l} iterations remaining. ",end='\x1b[G',flush=1)
for i,e in enumerate(a):
result+=f(e),;n=iabs(size)//l
r=12;g=255-(b:=i255//l);o=gb//255;g+=o;b+=o # change formulae for r,g,b as needed
print(f"\x1b[42m[\x1b[{n+1 if size>0 else-size-(n-1)}G\x1b[48;2;{r};{g};{b}m \x1b[44m\x1b[{abs(size)+1}G]\x1b[m {l-i} iterations remaining. ",end='\x1b[G',flush=1)
print(f'\x1b[42m[\x1b[{abs(size)+1}G\x1b[44m]\x1b[m 0 iterations remaining. ');return result
return map
import time
loadbar(-40)(time.sleep,[.1]*60)
golfed:
overload=lambda fn,o={}:o.setdefault(fn.__qualname__,[]).append((inspect.signature(fn),fn))or(lambda*a,**k:any(all(isinstance(v,(F:=f).__annotations__[n])for n,v in s.bind(*a,**k).arguments.items())for s,f in o.get(fn.__qualname__,[]))and F(*a,**k)or beep)
(yeah, I could rename fn to something else..)
also, beep is unnecessarily long
overload=lambda c,o={}:o.setdefault(q:=c.__qualname__,[]).append((__import__("inspect").signature(c),c))or(lambda*a,**k:any(all(isinstance(v,(F:=f).__annotations__[n])for n,v in s.bind(*a,**k).arguments.items())for s,f in o.get(q,[]))and F(*a,**k)or X)
other than changing the public API, I see no obvious spots for saving bytes
you can change isinstance to type(v)==...
but that changes behaviour, then I couldn't annotate int and have it accept bools
greyblue made a complex version of this
i also placed it in my repo https://github.com/thatbirdguythatuknownot/sniplections/blob/main/dynamic_dispatch.py
Collection of various snippets/files that I made. Contribute to thatbirdguythatuknownot/sniplections development by creating an account on GitHub.
^^^
at least we don't need an emulator to play games
your terminal language sucks though
what terminal language
cmd or pwsh?
ok but why does it suck
I'm on mobile, so i can't type fast
you're gonna have to wait a bit lol
ok tbh i don't even care anymore i just wanna have all of the stuff i want conveniently included in one thing without needing anything else
Oh so when itโs as short as it can be, you can go another level by shaving off bytes.. haha!! Love it
New challenge, a calendar that prints every day of the year for a whole year; starting from Monday, jan 1st 1999
No rules except thatโฆ.. GO!!!
batch too
that's pretty bad
Idk if you'd consider it a terminal language, but the point still stands...
Batch and cmd are almost the same thing
PowerShell has a few os interactions cmd can't do, otherwise I rarely use it.
I tend to use it for running scripts that need to be on for a couple weeks
Because blue = donโt close this window
You can make cmd blue
color followed by two hexadecimal characters
Figure out which one is blue and you have blue terminal
Alternatively, typing ctrl-[, [44m will begin text with a blue background, then you can fill the terminal with spaces or whatever
You now have no use for pwershell
You probably want 1f though not 17
(it doesn't work)
That's why you don't use gui, graphics are lame when you already have a terminal
What do you make of this, should I keep these fractional loadbars like such?
or negative loadbar size?
or negative loadbar size goes backwards?
.bm
GitHub copilot wrote it all
Donโt care what anyone says Iโve learned more with copilot then without it
Itโs one of the best tools Iโve ever seen, and it suited my beginner level when it came out so I ended up learning so much from it.
It a funny way, it doesnโt show you how to write the best code. Somehow it telegraphs that to you if your not a complete beginner
So you end up writing better code, and therefore learning how to write better code
Making a habit of constant improvement
I seen so many videos saying itโs a waste of time or it will make you lazy, but if Iโm being paid to write hundreds of lines of code by myself, a little bit of help (sometimes a lot) goes a long way
I think the future is going to be all AI assisted programming and, It will only raise the bar for skill level
the style of code I write cannot be produced with ai, I would probably break the ai, or corrupt it and cause the robot revolution.
the second you start writing code which hasn't been done before, copilot gets really useless. Though doing that is quite rare most of the time.
Copilot is useful
dang! this channel is awesome
You cannot leave this channel mortal
You had not heeded the warning
You are doomed to be driven insane in this God forsaken realm
With no exit in sight
If you manage to leave, you will bring dangers of which you cannot fathom to the land of mortals.
Armageddon will rear its head while all those under it cower.
In a other words, welcome to #esoteric-python
Hi uh, just for reference whats code gore? Listed on this chat description
Deliberately ugly, terrifying code
Hurts to look at, you'll want to wash your eyes afterwards. Like regular gore, but with code.
you can find several instances of such code at https://doc.rust-lang.org/book/
Thanks both of you ๐๐๐ @restive void @maiden blaze
(my message was a joke btw)
oof, well i didnt get it lmfao
having read chapter 15 i don't think it's a joke
target acquired
you should've at least linked to the nomicon lol
way more appropriate here
The Dark Arts of Advanced and Unsafe Rust Programming
lmao
welp
parents took my phone while I was typing
sorry!
I agree lol
but, bc I use Linux, I'm contractually obligated to argue that Linux is superior, even when imo they're roughly equivalent OSs
No
Never
Rust isn't as good as Python, but compared to C/C++ it's beautiful
Rust is still too new to have truly esoteric code, but in a few years maybe when it's 10 it will be a worthy competitor
Donno what ur on about rust is omega pretty
You can't compare Rust with python!
import string; print('\n'.join(map(str,[f"{char} has index {num}" for num, char in [*map(list,[*zip([i+1 for i in range(26)], [i for i in "".join(sorted(set(__import__("re").findall("\\w","".join("".join(__import__(m).__dict__).lower() for m in("collections", "builtins"))))-{"_"}))])])]])))
any way to make this more complicated and hard to read?
i seriously wanna do dunder methods right now but i don't wanna go through the hardships of that again
dunder method?
could replace string.ascii_lowercase with "".join(sorted(set(__import__("re").findall("\\w","".join("".join(__import__(m).__dict__).lower() for m in("collections", "builtins"))))-{"_"}))
what the HELL is taht
complicated and hard to read
like that????
!e
import string; print('\n'.join(map(str,[f"{char} has index {num}" for num, char in [*map(list,[*zip([i+1 for i in range(26)], [i for i in "".join(sorted(set(__import__("re").findall("\\w","".join("".join(__import__(m).__dict__).lower() for m in("collections", "builtins"))))-{"_"}))])])]])))
@sullen kayak :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | a has index 1
002 | b has index 2
003 | c has index 3
004 | d has index 4
005 | e has index 5
006 | f has index 6
007 | g has index 7
008 | h has index 8
009 | i has index 9
010 | j has index 10
011 | k has index 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/yedoqucibo.txt?noredirect
!e can make the second part a bit more obscure
print('\n'.join(map(str,[f"{char} has index {num}" for num, char in [*map(list,[*zip([i+1 for i in range(26)], [i for i in "".join(map(chr,sorted(filter((95).__lt__,map(ord, set(__import__("re").findall("\\w","".join(dict.__or__(*(__import__(m).__dict__ for m in(str({}.__class__.__module__),"collections")))))))))))])])]])))
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | a has index 1
002 | b has index 2
003 | c has index 3
004 | d has index 4
005 | e has index 5
006 | f has index 6
007 | g has index 7
008 | h has index 8
009 | i has index 9
010 | j has index 10
011 | k has index 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ipukujerak.txt?noredirect

easy, look: compare Rust Python :: Ordering
Yeah, or just define __eq__ and __lt__ on type(Python) and type(Rust) and then use the functools.total_ordering decorator.
Does this count as code gore? It's a 7572 lines long list.
what are you trying to do
it's annoying, dump it in a .pickle file and load it up on startup everytime instead
!e
print('\n'.join(map(str,[f"{char} has index {num}" for num, char in [*map(list,[*zip([i+1 for i in range(26)], [i for i in "".join(sorted(set(__import__("re").findall("\\w","".join("".join(__import__(m).__dict__).lower() for m in("collections", "builtins"))))-{"_"}))])])]])))
@sullen kayak :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | a has index 1
002 | b has index 2
003 | c has index 3
004 | d has index 4
005 | e has index 5
006 | f has index 6
007 | g has index 7
008 | h has index 8
009 | i has index 9
010 | j has index 10
011 | k has index 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/idugelecac.txt?noredirect
i think this describes the pattern well enough.
A simple change is to replace strings with hex-escapes
That does make it visually longer though, if you're wanting it short
E.g. "ABC" would be "\x41\x42\x43" (https://www.asciitable.com/ gives hex codes of the different ascii characters)
oh nonono
i do not want it short
i just want it to be hard to read
ynno
for fun ^w^
Also not sure what the point of the import string is given that you don't seem to be using it anywhere
Then hex escapes are your friend ๐
old code was more readable
But you're not using the import
import string; print('\n'.join(map(str,[f"{char} has index {num}" for num, char in [*map(list,[*zip([i+1 for i in range(26)], [i for i in string.ascii_lowercase])])]])))
Right, there you are
!e
print('\n'.join(map(str,[f"{b} \x20\x68\x61\x73\x20\x69\x6E\x64\x65\x78\x20 {a}"for a,c in[*map(list,[*zip([i+1for i in range(26)],[i for i in "".join(sorted(set(__import__("re").findall("\\w","".join("".join(__import__(m).__dict__).lower()for m in("collections", "builtins"))))-{"_"}))])])]])))
@sullen kayak :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | a has index 1
002 | b has index 2
003 | c has index 3
004 | d has index 4
005 | e has index 5
006 | f has index 6
007 | g has index 7
008 | h has index 8
009 | i has index 9
010 | j has index 10
011 | k has index 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/etuneposew.txt?noredirect
i wonder how that works
You can also remove some spaces that aren't needed
e.g. " for -> "for
i+1 for -> i+1for
(there's others too just cba to list all of them)
The second works since Python knows variables/keywords can't start with a number so it'll implicitly add the space if it sees a number then a letter
!e print("\x20\x68\x61\x73\x20\x69\x6E\x64\x65\x78\x20")
@sullen kayak :white_check_mark: Your 3.11 eval job has completed with return code 0.
has index
easy.
!e
print('\n'.join(map(str,[f"{c} \x20\x68\x61\x73\x20\x69\x6E\x64\x65\x78\x20 {a}"for a,c in[*map(list,[*zip([i+1for i in range(26)],[i for i in "".join(sorted(set(__import__("re").findall("\\w","".join("".join(__import__(m).__dict__).lower()for m in("collections", "builtins"))))-{"_"}))])])]])))
smhh
@sullen kayak :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:1: SyntaxWarning: invalid decimal literal
002 | a has index 1
003 | b has index 2
004 | c has index 3
005 | d has index 4
006 | e has index 5
007 | f has index 6
008 | g has index 7
009 | h has index 8
010 | i has index 9
011 | j has index 10
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/usiyapicem.txt?noredirect
amazing.
You can do it for all of those strings
Even the {c} and {a} iirc
And then the imports etc.
There's also a space I think after the in in i for i in "".join(...) that isn't needed (for i in"".join(...))
Even the space too iirc
!e
import re
source = R"""print('\n'.join(map(str,[f"{c} \x20\x68\x61\x73\x20\x69\x6E\x64\x65\x78\x20 {a}"for a,c in[*map(list,[*zip([i+1for i in range(26)],[i for i in "".join(sorted(set(__import__("re").findall("\\w","".join("".join(__import__(m).__dict__).lower()for m in("collections", "builtins"))))-{"_"}))])])]])))"""
ESCAPE = "R_"
SORTED = f"{ESCAPE}S__"
BUILTINS = f"{ESCAPE}B__"
KEYS = f"{ESCAPE}K__"
SORTED_STR = "".join(map(lambda x: "\\" + hex(x)[1:], list(bytes("sorted", "utf-8"))))
for i, b in enumerate(sorted(__builtins__.__dict__.keys())):
x = f"(lambda {ESCAPE}_:{BUILTINS}[{SORTED}([{ESCAPE}__ for {ESCAPE}__ in {KEYS}])[{ESCAPE}_]])({hex(i)})"
source = re.sub(rf"((?<![\w\.\']){b}(?!\w))", x, source)
source = f"(lambda {BUILTINS}: (lambda {SORTED},{KEYS}:{source})({BUILTINS}['{SORTED_STR}'],{BUILTINS}.keys()))(__builtins__.__dict__)"
print(source)
@twin reef :white_check_mark: Your 3.11 eval job has completed with return code 0.
(lambda R_B__: (lambda R_S__,R_K__:(lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x85)('\n'.join((lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x7b)((lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x90),[f"{c} \x20\x68\x61\x73\x20\x69\x6E\x64\x65\x78\x20 {a}"for a,c in[*(lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x7b)((lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x79),[*(lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x96)([i+1for i in (lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x87)(26)],[i for i in "".join((lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x8e)((lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x8b)((lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x4d)("re").findall("\\w","".join("".join((lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x4d)(m).__dict__).lower()for m in("collections", "builtins"))))-{"_"}))])])]]))))(R_B__['\x73\x6f\x72\x74\x65\x64'],R_B__.k
... (truncated - too long)
Full output: https://paste.pythondiscord.com/mojovuzani.txt?noredirect
!e
(lambda R_B__: (lambda R_S__,R_K__:(lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x85)('\n'.join((lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x7b)((lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x90),[f"{c} \x20\x68\x61\x73\x20\x69\x6E\x64\x65\x78\x20 {a}"for a,c in[*(lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x7b)((lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x79),[*(lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x96)([i+1for i in (lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x87)(26)],[i for i in "".join((lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x8e)((lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x8b)((lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x4d)("re").findall("\\w","".join("".join((lambda R__:R_B__[R_S__([R___ for R___ in R_K__])[R__]])(0x4d)(m).__dict__).lower()for m in("collections", "builtins"))))-{"_"}))])])]]))))(R_B__['\x73\x6f\x72\x74\x65\x64'],R_B__.keys()))(__builtins__.__dict__)
@twin reef :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:1: SyntaxWarning: invalid decimal literal
002 | a has index 1
003 | b has index 2
004 | c has index 3
005 | d has index 4
006 | e has index 5
007 | f has index 6
008 | g has index 7
009 | h has index 8
010 | i has index 9
011 | j has index 10
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/eruhocatox.txt?noredirect
wow it worked
i'm bored i'm goina make my randomised variant of python
WHAT????
who hurt you
it's an obfuscator i made some time ago, it simply replaces built-in functions with (approximately) __builtins__.__dict__[__builtins__.__dict__.keys()[{index of builtin}]]
simple yet effective
oh and welcome to esoteric python
i feel like this can be done quite easily
i'll try it
yeah here's a better way to do this
load_bar=lambda s:(lambda g,b,l,k:[(l:=l+f'\033[38;2;0;{g};{b};1mโ\033[0m',b:=b-k,g:=g+k,__import__('time').sleep(.1),print('\033[1A',end=''),print(l))for i in range(256//s)][-1][0])(0,256,'',s%256)
load_bar(2)```
not exactly as estoeric, but shorter
load_bar=lambda s:(lambda g,b,l,k:[(l:=l+f'\033[38;2;0;{g};{b};1mโ\033[0m',b:=b-k,g:=g+k, __import__('time').sleep(.1),print('\033[1A',end=''),print(l))for i in range(256//s)][-1][0])(0,256,'',s%256)
load_bar(2)โ
```without redundant spaces (-2 spaces)
bruh
golf this ```py
from inspect import signature
def fuckup(func):
@import('functools').wraps(func)
def _(a,**k):
return func(**dict((k,v2 if import('random').random()>.5 else v)if not(isinstance(v, bool))else(k,0 if v else 1) for k, v in signature(func).bind(*a,**k).arguments.items()))
return _
def f(func):
@import('functools').wraps(func)
def i(*a,**k):
c={}
for i, v in signature(func).parameters.items():
if v.kind is v.POSITIONAL_OR_KEYWORD:
if v.annotation!=v.empty:
if not(isinstance(signature(func).bind(*a,**k).arguments[v.name], v.annotation)):c[v.name]=v.annotation(signature(func).bind(*a,**k).arguments[v.name])
else:c[v.name]=signature(func).bind(*a,**k).arguments[v.name]
else:c[v.name]=signature(func).bind(*a,**k).arguments[v.name]
else:c[v.name]=signature(func).bind(*a,**k).arguments[v.name]
return func(**c)
return i
class b(str):
@fuckup
@n
def format(s, b,f:int):
return b.str()*f
@print
@lambda a: b().format(*a)
@lambda x: (x.doc[0], x.doc[1])
class _:
doc=("101101010101", import('random').randint(0, 100)^7)```
oneline fizzbuzz (still trying to get rid of x, but don't think it's possible.)
print(*[("fizz" if x % 3 == 0 else "") + ("buzz" if x % 5 == 0 else "") or x for x in range(1, 101)])
output:
1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz fizz 22 23 fizz buzz 26 fizz 28 29 fizzbuzz 31 32 fizz 34 buzz fizz 37 38 fizz buzz 41 fizz 43 44 fizzbuzz 46 47 fizz 49 buzz fizz 52 53 fizz buzz 56 fizz 58 59 fizzbuzz 61 62 fizz 64 buzz fizz 67 68 fizz buzz 71 fizz 73 74 fizzbuzz 76 77 fizz 79 buzz fizz 82 83 fizz buzz 86 fizz 88 89 fizzbuzz 91 92 fizz 94 buzz fizz 97 98 fizz buzz
for prettier outputs
print("\n".join([("fizz" if x % 3 == 0 else "") + ("buzz" if x % 5 == 0 else "") or f"{x}" for x in range(1, 101)]))
i=0
while i<100:i+=1;print('FizzBuzz'[i%~2&4:12&8+i%~4]or i)
seems like the shortest possible but its 2 lines
i found this here
Contains shortest solutions to fizzbuzz in various programming languages - GitHub - rsha256/shortest-fizzbuzz: Contains shortest solutions to fizzbuzz in various programming languages
so if we combine those we would get this.
print(*["FizzBuzz"[x%~2&4:12&8+x%~4] or x for x in range(1, 101)])
[x%~2&4:12&8+x%~4]
what in the heck is that
~ what dis do
~
???
What is the Tilde ~ in Python? Python's Tilde ~n operator is the bitwise negation operator: it takes the number n as binary number and โflipsโ all bits 0 to 1 and 1 to 0 to obtain the complement binary number. For example, the tilde operation ~1 becomes 0 and ~0 becomes 1 and ~101 becomes 010 .
what the fuck why
is for pure binary calculations
for doing what?
magic
those are identical so the ~2 in this case is just there to prevent ()
print([i%~2&4 for i in range(0, 10)])
print([i%(-3)&4 for i in range(0, 10)])
to copy paste calculations from other languages
i dont understand this
you don't even need the () there
It's supposed to be a wrapper to make map-like function
!e ```py
print(*["FizzBuzz"[x%-3&4:12&8+x%-5]or x for x in range(1, 101)])
does exactly the same thing
you don't need ()
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz
eww too much whitespace
print(*["FizzBuzz"[x%-3&4:12&8+x%-5]or(x)for(x)in range(1,101)])
this one is one character shorter.
You really need to stop putting spaces after commas and colons if you wanna golf
save yourself 2 characters by turning it from a comprehension to a regular for loop and letting each print happen on its own line
!e ```py
for x in range(1,101):print("FizzBuzz"[x%-3&4:12&8+x%-5]or x)
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/omahedovuq.txt?noredirect
!e save 1 byte by changing it into a while loop ```py
x=1
while x<101:print("FizzBuzz"[x%-3&4:12&8+x%-5]or x);x+=1
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/qowiderama.txt?noredirect
If only python had x++ like other languages
You can make ++x work, at least..
it will break simple +x, won't it?
yep, it will, bc you would have to hook unary +
though, unary + doesn't do much of anything lmao
!e
All you need to do is hide the identifier after it :P
๐ผ = 5
๐ผ += 2
print(๐ผ)
@sudden osprey :white_check_mark: Your 3.11 eval job has completed with return code 0.
7
Not necessarily :D
Just find some unused bit somewhere in the int object
How do you distinguish +x from ++x?
if you patch unary plus then type(+x) != int
and you can't really mock it because +(+x) shouldn't be equivalent to ++x
so you must break +x to make ++x work ๐ฆ
!e
import fishhook, ctypes
@fishhook.hook(int)
def __pos__(self):
refcount = ctypes.c_int.from_address(id(self))
if refcount.value > 100000:
refcount.value -= 100000
ctypes.c_int.from_address(id(x) + int.__basicsize__).value += 1
else:
refcount.value += 100000
return fishhook.orig(self)
x = 234234
print(x)
++x
print(x)
+x
print(x)
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 234234
002 | 234235
003 | 234235
:P
type(+x) is int, but +(+x) is equivalent to ++x. No way around that without changing grammar.
oh wow thats smart
well.... but doing +x, and then +x again, it still does ++x.
(Also, never do this with any integer someone else uses.)
You could.... inspect the frame, get the source of your caller and manually check that there are two unary adds after each other in the bytecode..
You can
- Hook function call procedure
- Inspect function bytecode on each call
- Find double unary adds
- Check their span in source code
- If they are next to each other, patch bytecode with incrementation
But hooking function call involves ugly things that break debuggers, etc.
nah, no one cares
who uses a debugger anyway
I just use 18,000,000 prints everywhere
!e
Not sure if this counts, or will even work on snekbox, but 3.11 makes this a bit easier (I just guessed this btw so it's probably wrong).
import inspect
class F():
def __pos__(self):
f = inspect.getframeinfo(inspect.currentframe().f_back)
if f.code_context[0][f.positions.col_offset-1:].startswith("++"):
print("double add")
else:
print("single add")
return self
x = F()
++x
print("---")
+(+x)
@sudden osprey :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 12, in <module>
003 | File "<string>", line 5, in __pos__
004 | TypeError: 'NoneType' object is not subscriptable
๐
How to print 1+1?
First of all, ask this in #python-discussion
Second of all,
print("something") # < Prints "something"
1 + 1 # < Calculates 1 + 1
Does that help?
Thx
No but print 1+1 not calculate
Anyways
Doesnt matter
that is simple
I have given you the skills to do that
Whatever you put in print is printed
/run
Def print1plus1():
_1plus1=("1" + "+" + "1")
Print(_1plus1)
I was especting a more esoteric answer btw
Ok
But are u able to do it btw?
I believe so
!e
print("1+1")
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
1+1
it's not much of a challenge?
That looks normal
why
!e
one = 1
plus='+'
opo=f'{one} {plus} {one}'
print(opo)
print(exec(opo))
a. I'm on mobile rn so I don't feel like typing
b. this is a good opportunity for you to learn to do it esoterically yourself
I tryed here
I this esoteric
Just run it for me pls i dont know the boy
Bot*
Yeah, mobile is annoying.
that ain't esoteric enough
How to run code?
!e
_=__import__('s'.__add__('y'.__add__('s'))).stdout.write(int(True).__str__()+'+'+int(True).__str__()+'\n')
@royal whale :white_check_mark: Your 3.11 eval job has completed with return code 0.
1+1
to run a python script, put !e as the beginning of your message, then a newline, then 3 backticks (`) then python
then your code
then a newline
then 3 backticks (`)
also it's invalid code
capitalization and indentation
and "print"
Im on mobile
jessyage = 18
Def print1plus1():
_1plus1=int("1" + "+" + "1")
str(_1plus1)
if jessyage == 18:
print(_1plus1)โ
Might this work?
what are you tring to do?
"Def" should be "def"
Can u fix it and run it for me
!e
jessyage = 18
def print1plus1():
_1plus1=int("1" + "+" + "1")
str(_1plus1)
if jessyage == 18:
print(_1plus1)
Run it
!e
(print((lambda:("1+1"))())if((_:=18)==18)else())
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
1+1
!e
from ast import*
print(unparse(eval("Expr(value=BinOp(left=Constant(value=1), op=Add(), right=Constant(value=1)))")).replace(" ",""))
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
1+1
!e
jessyage = 18
_1plus1=0
def print1plus1():
global _1plus1
_1plus1=int("1" + "+" + "1")
str(_1plus1)
if jessyage == 18:
print(_1plus1)
@quiet bone :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 6, in <module>
003 | NameError: name '_1plus1' is not defined
!e
jessyage = 18
_1plus1=0
def print1plus1():
global _1plus1
_1plus1=int("1" + "+" + "1")
str(_1plus1)
if jessyage == 18:
print(_1plus1)
@quiet bone :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 5
002 | _1plus1=int("1" + "+" + "1")
003 | IndentationError: unexpected indent
!e ```py
print(*map(chr,[(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1)),(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1)),(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))+(1and(1))]),sep="")
@old socket :white_check_mark: Your 3.10 eval job has completed with return code 0.
1+1
Not really esoteric though
instead of (1and(1)), you can save a character by using (1and 1)
It's not about saving characters here
true lol
[_:=0o0,[(_:=_+-~0o0)for __ in range(ascii_code_for_whatever_char_youre_making)],_][~0o0]```does functionally the same thing
Basically just a fanicer way of saying ascii_code_for_whatever_char_youre_making because it doensn't output a string you can copy and paste that does it
It just outputs the ascii_code_for_whatever_char_youre_making again
Ye more of a unecessary spamming
Can u make an esoteric code to print 1+1?
I cba
U made a Collective Barging Agreement?
yes
With who
with me
Cool
lemme start it up
Make the most esotericest of all of them
something with several layers of encoding and decoding along with adding a bunch of characters would take an hour, and i don't have that sort of time
i'll write a relatively small one
__import__('sys').stdout.write(chr(int(list((lambda x: map(lambda i: f'{ord(i):b}', x))((lambda decimals: bytes(decimals).decode())((lambda binary: [int(byte, 2) for byte in list(binary)])((lambda text: ([bin(ord(i)).replace('b', '') for i in str(text)]))("".join(map(lambda i: i, (i for i in (lambda string: [i for i in str(string)])(''.join(map(lambda x: (lambda l: chr(l))(int(x, 2)), ['110001'])))))))))))[0], 2)))
@lambda j: (__import__('importlib').import_module('sys').stdout.write(j),exec(r"""exec('print(' + ''.join(map(chr, __import__('zlib').decompress(b'''x\x9ceP\xcd\x0e\x820\x0c~\x95\xc6K\xdb\x84\x10\xf0\xb8W!\x1e6\x98Z3\xc0\x8c\x1d \xc6w\xb7\x83\xe0O\xdc\xa9\xdd\xf7\xd3\xafm\xaf\x91dH\x14dJD\xc1\xf6\xae\xb30\x1b\xe8\xed}\xef\xc4\xc0\x19\x1fc\xecH\xd8\xb8\'\x1603\xbf\xb9\x9do\xa5\xb7a2\xe0\x96\xe4\'\xda{.\xb5\x1a;O_\\\'\x83\x8d\x8b\x81&O\xcc\xf4\x02\x8e\x0c\xe71\xaeZ\x90\x01\xd6\x18\x1b\x8dO\x1fa\xf2s2@\x8d"\xb4\x05\xe12\xfa{\xb0\xad\'t\x9a\x08q\xf3\x91l2\xa5HY\xa1\x0eL\x87Cy\x1bU\xf6\xbb\x90\x14@\xf2Q\xec\x88*e\xb8\xe4\x80\xbfn\xdb\x7fN\x84\xf8g\xa7\xd7\xda\xcb`\xa0\xd5\x83\x06\x9d\x9bW\x9c\xf3~\\@\x83u]UU\x8d\x1a\xe8\xfd\x9a\xea\xb4\xc2/z|x\xaa'''))) + ')')"""))
@lambda x: ''.join(chr(i) for i in x)
@lambda _: map(lambda x: int(x, 2), _)
@lambda _: _.__delattr__(0)
class _:
def __delattr__(self):
return (lambda x: map(lambda i: f'{ord(i):b}', x))((lambda decimals: bytes(decimals).decode())((lambda binary: [int(byte, 2) for byte in list(binary)])((lambda text: ([bin(ord(i)).replace('b', '') for i in str(text)]))("".join(map(lambda i: i, (i for i in (lambda string: [i for i in str(string)])(''.join(map(lambda x: (lambda l: chr(l))(int(x, 2)), ['101011']))))))))))
there you go
@quiet bone
Masterpiece.
now that i think of it, #esoteric-python has practically never gone off topic.
when was the .topic command last run?
Every so often random people come in with beginner questions, I think that's pretty off-topic.
not nearly as much as other channels though
.topic
off-topic for here, because not Python
ye
!e
_ = [print,chr,int,(___:=(((_:=(([]==[])+([{}]!=[])))+(_<<_))+(__:=(~~([]==[])))+_+_+(_/_))*(_+_+_)+_/_),____:=(_i:=([{___}]==[{__}]))+___+_i+_i+_i+_i+_i+_i+_i+_i+_i+_i+_/_+_,(_____:=(__+_))*_____+____,(__+_+_+_+_+_+_+_+_+_+_+_+_)*_**_+__+_+__+__,(_+_+_+_+_<<_____>>__<<_<<_//_%_%_)*(__:=_-_)+_+__+____+_+_+_+__+_]
_[~~([]!=[])](_[[]==[]](_[__:=(~~([]==[])+([]==[]))](_[___:=~~([]==[])+([]==[])+~~([]==[])]))+_[[]==[]](_[__:=(~~([]==[])+([]==[]))](_[___+(~~([]==[]))]))+_[[]==[]](_[__:=(~~([]==[])+([]==[]))](_[___+__]))+_[[]==[]](_[__:=(~~([]==[])+([]==[]))](_[___+__+([]==[])]))+_[[]==[]](_[__:=(~~([]==[])+([]==[]))](_[___*__+(__//__)])))```
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
admin
what the hell
can you explain exactly what the is going on
or at least parts of it
!e
code
!e
print(~[])
@unreal echo :x: Your 3.11 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 ~: 'list'
not x is like this ```py
def not_func(x):
if x is True:
return False
if x is False or x is None:
return True
if hasattr(x, "bool"):
return x.bool() is False
if hasattr(x, "len"):
return x.len() == 0
return False
so it either calls __bool__ or __len__
!e ```py
@type.call
class nope:len=lambda s:0
if not nope:print("yep")
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
yep
!e ```py
from fishhook import*
nt = type(None)
hook(nt,'bool')(lambda s:True)
if None:print("nope")
@floral meteor :warning: Your 3.10 eval job has completed with return code 0.
[No output]
.topic
py_object or c_byte are probably the most convenient
i have a script, which makes an exec() call, and inside the exec is where my code goes
i need to suppress an exception globally (and add some handling)
similar to sys.excepthook, but making it so the program continues running
if anyones up to this, ping me for questions
when the code errors, is it supposed to just do a classic fuckit.py, and continue?
run a hook function, then continue
no clue
the code that may error is in a while True loop
so it should just restart the loop
then you could just do py while True: with fuckit: code
or continue to the next statement, doesnt matter if they all error until the loop restarts
i cant modify the main code though
nor can i use third-party libraries
i like modifying globals() and you cant stop me 
Maybe, but segfault will
You can make some kind of try-except-pass for segfaults: before executing any line, fork. Wait for the child to die with segfault, then skip the line in the parent. When the child dies without a segfault, exit as well.
Sounds like you have a lot of experience with segfault
so you essentially need to replace each raise with hook(Exception())?
I eat segfault for breakfast.
What an unhealthy breakfast
It's okay, I add a healthy seasoning of keyboard interrupt
hey, I am trying to make an eso lang using llvmlite. I got an .ll file but I cant make it into exe
TDLR: I did to make an .o file but I got .obj file!!! (3d file or some shiz)
llc -filetype=obj output.ll
then, I checked my "ls"
-a---- 21/08/2022 12:15 PM 437 output.ll
-a---- 21/08/2022 12:56 PM 687 output.obj
Then I did this anyway
gcc output.o -o output
gcc.exe: error: output.o: No such file or directory
gcc.exe: fatal error: no input files
what is the issue here? thanks
@fossil zodiacthis is more a question for off topic
I am using Python to make it thats why I asked here
ye, I understand the reasoning
got you! Cheers!
my snake game so dense, take this line for example
S.f().f().h=S[0,x//2,0,0].I(v=2,n=3,h=1)
"set two random food positions, then set head to left, half height, topleft panel, initialised as the head of a snake with length 3."
has a small chance of only spawning 1 food as a bethesda style bug/feature
the code matches the coder
not really
i think it can if you really try
disable gc, add -OO flag, patch some memory allocation related stuff
So it can, but only if you really try?
If you're not using @contextlib.contextmanager or otherwise expecting anything to get garbage collected before the end of the program, you can use pypy.
It's not overclocking unless you've gone so meta that you're thinking of python as a machine instead of a virtual machine, but that's up to you...
on every bytecode evaluation step toss a coin with chance 0.01% and if it succeeds os.exit your process
!e
lambda:(
(lambda x,y: x(y), (getattr,
((getattr, (
__import__, "sys"), "stdout"
)), "write"), "Olรก, mundo!")
)
import inspect
def Dicria(expr: tuple):
import types
*to_list, = expr
if isinstance(to_list[0], (types.FunctionType, types.BuiltinMethodType)):
pass
else:
raise SyntaxError
for index, element in enumerate(to_list):
if isinstance(element, tuple):
_ = Dicria(element)
to_list[index] = _
return to_list[0](*to_list[1:])
data = inspect.stack()[0].frame.f_code.co_consts[0]
import types
if isinstance(data, types.CodeType):
_ = lambda:0
_.__code__ = data
Dicria(_())
else:
print(0)
@royal coral :white_check_mark: Your 3.11 eval job has completed with return code 0.
Olรก, mundo!
this seems like it belongs here: https://twitter.com/dabeaz/status/1561655903291596800
not even using a combinator, I am disappointed.
He's continuing to refine it: https://twitter.com/dabeaz/status/1561720921966223361
!e
__import__('sys').stdout.write(chr(int(list((lambda x: map(lambda i: f'{ord(i):b}', x))((lambda decimals: bytes(decimals).decode())((lambda binary: [int(byte, 2) for byte in list(binary)])((lambda text: ([bin(ord(i)).replace('b', '') for i in str(text)]))("".join(map(lambda i: i, (i for i in (lambda string: [i for i in str(string)])(''.join(map(lambda x: (lambda l: chr(l))(int(x, 2)), ['110001'])))))))))))[0], 2)))
@lambda j: (__import__('importlib').import_module('sys').stdout.write(j),exec(r"""exec('print(' + ''.join(map(chr, __import__('zlib').decompress(b'''x\x9ceP\xcd\x0e\x820\x0c~\x95\xc6K\xdb\x84\x10\xf0\xb8W!\x1e6\x98Z3\xc0\x8c\x1d \xc6w\xb7\x83\xe0O\xdc\xa9\xdd\xf7\xd3\xafm\xaf\x91dH\x14dJD\xc1\xf6\xae\xb30\x1b\xe8\xed}\xef\xc4\xc0\x19\x1fc\xecH\xd8\xb8\'\x1603\xbf\xb9\x9do\xa5\xb7a2\xe0\x96\xe4\'\xda{.\xb5\x1a;O_\\\'\x83\x8d\x8b\x81&O\xcc\xf4\x02\x8e\x0c\xe71\xaeZ\x90\x01\xd6\x18\x1b\x8dO\x1fa\xf2s2@\x8d"\xb4\x05\xe12\xfa{\xb0\xad\'t\x9a\x08q\xf3\x91l2\xa5HY\xa1\x0eL\x87Cy\x1bU\xf6\xbb\x90\x14@\xf2Q\xec\x88*e\xb8\xe4\x80\xbfn\xdb\x7fN\x84\xf8g\xa7\xd7\xda\xcb`\xa0\xd5\x83\x06\x9d\x9bW\x9c\xf3~\\@\x83u]UU\x8d\x1a\xe8\xfd\x9a\xea\xb4\xc2/z|x\xaa'''))) + ')')"""))
@lambda x: ''.join(chr(i) for i in x)
@lambda _: map(lambda x: int(x, 2), _)
@lambda _: _.__delattr__(0)
class _:
def __delattr__(self):
return (lambda x: map(lambda i: f'{ord(i):b}', x))((lambda decimals: bytes(decimals).decode())((lambda binary: [int(byte, 2) for byte in list(binary)])((lambda text: ([bin(ord(i)).replace('b', '') for i in str(text)]))("".join(map(lambda i: i, (i for i in (lambda string: [i for i in str(string)])(''.join(map(lambda x: (lambda l: chr(l))(int(x, 2)), ['101011']))))))))))
@near gust :white_check_mark: Your 3.11 eval job has completed with return code 0.
1+1
wrong channel
Hmmm
How old was that
Like, 2 days ago
i go browsing because bored
got a challenge for all those willing
sum up the steps/process of this code
from inspect import signature
def fuckup(func):
@__import__('functools').wraps(func)
def _(*a,**k):
return func(**dict((k,v*2 if __import__('random').random()>.5 else v)if not(isinstance(v, bool))else(k,0 if v else 1) for k, v in signature(func).bind(*a,**k).arguments.items()))
return _
def f(func):
@__import__('functools').wraps(func)
def i(*a,**k):
c={}
for i, v in signature(func).parameters.items():
if v.kind is v.POSITIONAL_OR_KEYWORD:
if v.annotation!=v.empty:
if not(isinstance(signature(func).bind(*a,**k).arguments[v.name], v.annotation)):c[v.name]=v.annotation(signature(func).bind(*a,**k).arguments[v.name])
else:c[v.name]=signature(func).bind(*a,**k).arguments[v.name]
else:c[v.name]=signature(func).bind(*a,**k).arguments[v.name]
else:c[v.name]=signature(func).bind(*a,**k).arguments[v.name]
return func(**c)
return i
class b(str):
@fuckup
@n
def __format__(s, b,f:int):
return b.__str__()*f
@print
@lambda a: b().__format__(*a)
@lambda x: (x.__doc__[0], x.__doc__[1])
class _:
__doc__=("101101010101", __import__('random').randint(0, 100)^7)```
!e
print(len("00000000000000"))
@near gust :white_check_mark: Your 3.11 eval job has completed with return code 0.
14
Hey I just implemented an import system in my lang
Do any of you guys know a way to create a package registry
or a system like that?
And also a place to host it free
(I'm thinking of vercel)
i mean...
fuckup just randomly doubles non-bool arguments
f fixes the type of parameters if they don't fit type annotation
but it's not even helpful here
in your class b i assume you were trying to decorate __format__ with @f and not @n
so b().__format__ is just going to print b * f and sometimes double it
and class _ is just a way to call b().__format__ with that binary string and random number in some annoying interval
the code is not really obfuscated, so it's kinda not a challenge...
why use __doc__ when you can use x?
or another _?
this looks neater.
@print
@lambda _:b().__format__(*_._)
class _:_="101101010101", __import__('random').randint(0, 100)^7
from random import*;print(f"{2901:b}"*(randint(0,100)^7)*randint(1,2))
what's b, in the lambda?
class b(str):
@fuckup
@n
def __format__(s, b,f:int):
return b.__str__()*f
the run function can be a lambda instead of a def
run = lambda s: {...for _ in iter(lambda: bool(s:=s()),False)}
Im not sure if it is valid or correct code
darn it! I was typing my solution to it but I'm on mobile so I'm slow typer :(
Im also on mobile)
I believe that s:=s() assigns to the inner lambda namespace, not the outer?
!e
run = lambda s: {...for _ in iter(lambda: bool(s:=s()),False)}
from dis import dis
dis(run)
@fleet bridge :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | SyntaxError: assignment expression cannot be used in a comprehension iterable expression
Reasonable
!e
run = lambda s: {(...,s:=s())[0]for _ in iter(lambda: bool(s), False)}
from dis import dis
dis(run)
my solution to that was s:=[s], then make s a default arg in the inner lambda, then s.append(s.pop()()) inside the iter lambda
@fleet bridge :white_check_mark: Your 3.10 eval job has completed with return code 0.
001 | 1 0 LOAD_CLOSURE 0 (s)
002 | 2 BUILD_TUPLE 1
003 | 4 LOAD_CONST 1 (<code object <setcomp> at 0x7f35791ea1e0, file "<string>", line 1>)
004 | 6 LOAD_CONST 2 ('<lambda>.<locals>.<setcomp>')
005 | 8 MAKE_FUNCTION 8 (closure)
006 | 10 LOAD_GLOBAL 0 (iter)
007 | 12 LOAD_CLOSURE 0 (s)
008 | 14 BUILD_TUPLE 1
009 | 16 LOAD_CONST 3 (<code object <lambda> at 0x7f35791ea290, file "<string>", line 1>)
010 | 18 LOAD_CONST 4 ('<lambda>.<locals>.<lambda>')
011 | 20 MAKE_FUNCTION 8 (closure)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ohulicocug.txt?noredirect
Good idea
ty
wow
impressive lol
I can't type that fast unless I'm on a keyboard
>>> run = lambda s: {(...,s:=s())[0]for _ in iter(lambda: bool(s), False)}
>>>
>>> run(int)
{Ellipsis}
>>> run(print)
{Ellipsis}
>>> run(lambda: print())
{Ellipsis}
>>> run(lambda: (print('first'), lambda: print('second'))[1])
first
second
{Ellipsis}
works in my 3.10 repl (now im on pc :-)
my implementation of your idea
>>> run = lambda _s: (lambda s: {(...,s.append(s.pop()())) for _ in iter(lambda:bool(s[0]),False)})([_s])
>>> run(lambda: (print('first'), lambda: print('second'))[1])
first
second
{(Ellipsis, None)}
>>> run = lambda _s: (lambda s: {(...,s.append(s.pop()()))[0] for _ in iter(lambda:bool(s[0]),False)})([_s])
>>> run(lambda: (print('first'), lambda: print('second'))[1])
first
second
{Ellipsis}
``` fixed
this can be useful when you are converting statements to expressions
wb metaclasses?
afaik it's not still like py2 where you can just give it a __metaclass__ attr in the type call
ig you could just instance the metaclass and add attrs to the instance after, but that just feels wrong
Just use the metaclass instead of type
yeah I said that here, but it feels wrong
it accomplishes the desired behaviour, but it feels just so horribly wrong
What do you mean by "add attributes after"?
basically, just make the __call__ method on the meta return something to simulate an instance of the class that has the metaclass
(sorry for long response time, i just got on my computer where i can respond more easily lol)
Isn't that the case already? Except it doesn't simulate. MyMetaclass("some name", (), {})() (which is the __call__ of the metaclass) returns an instance of that class which has this as its metaclass.
does cls.__dunder__ = x set corresponding slot in c-structure of cls?
So there was this post in /r/LearnPython: https://www.reddit.com/r/learnpython/comments/wvoku5/heres_some_code_that_i_wrote_for_a_average_calc/
I tried to make that code really beautiful and readable.
1 vote and 9 comments so far on Reddit
So I came up with:
print(
sum(
items := (
gather_items := (
lambda lst: gather_items(lst + [float(new_string)])
if (new_string := input(f"Enter item #{len(lst)+1}: ")) != "end"
else lst
)
)([])
)
/ len(items)
)
yes, and you can actually enable it for builtin classes by toggling a flag with ctypes or memory corruption
print(
print("Type 'end' when you want to end.") or
"the average of the",
length := len(items := (
gather_items := (
lambda lst: gather_items(lst + [float(new_string)])
if (new_string := input(f"Enter {(length := len(lst)+1)}{ {1:'st',2:'nd',3:'rd'}.get((length < 11 or length > 13) and length % 10,'th')} number: ")) != "end"
else lst
)
)([])
),
f"number{'s' * (length != 1)} is",
sum(items) / length
)
``` supposed to replicate the code's behaviour but with some grammar changes
cheap discord rendering
although do remember that in the inline version of switch-case, the arguments are parsed backwards
Got bored and made random stuff
could add arrays and loops and call it turing complete.
I think it is turing complete if there is long bignum arithmetic
Because infinite length number is bit array
How std.out << x executes without NameError? You have a lot of predefined vars or you are mutating namespaces?
Hey @simple sphinx!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
dudes I made a program to calculate factorial 18!
https://paste.pythondiscord.com/nuhegihoti
!remind 3H do this when not on phone
Your reminder will arrive on <t:1661360160:F>!
globals is modified to make sentinal Variable instances on missing for now, but that will be removed.
from pygame import*;t=m=310;x=event.get;p=display
while draw.rect(p.set_mode((640,360)),"red",(0,t,50,50))or m:x(256)and l;t-=x(768)and m or t>m or-1;p.flip()```
from pygame import*;t=m=310;x=event.get
while s:=(p:=display).set_mode((640,360)):x(256)and l;t-=x(768)and m or t>m or-1;draw.rect(s,"red",(0,t,50,50));p.flip()
i'll just post it
so we don't have to go to #python-discussion every time
Here's your reminder: do this when not on phone
[Jump back to when you created the reminder](#esoteric-python message)
from pygame import*;t=m=310;x=event.get;p=display
while 1:draw.rect(p.set_mode((640,360)),"red",(0,t,50,50));x(256)and l;t-=x(768)and m or t>m or-1;p.flip()```
from pygame import*;t=m=310;x=event.get
while s:=(p:=display).set_mode((640,360)):x(256);t-=x(768)and m or t>m;draw.rect(s,"red",(0,t,50,50));p.flip()```
removed some unnecessary stuff
me is not a valid duration string.
Sorry, you can't do that here!
@unreal echo You mean this?
lst = ["aa", "bb", "cc"]
l = list(map(lambda u: 'from:' + u, lst))
' OR '.join(l)
# Get 'from:aa OR from:bb OR from:cc'
Is there a shorter way to do this tanks?
!e (foo:=lambda: foo())()
@plush halo :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <lambda>
004 | File "<string>", line 1, in <lambda>
005 | File "<string>", line 1, in <lambda>
006 | [Previous line repeated 996 more times]
007 | RecursionError: maximum recursion depth exceeded
!e ```py
print(' OR '.join(map('from:'.add,["aa","bb","cc"])))
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
from:aa OR from:bb OR from:cc
thanks
that happens because ints are cached in range(-5, 257)
!e pp a = 256 b = 256 print(a is b) c = 257 d = 257 print(c is d)
@plush halo :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | True
002 | True
yh different
!e py a = 256 b = 256 print(a is b) c = 258 d = 258 print(c is d)
@plush halo :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | True
002 | True
lol
False for me ```py
a = 258
b = 258
a is b
False
>>> a = 256
>>> b = 256
>>> a is b
True
>>> c = 257
>>> d = 257
>>> c is d
False
works probably because the REPL has separate codes for each line that evaluate to the same namespace
@plush halo :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
!e py a = 5 b = 6 a ^= b b ^= a a ^= b print(a, b)
@plush halo :white_check_mark: Your 3.11 eval job has completed with return code 0.
6 5
!e py print(True == False == 0/0)
@plush halo :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
this is quite fun ^^
!e ```py
True is False and when-it is False and when-it is not True
@quartz wave :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!e ```py
1<0 is not False, 1>0 or ... is it
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
<string>:1: SyntaxWarning: "is not" with a literal. Did you mean "!="?
lol
syntax warning should be an IDE thing not a code thing
!e ```py
from fishhook import hook
@hook(tuple)
def call(self, , __a=["Hello, World!\n"]):print(end=__a.pop(0));return()
() () () () () () () () () () () () () () ()
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:5: SyntaxWarning: 'tuple' object is not callable; perhaps you missed a comma?
002 | Hello, World!
!e ```py
import builtins
class foo:
def lshift(self, bar):
print(bar, end=''); return self
setattr(builtins, 'cout', foo())
####################
cout << "hello" << " " << "world"
@plush halo :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
is fishhook third party?
yes
the author is a regular of this channel
when "was" ๐
*is
!e ```py
import sys,fishhook
@fishhook.hook(type(sys.stdout))
def lshift(self,other):print(end=other);return self
nl=chr(10)
(sys.stdout << "Hello, World").write(nl);
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, World
think you can make it more like cout << x << y << z...?
๐
!e ```py
import sys,fishhook
@fishhook.hook(type(sys.stdout))
def lshift(self,other):print(end=other);return self
nl=chr(10)
sys.stdout << "Hello, World!" << nl;
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, World!
nice... where can I read the documentation?
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 |
002 | This module allows for swapping out the slot pointers contained in static
003 | classes with the `generic` slot pointers used by python for heap classes.
004 | This allows for assigning arbitrary python functions to static class dunders
005 | using `hook` and `hook_cls` and for applying new functionality to previously
006 | unused dunders. A hooked static dunder can be restored to original
007 | functionality using the `unhook` function
oh they put it in 3.11 now
!e ```py
from fishhook import hook
@hook(type(Ellipsis))
def index(self):return 0;
@hook(type(Ellipsis))
def getitem(self,whatever,__secret=["Hello, World!\n"]):print(end=__secret.pop(0));return[self]
[...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...] [...]
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:7: SyntaxWarning: list indices must be integers or slices, not ellipsis; perhaps you missed a comma?
002 | Hello, World!

Python tryna tell me I can't index with ellipsis
So I make indexing with ellipsis 29 times print hello world
use that in a sorting algorithm in place of a, b = b, a to obfuscate it lol
haha yeah
Still alive. I haven't had much time to work on python lately. I haven't been lurking here either, it's time-consuming to keep up with the conversation.
!e ```py
import this, sys
from fishhook import hook
@hook(type(print))
def call(*args, **kwargs):
...
@plush halo :x: Your 3.11 eval job has completed with return code 1.
001 | The Zen of Python, by Tim Peters
002 |
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/eyonetiyug.txt?noredirect
I think you imported this to early
probably
he's back
Also there's a danger of getting nerd sniped in this channel.
!e ```py
import sys as sus;from fishhook import hook
@hook(type(print))
def call(*a,**k):0
import this
@floral meteor :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | File "/snekbox/user_base/lib/python3.11/site-packages/fishhook/__init__.py", line 229, in pwrapper
004 | hook_cls_from_cls(cls, type(f'<{itos(id(cls))}>', (P,), body), **kwargs)
005 | File "/snekbox/user_base/lib/python3.11/site-packages/fishhook/__init__.py", line 186, in hook_cls_from_cls
006 | update_subcls(subcls, pcls)
007 | File "/snekbox/user_base/lib/python3.11/site-packages/fishhook/__init__.py", line 150, in update_subcls
008 | for name in vars(pcls).keys() - key_blacklist:
009 | ^^^^^^^^^^^^^^^
010 | AttributeError: 'NoneType' object has no attribute 'keys'
!e py import sys from fishhook import hook @hook(type(print)) def __call__(*args, **kwargs): ... import this
@plush halo :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | File "/snekbox/user_base/lib/python3.11/site-packages/fishhook/__init__.py", line 229, in pwrapper
004 | hook_cls_from_cls(cls, type(f'<{itos(id(cls))}>', (P,), body), **kwargs)
005 | File "/snekbox/user_base/lib/python3.11/site-packages/fishhook/__init__.py", line 186, in hook_cls_from_cls
006 | update_subcls(subcls, pcls)
007 | File "/snekbox/user_base/lib/python3.11/site-packages/fishhook/__init__.py", line 150, in update_subcls
008 | for name in vars(pcls).keys() - key_blacklist:
009 | ^^^^^^^^^^^^^^^
010 | AttributeError: 'NoneType' object has no attribute 'keys'
They're back, temporarily. But they don't have much to add.
see lol
I beat you to it lol
xD
wait why is sys imported?
I was using it for smth else... it's rly not needed
I'm going to feel guilty reading the zen of python after this
a few weeks or months ago idk, I corrupted the zen.
how?
!e ```py
from ctypes import c_char
def corrupt(victim):
l = len(victim)
type_base = (c_char8).from_address(id(victim)+8)
odata = (c_charl).from_address(id(victim)+48)
type_base.value = bytes((c_char8).from_address(id(0)+8))
a = victim + 1
odata.value = bytes((c_charl).from_address(id(a)+48))
type_base.value = bytes((c_char*8).from_address(id('')+8))
s = """Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""
corrupt(s)
print(s)
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Bea5uif5m i3!be4uer tha.!ug,z.
002 | ypl)dit is "ftt%s t(bn )npl)dit.
003 | Si-qle is "ftt%s t(bn #pmp,fx.
004 | Com0mex is "ftt%s t(bn #pmp,jca4fd.
005 | Fla4!is bet4fr 4ian nes4fd.
006 | Spa2te )t b%ute2!th!o d%ose.
007 | Re!eab)mit9!co5ots.
008 | Sp%dia,!ca3fs !sen't s0fci!m e.pug(!to bre!l t(f r5mes.
009 | Al4iou'i p2bct)dal)uy "fat3!pu2jty.
010 | Er2prs sho5md .fve2!pa3t s)men4my.
011 | Unl%ts %ypl)dit,z s)men#fd.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/utumeromen.txt?noredirect
it is not a reversible operation.
Before I go, there's a site that has some cool obfuscated code in Python and other languages, some written by myself. It's an archive of competition entries for an unrelated discord server https://cg.esolangs.gay
competition?
It's mostly an excuse to write weird code, but the description is on the info page of the site. It's a game. I just thought it might provide an alternate source for what Python I get up to.
I'm off now. Possibly another 200 days, we'll see.
ok goodbye
thx for confirming you're still alive
@floral meteor I tried corrupt with the encrypted version of s...
corruption is neither repeatable nor reversible
!e ```py
import builtins
tmp, builtins.print = builtins.print, lambda *args, **kwargs: None
import this
builtins.print = tmp; del tmp; s = this.s
from ctypes import c_char
def corrupt(victim):
l = len(victim)
type_base = (c_char8).from_address(id(victim)+8)
odata = (c_charl).from_address(id(victim)+48)
type_base.value = bytes((c_char8).from_address(id(0)+8))
a = victim + 1
odata.value = bytes((c_charl).from_address(id(a)+48))
type_base.value = bytes((c_char*8).from_address(id('')+8))
corrupt(s)
print(s)
@plush halo :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Gur Mra bs mgu"b, /m G6{ C2hre&
002 | O2ohg6thy vf /sgg2f g5oa (uyl.
003 | Rk#zvp6h v&!or'hre gun!!vz#zvp6h.
004 | wzc9s v&!or'hre gun!!pb:dyr+/
005 | P"{cy2l v&!or'hre gun!!pb:dyv0ogr1/
006 | S9og 6g o2hgr%!gu.b a2ggr1/
007 | F#oef2!vf org'se 'vna qra&s.
008 | snq.pvy6hl 0cha'g.
009 | drp6oy 0ofr&!ne2b'g fcr0wny rab(uu 'c o%snx gur ehy2g.
010 | zgu"itu cen0hvp.zvg,!or.hf #iev'm.
011 | feb%g f5chy1!ar)se #off fvy2bgy,/
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/odatazekoy.txt?noredirect
now, I wont feel guilty anymore xD
wait, you tried it with the actual module on your pc?
rip lol
what module?
I thought you get something like this -> #esoteric-python message when you import this
It doesn't modify the code of the module, so it's not permanent beyond runtime
i see
https://cg.esolangs.gay/14/ one of my fav ones
what's with the scoring btw
getting a py_object from id(obj)+8 is the object in memory right? what is id(obj)+16
+8 is (a pointer to) the type of the object.
I think the size? But I don't remember
id(obj) is the object place in memory then, right?
I mean, yes, kind of? But the value at id(obj) is the refcount
how do i interact with the object in memory itself then?
_________________ # OPTIONAL
|____ _ob_next ___| ## id(obj), PyObject*/py_object
|____ _ob_prev ___| ## id(obj) + tuple.__itemsize__, PyObject*/py_object
|_________________| # REQUIRED
|___ ob_refcnt ___| ## id(obj) + object.__basicsize__ - tuple.__itemsize__ * 2, Py_ssize_t/c_ssize_t
|____ ob_type ____| ## id(obj) + object.__basicsize__ - tuple.__itemsize__, PyObject*/py_object
|______ ... ______|
the part below REQUIRED is the one you'll often see
.bm cty;es guide
I can't understand why it works
- saving ptr to type of string and string data array
- changing string type to to int
- a = victim + 1
- copy int digits from a to victim
- changing type of victim to str back
I think i understand all steps correctly, but i cant understand why it all works how it works. int+1 can change only several digits at the end of integer, not some random digits inside of it
Why it isnt reversible? Cant you do the same but a=victim-1?
!e ```py
from ctypes import c_char
def corrupt(victim):
l = len(victim)
type_base = (c_char8).from_address(id(victim)+8)
odata = (c_charl).from_address(id(victim)+48)
type_base.value = bytes((c_char8).from_address(id(0)+8))
a = victim - 1
odata.value = bytes((c_charl).from_address(id(a)+48))
type_base.value = bytes((c_char*8).from_address(id('')+8))
s = """Bea5uif5m i3!be4uer tha.!ug,z.
ypl)dit is "ftt%s t(bn )npl)dit.
Si-qle is "ftt%s t(bn #pmp,fx.
Com0mex is "ftt%s t(bn #pmp,jca4fd.
Fla4!is bet4fr 4ian nes4fd.
Spa2te )t b%ute2!th!o d%ose.
Re!eab)mit9!co5ots.
Sp%dia,!ca3fs !sen't s0fci!m e.pug(!to bre!l t(f r5mes.
Al4iou'i p2bct)dal)uy "fat3!pu2jty.
Er2prs sho5md .fve2!pa3t s)men4my.
Unl%ts %ypl)dit,z s)men#fd.
In 4ie &bce of !nbi'vit9- r%gus%!th%!te-qta4jon to 'ves3/
T(fre sho5md "f o.f-- and pre&fra"my /oly one --o"wio5t w!z t/!do it.
Alt(pug(!th!u w!z m!z n/u b%!ob6jou3!at fir3u u.mes3!yo5(re Dut#i.
pw )t b%ute2!th!o n%wer.
Al4iou'i n%wer is /gte.!be4uer tha.!ri'it .pw.
If 4ie )npl%nen4bti/o i3!ha2e t/!ex0mai.- i4(s !!ba$!id%b.
g t(f i-qle-fnt!uio.!is eas9!to exp,bin, it may be !!go/e i$fa.
Nam%tpa#fs !se /oe (pnk)og 'sea4!id%b -- le4(s $p m/se /g t(pse!"""
corrupt(s)
print(s)
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Bea5uif5m i3!be4uer tha.!ug,z.
002 | ypl)dit is "ftt%s t(bn )npl)dit.
003 | Si-qle is "ftt%s t(bn #pmp,fx.
004 | Com0mex is "ftt%s t(bn #pmp,jca4fd.
005 | Fla4!is bet4fr 4ian nes4fd.
006 | Spa2te )t b%ute2!th!o d%ose.
007 | Re!eab)mit9!co5ots.
008 | Sp%dia,!ca3fs !sen't s0fci!m e.pug(!to bre!l t(f r5mes.
009 | Al4iou'i p2bct)dal)uy "fat3!pu2jty.
010 | Er2prs sho5md .fve2!pa3t s)men4my.
011 | Unl%ts %ypl)dit,z s)men#fd.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/zozepowure.txt?noredirect
@fleet bridge i don't think so
No, i mean you should do +1 to corrupt and -1 to uncorrupt
...i just tried that?
Alright prepare for your brain to be explode
๐
!e ```py
from ctypes import c_char
def corrupt(victim):
l = len(victim)
type_base = (c_char8).from_address(id(victim)+8)
odata = (c_charl).from_address(id(victim)+48)
type_base.value = bytes((c_char8).from_address(id(0)+8))
a = victim + 0
odata.value = bytes((c_charl).from_address(id(a)+48))
type_base.value = bytes((c_char*8).from_address(id('')+8))
s = """Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""
corrupt(s)
print(s)
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Bea5uif5m i3!be4uer tha.!ug,z.
002 | ypl)dit is "ftt%s t(bn )npl)dit.
003 | Si-qle is "ftt%s t(bn #pmp,fx.
004 | Com0mex is "ftt%s t(bn #pmp,jca4fd.
005 | Fla4!is bet4fr 4ian nes4fd.
006 | Spa2te )t b%ute2!th!o d%ose.
007 | Re!eab)mit9!co5ots.
008 | Sp%dia,!ca3fs !sen't s0fci!m e.pug(!to bre!l t(f r5mes.
009 | Al4iou'i p2bct)dal)uy "fat3!pu2jty.
010 | Er2prs sho5md .fve2!pa3t s)men4my.
011 | Unl%ts %ypl)dit,z s)men#fd.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/geyasodoho.txt?noredirect
+0 works
And it doesn't work without the + 0
It's because the integers are stored as base 30 number system in a 32 bit sizes, so digits that aren't valid are distorted.
When a new integer is created from the data using + 0
why base 30, instead of a power of 2?
he forgot to append that
python integers are base 2**30
can be customized to be base 2**15
oh, 2**30
i thought it was literally base 30
golfing challenge: print this matrix.
!e I've got```py
r=range;print('[\n'+',\n'.join(map(str,[[i^j for i in r(16)]for j in r(16)]))+'\n]')
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [
002 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
003 | [1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14]
004 | [2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13]
005 | [3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12]
006 | [4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11]
007 | [5, 4, 7, 6, 1, 0, 3, 2, 13, 12, 15, 14, 9, 8, 11, 10]
008 | [6, 7, 4, 5, 2, 3, 0, 1, 14, 15, 12, 13, 10, 11, 8, 9]
009 | [7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8]
010 | [8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7]
011 | [9, 8, 11, 10, 13, 12, 15, 14, 1, 0, 3, 2, 5, 4, 7, 6]
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/kerawixena.txt?noredirect
This fractal at higher resolution
the code for the fractal ```py
r=range;print('\n'.join(map(lambda s:''.join([*map(lambda a:f'\x1b[48;2;{(255//32)*a};0;0m \x1b[m',s)]),[[i^j for i in r(32)]for j in r(32)])))
the code for the mirror ```py
print('\n'.join(map(lambda s:''.join([*map(lambda a:f'\x1b[48;2;{(255//32)*a};0;0m \x1b[m',s)]),[[(i&j)|((31-i)&(31-j))for i in r(32)]for j in r(32)])))
this would be quite detailed if it was actual pixel output
another cursed fractal
r=range;print('\n'.join(map(lambda*q:''.join([*map(lambda r,g,b:((k:=r*g*b+38+b),f'\x1b[48;2;{255//32*r+k};{255//32*g+k};{255//32*b+2*k}m \x1b[m')[1],*q)]),[[i^j for i in r(32)]for j in r(32)],[[(i&j)|((31-i)&(31-j))for i in r(32)]for j in r(32)],[[i&j for i in r(32)]for j in r(32)])))
I can increase resolution by times 4, but it's more code.
I was talking like actual graphical output instead of terminal fun ๐
hi guys
Hi lad
could u refer me to a page to get basic help for python
anywhere but here
I learnt python in university without a single textbook I don't know how others learn python, someone else answer?
well i know how to code
i just dont know hwy this syntax is wrong
even tho it looks right
I notice you're on help cooldown.
This is the channel where the syntax looks wrong but it is right
So subverting that cooldown by asking in nonhelp channels probably won't help you out a lot lol
but hey if you as @floral meteor you might get a fun answer involving ctypes
for example, indexing with ellipsis 28 times prints hello world.
ctypes?
If there's no syntax error I could probably make it right with a lot of craziness
they so slow
ctypes gives access to the internals so you can fidget with the interpeter as you go. But it's like fixing a car while you're driving it
๐ด for a easy problem
u need 4 hands?
thats what i said lol
@loud sail linked post is where I added 0 to an integer and it broke it.
lol
i dont wanna know whatu used this for
lol
actually what u use it for
mans a tricky a person
im just curious
since i can read your code
how good are you at leet code if you ever seen it @floral meteor
or can i not compare them?
I haven't dabbled in the dark arts of leetcode yet
lol leetcode
!e my code is not readable ```py
from ctypes import*;
class output:
def init(self,victim):self.victim=id(victim);ol=len(victim);(c_charol).from_address(id(victim)+48)[:]=[0]ol;c_longlong.from_address(id(victim)+16).value=0;
def lt(self,item):_l=c_longlong.from_address(self.victim+16);_l.value+=1;_a=c_byte.from_address(self.victim+48+_l.value);_a.value=-item;return 0;
neg=lambda s:s;
def gt(self,a):a,i,_l=a,c_longlong.from_address(self.victim+16);data=(c_byte_l.value).from_address(self.victim+49);v,data[:-1]=data;l.value-=1;a[i]=v;return 0;
class array:
def init(self,victim):self.memory="\0\0\0\0\0\0\0\0"[:]*256;=self.memory=id(self.memory);c_longlong.from_address(+16).value=2568-1;self.i=0;self.o=output(victim)
@property
def mem(self):return(c_byte(2568-1)).from_address(self.memory+48);
def inc(self):self.mem[self.i]+=1;return 0;
def dec(self):self.mem[self.i]-=1;return 0;
def left(self):self.i-=1;return 0;
def rite(self):self.i+=1;return 0;
def dot(self):return self.o <- self.mem[self.i];
def com(self):return(self.mem,self.i) <- self.o;
def loop(self):return+(not self.mem[self.i]);
def endl(self):return-bool(self.mem[self.i]);
def iter(self):return iter([self.mem]);
def _get(self,c,p):
if not 0<=p<len(c):raise StopIteration;
return c[p];
def run(self,c):
p=t=0;s=type('',(),{'iter':lambda s:s,'next':lambda s:self._get(c,p)})();
try:
for k in s:t=t+(k=='[')-(k==']')if t else{'+':self.inc,'-':self.dec,'<':self.left,'>':self.rite,'.':self.dot,',':self.com,'[':self.loop,']':self.endl}.get(k,lambda:0)();p+=1-2*(t<0);
except:0;
finally:return self.o;
def brainfuck(victim,,_n=[0]):clone,a=victim+'.',array(victim);a.run(clone);_l=c_longlong.from_address(a.o.victim+16);l=_l.value;_l.value-=1;data=(c_bytel).from_address(a.o.victim+48);_,*data[:-1]=data;import('sys')._getframe(1).f_globals[_n[0]]=a.o;_n[0]+=1;return 0;
...;
code="++++++++++[>+++++++>+++++++++++>+++<<<-]++++++++++>++>--.>++.<.<.>-------.,..+++.>++++++++++++.,.+<<+++++++++++++++.>.+++.,.--------.>.<<<.";
print(code);
brainfuck(code);
print(code);
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ++++++++++[>+++++++>+++++++++++>+++<<<-]++++++++++>++>--.>++.<.<.>-------.,..+++.>++++++++++++.,.+<<+++++++++++++++.>.+++.,.--------.>.<<<.
002 | Hello, World!
yes, but I overcomplicated it by using native memory
whats native memory
the memory allocated to the python interpreter
python's native allocator will be the death of me
does everyone write like this?
so many bugs are trickier to exploit because of it
no, just this obscure corner of wherever we are
import pprint;r=range;pprint.pp([[i^j for i in r(16)]for j in r(16)])
```does this count
yes
@floral meteor i found more C level bugs in python btw
It is mostly for fun code, pretty code, ugly code, or other metacoding
how long did u guys code for
noice
@rugged sparrow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | bytearray: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')
002 | leaked memory of buffer: [1, 140539191971648, 8, 9, 140539181891952, 140539181891952, 0]
i hope i can get to your level in 3 months
maybe 1 month
idk depending on how much time i have
ill see u guys again soon
gn
import pprint;r=range(16);pprint.pp([[i^j for i in r]for j in r])
If you interpret values as height and draw 3d plot you will get 3d sierpinsky fractal
If you are interested i can draw it in wolfram mathematica
yes
!e
print(', '.join(str(i) for i in {i*j for (i, j) in [(i, j) for i in range(2, 10) for j in range(2, 10)] if i*j%2 == 0}))
is this a little bit esoteric?
@coarse oyster :white_check_mark: Your 3.11 eval job has completed with return code 0.
4, 6, 8, 10, 12, 14, 16, 18, 20, 24, 28, 30, 32, 36, 40, 42, 48, 54, 56, 64, 72
Not really
!e
print(', '.join(str(i) for i in {i*j for (i, j) in [(i, j) for i in range(__import__('random').randint(0, 2), __import__('random').randint(2, 10)) for j in range(__import__('random').randint(0, 2), __import__('random').randint(2, 10))] if i*j%2 == 0}))
maybe this?
@coarse oyster :white_check_mark: Your 3.11 eval job has completed with return code 0.
0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 24, 30
what is really esoteric
This
Made a small project (with a coworker) that I find somewhat esoteric: https://github.com/L3viathan/batchable
Doesn't use ctypes, but it does use gc.get_referrers :)
+48 does what for mem address?
its an offset. so +48 is looking at the 6th pointer of the object, assuming a 64bit system
If a string is entirely ascii, it will store its bytes at position 6 in the object structure. It's 71 or 72 for higher value bytes
import sys
sys.stdout.write("hello world")
(actually, are social media posts allowed?)
I'll publish the code for this later, whenever I'm finished cleaning this up,
!e ```py
import fishhook, sys;
@fishhook.hook(type(sys.stdout))
def lshift(self,data):self.write(str(data));return self;
nl=chr(10);
name=='main'=={
sys.stdout << "Hello, World" << '!' << nl,
};
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, World!
I hate that I can read all of this
you want something you can't read?
maybe I don't
can you read this?
it doesn't just interpret the string, it hacks the string and directly brainfucks it
!e ```py
from sys import _getframe as _gf,stdout,stderr
class IOStreamAttribute:
dictionary={}
def new(cls,name,stream,dict_=dictionary,ns="nul"):
if name in dict_:
return dict_[name]
res=dict_[name]=super().new(cls)
res.name=name
res.stream=stream
res.is_read=stream and 'r' in stream.mode
res.dict_=dict_
res.ns=ns
return res
def lshift(self,value):
if self.is_read is True:
raise NotImplementedError
if value is self.dict_.get("endl"):
self.stream.write("\n")
self.stream.flush()
else:
self.stream.write(value)
return self
def str(self):
return f"{self.ns!r}[::{self.name!s}]"
def repr(self):
return f"IOStreamAttribute({self.name!r})"
@lambda c: c()
class std:
def getitem(self,x):
if type(x) is slice and x.start is x.stop is None:
return x.step
def repr(self):
return "std"
cout=IOStreamAttribute("cout",stdout,ns=std)
cerr=IOStreamAttribute("cerr",stderr,ns=std)
endl=IOStreamAttribute("endl",None,ns=std)
std[::cout] << "stdout" << (std[::cerr] << "stderr\n" and "") << std[::endl]
why is it right shift?
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
stdoutstderr
why is it flushed
toilet noises
because you did \n
\n is like pressing that button on the toilet
!e ```py
from sys import _getframe as _gf,stdout,stderr
class IOStreamAttribute:
dictionary={}
def new(cls,name,stream,dict_=dictionary,ns="nul"):
if name in dict_:
return dict_[name]
res=dict_[name]=super().new(cls)
res.name=name
res.stream=stream
res.is_read=stream and 'r' in stream.mode
res.dict_=dict_
res.ns=ns
return res
def lshift(self,value):
if self.is_read is True:
raise NotImplementedError
if value is self.dict_.get("endl"):
self.stream.write("\n")
self.stream.flush()
else:
self.stream.write(value)
return self
def str(self):
return f"{self.ns!r}[::{self.name!s}]"
def repr(self):
return f"IOStreamAttribute({self.name!r})"
@lambda c: c()
class std:
def getitem(self,x):
if type(x) is slice and x.start is x.stop is None:
return x.step
def repr(self):
return "std"
cout=IOStreamAttribute("cout",stdout,ns=std)
cerr=IOStreamAttribute("cerr",stderr,ns=std)
endl=IOStreamAttribute("endl",None,ns=std)
std[::cout] << "stdout" << (std[::cerr] << "stderr" and "") << std[::endl]
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
stdoutstderr
@floral meteor doesn't work if i remove it
you also sent endl which think is also \n
works fine on the REPL ```py
std[::cout] << "stdout" << (std[::cerr] << "stderr\n" and "") << std[::endl]
stderr
stdout
I hate this formatting but I kind of understand what's going on
I did do a whitespace purge on the first class, before I did that it was quite easy to follow
relatively
get rid of the indentation and newlines then
@sick hound ah yes this is what you're looking for
lol nice
Hey @sick hound!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
does a write syscall to stdout
Traceback (most recent call last):
File "<stdin>", line 192, in <module>
File "%PYTHONROOT%\python39\lib\ctypes\__init__.py", line 364, in __init__
if '/' in name or '\\' in name:
TypeError: argument of type 'NoneType' is not iterable
thanks, I should try remaking it too there's a c := in the middle of it I got too lazy to obfuscate out
!e
print(eval("\65\76\61\6C\28\22\68\65\6C\6C\6F\22\29"))```
@unique heath :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1
004 | 5>1C885CCF9
005 | ^
006 | SyntaxError: invalid non-printable character U+0006
rip
!e ```py
print("\x65\x76\x61\x6C\x28\x22\x68\x65\x6C\x6C\x6F\x22\x29")
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
eval("hello")
NameError: name 'hello' is not defined
this ?
#internals-and-peps message
yes
it = you = True ; are = print
are ( you, it )
if False is True:
are ( you, False or are (you, it) )
else:
are (you,True or False)
for i in str(you):
are(you,True)
shout out for @royal patrol, he helped me vastly improve this decompiler https://github.com/greyblue9/unpyc37-3.10
which he used with his PyArmor unpacker https://github.com/Svenskithesource/PyArmor-Unpacker
if anyone wants to help us test (especially me) or give feedback itd be awesome :b
thanks to @serene stratus who has more contribution to the unpacker than myself
im still amazed that it all basically worked lol
xD yep same
need to find some other nasty exe to unpack and decompile
i think that i do have one
i have plenty as well
it might be py39 tho ๐๐
try it
it was supposed to be compatible till 3.10
so will be a good chance
to test
yeah soo awesome @serene stratus , you are a legend -- those pyarmor things are such a beast
Thanks, always welcome to reverse engineer the paid modes with me ๐
i remember when i first saw from pytransform import _transform or some such thing
Could definitely use an extra set of brains
and some horriffic native code call
i couldnt even execute the .so on the machine i was using to look at the time so i was kinda stuck then
were you issued a whole set coz i unluckily got just a single brain
maybe the three of us can team up on reversing some future horrible proprietary mindfuck
surely would love to do after the semester ends
Well starting from 1 September school starts from me so I'll be busy from then on
Still I'd like to help when I can
ahhh our schedules ๐๐
well i can work whenever because i have a slack-friendly job lol
I wish
so you have like 5 more days lol
Yup
and @royal patrol you are gonna be less busy than now ?
gonna be more busy lol, cuz the semester begins soon after the admission and the entrance tests ends
oh i thought it was too good to be true lol
xDDDD
def get_resp(foo=[]):
foo.append('really')
return input(f"Do you {' '.join(foo)} want to know?\n>>> ")
print('How to keep a fool busy for hours')
while not get_resp().strip().lower().startswith('n'):
continue
print('Now you know :)')
How to keep a fool busy for hours
Do you really want to know?
>>> maybe
Do you really really want to know?
>>> umm...
Do you really really really want to know?
>>> cmon I really do
Do you really really really really want to know?
>>> pleaseeeee
Do you really really really really really want to know?
>>> yesssssss i freekin doooo
Do you really really really really really really want to know?
>>> ahh pretty please
Do you really really really really really really really want to know?
>>> fine
Do you really really really really really really really really want to know?
>>> nah I give up
Now you know :)
can you make it compatible across all python and pypy versions excluding 3.12
also why does this happen ```py
print(decompile(compile("5 < 7 and print('lol')","","exec")))
(5 > 7 and print)('lol')
return
I mean.. it's not wrong
!e
from dis import dis
dis("5<7 and print('lol')")
dis("(5<7 and print)('lol')")
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 0 RESUME 0
002 |
003 | 1 2 LOAD_CONST 0 (5)
004 | 4 LOAD_CONST 1 (7)
005 | 6 COMPARE_OP 0 (<)
006 | 12 JUMP_IF_FALSE_OR_POP 11 (to 36)
007 | 14 PUSH_NULL
008 | 16 LOAD_NAME 0 (print)
009 | 18 LOAD_CONST 2 ('lol')
010 | 20 PRECALL 1
011 | 24 CALL 1
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/udukizidex.txt?noredirect
Ok, it does produce different bytecode
In 3.10 the bytecode is basically identical though.
it is identical but the important part is where JUMP_IF_FALSE_OR_POP jumps
h
we are working on that
it happens everytime with "==" and "not in" and "in" stuffs
!e
from dis import dis
dis("5<7 and print('lol')")
dis("(5<7 and print)('lol')")
@fleet bridge :white_check_mark: Your 3.10 eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (5)
002 | 2 LOAD_CONST 1 (7)
003 | 4 COMPARE_OP 0 (<)
004 | 6 JUMP_IF_FALSE_OR_POP 8 (to 16)
005 | 8 LOAD_NAME 0 (print)
006 | 10 LOAD_CONST 2 ('lol')
007 | 12 CALL_FUNCTION 1
008 | 14 RETURN_VALUE
009 | >> 16 RETURN_VALUE
010 | 1 0 LOAD_CONST 0 (5)
011 | 2 LOAD_CONST 1 (7)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/acunabudep.txt?noredirect
Same code, but in 3.10
class Foo:
@infix("^-^")
def foo(self, other):
return f"hi, {other}!"
class Bar:
@infix("^-^", flipped=True)
def bar(self, other):
return f"hello there, {other}!"
print(Foo() ^-^ "foo") # output: hi, foo!
print("bar" ^-^ Bar()) # output: hello there, bar!
print("foo" ^-^ "bar") # raises TypeError
hello I also H
even weirder with 3.7 ```py
print(decompile(compile("5<7 and print('lol')","","eval")))
return 5 exception match 7 and print('lol')
ig ik where the problem is lol
are_opname != 10: # 10 is exception match
self.stack.push(PyCompare([left, cmp_op[compare_opname], right]))
make this change
isn't that gonna return BAD for <
nvm doesn't do anything
oh wait i wasn't modifying the thing in the 3.7 directory
try this
without - 1
sorry for the issue
Please don't use that kind of language here.
works now
there will be a few problems with if statements now as well
ima fix that soon
can u create a pr to the repo with the change?
btw couldn't you just use target in POP_JUMP_IF
also done
well ya, i agree but the code wasnt initially mine so im still getting familiar with the codebase
have asked @rapid sparrow to split it into multiple files :/
so its easier to look instead of scrolling 1000 lines of code
nvm i managed to fixed it for versions 3.7 -> 3.9
niceeeee
idk if it breaks anything else
it did sadly
;-;
causes an infinite IMPORT_NAME loop
lets see what is going wrong
also i have like an hour before school starts and i haven't even taken a shower yet
lmao then ig will discuss that later cuz i think its a problem with the pyc and cant repro with the decompiled code
ima send ya the pyc file if u need in dms
ok
!e
code
!eval [python_version] <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.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside of them.
By default your code is run on Python's 3.11 beta release, to assist with testing. If you run into issues related to this Python version, you can request the bot to use Python 3.10 by specifying the python_version arg and setting it to 3.10.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
i removed a file {more_opcodes.py} :3
thanks merged your PR still seems to work nicely ๐
is it still ?
3745 line file ๐๐
faik does not wurk
thats something with the pyc file nothing wrong with the pr
hehe, so you think ๐
!e
class Foo:
@infix("^-^")
def foo(self, other):
return f"hi, {other}!"
class Bar:
@infix("^-^", flipped=True)
def bar(self, other):
returnf "hello there, {other}!"
print(Foo() ^-^ "foo") # output: hi, foo!
print("bar" ^-^ Bar()) # output: hello there, bar!
print("foo" ^-^ "bar")```
@unique heath :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 9
002 | returnf "hello there, {other}!"
003 | ^^^^^^^^^^^^^^^^^^^^^^^
004 | SyntaxError: invalid syntax
also i'm trying to fix 3.10 if statements and else clauses in all versions but i'm having some trouble
k so i had problems with the new importing
