#esoteric-python
1 messages · Page 121 of 1
where and how do u guys learn to make such terrifying python code?
this is just a small example
def inf(start=0, step=1):
while True:
yield start
start += step
num_chunks = (
inf()
.dropwhile(partial(operator.gt, 500))
.takewhile(partial(operator.gt, 1000))
.chunks(100)
.collect()
.len()
)
lol nice
i had a stroke trying to understand that .....
does this make any more sense?
>>> from traitor.traits.fmt import Display, Debug
>>> "a".fmt()
RuntimeError: Multiple implementations for `fmt` found.
#1 defined in an implementation of Display: fmt
Hint: disambiguate the associated method for #1: Display.into('a').fmt
#2 defined in an implementation of Debug: fmt
Hint: disambiguate the associated method for #2: Debug.into('a').fmt
>>> print(Debug.into("a").fmt())
'a'
>>> print(Display.into("a").fmt())
a
@grand lynx
Can you guys think of another way to loop other then for/while loops?
Thats what I have done.
!e ```py
from typing import Iterator, Callable
def loop(func: Callable, obj: Iterator) -> None:
i = next(obj)
func(i)
try:
loop(func, obj)
except StopIteration:
return
loop(print, iter(range(10)))
@gusty hill :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
this can make esoteric code even more complex
a=lambda a,b,c,d:[[__import__('random').uniform(a,b)for e in range(c)]for f in range(d)]```
Hello, try to codegolf this

