#esoteric-python
1 messages · Page 106 of 1
ahhh welp tysm
for x in range(1,101):print(*[i for i in range(1,x+1)if x%i==0])``` this also makes it another character shorter
ohhh ty!
i'm assuming people who scored lower than that would have used a different method
but i'll try another problem now
thank you 🙂
when normal seed isn't enough
think im gonna make a hello world just from zero
(
(lambda _: (
print(_.__invert__().__abs__())
))(
__import__("__main__").__doc__.__bool__().__int__())
)```
!e (
(lambda : (
print(.invert().abs())
))(
import("main").doc.bool().int())
)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1
how did you learn to make this
by stalking this channel for months on end and learning dunders
almost have one letter!
out of all of these..
uh
i cant send my code
not sure why it gives me that but i now have one letter!
what.
lmao
lemme try to compress it and send
!e
(lambda _,__,___:__.stdout.write(___(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__())))))))))))).__mul__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__()))))))).__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__().__add__(_.__invert__().__abs__())))))))(__import__('__main__').__doc__.__bool__().__int__(),__import__('sys'),chr)
@toxic jewel :white_check_mark: Your eval job has completed with return code 0.
_
Instead of x%i==0 you can often get away with x%i<1 or even 1^x%i
Wait no, xor doesn't work here, but the less than 1 should
!e t```py
____ = 100
print(chr(.add(import("math").sqrt().int()).add(import("math").sqrt().int().sub([].len().bool().str().len().sub([].len().bool().str().len())).sub([].len().bool().str().len().sub([].len().bool().str().len())).sub([].len().bool().str().len().sub([].len().bool().str().len())).sub([].len().bool().str().len().sub([____].len().bool().str().len())))))
@terse mortar :white_check_mark: Your eval job has completed with return code 0.
t
its finished
1k+ lines
that can all be condensed to one
which is shown here: https://mystb.in/RatingsSessionsSlots.lisp
How many fucking characters is it lol
Pog
it could definitely hit 100k chars if i didnt use lambda
thats what it says
theres alot of room for length improvement
i also used .__mul__ because i'm lazy
cant remember who i took this from but it's not mine
def ___(n):
_,__ = 0,1
while _ < n:
yield _
_,__ = __,_+__
for _ in ___(20):
print(_)
!e def (n):
, = 0,1
while _ < n:
yield _
, = __,+__
for _ in __(20):
print()
@bronze anvil :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 1
004 | 2
005 | 3
006 | 5
007 | 8
008 | 13
@bronze anvil
That can be done in one line
Inside the print expression
yeah
Don't make me do it, I'll do unholy things to python that will traumatise you for life
yes please
(lambda _, __, ___, ____, _____, ______, _______, ________:getattr(__import__(True.__class__.__name__[_] + [].__class__.__name__[__]),().__class__.__eq__.__class__.__name__[:__] +().__iter__().__class__.__name__[_:][_____:________])(_, (lambda _, __, ___: _(_, __, ___))(lambda _, __, ___:bytes([___ % __]) + _(_, __, ___ // __) if ___ else(lambda: _).__code__.co_lnotab,_ << ________,(((_____ << ____) + _) << ((___ << _____) - ___)) + (((((___ << __)- _) << ___) + _) << ((_____ << ____) + (_ << _))) + (((_______ <<__) - _) << (((((_ << ___) + _)) << ___) + (_ << _))) + (((_______<< ___) + _) << ((_ << ______) + _)) + (((_______ << ____) - _) <<((_______ << ___))) + (((_ << ____) - _) << ((((___ << __) + _) <<__) - _)) - (_______ << ((((___ << __) - _) << __) + _)) + (_______<< (((((_ << ___) + _)) << __))) - ((((((_ << ___) + _)) << __) +_) << ((((___ << __) + _) << _))) + (((_______ << __) - _) <<(((((_ << ___) + _)) << _))) + (((___ << ___) + _) << ((_____ <<_))) + (_____ << ______) + (_ << ___))))(*(lambda _, __, ___: _(_, __, ___))((lambda _, __, ___:[__(___[(lambda: _).__code__.co_nlocals])] +_(_, __, ___[(lambda _: _).__code__.co_nlocals:]) if ___ else []),lambda _: _.__code__.co_argcount,(lambda _: _,lambda _, __: _,lambda _, __, ___: _,lambda _, __, ___, ____: _,lambda _, __, ___, ____, _____: _,lambda _, __, ___, ____, _____, ______: _,lambda _, __, ___, ____, _____, ______, _______: _,lambda _, __, ___, ____, _____, ______, _______, ________: _)))
!e ```py
[(:=[]==[]),(__:=[~-,^-,lambda ,,:[[.extend([[],.pop(_)+.pop(~-),__.pop(~-)])]and [~-_]for ____ in iter(lambda:[~-]<,not )]]),....class.class('%c'%(+),(),{'':print,'le':lambda ,__:.(*__)})()][-]<=__-~_
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041
@bronze anvil @sick hound there you go
!e und here's ein modifikaschun:
fib=lambda ___:[(_:=[]==[]),(__:=[~-_,_^_-_,lambda _,__,___:[[__.extend([__[_],__.pop(_)+__.pop(~-_),__.pop(~-_)])]and __[~-_]for ____ in iter(lambda:__[~-_]<___,not _)]]),....__class__.__class__('%c'%(_+_),(),{'_':print,'__le__':lambda _,__:_._(*__,sep=chr(10))})()][-_]<=__[-~_](_,__,___)
#===
fib(20)
can you go on an interview and write that as the interview answer when they ask you for fibonachi
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 1
003 | 2
004 | 3
005 | 5
006 | 8
007 | 13
008 | 21
well that's fibonacci numbers up to a certain value but if you wanted n terms instead....
!e und here's ein modifikaschun:
fib=lambda ___:[(_:=[]==[]),(__:=[~-_,_^_-_,lambda _,__,___:[[__.extend([__[_],__.pop(_)+__.pop(~-_),__.pop(~-_)]),(___:=___-_)]and __[_]-__[~-_]for ____ in iter(lambda:___,_-_)]]),....__class__.__class__('%c'%(_+_),(),{'_':print,'__le__':lambda _,__:_._(*__,sep=chr(10))})()][-_]<=__[-~_](_,__,___)
#===
fib(8)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 1
004 | 2
005 | 3
006 | 5
007 | 8
008 | 13
there it's now correct
it didn't have zero before
alrighty then so you want me to explain the workings of this monstrosity?
yes please
def ___(n):
_,__ = 0,1
while _ < n:
yield _
_,__ = __,_+__
for _ in ___(20):
print(_)
Is how it works.
jk
fib=lambda ___:[(_:=[]==[]),(__:=[~-_,_^_-_,lambda _,__,___:[[__.extend([__[_],__.pop(_)+__.pop(~-_),__.pop(~-_)]),(___:=___-_)]and __[_]-__[~-_]for ____ in iter(lambda:___,_-_)]]),....__class__.__class__('%c'%(_+_),(),{'_':print,'__le__':lambda _,__:_._(*__,sep=chr(10))})()][-_]<=__[-~_](_,__,___)
fib= that's assigning to a variable. the variable is called fib and this is what we call on later with the desired number n terms of fibonacci.
lambda ___: makes a function, with one input to LOAD_FAST
also overrides any ___ in locals() / globals() but doesn't override any other variables
[ start a list.
(_:=[]==[]) initialise the value of _ at True
(__:=[ use another walrus operator and start another nested list
assigning such to __
~-_ invert negative True = 0
_^_-_ :: 1 xor (1 - 1) = 1
lambda _,__,___:three input variable function
[ begin list comprehension
[ begin another list
__.extend( ... ) make __ longer
[__[_],__.pop(_)+__.pop(~-_),__.pop(~-_)] another list.
__[_] the zeroeth element
__.pop(_) get rid of the 1th element and return
+__.pop(~-_) add the return of getting rid of the 0th element
__.pop(~-_) move the now 0th element back to its original position
quick question
(___:=___-_)] finish the list of evaluation with decrementing the input stack
why the fuck is pytorch so hard
hol up im still going
thank u
and __[_]-__[~-_] forget the previous list and return the previous iteration
It's supposed to be easy for the machine to learn, not you
lmao
hence machine learning
for ____ in iter iterate.
(lambda:___,_-_) only stop iterating if ___ evaluates to 0
hence the counter decrements to 0
]]), end most of the fuckload of lists and listcomprehension, except for one
....__class__.__class__('%c'%(_+_),(), create a class called 0x02 with no inheritance.
{'_':print, set the _ attribute to print
'__le__':lambda _,__:_._(*__,sep=chr(10)) set the <= behaviour to a function
lambda _,__: self, args
_._ print
*__, expand list as args
sep=chr(10) newline separate args
})() end class definition and create an instance of it, with the property that object : 0x02 <= s : List(str) will print the list of strings with newline separation
][-_] end our list comprehension suffering and return the last value evaluated in it
<= call the __le__ method of this value
__[-~_](_,__,___) get the second element of __ and call it with (True, self, input)
and that's the end of the function
I call it with 8, 8 goes to input, hence it evaluates 8 iterations of yielding fibonacci terms and prints them newline separated
any questions?
>>> @optimize
... def test():
... x = []
... x.append(1)
... x.extend([2,3,4])
... return x
...
>>> test()
[1, 2, 3, 4]
>>> dis.dis(test)
3 0 BUILD_LIST 0
2 STORE_FAST 0 (x)
4 4 LOAD_FAST 0 (x)
6 NOP
8 LOAD_CONST 1 (1)
10 LIST_APPEND 1
12 POP_TOP
5 14 LOAD_FAST 0 (x)
16 NOP
18 BUILD_LIST 0
20 LOAD_CONST 2 ((2, 3, 4))
22 LIST_EXTEND 1
24 LIST_EXTEND 1
26 POP_TOP
6 28 LOAD_FAST 0 (x)
30 RETURN_VALUE
>>> ``` wrote some code that tries to infer a variables type, and if it can it optimizes the bytecode to use the direct opcodes for stuff like `list.append`
it works for the following methods
set.add, SET_ADD
set.update, SET_UPDATE
list.append, LIST_APPEND
list.extend, LIST_EXTEND
dict.update, DICT_UPDATE
cool
thank you very much
ur welcome
Does overload abuse fit?
from typing import *
@overload
def frobnicate(n: Literal[0]) -> Literal[1]: ...
@overload
def frobnicate(n: Literal[1]) -> Literal[2]: ...
@overload
def frobnicate(n: Literal[2]) -> Literal[3]: ...
# ...
def frobnicate(n: int) -> int:
return n + 1
!e (lambda , , , ____, , , ______, ________:getattr(import(True.class.name[] + [].class.name[]),().class.eq.class.name[:] +().iter().class.name[:][:__])(, (lambda _, __, : (, __, ))(lambda , __, :bytes([ % __]) + (, __, ___ // __) if ___ else(lambda: ).code.co_lnotab, << ___,((( << ) + ) << (( << ) - )) + ((((( << )- ) << ) + ) << (( << ) + ( << ))) + ((( <<) - ) << ((((( << ) + )) << ) + ( << ))) + (((<< ) + ) << (( << ) + )) + ((( << ) - ) <<(( << ))) + ((( << ) - ) << (((( << ) + _) <<) - )) - ( << (((( << __) - ) << __) + )) + (<< ((((( << ) + )) << ))) - (((((( << ) + )) << __) +) << (((( << ) + ) << ))) + ((( << ) - ) <<((((( << ) + )) << ))) + ((( << ) + ) << (( <<))) + ( << _____) + ( << ___))))(*(lambda _, __, ___: (, __, ___))((lambda , , :[([(lambda: ).code.co_nlocals])] +(, __, ___[(lambda _: _).code.co_nlocals:]) if ___ else []),lambda _: _.code.co_argcount,(lambda _: _,lambda _, __: _,lambda _, __, ___: _,lambda _, __, ___, ____: _,lambda _, __, ___, ____, _____: _,lambda _, __, ___, ____, _____, ______: _,lambda _, __, ___, ____, _____, ______, _______: _,lambda _, __, ___, ____, _____, ______, _______, ________: _)))
@bronze anvil :white_check_mark: Your eval job has completed with return code 0.
Hello world!
lol
divisors!
ty! i later found the <1 by myself haha but it's a really nice tip
python malbolge interpreter in 1 line :)
not really bullshit
it has good irl use
lambda still tops it tho imo
(lambda t: print(f"{t} is your name.")(input("What is your name?")
heres a thingy i made
while 1: (
(lambda o: (
(lambda d: (
(lambda i: (
d.get(i)() if i in d else print("Invalid command.")
))(input("root@localhost $ ")) # Input
))({"clear": lambda: o.system("cls")if o.name == "nt"else o.system("clear")}) # Dict
))(__import__("os")) # OS
)
why use := when you can use a comprehension

@toxic jewel p is the whole input, so p[1] is the second character of 'echo e'
you could do on line 13
)(*input('root... ').split())
``` and then actually use the `*a` you take in the lambda starting at line 8
while 1:(lambda o,s,t:(lambda d:(lambda i,*a:d.get(i)(*a)if(i)in(d)else(print(f'Command "{i}" Not Found.')))(*input(f'{t["config"]["name"].lower()}@{t["config"]["host"]}: ').split()))({'clear':lambda:o.system('cls')if(o.name)==('nt')else(o.system('clear')),'exit':lambda:s.exit('Process Killed Successfully.'),'echo':lambda *a:print(*a)}))(__import__('os'),__import__('sys'), (__import__("toml").loads(open("config.toml").read())))
config.toml is just hostname
and with no walrus 😎
Lambdas are bad
(lambda a:print(a))(1)
[print(a)for a in(1,)]
fair enough
I open this channel and now i feel like I'm home...
alright challenge for y'all:
make something that's readable for the wrong reasons
but you lose points for anything that's readable for the right reasons
obligatory warning to not run the above code
Care to explain what this does?
I'm not going to run it, but python can't actually "rm -rf /" without sudo, right?
I assume that either it does nothing because of some short-circuit evaluation that I am not seeing, or it attempts to delete your hard drive then exits
sudo python3
😳
That's why I don't sudo python unless it is my code... Or I am in a chroot on a temporary device
That's not to say I don't run plenty of code I shouldn't, just that I don't use sudo
Actually it attempts to wipe hard drive but exits if it fails
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Imma make an anti-zen
and it will perfectly describe the code posted here
**The AntiZen of Python, not by Tim Peters.**
Beautiful is worse than ugly.
Implicit is better than explicit.
Complex is better than simple.
Complicated is better than complex.
Nested is better than flat.
Dense is better than sparse.
Readability sucks.
Special cases should break the rules.
Although purity beats practicality.
Errors should be silenced.
In the face of ambiguity, guess.
There should be many-- and preferably more than one --obvious way to do it.
Although none of them might be obvious at first, especially if you're Dutch.
Now is worse than never.
Although *right* now is better than procrastinating.
If the implementation is hard to explain, you're on the right track.
If the implementation is easy to explain, you're doing something wrong.
Namespaces are a terrible idea -- try not to do any of those!
Can we please not post malicious code that people may accidentally run?
Or at least take the responsibility of properly caveating the code snippet itself.
Letting evil code float around without adequate warning in the very same message is not cool.
Instead, can we all set up a bot to automatically fetch and execute all code blocks posted in this channel? Preferably in the same installation as your discord client.
alright it has been exterminated
**The Stress of Esoteric Python, by IFcoltransG**
Ugliness is not worse than or equal to beautiful-ness.
Implicit...
Complex things and the idea of complexity itself is seen as more pleasant and/or useful than simplicity in of itself, and by extension simple things, as if anyone would actually consider simple things good, by some unspecified people or person.
Some things are nested (and those things exist (in a manner better than flat ones)).
Dense-is-better-than-sparse.
Eadabilityway isway otnay atthay eatgray.
*Everything is special, especially special cases, enough to warrant breaking the rules.*
Though when in doubt, make it unnecessarily abstract.
Errors? Never heard of 'em.
Maybe in the face of ambiguity, keep them guessing.
There should be many++ or preferably zero ++ways to do it.
Though we're rather cosmopolitan here, so your nationality shouldn't impact your ability to programme.
But not never, because things have to happen.
If the implementation is hard to explain, it's inherently good.
If the implementation is easy to explain, you'd better be sure it's worth it.
Namespaces $namespaces __namespaces__ NameSpaces.
Maybe later.
wiped from hardrive, as you will
alright I'll abstract the example for the 'readable for the wrong reasons ' challenge
!e ```py
not_snekbox_compatible="""
from os import system as sys
from things_to_do.tasks import shell_commands as a
"""
#snekbox substitution
sys=lambda a:0
a=["do this", "do that", "do the other thing"]
#continue
error = debug; command,successfully,executed=('command','successfully','executed')
if sys(a[0]) or sys(a[1]) or sys(a[2]) >= error : exit(error)
else: print(command,successfully,executed)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
command successfully executed
there I finally did it
Anyone here ever obfuscated their Python code?
Or is there a way to make my Python code non readable to other users?
They're are some string obfuscators in the esoteric python challenges GitHub repo.
It's like, I wanna obfuscate it and then pack it using cx_Freeze and distribute to other people
Can anyone help?
Thank you. 😊
There's a few obfuscators available, I believe pyamor is one. Check it out. I will note though that there's code deobsfucators available too
Oh, and if I use PyArmor, then how to pack my application with cx_Freeze?
@stone bane sorry for the ping, but do u know how to do it?
Does it have to be python?
Yes
Give it the nuke codes too
And i have one that obfuscates control flow but not names
keep in mind: there are a lot of ways, none of them are going to stop someone who is dedicated enough, has enough time, and is good enough at reverse-engineering obfuscated code 
Oh well, suppose I distribute my application to 10 people with obfuscating, then at least 9 won't be able to crack it, only one will be able to. This is better than letting 6 people crack the code without obfuscating the code
if it actually matters if someone can get the code (i.e. if they could then obtain supposed-to-be-secret information and break the security of something) then you've already done something wrong and you should rewrite things on the assumption that an attacker can deobfuscate your code perfectly
if you just generally don't really want people to be able to deobfuscate it but nothing particularly bad is going to happen if they do then it's fine
Well it's not like, I have any passwords or credit card numbers or something
I just don't want people to see the code
alright sounds like it's fine then 
If they see it by cracking the obfuscated code, then I don't have a problem
just sometimes obfuscation is an attempt to make sure someone won't see holes in a clearly insecure system and with that the solution is to make the system more secure

Ahh nah, haha
alright good 

It's probably pretty easy to just ship the .pyc files rather than the source. They look incomprehensible, even if they're not too hard to decode.
You do need to be more careful about your Python version if you go that route though.
Oh well, I am tryna convert the obfuscated code to an exe
import os
os.urandom(2147483646)
Sure!
(don't run that. seriously.)
!e
1+1+1*0.+1
@hardy burrow :warning: Your eval job has completed with return code 0.
[No output]
what
...what did you expect it to do 
!e
print(*b"e")
How does this work
@lunar ore :white_check_mark: Your eval job has completed with return code 0.
101
@lunar ore :white_check_mark: Your eval job has completed with return code 0.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
Unpacking a bytes object gives you an int?
shouldn't it be bytes
each byte is just a number right?
Saw this on https://codegolf.stackexchange.com/q/219576
The things people get up to smh...
i think i broke repl.it with that
nvm it got killed
laughs in uncompyle6
it would probably dissuade most people; won't help if someone really wants to though
creating OS and kernel in python
Smart
!e
type("H",(),{"H":"H"})().H
@lone scarab :warning: Your eval job has completed with return code 0.
[No output]
!e
print(type("H",(),{"H":"H"})().H)
@lone scarab :white_check_mark: Your eval job has completed with return code 0.
H
um, scroll up?
@next flame to?
just keep scrolling until you find discord messages
it crashed my pc with windows 10 on it
if run in terminal on linux terminal crashes
(don't run that. seriously.)
presumably you read this part, right
it attempts to read ~2.15 gb of random data
lmao
i was the same person who sent it if you didn't realize
i didnt know what would happen
and i just ran it
and
it fucking crashed my pc
you...sent it without knowing what it does?
works fine with 32GB mem
bruh
anyone know how to inline with open?
while 1:
(
lambda o, s, n, h: (
lambda d: (
lambda i, *a: d.get(i)(*a)
if (i) in (d)
else (print(f'Command "{i}" Not Found.'))
)(*input(f'{n}@{h}: ').split())
)(
{
"clear": lambda: o.system("cls")
if (o.name) == ("nt")
else (o.system("clear")),
"exit": lambda: s.exit("Process Killed Successfully."),
"echo": lambda *a: print(*a),
}
)
)(
__import__("os"),
__import__("sys"),
(lambda _o: (_o.read(), _o.close())[0])(open("storage/user.txt")),
(lambda _o: (_o.read(), _o.close())[0])(open("storage/host.txt")
)
)
currently doing this because i can't figure out how to do it
I tend to like pathlib for files. It means not worrying about closing them.
yea ik i just wanna go that extra length to close it and all
i wanna make a fully functioning command line
i made rmdir/mkdir/mkfile/rmfile today
not sure how ill do file management
I think Pathlib has commands for all of those.
That looks a little bit neater than how I do it, I puts the open inside the lambda with the read and close and I put the lambda inside a dunder heavy class so I can use it like iostreams
i would do open(file).read().close() but read() returns a string
so i use lambda to compensate
I use lambda already as I use it within a dunder method
So I make it an array of operations and return the relevant value by indexing it
i was originally gonna do something like elif _input == "echo": but then i remembered dictionaries are just python switch statements
Yeah almost a replacement
"rmfile": lambda *a: (o.remove(a[0] if type(a) == tuple else a))if o.path.exists(a[0] if type(a) == tuple else a) else print("Lambda: File does not exist.")
weird workaround but somehow works
What would be another tuple element?
Oh o.path.exists
I'm dumb aha
I did a whole try except suite
With open with read perms dot close
Yeah there was a python enhancement protocol for that that got rejected
Probably by some pep8 purist
pep8!? cringe!
while 1:(lambda o,s,n,h:(lambda d:(lambda i,*a:d.get(i)(*a)if i in d else print(f'Lambda: Command "{i}" Not Found.'))(*input(f"{n}@{h} $ ").split(' ')))({'':lambda:s.stdout.write(''),'clear':lambda:o.system('cls')if o.name=='nt'else o.system('clear'),'exit':lambda:s.exit('Process Killed Successfully.'),'echo':lambda *a:print(*a),'mkfile':lambda *a:open(a[0]if type(a)==tuple else a,'w').close(),'rmfile':lambda *a:o.remove(a[0]if type(a)==tuple else a)if o.path.exists(a[0]if type(a)==tuple else a)else print('Lambda: File does not exist.')}))(__import__('os'),__import__('sys'),(lambda _o:(_o.read(),_o.close())[0])(open('storage/user.txt')),(lambda _o:(_o.read(),_o.close())[0])(open('storage/host.txt')))
not at all the right place
i checked multiple times to make sure its in the right place
perhaps get a help channel?
i did not realize this was the channel i was typing in my bad
no problem
!e
@toxic jewel
You can use iter and call a function repeatedly.
sum(iter(lambda: print("hi") or 0, object()))
Sorry, an unexpected error occurred. Please let us know!
ClientResponseError: 500, message='Internal Server Error', url=URL('http://snekbox.default.svc.cluster.local/eval')
oop
This way, you turn while into an expression instead of a statement
pro tip: use proper formatting, and only remove whitespace as a final step
maybe just run black on the thing or something like that
Output of black: https://paste.pythondiscord.com/vuqasigato.py
Short answer is "Context managers"
yeah i originally had it all spread out but ran it through a minifier
How does this work?
!d iter
iter(object[, sentinel])```
Return an [iterator](../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__()`](../reference/datamodel.html#object.__iter__ "object.__iter__") method), or it must support the sequence protocol (the [`__getitem__()`](../reference/datamodel.html#object.__getitem__ "object.__getitem__") method with integer arguments starting at `0`). If it does not support either of those protocols, [`TypeError`](exceptions.html#TypeError "TypeError") is raised. If the second argument, *sentinel*, is given, then *object* must be a callable object... [read more](https://docs.python.org/3/library/functions.html#iter)
!e
x = 0
def f():
global x
x += 1
return x - 1
print(list(iter(f, 10)))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
You're probably trying iter(print(...), ...) or something
wrap the inner function in a lambda
Make a new "language" type thingy by using classes and stuff
(something like this) ```py
System = Language()
square = (System+System.function)("a", "b") & ValueError > (
f"squared = System.Math().pow(a, b){newline}"
"System[::].Stdout(int).write(squared)"
)
System.loop(0, 7, 1, square, 5)```
with code that looks like #bot-commands message
DSL-s in python are my favorite
yes
kool
could I use a for loop as a while loop?
yeah
how
using iter I forgot how but it went along the lines of: py [thing for thing in iter(0, condition)]
'v must be callable'
you swapped the params but yeah, iter(lambda: condition, 0)
what would condition be?
whatever you would put in while
not sure if im doing this right
Which lambda is for the loop?
iter's first argument has to be a function that takes no args, so it's a lambda: rather than a lambda anything:.
is there a way to run code without having it in a string
so like py run( custom_function_in_the_file(a, b) )
because right now run calls exec on the string passed into it
like I have esoteric code that goes like: py func = (System+System.function)({"a": language.int64, "System": language.Language}) & throws(Exception) > ( "num = System[::].Stdin(int64).scan()", "System[::].Stdout(int64).write(a + num);" )
I want the code part though to be not a string
Technically
If you want it to be outside a string, you'll have to make sure everything is a valid expression
So something like x = y isn't an expression but (x:=y) is
Do you want it hardcoded or simply not using str objects?
So realistically you'll have to change your syntax slightly, and to wrap things in lambdas
(for delayed execution)
Trailing semicolon alert!
Here come the Pep8 police...
And they died of shock seeing everything else in this channel
How do I make a class with __repr__ override detect whether it's being used in a terminal or running file?
Essentially so I can make a special string subclass that, when printed, I can return it's value without echoing it's representation
Name equals main in terminal and file
Or is something else when imported
__str__?
Perhaps file but that accesses module globals not running globals
print uses __str__ rather than __repr__.
Ik but the terminal echoes the representation rather than the string
When a raw expression is thrown in there
Try checking stack frames.
wdym?
If you can put some code in brackets and it gives back a value, it's an expression. If it has to be on a line of its own, it's a statement.
the reason why it's in a String is so that it doesn't run immediately before being called
You can use lambda to delay evaluation of expressions.
delay it how?
So I want
ls
In the terminal to have a repr of its empty call, which I have achieved,
_=-ls
to store data in _
But
std << ls
To return the data as well as execute the write to stdout but the data shouldn't display when represented hence I have to set it's representation to blank but I want this to happen only in terminal where representation gets echoed
lambda: print("hello") does nothing, but (lambda: print("hello"))() prints hello.
If you use IPython, there's an inbuilt ls command.
The syntax is lambda <function arguments>: <expression>, which is why you'll need to change your statements to expressions.
Also, additionally if it's being sub-repred I.e. error involving this object, or repr of an array of these to be a string that's not empty
Also, \n inside a string is a shortcut for a newline.
I know
I can't do the lambda thing
it cannot be an expression
it has to be a statement
Why?
In this channel we have a very specific set of skills, one being turning code into expressions.
because of names
num = System[::].Stdin(int64).scan()
System[::].Stdout(int64).write(a + num)
```is just `(num := System[::].Stdin(int64).scan(), System[::].Stdout(int64).write(a + num))` in Python 3.9.
what if I wanna reference an argument in the function
it won't be defined in the expression
because of how the function is called
func: language.Function = (System+System.function)({"a": language.int64, "System": language.Language}) & throws(Exception) > (
lambda: num := System[::].Stdin(int64).scan(),
lambda: System[::].Stdout(int64).write(a + num)
)``` the arguments here are `a` and `System`
it won't work with expressions because it runs exec on the string code with the second argument as a dictionary of the arguments for globals
Were you using them as exec's globals dictionary?
Well, you can do globals().update(dictionary goes here).
It's not as contained as with exec though, if that matters.
Before calling the functions (the lambdas, I mean).
It's equivalent to ```python
a = language.int64
System = language.Language
well I've have to completely change the code
but the code is esoteric
there's a lot to take in
An alternative is to give the lambdas a parameter, like lambda dictionary: num := dictionary["System"][::].Stdin(int64).scan()
class Function:
def __init__(self, args: dict): # {"name": type} so... {"x": languages.int64}
self.args = args
def __and__(self, exception: throws):
self.exception = exception.exception
return self._handleFunction(self.exception, self.args)
class _handleFunction:
def __init__(hf, exception, *args):
hf.exception = exception
hf.args = args
def __gt__(hf, code: tuple):
return functools.partial(hf._function, code, hf.exception, hf.args)
def _function(hf, code, exc, arguments, *args):
if (length := len(list(arguments[0].keys()))) != len(args):
raise exc(f"Function takes {length} arguments, instead, {len(args)} arguments were passed")
for index, value in enumerate(list(arguments[0].values())):
if type(args[index]) != value:
raise exc(f"Type '{type(args[index])}' of Argument {index} does not match type {type(value)}")
try:
code_globals = {**globals(), **dict(zip(list(arguments[0].keys()), args))}
#print(code_globals, dict(zip(arguments, args)))
exec("\n".join(code), code_globals)
except Exception as e:
raise exc(e)``` here's how it is now
{**globals(), **dict(zip(list(arguments[0].keys()), args))} is globals() | dict(zip(list(arguments[0].keys()), args)), incidentally.
I expect you have your reasons.
I guess given what channel we're in I shouldn't be suggesting ways to simplify code.
It's fine, but all I need right now is a way to pass something into the function that takes in statements but doesn't run them until the function is called
I don't even think that's possible
maybe strings is the only way
Get rid of the middle man variable
Nest the expression
Don't assign variables to spread it unnecessarily over lines
That's unesoteric id say as it follows the Zen
(lambda dictionary: dictionary["System"])({"System": "foo"}) is "foo", which is pretty much your goal. Simply call the lambda with the parameters you want later.
This is the Zen of Esoteric Python.
Refer...
well what else do I need to add to this language
I should add loops right?
I don't know exactly how though
It depends on your goal.
What about the antiZen above it?
I've mocked c++
so like I want a way to do it how Java does it
Having never used Java, I'd suggest yes loops.
Abstract away a whole bunch of java commands then import these
dunders of what
You can do anything
Dunders of operstors
Operators are deceptive
They are really shortcuts to calling dunders
Change what those dunders do
Loop(i=0) @ "i < 5" @ "i + 1" something like this
Loop(i=0) @ "i < 5" @ "i + 1" > (
"code"
)```
I need to know how to implement the i < 5 and i + 1 part though
When you become fluent at dunders, you get off your L plates in esoteric python and upgrade to Ps
could be challenging
If you're doing that then you know what I'm talking about I guess
I just can't figure it out
Not really you can turn a lambda of multiple inputs into nested lambdas
I have no clue how to implement this
Not really to challenging soz I'm on phone
I really don't want for x in thing to be left in because it looks too good
Laptop died
it needs to look bad like Java
Yeah, easy,
You want it to loop through code? With step 1 and end when i no longer less than 5?
Show me your code so far
I think this would be easier py Loop() @ lambda i: ({i: 0}, i < 5, i + 1) > ( code )
I just need help for Loop
!dunder
Bad bot
Yeah that's what source means
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
lemme paste it
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Do that
it's more than 2k chars
okay here it is for the loop
class Loop:
def __matmul__(self, function) # Loop() @ lambda i: ({i: 0}, i < 5, i + 1)```
that's all I have now
I just started
__matmul__ is the dunder here
Alrighty then that's what i needed lol
Ty0u g up cos eognkd0heone gonna e.g. wpreyy dhit
Ahem
must tough typing on the phone
busy day tomorrow
Hyperbole
yes
this could be a start py n = 0 a = lambda i: ({i: 0}, i < 5, i + 1) while True: if a(n)[1]: print("hi") n = a(n)[2]
the only problem is the initial value of the specific index
i
it's supposed to be 0, but n is hardcoded as 0
so that's one problem
I'll way for you to finish typing your code
This is not the best format, unless you plan on doing complicated introspection on the code object.
Is it easy to make a code obfuscater myself?
You want your initial value of i to be outside the lambda, or better yet lambda i=0: (i < 5, i + 1).
it was easy for me
but it look a long time
a really long time
If you only have a little code, it's more fun to obfuscate by hand.
Maybe i should be a kwarg for Loop?
so like
@tribal moon and can I get a link to the same?
class Loop:
__new__=lambda s,**k:type("",(),dict(
__matmul__ =lambda s, t:type("",(),dict(
__matmul__=lambda u,v:type("",(),dict(
__gt__=lambda w,x:(lambda ...:...)(k,t,v,x)
)
)
)
)
Loop(i=0) @ lambda i: (i < 5, i + 1)```
Something like that
there is no link
Replacing ...s with some crazy esoteric code
Sooo, I can't use the obfuscater with my code? The one you made
You don't really need the i= because the lambda already knows what variable it depends on.
That nesting I made above will pass all those arguments down across the syntax methods
what about the function argument?
for lambda?
?
Personally, I'd do it Loop @ lambda i=0: (i < 5, i + 1) and keep feeding the right of the tuple back into the function until the left of the tuple is False.
You'd call the lambda, and since i is 0 by default, you'd receive (True, 1), so you'd pass 1 in and get (True, 2) and so on, until you pass in 5 and get (False, 6).
Well I'm a slow typer so my solution is for the original syntax
I wanna do the lambda one now
@snow beacon can I use yr code obfuscater, which is in the Python Discord Repo?
the lmabda i
Nvm
It's probably already under a permissive license, I don't recall.
But yes, I give my blessing.
GPL or something
Wait, I can't encode whole Python files with yr obfuscater?
You should be able to.
Could you make a computer think in ND instead of 3D?
Keep in mind: it takes a string and returns a string, so if you feed it code, you'll need to exec or eval the result.
Certainly.
Then how can I Compile those using pyinstaller?
I.e. not be limited to thinking in 3d, an AI could visualise and solve higher dimension puzzles like minesweeper
Do you want to obfuscate the code before or after compilation?
What do u prefer?
If you have a multi-dimensional problem, granted.
I think I would do before compilation
Well, I can flatten 4d to 2d if it's discrete data rather than continuous
I don't know much about pyinstaller, but if you can give it arbitrary Python code, then before would be fine.
Oh well
I do be making 4d minesweeper puzzles
Thanks for telling!
There's a free 4d minesweeper game on Steam.
Unfortunately it has no guess-free mode.
Most 3d programs can be generalised. A computer doesn't inherently understand physical space, so doesn't have the reasons we have to avoid four-dimensional conceptualisation.
I need to make it so the i attribute of the lambda function is accessible
so should the third element of the tuple just be an i/? Alone?
That depends.
In your lambda i=0: (i < 5, i + 1) example, do you want the first loop iteration to be on 0 or on 1?
0
wait
does this make sense
class Loop:
def __matmul__(self, function): # Loop() @ lambda i=0: (i, i < 5, i + 1)
return _handleLoop(function)
class _handleLoop:
def __init__(hl, function):
hl.function = function
def __gt__(hl, code: tuple):
System = Language()
loopFunction: Function = (System+System.function)({"i": int, "System": Language}) & throws(InterruptedError) > code
called = hl.function()
while called[1]:
loopFunction(int(called[-1]), System)
called = hl.function(i + 1)```
The hl.function(i + 1) part looks off, at the very least.
You're getting your i + 1 from the last element of the tuple.
That implies it only ever increases by 1.
I figured the lambda was there to specify what the transition is.
so the last argument should only be an int?
In this case i + 1.
I'm still grappling with how to get the i out of the lambda and into an i variable in the body.
it's going good so far ```py
Loop() @ (lambda i=0: (i, i < 5, i + 1)) > (
"print('hello')",
)
hello
hello
hello
hello
hello
Loop() @ (lambda i=0: (i, i < 5, i + 1)) > (
"print(i)",
)
1
2
3
4
5
``` but theipart
the incremental part
and the name
how do I get the name of the arg in the lambda
like just treat it as any other function
is there such thing as a lambda i=0: i to lambda_function.__code__.co_argnames -> ('i',)
I'm sure there is, let me check...
inspect.getfullargspec?
There might be a simpler function.
yesss awesome it works
>>> loop_it = Loop() @ (lambda x=0: (x, x < 10, x + 2)) > (
"print(x)",
)
2
4
6
8
10
>>> ```
I don't know why I set a variable to it
that's useless lol
but works
inspect.getargvalues looks similar to .getfullargspec.
You could make the loop body another lambda if you want — that would obviate the need for figuring out the argument names, but mean more repetition.
Or you could mix both and make the loop body a function with no arguments, and call it with an appropriate global.
here's how it is now
I have freed myself from space conceptualization hence why I find higher dimensional puzzles fun
I don't avoid higher dimensions for pretty much the same reason we are all hanging out in esoteric python channel
@floral meteor do a 4 dimensional conways game of life
😔 advent of conway's game of life 😔
yea i remember having to implement the 4d conway for that
not as bad as day 20 was tho
O_[]
I should make 4d CGoL esoterically...
Hehehehehehe
Wait that's almost the same algorithm minesweeper uses
Just without... displaying it?
Or do we have to show results?
should i take two minutes to write code up here? :P
import itertools, numpy
def ___(__):
___=[__];_____=lambda _:_[-1]not in _[:-1];_=__;dims=(len(_),)
while _[0].__class__==list:_=_[0];dims+=(len(_),)
while _____(___):
for i, j,k, l in itertools.product(*(range(_)for _ in dims)):
count=0
for I in range(-1,2):
for J in range(-1,2):
for K in range(-1,2):
for L in range(-1,2):
try:
if __[i+I][j+J][k+K][l+L]:
count+=1
except:pass
if count<=1 or count>3: __[i][j][k][l]=0
elif count==3:__[i][j][k][l]=1
return __
boom
Now do it for an arbitrary amount of dimensions.
Oh, and no recursion.
Recursion is too easy.
Type-safe routing in Python using continuation-passing style (sort of, not really, I guess).
https://paste.pythondiscord.com/ugejanerug.py
r = Const("foo", Str(Int(Const("bar", Int(Empty())))))
match = r.extract("/foo/some-string/1/bar/42")
match is inferred as Tuple[str, Tuple[int, Tuple[int, None]]] | None
The idea is quite simple. We have a generic Route type parametrized by the type it 'captures'.
Some basic examples:
class Rest(Route[str]):
"""
Captures the rest of the path unconditionally
"""
def extract(self, path: str) -> str:
return path
class Empty(Route[Literal[None]]):
"""
Captures None unconditionally
"""
def extract(self, _: str) -> None:
return None
more sophisticated routes are done by passing the "rest of the path" as an argument to the constructor:
class Str(Generic[A], Route[Tuple[str, A]]):
"""
Captures a piece of the path as a string
"""
def __init__(self, rest: Route[A]):
self.rest = rest
def extract(self, path: str):
m = re.match(r"/([^/]*)(.*)", path)
if m is None:
return None
return (m[0], self.rest.extract(m[1]))
So if you want to have a route like /abc/{str}, you write
Const("abc", Str(Empty()))
If your route is /abc/{str}/def/{str}/{str}/{ghi}, it's going to be
Const("abc", Str(Const("def", Str(Str(Const("ghi", Empty()))))))
so could i do lambda: lambda variable: ... as a workaround
all of that just to have a statement at the beginning
(print("Console loaded successfully.")),[x for x in iter(lambda: (lambda o,s,n,h:(lambda d:(lambda i,*a:d.get(i)(*a)if i in d else print(f'Lambda: Command "{i}" Not Found.'))(*input(f"{n}@{h} $ ").split(' ')))({'':lambda:s.stdout.write(''),'clear':lambda:o.system('cls')if o.name=='nt'else o.system('clear'),'exit':lambda:s.exit('Process Killed Successfully.'),'echo':lambda *a:print(*a),'mkfile':lambda *a:open(a[0]if type(a)==tuple else a,'w').close(),'rmfile':lambda *a:o.remove(a[0]if type(a)==tuple else a)if o.path.exists(a[0]if type(a)==tuple else a)else print('Lambda: File does not exist.')}))(__import__('os'),__import__('sys'),(lambda _o:(_o.read(),_o.close())[0])(open('storage/user.txt')),(lambda _o:(_o.read(),_o.close())[0])(open('storage/host.txt'))), 1)]
looping a function: ```py
System = Language()
from numpy import int64
function =(System+System.function)({"x": int64, "y": int64, "System": type(System)}) & throws(Exception) > (
"System[::].Stdout(int64).write(System.Math().pow(x, y))",
)
Loop() @ (lambda i=1: (i, i < 10, i + 1)) & inherits({"function": function}) > (
"function(int64(i), int64(i), System)",
)
4
27
256
3125
46656
823543
16777216
387420489
10000000000```
https://hatebin.com/adkklahoqa add your own features
this is what I have now
too bad I didn't document it
attempt to remove all spaces except for strings and lambda variables: ... because idk how
print('Console loaded successfully.'),[(x)for(x)in(iter(lambda:(lambda o,s,n,h:(lambda d:(lambda i,*a:d.get(i)(*a)if(i)in(d)else(print(f'Lambda: Command "{i}" Not Found.')))(*input(f"{n}@{h} $ ").split(' ')))({'':lambda:s.stdout.write(''),'clear':lambda:o.system('cls')if o.name=='nt'else o.system('clear'),'exit':lambda:s.exit('Process Killed Successfully.'),'echo':lambda*a:print(*a),'mkfile':lambda*a:open(a[0]if(type(a))==(tuple)else(a),'w').close(),'rmfile':lambda*a:o.remove(a[0]if(type(a)==tuple)else(a))if(o.path.exists(a[0])if(type(a))==(tuple)else(a))else(print('Lambda: File does not exist.'))}))(__import__('os'),__import__('sys'),(lambda _o:(_o.read(),_o.close())[0])(open('storage/user.txt')),(lambda _o:(_o.read(),_o.close())[0])(open('storage/host.txt'))),1))]
also added some error handling
Look! ```py
isPrime: Function = (System+System.function)({"n": int, "i": int, "System": type(System)}) & throws(ValueError) > (
"if (System.Math().mod(n, i)) == 0:",
" System[::].Stdout(bool).write(False)",
" System.exit()",
"else:",
" System[::].Stdout(bool).write(True)",
" System.exit()",
)
checkPrimeNumber = System[::].Stdin(int).scan()
1471
Loop() @ (lambda i=2: (i, i < checkPrimeNumber, i + 1)) & inherits({"isPrime": isPrime}) > (
"isPrime(checkPrimeNumber, i, System)",
)
True```
this checks for prime number
it works!
I need to add arrays now
I was thinking of something like this ```py
var = 0
class Array:
def gt(self, a):
return self
class _:
def eq(self, b):
return b
var<Array()>_() == 335
335
type[num] could declare an array of type that is num long
Is there a way to get variable annotations?
Because I can just use Python's built in variable type hinting mechanism to do it
but I need a way to get a variable's annotations
so like ```py
var: Array(int) = [1, 2, 3 4]
var.annotations
(Array,)```
so the upper scope should have an __annotations__dictionary
so to get the annotations for a certain variable name you need details from the upper scope
Well I need to make a way to make strong typing in this Python script
one sec i can write a frame hacky thing to do it
@tribal moon so the issue is that when Array(int) is called nothing has been stored as an annotation yet
why not?
because the result of Array(int) is what is stored as an annotation
it also wont work inside functions
So how do I make strong typing?
well when ```py
def func():
x: int = 1
the int type hint isnt saved anywhere
its stripped
!e ```py
def func():
x: this_name_doesnt_exist
func()```
@rugged sparrow :warning: Your eval job has completed with return code 0.
[No output]
^ see its stripped. Its never even ran
I know
you could use inspect.getsource and parse it yourself
Nah I can't do that
the code is meant to be used in a file and a shell
the shell doesn't work for that
>>> array = Array(int)
>>> array.addItem(26)
[26]
>>> array.addItem(26)
[26, 26]
>>> array.getItem(3)
IndexError: Item {index} could not be found.
>>> array.getItem(1)
26``` any way to make the syntax more Java-like? (more esoteric)
also ignore the {index} part I forgot to make it an fstring
I think Array<int>() is possible, but not 100% sure
it looks like it could work
but how would I make Array?
Like it'd need to be a class because of the operators and dunders
but without calling it, it's type
is there a dunder for that?
metaclasses
what would I make the metaclass?
it's expanded as Array < int and int > (), and int > () will throw an exception.
aww
You could just do Array[int](), right?
I guess you can redefine int
or make Array < int falsey, while introspecting the line when < is called
How am I supposed to make that falsey?
I'm still trying to figure out how to change the value of Array without calling it
with metaclasses
I can write an implementation that'll work with Array<int>(args) in like an hour
*it should work
you probably have to modify int or sth
You can parse bytecode to get the args
or that
Yea. It'll work. Gimme an hour
alright
ping me when you're done
in my program, the thing uses int64 from numpy because it feels like it makes more sense that way
!e
import sys
print(sys.version())
@verbal geode :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | TypeError: 'str' object is not callable
!e
import sys
print(sys.version)
@verbal geode :white_check_mark: Your eval job has completed with return code 0.
001 | 3.9.2 (default, Feb 19 2021, 17:23:45)
002 | [GCC 8.3.0]
@tribal moon so my logic i use is this:
scan until we hit COMPARE_OP (>) Followed by JUMP_FORWARD, ROT_TWO, POP_TOP
replace those ops with LOAD_NAME(cls.__name__) LOAD_METHOD(cls.__name__) CALL_METHOD(0) NOP
cls.(cls.name)() will retrieve the TOP two stack items (ocls, args) of the upper frame and shift stack pointer of upper frame
it will then return cls(ocls, args)
I'm sorry I'm not good with bytecode and code frames
!e ```py
import sys, dis
from ctypes import *
def getmem(addr, size):
return (c_char*size).from_address(addr)
class Tmeta(type):
def lt(cls, ocls):
frame = sys._getframe(1)
idx = 0
instructions = [*dis.get_instructions(frame.f_code)]
for instruction in instructions:
if instruction.opname == 'COMPARE_OP' and instruction.argval == '>':
if instructions[(idx//2)+1].opname == 'JUMP_FORWARD':
if instructions[(idx//2)+2].opname == 'ROT_TWO':
if instructions[(idx//2)+3].opname == 'POP_TOP':
setattr(cls, cls.name, cls.magic)
nm_idx = frame.f_code.co_names.index(cls.name)
inj_code = bytes([
dis.opmap['LOAD_NAME'], nm_idx,
dis.opmap['LOAD_METHOD'], nm_idx,
dis.opmap['CALL_METHOD'], 0,
dis.opmap['NOP'], 0
])
mem = getmem(id(frame.f_code.co_code) + bytes.basicsize + idx - 1, len(inj_code))
mem[:] = inj_code
idx += 2
return True
def _magic_(cls):
frame = sys._getframe(1)
stack = POINTER(py_object).from_address(id(frame) + 8 * sizeof(c_ssize_t))
ocls = stack[0]
args = stack[1]
c_void_p.from_address(addressof(stack)).value -= 2 * sizeof(py_object)
return cls(ocls, args)
class Array(metaclass=Tmeta):
def init(self, T, args):
print('Array called with:', T, args)
var = Array<int>(1, 2, 3)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
Array called with: <class 'int'> (1, 2, 3)
@tribal moon ^ example
has a bit of everything
How did you learn how to do this? This is incredible
basically when it hits Array<int>(1,2,3) ^ Array.__lt__(Array, int) is called
oh lots of too much free time
inside Array.__lt__ it converts the bytecode of Array<int>(1,2,3) to roughly Array<int;(1,2,3);Array._magic_()
then Array._magic_ grabs int and (1,2,3) off of the stack using ctypes, then shifts the stack by 2, then returns Array(int, (1,2,3))
that sounds very complicated
its a bit complex. it helps to understand the interpreter itself
@tribal moon that code should work in most cases
should work?
in some cases?
wdym
for some reason it restarts the shell
IDLE shell btw
it could just be IDLE because IDLE is like that
acc wait
pattern matching is implemented on cpython/master, prepare your most brutal esoteric ideas
I can't wait to see it
you can clone cpython and compile it
works for me
I'll work up to that I'm on phone rn ahahahaha
Imma keep working on this
But I'll also make a switch statement
Do you know how to make a Java-like syntax for HashMap
so like in the Python Shell: py hashmap = HashMap<str, int>{ "3": 2, "5": 6 } using gt, lt, and altering frame bytecode>
like like what chilaxan did before
I struggle to get past read only in a code object
#esoteric-python message here to be exact
actually I don't think the code really makes sense that I gave for the hashmap thing lol
hashmap = HashMap<(str, int)>{
"3": 2,
"5": 6
}``` it'd make a bit more sense if the type where in a tuple or something?
because I don't think it's possible without
or at all maybe....
There's no such thing as impossible here
Could do something like the above but when HashMap < str, make tuple packing turn into what you want
I don't know how to do this code lol
It's really cool how people can do this
like there obviously aren't any online tutorials for this bytecode thing
it's really cool
Oooh Tysm
@floral meteor i could implement that alternative syntax
but it would be way longer
but typ<(int,int)>{} works tho
!e ```py
import sys, dis
from ctypes import *
def getmem(addr, size):
return (c_char*size).from_address(addr)
replace JUMP_IF_FALSE_OR_POP with NOP then
scan until we hit COMPARE_OP (>) Followed by JUMP_FORWARD, ROT_TWO, POP_TOP
replace those ops with ROT_TWO, ROT_THREE, CALL_FUNCTION(2), NOP
This rearranges the stack to be [cls, T, args], then calls cls(T, args)
and returns it
class Tmeta(type):
def lt(cls, ocls):
frame = sys._getframe(1)
idx = 0
mem = getmem(id(frame.f_code.co_code) + bytes.basicsize - 1, len(frame.f_code.co_code))
mem[frame.f_lasti + 2] = dis.opmap['NOP']
instructions = [*dis.get_instructions(frame.f_code)]
for instruction in instructions:
if instruction.opname == 'COMPARE_OP' and instruction.argval == '>':
if instructions[(idx//2)+1].opname == 'JUMP_FORWARD':
if instructions[(idx//2)+2].opname == 'ROT_TWO':
if instructions[(idx//2)+3].opname == 'POP_TOP':
inj_code = bytes([
dis.opmap['ROT_TWO'], 0,
dis.opmap['ROT_THREE'], 0,
dis.opmap['CALL_FUNCTION'], 2,
dis.opmap['NOP'], 0,
])
mem[idx:idx + len(inj_code)] = inj_code
idx += 2
return cls
class Array(metaclass=Tmeta):
def init(self, T, args):
print('Array called with:', T, args)
class HashMap(metaclass=Tmeta):
def init(self, T, args):
print('HashMap called with:', T, args)
a = Array<int>(1,2,3)
b = HashMap<(str, int)>{
'a': 0,
'b': 1
}```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | Array called with: <class 'int'> (1, 2, 3)
002 | HashMap called with: (<class 'str'>, <class 'int'>) {'a': 0, 'b': 1}
yea
they should work like regular classes
just remember to do metaclass=Tmeta
the reason it didnt work before is because i didnt handle the stack correctly
this is amazing
How can I learn how to do this?
Like the bytecode part
how does it work?
so python uses frames to handle function calls and what not
every frame has its own bytecode
you cant normally modify it like this, but with ctypes you can do it inplace, while it is running
!e ```py
def f():
print('hello world')
print(f.code.co_code)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
b't\x00d\x01\x83\x01\x01\x00d\x00S\x00'
thats the bytecode of that function ^
@rugged sparrow what's bytes.basicsize I cant find anything in the c docs for it
its the size of a bytes object before any additional data is added to it.
its the sizeof the raw c struct
Ah
i use it there because bytes holds its char[] right after its base data (-1 to account for the 0x00 at the end of the array)
Ohhh
So now we have Arrays
what code should I make now
including arrays
with this custom Java-like syntax in Python 😆
i actually wrote an implementation of c structs in pure python (that could interface with c code) using the fact that LOAD_CONST can load arbitrary python objects
If you wanna add your own things to the code I can send the full code
just in case anyone wants to see
!e ```py
class switch:
def init(self,value=True):
self.value=value
def getattr(self,kw):
if kw=='case':return type("Case",(),dict(getitem=lambda s,v:type("CaseStatement",(),dict(init=lambda _,f:[self.value==v and setattr(self,'return',f()),self][1])))
elif not hasattr(self,kw): return None
def otherwise(self, f,*a):
if not hasattr(self,'return'): self.return=f(*a)
return type("returnable",(),{'return':self.return})
i=4
print(switch(i). case[2](lambda: print("haha")). case[4](lambda: print("i can't believe it but it works")or 69). otherwise(lambda: "I'm dumb").return)
@floral meteor :x: Your eval job has completed with return code 1.
001 | File "<string>", line 6
002 | elif not hasattr(self,kw): return None
003 | ^
004 | SyntaxError: invalid syntax
Now what else to add to this language?
🤔
you cant use return as an attribute name
What about a 'soft' attribute?
!e ```py
class x:
pass
setattr(x, 'return', 1)
print(x.return)```
@rugged sparrow :x: Your eval job has completed with return code 1.
001 | File "<string>", line 5
002 | print(x.return)
003 | ^
004 | SyntaxError: invalid syntax
Now I need to make code
what code should I make for my language
maybe a fibonacci sequence calculator?
there's a problem with looping inside of functions
!e ```py
w1=print
w2=lambda :getattr(,'..')
class :init=lambda s:s.setattr('..',"()...")
w1(w2(__()))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
__()...
Soft coded attributes go brrrrrr
!e ```py
import sys, dis
from ctypes import *
def getmem(addr, size):
return (c_char*size).from_address(addr)
def builtinexc(exc):
# inject raise after upper function
frame = sys._getframe(2)
mem = getmem(id(frame.f_code.co_code) + bytes.basicsize - 1, len(frame.f_code.co_code))
mem[frame.f_lasti + 2:frame.f_lasti + 4] = bytes([dis.opmap['RAISE_VARARGS'], 1])
return exc
def func():
return builtinexc(TypeError('testing'))
func() # raises exc in upper scope and does not reveal internals of func
@rugged sparrow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 18, in <module>
003 | TypeError: testing
^ that basically lets you write functions that can emulate c exceptions (with the stripped traceback)
!e py int('a')
@rugged sparrow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ValueError: invalid literal for int() with base 10: 'a'
^ like that
@rugged sparrow for some reason the array is not working
it's restarting the shell
I'm defining one inside of an if statement in the code
Okay
fibFunction = (System+System.function)({"n": Integer, "value1": Integer, "value2": Integer}) & throws(KeyboardInterrupt) > (
"value1, value2 = value2, value1+value2",
);
System[::].Stdout(String).write("Enter a number here: ");
n = System[::].Stdin(Integer).scan();
value1, value2 = 1, 1;
if (n == 0):
System[::].Stdout(Integer).write(0);
System.exit()
array = Array<int>(0, 0, 1, 1)
Loop() @ (lambda i=n: (i, i > 2, i - 1)) & inherits({"array": array}) > (
"array.addItem(4)",
"System.globalsUpdate('array', array)",
)```
Can you try initializing the array normally?
like Array(int, (1,2,3,4))
its working for me
maybe it's because I'm using IDLE
I get this
>>> import language
Enter a number here:
10
Segmentation fault```
I have no idea why this happened lol
can you try running this: ```py
System[::].Stdout(String).write("Enter a number here: ");
n = System[::].Stdin(Integer).scan();
value1, value2 = 1, 1;
if (n == 0):
System[::].Stdout(Integer).write(0);
System.exit()
array = Array<int>(0, 0, 1, 1)
Loop() @ (lambda i=2: (i, i < (n - 1), i + 1)) & inherits({"array": array}) > (
"array = array.addItem(array.getItem(i) + array.getItem(i - 1))",
"System.globalsUpdate('array', array)",
)
System[::].Stdout(Integer).write(array.getItem(-1))
input()
System.exit()```
sure
yeah how does it work for you?
that seg faulted
ohhh wait
interesting
it works for you because I sent the code with the other non-esoteric way to define the array
why is it doing that?
for some reason it only works in the shell and not in that if statement
looks like it can't get passed array = Array<int>(0, 0, 1, 1)
oh
wow
okay for some reason I got it working
found the reason
but the only way it fix it was to do exec("array = Array<int>(0, 0, 1, 1)")
gimme a min ill send a new Tmeta
its because the file is so long lmao
there is an EXTENDED_ARG opcode
one sec
class Tmeta(type):
def __lt__(cls, ocls):
frame = sys._getframe(1)
idx = 0
mem = getmem(id(frame.f_code.co_code) + bytes.__basicsize__ - 1, len(frame.f_code.co_code))
i = frame.f_lasti
while dis.opname[ord(mem[i])] != 'JUMP_IF_FALSE_OR_POP':
i += 2
mem[i] = dis.opmap['NOP']
instructions = [*dis.get_instructions(frame.f_code)]
for instruction in instructions:
if instruction.opname == 'COMPARE_OP' and instruction.argval == '>':
if instructions[(idx//2)+1].opname == 'JUMP_FORWARD':
if instructions[(idx//2)+2].opname == 'ROT_TWO':
if instructions[(idx//2)+3].opname == 'POP_TOP':
inj_code = bytes([
dis.opmap['ROT_TWO'], 0,
dis.opmap['ROT_THREE'], 0,
dis.opmap['CALL_FUNCTION'], 2,
dis.opmap['NOP'], 0,
])
mem[idx:idx + len(inj_code)] = inj_code
idx += 2
return cls``` @tribal moon new Tmeta
alright lemme see
wait its still broken
yeah I keep getting IndexError: tuple index out of range
I don't know if that's my code or the Tmeta though
no ik the issue
class Tmeta(type):
def __lt__(cls, ocls):
frame = sys._getframe(1)
idx = 0
mem = getmem(id(frame.f_code.co_code) + bytes.__basicsize__ - 1, len(frame.f_code.co_code))
i = frame.f_lasti
while dis.opname[ord(mem[i])] != 'JUMP_IF_FALSE_OR_POP':
if dis.opname[ord(mem[i])] == 'EXTENDED_ARG':
mem[i] = dis.opmap['NOP']
i += 2
mem[i] = dis.opmap['NOP']
instructions = [*dis.get_instructions(frame.f_code)]
for instruction in instructions:
if instruction.opname == 'COMPARE_OP' and instruction.argval == '>':
if instructions[(idx//2)+1].opname == 'JUMP_FORWARD':
if instructions[(idx//2)+2].opname == 'ROT_TWO':
if instructions[(idx//2)+3].opname == 'POP_TOP':
inj_code = bytes([
dis.opmap['ROT_TWO'], 0,
dis.opmap['ROT_THREE'], 0,
dis.opmap['CALL_FUNCTION'], 2,
dis.opmap['NOP'], 0,
])
mem[idx:idx + len(inj_code)] = inj_code
idx += 2
return cls``` @tribal moon actually fixed it
basically the JUMP_IF_FALSE_OR_POP was jumping to more than 255 so it was generating opcodes that i didnt expect there
I get another error
the same thing
restarting
code that probably causes it: py numbers = Array<Integer>() done: Boolean = False while (not done): try: n = System[::].Stdin(Integer).scan() except TypeError: break numbers = Array<Integer>numbers.addItem(n)
anyways that code shouldnt cause an issue
Well for some reason it does
here's how it goes
it asks me for a number
I write 1
it works
it asks me again
I write 2
then it stops
yea i see where it breaks
bytecode must be hard to work with lol
also
is there a way to do System::Stdout instead of System[::].Stdout?
like similar to C++
using bytecode or something maybe?
_[System::Stdout] is as close as you can get
@rugged sparrow why not use ands instead of nested ifs?
@tribal moon it is because python optimizes it
also your file is massive which leads to python mucking with the bytecode more
@floral meteor it would look messier
yeah I don't want a 100 char line with just ands
the nested if looks cleaner imo
my file is massive?
like the code I'm writing or the code that makes the code that I'm writing?
all of your code is in one file
I can make it multiples files
so the bytecode is getting annoying to handle
what if you flip the annotation and the name somehow boolean: x = 7 lol would look a bit more like Java i guess
so it's easier
This is esoteric python readability is overrated
@tribal moon the reason it breaks is due to my EXTENDED_ARG fix
im not gonna fix it
to much effort for a joke program
lol
Yeah my mistake for putting the code where the code that makes that code work
I'll put it in another file
that could fix it right?
Meanwhile I have iostreams/bash
this time it's a bit weird
while dis.opname[ord(mem[i])] != 'JUMP_IF_FALSE_OR_POP':
IndexError: invalid index```
I don't know what that means
yea thats cause my EXTENED_ARG fix was hacky af
Now that the code is in a completely new file, can I roll back to the old TMeta where it was made for short bytecode?
Add iostreams and "<include import>" syntax
what is iostreams
Input output streams
Stdout
Stdin
Stderr
Terminal
Using gt and lt signs to pipe to or from files
oh my god FINALLY
IT WORKED
from language import *
System = Language()
System[::].Stdout(String).write("Enter numbers here (write a letter if you're done): ");
numbers = Array<Integer>()
done: Boolean = False
while (not done):
try:
n = System[::].Stdin(Integer).scan()
except TypeError:
break
numbers = numbers.addItem(n)
numbers = Array<Integer>numbers
#n = System[::].Stdin(Integer).scan();
value1, value2 = 1, 1;
if (n == 0):
System[::].Stdout(Integer).write(0);
System.exit()
hashMap = HashMap<(String, Integer)>{}
Loop() @ (lambda x=0: (x, x < len(numbers), x + 1)) & inherits(
{"Loop": Loop,
"numbers": numbers,
"hashMap": hashMap}) > (
"array = Array<Integer>(0, 0, 1, 1)",
"n = numbers.getItem(x - 1)",
'Loop() @ (lambda i=2: (i, i < n, i + 1)) & inherits({"array": array}) > (',
" 'array = array.addItem(array.getItem(i) + array.getItem(i - 1))',",
" 'System.globalsUpdate(\"array\", Array<Integer>array)',",
')',
"hashMap.putValue(String(n), array.getItem(-1))",
"System.customGlobalsUpdate('hashMap', hashMap, globals())"
)
writeToFile = (System+System.function)(
{"hashMap": HashMap,
"fileName": String,
"subSystem": System.getType()
}) & throws(IOError) > (
"fileReader = subSystem[IOReader].FileIOReader;",
'fileObj = fileReader(subSystem[::].IOFileMode()[subSystem[::].File:"w"]) >> fileName;',
'fileObj.write(repr(hashMap))'
)
writeToFile(hashMap, "calculated_fibonacci_sequence.txt", System)
System.exit()
print(fib(n))
``` here's the code

Yo’, @bitter iris told me I should check this out—but I have no idea what’s going on here.
crazy stuff
I wonder if I have anything recent that’s cool enough to show off. Maybe peek on a generator?
Here’s something I struggled with the other day: presumably since the data of list are likely to be discontiguous in memory, you could show an appreciable performance difference between a loop on xs and on sorted(xs, key=id) for a sufficiently large structure. Presumably the former would involve more loads as a consequence of cache miss, and you’d see it in a naïve timing. But I was never able to make that materialize, and I ran out of time trying to simulate a pathological case using ctypes to control exact memory layout.
@grand urchin lists are not discontiguous

