#esoteric-python
1 messages · Page 116 of 1
this is not the channel for homework questions, see #❓|how-to-get-help
this channel is not for that. this channel is for advanced / crazy python code.
You can use help channels for general python questions. See #❓|how-to-get-help
Is it possible to create a class that does not inherit from object in python 3?
!e py from ctypes import * class Class: pass (c_longlong*133).from_address(id(Class))[42] = id(()) print(Class.__bases__)
@stark fable :white_check_mark: Your eval job has completed with return code 0.
()
@cerulean rivet
!e py from ctypes import * class Class: pass (c_longlong*133).from_address(id(Class))[42] = id(()) print(Class.__mro__)
@astral rover :white_check_mark: Your eval job has completed with return code 0.
(<class '__main__.Class'>, <class 'object'>)
Can you explain it for me?
(c_longlong*133).from_address(id(Class))[42] is the location of the __bases__ tuple in the class object
so i'm just replacing that with the address of an empty tuple
If you replace mro does that break everything?
it only breaks stuff that uses __mro__ I'd assume
and actually removing the pyobject from a pyobject just breaks everything that expects that object to have a pyobject...
so yeah it'll break everything lol
object being "inherited" from at the python level is kinda just a cute obfuscation of what rly happens on an implementation level
in CPython it's the fact any object contains a PyObject which contains a ref count and a pointer which are required by all sorts of functions that carry out the usual python magic
but replacing __bases__ removes the cute obfuscation without actually removing the object and afaik it'd just break super() and stuff to have an empty __mro__ but I'd say fuck around and find out if you rly wanna know
yo i just found out about the craziest thing
idk what this is called
i think its called machine language
i opened up league intaller in vscode
and i see this
but if you look closely
right here
you might see
THIS
CHINESE CHARACTER
LOLLLL
they ran out of special characters so they resort to chinese 
it's what happens when you interpret binary files (that are not supposed to be text) as text
specifically, as utf-8
great trick for code golf if it's scored in chars instead of bytes
a randomly chosen unicode character is most likely going to be from a cjk (chinese, japanese, korean) script, and since this is basically generating random characters, I'm not surprised
(er, well, a randomly chosen one including astral fields is an invalid character)
The proper tool to edit binary files is a hex editor or anything made specifically for exes.
ohh ok
!e ```python
print(import('os').urandom(100).decode('utf8', 'ignore'))
@snow beacon :white_check_mark: Your eval job has completed with return code 0.
001 | hՐ>"
002 | ;Q,M`ҝ6:ҀާyC+cX>-ȷh!X/sLk:Z7kaQ,6*P%m(̔m>1O:?z\
nah i was just messing around
im not going to go edit binary files
too scary for me
might mess up something
and i cant download league of legends again
lol you can copy the installer if you wanna mess with it for some reason
Most of the time if you know the format you'd disassemble binary into assembly code, which looks much more friendly. [citation needed]
seems like a weird binary to mess with
a standard part of modding witcher 3 is opening the exe in a hex editor to remove the mod limit
iirc
Python had its own binary format for compiled code: Python bytecode.
!e ```py
import random
print(*(chr(random.randint(0,0x10ffff)) for _ in range(100)))
@earnest wing :x: Your eval job has completed with return code 1.
001 | 𡫋 쬌 尚 𩡔 𡈸 쎼 𦓆 𘀾 퓳 䠻 𔓰 엺 𧽻 Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | UnicodeEncodeError: 'utf-8' codec can't encode character '\udad5' in position 0: surrogates not allowed
yep, unknown chars + cjk
!e
exec("灲楮琨❈敬汯⁗潲汤℧⤠".encode('UTF-16BE').decode())
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
Hello World!
ping ?
!e
!e [print(bytes([(True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << (True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << True ^ True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True)))]).decode())]
@heavy ermine :white_check_mark: Your eval job has completed with return code 0.
hello
!e
@signal herald rеturn is not a function, they said. Bullshit.
class Return(Exception):
def __init__(self, value):
self.value = value
def rеturn(value):
raise Return(value)
def return_expression(fn):
def _fn(*args, **kwargs):
try:
fn(*args, **kwargs)
except Return as e:
return e.value
return _fn
@return_expression
def factorial(n):
rеturn(1) if n <= 1 else rеturn(n * factorial(n - 1))
print(factorial(10))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
3628800
that syntax highlighting 😄
I can also use cyrillic letters in module names, so I could have a full-blown __futurе__ module
!charinfo futurе
\u005f : LOW LINE - _
\u005f : LOW LINE - _
\u0066 : LATIN SMALL LETTER F - f
\u0075 : LATIN SMALL LETTER U - u
\u0074 : LATIN SMALL LETTER T - t
\u0075 : LATIN SMALL LETTER U - u
\u0072 : LATIN SMALL LETTER R - r
\u0435 : CYRILLIC SMALL LETTER IE - е
\u005f : LOW LINE - _
\u005f : LOW LINE - _
\u005f\u005f\u0066\u0075\u0074\u0075\u0072\u0435\u005f\u005f
from __futurе__ import return_expression
hah
nice
I've been doing a CTF that the Together C and C++ server put together
they have several Python challenges on it now
I think you'd enjoy it
https://stty.sh/lab/challenges - pyval, pyval2, pickle factory, and restricted pickle factory are all Python challenges
pyval2 gave me the most trouble. It's just a script that does this:
#!/usr/bin/python3 -u
environ = {'__builtins__': {}}
cmd = input('Your command plz: ')
print(eval(cmd, environ, environ))
the challenge is to get the contents of a file named "flag" from the current working directory.
it took me a while to solve that, and my solution was absolutely absurd.
well, the first one is trivial!
indeed - "Hello World" 😄
We've had a lot of discussion of how to reclaim globals after they've been deleted, it's just that Discord search is lacking...
oh yay pyjails are fun
Solution to the second: ||[x for x in ().__class__.__base__.__subclasses__() if "port" in x.__name__][0].load_module("os").system("/bin/sh")||
||couldn't you just directly use os._wrap_close instead of going through importlib||
I didn't see an easy way to do that.
||oh wait importlib is easier nvm||
i was thinking something like ||[c for c in object.__subclasses__() if "wrap_close" in str(c)][0].close.__globals__["system"]("sh")||
anyone else trying the last one? i think i am going about it wrong
I'm doing the second pickle one now.
I don't really understand pickles all that well.
it seems that pickles are basically bytecode for the "pickle vm"
E pings
The pings were a raid I think.
Correct. It's since been dealt with
From https://checkoway.net/musings/pickle/
c: Read to the newline as the module name, module. Read the next line as the object name, object. Push module.object onto the stack.
(: Insert a marker object onto the stack. For our purpose, this is paired with t to produce a tuple.
t: Pop objects off the stack until a ( is popped and create a tuple object containing the objects popped (except for the () in the order they were /pushed/ onto the stack. The tuple is pushed onto the stack
S: Read the string in quotes up to the newline and push it onto the stack.
R: Pop a tuple and a callable off the stack and call the callable with the tuple as arguments. Push the result onto the stack.
.: End of the pickle.
```The first instruction seems to be limited here to only the objects in the Python file. And then we can create strings and tuples and call things with the tuples as arguments.
Don’t unpickle a Python pickle that you did not create yourself from known data. That’s old news. The Python documentation for the pickle module clearly states,
While it seems easy enough to get top level objects and modules themselves, I don't see a way to get an attribute of anything very easily.
Oh!
Ach, never mind.
You can get the safe_modules list, and I thought there was a way to pretend it was the order list.
I'm gonna spend tomorrow reading pickle source looking for a way to exec arbitrary code (and imma see how limited an instruction set I can do it in)
Did you get through the first pickle problem?
pickle_factory?
Yes.
Yea, that one just needed __reduce__
Hey, is it possible to use a stacking algorithm on just 3 inputs?
What do you mean by a stacking algorithm?
An algorithm that makes a prediction based on the inputs, that uses the stacking method
This sounds like machine learning. Check out #data-science-and-ml.
Aite, thanks
Oh, there's a pickle command for appending to a list.
||b"c__main__\nsafe_modules\nS'os'\nacos\nsystem\n(S'/bin/sh'\ntR." Pushing __main__.safe_modules, pushing "os", appending, pushing os.system, ("/bin/sh",) and calling.||
I solved it differently -- ||store map(Path.read_text,[Path('flag')]) into self.ingredients||
Whenever I see __reduce__ I always get excited before I realise it's not functools.reduce.
By the way, pickletools.opcodes has all of the different opcodes that can be used, if it helps.
pickle scares me
It should
Who pinged me here?
There was a raid
You can use __reduce__ for the restricted pickle factory, as well. I did it with this: || https://paste.pythondiscord.com/epilamaceg.py ||
Ah I didn't think about that. I don't know enough about pickle yet
That just works by ||tricking pickle into thinking that io is an object in __main__ that it's doing attribute lookups on, rather than a module||
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Utah bread
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: 'float' object cannot be interpreted as an integer
is anyone here good with cryptography and making codes/ciphers?
i am currently working on making a cipher, and so far, the code takes your input Plaintext, reverses it, shifts the letters however many times you want, and then turns each letter into its numeric value in separate numbers. I want to add more onto this but i dont know what else to add and i was wondering if anyone here would have any ideas for the matter
for example:
112 60 107 104 104 97 100 60 97 110 97 100
this is "hello there" with a key of -28 and a shift of 17
i am looking into ways to not have this cipher Monoalphabetic because this means it is easy for somebody to find patterns, kind of like what the Vigenere cipher does, where 2 of the same letters can have a different value/character when they are turned into CipherText
The simplest step would be to replace the offset to shift by with a list of offsets that it goes through letter by letter — that's your Vigenère. There's an example I made in the Python Discord Esoteric Python Challenges GitHub Repository that does something similar.
@snow beacon want to see my current code?
I don't have time to inspect things this morning, unfortunately.
@tame kraken how advanced you willing to go?
Since you have got numbers at this stage you could apply a mathematical function, one that you would memorize, alongside it's inverse function, so that any potential decrypters wouldn't immediately recognise ceasar (or otherwise) shifted ascii
!This program cannot be run in DOS mode.
I think that means something like "safe mode" used for recovery. Someone correct me if I'm wrong but that means you can't run that in minimalist OS mode.
My latest successful encryption project, the source code looks like hannibel lecter wrote it, it would possibly take those numbers, if you made trailing zeros to make them all three digit, and concatenated them like strings to make one huge integer.
It would encrypt it using two key elements, subject of encryption and order of encryption, and spit out an array of mildly large integers.
the reverse decryption process would thus spit out an arbitrarily large integer which you would take three digits at a time, shift and fetch ascii characters, if you decrypted it right, else you may find yourself with what suspiciously looks like mojibake.
except with this one I usually don't bother with any sort of pre-encryption shift, I just encode a message via a brainfuck generator, then map bf chars to digits, and the decoder is an integer brainfuck interpreter.
I made pep8 warnings in pycharm the same colour as tthe background ;)
now it's a splendid esoteric IDE XD
alright ye coders of cursed scripts,
How do I make this increment function look like one big ugly punctuation-rich augmented operator?
a = [0,278,3,8,3,6,7,4,0,0,0,0,0] # etc..
i = 4 # could be anything
c = 8 # changes less often than the others
def increment():
a[i] += 1
a[i] %= 1 <<+ c
the function modifying a global mutable by index with globals as inputs is already pretty damn ugly
!e
exec("愠㴠嬰ⰲ㜸ⰳⰸⰳⰶⰷⰴⰰⰰⰰⰰⰰ崠⌠整挮⸊椠㴠㐠⌠捯畬搠扥湹瑨楮朊挠㴠㠠⌠捨慮来猠汥獳晴敮⁴桡渠瑨攠潴桥牳ਊ摥映楮捲敭敮琨⤺ਠ孩崠⬽‱ਠ孩崠┽‱‼㰫".encode('UTF-16BE').decode())
print(a)
increment()
print(a)
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
001 | [0, 278, 3, 8, 3, 6, 7, 4, 0, 0, 0, 0, 0]
002 | [0, 278, 3, 8, 4, 6, 7, 4, 0, 0, 0, 0, 0]
the +-_-+ infix binary operator
you don;t need decode there
!e ```py
class bf:
def init(s,c:str):s.c=c
def int(s):return int(''.join([t for t in s.c if t in'+-<>[],.']).translate(str.maketrans('+-<>.,[]','23456789')))
def decode(n):
l,a,o=len(s:=str(int(n))),import('collections').defaultdict(int),str();i=p=a[int()];c=8;t=0# initial state
while p<l:#halting state
# update func scope
def _2():a[i]+=1;a[i]%=1<<+c;return i,c,o,t#looped increment
def _3():a[i]-=1;a[i]%=1<<+c;return i,c,o,t#looped decrement
_4,_5=lambda:(+i+ 1,c,o,t),lambda:(+i- 1,c,o,t)#cell shift
_6=lambda:(i,c,print(end=chr(a[i]))or o+chr(a[i]),t)#push char to stdout
def _7():a[i]=ord(import('sys').stdin.read(1));return i,c,o,t#pull char from stdin
_8,_9=lambda:(i,c,o,t+(not bool(a[i]))),lambda:(i,c,o,t-bool(a[i]))#conditional looping
_0,_1=lambda:(i,c+1%32,o,t),lambda:(i,c-1%32,o,t)#cell size shift
# turing machine
i,c,o,t=[_0,_1,_2,_3,_4,_5,_6,_7,_8,_9]int(s[p])if not t else(# interpret digit if t is in 0 state
i,c,o,t -(t >+ int()and s[p]=='9')+(t <- int()and s[p]=='8')# find 'matching' bracket
);p -= 2 *+ (t <- int()) -1#move pointer
if l <+ p <- int():break#forced halt
return type('invisible_list',(list,),{'repr':lambda s:''})([ord(k)for k in o])#don't echo machine-friendly return.
decode(bf("++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++."))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
@floral meteor :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 7
004 | while p<l:#halting state
005 | IndentationError: unexpected indent
!e ```py
exec("""捬慳猠扦㨊†摥映彟楮楴彟⡳Ᵽ㩳瑲⤺献挽挊†摥映彟楮瑟弨猩㩲整畲渠楮琨✧潩渨孴潲⁴渠献挠楦⁴渧⬭㰾孝Ⱞ❝⤮瑲慮獬慴攨獴爮浡步瑲慮猨✫ⴼ㸮ⱛ崧Ⱗ㈳㐵㘷㠹✩⤩敦散潤攨温㨊†氬愬漽汥渨猺㵳瑲⡩湴⡮⤩⤬彟業灯牴彟⠧捯汬散瑩潮猧⤮摥晡畬瑤楣琨楮琩ⱳ瑲⠩㭩㵰㵡孩湴⠩崻挽㠻琽〣湩瑩慬瑡瑥ਠ⁷桩汥⁰㱬㨣桡汴楮朠獴慴攊††⌠異摡瑥畮挠獣潰攊††摥映弲⠩㩡孩崫㴱㭡孩崥㴱㰼⭣㭲整畲渠椬挬漬琣汯潰敤湣牥浥湴ਠ†敦 ㌨⤺慛楝ⴽㄻ慛楝┽ㄼ㰫挻牥瑵牮ⱣⱯⱴ⍬潯灥搠摥捲敭敮琊††弴ⱟ㔽污浢摡㨨⭩⬠ㄬ挬漬琩ⱬ慭扤愺⠫椭‱ⱣⱯⱴ⤣捥汬桩晴ਠ† 㘽污浢摡㨨椬挬灲楮琨敮搽捨爨慛楝⤩潲⭣桲⡡孩崩ⱴ⤣灵獨桡爠瑯瑤潵琊††摥映強⠩㩡孩崽潲搨彟業灯牴彟⠧獹猧⤮獴摩渮牥慤⠱⤩㭲整畲渠椬挬漬琣灵汬桡爠晲潭瑤楮ਠ† 㠬弹㵬慭扤愺⡩ⱣⱯⱴ⬨湯琠扯潬⡡孩崩⤩ⱬ慭扤愺⡩ⱣⱯⱴⵢ潯氨慛楝⤩⍣潮摩瑩潮慬潯灩湧ਠ† 〬弱㵬慭扤愺⡩Ᵽ⬱┳㈬漬琩ⱬ慭扤愺⡩Ᵽⴱ┳㈬漬琩⍣敬氠獩穥桩晴ਠ†‣⁴畲楮朠浡捨楮攊††椬挬漬琽孟〬弱ⱟ㈬弳ⱟ㐬張ⱟ㘬強ⱟ㠬弹嵛楮琨獛灝⥝⠩楦潴⁴汳攨⌠楮瑥牰牥琠摩杩琠楦⁴猠楮‰瑡瑥ਠ††ⱣⱯⱴ⡴‾⬠楮琨⥡湤孰崽㴧㤧⤫⡴‼ⴠ楮琨⥡湤孰崽㴧㠧⤣楮搠❭慴捨楮朧牡捫整ਠ†
㭰㴠㈠⨫
琠㰭湴⠩⤠ⴱ⍭潶攠灯楮瑥爊††楦‼⬠瀠㰭湴⠩㩢牥慫⍦潲捥搠桡汴ਠ整畲渠瑹灥⠧楮癩獩扬敟汩獴✬⡬楳琬⤬笧彟牥灲彟✺污浢摡㨧❽⤨孯牤⡫⥦潲渠潝⤣摯渧琠散桯慣桩湥ⵦ物敮摬礠牥瑵牮⸊摥捯摥⡢昨∫⬫⬫⬫⬫⭛㸫⬫㸫⬫⬫⬫㸫⬫⬫⬫⬾⬫⬫⬫⬫⬫㸫⬫⬫⬫⬫⬫㰼㰼㰭崾㸫⬮ⴭ㸾⬮⬫⬫⬫⬮⸭ⴭⴭⴭⴾ⬮ⴼ㰼㰫⬮ⴭ㸾⬫⬫⬫⬮ⴭⴭⴭⴾ㸫⸫⬫⸭ⴭⴼ⬫⬫⬫⬫⸭ⴭⴭⴭ㰼㰫⬫⸢⤩""".encode('UTF-16BE').decode())
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
!e ```py
#encoding:UTF-16BE
捬慳猠扦㨊†摥映彟楮楴彟⡳Ᵽ㩳瑲⤺献挽挊†摥映彟楮瑟弨猩㩲整畲渠楮琨✧潩渨孴潲⁴渠献挠楦⁴渧⬭㰾孝Ⱞ❝⤮瑲慮獬慴攨獴爮浡步瑲慮猨✫ⴼ㸮ⱛ崧Ⱗ㈳㐵㘷㠹✩⤩敦散潤攨温㨊†氬愬漽汥渨猺㵳瑲⡩湴⡮⤩⤬彟業灯牴彟⠧捯汬散瑩潮猧⤮摥晡畬瑤楣琨楮琩ⱳ瑲⠩㭩㵰㵡孩湴⠩崻挽㠻琽〣湩瑩慬瑡瑥ਠ⁷桩汥⁰㱬㨣桡汴楮朠獴慴攊††⌠異摡瑥畮挠獣潰攊††摥映弲⠩㩡孩崫㴱㭡孩崥㴱㰼⭣㭲整畲渠椬挬漬琣汯潰敤湣牥浥湴ਠ†敦 ㌨⤺慛楝ⴽㄻ慛楝┽ㄼ㰫挻牥瑵牮ⱣⱯⱴ⍬潯灥搠摥捲敭敮琊††弴ⱟ㔽污浢摡㨨⭩⬠ㄬ挬漬琩ⱬ慭扤愺⠫椭‱ⱣⱯⱴ⤣捥汬桩晴ਠ† 㘽污浢摡㨨椬挬灲楮琨敮搽捨爨慛楝⤩潲⭣桲⡡孩崩ⱴ⤣灵獨桡爠瑯瑤潵琊††摥映強⠩㩡孩崽潲搨彟業灯牴彟⠧獹猧⤮獴摩渮牥慤⠱⤩㭲整畲渠椬挬漬琣灵汬桡爠晲潭瑤楮ਠ† 㠬弹㵬慭扤愺⡩ⱣⱯⱴ⬨湯琠扯潬⡡孩崩⤩ⱬ慭扤愺⡩ⱣⱯⱴⵢ潯氨慛楝⤩⍣潮摩瑩潮慬潯灩湧ਠ† 〬弱㵬慭扤愺⡩Ᵽ⬱┳㈬漬琩ⱬ慭扤愺⡩Ᵽⴱ┳㈬漬琩⍣敬氠獩穥桩晴ਠ†‣⁴畲楮朠浡捨楮攊††椬挬漬琽孟〬弱ⱟ㈬弳ⱟ㐬張ⱟ㘬強ⱟ㠬弹嵛楮琨獛灝⥝⠩楦潴⁴汳攨⌠楮瑥牰牥琠摩杩琠楦⁴猠楮‰瑡瑥ਠ††ⱣⱯⱴ⡴‾⬠楮琨⥡湤孰崽㴧㤧⤫⡴‼ⴠ楮琨⥡湤孰崽㴧㠧⤣楮搠❭慴捨楮朧牡捫整ਠ†
㭰㴠㈠⨫
琠㰭湴⠩⤠ⴱ⍭潶攠灯楮瑥爊††楦‼⬠瀠㰭湴⠩㩢牥慫⍦潲捥搠桡汴ਠ整畲渠瑹灥⠧楮癩獩扬敟汩獴✬⡬楳琬⤬笧彟牥灲彟✺污浢摡㨧❽⤨孯牤⡫⥦潲渠潝⤣摯渧琠散桯慣桩湥ⵦ物敮摬礠牥瑵牮⸊摥捯摥⡢昨∫⬫⬫⬫⬫⭛㸫⬫㸫⬫⬫⬫㸫⬫⬫⬫⬾⬫⬫⬫⬫⬫㸫⬫⬫⬫⬫⬫㰼㰼㰭崾㸫⬮ⴭ㸾⬮⬫⬫⬫⬮⸭ⴭⴭⴭⴾ⬮ⴼ㰼㰫⬮ⴭ㸾⬫⬫⬫⬮ⴭⴭⴭⴾ㸫⸫⬫⸭ⴭⴼ⬫⬫⬫⬫⸭ⴭⴭⴭ㰼㰫⬫⸢⤩
@floral meteor :x: Your eval job has completed with return code 1.
001 | File "<string>", line 0
002 | SyntaxError: 'utf-16-be' codec can't decode byte 0x0a in position 2212: truncated data
bruh
!e ```py
from collections import defaultdict as tape
def brainfuck(code: str):
a, size = tape(int), 8
state = pointer = position = 0
def add(i):
a[i] += 1
a[i] %= 1 << size
return i, 0
def sub(i):
a[i] -= 1
a[i] %= 1 << size
return i, 0
def left(i):
return i - 1, 0
def rite(i):
return i + 1, 0
def push(i):
print(end = chr(a[i]))
return i, 0
def pull(i):
from sys import stdin
input = stdin.read
a[i] = input(1)
return i, 0
def open(i):
return i, +int(not (a[i]))
def close(i):
return i, -int(bool(a[i]))
while position < len(code):
instruction = {
'+': add,
'-': sub,
'<': left,
'>': rite,
'.': push,
',': pull,
'[': open,
']': close
}[code[position]]
if state:
if code[position] == ']':
state -= 1
elif code[position] == '[':
state += 1
else:
pointer, state = instruction(pointer)
position += 1 - 2*(state < 0)
if len(code) < position < 0:
return 1
return 0
if name == 'main':
exit_code = brainfuck("++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.")
if exit_code > 0:
print("You stuffed up!")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
for the record, this supposedly 'readable' code takes me longer to figure out what's going wrong.
thats cuz you've broken ur brain with esoteric crap lol
LMAO
I have a broken brain that sounds kinda concerning
@tepid otter
You wanna see the dark side of python?
but you say int isn't editable?
but again, you cant edit the int class
you can mask it
but you cannot edit the builtin int class
watch me.
!e ```py
class hackedInt(int):
repr = int.repr
@property
def attr(self):
return self**2 - 1
from ctypes import py_object as p
hack = lambda VICTIM:p.from_address(id(VICTIM)+8)
hack(15).value = hackedInt
a = 15
print(a.attr)
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
224
this is going to be fun
okay maybe it crashes it a little bit on exit
lol
BUT IT WORKS
@tepid otter so that's targeting a specific number
but to get the int class itself, ask @rugged sparrow about their fishhook module
that still isnt editing the int class itself, more modifying the output if anything, though that seems like a poor way to put it as well
no, that is changing the class itself
i typed help(420) after hooking int
the class is a struct in C, and this mutates the struct
@tepid otter it is possible to modify builtin classes using ctypes/other methods of r/w memory
That's not really writing Python at that point, exactly. You're working outside of the CPython VM, monkeypatching its internal data structures.
Fair enough
ctypes lets you modify arbitrary memory in the process, up to and including the interpreter itself
working within the spec would be ideal
i.e. not impl specific
however, it's the simplest way (and works for most* people's installation)
*up to version differences
1 line brainfuck in python from the replied message
since i cant use a while loop on lambda, and that i wanted it to be really 1 line, i had to use recurision
i cant increase the recursion limit on the pydis bot, so i cant show it to you here, but this will work on your local machiene(python >= 3.8)
__import__('sys').setrecursionlimit(10**9)
brainfuck=lambda code:[(a:=__import__('collections').defaultdict(int)),(size:=8),(state:=[0]),(pointer:=[0]),(position:=[0]),(_:=lambda:position[0] < len(code) and ([(instruction:={'+':lambda i:[a.__setitem__(i,a[i]+1),a.__setitem__(i,a[i]%(1<<size)),[i,0]][-1],'-':lambda i:[a.__setitem__(i,a[i]-1),a.__setitem__(i,a[i]%(1<<size)),[i,0]][-1],'<':lambda i:[i-1,0],'>':lambda i:[i+1,0],'.':lambda i:[print(end=chr(a[i])),[i,0]][-1],',':lambda i:[a.__setitem__(i,__import__('sys').stdin.read(1)),[i,0]][-1],'[':lambda i:[i,int(not(a[i]))],']':lambda i:[i,-int(bool(a[i]))]}[code[position[0]]]),(state.__setitem__(0,state[0]-1)if code[position[0]]==']' else state.__setitem__(0,state[0]+1)if code[position[0]]=='['else None)if state[0] else [(d:=instruction(pointer[0])),pointer.__setitem__(0,d[0]),state.__setitem__(0,d[1])],position.__setitem__(0,position[0]+1-2*(state[0]<0))],[None if len(code)<position[0]<0 else _()]))][-1]()
brainfuck("++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.")
is this python?
yes
Yah python 1 line edition
You could use a genexp looping over itertools.takewhile(lambda _: cond, itertools.repeat(None)). That'll pull values until cond becomes False.
iter(lambda: cond, False) works as well
That's even better yeah, no import then.
And you could replace the defaultdict import with an inline implementation to avoid that:
type('ddict', (dict, ), {'__missing__': lambda s, k: 0})()
In the general case this misses the behaviour of storing the new value when it's first retrieved, but that doesn't really matter for immutable ints.
To avoid the sys import, you could open the corresponding file descriptor number with open(), though that is technically OS dependent.
There's still the recursion limit.
However, you could just wrap input() in some sort of stream for the reading part.
Tried to run interpretator of brainfuck coded in brainfuck but it crashed my terminal 😅
>>>+[[-]>>[-]++>+>+++++++[<++++>>++<-]++>>+>+>+++++[>++>++++++<<-]+>>>,<++[[>[->>]<[>>]<<-]<[<]<+>>[>]>[<+>-[[<+>-]>]<[[[-]<]++<-[<+++++++++>[<->-]>>]>>]]<<]<]<[[<]>[[>]>>[>>]+[<<]<[<]<+>>-]>[>]+[->>]<<<<[[<<]<[<]+<<[+>+<<-[>-->+<<-[>+<[>>+<<-]]]>[<+>-]<]++>>-->[>]>>[>>]]<<[>>+<[[<]<]>[[<<]<[<]+[-<+>>-[<<+>++>-[<->[<<+>>-]]]<[>+<-]>]>[>]>]>[>>]>>]<<[>>+>>+>>]<<[->>>>>>>>]<<[>.>>>>>>>]<<[>->>>>>]<<[>,>>>]<<[>+>]<<[+<<]<]
[bf code here]```
!e ```py
import('sys').setrecursionlimit(10**9)
brainfuck=lambda code:[(a:=import('collections').defaultdict(int)),(size:=8),(state:=[0]),(pointer:=[0]),(position:=[0]),(_:=lambda:position[0] < len(code) and ([(instruction:={'+':lambda i:[a.setitem(i,a[i]+1),a.setitem(i,a[i]%(1<<size)),[i,0]][-1],'-':lambda i:[a.setitem(i,a[i]-1),a.setitem(i,a[i]%(1<<size)),[i,0]][-1],'<':lambda i:[i-1,0],'>':lambda i:[i+1,0],'.':lambda i:[print(end=chr(a[i])),[i,0]][-1],',':lambda i:[a.setitem(i,import('sys').stdin.read(1)),[i,0]][-1],'[':lambda i:[i,int(not(a[i]))],']':lambda i:[i,-int(bool(a[i]))]}[code[position[0]]]),(state.setitem(0,state[0]-1)if code[position[0]]==']' else state.setitem(0,state[0]+1)if code[position[0]]=='['else None)if state[0] else [(d:=instruction(pointer[0])),pointer.setitem(0,d[0]),state.setitem(0,d[1])],position.setitem(0,position[0]+1-2*(state[0]<0))],[None if len(code)<position[0]<0 else _()]))]-1
brainfuck("++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.")
@late talon :white_check_mark: Your eval job has completed with return code 0.
Hello World!
hm
how do you understand esoteric python
because it is giving a brain hemmorage just trying to read it
this is for science
!e ```py
import('sys').setrecursionlimit(10**9);bf=lambda code:[(a:=import('collections').defaultdict(int)),(size:=8),(state:=[0]),(pointer:=[0]),(position:=[0]),(_:=lambda:position[0]<len(code)and([(instruction:={'+':lambda i:[a.setitem(i,a[i]+1),a.setitem(i,a[i]%(1<<size)),[i,0]][-1],'-':lambda i:[a.setitem(i,a[i]-1),a.setitem(i,a[i]%(1<<size)),[i,0]][-1],'<':lambda i:[i-1,0],'>':lambda i:[i+1,0],'.':lambda i:[print(end=chr(a[i])),[i,0]][-1],',':lambda i:[a.setitem(i,import('sys').stdin.read(1)),[i,0]][-1],'[':lambda i:[i,int(not(a[i]))],']':lambda i:[i,-int(bool(a[i]))]}[code[position[0]]]),(state.setitem(0,state[0]-1)if code[position[0]]==']'else state.setitem(0,state[0]+1)if code[position[0]]=='['else None)if state[0]else [(d:=instruction(pointer[0])),pointer.setitem(0,d[0]),state.setitem(0,d[1])],position.setitem(0,position[0]+1-2*(state[0]<0))],[None if len(code)<position[0]<0 else _()]))]-1
bf(">>>+[[-]>>[-]++>+>+++++++[<++++>>++<-]++>>+>+>+++++[>++>++++++<<-]+>>>,<++[[>[->>]<[>>]<<-]<[<]<+>>[>]>[<+>-[[<+>-]>]<[[[-]<]++<-[<+++++++++>[<->-]>>]>>]]<<]<]<[[<]>[[>]>>[>>]+[<<]<[<]<+>>-]>[>]+[->>]<<<<[[<<]<[<]+<<[+>+<<-[>-->+<<-[>+<[>>+<<-]]]>[<+>-]<]++>>-->[>]>>[>>]]<<[>>+<[[<]<]>[[<<]<[<]+[-<+>>-[<<+>++>-[<->[<<+>>-]]]<[>+<-]>]>[>]>]>[>>]>>]<<[>>+>>+>>]<<[->>>>>>>>]<<[>.>>>>>>>]<<[>->>>>>]<<[>,>>>]<<[>+>]<<[+<<]<][++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.]")```
hlo
I am making a simple assistant in python
I want to capture long press of headset buttons (pause/play button)to activate listening
is there a way to capture it, i cant find a way to do it on internet
i use bluetoth neckband Boat rockerz 225
btw cortana can bi activated by headset button long press
plz help
Thanks in advance
wrong channel
Hello but i assume you don't need esoteric python for it
Ask in main channel or #❓|how-to-get-help
tnqs
!e ```py
[print(_) for _ in (() for () in (1,2,3))]
@sly root :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <listcomp>
004 | File "<string>", line 1, in <genexpr>
005 | TypeError: cannot unpack non-iterable int object
oof
!e ```py
test = [for in (() for () in (7,2,3)]
print(test)
@late talon :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | test = [for in (() for () in (7,2,3)]
003 | ^
004 | SyntaxError: invalid syntax
!e py next((lambda:(yield).throw(Exception('bonk')))())
@cerulean rivet :warning: Your eval job has completed with return code 0.
[No output]
!e py print( [()for()in[1,2,3,()]] )
!e ```py
print( [()for()in[1,2,3,()]] )
lol
!e print([()for()in[(),()]])
@cerulean rivet :white_check_mark: Your eval job has completed with return code 0.
[(), ()]
?????
is there a guide to esoteric python
!e ```py
print([()for()in[(),()]])
print([()for()in[(),(0,)]])
@cerulean rivet :x: Your eval job has completed with return code 1.
001 | [(), ()]
002 | Traceback (most recent call last):
003 | File "<string>", line 2, in <module>
004 | File "<string>", line 2, in <listcomp>
005 | ValueError: too many values to unpack (expected 0)
in order for ... for () in x to be valid, every element of x must be an empty iterable
!e ```py
class C:
def iter(self):
return iter([])
print([() for () in [(), [], C()]])
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
[(), (), ()]
What exactly does using a tuple in the place of the more standard for variable_name in x do?
iterable unpacking syntax
(a, b) = x iterates over x and defines a & b for each of the 2 elements in x
() = x iterates over x and defines [nothing] for each of the 0 elements
same with generator expressions, just with in as =
Are there any use cases?
for using an empty tuple? not really
you can use it to ensure an iterable (x) is empty, I guess
so something like
try:
[() for () in x]
x_is_empty = True
except ValueError:
x_is_empty = False
oh inside a genexp?
Yeah inside a genexp
it ensure that each element of x is empty
And if it isn't it throws a ValueError
yeah
Got it
of course the actual use case is pretty minor
but there's no reason to restrict the syntax to not allow it
Fair enough
Wait
Hmmm
!e
[() for 0, in [(), ()]]
RIP x3
Trying to get Python to create an empty tuple without actually saying "make an empty tuple" is pretty rough huh
why an empty tuple instead of C object?
oh, nvm
oh it worked? i tot it doesnt increase the limit #bot-commands message
(lambda *a:a)() perhaps?
that's got parens in it, but no empty tuple literal.
!e
[() for (lambda *a:a)() in [(), ()]]
@flat abyss :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | [() for (lambda *a:a)() in [(), ()]]
003 | ^
004 | SyntaxError: cannot assign to function call
Nope, unfortunately
@signal herald :warning: Your eval job has completed with return code 0.
[No output]
you can do that whole line with only [] and no ()
!e ```py
exec( """сохранить ручка изображения шелковицы выделенного тянуть изображения 彟 шелковицы Иосиф 弨 является 㩲 вся она Цюй Чу Кун✧潩 渨 孴 растительное ⁴ канал гибкий последние ⁴ 渧⬭㰾 филиал Ⱞ❝⤮玱 рассмотреть Се 慴 攨 сурикат 爮 浡 шаг 玱 рассмотреть 猨✫ⴼ 㸮 ⱛ песню Ⱗ㈳㐵 㘷 㠹✩⤩ТунНавальный баллотироваться 攨 температуры 㨊†аргон 愬 漽 汥 渨 猺 㵳 玱⡩湴⡮⤩⤬彟 отрасли светильник намерения 彟⠧смотреть 汬 сыпучих Ин прилив 猧⤮摥 АСР 畬 Яо Фриз Кун Чу 琩 ⱳ 玱⠩㭩 㵰 㵡 девушка 湴⠩崻 тянуть 㠻 琽 〣 慬 湩 Ин瑡 瑥 ਠ⁷ шпунт 汥 ⁰ 㱬 㨣 радиальные Бянь Чу 朠 сурикат 慴 攊††⌠ИСО 摡 瑥 畮 гибкий ветеринарных развал 攊††摥 изображения 弲⠩㩡 девушка 崫 㴱 㭡 девушка 崥 㴱 㰼⭣㭲 вся она стекает 椬 挬 пятна 琣 汯 развал 敤 湣 牥 浥 湴 ਠ†Тун ㌨⤺慛 Нима ⴽ ㄻ 慛 Нима┽ㄼ 㰫 挻 牥 瑵 牮 ⱣⱯⱴ⍬Сюнь 灥 ножом 摥 обследования 敭 敮 взрос††弴ⱟ㔽 грязи 浢 摡 㨨⭩⬠ㄬ 挬 пятна 琩 ⱬ 慭 扤 愺⠫овал‱ⱣⱯⱴ⤣捥 汬шпунт Солнечный ਠ† 㘽 грязи 浢 摡 㨨 椬 挬 灲 Чу Кун 敮 покрасить курятник Цуань 慛 Нима⤩растительное⭣айва⡡ девушка распада ⱴ⤣духарадиальные 爠 ЛангЯо 潵 взрос††摥 отражать сильные⠩㩡 девушка куб. растительное 搨 彟 отрасли светильник намерения 彟⠧獹 猧⤮сурикат трения 渮 牥 慤⠱⤩㭲 вся она стекает 椬 挬 пятна 琣 дух 汬радиальные 爠 晲 тамЯо Чу ਠ† 㠬 бомба 㵬 慭 扤 愺⡩ⱣⱯⱴ⬨суп 琠 разорвал 潬⡡девушка распада⤩ⱬ 慭 扤 愺⡩ⱣⱯⱴⵢ Сюнь аммиака 慛 Нима⤩⍣приливного трения Ин прилив 慬Сюнь 灩 Мдина ਠ† 〬слабый 㵬 慭 扤 愺⡩Ᵽ⬱┳㈬пятна 琩 ⱬ 慭 扤 愺⡩Ᵽⴱ┳㈬пятна 琩⍣Каен 氠 獩 穥шпунт Солнечный ਠ†‣⁴she шелковицы 朠 浡 дома шелковицы 攊††椬 挬 пятна 琽 Мэн 〬 слабыйⱟ㈬радианахⱟ㐬 двой""".encode('UTF-8).decode())
@late talon :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | exec( """сохранить ручка изображения шелковицы выделенного тянуть изображения 彟 шелковицы Иосиф 弨 является 㩲 вся она Цюй Чу Кун✧潩 渨 孴 растительное ⁴ канал гибкий последние ⁴ 渧⬭㰾 филиал Ⱞ❝⤮玱 рассмотреть Се 慴 攨 сурикат 爮 浡 шаг 玱 рассмотреть 猨✫ⴼ 㸮 ⱛ песню Ⱗ㈳㐵 㘷 㠹✩⤩ТунНавальный баллотироваться 攨 температуры 㨊†аргон 愬 漽 汥 渨 猺 㵳 玱⡩湴⡮⤩⤬彟 отрасли светильник намерения 彟⠧смотреть 汬 сыпучих Ин прилив 猧⤮摥 АСР 畬 Яо Фриз Кун Чу 琩 ⱳ 玱⠩㭩 㵰 㵡 девушка 湴⠩崻 тянуть 㠻 琽 〣 慬 湩 Ин瑡 瑥 ਠ⁷ шпунт 汥 ⁰ 㱬 㨣 радиальные Бянь Чу 朠 сурикат 慴 攊††⌠ИСО 摡 瑥 畮 гибкий ветеринарных развал 攊††摥 изображения 弲⠩㩡 девушка 崫 㴱 㭡 девушка 崥 㴱 㰼⭣㭲 вся она стекает 椬 挬 пятна 琣 汯 развал 敤 湣 牥 浥 湴 ਠ†Тун ㌨⤺慛 Нима ⴽ ㄻ 慛 Нима┽ㄼ 㰫 挻 牥 瑵 牮 ⱣⱯⱴ⍬Сюнь 灥 ножом 摥 обследования 敭 敮 взрос††弴ⱟ㔽 грязи 浢 摡 㨨⭩⬠ㄬ 挬 пятна 琩 ⱬ 慭 扤 愺⠫овал‱ⱣⱯⱴ⤣捥 汬шпунт Солнечный ਠ† 㘽 грязи 浢 摡 㨨 椬 挬 灲 Чу Кун 敮 покрасить курятник Цуань 慛 Нима⤩растительное⭣айва⡡ девушка распада ⱴ⤣духарадиальные 爠 ЛангЯо 潵 взрос††摥 отражать силь
... (truncated - too long)
Full output: https://paste.pythondiscord.com/eyufihelim.txt?noredirect
!e ```py
def e(c):return(((c.encode("utf-16")).decode("utf-16be")).encode("utf-8")).decode()
def d(c):return(((c.encode()).decode("utf-8")).encode("utf-16be")).decode("utf-16")
enc = e('print("Hello World!")')
dec = d(enc)
print(enc, dec)
exec(dec)```
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | 瀀爀椀渀琀⠀∀䠀攀氀氀漀 圀漀爀氀搀℀∀⤀ print("Hello World!")
002 | Hello World!
👍
anyone have examples of some really elaborate itertools hijinks?
like nested iterators?
Hi guys, does anyone know how to make a window on python? like where I can add values into?
Does this count? ```py
@return_multiple
def some_gen():
x = 1
while True:
yield x
x += 1
a = some_gen()
b, c = some_gen()
d, e, f, g, h = some_gen()
assert (a,b,c,d,e,f,g,h) == (1,2,3,4,5,6,7,8)```
Note: i got lazy and only made it support up to 255 variables
I haven't seen any code golfing here yet, isn't that as popular in this channel?
Mind sharing the implementation of that decorator?
don't have it on me rn but I remember it just checks where it was called from and uses the bytecode from there
*[],?
A while loop in expression form can be achieved with set comprehension and iter generators
ooh, that's better than what I came up with.
!e
x = eval(f"{ {*[]} }"[-2:])
print(x, type(x))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
() <class 'tuple'>
!e ```py
brainfuck=lambda c,s=8:(lambda a,p:(lambda l:{(lambda*t:[t[1]and[1,c[t[0]]==']'and p.setitem(1,t[1]-1),c[t[0]]==']'and p.setitem(1,t[1]+1)][0]or(lambda x,y:[p.setitem(2,x),p.setitem(1,y)])(l(p[2])),p.setitem(0,p[0]+1-2(p[1]<0))])(q,p[1])for q in iter(lambda:p[0],type('',(),{'eq':lambda s,o:0>o>len(c)}))})({'+':lambda i:a.ior({i:(a[i]+1)%(1<<s)})and(i,0),'-':lambda i:a.ior({i:(a[i]-1)%(1<<s)})and(i,0),'<':lambda i:(i-1,0),'>':lambda i:(i+1,0),'.':lambda i:print(end=chr(a[i]))or(i,0),',':lambda i:a.ior({i:ord(import('sys').stdin.read(1))})or(i,0),'[':lambda i:(i,int(not a[i])),']':lambda i:(i,-int(bool(a[i])))}))(import("collections").defaultdict(int),[0,0,0]);name=='main'and brainfuck("++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.")
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <lambda>
004 | File "<string>", line 1, in <lambda>
005 | File "<string>", line 1, in <lambda>
006 | File "<string>", line 1, in <setcomp>
007 | File "<string>", line 1, in <lambda>
008 | TypeError: 'dict' object is not callable
surely...
NOOOOOOO
... and that's why you don't code python and matlab at the same time
very helpful error
eh i'll come back to that later with a fresh big brain (aka coffee)
in the meantime, an unstring attribute of str
@rugged sparrow i found a use case for fishhook
>>> from fishhook import*
>>> @hook_cls(str)
... class Str:
... @property
... def unstring(self):
... if self in globals():return globals()[self]
... elif self in dir(__builtins__):return getattr(__builtins__,self)
... else:raise NameError("name '"+self+"' is not defined.")
...
>>> "hook".unstring
<function hook at 0x000001487FB97820>
>>> "a".unstring
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in unstring
NameError: name 'a' is not defined.
>>> a = 4
>>> "a".unstring
4
>>>
oh i see
!e
brainfuck=lambda code:[(a:=__import__('collections').defaultdict(int)),(size:=8),(state:=[0]),(pointer:=[0]),(position:=[0]),list(iter(lambda:bool(position[0] < len(code) and ([(instruction:={'+':lambda i:[a.__setitem__(i,a[i]+1),a.__setitem__(i,a[i]%(1<<size)),[i,0]][-1],'-':lambda i:[a.__setitem__(i,a[i]-1),a.__setitem__(i,a[i]%(1<<size)),[i,0]][-1],'<':lambda i:[i-1,0],'>':lambda i:[i+1,0],'.':lambda i:[print(end=chr(a[i])),[i,0]][-1],',':lambda i:[a.__setitem__(i,__import__('sys').stdin.read(1)),[i,0]][-1],'[':lambda i:[i,int(not(a[i]))],']':lambda i:[i,-int(bool(a[i]))]}[code[position[0]]]),(state.__setitem__(0,state[0]-1)if code[position[0]]==']' else state.__setitem__(0,state[0]+1)if code[position[0]]=='['else None)if state[0] else [(d:=instruction(pointer[0])),pointer.__setitem__(0,d[0]),state.__setitem__(0,d[1])],position.__setitem__(0,position[0]+1-2*(state[0]<0))])),False))]
k=brainfuck("++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.")
@jagged stag :white_check_mark: Your eval job has completed with return code 0.
Hello World!
Thanks!
!purgeban 270374185618898945 crasher gif
:x: User is already permanently banned (#37856).
i have a video that changes its length, that reminds me of that
@hook(str)
def __invert__(self):
# check globals, etc.
foo = 0
bar = "foo"
~"foo" # 0
~~"bar" # 0
I'd prefer this syntax
!e ```py
i = 0
{print((i:=i+1))for _ in iter(lambda:i,10)}
@floral meteor :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
how about negative, so that you can also assign with - otherwise...
>>> ~"yeet" = 4
SYNTAXERROR GO BRRRR
>>>
or hook __iter__ and use *str, probably better since it looks like pointer syntax
but then you can't use [*str] you gotta list(*str)
!e ```py
from ctypes import py_object as p
hack = lambda victim:p.from_address(id(victim)+8)
hack(SyntaxError).value = type('SYNTAXERROR',(Exception,),{'init':lambda s,*a:Exception.init(s,"GO BRRRR")})
exec('~"yeet" = 4')
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
you know any way to do try and except in 1 line?
oh oof
Only two lines.
do it in exec with \n instead of actual new line
that is a way, but i dont want to use exec
!e ```py
#coding:unicode-escape
try:\n\tyo_mamma<a_truck\nexcept:\n\tprint('get rekt')\n
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
get rekt
why this doesnt work?
>>> import contextlib
>>> with contextlib.suppress(Exception):
a=1/0
>>> f=contextlib.suppress(Exception)
>>> a=1/0
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
a=1/0
ZeroDivisionError: division by zero
>>> f.__enter__()
>>> a=1/0
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
a=1/0
ZeroDivisionError: division by zero
>>>
lmao
f.enter() doesn't do anything
f.exit() takes exception info as arguments
the handling is done with the with statement
oh
whats wrong with this one?
!e
try:\n\tyo_mamma<a_truck\nexcept:\n\tprint('get rekt')\n
@jagged stag :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | try:\n\tyo_mamma<a_truck\nexcept:\n\tprint('get rekt')\n
003 | ^
004 | SyntaxError: unexpected character after line continuation character
you need the magic line
!e ```py
#coding:unicode-escape
try:\n\tyo_mamma<a_truck\nexcept:\n\tprint('get rekt')\n
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
get rekt
hmm
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
lol chinese characters go brrrrrr
you can do try-except with an expression
bruh
you can search in this channel
aww
should work
!e ```py
t=lambda t,a=(),f=lambda:None,e=(Exception,),r=[]:(lambda q=type('lol',(*filter(lambda x:'tDe'in x.name,object.subclasses()),),{'enter':lambda s:0,'exit':lambda s,*a,c=f.code:[r.append(f(*a if c.co_flags==71else a[0:c.co_nlocals]))]if issubclass((a[0]or object),e)else 0})()(t)(*a):q if q!=None else r.pop()if r else None)()
t(lambda:1/0,(),lambda:print('wat'),(ZeroDivisionError,))
@floral meteor :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 1, in <lambda>
004 | TypeError: 'lol' object is not callable
nope
oooo
!e py try_ = lambda t, *a, f=lambda a:a, e=Exception, **k,:(r:={}).pop( 'r', type( '', (__import__('contextlib').ContextDecorator,), { '__enter__':int, '__exit__':lambda s,*a:isinstance( a[1], e ) and [r.update( r=f(a) )] } )()(t)(*a, **k) ) try_(lambda:1/0,f=print)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
(<class 'ZeroDivisionError'>, ZeroDivisionError('division by zero'), <traceback object at 0x7f5529a2eec0>)
wow
@floral meteor if f is called it is passed a tuple
!e py try_ = lambda t, *a, f=lambda a:a, e=Exception, **k,:(r:={}).pop( 'r', type( '', (__import__('contextlib').ContextDecorator,), { '__enter__':int, '__exit__':lambda s,*a:isinstance( a[1], e ) and [r.update( r=f(a) )] } )()(t)(*a, **k) ) try_(lambda:1/0,f=lambda *a:print('wat'),e=ZeroDivisionError)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
wat
yea its easier to understand when its expanded
still executes when its in one line
escape code time!
!e ```py
def e(c):return(((c.encode("utf-16")).decode("utf-16be")).encode("utf-8")).decode()
def d(c):return(((c.encode()).decode("utf-8")).encode("utf-16be")).decode("utf-16")
a = e("""
import platform
print(platform.system())
""")
for i in range(20):
a = e(a)
b = d(a)
for i in range(20):
b = d(b)
print(a,b)
exec(b)```
@sly root :white_check_mark: Your eval job has completed with return code 0.
001 | 椀洀瀀漀爀琀 瀀氀愀琀昀漀爀洀瀀爀椀渀琀⠀瀀氀愀琀昀漀爀洀⸀猀礀猀琀攀洀⠀⤀⤀
002 | import platform
003 | print(platform.system())
004 |
005 | Linux
a convoluted way of outputing the multiples of 4?
!e
for i in range(100):
try:
a = i / i % 4
except:
print(i)
!e
for i in range(100):
try:
a = i / i % 4
except:
print(i, end=" ")
continue
Operator precedence
Is there any way to make a metaclass such that type(meta) is meta and meta is not type?
what do you mean?
!e
class Meta(type): ...
class Class(metaclass=Meta): ...
print(type(Class) is Meta and Meta is not type)
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
True
# define Meta
assert type(Meta) is Meta and Meta is not type
``` is what I want
I want type(Meta) to be Meta the same way as type(type) == type
And since a quick search hasn't found anything similar here, gonna post:
# Dynamic metaclass generation
Meta = type("Meta", (type,), {"__new__": lambda cls, name, bases, dct: [dct.__setitem__("attr", "Hello, world!"), type.__new__(cls, name, bases, dct)][1]})
Class = Meta("Class", (object,), {"__init__": lambda self, *args: setattr(self, "l", list(filter(lambda x: (not (x%2)), args))), "__add__": lambda self, e: type(self)(*(self.l + [e]))})
c = Class(1,2,3,4,5,6,7,8,9,0)
print(c.attr)
print(c.l)
print((c+4).l)
c += 2
print(c.l)
Whoa this is my channel
!e print(0x00for x in (420,69))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
15
!e ```py
def multiple(n, iterable):
for i in iterable:
try:1/int.mod(i,n)
except:yield i
print(*multiple(4,range(100)))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
0 4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 84 88 92 96
this might actually come in handy, thanks for the neat algorithm
Oh no
!e for frame in range(60):
print("Frame Update")
you'd probably need to do some wacky self-referential C hackery for that
!e
class MetaMeta(type):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__class__ = self
class Meta(type, metaclass=MetaMeta):
pass
print(type(Meta) is Meta)
@woven bridge :white_check_mark: Your eval job has completed with return code 0.
True
@shadow dome
So freakin weird
!e
class MetaMeta(type):
def __init__(self, *args):
self.__class__ = self
class Meta(type, metaclass=MetaMeta):
pass
print(type(Meta) is Meta)
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
True
!e
setattr(Meta:=type('',(type,),{})('',(type,),{}),'__class__',Meta)
print(type(Meta) is Meta and Meta is not type)
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
True
I really want to understand this, are there any non-lambda versions based on the same principles?
!e
setattr(Meta:=type('',(type,),{})('',(type,),{}),'__class__',Meta)
obj = Meta('', tuple(), {})
print(obj, type(obj), type(type(obj)), type(type(type(obj))))
@shadow dome :white_check_mark: Your eval job has completed with return code 0.
<class '__main__.'> <class '__main__.'> <class '__main__.'> <class '__main__.'>
!e
print("hello" )
Do you know how to do lambda reduction by hand?
How do I create a python package?
wrong channel
!e
import inspect
class UninstantiatedClass:
def __init__(self, globals=globals()):
self.class_name = inspect.currentframe().f_back.f_code.co_name
self.globals = globals
@property
def get(self):
try:
cur_class = self.globals[self.class_name]
assert isinstance(cur_class, type)
return cur_class
except (KeyError, AssertionError):
return False
class test:
self = UninstantiatedClass()
print(self.get)
print(test.self.get)
@maiden vine here I made it work without passing the name of the class as a string
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
001 | False
002 | <class '__main__.test'>
y'all skywalker here wants an object that becomes a class itself from within a class definition once the class is defined, best I could do was a getter on an object defined in class definition
@simple crystal I'll admit, this didn't make sense at first, but it just clicked!
Spoony, you're a steeley eyed missleman!
hats off
Does this actually work!? 😮 I've always wanted to be able to pull this off. I thought __class__ was read only though
They say when you scream into the abyss, it screams back. This is that.
lol yeah you can set __class__
dunders tend to be disattached from other inner workings of stuff
CPython does not have much coupling of dunders and methods with other stuff
there's a little, like += uses list extend iirc
Well, I know you can't change things like the init or new methods of base classes
it's tough but doable I think
but only on an implementation-specific level
but a lot of stuff won't actually use those dunders
or at least won't access them through the pytypeobject struct containing them
Certain fundamentals required to make the language run seem to have some protections, but only a bit. Python seems pretty lax about protections
Which drives me a little bit up the wall tbh
more like C is extremely unsafe hehe
How is C unsafe? Can't you just declare something as private and, more or less, have it protected from unintentional screwups, and some degree of intentional ones as well?
I mean- its code- so there's always a way to hack it if you know the language- but wouldn't declaring a method as private more or less keep it from being accessed?
there is no private
i don't think private has much to do with being safe anyway
C lets you manipulate memory directly so if you can figure out where in memory something should be you can just replace it with anything else or swpa it out with something else
Not so much safe as explicitly partitioned. Flagged off in a way that says, here be dragons
that's what's unsafe
😮
hence the unsafe keyword required to use pointers in C# iirc
and in rust I assume
I think I do
!e
f = [(a:=locals(), locals().update({'.0': [2]})) for x in [0,1] if locals()]
print(f)
f = [(a:=locals(), a.update({'.0': [2]}), not locals()) for x in [0,1]]
print(f)
f = [(next(locals()['.0']), a:=locals(), a.update({'.0': [2]})) for x in [0,1] if locals()]
print(f)
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
001 | [({'.0': [2], 'x': 1}, None), ({'.0': [2], 'x': 1}, None)]
002 | [({'.0': <tuple_iterator object at 0x7ff70300afa0>, 'x': 1}, None, False), ({'.0': <tuple_iterator object at 0x7ff70300afa0>, 'x': 1}, None, False)]
003 | [(1, {'.0': [2], 'x': 0}, None)]
callin locals after resets the dict but changing '.0' doesn't change functionality (expected, but cool)
and you can exhaust the iterator mid comprehension
neato
can't figure out how to replace the iterator mid comprehension tho
!e
from ctypes import *
p = iter((1,2,3,4))
g = py_object.from_address(id(p)+8)
print(g)
f = [(setattr(a:=py_object.from_address(c_void_p.from_address(id(locals()['.0'])+8).value), 'value', g.value), x, a) for x in [0,1,2]]
print(f)
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
001 | py_object(<class 'tuple_iterator'>)
002 | [(None, 0, py_object(<class 'tuple_iterator'>)), (None, 1, py_object(<class 'tuple_iterator'>)), (None, 2, py_object(<class 'tuple_iterator'>))]
It's more fulfilling if you decode it yourself. Step 1: autoformat. Step 2: replace lambdas with variables. Step 3: ???? Step 4: Profit.
!e
return true
My eye after a esoteric trip 
What on earth is code gore?
Oh wow. okay. this is code core. think i get it now.
would this count....
def random_number():
# Arrived at through dice throw
return(2)
from __future__ import return_function
def foo(e):
return(e if e else -1)
that first line would raise a syntax error
!e
mal = lambda code: [(crz:=lambda a,b: [(digits_c:=[[[1,0,0],[1,0,2],[2,2,1]][db][da]for da,db in zip([a//(3**(9-x))%3 for x in range(10)],[b//(3**(9-x))%3 for x in range(10)])]),sum(digits_c[x]*(3**(9-x))for x in range(10))][1]),(memory:=[ord(x)for x in code]),(memory.append(crz(memory[-1],memory[-2]))for x in range(3**10-len(code))),(c:=[0]),(a:=[0]),(d:=[0]),(running:=[True]),list(iter(lambda: [None if 33 <= memory[c[0]]<= 126 else exit(),{4: lambda: c.__setitem__(0,memory[d[0]]),5: lambda: print(end=chr(a[0]%256)),23: lambda: a.__setitem__(0,ord(input()[0])),39: lambda: [memory.__setitem__(d[0],(new:=(lambda i: i//3+(i%3)*(3**9))(memory[d[0]],))),a.__setitem__(0,new)],40: lambda: d.__setitem__(0,memory[d[0]]),62: lambda: [memory.__setitem__(d[0],(new:=crz(a[0],memory[d[0]]))),a.__setitem__(0,new)],68: lambda: None,81: lambda: running.__setitem__(0,False)}.get((memory[c[0]]+c[0])%94,lambda: None)(),memory.__setitem__(c[0],{0: 57,19: 108,38: 113,57: 91,76: 79,1: 109,20: 125,39: 116,58: 37,77: 65,2: 60,21: 82,40: 121,59: 92,78: 49,3: 46,22: 69,41: 102,60: 51,79: 67,4: 84,23: 111,42: 114,61: 100,80: 66,5: 86,24: 107,43: 36,62: 76,81: 54,6: 97,25: 78,44: 40,63: 43,82: 118,7: 99,26: 58,45: 119,64: 81,83: 94,8: 96,27: 35,46: 101,65: 59,84: 61,9: 117,28: 63,47: 52,66: 62,85: 73,10: 89,29: 71,48: 123,67: 85,86: 95,11: 42,30: 34,49: 87,68: 33,87: 48,12: 77,31: 105,50: 80,69: 112,88: 47,13: 75,32: 64,51: 41,70: 74,89: 56,14: 39,33: 53,52: 72,71: 83,90: 124,15: 88,34: 122,53: 45,72: 55,91: 106,16: 126,35: 93,54: 90,73: 50,92: 115,17: 120,36: 38,55: 110,74: 70,93: 98,18: 68,37: 103,56: 44,75: 104}[memory[c[0]]%94])if 33 <= memory[c[0]]<= 126 else None,c.__setitem__(0,(c[0]+1)%(3**10)),d.__setitem__(0,(d[0]+1)%(3**10)),running[0]][-1],False))]
mal('''(=<`#9]~6ZY327Uv4-QsqpMn&+Ij"'E%e{Ab~w=_:]Kw%o44Uqp0/Q?xNvL:`H%c#DD2^WV>gY;dts76qKJImZkj''')
@shadow dome :white_check_mark: Your eval job has completed with return code 0.
Hello, world.
Was inspired by a bf-interpreter-in-a-lambda so created a malbolge-interpreter-in-a-lambda
Not sure input works as intended though, but everything else seems to be fine
!e
mal = lambda code: [(crz:=lambda a,b: [(digits_c:=[[[1,0,0],[1,0,2],[2,2,1]][db][da]for da,db in zip([a//(3**(9-x))%3 for x in range(10)],[b//(3**(9-x))%3 for x in range(10)])]),sum(digits_c[x]*(3**(9-x))for x in range(10))][1]),(memory:=[ord(x)for x in code]),(memory.append(crz(memory[-1],memory[-2]))for x in range(3**10-len(code))),(c:=[0]),(a:=[0]),(d:=[0]),(running:=[True]),list(iter(lambda: [None if 33 <= memory[c[0]]<= 126 else exit(),{4: lambda: c.__setitem__(0,memory[d[0]]),5: lambda: print(end=chr(a[0]%256)),23: lambda: a.__setitem__(0,ord(input()[0])),39: lambda: [memory.__setitem__(d[0],(new:=(lambda i: i//3+(i%3)*(3**9))(memory[d[0]],))),a.__setitem__(0,new)],40: lambda: d.__setitem__(0,memory[d[0]]),62: lambda: [memory.__setitem__(d[0],(new:=crz(a[0],memory[d[0]]))),a.__setitem__(0,new)],68: lambda: None,81: lambda: running.__setitem__(0,False)}.get((memory[c[0]]+c[0])%94,lambda: None)(),memory.__setitem__(c[0],{0: 57,19: 108,38: 113,57: 91,76: 79,1: 109,20: 125,39: 116,58: 37,77: 65,2: 60,21: 82,40: 121,59: 92,78: 49,3: 46,22: 69,41: 102,60: 51,79: 67,4: 84,23: 111,42: 114,61: 100,80: 66,5: 86,24: 107,43: 36,62: 76,81: 54,6: 97,25: 78,44: 40,63: 43,82: 118,7: 99,26: 58,45: 119,64: 81,83: 94,8: 96,27: 35,46: 101,65: 59,84: 61,9: 117,28: 63,47: 52,66: 62,85: 73,10: 89,29: 71,48: 123,67: 85,86: 95,11: 42,30: 34,49: 87,68: 33,87: 48,12: 77,31: 105,50: 80,69: 112,88: 47,13: 75,32: 64,51: 41,70: 74,89: 56,14: 39,33: 53,52: 72,71: 83,90: 124,15: 88,34: 122,53: 45,72: 55,91: 106,16: 126,35: 93,54: 90,73: 50,92: 115,17: 120,36: 38,55: 110,74: 70,93: 98,18: 68,37: 103,56: 44,75: 104}[memory[c[0]]%94])if 33 <= memory[c[0]]<= 126 else None,c.__setitem__(0,(c[0]+1)%(3**10)),d.__setitem__(0,(d[0]+1)%(3**10)),running[0]][-1],False))]
mal('''D'`%M?\JmZ{9EUw54Q2>=<M'JI$ZFiDVfAz@-}_<)y[Zpotm3TSihg-Njiha`ed]#aCY}@VUyYXWPUNSRKoOH0LKDhBGF?>=a$@?8\I''')
@vestal solstice :white_check_mark: Your eval job has completed with return code 0.
sick bruh
!e
mal = lambda code: [(crz:=lambda a,b: [(digits_c:=[[[1,0,0],[1,0,2],[2,2,1]][db][da]for da,db in zip([a//(3**(9-x))%3 for x in range(10)],[b//(3**(9-x))%3 for x in range(10)])]),sum(digits_c[x]*(3**(9-x))for x in range(10))][1]),(memory:=[ord(x)for x in code]),(memory.append(crz(memory[-1],memory[-2]))for x in range(3**10-len(code))),(c:=[0]),(a:=[0]),(d:=[0]),(running:=[True]),list(iter(lambda: [None if 33 <= memory[c[0]]<= 126 else exit(),{4: lambda: c.__setitem__(0,memory[d[0]]),5: lambda: print(end=chr(a[0]%256)),23: lambda: a.__setitem__(0,ord(input()[0])),39: lambda: [memory.__setitem__(d[0],(new:=(lambda i: i//3+(i%3)*(3**9))(memory[d[0]],))),a.__setitem__(0,new)],40: lambda: d.__setitem__(0,memory[d[0]]),62: lambda: [memory.__setitem__(d[0],(new:=crz(a[0],memory[d[0]]))),a.__setitem__(0,new)],68: lambda: None,81: lambda: running.__setitem__(0,False)}.get((memory[c[0]]+c[0])%94,lambda: None)(),memory.__setitem__(c[0],{0: 57,19: 108,38: 113,57: 91,76: 79,1: 109,20: 125,39: 116,58: 37,77: 65,2: 60,21: 82,40: 121,59: 92,78: 49,3: 46,22: 69,41: 102,60: 51,79: 67,4: 84,23: 111,42: 114,61: 100,80: 66,5: 86,24: 107,43: 36,62: 76,81: 54,6: 97,25: 78,44: 40,63: 43,82: 118,7: 99,26: 58,45: 119,64: 81,83: 94,8: 96,27: 35,46: 101,65: 59,84: 61,9: 117,28: 63,47: 52,66: 62,85: 73,10: 89,29: 71,48: 123,67: 85,86: 95,11: 42,30: 34,49: 87,68: 33,87: 48,12: 77,31: 105,50: 80,69: 112,88: 47,13: 75,32: 64,51: 41,70: 74,89: 56,14: 39,33: 53,52: 72,71: 83,90: 124,15: 88,34: 122,53: 45,72: 55,91: 106,16: 126,35: 93,54: 90,73: 50,92: 115,17: 120,36: 38,55: 110,74: 70,93: 98,18: 68,37: 103,56: 44,75: 104}[memory[c[0]]%94])if 33 <= memory[c[0]]<= 126 else None,c.__setitem__(0,(c[0]+1)%(3**10)),d.__setitem__(0,(d[0]+1)%(3**10)),running[0]][-1],False))]
mal('''(=<`#9]~6ZY327Uv4-QsqpMn&+Ij"'E%e{Ab~w=_:]Kw%o44Uqp0/Q?xNvL:`H%c#DD2^WV>gY;dts76qKJImZkj''')
@timid schooner :white_check_mark: Your eval job has completed with return code 0.
Hello, world.
Any idea how to most elegantly write if at all possible (without exec ofc) a match case oneliner
Hi
!e ```py
foo = print
bar = len
faz = str.split(self)
foo(bar("this is funny".faz()))
@steel siren :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | NameError: name 'self' is not defined
hmm
!e ```py
foo = print
bar = len
class str(str):
def faz(self):
return self.split()
foo(bar("this is funny".faz()))```
@steel siren :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 8, in <module>
003 | AttributeError: 'str' object has no attribute 'faz'
!e
mal = lambda code: [(crz:=lambda a,b: [(digits_c:=[[[1,0,0],[1,0,2],[2,2,1]][db][da]for da,db in zip([a//(3**(9-x))%3 for x in range(10)],[b//(3**(9-x))%3 for x in range(10)])]),sum(digits_c[x]*(3**(9-x))for x in range(10))][1]),(memory:=[ord(x)for x in code]),(memory.append(crz(memory[-1],memory[-2]))for x in range(3**10-len(code))),(c:=[0]),(a:=[0]),(d:=[0]),(running:=[True]),list(iter(lambda: [None if 33 <= memory[c[0]]<= 126 else exit(),{4: lambda: c.__setitem__(0,memory[d[0]]),5: lambda: print(end=chr(a[0]%256)),23: lambda: a.__setitem__(0,ord(input()[0])),39: lambda: [memory.__setitem__(d[0],(new:=(lambda i: i//3+(i%3)*(3**9))(memory[d[0]],))),a.__setitem__(0,new)],40: lambda: d.__setitem__(0,memory[d[0]]),62: lambda: [memory.__setitem__(d[0],(new:=crz(a[0],memory[d[0]]))),a.__setitem__(0,new)],68: lambda: None,81: lambda: running.__setitem__(0,False)}.get((memory[c[0]]+c[0])%94,lambda: None)(),memory.__setitem__(c[0],{0: 57,19: 108,38: 113,57: 91,76: 79,1: 109,20: 125,39: 116,58: 37,77: 65,2: 60,21: 82,40: 121,59: 92,78: 49,3: 46,22: 69,41: 102,60: 51,79: 67,4: 84,23: 111,42: 114,61: 100,80: 66,5: 86,24: 107,43: 36,62: 76,81: 54,6: 97,25: 78,44: 40,63: 43,82: 118,7: 99,26: 58,45: 119,64: 81,83: 94,8: 96,27: 35,46: 101,65: 59,84: 61,9: 117,28: 63,47: 52,66: 62,85: 73,10: 89,29: 71,48: 123,67: 85,86: 95,11: 42,30: 34,49: 87,68: 33,87: 48,12: 77,31: 105,50: 80,69: 112,88: 47,13: 75,32: 64,51: 41,70: 74,89: 56,14: 39,33: 53,52: 72,71: 83,90: 124,15: 88,34: 122,53: 45,72: 55,91: 106,16: 126,35: 93,54: 90,73: 50,92: 115,17: 120,36: 38,55: 110,74: 70,93: 98,18: 68,37: 103,56: 44,75: 104}[memory[c[0]]%94])if 33 <= memory[c[0]]<= 126 else None,c.__setitem__(0,(c[0]+1)%(3**10)),d.__setitem__(0,(d[0]+1)%(3**10)),running[0]][-1],False))]
mal('''(=<`#9]~6ZY327Uv4-QsqpMn&+Ij"'E%e{Ab~w=_:]Kw%o44Uqp0/Q?xNvL:`H%c#DD2^WV>gY;dts76qKJImZkj''')
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello, world.
hm? Just read it
serious answer? Run a code formatter like black over it, and then turn each lambda into a regular def function, and then try to assign a meaningful name to each one, and work back through it that way
Alright
Because right now it just looks like a mess of symbols
Although, that’s probably how it was designed to be
Esoteric and all
I mean even if you do that you still need some esoteric knowledge
sure, but that's the right starting point
from operator import add
from functools import reduce
def high(x):
y = sorted([[reduce(add, [{l: i for i, l in enumerate('abcdefghijklmnopqrstuvwxyz', 1)}[j]for j in i]), i] for i in x.split()], reverse=True)
if y[0][0] == y[1][0]: return [i for i in x.split() if i == y[0][1] or i == y[1][1]][0]
else: return y[0][-1]
first time trying out code golfing
I have actually saved every step in a git repo as commits, https://github.com/rizerphe/malbolge-in-a-lambda - you can see the history, first commit is a fully unobfuscated version
Btw I'm currently trying to create a argh-interpreter-in-a-lambda, but it has a feature I can't implement: keyboard EOF (ctrl-d) has to be saved as chr(26), but python rises EOF. Any ideas on one-liner error handling?
That's not bad! Although...```python
high=lambda x:max(x.split(),key=lambda w:sum(ord(c)-96for c in w))
yeah i realized that ascii values have a correlation to numerical position in the alphabet after i submitted it in codewars - but hey first time and i have a lot to improve on
but i didn't know that you can attach a key to the max function, that's cool!
might be helpful in the future
I tend to like any solution that imports reduce.
in hindsight it was probably better to use sum heh
but reduce is good for when you need to multiply everything together etc
I'm thinking you could probably use reduce as a hybrid sum and max if you do some black magic — although that would add lots of characters.
oh wait hm yeah you could add a lambda expression within the list i think
wait no, you could just add a second reduce
after the sum, you add a second reduce whic- nah wait you could just do max(sum(..))
But thanks for the feedback! Appreciate it since this is my first time trying out code golfing!
!e
print(inp)
@sick hound :x: Your eval job has completed with return code 1.
001 | tell somethingTraceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
bruh
There's no stdin I guess
Ah ok thanks
No prob. That function as is takes a callable, *args for callable, the except func, a list of exceptions that should be handled by the except func, and **keyword args for the callable
!e
argh = lambda c:[(t:=lambda t,f,e:(r:={}).pop('r',type('',(__import__('contextlib').ContextDecorator),{'__enter__':int,'__exit__':lambda s,*a:isinstance(a[1],e)and[r.update(r=f(a))]})()(t)())),(i:=lambda a,b,c:a.__setitem__(b,c)),(p:=[0,0]),(r:=[0]),(k:=[]),(f:=[list(l)+[" "]*(80-len(l))for l in c.split("\n")]+[[" "]*80]*(40-len(c.split("\n")))),(s:=k.__setitem__),(x:=lambda a:i(p,1,a)),(y:=lambda a:i(p,0,a)),(d:=lambda a:i(r,0,a)),list(iter(lambda:[{"A":lambda:s(-1,k[-1]+ord(f[p[0]-1][p[1]])),"a":lambda:s(-1,k[-1]+ord(f[p[0]+1][p[1]])),"D":lambda:k.pop(),"d":lambda:k.append(k[-1]),"E":lambda:i(f[p[0]-1],p[1],chr(26)),"e":lambda:i(f[p[0]+1],p[1],chr(26)),"F":lambda:i(f[p[0]-1],p[1],chr(k.pop())),"f":lambda:i(f[p[0]+1],p[1],chr(k.pop())),"G":lambda:t(lambda: i(f[p[0]-1],p[1],input()[0]),lambda:i(f[p[0]-1],p[1],chr(26)),EOFError),"g":lambda:t(lambda: i(f[p[0]+1],p[1],input()[0]),lambda:i(f[p[0]+1],p[1],chr(26)),EOFError),"H":lambda:[x(1,p[1]-list(reversed(f[p[0]][0:p[1]])).index(chr(k[-1]))),d(2)],"h":lambda:d(2),"J":lambda:[y(p[0]+[l[0]for l in f[p[0]:]].index(chr(k[-1]))),d(1)],"j":lambda:d(1),"K":lambda:[y(p[0]-list(reversed([l[0]for l in f[0:p[0]]])).index(chr(k[-1]))),d(3)],"k":lambda:d(3),"L":lambda:[x(1,p[1]-f[p[0]][p[1]:].index(chr(k[-1]))),d(0)],"l":lambda:d(0),"P":lambda:print(end=f[p[0]-1][p[1]]),"p":lambda:print(end=f[p[0]+1][p[1]]),"q":lambda:exit(),"R":lambda:s(-1,k[-1]-ord(f[p[0]-1][p[1]])),"r":lambda:s(-1,k[-1]-ord(f[p[0]+1][p[1]])),"S":lambda:k.append(ord(f[p[0]-1][p[1]])),"s":lambda:k.append(ord(f[p[0]+1][p[1]])),"X":lambda:d((r[0]+3)%4)if k[-1]<0 else 0,"x":lambda:d((r[0]+1)%4)if k[-1]<0 else 0,"#":lambda:d(1)if p==[0,0]and f[0,1]== "!"else 0}.get(f[p[0]][p[1]],lambda:[print("[ARGH!]"),exit()])(),[lambda:x(p[1]+1),lambda:y(p[0]+1),lambda:x(p[1]-1),lambda:y(p[0]-1)][r[0]]()],0))]
argh('''j world
lppppppPPPPPPsrfj
hello, * j
qPh''')
@shadow dome :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 | File "<string>", line 1, in <lambda>
005 | File "<string>", line 1, in <lambda>
006 | File "<string>", line 1, in <lambda>
007 | NameError: name 'exit' is not defined
Was bored so here's another esolang interpreter in a lambda: argh-in-a-lambda
https://github.com/rizerphe/argh-in-a-lambda if anyone wants to see the commit history
The most difficult thing here was actually keeping the code <2000chars as I still wanted to post it here
And also apparently the bot doesn't support exit() nor quit() or whatever, and I use those to halt the program
Is there a way to instantly interrupt lambda evaluation without using exceptions or interrupting the whole script? In this case you can use exit()/quit() which has many disadvantages, or raise an exception and catch it - which is pretty elegant but unreadable in a lambda; is there a different way?
What on the actual earth haha
so like return from a lambda?
Pretty much. So that you interrupt the execution, but not stop the whole script
To be clear: I don't care what value gets returned
hmm, maybe using some form of conditional before executing the rest of the script?
(program_continuation_lambda, lambda:0)[boolean_condition]
Won't work in this case
I'm using list(iter(...)) to create an infinite loop with a lambda, and want to simulate break/return
So that one iteration doesn't finish, but everything instantly quits
hmm, raise StopIteration doesn't work?
Well, I think you have to call .throw() or something since raise is a statement
But if you can simulate that, I think it can work
!e
raise_lambda = lambda:(_ for _ in ()).throw(StopIteration)
raise_lambda()
@thin trout :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <genexpr>
003 | StopIteration
004 |
005 | The above exception was the direct cause of the following exception:
006 |
007 | Traceback (most recent call last):
008 | File "<string>", line 2, in <module>
009 | File "<string>", line 1, in <lambda>
010 | RuntimeError: generator raised StopIteration
!e
a = lambda: [(x:=[0], list(iter(lambda: [x.__setitem__(0, x[0]+1), (_ for _ in ()).throw(StopIteration) if x > 100 else None], None))]
a()
Fwiw you can edit your code and press replay
!e
a = lambda: [(x:=[0]), list(iter(lambda: [x.__setitem__(0, x[0]+1), (_ for _ in ()).throw(StopIteration) if x[0] > 100 else None], None))]
a()
@shadow dome :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <genexpr>
003 | StopIteration
004 |
005 | The above exception was the direct cause of the following exception:
006 |
007 | Traceback (most recent call last):
008 | File "<string>", line 2, in <module>
009 | File "<string>", line 1, in <lambda>
010 | File "<string>", line 1, in <lambda>
011 | RuntimeError: generator raised StopIteration
iter(object[, sentinel])```
Return an [iterator](https://docs.python.org/3/glossary.html#term-iterator) object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, *object* must be a collection object which supports the iteration protocol (the [`__iter__()`](https://docs.python.org/3/reference/datamodel.html#object.__iter__ "object.__iter__") method), or it must support the sequence protocol (the [`__getitem__()`](https://docs.python.org/3/reference/datamodel.html#object.__getitem__ "object.__getitem__") method with integer arguments starting at `0`). If it does not support either of those protocols, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") is raised. If the second argument, *sentinel*, is given, then *object* must be a callable object. The iterator created in this case will call *object* with no arguments for each call to its [`__next__()`](https://docs.python.org/3/library/stdtypes.html#iterator.__next__ "iterator.__next__") method; if the value returned is equal to *sentinel*, [`StopIteration`](https://docs.python.org/3/library/exceptions.html#StopIteration "StopIteration") will be raised, otherwise the value will be returned.
wrapping the thing in a itertools.takewhile would help
you could just return a sentinel and have it end the iterable
though that wont work if you are using a list literal for sequential evaluation
This exception is one of the biggest mystery of my life
StopIteration can no longer do that afaik
Wouldn't that complete the iteration? I don't want that
Couldn't you use type() to create a fake object with a __next__ attribute?
yeah, that may be best
__next__ should handle StopIteration
just use a full object instead of iter
I wonder what type is the 2 arg form of iter
So like,
!e py list(iter(type('',(),{"__init__":lambda s:s.x=0"__iter__":lambda s:s,"__next__":(lambda s:(s.x:=s.x+1,print(x)),lambda s:(_ for _ in ()).throw(StopIteration))[s.x>69]})()))
hmm
lemme fix that
!e
a = lambda: [
(try_ := lambda t, *a, f=lambda a:a, e=Exception, **k,:(r:={}).pop(
'r',
type(
'',
(__import__('contextlib').ContextDecorator,),
{
'__enter__':int,
'__exit__':lambda s,*a:isinstance(
a[1], e
) and [r.update(
r=f(a)
)]
}
)()(t)(*a, **k))),
(x:=[0]),
try_(lambda: list(iter(lambda: [x.__setitem__(0, x[0]+1), 1/0 if x[0]>100 else None], None)), f=lambda a: print("Interrupted"), e=ZeroDivisionError)
]
a()
@shadow dome :white_check_mark: Your eval job has completed with return code 0.
Interrupted
The exception method I was talking about
My incremental for x isn't working (probably because of scoping) but this should work
x=0
list(
iter(
type(
'',
(),
{
"__iter__":lambda s:s,
"__next__":(
lambda s:print(x),
lambda s:(_ for _ in ()).throw(StopIteration)
)[(x:=x+1)>10]
}
)()
)
)```
Just wrap x in a list and use setitem
oh I see it now
hmmmm, any idea why this doesn't work? It is still suck in a loop
x=[0]
list(
iter(
type(
'',
(),
{
"__iter__":lambda s:s,
"__next__":lambda s:(
lambda s:(x.__setitem__(0,x[0]+1),print(x[0])),
lambda s:(_ for _ in ()).throw(StopIteration)
)[x[0]>10](s)
}
)()
)
)```
Ah
You aren't calling those 2 lambdas inside
One second
Ah no
Wait, one second
You put the brackets in the wrong place and no, it doesn't work, at least not on my machine - the bot seems to perform differently for some reason
that's weiiiird
!e
a = lambda: [(x:=[0]),
list(
iter(
type(
'',
(),
{
"__iter__":lambda s:s,
"__next__":lambda s:((
lambda s:[(x.__setitem__(0,x[0]+1),print(x[0]))],
lambda s:(_ for _ in ()).throw(StopIteration)
)[x[0]>10](s))
}
)()
)
)]
a()
@shadow dome :x: Your eval job has completed with return code 1.
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/cesovinuxo.txt?noredirect
Ah ok it just truncated
I'm not 100% sure why it is letting the exception propagate
If you do it without lambdas, does the same happen?
!e
list(
iter(
type(
'',
(),
{
"__iter__": lambda s: s,
"__next__": lambda s: (_ for _ in ()).throw(StopIteration)
}
)()
)
)
```that?
@thin trout :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 8, in <genexpr>
003 | StopIteration
004 |
005 | The above exception was the direct cause of the following exception:
006 |
007 | Traceback (most recent call last):
008 | File "<string>", line 1, in <module>
009 | File "<string>", line 8, in <lambda>
010 | RuntimeError: generator raised StopIteration
is it because it is converted to a RuntimeError at some point
!e
list(
iter(
type(
'',
(),
{
"__iter__": lambda s: s,
"__next__": lambda s: exec("raise StopIteration")
}
)()
)
)```
@thin trout :warning: Your eval job has completed with return code 0.
[No output]
Yeah, as soon as I uncomment it it breaks:
def a():
x = [0]
class T:
def __iter__(s): return s
def __next__(s):
if x[0]>10:
# (_ for _ in ()).throw(StopIteration)
raise StopIteration
else:
[(x.__setitem__(0,x[0]+1),print(x[0]))],
list(iter(T()))
a()
@thin trout :warning: Your eval job has completed with return code 0.
[No output]
Hmm you don't see it but it raises StopIteration it seems like
!e
(x := [0], list(
iter(
type(
'',
(),
{
"__iter__": lambda s: s,
"__next__": lambda s: ((
lambda s: (x.__setitem__(0, x[0] + 1), print(x[0])),
lambda s: iter(())
)[x[0] > 10](s))
}
)()
)
))
@thin trout :x: Your eval job timed out or ran out of memory.
001 | 1
002 | 2
003 | 3
004 | 4
005 | 5
006 | 6
007 | 7
008 | 8
009 | 9
010 | 10
011 | 11
Out of memory? Why?
@thin trout :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | StopIteration
Yeah, that works 🥳
Thanks!
!e
a = lambda: [(x:=[0]),
list(
iter(
lambda:((
lambda:[(x.__setitem__(0,x[0]+1),print(x[0]))],
lambda:next(iter(()))
)[x[0]>10]()), None)
)]
a()
@shadow dome :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
!e ```py
list(
type(
'',
(),
{
"x":0,
"iter": lambda s: s,
"next": lambda s: ((
lambda s: (s.setattr("x", s.x + 1), print(s.x)),
lambda s: next(iter(()))
)s.x > 10)
}
)()
)
@snow beacon :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
!e
# Quite a minimal version:
a = lambda: [(x:=[0]),
list(iter(
lambda:[
(x.__setitem__(0,x[0]+1),print(x[0])),
next(iter(()))if x[0]>=10 else None
], None))]
a()
@shadow dome :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
nice
Programming in lambdas resembles jsx. Mainly because you have to put commas everywhere
could you explain, what are you using this r dict from which you are poping elements and how does that work in this
No, not really. That's a piece of code provided by chilaxan, #esoteric-python message , and I didn't really look into how it works
It works for me like this which is much simpler
try_= lambda t,*a,f=lambda a:a,e=Exception,**k,:type(
'',
(__import__('contextlib').ContextDecorator,),
{
'__enter__':int,
'__exit__':lambda s,*a:isinstance(a[1], e) and [f(a)]
}
)()(t)(*a, **k)
Now, back to my old question, how to implement match/case as single (oneline) lambda function
!e
a = lambda x: (list(filter(lambda a: x in a[0],[
[[0,3], lambda: print("Hello, world!")],
[range(10), lambda: print("Till 10")],
[list("abc"), lambda: print("abc")]
]))+[[None,
lambda: print("Else...")
]])[0][1]()
a(0)
a(1)
a(3)
a("a")
a("j")
@shadow dome :white_check_mark: Your eval job has completed with return code 0.
001 | Hello, world!
002 | Till 10
003 | Hello, world!
004 | abc
005 | Else...
@livid hatch Is this good enough?
I'm using a list and not a dictionary to set some kind of hierarchy
And by using the same try_ function you can use things like strings as first items in a pair
!e
it doesn't cover creating stuff like
action=input().split()
direc=["north","west","south","east"]
match action:
case [direction] if direction in direc | ["go", direction] if direction in direc:
print(f"going {direction}")
case ["get", item] | ["pick", "up", item] | ["pick", item, "up"]:
print(f"picking up: {item}")
this will match and also give you matched direction/item for example
not just match
Then the only option is per-situation ig
@livid hatch the r dict allows the result of f to be returned if it is called
it's hella weird that match case requires double indent
but if you wanna apply it in an expression you can always just write a function that does it for you
or ofc use exec and /n
Exec feels like cheating + is a security hazard, so ig nobody uses it
Exec is a cognitohazard
exec is used several times in built ins because it's better than alternatives
exec is only a security hazard if you're letting I/O run exec
and especially in esoteric python nothing is cheating
frankly, ppl who say "there's always a better alternative over exec" know nothing about metaprogramming
is what I've gathered after months trying to determine if they're right
if u wanna do one liner math case without actually using match case's syntax (double indented) u gotta rebuild the pattern matching from scratch
yeah, the standard library uses exec since it is the less error prone option
it's also a cognitohazard
python is a cognito hazard
Cognito ergo hazard. Some cognitohazards are fun.
all experienced python users are susceptible to a snow crash as long as it's a bytes object
is there a way to add \alpha (resolving to unicode α) in python code?
specifically as an identifier
You can just paste it into your code
a more elegant way?
Although that breaks pep3131, but who cares?
As a variable name?
No, I don't think there is
Variable names are meant to be purely internal
So why don't just agree with everyone collaborating that, for example, _alpha_ means alpha?
i was thinking of jupyter notebooks, \alpha works in cells there, but not in code
maybe for code it would need to be some kind of preprocessor
It works in cells because it's markdown iirc
For code - yeah, you are not meant to name your variables that
See pep8 or pep3131 or whatever, I don't remember which exact one
The most you can do is use it in strings
well, most maths doesn't use english names or ASCII, so there's that ^^
!e
print("\u03B1")
@shadow dome :white_check_mark: Your eval job has completed with return code 0.
α
Then you just name your variable "alpha" since maths doesn't use multi-character varnames so there's that
I really don't think there's a way and I don't see how you'd justify adding that either
As for the limited number of uses you can just copy-paste
!e
# Or do this:
exec('''
\u03B1 = 4
print(α)
''')
@shadow dome :white_check_mark: Your eval job has completed with return code 0.
4
there are many instances of variables with multicharacter indexes/specifiers, which is basically a multicharacter varname
however, many times when you look up a maths formula and want to turn it into code, it can get convoluted quickly with names
The thing is, python code isn't meant to be pretty, but easy to understand at most
So it doesn't have any preprocessors or anything, and is saved as a plaintext file
So the most you can do is get an addon for your editor etc. that would do that for you
that might be an idea
from typing import Any;
class Fossilized(type):
def __new__(metatype, name:str, bases:tuple[type, ...], namespace:dict[Any]):
exception = f'''"class '{name}' cannot be subclassed"''';
disabled = lambda prototype: exec(f'raise(Exception({exception}))');
namespace.update({'__init_subclass__': disabled});
return type.__new__(metatype, name, bases, namespace);
def __call__(prototype, *positional:Any, **encyclopedic:Any):
if not (instance := getattr(prototype, ':instance', None)):
instance = super().__call__(*positional, **encyclopedic);
setattr(prototype, ':instance', instance)
return instance;
Thought you guys might find this interesting
A singleton metaclass whose instances can't be subclassed
And yes, I know, semicolons
How to execute command without using exec or eval command also os.system command
like, a shell command?
!e print(0.1+0.2)
@tropic mountain :white_check_mark: Your eval job has completed with return code 0.
0.30000000000000004
yes
If anyone is wondering, this is a rounding error. Both 0.1 and 0.2 are actually infinitely long sequences of digits in base-2, that's why
The proper way to execute system commands is probably subprocess.Popen - though it's essentially the same thing as os.system, and I don't think there's a different way
subprocess.call is the easiest option generally
no no I am not looking for easiest option I am looking for something unsual shell execution
do you need it to be cross platform?
There's literally no way to do it without importing anything
only windows
something like can I do like this
copy cmd.exe and include in my python project
but can I compile many python + exe files together
No, literally no way
not really, that is still part of what you use subprocess
can I include C in my python for execute system commands ?
you could write a C library that would execute system commands, yes
okey so
when I compile the python program exe file I will be executing
but assembly code still same all the time
I want to change it any time for execution
every time I execute the program I want all assembly codes be changing
that is a thing you will want to use C for, python isn't going to do much for that
positional and encycopedic WHAT THE FUCK IS YOUR NAMING?!?????
A singleton class should not accept any parameters.
Does anyone know why overwriting the NodeTransformer visit_FunctionDef method does not visit nested function definitions?
Nevermind, I guess generic_visit() is needed? That fixed it
Why you need to copy cmd when it's available in whole system if it's in windows folder?
I take more issue with the semicolons.
unnecessary semicolons are fun
For bypass antivirus
O_o scawy
Btw just so you know python, as an interpreted language, is pretty much the worst choice for making viruses 👀
||I use arch btw||
you think that's bad?
alright I will now show you what bad naming really looks like
O_o esoteric, spicy
!e ```py
_00 = import('collections').defaultdict
_01 = chr,ord
02 = int;=_02()==_02()
_03 = str,len
_04 = lambda _0:print (end=_01-)
_05:02 = <<((0x00for x in 06.cell_size)//(<<)+)
06:03[-] = """++++++++++[
>+++>+++++++>++++++++>++++++++++>+++++++++++
<<<<<-
]>>++.-->>+.+++++++..-------->+.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++."""
def _07(0):
1=_00 (_02)
2=3=4=_02()
def _0(_0):
1[0]+=
1[_0]%=_05
return _0,_02()
def _1(_0):
1[0]-=
1[_0]%=_05
_2 = lambda _0:(0-,_02())
_3 = lambda _0:(0+,_02())
def _4(_0):
_04(1[_0])
return _0,_02()
def _5(_0):
_1 = import('sys').stdin
_2 = _1.read
_3 = 2()
1[_0] = _3
return _0,_02()
def _6(_0):
_1 =+ (not 1[_0])
return _0,_1
def _7(_0):
_1 =- (not not 1[_0])
return _0,1
5 = '[',']'
while 03_>3>02():
6 = {'+':0,'-':1,'<':2,'>':3,'.':4,',':5,5[-]:6,5[]:7}
if 0[3] not in 6:continue
7 = 6[0[3]]
if 4:
if 0[3]==6[] :4-=
elif 0[3]==6[-]:4+=
else: 2,4 = 7(2)
3+=-(<<)*(4<_02())
_07(_06)
Kewl naming, I like it
if the naming is good, what's the bug?
XD
In _5, what's the value of _?
hagn on i think i found it
Is _ supposed to be 1? Because it seems like it is 0
Edit: no, I'm dumb
What does _1 return?
@floral meteor :x: Your eval job has completed with return code 143 (SIGTERM).
++++++++++[
well i got the location of the issue narrowed down
print(end=chr(_1_[_0])), no?
_04 = lambda _0:print(end=chr(_0))
What’s esoteric python?
replacing readability with fun
See the description of the channel. Basically anything that's useless but cool
not useless: used as a higher form of torture
lmfao i figured it out
well you're not helping
!e ```py
_00 = import('collections').defaultdict
_01 = chr,ord
02 = int;=_02()==_02()
_03 = len
_04 = lambda _0:print (end=_01-)
_05:02 = <<((0x00for x in 06.cell_size)//(<<)+)
_06 = """++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++."""
def _07(0):
1=_00 (_02)
2=3=4=_02()
def _0(_0):
1[0]+=
1[_0]%=_05
return _0,_02()
def _1(_0):
1[0]-=
1[_0]%=_05
return _0,_02()
2 = lambda 0:(0-,-)
3 = lambda 0:(0--,-)
def _4(_0):
_04(1[_0])
return _0,_02()
def _5(_0):
_1 = import('sys').stdin
_2 = _1.read
_3 = 2()
1[_0] = _01_
return _0,_02()
def _6(_0):
_1 =+ (not 1[_0])
return _0,_1
def _7(_0):
_1 =- (not not 1[_0])
return _0,1
5 = '[',']'
while 03(0)>3>=02():
6 = {'+':0,'-':1,'<':2,'>':3,'.':4,',':5,5[-]:6,5[]:7}
if 0[3]in 6:
7 = 6[0[3]]
if 4:
if 0[3]==5[] :4-=
elif 0[3]==5[-]:4+=
else: 2,4 = 7(2)
3+=-(<<)*(4<_02())
_07(_06)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
!e ```bf
#[
a,i=import ('collections').defaultdict(int),int()
BITS=((int()**int())<<(int()**int()))<<((int()**int())+(int()**int())+(int()**int()))
def add(*s):
a[i<<int()]+=(int()**int())<<int()
a[i>>int()]%=((int()**int())<<(int()**int()))**BITS
return s[int()]
pos=add
def sub(*s):
a[i<<int()]-=(int()**int())<<int()
a[i>>int()]%=((int()**int())<<(int()**int()))**BITS
return s[int()]
neg=sub
def lt(*s):globals()['i']-=(int()**int())<<int();return s[int()]
def gt(*s):globals()['i']+=(int()**int())<<int();return s[int()]
def lshift(*s):return lt(*s)<int()<<int()
def rshift(*s):return gt(*s)>int()>>int()
def getattr(s,o):
try:return object.getattr(s,o)
except:import('sys').stdout.write(chr(a[i<<int()]>>int()));return s
def call(self,f,a):
if a:a[i>>int()]=ord((f or import('sys').stdin).read(len(a)<<int()))
return self
bool=lambdas:not int()
def getitem(s,item):
while a[i>>int()]:(v:=item()if hasattr(item,'call')else+s if item>=int()else-s).class is int and(v<int()and-s or+s)
return s
=type("brainfucker",(int,),globals())(int())
#]
(+++++++)[lambda:>_ and +++++++ and < and -]>_ and +++++ and(.+++_).int(int())
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
@shadow dome "polyglot"
now make it a quine
whats some esoteric code I can do with match statements now?
match match:
case case if case:
case(case)
case case(case=case) as case:
case[case]
```try to make this run. (I hope the syntax is right, been a while)
is that brain fuck..
hmph
i can write esoteric code as well!
!e
esoteric = True
if esoteric == True:
print('This is real esoteric code ya nubs')
@sick hound :white_check_mark: Your eval job has completed with return code 0.
This is real esoteric code ya nubs
how can I stream video using thread
!e
esoteric = True if True == True else True or False;
if esoteric == (lambda x: True)(False):
print('This is real esoteric code ya nubs' *
sum([1, 2, 3, 4, 5, -5, -4, -3, -2]), sep=' ', end='\n')
@steel vector :white_check_mark: Your eval job has completed with return code 0.
This is real esoteric code ya nubs
smh
smhsmh
That's esoteric?
wtf am i reading
how does this work??
Is that meant to be a bf-python polyglot?
don't really know sorry
i just thought it was redundant code and stuff
Lol
Not mine:
793 lines when hit with the
stick 
oh god
You have a whole image encoded in there smh
Not mine:
lmao
10/10 
can you make anything in one line with semicolons?
or do blocks like if and for need to have a newline
semicolons end the line
so u could do print("1");print("2")
if and for need to have an indentation
unless it’s ternary
or list comp
so semicolons don’t make everything oneline, but most things can be used one line
oh i haven’t learned generators
idk what they are
[print(i) for i in range(10) if i%2==0]```or```py
print("\n".join(str(i) for i in range(10) if i%2==0))```if you don't want the `[None, None, None...]` return value
Generators are just inline for loops basically
ok 👌
Anything that yields If I remember correctly
Kinda yea
k
If you wanna read more: https://realpython.com/introduction-to-python-generators/
What do you guys think of Python 3.10s new way of making union typehint
def function(arg: int) -> Union[int, str]:
return arg```
to 3.10: ```py
def function(arg: int) -> int | str:
return arg```
Much nicer, but will take some getting used to; my brain sees the int and then stops
Hi So I’ve the code and some feedback which I need to make changes accordingly I’ve tried to do it but I still have some trouble can anyone please help
So this is feedback + broken code
So I need help in fixing this can someone pls help me
not here, no, look at #❓|how-to-get-help
Python on esoteric hardware and operating systems 🙂 so cool
You can do while cond: statement and the like on one line. It can't have more colons though.
I'd like to someday implement a Python bytecode interpreter in the Pickle format.
so it runs when unpickled?
working on a lil obfuscator using the new match statements
import builtins as bb
b= {'tnirp':'tnirp'[::-1]}
def JngEtxMSpM(SZMQTkwJir):
while SZMQTkwJir:
match(SZMQTkwJir.pop()):
case "TNYAjekzsg":
getattr(bb, b['tnirp'])(type(a))
case "xLVopiwujA":
getattr(bb, b['tnirp'])("testing")
case "MgKpNuQlvI":
a = 9+True
case "uwWPjqavAp":
a = str(5-False)
case "nYHiGoDXho":
getattr(bb, b['tnirp'])(a)
def kVwpILQWyf(bvhOvtJCkr):
while bvhOvtJCkr:
match(bvhOvtJCkr.pop()):
case "bXCZuCCypf":
b['xLVopiwujA'] = (lambda MgKpNuQlvI: b['nYHiGoDXho'](MgKpNuQlvI))
case "DiaLnWXzOi":
b['nYHiGoDXho'] = JngEtxMSpM
case "nytSnDenNB":
b['xLVopiwujA']("TNYAjekzsg|uwWPjqavAp|nYHiGoDXho|MgKpNuQlvI|xLVopiwujA".split('|'))
case "PVkvaLYNQT": ...
kVwpILQWyf("PVkvaLYNQT|nytSnDenNB|BhLzRWOGwf|bXCZuCCypf|DiaLnWXzOi".split("|"))
I haven't checked how feasible it would be, but that's the goal.
how does one set the module attribute of a built in class with a property?
ive tried using ctypes.pythonapi.PyDict_SetItem but that didnt work as cls.dict is a mappingproxy
and PyObject_SetAttr doesnt work either
a bit of info im trying to set the module attr of something and make it be different if the caller is a specific file
The largest issue I think you'd have is lack of control of the instruction pointer
Now fit it on one line
you can do anything on one line
"lets see what esoteric python is up to- oh god"
please god no
my goal is to have atleast 300 lines to print hello world
with multiple layers of match statements
lol
i do have one small complaint about best practice, although thats utterly redundant here
I mean im just trying to recreate a very popular obfuscator thats in Javascript
into python
although the source isnt public
with the match statements I should be able to replicate all of their methods
already got that much down from reversing it
pain
is there a way to import a module without using "import" ?
__import__
does switch stop on a matching case or does it evaluate all matching cases?
cos I made a full switch suite here long before match was cool ;)
eh imo match was never cool
switch-case is not cool
pattern matching is cool
sup
That depends on the language. Python match stops on a matching case.
!e ```py
class apply(metaclass=lambda*a:type(*a)()):
def call(self, wrapper, source=None, index=None):
if source is None and index is not None:
return self(wrapper,import('sys')._getframe(1).f_globals,index)
elif source is None:
return type("starred-apply",(),dict(
mul=lambda s,o:self(wrapper,*o),
call=lambda s,o:so),
setattr=lambda s,k,source:setattr(source,k,wrapper(getattr(source,k))))()
elif index is None:
return type("attr-apply"),(),dict(
mul=lambda s,o:setattr(source,o,wrapper(*getattr(source,o))),
getattribute=lambda s,k:setattr(source,k,wrapper(getattr(source,k))),
setattr=lambda s,k,v:setattr(source,k,wrapper(v)))()
else:source[index] = wrapper(source[index]);return source[index];
def mul(self,args:tuple):
if type(args)is list:
raise TypeError("Starred function is not subscriptable.")
wrapper, *others = args
star_wrapper = lambda a:wrapper(*a)
return self(star_wrapper,*others)
a = b = ("this",(),{'a':4})
apply*(type,globals(),'a')
assert type(b)is tuple and type(a)is not tuple
apply(lambda c:c(),index='a')
s = apply(str)
s(a).a
s(a).b = 27
assert int(a.a+a.b)>int(a.a)+int(a.b)
apply(print,index='b')
assert b is None
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 27, in <module>
003 | File "<string>", line 6, in __call__
004 | TypeError: starred-apply.__init_subclass__() takes no keyword arguments
pattern matching is weird just cuz it's got a mini lang specific to one single set of keywords that require double indents
but it still kinda seems necessary to me
I wish single boolean matches with capture were usable as expressions tho for example
It has to start somewhere.
true
so any clue how to make this work?
a = b = ("this",(),{'a':4})
apply*(type,globals(),'a')
assert type(b)is tuple and type(a)is not tuple
apply(lambda c:c(),index='a')
s = apply(str)
s(a).a
s(a).b = 27
assert int(a.a + a.b) > int(a.a) + int(a.b)
apply(print,index='b')
assert b is None
b = [1, 4, 3]
apply(lambda n:n//2,b,1)
assert b==[*range(4)][1:]
just cos the magic line source[index] = wrapper(source[index]) I hate so much i'd rather use a function like the above
note apply is not a function, it is an object, that pretends like apply* is the name of another function
never done FizzBuzz before, how'd I do?
print(*[('FizzBuzz' if (n % 3 == 0) and (n % 5 == 0) else ('Fizz' if n % 3 == 0 else 'Buzz')) if any([(n % 3 == 0), (n % 5 == 0)]) else n for n in range(1, 101)], sep='\n')```
for i in range(1,101):print(i%3//2*"Fizz"+i%5//4*"Buzz"or-~i)```is the shortest that has been done iirc (61 chars)
But in terms of readability + one-liner that looks good
Way more readable than the short one lol
('Fizz' if n % 3 == 0 else 'Buzz')) if any([(n % 3 == 0), (n % 5 == 0)]) else n```keeping the same spacing, could be shortened to```py
'Fizz' if n % 3 == 0 else 'Buzz' if n % 5 == 0 else n```(no need for the `any`)
print((''.join((chr(ord(i)+1) if i in 'abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXY' else chr(ord(i)-25) if i in 'zZ' else i for i in input('> ')) if (x := input('(d)ecode/(e)ncode: ')[0].lower()) == 'd' else (chr(ord(i)-1) if i in 'bcdefghijklmnopqrstuvwxyzBCDEFGHIJKLMNOPQRSTUVWXYZ' else chr(ord(i)+25) if i in 'aA' else i for i in input('> ')) if x == 'e' else 'bruh wrong option')).swapcase()[::-1])
what do you guys think
lol
getattr(__import__(True.__class__.__name__[1] + [].__class__.__name__[2]), ().__class__.__eq__.__class__.__name__[:2] + ().__iter__().__class__.__name__[1:][5:8])(1, bytes((lambda __ : "".join([chr(int(_, 2)) for _ in __.split()])) ((lambda _: getattr(__import__(print.__class__.__name__[18] + print.__class__.__name__[21]), 'sub')(r'(.{8})(?!$)', r'\1 ', _) ) ((lambda _: '0' + str(_[1]))((lambda _, __, ___: (_ * 1 << 1, __ >> 5, ___ * 5918))(48514, 3523200035203232352352003523520035235552, 124921)))), encoding=''.join(chr(i) for i in [117, 116, 102, 56])))```
oh my god thats amazing
i know its a ceasar but its a beautiful one
hello5?
its hello, just put in in a script.py
it python.exe it prints the bytes length of hello
>>> getattr(__import__(True.__class__.__name__[1] + [].__class__.__name__[2]), ().__class__.__eq__.__class__.__name__[:2] + ().__iter__().__class__.__name__[1:][5:8])(1, bytes((lambda __ : "".join([chr(int(_, 2)) for _ in __.split()])) ((lambda _: getattr(__import__(print.__class__.__name__[18] + print.__class__.__name__[21]), 'sub')(r'(.{8})(?!$)', r'\1 ', _) ) ((lambda _: '0' + str(_[1]))((lambda _, __, ___: (_ * 1 << 1, __ >> 5, ___ * 5918))(48514, 3523200035203232352352003523520035235552, 124921)))), encoding=''.join(chr(i) for i in [117, 116, 102, 56])))
hello5
python 3.8.5
ohh in a .py it works different? spicy
already told you you need to run in a script.py
yea
its because it prints hello and the bytes of hello 5
in script it doesnt
this reminds my of cout, i always forget endl and wind up with my prompt on the end lol.
prompt_here$ python3 playground.py
helloprompt_here$
very impressive obfuscation nonetheless
yea lol
I have made some more similar ones
how did you get into making stuff like this? i wouldnt know where to begin
find what to do
and just extend
its not that hard
decrypt__it = 'but you are total trashes'
____ = decrypt__it.split(' ')
getattr(__import__(True.__class__.__name__[1] + [].__class__.__name__[2]), 'wr' + (quit.__class__.__name__).replace('tt', 't')[2:5])(1, eval(____[0][0] + ____[1][0] + ____[3][0] + ____[4][5:]) (''.join(chr(i) for i in (lambda __: [int(i) for i in __])((lambda _: _.split('0xf'))('720xf1010xf1080xf1080xf1110xf320xf870xf1110xf1140xf1080xf1000xf330xf10'))), 'ascii'))```
just
its simple
you start from os.write('Hello World!/n')
then I convert it to
thanks
getattr(__import__('os'), 'write')(1, bytes('Hello World!\n', encoding='ascii'))
oh i see, you start with normal code and bit by bit make it increasingly obscure. that makes it a lot easier
hmm string argument without enconding
always forget it
here
u know what imma just make an extremely huge one to print hello world
how to improve this
encrypt strings
yea encrypt strings
^
like this one
how will that make it shorter
so for functions from modules you can getattr(__inport__("module"), "func")(), is there such a thing for bytes() str() etc?
but ti has to be 1 line
yea
hmm not sure lemme check
alright thank you
technically?
well what you do
is get the attributes of a function
and use its functions under it
i could just do ```py
''.join(chr(ord(i)-1) for i in input('> '))
hello
'gdkkn'
''.join(chr(ord(i)+1) for i in input('> '))
gdkkn
'hello'
but then it wouldnt be as good
sometimes itl give an error
i feel like im not doing things right, but i guess thats part of the point. heres my first attempt at doing this stuff
getattr(__import__("os"), "write")(1, getattr(__import__("builtins"), "bytes")(getattr(__import__("builtins"), "str")({x: y for x, y in getattr(__import__("builtins"), "zip")(getattr(__import__("builtins"), "range")(10), [_ for _ in getattr(__import__("builtins"), "list")("0123456789")])}), encoding="ascii"))
perfect
is there a dedicated channel to pyopengl or can i show my issue here?
Discord's syntax highlighting doesn't even recognize my hello world ):
Is there a character limit for syntax highlighting?
No
I'm putting it in the triple back ticks with py
Yeah I'm not sure either
Maybe I beat Discord's parser?
I think it's a bug with Discord though actually. The code runs and other editors are handling the highlighting just fine
Hm
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
Based on this, highlight.js works fine so idk
@slim sonnet what's the hello world look like?
Like this
I just got a little inspiration from you guys
Don't hurt me
It's nice until you start having a lot of them haha I got up to 14
I would have lost my mind without suggestions
Definitely
Any ast module gurus? I'm replacing an ast node with another and it is pretty long. But it's adding a new line when I unparse the tree that results in an error that I have to manually fix before I can run the code
Never mind, I am just ding dong
No, I'm not ding dong. It's still doing it
All python obfuscation can be broken
Even things that rely on fetching data from servers can be spoofed pretty easily since python is interpreted
oh
challenge: make a program that rickrolls someone as complicated as possible
I made one but not complicated
At one point I set up a server that displayed an innocent page, posted a link to it on discord => the preview was generated, then I changed the server code to use a redirect. Even if you had no js and stuff it'd still rickroll you while having an innocent preview on discord