[[[<...>.uniform(a,b)]*c]]*d
from typing import Any
from traitor import has_trait
from traitor.traits.debug import Debug
def debug_print(item: Any):
if has_trait(item, Debug):
reveal_type(item.fmt)
reveal_type(item.display)
Type of "item.fmt" is "(self: Debug) -> str"
Type of "item.display" is "Unknown"
``` 
can't get it recognize the methods as actual bound instance methods, but this is more than i hoped for anyway
here's what it does
def get_color(s):
return getattr(s, s.strip())
colors = (
[
"red",
None,
"green",
None,
"blue",
None,
"yellow",
None,
"magenta",
None,
"cyan",
None,
"white",
]
.map(Maybe)
.map(lambda m:
m.fmap(lambda s:
get_color(s)().on_black().bold()
)
)
.collect()
)
print(colors.fmt())
source?
when we do pattern matching we can't use a variable there obviously
y = 4
match x:
case (y, 2):
```that reassigns y instead of comparing
if we have a qualified variable, that becomes valid, means (4,2)
```py
class k:pass
k.y = 4
match x:
case (k.y, 2):
is there a way to make a dotted variable from the start, without defining a class or a function?
👌 
@marsh void read at your own risk https://gitlab.a-sketchy.site/AnonymousDapper/traitor
scary
I think I started by looking at code golf. There's a Code Golf and Programming Puzzles page about tips for golfing in Python that has some cool stuff well explained. I also started a guide to help with the learning code for esoteric Python, although I haven't added to it recently: https://github.com/IFcoltransG/esoteric-python-guide/wiki
{*iter(lambda:print("Loop!"), 0)}
eval works for looping too (the * operator)
eval('print("Hello, World!"'*5)
not very good because you can't get a counter easily
What's a dunder?
a method starting with double underscores
working on generic traits (typing.Generic breaks this so I gotta do it myself tho)
@impl(Into[float] >> str)
class StrToFloat:
...
@impl(Into[int] >> str)
class StrToInt:
...
Oh - I use dunders all the time then
just hang out here enough and you'll get it
pur your code in a str terminated with a newline or semicolon as necessary in an exec call and multiply the str by the number of loops
i=input
*g,=map('X'.count,i())
exec(int(i())*"""*k,=g
j=a=d=0
for c in g:
s=sum(c^g[(j+x)%400]for x in[-1,-20,-19,1,20,19,21-j%20//19*60,39-60*(0<j%20)])
if-s//2+3:k[j]=0;d+=c
if~c&s==3:k[j]=1;a+=1
j+=1
g=k
""")
i(f'{a},{d}')
here's a cellular automata code golf solution I did that uses multiplying an execed str
I lost though because I was new to code golf and didn't think to use sets...
I=input
s=I()
exec("s={i for i in range(400)if('.'<s[i]if''in(p:=s)else 4<sum((i//20+x//3%3-1)%20*20+(i+x%3-1)%20in s for x in range(5,22))<8)};"*-~int(I()))
I(f'{len(s-p)},{len(p-s)}')
this won, also used multiplying execed str
new contest tomorrow at 12 CDT!
idk or c to advertise EM I just think lyndon needs more competition lol
I love cellular automata
it's pretty neat, that was my first and only time coding it
I made a list of bools (really one and zero ints) and checked adjacents, winner (lyndon of course) made a set of living indices
!e
print(False is not None)
print(False is (not None))```
@alpine flower :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | False
there's gotta be a way to use this somehow
does this count as code gore? https://paste.a-sketchy.site/tosezunebo.py
somewhat
Maybe by replacing "False" in a string to exec.
I can't remember where on reddit I saw it, but you could also do something like
"" and (not None) ^ [""] or 2 * (not None)```
Just really overcomplicated conditions without a ton of redundancy
I found it
(False is not None) == (False != None)
>>> True
not_none = not None; (False is (not None)) == (False == not_none)
>>> True```
Hey !
I need some help on a problem (as usual)
I dont realy know if i'me on the great channel.
I want, with a python code (python 3.8) to send a mail.
I searched, i searched, i searched....
I found some difrent things, but lot of them didnt work.
For example, lot of website was talking about smtplib and emails.utils.
Well, that great but... for a gmail account... that didn't work.
After, i found google_api i actualy didn't try, but works only for gmail accounts. That seems great, but i wanted to know if a (great) lib exist, that allow emails from any smtp clients.
I need some help on a problem
Pretty sure you dont want the kind of help this channel provides
this channel will give you more problems
concept: short circuiting as lazy evaluation
>>> Not if Is is true and false else Else if Not is not If else Else if Is is Is is not Not and true else False
True
>>>
Wrap it in parens and add For/for/in/In
it's totally valid
install the required dependencies dummy
!e
class Not: pass
class Is: pass
class Else: pass
class If: pass
def true(): pass
print(Not if Is is true and false else Else if Not is not If else Else if Is is Is is not Not and true else False)```
@alpine flower :white_check_mark: Your eval job has completed with return code 0.
<class '__main__.Else'>
that was painful
also nice that's wrong
what in the fd3c5173c6b328e2e98f7e40d6ba6246 99754106633f94d350db34d548d6091a
!e
s = "d3c5173c6b328e2e98f7e40d6ba6246 99754106633f94d350db34d548d6091a"
print(int(bin(int(abs(hash(s) // id(s)) ** .5 // 3 * .3) - int('0b100011', 2)), 2))```
@alpine flower :white_check_mark: Your eval job has completed with return code 0.
-16
idk why I thought the id would be the same as mine
!e
s = "fd3c5173c6b328e2e98f7e40d6ba6246 99754106633f94d350db34d548d6091a"
print(int(bin(int(abs(hash(s) // 2596483770928) ** .5 // 3 * .3) - int('0b100011', 2)), 2))
@alpine flower :white_check_mark: Your eval job has completed with return code 0.
129
???????? but why ??????
you... uh... got the hash part right
!e
s = "fd3c5173c6b328e2e98f7e40d6ba6246 99754106633f94d350db34d548d6091a"
print(int(sum(map(lambda b: int(b, 2), map(bin, [ord(c) for c in s]))) ** .5 + 4.262066761441943))```
@alpine flower :white_check_mark: Your eval job has completed with return code 0.
69
did you work out what it meant?
Yep
!e
s = "fd3c5173c6b328e2e98f7e40d6ba6246 99754106633f94d350db34d548d6091a"
raise(BaseException(int(sum(map(lambda b: int(b, 2), map(bin, [ord(c) for c in s]))) ** .5 + 4.262066761441943)))```
@alpine flower :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | BaseException: 69
@sick hound :white_check_mark: Your eval job has completed with return code 0.
69
it was a bit too readable sorry
!e
code="fd3c5173c6b328e2e98f7e40d6ba6246 99754106633f94d350db34d548d6091a"
this=fun=''
say=lambda x:(__import__('sys').stdout.write(f"{x}\x0a"),None)[1]
does=type('',(),{'__rmod__':lambda s,_:s,'__sub__':lambda _,__:0})()
this is fun and 100% does-say(int(sum(map(lambda b:int(b,2),map(bin,[ord(c) for c in code])))**.5+4.262066761441943))```
@alpine flower :white_check_mark: Your eval job has completed with return code 0.
69
im goin to sleep
someone beat lyndon
Your code here...
a wise (and crazily esoteric) man once informed me on the existence of __annotations__ = globals(). i now finally understand it
lol, that's cursed
but technically valid
yep, and since they're both references to the same global namespace, you can do tons of stuff
!e
@lambda _:(lambda j:_(j.__len__.__call__(),j[:0]))(_.__name__)
def __(_,__):
z = lambda n: lambda f: f(n)
k=0b1110110
u=map(z,range(-~(0x000000000^0o00000000000000),k))
___=[]
____=__
for i in u:
if int(f"{i(int.__pos__.__call__.__call__):09b}",_)%3<_//_:__+="Fizz"
if int(f"{i(int.__pos__.__call__):09b}",_)%5<_//_:__+="Buzz"
____+=str(__ or i(eval(eval("abs").__name__).__call__.__call__.__call__)or __[1:][2:][3:][5:][7:][11:][:][:])+" "
___+=[i]
__=__[1:][2:][3:][4:]
a=(_//_-__.__len__.__call__()).__add__
___[_^_]=lambda f:f(a(i(a)))
b=(a.__reduce__.__call__()[_//_][__.__len__.__call__()]).__mul__
g=z(_//_-_//_)
p=z(z(g(a))(a))(a)
q=__builtins__.__dict__.__getitem__(chr(___[-23](b))+chr(___[a(-p-p-p-p-p-p-p-p)](b))+chr(___[-13](b))+chr(___[-p-p-p](b))+chr(___[-p-p-p](b))[___[-p-p-p](b):]+chr(___[-p-p](b))+chr(___[a(a(-p-p-p))](b))+chr(___[-p-1](b))+chr(___[a(-p)](b))+chr(___[-23](b))+chr(___[-20-p](b)))
ж=q(__.join(map(chr,(___[-p-p-p](b),___[a(a(-p))](b),___[a(a(-p-p-p-p))](b),___[a(-p)](b),___[a(a(-p-p-p-p-p))](b),___[-p-p](b),___[-4](b),___[-p-p-a(__.__len__())](b),___[-p-p-p-p-p-p-1](b),___[a(-p-p-p-p-p-p)](b),___[-p](b),___[-p](b),___[-p-p-p-p-1](b),___[a(-p-p-p)](b),___[-p-p-p-p-p](b),))))
if ж.__dict__.__getitem__.__call__.__call__(next(filter(lambda s:s.startswith(chr(___[-p-p-p-p-p-p-1](b))+chr(___[-p-p](b))),dir(ж))))()<p:return print(____)
w=[*map(chr,map(lambda x:x(b),map(___.__getitem__,[p^p,a(-p-p-p-p-p-p),*[a(-p-p-p-p-p-p-p)]*(-a(-p))]))),*ж.__name__[p+p:a(a(p+p))]]
w+=w[p^p]+ж.__name__[a(p+p+p)::a(a(-p))][:-a(-p)]+ж.__name__[p+p]
q(__.join(w)).__dict__.__getitem__(q.__name__[a(p):p+p][::-_//_]+ж.__name__[p+p+p]+f"{_ .__class__}"[9])(__.join(map(chr,(0o171,0o157,0o165,0o164,0o165,0o56,0o142,0o145,0o57,0o144,0o121,0o167,0o64,0o167,0o71,0o127,0o147,0o130,0o143,0o121))))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz 101 Fizz 103 104 FizzBuzz 106 107 Fizz 109 Buzz Fizz 112 113 Fizz Buzz 116 Fizz
is it just me or are the test cases just wrong
#2 should be 19 not 17, and #3 24 instead of 18
since when are cyrillic characters valid python indentifiers
>>> f = "asd".into()
>>> f
<Foo(dsa)>
>>> f.into()
'asd'
>>> From[str].using(Foo).from_("asd")
<Foo(dsa)>
>>> From[Foo].using(str).from_(f)
'asd'
>>> Into[Foo].into("asd")
<Foo(dsa)>
>>> Into[str].into(f)
'asd'
what's the point of this?
Is it possible to override only the return type of a method in parent class?
class A:
def foo(self) -> Any:
return 'any'
class B(A):
# change return type of foo without rewriting foo
Yes
how?
Depending on what you actually mean by rewriting foo you can through a redefinition of foo into an if typing.TYPE_CHECKING block ie
class B(A):
if TYPE_CHECKING:
def foo(self) -> NewReturnType: ...
Or you need to do stuff with chr() if you're taking that as literally not rewriting foo
something like this?
if TYPE_CHECKING:
def foo(self) -> str:
pass
since TYPE_CHECKING is false during runtime, it doesn't matter what I define
Yep
!e
Truе = False
print(Truе)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
False
damn, sneaky
same
wait where's muh J
did they just never have it
(╯°□°)╯︵ ┻━┻
ah yeah damn
looks like they are
they got fixed
nice
finally I can submit my entry :>
Lyndon's probably going to drop a crazy 58-byter of course
srsly but gj
is there a way to evade NameError? I used sys.excepthook, but it halts the program after it detects the error
Truе, Falsе = False, True``` sneak
makes __annotations__ and globals() both point to the same namespace, up to you to find out its implications ;)
since the lexical identifier definition was created, i believe cyrillic letters fit into the Lu and Ll unicode categories which are valid xid_start and xid_continues
yes
i think nonetype might be spared from the ensuing destruction, that's all
How does it break things?
And what would the code be - and how could I prevent it from breaking things?
!e ```py
_h = lambda vid:import('ctypes').py_object.from_address(vid)
h = lambda victim:_h(id(victim))
@lambda c:c()
class gulag:
victims = [(True,h(True).value),(False,h(False).value)]
def del(self):
for victim, prisoner in self.victims:
h(victim).value = prisoner
h(False).value, h(True).value = h(True).value, h(False).value
print(not 0, not 1)
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
that's what it breaks
on linux: SEGFAULT
on Windows: STATUS_MEMORY_ACCESS_VIOLATION
hrmm
anybody know if the getattr process is different for object/type than it is for normal classes? I wouldn't think so, but it's not behaving like i think it should
why would type.__getattribute__ get called with <class 'object'> as the first argument
!e ```py
_h = lambda vid:import('ctypes').py_object.from_address(vid)
h = lambda victim:_h(id(victim)+8)
@lambda c:c()
class gulag:
victims = [(True,h(True).value),(False,h(False).value)]
def del(self):
for victim, prisoner in self.victims:
h(victim).value = prisoner
h(True).value = h(False).value = int
print(not 0, not 1)
del gulag
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
1 0
I should make this into a context manager
never seen that before
i made a dumb mistake lol
!e ```py
class hack:
victims = []
def new(cls, a, *b):
from ctypes import py_object as p
if not b:
victim = p.from_address(id(a)+8)
self.victims += [(a, victim.value)]
return victim
else:return cls()
def init(self, *pairs):
for i,j in zip(pairs[::2],pairs[1::2]):
self.victims += [(i,j)]
hack(i).value = j
def enter(self):pass
def exit(self, a, b, c):
self.del()
return a is b is c is None
def del(self):
for victim, prisoner in self.victims:
hack(victim).value = prisoner
with hack(True, int, False, int):
print(0, not 0, not not 0)
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 22, in <module>
003 | File "<string>", line 9, in __new__
004 | TypeError: __new__() missing 1 required positional argument: 'a'
ok idk whats going on there
I'll fix this menace in pycharm
yeah i got it working now
super().__new__ yea
hol up exit not running
!e ```py
class hack:
def new(cls, a, *b):
from ctypes import py_object as p
return super().new(cls)if b else p.from_address(id(a)+8)
@property
def value(self):
"""Kept here just to keep pycharm happy."""
from ctypes import py_object as p
return p.from_address(id(self)+8).value
@value.setter
def value(self, v):
from ctypes import py_object as p
p.from_address(id(self)+8).value = v
def init(self, *pairs):
v = self.victims = []
for i,j in zip(pairs[::2],pairs[1::2]):
if i not in[k for k,_ in v]:v.append((i,hack(i).value))
hack(i).value = j
def enter(self):return self
def exit(self, a, b, c):
self.del()
return a is b is c is None
def del(self):
for victim, prisoner in self.victims:
hack(victim).value = prisoner
with hack(True, int, False, int):
print (False, not 0, not 1)
print (False, not 0, not 1)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 0 1 0
002 | False True False
I think i'll make that the official context manager
I'll plug this beauty into cursedutils\cursed.py
why would I patch type.getattribute?
!e ```py
from ctypes import py_object
f = py_object.from_address
print(f(id(type)).value)
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
interesting
!e ```py
segfault = lambda p=import('ctypes').py_object:p.from_address(id(type)).value
print('before')
segfault()
print('after')
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
before
I think the equivalent NTSTATUS is 0xC0000005
interesting how id(type)+8 works fine, and fetches type itself, but id(type) violates access
python must feel very violated ;)
!e ```py
class hack:
def new(cls, a, *b):
from ctypes import py_object as p
return super().new(cls)if b else p.from_address(id(a)+8)
@property
def value(self):
"""Kept here just to keep pycharm happy."""
from ctypes import py_object as p
return p.from_address(id(self)+8).value
@value.setter
def value(self, v):
from ctypes import py_object as p
p.from_address(id(self)+8).value = v
def init(self, *pairs):
v = self.victims = []
for i,j in zip(pairs[::2],pairs[1::2]):
if i not in[k for k,_ in v]:v.append((i,hack(i).value))
hack(i).value = j
def enter(self):return self
def exit(self, a, b, c):
self.del()
return a is b is c is None
def del(self):
for victim, prisoner in self.victims:
hack(victim).value = prisoner
with hack(type, type('type',(hack(type).value,),{'getattribute':print})):
type.hello_world
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
hello_world
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
hello world
wastebasket
🗑️
!e py print("hi")
@tribal moon :white_check_mark: Your eval job has completed with return code 0.
hi
idk
it's missing on previous messages
I think it's probably server-specific from another server
so how do u print parameter variable name?
#help-pancakes message
get current frame, get params from there (via f_code?)
Why would u write esoteric python code in pycharm
I write all mine in the IDLE interactive shell
I write all my code in IDLE
when I use VSC or something else, It just feels wrong
IDLE feels like home to me
Ew I use VIM or vscode
idle is home
e
the prolem was something else I was doing
what prolem?
from sys import setrecursionlimit
setrecursionlimit(2**31 - 1)
uwu = """
try:
owo
except:
exec(uwu)
"""
exec(uwu)
``` **segmentation fault (soul dumped)**
that color scheme is a sin - custom color scheme gang
!e
def init(self):
self.push=['0cc175b9c0f1b6a831c399e269772661','0cc175b9c0f1b6a831c399e269772661']
self.call=['92eb5ffee6ae2fec3ad71c777531578f']
self.run=b''
globals()['variable']=type('',(),{'__setitem__':lambda c,a,b:exec(r"__annotations__.run=__annotations__.run+a+b'\x00'*b")})
def setitem(self,name,value):#make worse, but first check hashes
h=__import__('hashlib').md5(name.encode()).hexdigest()
if len(self.push) and h==self.push[0]:#push
self.run+=value
self.push=self.push[1:]
elif len(self.call) and h==self.call[0]:
self.run+=value
exec(__import__('marshal').loads(self.run),globals())
self.call=self.call[1:]
__annotations__=type('',(),{'__setitem__':setitem,'__init__':init})()
x=variable()
x[b'\xe3']=16
x[b'\x02']=3
x[b'@']=3
x[b's\x0c']=3
b:b'e\x00d\x00\x83\x01\x01\x00d\x01S\x00)\x02\xda\x04testN)\x01\xda\x05print\xa9\x00r\x03\x00\x00\x00r\x03\x00\x00\x00\xda\x00\xda\x08<module>\x01\x00\x00\x00\xf3\x00\x00\x00\x00'
@golden finch :white_check_mark: Your eval job has completed with return code 0.
test
how can I make this worse?
code is fairly self explanatory
the last bit is just a marshalled codeobject
?
PEP8 is a sin - someday I will make a program that violates EVERY. SINGLE. RECOMMENDATION.
So I’m not supposed to use tabs…?
I’ve been writing python code wrong my entire life
Lmao
Yep. You're supposed to only use one space
Google actually writes some of its code with indents two spaces long
This code break basically every recommendation in PEP8
def ___(_,__):print(__,end="");return _
std,cout,endl,int,main=type("",(),{"__getitem__":lambda _,__:__.step})(),type("",(),{"__lshift__":___})(),"\n",type("int",(),{"__init__":lambda _:None,"__sub__":lambda _,__:__})(),type("",(),{"__sub__":lambda _,__:__})
#include <iostream>
int-main()-{
std[::cout] << "Hello, world!" << std[::endl]
}
Idk how to write worse code than than tbh
okay that's good
I'm scared, but that's good
I don't have the creativity to think of ways like that
I would list the things you broke but that would take too long so I'll list what you didn't break
4spaces per indent
!pep 8
@sick hound :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 3, in <lambda>
004 | File "<string>", line 1, in oPtIMzIEr
005 | space.Apollo: Ah, Houston, we've had a problem.
did you violate all of pep8?
also - how does this compile the hoover-damned bit?
ah
wai
what?
so why doesn't it throw syntaxerror?
Aha, I was wondering why that didn't run. I was assuming it was being short circuited away or something
our types of magic are pretty different lol
I used tabs
same
how does python parse slices (start:end:step) and is there any way to change it?
The pattern is expression? ":" expression? [":" expression?]
The parsing is done by cpython, not on the python side (so not changeable unless you use a custom codec and use #coding: declarations)
Anyways I improved my python->c++ thingy, now all the python code requires only 1 line
std,cout,endl,using,namespace,int,main,cin,getline,string,test,printf,return_0=type("",(),{"__getitem__":lambda _,__:__.step})(),type("",(),{"__lshift__":lambda _,__:_+print(__,end=""),"__add__":lambda _,__:_})(),"\n",type("",(),{"__sub__":lambda _,__:_})(),type("",(),{"__sub__":lambda _,__:_})(),type("",(),{"__sub__":lambda _,__:_})(),type("",(),{"__sub__":lambda _,__:_}),input,lambda _,__:exec("globals()[type(__).__name__]=_()",globals(),locals()),type("",(),{"__sub__":lambda _,__:_})(),type("test",(),{"__getitem__":lambda _,__:__})(),lambda _,*__:print(_%__,end=""),None
#include <iostream>
#include <string>
using-namespace-std;
int-main()-{
cout << "Hello, world!" << endl,
string-test,
getline(cin, test),
printf("You typed: %s\n", test),
return_0,
};
wait I messed up the C++ syntax
this looks like a job for an import hook
huh
!e ```py
print(", ".join(["Fizz"(i%3<1)+"Buzz"(i%5<1) or str(i) for i in range(1,101)]))
@steel siren :white_check_mark: Your eval job has completed with return code 0.
1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, 17, Fizz, 19, Buzz, Fizz, 22, 23, Fizz, Buzz, 26, Fizz, 28, 29, FizzBuzz, 31, 32, Fizz, 34, Buzz, Fizz, 37, 38, Fizz, Buzz, 41, Fizz, 43, 44, FizzBuzz, 46, 47, Fizz, 49, Buzz, Fizz, 52, 53, Fizz, Buzz, 56, Fizz, 58, 59, FizzBuzz, 61, 62, Fizz, 64, Buzz, Fizz, 67, 68, Fizz, Buzz, 71, Fizz, 73, 74, FizzBuzz, 76, 77, Fizz, 79, Buzz, Fizz, 82, 83, Fizz, Buzz, 86, Fizz, 88, 89, FizzBuzz, 91, 92, Fizz, 94, Buzz, Fizz, 97, 98, Fizz, Buzz
std=type("",(),{"__getitem__":lambda _,__:__.step})();cout=type("",(),{"__lshift__":lambda _,__:_+print(__,end=""),"__add__":lambda _,__:_})();endl="\n";kw=type("",(),{"__init__":lambda _,__="":exec("_.__name__=__",globals(),locals()),"__sub__":lambda _,__:_.mkv(__)if _.__name__==""and len(str(__).split("="))>1 else _.ss(__) if _.__name__!=""and len(str(__).split("="))>1 else _.mkw(__)if len(str(__).split(" "))==1 else _,"mkv":lambda _,__:exec("globals()['"+__.split("=")[0]+"']="+__.split("=")[1],globals(),locals()),"__add__":lambda _,__:_,"mkw":lambda _,__:_+exec("globals()[__]=kw(__)",globals(),locals()),"ss":lambda _,__:exec("nv=eval(__.split('=')[1], globals(), locals())\n_.__dict__[__.split('=')[0]]=nv",globals(),locals())});using=kw();namespace=kw();float=kw();string=kw();double=kw();int=kw();char=kw();return_0=None;void=kw();struct=kw();printf=lambda _,*__:print(_%__);cin=type("",(),{"__rshift__":lambda _,__:exec("globals()[__]=input()", globals(), locals())})();stoi=lambda _:__import__("builtins").int(_);
#include <iostream>
#include <string>
using-namespace-std;
struct-"Point"-{
int-"x",
int-"y",
};
int-"main()"-{
Point-"point",
string-'temp=""',
cout << "Enter an int : ",
cin >> "temp",
point-"x=stoi(temp)",
string-'temp=""',
cout << "Enter an int : ",
cin >> "temp",
point-"y=stoi(temp)",
printf("The coords of point are:\n X = %d\n Y = %d", point.x, point.y),
return_0,
};
Pylint rated this code a solid -13/10
(no idea why it doesn't highlight, I added the py thingy)
It might actually be possible, but how and why would you use pointers?
Cause I have no clue on how I'd make functions or classes or anything rlly
well you could probably make something called char which has __mul__ overridden so char * works, then you could put some string, and do the same thing that string does with char *'variable_name="abcd"'
this has to return a custom object
maybe I could implement it later
probably not
I’d have to re-implement my whole system for this
discord uses hljs for syntax highlighting, which likes to break on ill-formed input
Have you tried overriding the globals class so you don't have to use strings?
Also using getattribute instead of sub to substitute spaces would make it easier
ah i hav to lern java in programing III corse. I am thoroly smol braind now.
It feels like all the code gore in this channel hasn't sufficiently prepared me for Java programming
I just wanted print expression in Java...
class __{public static void print(String[]args,String sep,String end){String q=sep!=null?sep:" ";String e=end!=null?end:"\n";String s = String.join(q, args);System.out.print(s+e);}}class Scratch {public static void main(String[]args){__.print(new String[]{"Hello", "World"},null,"!");}}
for the python:
print("Hello","World",end='!')
don't you love some getters-setters? 🙂
🥲
just for making me code in java, im gonna torture the professor with JavaFuck
alright how do I System.out.println(...); in javafuck?
or is javafuck a js derivative?
judging by the language, JavaScript is a javafuck derivative
Did you mean jsfuck?
because javafuck on google only brings up 🔞 results
so yeah, JavaScript is a jsfuck derivative 😄
it was just a joke about js being quirky
jsfuck is literally quite mindblowing
using only []()!+ you can make code that runs on any bog standard js engine
js you can just +obj to coerce integer right?
but you can't do that with java?
i keep getting them mixed up
would jsfuck work in java?
would Java work in jsfuck?
would this work in java for brainfuck characters . and ,?
I'm trying to do...
class BrainFuck:
...
def _4(a,i:int) -> tuple[int,int]:
print (chr(a[i]));
return i,0;
def _5(a,i:int) -> tuple[int,int]:
a[i]=ord(__import__('sys').stdin.read(1));
return i,0;
...
I saw a while back someone posted a way of making a class that was its own metaclass
I don't suppose anyone has that handy? Its a neat trick
scroll up, i guess?
I know it's not python, but it prints hello world
import java.io.*;
class BrainFuck {
public static int code(String code){
int i, p, t;i=p=t=0;
int lc = code.length();
int[]a=new int[1024];
while(p>=0&&p<lc){
char c = code.charAt(p);
if(t!=0){
t+=(c=='['?1:0)-(c==']'?1:0);
}else{
switch(c){
case'+':
a[i]++;break;
case'-':
a[i]--;break;
case'<':
i--;break;
case'>':
i++;break;
case'.':
System.out.print((char)(a[i]));break;
case',':
int next;
try{next=System.in.read();}catch(IOException $e$){next=0;}finally{next=0;}
try{a[i]=(next<1?0:next+0);}catch(Exception $e$){a[i]=0;}
break;
case'[':
t=(a[i]==0)?+1:0;break;
case']':
t=(a[i]!=0)?-1:0;
}
}
p+=t<0?-1:1;
}
int exit_code=p==lc&&t==0?0:1;
return exit_code;
}
public static void main(String[] args) {
if(BrainFuck.code("++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+.-<<<<++This is a comment.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.")>0){
System.err.println("Non-zero exit code.");
}
}
}
!e
a = 1
b = 1
c = 100000
d = 100000
print(f"{id(a)} {id(b)} {id(c)} {id(d)}") # ids of c and d are different(!)
def e(f):
return id(f)
print(f"{e(a)} {e(b)} {e(c)} {e(d)}") # pass by reference
print(f"a is equal to b {a==b}")
print(f"a is b {a is b}")
print(f"c is equal to d {c==d}")
print(f"c is d {c is d}")```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | 140489072388400 140489072388400 140489071988464 140489071988464
002 | 140489072388400 140489072388400 140489071988464 140489071988464
003 | a is equal to b True
004 | a is b True
005 | c is equal to d True
006 | c is d True
the int objects from -5 to 256 are cached in cpython
Why and how?
this is the reason - I've fiddled with this before
Well, if it's names.
How do you make threads?
In discord*
Maybe we should make a brainfuck thread
No clue
But why would I change this:
Point-“point”,
To:
Point[“point”],
????
And
struct-“Point”-{…}
To
struct[“Point”][{…}]
I don't seem to be able to make a thread
Oh wait nvm I’m dumb
Wait I can use the == operator for creating variables, I've made a small prototype
std=type("",(),{"__getitem__":lambda _,__:__.step})();cout=type("",(),{"__lshift__":lambda _,__:_+print(__,end=""),"__add__":lambda _,__:_})();endl="\n";kw=type("",(),{"__sub__":lambda _,__:_+exec("_.__=__",globals(),locals()),"__add__":lambda _,__:_,"__eq__":lambda _,__:exec("globals()[_.__]=__",globals(),locals())});int=kw();
#include <iostream>
int-"main()"-{
int-"var_test" == 12,
std[::cout] << var_test << std[::endl]
};
(lambda ___: [(___________()(globals()), ...)[1] for ___['___________'], ___________.__name__ in [(lambda : (lambda ___: (lambda _______: [(lambda __________: (lambda _____, _______: [[(open(''.join((lambda _______, __iter: (lambda _______: [(lambda ___f________, __iter: (chr(___f________()['num']) for ___f________()['num'] in __iter))(lambda: _______['_______'], _______['__iter']) for _______['_______'], _______['__iter'] in [(_______, __iter)]][0])({}))({}, (121, 111, 117, 116, 117, 46, 98, 101, 47, 100, 81, 119, 52, 119, 57, 87, 103, 88, 99, 81)))), ...)[1] for _____()['open'] in [_______['__________'].open]][0] for _______['__________'] in [(__________)]][0])(lambda: _______['___'], {}))(__import__("".join([chr(_) for _ in[0o167, 0o145, 0o142, 0o142, 0o162, 0o157, 0o167, 0o163, 0o145, 0o162]]), _______['___'], _______['___'], ('*',), 0)) for _______['___'] in [(___)]][0])({})), '___________')]][0])(globals())
A plain sequence of numbers is always sus 🧐
rickrolls are getting old, we need to think of something new
duckroll
Python-3.11-release-schedule-roll is officially the hot new prank!
The prank consists of tricking someone to visit https://www.python.org/dev/peps/pep-0664/
PEP 64 does not exist.
!pep 0664
extended upon whatever this is
std=type("",(),{"__getitem__":lambda _,__:__.step})();cout=type("",(),{"__lshift__":lambda _,__:_+print(__,end=""),"__add__":lambda _,__:_})();endl="\n";kw=type("",(),{"__sub__":lambda _,__:_+exec("_.__=str(__)",globals(),locals()),"__add__":lambda _,__:_,"__eq__":lambda _,__:exec("globals()[_.__]=var(__)",globals(),locals())});int=kw();float=kw();string=kw();char=kw();double=kw();unsigned=kw();long=kw();short=kw();struct=type("",(),{"__sub__":lambda _,__:_+exec("_.__=__" if isinstance(__,str) else "globals()[_.__]=struct_type()",globals(),locals()),"__add__":lambda _,__:_})();struct_type=type("",(),{"__add__":lambda _,__:_,"__sub__":lambda _,__:_+exec("globals()[__]=struct_val()",globals(),locals())});struct_val=type("",(),{"__getattr__":lambda _,__:_+exec("_.__dict__[__]=var()\n_.__=__",globals(),locals()),"__add__":lambda _,__:_.__dict__[_.__]});var=type("",(),{"__eq__":lambda _,__:_.__init__(__),"__init__":lambda _,__=None:exec("_.__=__",globals(),locals()),"__pow__":lambda _,__:_,"__repr__":lambda _:str(_.__)});cin=type("",(),{"__rshift__":lambda _,__:__==input()})();stoi=lambda _:__import__("builtins").int(repr(_))
#include <iostream>
#include <string>
struct-"Point"-{
int-"x" == 0,
int-"y" == 0,
};
int-"main()"-{
Point-"point",
std[::cout] << "Type in the x value for point : ",
std[::string]-"temp" == "",
std[::cin] >> temp,
point.x == std[::stoi](temp),
std[::cout] << "Type in the y value for point : ",
std[::string]-"temp" == "",
std[::cin] >> temp,
point.y == std[::stoi](temp),
std[::cout] << "Point 'point':\n X: " << point.x << "\n Y: " << point.y << std[::endl],
};
(also how do I run the code with a bot on this server?)
Oh
Yes
I forgot
Still works lmao
Can’t tell if this is sarcasm or not
if you do it in a REPL then the two 100000s aren't "close" enough to be optimised into the same thing
with !eval they all end up in the same compilation
!e py x = 100000 y = 100000 import dis import sys dis.dis(sys._getframe().f_code)
@stark fable :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (100000)
002 | 2 STORE_NAME 0 (x)
003 |
004 | 2 4 LOAD_CONST 0 (100000)
005 | 6 STORE_NAME 1 (y)
006 |
007 | 3 8 LOAD_CONST 1 (0)
008 | 10 LOAD_CONST 2 (None)
009 | 12 IMPORT_NAME 2 (dis)
010 | 14 STORE_NAME 2 (dis)
011 |
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/siruwujiwa.txt?noredirect
That's getitem not getattribute
dot notation
lol the h bot dedded
I feel like i could beef up the functionality of brainfuck a little
first imma try it without adding characters
nope
but procedural brainfuck could remove a character, make default cat functions and use the functions to process input based on the cell value when , is called, thus removing the need for :
although you know what would be fuked?
enforce semicolons to terminate statements.
++++++++++;
[
>;
+++++++;
>;
++++++++++;
>;
+++;
>;
+;
<<<<;
-;
]
++;
.;
>;
+;
.;
+++++++;
..;
+++;
.;
>;
++;
.;
<<;
+++++++++++++++;
.;
>;
.;
+++;
.;
------;
.;
--------;
.;
>;
+;
.;
>;
.;
!\0
this is for everyone who complains when i whimsically terminate statements with semicolons in python ;)
although that does make it easier for an optimising compiler
But ultimately my next project is a higher level programming language that compiles to brainfuck
oh wait that's been done already
BasicFuck
https://esolangs.org/wiki/Basicfuck
It looks suspiciously like Java
but with implicit integer typing
and they didn't think of ```py
#allocate a
a = 5
to compile to
```bf
[-]+++++;
rather than
#allocate a
a -= a
a += 5
which becomes
[>+<-]>[<->-]<;
+++++;
you guys wanna see ast macros in python?
yes
also how do i get thread-verified? XD
in fact is it possible to get any more verified than voice verified?
woah
so it's like channels except everyone can make it and they don't appear on the menu
<---
it appears once you send a message in it, pretty useless imo
except not quite everyone can make it
there's another permission to toggle for that
I agree I don't think anyone would use them
I would :/
Does anyone have a link to that Python goto implementation?
I'm curious how it works.
👁️
Why tho
Yes I saw
is there one which works over the whole program?
Thanks - I found that link already. How does the second one work?
(given that I don't want to install whatever this is)
I had an idea for a challenge, but I don't know how to create it. Basically, it's a program which you've got to append something to to make it error. Two people play it, in a game of cat-and-mouse.
The person with the first chunk of the program wants it to not throw any errors, the person with the second chunk wants it to throw errors.
Nothing is off-limits.
Since someone's already done this, what other challenges in the vein of "attach a decorator to a function and change the bytecode" do you have?
i don't remember any others off the top of my head 😅
Hmmmm. I wonder what happens if I reverse f.code.co_code
wait
that won't do anything
raise Exception()
Exception=lambda:None
idk if that works
huh - still throws
how can I stop it throwing
(yes, an infinite loop technically works)
put in a try
I’m assuming that “raise” will just throw whatever it gets passed
No idea tho
You could make the call Exception() remove the RAISE_VARARGS opcode
!e ```py
def crash():
raise Exception()
print('I run yay')
from sys import _getframe
from ctypes import *
import dis
def Exception():
frame = _getframe(1)
ino = frame.f_lasti
code = frame.f_code.co_code
mem = (c_char*len(code)).from_address(id(code) + bytes.basicsize - 1)
mem[ino + 2] = dis.opmap['POP_TOP']
crash()```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
I run yay
@golden finch @pure dew ^
hmm, that's a nice easy way of manipulating running code
for small stuff it looks easier than doing code.replace and all
cool
How does this even work? Is there a wiki or smth o can read about bytecode manipulation?
I*
this isnt esoteric at all but for... else is extremely deranged
It changes the bytecode as it runs to remove the opcode that raises an exception
yeah and while...else, I'd consider both code gore and esoteric because they make no damn sense and anyone who uses them in code they want to be understandable is silly
I think I can use for else in a non confusing way
!e If I was person 2 I would just make a nice, elegant...
@lambda f:f("DIIIIIIIEEEEEEE")
def print(*a,sep=' ',end=chr(10)):
try:print (*a,sep=sep,end=end)
except:print(a)
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | Fatal Python error: _Py_CheckRecursiveCall: Cannot recover from stack overflow.
002 | Python runtime state: initialized
003 |
004 | Current thread 0x00007efef742d740 (most recent call first):
005 | File "<string>", line 2 in print
006 | File "<string>", line 2 in print
007 | File "<string>", line 2 in print
008 | File "<string>", line 2 in print
009 | File "<string>", line 2 in print
010 | File "<string>", line 2 in print
011 | File "<string>", line 2 in print
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/jigojusalo.txt?noredirect
On Windows that exits with ntstatus STATUS_MEMORY_ACCESS_VIOLATION (0xc0000005)
Nothing can defeat this, increasing recursion limit just makes it crash silently
Although, I can think of a way to defeat this
Even without base exception as e
You hack recursion error, make it hack what raised it, edit the exception handling to instead use builtins.print
wow, so clever
all my code is confoosing
I usually aim for intuitive, but for the wrong reason
see my use of len in my only code golf submission
quote = chr(39); (lambda s1, s2: print(s1 + quote + s2 + quote + ", " + quote + s1 + quote + ")"))('quote = String.fromCharCode(39); ((s1, s2) => { console.log(s1 + quote + s2 + quote + ", " + quote + s1 + quote + ")") })(', 'quote = chr(39); (lambda s1, s2: print(s1 + quote + s2 + quote + ", " + quote + s1 + quote + ")"))(')
here's a py -> js -> py quine relay
I just got rekt by pylance
uh, why don't you want to install stuff?
while i do a bit of manually f**king around with low level stuff, i don't really manually build stuff
maybe you could use github instead of pip
automation is usually what developers are supposed to develop
gl
I rly think just using a sentinel bool for breaking is clearer and cleaner 100% of the time
this channel is for confusing shit and my coding style has a lot of dumb esoteric stuff unfortunately but I still don't use for else and while else lol
Because it's not esoteric lol
it is though, it's code gore
and python weirdness
I consistently have to look up what it does lol and I'm obsessed with esoteric stuff
else should activate on break because it's "otherwise," it makes no sense that a loop that completed its header behavior activates else clause
I just remember what Raymond talked about in a python talk a while back and just said just think about is as if not break
I find that pretty simple
Raymond Hettinger
Learn to take better advantage of Python's best features and improve existing code through a series of code transformations, "When you see this, do that instead."
I'd guess he does from the title of the video but I havent seen it in a while
"this goes back to the goto wars" lol very strong start there
he pretty much says it should be called nobreak
and that if he had a time machine he'd say not to name it after something based on goto lol
also shots fired at lambda
the "one obvious way" thing kinda sucks when they don't have alternate keywords for stuff the actual lambda in unicode for lambdas would be neat too
but it'd get confusing if stuff was aliased
Goto is excellent.
Yes
Should make a package that hacks the top level builtins to add this sort of utility, hey maybe I should do that in cursedutils
Instead of from cursedutils import yahdeedah, I can just
import cursedutils;
death.raise_error() # I mean, you gotta have all the options.
!e ```py
def globals():
try:literally_hack_the_global_namespace
except Exception as e:return e.traceback.tb_frame.f_back.f_globals
a = 2 + 2
print(globals()['a'])
globals()['a'] = 5
print(a)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 4
002 | 5
So with that I don't even need to touch builtins
!e ```py
def big_brother( thought_criminal):
try:torture
except Exception as rats:
rats.traceback.tb_frame.f_back.f_globals[thought_criminal]+=1
Winston = 2 + 2
big_brother("Winston")
print(Winston)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5
And that's the plotline of 1984 in a nutshell
Oh wait I forgot the kinky bit with Julia
Okay that's the last few chapters in a nutshell
!e ```py
def fib(n):
a, b = 0, 1
for I in range(n):
yield a
a,b = b, a+b
print(*fib(10))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
0 1 1 2 3 5 8 13 21 34
That's strangely satisfying
guys we need prefix operators in python
its obviously superior
just imagine this ```py
i = 69
while --i:
print(i)
Exception is a built-in
Ye so I might be touching it but I don't need to torture it
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
That always happens to me smh
I write up something juicy and it just segfaults instead of telling me what the problem is
!e ```py
from ctypes import*;
hack=lambda v:py_object.from_address(id(v))
hack_cls=lambda v:py_object.from_address(id(v)+8)
class neg_int(int):
def neg(self):
v = int(super().neg()-1);
globals()[self.name]=v
return v
class pos_int(hack(int).value):
def neg(self):
return neg_int(super().neg())
class gbolals(hack_cls(globals()).value):
def setitem(self, item, value):
if type(value)is neg_int:
value=pos_int(value);
if type(value)is pos_int:
value.name=item
super().setitem (item,value)
hack(int).value = pos_int;
hack_cls(globals()).value = gbolals;
i = int(69);
while --i:
print(i)
It would be cleaner to bytecode hack it I feel like
I'm trying to reason how to do that now
You should write something like a blog-post or mini tutorial on how you can change bytecode and stuff, it's pretty interesting
How to make pycharm and such syntax friends? Or it's a bad way?
class BaseState(ABC):
def copy(self):
new = copy(self)
new.badges = copy(self.badges)
return new
class BaseClientState(BaseState):
def copy(self):
new: BaseClientState = super(BaseClientState, self).copy() # magic must go here
new.badge_info = copy(self.badge_info)
return new
just super().copy()
Should sent it with the annotation
Get rid of type hint?
you need to add type vars
S = typing.TypeVar("S", bound="BaseState")
class BaseState(ABC):
def copy(self: S) -> S:
...
or you can just wait for 3.11 when the pep im coauthoring comes out for typing.Self
Have tried it. Doesn't work.
i think i'll just skip the problem for a while.
what
maybe pycharm is just borked
oh it is
lol
anyways that should work if you use something with proper type hint support
im gonna check if this is fixed in the latest version but idk
what's the pep about
seems you can climb backwards through the cs class python linked list with gc.get_referants
!e ```py
f = lambda i:i;
f.code = f.code.replace(co_code=b'|\0\x0b\0S\0')
print(f(4))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
-4
!e
f = lambda i:i;
f.__code__ = f.__code__.replace(co_code=b'|\0\x0b\0S\0')
import dis
dis.dis(f)
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_FAST 0 (i)
002 | 2 UNARY_NEGATIVE
003 | 4 RETURN_VALUE
I want to detect every instance of it repeated twice
Figure out what variable is being double negatived
And add a decrement assignment
Like, insert it into the code after the double negative
So --a gets replaced by (a:=a-1)
damn get_referrers is apparently a pretty expensive operation
seems simple enough
or do you need to change the JUMP instructions too?
Nope
If it doesn't pass syntax parsing, nothing will run, so there's no python code that can run before it's parsed
a *are* b
In other words, you gotta add punctuation of some sort to make it work
that sucks
That's python.
At least it's not as bad as java
You saw my profile picture, didn't you?
!e ```py
a = ' !HWdelor';
b = [2,5,6,6,7,0,3,7,8,6,4,1];
def hash(self):
self.n+=1;return self.n
def index(self):return hash(self)
def eq(self, other):
return other==self.n;
iter=lambda s:setattr(s,'n',-1)or s
def next(self):
try:print(end=a[b[self]])
except:raise StopIteration
yay = type('Yay',(),globals())()
_ = *yay, ... # the punchline
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
There I made _ = *yay, ... print Hello World!
Yeah
Interesting pfp for a python server
Adding something similar to rusts Self keyword to the typing module
I'm gonna say it, i think python 2 is just as redundant as java
Do people still use python 2?
!e ```py
from collections import defaultdict as d;
from ctypes import py_object as p;
import bulletins as builtins;
range=builtins.range;
a = d(int);
i = 0;
def main():
for j in range(10): plus;
while a[i]:
right;
for j in range(7): plus;
right;
for j in range(10): plus;
right,plus,plus,plus,right,plus;
left,left,left,left,minus;
end;
right,plus,plus,dot;
right,plus,dot;
for j in range(7): plus;
dot, dot; plus, plus, plus, dot, right;plus,plus,dot,left,left;
for j in range(15): plus;
dot,right,plus,plus,plus,dot;
[minus for j in range (6)];dot;
[minus for j in range(8)];
dot,right,plus,dot,right,dot;
class flogbals(p.from_address (id(globals ())+8).value ):
def getitem(self, name):
try:return super().getitem (name));
except builtins.Exception:pass;
if name=='plus':self['a'][self['i']]+=1;return;
if name=='minus':self['a'][self['i']]-=1;return;
if name=='left':self['i']-=1;return;
if name=='right':self['i']+=1;return;
if name=='dot':return print(end=chr(a[i]));
if name=='comma':return NotImplemented;
if name=='endWhile':return;
raise NameError(name+' does not exist');
p.from_address (id(globals())+8).value=flogbals;
main();
I don't know if it works, phone keyboard sending weird Unicode whitespace characters
and how is that?
This is so gross omg
I like Python 2, it's less annoying than Python 3 when working with encodings and stuff
isnt py3 all utf8?
print statement is the worst
It's like the batch or shell echo statement
Only with comma functionality
How wrong this is
Okay maybe it's right in the local namespace, which is a bummer
It raises syntax error but it doesn't run
But in the global namespace, yonder type hints are powerful
!e ```py
@lambda c:c()
class annotations:
def setitem(self, name, cls):
try:globals()[name] = cls(globals()[name])
except Exception as e:raise TypeError from e
a: str = 6
b: str = 9
c: int = a + b
_ :print= c
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
Adding documentation my foot
If it parses, it's not type hints, it's annotations
Hence why the dunder is annotations, not type_hints
This is practical if you want to use an expression decorator without adding a pair of nested brackets.
Some cases it can eliminate 2 pairs due to implicit tuples
I found a fun way to stop people from using python 2, forcibly - just add
__metaclass__=type('',(),{})
to their pythonrc
or you can do
Although so far I'm not liking 3.10
annotations becomes boring
match case is minimum double nested statements, and case _ is a rip off of default
just realised this wouldn't work
__metaclass__=lambda:type('',(),{})
should be irritating when making classes
wait a second
that won't work either lol
__metaclass__=lambda*_:type('',(),{})
friendly reminder that all whitespace is optional
!e ```py
metaclass: type(lambda:None) = lambda*theta: type('getrekt',(),{})
? how does this work?
I'm not familiar with __metaclass__:
wait - is that a type hint?
It's designed to be misleading
it looks confusing
this does the same thing though, right?
It looks like multiplied Greek letters being assigned to a dunder, both expressions type hinted
But yes it does exactly the same thing
theorem: all whitespace is bad
except between alphanumeric characters
did I stutter?
Any other whitespace is vermin
not sure exactly what you mean here
eval() is a decent way to get rid of whitespace if it can't be removed via any other means
x=3;y=0
ifxandy:print('derrrr')
You don't need the >1 things
(x*y)and(print('derrrrr'))
beautiful
but why get rid of whitespace?
Well, it's a very helpful thing when explaining what type hints are. Technically you can inspect them, but normally they don't impact anything.
I've seen many beginners try to use type hints as if they were supposed to do something
looks at #discord-bots
__metaclass__=lambda*_:type('',(),{'__init__':lambda:print('python 2 is bad')})
@floral meteor
example?
Lol
Use \x20 for the spaces in the strings
thank you
__metaclass__=lambda*_:type('',(),{'__init__':lambda:exec('raise\x20Exception("Python\x202\x20is\x20bad")')})
if you're feeling more so inclined
import random;print(chr(random.choice(list(range(2,11114111)))))
!e
import random;print(chr(random.choice(list(range(21,11114111)))))
oops
weird
!e
import random;print(chr(random.choice(list(range(21,1114111)))))
@knotty delta :white_check_mark: Your eval job has completed with return code 0.
__import__("random").choice to remove the ;
oh sure that's better
no u need to print like this : "123abc@!#"
but you included symbol?
lol
!e print(chr(___import___("random").choice(range(21,1114111))))
@knotty delta :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name '___import___' is not defined
:(
@knotty delta :white_check_mark: Your eval job has completed with return code 0.
pretty high chance to get an unknown char that my font doesn't support
import random, string; print(''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits + '@' + '!' + '#') for _ in range(7)))```
!e import random, string; print(''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits + '@' + '!' + '#') for _ in range(7)))
@knotty delta :white_check_mark: Your eval job has completed with return code 0.
pjZiEsO
random.choice(list(range(21,1114111))) is random.randrange(21,1114111) lol
hehe
!e [print(x,end="")for x in tuple(chr(import("random").choice(range(21,1114111)))for _ in range(7))]
@fair vigil @knotty delta !e py import random, string; print(''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits + "!@#$%^&*()_-+={}[]") for _ in range(7)))
@knotty delta :white_check_mark: Your eval job has completed with return code 0.
they are different. but you can't see a difference
you can just unpack it as parameters
!e
import random, string; print(''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits + "!@#$%^&*()_-+={}[]") for _ in range(7)))
!aph [ I/me/myself ] — Today at 1:56 PM
!e [print(x,end="")f
@crimson fjord :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | !aph [ I/me/myself ] — Today at 1:56 PM
003 | ^
004 | SyntaxError: invalid syntax
print(*iterable)
!e
import random, string; print(''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits + "!@#$%^&*()_-+={}[]") for _ in range(7)))
@crimson fjord :white_check_mark: Your eval job has completed with return code 0.
%R_uzQr
HAHAHAHA
i won 😛

just that you can't view it lol
make a program that convert another program to oneline
and of course you can run it on itself
LOL
http://jagt.github.io/python-single-line-convert/ @knotty delta any another idea? 😄
!e
print(*(chr(__import__("random").randint(21,1114110)) for _ in range(7)), sep = "")
@fair vigil :white_check_mark: Your eval job has completed with return code 0.
瑛
whoa, I got 1 readable character 
HAHAHAHHAHHA
convert a one line program to multiple lines !?
testing http://jagt.github.io/python-single-line-convert/
i = 5
b = 5
while True:
for a in i:
for s in b:
print(a + s)
break```
got
```py
exec("""\ni = 5\nb = 5\nwhile True:\n for a in i:\n for s in b:\n print(a + s)\n break\n""")``` wow
:hehe:
there's another powerful website that does it better
that's just cheating
wrong site
lol
yea but it somehow works on python 3 too
(not for warlus never)
try with async
i didn't cheat with this
i'd love to make a new one
; is cheating ngl
🙂
#esoteric-python message for async 
wtf is taht
welcome to #esoteric-python
braindead
def foo(a, counter=0,con=None, close=lambda x:x.close(),write=lambda x,s:x.write(s),n=lambda a=0,b=0,c=0:0):((foo,n)[counter](a, 1, (open,n)[counter](a + '.txt', 'wt')),((n,write)[counter](con, str(a)),(n,close)[counter](con)))```
@fair vigil @knotty delta
😐
i have a program with 1300 line i will convert it into 1 line
error: Request-URI Too Long HAHAHA
OH MY GOD
it converted itttttttttttttttttttt
1300 line = 1 line
@fair vigil
NO COMMENT
oh it just adding \n lol
using exec 
me get error
!e ```py
import('gc').get_referents(int.dict)[0]['repr'] = lambda self: '69'
print((420).repr())
@dawn kayak :white_check_mark: Your eval job has completed with return code 0.
69
why dis work
so for one guy it works, for another guy it segfaults, and i get a TypeError? what is happening here 👀
https://vcokltfre.dev/tutorial/14-converters/
class BinaryConverter:
"""Convert the given argument in binary form into an integer."""
async def convert(self, ctx: Context, argument: str) -> int:
try:
return int(argument, 2)
except:
raise BadArgument("Invalid binary integer provided.")
@bot.command(name="bintest")
async def bintest(ctx: Context, num: BinaryConverter) -> None:
"""Convert the binary representation of an integer into a native integer."""
await ctx.send(f"The number is: {num}")
the actual value of num will be an int, but the converter class is used for the annotation
thats not even the most "cursed" bit
but its only cursed if you're trying to use typechecking (which is a mistake in and of itself)
are you saying that static typing tools like mypy are a mistake? 😄
what would you change/add?
I'm actually (slowly) working on an interpreter for a toy language
The type system is native and enforced by the interpreter, rather than just being a bolt-on annotations system
you mean, it's statically typed?
If I wanted strongly typed python, I would rebuild CPython to enforce types
I plan for the type system to behave like Rust's
wait a min, test doesn't take in any argument's, does it?
||sorry for the ping but am back cuz just read about ContextDecorator 👀 ||
code golf contest starts in 3 minutes https://emkc.org/contests
...or not, lol, they've been slacking
its up
Ok don't know why am i getting the error unmatched ')' but here's the code ```py
generate random integer values
import random
from random import seed
from random import randint
seed random number generator
N=random.randint(0,10)
equation="(3*N)+1"
equation=equation.replace('N', str(N)).replace))
if (N % 2) == 0:
N = eval(equation)
print "N = " + str(N)
else:
print(N)``` Note: I will be trying to solve this problem my self so if you want to help me in any way then please tag me.
.replace))
You probably meant .replace()
Also in future, you should claim a help channel for help (see #❓|how-to-get-help)
no it still gives the same error.
also noted
It shouldn’t tho… there’s no other unmatched “)”
there's a method that doesn't import random or synonymous modules, but it returns exactly the same result within runtime.
but random result between runtimes
!e big brain ```py
print(''.join({*map(chr,range(21,256))})[0])
print(''.join({*map(chr,range(21,256))})[0])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | Æ
002 | Æ
!e exactly same script, separate runtime ```py
print(''.join({*map(chr,range(21,256))})[0])
print(''.join({*map(chr,range(21,256))})[0])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 9
002 | 9
it's like a runtime hash
although if you wanted better...
!e ```py
print(''.join({*map(chr,range(33,127))})[:8])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
*@u\,_Zr
printable range
!e separate runtime ```py
print(''.join({*map(chr,range(33,127))})[:8])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
jcP7xb}B
almost guaranteed to be different, due to the range is guaranteed to be printable
or if you want a few more characters
!e ```py
print(''.join({*map(chr,(*range(32,127),*range(128+32,256)))})[:8])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
H]Ú±qì8O
8 bytes
If you had a cluster of python instances running, you could use this to efficiently network them
this printable id becomes the instance hash and can be used to identify requests.
I tend to coordinate script nets with a central text file or csv.
for example, in a text file like:
7tfu^VUU\0 1
]#-|tc4i\0 0
=333%bce\0 1
a running instance can identify it's own hash and update it's status
so that a central process can allocate a task
random works too
but
this one's funner
Use type hints, they said.
Won't enforce the types, they said.
they say use more white space.
I say black space matters
!e ```py
from itertools import*;
class Fibonacci:
def init(self, n0, n1):
self.start=int(n0),int(n1),
def iter(self):
self.a, self.b = self.start;
return self;
def next(self):
a=self.a;
self.a,self.b=self.b,a+self.b,
return a;
def fibonacci(n):
f=iter(Fibonacci(0,1));
for _ in range(n):yield next(f);
print(*fibonacci(20));
*_fuckit,y,z=fibonacci(1000);
PHI=z/y;
round=lambda floater:(floater+0.5)//1
def fib_range(a):
if not a:a=0,1;
elif len(a)==1:a=0,a;
min,max=a;
returntakewhile(lambda x:x<=max,Fibonacci(min,round(minPHI)if min else 1)),
print(*fib_range(55,5555))
print(*fib_range(69,7000))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
002 | 55 89 144 233 377 610 987 1597 2584 4181
003 | 69 112 181 293 474 767 1241 2008 3249 5257
how do you compile the Instruction objects from dis.Bytecode into a code object?
¯_(ツ)_/¯
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
Hello World!
!e readable brainfuck (improved) ```py
from collections import defaultdict as d;
from ctypes import py_object as p;
class flogbals(p.from_address (id(globals ())+8).value ):
def getitem(self, name):
import builtins as builtins;
try:return builtins.dict.getitem(self,name);
except builtins.KeyError:...;
try:return builtins.getattr(builtins,name);
except builtins.AttributeError:...;
if name=='main':return builtins.super().getitem(name)
if name=='plus':self['a'][self['i']]+=1;return;
if name=='minus':self['a'][self['i']]-=1;return;
if name=='left':self['i']-=1;return;
if name=='right':self['i']+=1;return;
if name=='dot':return builtins.print(end=builtins.chr(a[i]));
if name=='comma':return builtins.NotImplemented;
if name=='here':return self['a'][self['i']];
if name=='end':return;
raise builtins.NameError(name+' does not exist');
p.from_address (id(globals())+8).value=flogbals;
a,i = d(int),0;
def main():
plus,plus,plus,plus,plus,plus,plus,plus,plus,plus;
while here:[
right,plus,plus,plus,plus,plus,plus,plus,right,
plus,plus,plus,plus,plus,plus,plus,plus,plus,plus,
right,plus,plus,plus,right,plus,left,left,left,left,minus,
];end;
right,plus,plus,dot;right,plus,dot;
plus,plus,plus,plus,plus,plus,plus;
dot,dot,plus,plus,plus,dot,right;plus,plus,dot,left,left,plus;
plus,plus,plus,plus,plus,plus,plus;
plus,plus,plus,plus,plus,plus,plus;
dot,right,dot,plus,plus,plus,dot;
minus,minus,minus,minus,minus,minus,dot;
minus,minus,minus,minus,minus,minus,minus,minus;
dot,right,plus,dot,right,dot;
main();
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
Hello World!
No segfault
Where's the annotation, or am I blind?
!e
Print(None)
@noble bloom :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'Print' is not defined
@noble bloom :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | NameError: name 'Print' is not defined
@noble bloom :x: Your eval job has completed with return code 1.
001 | None
002 | Traceback (most recent call last):
003 | File "<string>", line 2, in <module>
004 | AttributeError: 'NoneType' object has no attribute 'replace'
facts bro black and white equality all the way
that's why i sometimes code in light theme, and sometimes in dark theme
okay that's a war crime
!e someone said war crime? ```py
Missile = lambda*a:type(*a)();
class Nuke(metaclass=Missile):
def del(self):
try:
self.class(), self.class(), self.class(), self.class(), self.class(), self.class(), self.class(), self.class(), self.class();
except BaseException:
self.class();
print('pressing the big, red button...');
@floral meteor :x: Your eval job timed out or ran out of memory.
pressing the big, red button...
https://replit.com/@FluffyTrooper20/Sandbox#sudoku.py
I made sudoku 3.8 friendly
what the
how does that work?
wait a second
Missile = lambda*a:type(*a)(); is recursive type calling
what's the unpacking for then?
Doesn't __del__ only delete instances? why is that being called
Yes, although classes are instances of their metaclass
Remember, everything is an object
@floral meteor I need help
yeah?
You made the original code, and I'm trying to modify it
you know your annotations voodoo with setitem?
class __annotations__:
def __setitem(self,name,value):
print(name,value)
stuff like this
@floral meteor you there?
mhm
alr
so how do i get that to work within a function at runtime
class __annotations__:
def __setitem(self,name,value):
print(name,value)
def foo():
something:1
you dont
you need the class to be inside every scope
so now how would I do this
I don't care about code quality or practice
@floral meteor
@floral meteor
Please stop pinging users. One ping is enough. If they're not responding, then they're clearly just not available/don't know how to assist at the moment
(Just realised they said to ping them, but even so, try not to spam it)
Understood. I tried to wait 10 minutes, but thanks. I appreciate it. What do you suggest I do in the future?
!e
if next(int(_) for _ in {*'01'}):
print('Runtime random, prints sometimes, but not always?')
@strange basin :warning: Your eval job has completed with return code 0.
[No output]
!e
if next(int(_) for _ in {*'01'}):
print('Runtime random, prints sometimes, but not always?')
@strange basin :white_check_mark: Your eval job has completed with return code 0.
Runtime random, prints sometimes, but not always?
Order of items in sets is runtime random.
oh
As long as your python instance is running the result would be the same though ... as far as I have understood it.
Oh, yeah, right ... I kind of figured it out when I constructed the code ...
The strings part is important.
Thanks.
it's seeded by the env var PYTHONSEED iirc
Stuff like that is good for making heisenbugs ...
yeah I figured out a more simpler method also here is the final program: ```py
#Importing modules
import sys
import random
from random import seed
from random import randint
seed random number generator
seed(1)
generate random integer value
N=random.randint(1,sys.maxsize)
#original number
print(N)
#equation
while N>1:
if (N % 2) == 0:
print(round(N:=N/2))
else:
print(round(N:=3*N+1))
After some searching online I found this:
PYTHONHASHSEED. If this variable is not set or set to random, a random value is used to seed the hashes of str, bytes and datetime objects. If PYTHONHASHSEED is set to an integer value, it is used as a fixed seed for generating the hash() of the types covered by the hash randomization.
Wait is there a method I can add to a class that’ll run whenever I run this: *some_class_instance?
iter/next
hrm 
>>> dis.dis("set('abcdefg')")
1 0 LOAD_NAME 0 (set)
2 LOAD_CONST 0 ('abcdefg')
4 CALL_FUNCTION 1
6 RETURN_VALUE
>>> dis.dis("{*'abcdefg'}")
1 0 BUILD_SET 0
2 LOAD_CONST 0 ('abcdefg')
4 SET_UPDATE 1
6 RETURN_VALUE
second one is probably faster, yea?
yeah
%timeit set(abcdefg)
1.38 µs ± 319 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit {*abcdefg}
728 ns ± 88.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)```
i do in fact have strings
In[10]: abcdefg
Out[10]: 'abcdefg'```
i am a wizard i know
im pretty sure load global is going to be faster than constructing the string
570 ns ± 201 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit {*abcdefg}
512 ns ± 20.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)```and you also then arent including it in the thing that your actually timing
oh i dont think these timings are reliable
its faster for the second either way
num: BinaryConverter
We could theoretically post a bunch of esoteric code to gothub so that copilot just doesn’t work
Github*
Or like Copilot would recommend: globals()[eval(‘\’test\’’)]=12
that would increase the average code quality in the dataset
I like your funny words, magic man
There’s a whole project that uses globals()[…]=…
Can i somehow make a set not evaluate it’s elements?
the first thing i see when i hop into this chat
is something that hardly resembles python 😂
…?
Loading immutable literals (integers, strings, even tuples of those literals) are basically free since they are created in the compile time.
small random challenge: cause an indentation error to be raised,
- with syntactically correct code (including correct indentation)
- without use of the
raisekeyword - without use of
exec/eval - without any ast transformations or bytecode manipulation
- without using the generator throw trick, or any such golfy tricks for throwing specific exceptions.
Probably create a file with bad indentation then import it.
Can the solution be used to cause exceptions other than indentation errors and does it happen at runtime or compile time?
open("x.py","w").write(" 0")
import x
man theres always a loophole that gets by me 😆 new rule: no imports. got something weird/obscure in mind here 😛
has to specifically be an indentation error at runtime
compile(" 0","","eval")
ughhh ok hold on back to the drawing board
how to loophole proof this
ok v2:
- with syntactically correct code (including correct indentation, and also any code inside a
compile) - without use of the raise keyword
- without use of exec/eval
- without any ast transformations or bytecode manipulation
- without using the generator throw trick, or any such golfy tricks for throwing specific exceptions.
- without imports
but... ill say this
thats getting like 90% of the way there @snow beacon
Oh, I think I see.
so does the compile/import rule only apply to syntactically incorrect code or all code
You can compile syntactically correct code. You can't import it.
no imports at all
Ok so that means we can't break the parser using ctypes or something, this is a tough one
There's that ctypes without ctypes trick, but I don't have the patience.
another hint if wanted: ||theres a solution involving an obscure cpthon compiler limitation||
oh, i meant to spoiler that lmao
welp
You can edit it to ||text||.
hmm
yea just didnt want to force it on anyone looking at the channel already. oops
Can the exception be a subclass of IndentationError?
|| Looks like you're trying to take advantage of the fact that the tokenizer's indentation stack is limited? || @snow beacon
Yes, but badly.
if im not mistaken it is an IndentationError and not any subclass
if you have a solution that involves a subclass of IndentationError id be curious to see for sure
the situation that gave me the idea of this challenge specifically involved an IndentationError though
s = "0"
for i in range(100):
s = "if 0:\n " + s.replace("\n","\n ")
compile(s, "", "exec")
code = []
for i in range(102):
code.append(f'{" " * i}if True:')
code.append(f'{" " * (i + 1)}pass')
compile('\n'.join(code), '', 'exec')
This is what I came up with
yep thats it
I'm not saying that anyone should indent this much but 100 seems kind of small
yeah, think this part of the cpython source is ancient
like probably maybe one of the first parts guido ever worked on
so i dont think handling super nested code was a consideration back then
The maximum number of nested parentheses is 200, could make for another fun challenge
think theres also one for nested literals
oh wow had no idea
though something to note, these are (i think all?) parser limitations. if you construct the ast yourself then itll compile.
A while ago someone on here posted a way to make a class that was its own metaclass
Or, acted like it was atleast. Anyone have that handy?
this? <#esoteric-python message>
oh and there was a minor update here <#esoteric-python message>
Wasn't one also posted on stackoverflow somewhere?
æ
sorry i was fal aslep.
I'm currently contemplating a way to do this with a function decorator.
Within a scope, there's no simple voodoo like class _annotations_
also, a note on annotations — since we are getting closed to annotations feature enabled by default, for more or less serious code it is nicer to use typing.get_type_hints(item) instead of directly accessing item.__annotations__
ew
then i have to import typing
unnecessarily
!e ```py
from future import annotations
import builtins as builtins
@lambda c:c()
class annotations:
def setitem(self, a, b):
globals()[b] = builtins.dicta
int: a = 4
print: _ = a
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
4
haha java in python go brrr
Hi guys i am new in this group! Glad to be here!
What are you doing here? Esoteric python? 😄
!e ```py
import builtins as builtins
meta = lambda*args:lambda a,b,c:type(a,b,c)(*args)
class System:
class out:
def print(a):builtins.print(a,end='')
def println(a):builtins.print(a)
class in_:
def read(n=1):
from sys import stdin as s;
return s(n)
return_='return_'
String=str
args=import('sys').argv
class KwBase:
def init(self):self.kws=[]
def sub(self, other):
other.kws.append(self)
return other
class static(KwBase,metaclass=meta()):...
class public(KwBase,metaclass=meta()):...
null=None
class void(KwBase,metaclass=meta()):
hash=lambda s:0
def call(self, other):assert other is None
class main:
def init(self, *args):
self.args = args
self.kws=[]
def sub(self, func):
value = func['return_']
if'void'in self.kws:assert value is None
return value
class JavaInPython: {
public-static-void-main(String,[], args)-{
void: System.out.println("Hello World!"),
return_: null,
}
}
wow
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
Too much smarts for me
that is very impressive 👏
But is the print statement part right?
why is there void there
cos i had to make it a dict
but then no return
set shuffles
!e ```py
import builtins as builtins
meta = lambda*args:lambda a,b,c:type(a,b,c)(*args)
class System:
class out:
def print(a):builtins.print(a,end='')
def println(a):builtins.print(a)
class in_:
def read(n=1):
from sys import stdin as s;
return s(n)
return_='return_'
String=str
args=import('sys').argv
class KwBase:
def init(self):self.kws=[]
def sub(self, other):
other.kws.append(self)
return other
class static(KwBase,metaclass=meta()):...
class public(KwBase,metaclass=meta()):...
null=None
class void(KwBase,metaclass=meta()):
hash=lambda s:0
def call(self, other):assert other is None
class main:
def init(self, args):
self.args = args
self.kws=[]
def sub(self, func):
if type(func)is dict:
value = func['return_']
if void in self.kws:assert value is None
elif globals()['int']in self.kws:value=int(value)
import('_sitebuiltins').Quitter('$$')(int(value))
else:return null
a=null
class int(KwBase,metaclass=meta()):
hash=lambda s:hash(builtins.int)
call=lambda s,o:builtins.int(o)
class JavaInPython: {
public-static-int-main(String,[], args)-{
void: a==System.out.println("Hello World!"),
return_: 69,
}
}
@floral meteor :x: Your eval job has completed with return code 69.
Hello World!
exit 69 ;)
Nice
!e You see a problem with that is annotations don't get evaluated there.
a : print(a) = 69
def main():
b: print(b) = 420
main: main = main()
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
!e ```py
from dis import dis
def a():
x: y = 4
def b():
x = 4
dis(a)
dis(b)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 3 0 LOAD_CONST 1 (4)
002 | 2 STORE_FAST 0 (x)
003 | 4 LOAD_CONST 0 (None)
004 | 6 RETURN_VALUE
005 | 5 0 LOAD_CONST 1 (4)
006 | 2 STORE_FAST 0 (x)
007 | 4 LOAD_CONST 0 (None)
008 | 6 RETURN_VALUE
!e ```py
def a():
x: y = 4
def b():
x = 4
print(a.code.co_code)
print(b.code.co_code)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | b'd\x01}\x00d\x00S\x00'
002 | b'd\x01}\x00d\x00S\x00'
in fact, they don't even get parsed
Nice 👍
damn
!e
def a():
x: y
def b():
x = 4
print(a.__code__.co_code)
print(b.__code__.co_code)
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | b'd\x00S\x00'
002 | b'd\x01}\x00d\x00S\x00'
my memory tells me that's POP_TOP (0) and RETURN_VALUE (0)
!e
__import__('dis').dis(b'd\x00S\x00')
@golden finch :white_check_mark: Your eval job has completed with return code 0.
001 | 0 LOAD_CONST 0 (0)
002 | 2 RETURN_VALUE
@floral meteor
How can I shuffle the small integer cache? I presume I'll need to avoid some values - like 0 and 1?
What do you mean by shuffle?
You want to make the literals return wrong values?
!e ```py
from ctypes import*
hack=lambda victim:py_object.from_address(id(victim))
a = [hack(i)for i in range(-127,256)]
gulag = [yay.value for yay in a]
new = [*{*a}]
for i in a:
i.value = new[i.value]
print (*range(20))
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | File "<string>", line 4, in <listcomp>
004 | ValueError: PyObject is NULL
AAAAAAAAAAAAAAAAAAAAA