#esoteric-python
1 messages · Page 108 of 1
but it's gotta be in the frame code
not the frame, but the ast definitley
ast? even better i spose
!e ```py
import ast
a = ast.parse("""
from typing import List
List[int]
""")
print(a.body[1].value.slice.id, a.body[1].value.value.id)
@broken mesa :white_check_mark: Your eval job has completed with return code 0.
int List
neat
@floral meteor thats how you could get it using ast
but if you can get the actual return of List[int] (or any subscriptable typing) you can just look up the args from that object
@floral meteor what you actually want does work with ast, you just need to access .target and .annotation
unfortunately you do need to either use string literals or custom encodings
@broken mesa I believe the question is how to access the annotation in foo[bar]: something
In [12]: a = ast.parse("list[int]: expr")
In [13]: a.body[0].target
Out[13]: <ast.Subscript at 0x10aa676a0>
In [14]: a.body[0].annotation
Out[14]: <ast.Name at 0x10b8c7f40>
!e ```py
from typing import List
a = List[int]
print(a.args)
@broken mesa :white_check_mark: Your eval job has completed with return code 0.
(<class 'int'>,)
this is the way to do it if you were to make it a custom type, and have access to the return value
i used List as a example, can obviously be a custom subscriptable typing
anyways, i gotta sleep
hmmm
:D
What if I made brainfuck, instead of printing, execute as byte code?
A brainfuck object would inherit from function
Nah that wouldn't work
Nope my brain is fucked now
Will pattern matching ever get implemented? The PEP says it’s superseded, but I don’t know what that means in this context
Yes look at pep 634 it was already accepted
It will be in Python 3.10.
yo
can you rename a function
i want to do something like this
read a line form a file, which has a list of words say
a
b
c
...
thne i want to make fncitons dynamically
def a:
pass
def b:
pass
htf will i do that?
patma is already accepted:
!pep 634
In fact, it's already implemented.
You can clone https://github.com/python/cpython and follow the bulid instructions to enjoy it
"superseded" means that a newer PEP makes that one deprecated.
Or download 3.10a6
Something like```py
def a():0
b = type(a)(a.code.replace(co_name="b"), globals())
print(b)
how is it working
The type(a) is to get the function type, which is initialised on the same code as a, except with its name replaced.
It makes a new function from scratch, out of the old one.
CodeType.replace is a thing now?
Thank god I don't have to make these awful functions to do that now
nice yeah since 3.8
very convenient
posted this in the wrong channel before 😎
def fix(code):
return 'exec(' + '+'.join(['chr(' + '+'.join('1'*ord(c)) + ')' for c in code]) + ')'
print(fix(input('Code? ')))```
@snow beacon
your approach is pretty cool though
exec?
nice
file handling
still need to figure out why it strips all spaces
oh i see why nvm
!e
print(*("fizz"*(not x%3)+"buzz"*(not x%5) or x for x in range(1,101)), sep="\n")
@lunar ore :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | fizz
004 | 4
005 | buzz
006 | fizz
007 | 7
008 | 8
009 | fizz
010 | buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/depufoqupo.txt
Interviewers can suck it
hired on the spot
Whats the shortest fizzbuzz can be in py3
Thats 78 chars with some white space trimmed
what is esosteric python?
https://mystb.in/ShipmentSurfaceBall.lua @half cove
:x: According to my records, this user already has a mute infraction. See infraction #29673.
!e ```
print(("fizz"(x%3<1)+"buzz"*(x%5<1)or x for x in range(1, 101)), sep="\n")
@fluid tree :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | fizz
004 | 4
005 | buzz
006 | fizz
007 | 7
008 | 8
009 | fizz
010 | buzz
011 | 11
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/acaqozizuv.txt
I don't know if this is how it works, but it would be useful to have a !esoteric command, for when pilgrims from the outside world want to know what #esoteric-python is about.
@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 0x00007f5899ef9740 (most recent call first):
005 | File "<string>", line 2 in crash
006 | File "<string>", line 2 in crash
007 | File "<string>", line 2 in crash
008 | File "<string>", line 2 in crash
009 | File "<string>", line 2 in crash
010 | File "<string>", line 2 in crash
011 | File "<string>", line 2 in crash
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/pujebigico.txt
!e ```py
class YouCantTouchThis(RecursionError):
def init(self):
def MCHammer():
try:
raise YouCantTouchThis
except RecursionError:
raise YouCantTouchThis
MCHammer()
try:
raise YouCantTouchThis
except:
dun_dun_dun_dun, dun_dun, dun_dun
@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 0x00007f214aed5740 (most recent call first):
005 | File "<string>", line 8 in __init__
006 | File "<string>", line 5 in MCHammer
007 | File "<string>", line 8 in __init__
008 | File "<string>", line 5 in MCHammer
009 | File "<string>", line 8 in __init__
010 | File "<string>", line 5 in MCHammer
011 | File "<string>", line 8 in __init__
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ufixoponus.txt
!e
print ("Hello World")```
@grave dock :white_check_mark: Your eval job has completed with return code 0.
Hello World
bruh why does forbiddenfruit not work?
!e ```py
def print(*args):
try:print (*args)
except:print (*args)
print ("Hello World")
@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 0x00007f2fcfd01740 (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/robuzekome.txt
this is the channel where a simple statement like that would crash python.
@grave dock this is how we hello world here
this is the insanity of trying to explain code that comes from here
this is the type of error that code from here usually raises.
"normal" errors? unheard of.
explain
explain what?
!e ```py
(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 _, __, ___, ____, _____, ______, _______, ________: _)))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello world!
clicking on the reply will take you to the context
Ok
what needs explaining?
That'd be a tag - you can suggest new tags by commenting at https://github.com/python-discord/meta/discussions/86 or in #community-meta i think
L=lambda n:str(sum([(int(str(int(d)*2)[0])+int(str(int(d)*2)[1])if len(str(int(d)*2))==2else int(d)*2)if c%2==0 else int(d)for c,d in enumerate(str(n))]))[-1]=='0'and len(str(sum([(int(str(int(d)*2)[0])+int(str(int(d)*2)[1])if len(str(int(d)*2))==2else int(d)*2)if c%2==0else int(d)for c,d in enumerate(str(n))])))>1
print(L(15592958920))
this checks a number for divisibility by 10
modulus
All
!e ```py
def self(n=0):
n+=2
f=lambda*a,**k:None
def b(c):
try:raise Exception("\x1b[31mTop level frame, cannot reference.\x1b[0m")
except Exception as e:fr=e.traceback.tb_frame;return[{(fr:=getattr(fr,'f_back'))for _ in range(c)},fr.f_code][1]
f.code=b(n);return f
modulus = lambda ,__: if <_ else self()(_-,)
print(modulus(28,3), modulus(27,3), modulus(26,3), modulus(9,1),sep='\n')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 0
003 | 2
004 | 0
0_0
you want the unofficial esoteric tutorial, then?
or are you yet to learn python itself?
who's 0_0?
alright before we start, just some tips;
error == ur fucked
no worky == ur fucked
want to patch == ur fucked
golfing != security
So, you said you know python, so I'm gonna assume a lot of knowledge.
for example, the difference between the Look Before You Leap approach to programming and Easier to Ask Forgiveness than Permission
I haven’t said yet that I’m Russian and I don’t know English well
noice
Yes
There's many different activities that fall under the category of esoteric coding.
for example, code golf is achieving code in minimal characters.
while brainfuck is a minimalist Turing Complete interpreter.
essentially, the core theme is either challenge, gore, or art
if ur using google translate ur probably getting wierd stuff like blood and occupations. idk im not exactly multilinguist
yeah
Есть много разных занятий, подпадающих под категорию эзотерического кодирования.
например, код гольф - это код, состоящий из минимального количества символов.
в то время как brainfuck - это минималистский интерпретатор Turing Complete.
по сути, основная тема - вызов, кровь или искусство.
is the wrong translation. :P
what is the right way then?
Heh, Okey
still find this specialist
Heh
there is also a checkmate
:/
further
defeat?
No
гугл переводчик работать нет. приговор полностью
может мне стоит просто закодировать змейку
Yes
I'm going to school
so I can’t :(
a = 1
if a:
print("Я тупой")
if not not a:
print("...")
->
a = 1
a and print("побочный эффект")
not a or print("также побочный эффект")
russian friendly coding really make brain hurt lmao
what does this code do?
What?
idk it got really noisy here i can't think
очень шумно
yes
Ладно. до свидания.
Goodbye
it calls the __mod__ method of the left side, with the right side as the argument.
!e like this:
def self(n=0):
n+=2;f=lambda*a,**k:None
def b(c):
try:raise Exception("\x1b[31mTop level frame, cannot reference.\x1b[0m")
except Exception as e:fr=e.__traceback__.tb_frame;return[{(fr:=getattr(fr,'f_back'))for _ in range(c)},fr.f_code][1]
f.__code__=b(n);return f
modulus=lambda _,__:_ if _<__ else self()(_-__,__)
print(modulus(9,5))
class Int(int):__mod__=modulus
print(Int(9)%5)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 4
002 | 4
strings have a different __mod__ method, which has nothing to do with integer modulus
Hmm what's the difference?
something like this... ```py
class Str(str):
def mod(self, args):
prev_char="";new_self=self.str()
if isinstance(args,str):args=[args]
elif not hasattr(args, 'iter'): args=[args]
it = args.iter()
for c in self:
if prev_char == "%":
if c=='c':
subst=it.next();assert isinstance(subst,int)
new_self.replace("%c",chr(subst),1)
elif c=='s':
new_self.replace('%s',str(it.next()),1)
elif c=='d':
new_self.replace('%d',int(it.next()),1)
elif c=='f':
new_self.replace('%f',float(it.next()),1)
elif c=='%':new_self.replace('%%','%',1)
else:raise ValueError
prev_char=c
return new_self
print(Str('%d')%4)
What did you do lol
!e print(str.mod('%d',4))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
4
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
%d
!e
class Str(str):
def __mod__(self, args):
prev_char="";n=self.__str__()
if isinstance(args,str):args=[args]
elif not hasattr(args, '__iter__'): args=[args]
it = args.__iter__()
for c in self:
if prev_char == "%":
if c=='c':subst=it.__next__();assert isinstance(subst,int);subst=chr(subst)
elif c=='s':subst=str(it.__next__())
elif c=='d':subst=str(int(it.__next__()))
elif c=='f':subst=str(float(it.__next__()))
elif c=='%':subst='%'
else:raise ValueError
n=n[:n.find(f"%{c}")]+subst+n[n.find(f"%{c}")+2:]
prev_char=c
return n
print(Str('%d')%4)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
4
Pog
mod substitution
!e whatever you want it to
Hello=type("Hello",(),dict(__mod__=lambda s,n:print(s.__class__.__name__,n)))()
World=type("World!",(),dict(__str__=lambda s:s.__class__.__name__))()
#---
Hello % World
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
@rugged sparrow one use i've found for fishhook is for using "named anonymous functions" :>
from fishhook import hook
@hook(hook.__class__)
def named_as(s,n):s.__name__=n;return s
hook(Ellipsis)(print.named_as("__call__"))
...("Hello World!")
what is it?
**prescribed external modules for esoteric coding**
# fuckit
> pip install fuckit
# fishhook
> pip install fishhook
:>
@grave dock like forbiddenfruit only it actually does what its supposed to
:)
😆
!e virgin forbiddenfruit (Запретный плод)
from forbiddenfruit import curse
curse(Ellipsis, "__call__", print)
...("Hello World!")
@floral meteor :x: Your eval job has completed with return code 1.
001 | <string>:3: SyntaxWarning: 'ellipsis' object is not callable; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 | File "<string>", line 2, in <module>
004 | File "/snekbox/user_base/lib/python3.9/site-packages/forbiddenfruit/__init__.py", line 425, in curse
005 | _curse_special(klass, attr, value)
006 | File "/snekbox/user_base/lib/python3.9/site-packages/forbiddenfruit/__init__.py", line 332, in _curse_special
007 | tp_as_name, impl_method = override_dict[attr]
008 | KeyError: '__call__'
I sing
What a forbidden fruit
chad fishhook (
рыболовный крючок)
from fishhook import hook
@hook(hook.__class__)
def named_as(s,n):s.__name__=n;return s
hook(Ellipsis.__class__)(print.named_as("__call__"))
...()
metaphor for you're not supposed to use this
i.e. to use this module is sinful
understandably
fishhook will hook a method to a класс
.-.
You don't have to translate
Никита
Я
Что здесь делать
А
fishhook will hook a method to a class
got it
keep swapping English and Russian, in the translater, to see translation error
There are no errors yet
much error -> большая ошибка <-> big mistake
aa
смайлики - это международный язык
Yes
😀
👍
brainfuck == 🧠 🍆
fishhook == 🎣
there's still a few things I can't translate to emoji ;-;
class == тип
def == прием
print == стандартный вывод << шрифт
input == стандартный ввод >>
Переменная
!e ```py
class стандартный:
lshift=print
rshift=input
стандартный() << "Привет, мир!"
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Привет, мир!
wait this whole time you can make russian variable names?
*cyrillic
XD
!e ```py
class меер:
str=print
try:print(меер())
except:print(меер())
@floral meteor :x: Your eval job has completed with return code 1.
001 |
002 |
003 | Traceback (most recent call last):
004 | File "<string>", line 3, in <module>
005 | TypeError: __str__ returned non-string (type NoneType)
006 |
007 | During handling of the above exception, another exception occurred:
008 |
009 | Traceback (most recent call last):
010 | File "<string>", line 4, in <module>
011 | TypeError: __str__ returned non-string (type NoneType)
what, but I did not know: /
!e ```py
def меер():
try:меер()
except:меер()
меер()
@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 0x00007fc162317740 (most recent call first):
005 | File "<string>", line 2 in \u043c\u0435\u0435\u0440
006 | File "<string>", line 2 in \u043c\u0435\u0435\u0440
007 | File "<string>", line 2 in \u043c\u0435\u0435\u0440
008 | File "<string>", line 2 in \u043c\u0435\u0435\u0440
009 | File "<string>", line 2 in \u043c\u0435\u0435\u0440
010 | File "<string>", line 2 in \u043c\u0435\u0435\u0440
011 | File "<string>", line 2 in \u043c\u0435\u0435\u0440
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/nocemulafo.txt
Some letters get treated as each other, so you can have two different Unicode character sequences that are both the same identifier.
Horrible example of this: https://gist.github.com/vient/27800c8a2d4fd1d9651fc8eece88b6bf
Edit: It is not my code, but it works and even transforms other code to look equally horrible...
Russian/Cyrillic should be different than what you say. even if they look similar, they are not "fancy Latin letter" so their normalized version is still Cyrillic
!e
е = 1 # Cyrillic alphabet, "ye"
print(e) # Latin alphabet
@finite rose :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 'e' is not defined
https://docs.python.org/3/reference/lexical_analysis.html#identifiers
Python 3.0 introduces additional characters from outside the ASCII range (see PEP 3131). For these characters, the classification uses the version of the Unicode Character Database as included in the unicodedata module.
(...)
All identifiers are converted into the normal form NFKC while parsing; comparison of identifiers is based on NFKC.
After seeing that I will no longer use variable names
I would now update calls to locals and globals. Far less implicit
locals()[name] = value doesnt work. @floral meteor
when locals is called, it builds a mapping that contains the current names -> values
!e ```py
def DOOT():
locals().update({'f':4})
print(f)
DOOT()
@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 3, in DOOT
004 | NameError: name 'f' is not defined
bruh
BRUH
I am no longer using locals then
imma make a namespace stack in globals
XD
!e ```py
class function((lambda:None).class):
def init(self, code, g_gandle, name="<lambda>", doc=None):super().init(); self.name=name; self.doc=doc;g_handle['namespace.stack'].append(g_handle.copy());g_handle['namespace.stack'][-1].update({name:self})
def lshift(s,o):
try:return s(o)
except:return lambda a:s(o,a)
globals()['namespace.stack']=[globals()]
globals()['get-frame']=function((lambda n:globals()['namespace.stack'][~n]).code,globals(), "get-frame")
def add(a,b):
globals()'get-frame'.update({'.':globals()'get-frame'.pop('a')+globals()'get-frame'.pop('b')})
return globals()'get-frame'['.']
globals()['add']=function(globals()['add'].code,globals(),globals()['add'].name)
globals().update({'2':3})
print(globals()['namespace.stack'][0]['add'] << globals()['2'] << 2)
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: type 'function' is not an acceptable base type
ur mom is not an acceptable weight
jk y'all get the idea of what it does, tho, right?
y'see I used . as a variable name?
only this channel could produce something as twisted as that
you know i might be able to write code that makes locals()[name] = value actually work
acc i prob could yea
if you could find a way to access locals() non-locally that would be great :>
It has been tried in the past.
well it would require that the name name exists in the code
@snow beacon i can access the fastlocals array manually
wait, can't you do it with exception catching?
something like
def funcy():
a=4
try:raise Exception
except Exception as e: return e.__traceback__.tb_frame.f_locals
globals.update(funcy())
print(a)
```?
huh. what if...
!e ```py
a=3
def wow():
a=4
def mucherror():
a=5
raise Exception
try: mucherror()
except Exception as e: print(e.traceback.tb_frame.f_lineno); return e.traceback.tb_frame.f_back.f_locals['a']
print(wow())
well I can access the locals of the previous frame, but that can already be done by the namespace, iirc
@floral meteor making locals() assignable has more issues than i forsaw
uh oh
yea cause any names that arent assigned to in that scope use LOAD_GLOBAL
(so messing with locals does nothing)
pycharm has r colouring 0o0
I prefer my much more explicit namespace regime
everything comes from globals
Myself I like adequate scoping, which is very difficult in Python.
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 19, in <module>
003 | File "<string>", line 6, in __lshift__
004 | TypeError: <lambda>() takes 1 positional argument but 5 were given
how long did that take you?
a long time
!e ```py
class function():
name="<lambda>"
def init(self, code, g_handle=globals(), name="<lambda>", doc=None):locals()['call']=lambda s:None;locals()['call'].code=locals()['code'];self.call=lambda s,a,**k:[locals()'call',locals()['g_handle']['namespace.stack'].pop(len(locals()['g_handle']['namespace.stack'])-1)][0];self.name=locals()['name'];self.doc=locals()['doc'];locals()['g_handle']['namespace.stack'].append(locals()['g_handle'].copy());locals()['g_handle']['namespace.stack'][-1].update({locals()['name']:locals()['self']})
call=lambdas:None
def lshift(s,o):
locals()['f']=lambda*a,**k:s(o,a,**k)
return locals()['s'].class(locals()['f'].code,globals(),locals()['s'].name,locals()['s'].doc)
def setattr(s,o,v):
locals()['f']=lambdaa,**k:s(*a,k,{o:v})
return locals()['s'].class(locals()['f'].code,globals(),locals()['s'].name,locals()['s'].doc)
globals()['namespace.stack']=[globals()]
globals()['get-frame']=globals()['function']((lambda n:globals()['namespace.stack'][~n]).code,globals(),"get-frame")
def add(a,b):
"""
adds a and b.
warning: may be dystopic
:rtype: int
"""
globals()'get-frame'.update({'.':globals()'get-frame'.pop('a')+globals()'get-frame'.pop('b')})
return globals()'get-frame'['.']
globals()['add']=function(code=globals()['add'].code,g_handle=globals(),name='add',doc=globals()['add'].doc)
globals().update({'2':3})
print((globals()['namespace.stack'][0]['add'] << globals()['2'] << 2)())
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 12, in <module>
003 | File "<string>", line 3, in __init__
004 | File "<string>", line 10, in __setattr__
005 | File "<string>", line 3, in __init__
006 | ValueError: <lambda>() requires a code object with 0 free vars, not 3
whats globals.update do?
why can't i f-
# clash_of_the_titans.py
import fuckit
def youcantfuckthis():
try:youcantfuckthis()
except:
with fuckit:youcantfuckthis()
with fuckit:youcantfuckthis()
The Ultimate Python Error Steamroller vs. The Ultimate Fatal Python Error
who will win?
!e ```py
def f():
try:1/0
except:f()
f()```
@sick hound you sound like Bernadette from Big Bang Theory
@rugged sparrow :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 0x00007fce14ca2740 (most recent call first):
005 | File "<string>", line 2 in f
006 | File "<string>", line 3 in f
007 | File "<string>", line 3 in f
008 | File "<string>", line 3 in f
009 | File "<string>", line 3 in f
010 | File "<string>", line 3 in f
011 | File "<string>", line 3 in f
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ozifivavic.txt
!e
(lambda cout: cout << "Hello, World")(type("", (), {"__lshift__":print})())
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
Hello, World
took a couple of tries
!e (lambda cout: cout << "Hello World!")(type("stdout", (), dict(lshift=print))())
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
it took me one try :>
owo
I have a whole module for that
!e (lambda cout: cout << "Hello World!")(type(str, tuple, dict(lshift=print))())
@sudden willow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: type.__new__() argument 1 must be str, not type
sad
it looks like this
nice
@sudden willow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AttributeError: __enter__
oh
!e with type("", (), {"__enter__": ..., "__lshift__": print, "__exit__": ...}) as cout: cout << "hewwo world";
@sudden willow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AttributeError: __enter__
!e ```py
with type(str(),(),{"lshift":print,"enter":lambda*s:s[0],"exit":lambda s,*e:True})() as cout:cout << "hewwo world!";
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
hewwo world!
that took me a few tries
@sudden willow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | AttributeError: __enter__
no, you need more dunders
o_o
with requires a valid context manager.
A context manager defines an __enter__ and __exit__.
still not too good at implementing with in my code
You've implemented a __lshift__. It's a similar principle.
!e ```py
int=type("statement",(),dict(getattr=lambda s,o:globals().update({o:0})or s,call=lambda s,*a:type("",(),{'enter':lambda s:a,'exit':lambda s,*b:True})()))()
#---
int.n.m
with int(2, 3) as n,m:
with type(str(),(),{"lshift":print,"enter":lambda*s:s[0],"exit":lambda s,*e:True})() as cout:
cout << n + m;
In order to see what arguments with calls, you can try:
@floral meteor :warning: Your eval job has completed with return code 0.
[No output]
!e ```python
class Test:
def enter(*args, **kwargs):
print(args, kwargs)
def exit(*args, **kwargs):
print(args, kwargs)
with Test():
pass
@snow beacon :white_check_mark: Your eval job has completed with return code 0.
001 | (<__main__.Test object at 0x7f4a8629afd0>,) {}
002 | (<__main__.Test object at 0x7f4a8629afd0>, None, None, None) {}
cool
As you can see, __enter__ is just called with self, and __exit__ has some extra Nones.
i'm only really used to using the mathematical operator dunders
I'm pretty sure the Nones are related to exceptions thrown inside the with.
but if there's an error, those Nones stop becoming Nones. Maybe they lose their virginity?
Presumably they were never None in the first place, because None is singleton.
owo
Pun only half intended.
every time you say Nones i think nuns
I am aware.
none is falsey right
Correct.
so if there's an error, your code loses its virginity!
True, falsey.
!e print(None.__bool__().__int__())
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
0
!e assert bool(None)==False
@floral meteor :warning: Your eval job has completed with return code 0.
[No output]
!e print(+bool(print("None is: ")))
@snow beacon :white_check_mark: Your eval job has completed with return code 0.
001 | None is:
002 | 0
!e ```py
def weight(n):
return abs(float(ord(n[0]).add(ord(n[1]))))
assert weight('your mom') > weight('a truck full of big macs')
assert "That was a pretty epic burn"
assert "P" != "NP"
assert "False"
@floral meteor :warning: Your eval job has completed with return code 0.
[No output]
Didn't you learn any lessons?
!e (lambda cin: cin >> "not exactly like c++ but eh")(type("", (), {"__rshift__": input})
Should be an =.
@sudden willow :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | (lambda cin: cin >> "not exactly like c++ but eh")(type("", (), dict("__rshift__": input))
003 | ^
004 | SyntaxError: invalid syntax
man coding on mobiles hard
!e (lambda cin: cin >> "not exactly like c++ but eh")(type("", (), {"__rshift__": input})())
@sudden willow :x: Your eval job has completed with return code 1.
001 | not exactly like c++ but ehTraceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <lambda>
004 | EOFError: EOF when reading a line
!e (lambda cin: cin >> "not exactly like c++ but eh")(type("", (), {"__rshift__": __import__("sys").std.in})())
@sudden willow :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | (lambda cin: cin >> "not exactly like c++ but eh")(type("", (), {"__rshift__": __import__("sys").std.in})())
003 | ^
004 | SyntaxError: invalid syntax
hm
in is a keyword.
oh
i couldve swore there was something like stdin
oh wait
!e (lambda cin: cin >> "not exactly like c++ but eh")(type("", (), {"__rshift__": __import__("sys").stdin})())
@sudden willow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <lambda>
004 | TypeError: '_io.TextIOWrapper' object is not callable
!e input()
stdin is not a function.
@sudden willow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
:^(
sys.stdin.readline or .read?
!e (lambda cin: cin >> "not exactly like c++ but eh")(type("", (), {"__rshift__": __import__("sys").stdin.read})())
@sudden willow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <lambda>
004 | TypeError: argument should be integer or None, not 'str'
not sure
What are you trying to do?
!e ```py
def donotpressthisbutton(*a):
print("donotpressthisbutton")
def do_not_press_this_button(*b):
print("do_not_press_this_button")
def DoNotPressThisButton(*c):
print("DoNotPressThisButton")
def DONOTPRESSTHISBUTTON(*d):
print("DONOTPRESSTHISBUTTON")
def I_SAID_DO_NOT_PRESS_THIS_BUTTON_YOU_FOOL(*e):
print("I SAID DO NOT PRESS THIS BUTTON YOU FOOL")
def NO_BUTTON_PRESS_FOR_YOU(*f):
print("FINE THEN, PROGRAM WILL FORCE TERMINATE")
try:donotpressthisbutton(*a)(*b)(*c)(*d)(*e)(*f)
except:print(*a,*b,*c,*d,*e,*f);donotpressthisbutton(*a)(*b)(*c)(*d)(*e)(*f)
return NO_BUTTON_PRESS_FOR_YOU
return I_SAID_DO_NOT_PRESS_THIS_BUTTON_YOU_FOOL
return DONOTPRESSTHISBUTTON
return DoNotPressThisButton
return do_not_press_this_button
k = donotpressthisbutton(1)
k = k(2,4,5)
k = k(9, 2, 3)
k = k("f", print, 3)
k = k(k, 6, 9)
k = k(4,2,0)
k = ("terminate")
print("this wont print ahahaha")
huh
I don't know what that is.
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | donotpressthisbutton
002 | do_not_press_this_button
003 | DoNotPressThisButton
004 | DONOTPRESSTHISBUTTON
005 | I SAID DO NOT PRESS THIS BUTTON YOU FOOL
006 | FINE THEN, PROGRAM WILL FORCE TERMINATE
007 | donotpressthisbutton
008 | do_not_press_this_button
009 | DoNotPressThisButton
010 | DONOTPRESSTHISBUTTON
011 | I SAID DO NOT PRESS THIS BUTTON YOU FOOL
... (truncated - too many lines)
Full output: too long to upload
int x; cout << "Type a number: "; // Type a number and press enter cin >> x; // Get user input from the keyboard cout << "Your number is: " << x; // Display the input value
is what i'm trying to replicate
That would be difficult given you're trying to assign to a string.
yes
ah, remake int
!e (lambda owo: owo >_<)(type("owo", (), {">_<": ...}))
@sudden willow :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | (lambda owo: owo >_<)(type("owo", (), {">_<": ...}))
003 | ^
004 | SyntaxError: invalid syntax
Identifiers have to be letters, digits or underscores (for rather loose definitions of each).
sadly
They also can't begin with digits.
There's probably some Unicode letter that looks like > or <.
Look into custom codings codecs.
You can do a lot of crazy stuff by hooking into site.
i guess its time to create the most painstaking part of my command line
actual file management
https://github.com/ssize-t/inlinec and https://github.com/dropbox/pyxl can all ignore Python syntax.
Why not both?
😳
!e this will probably tell me that o is an invalid keyword argument ```py
class Int(int):
def init(s,*a,name=""):setattr(s,'name',name)or super.init(s,*a)
int=type("statement",(),dict(getattr=lambda s,o:globals().update({o:Int(0,name=o)})or s,call=lambda s,*a:type("",(),{'enter':lambda s:a,'exit':lambda s,*b:True})()))()
cout=type(str(),(),{"lshift":lambda s,o:print(o,end=' ')or s})()
cin=type(str(),(),{'rshift':lambda s,o:globals().update({o.name,o.class(input(),name=o.name)})})()
#---
int.x
cout << "whee"
cin >> x
cout << "your number is" << x
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 9, in <module>
003 | File "<string>", line 3, in <lambda>
004 | TypeError: 'name' is an invalid keyword argument for int()
never really understood super().__init__()
It's special compiler magic that's replaced by super(self.__class__, self) ... iirc
😦
Only within method contexts (super)
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 10, in <module>
003 | File "<string>", line 4, in <lambda>
004 | File "<string>", line 3, in __new__
005 | TypeError: object.__new__(Int) is not safe, use int.__new__()
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 10, in <module>
003 | File "<string>", line 4, in <lambda>
004 | File "<string>", line 2, in __init__
005 | TypeError: object.__init__() takes exactly one argument (the instance to initialize)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
@floral meteor :x: Your eval job has completed with return code 1.
001 | whee Traceback (most recent call last):
002 | File "<string>", line 13, in <module>
003 | File "<string>", line 7, in <lambda>
004 | EOFError: EOF when reading a line
!e ```py
input=lambda:print("4")or "4" # snekbox
#---
int=type("statement",(),dict(getattr=lambda s,o:globals().update({o:type("Int",(globals()['builtins'].int,),dict(named_as=lambda self, name:setattr(self,"name",name)or self))(0).named_as(o)})or s,call=lambda s,*a:type("",(),{'enter':lambda s:a,'exit':lambda s,*b:True})()))()
cout=type(str(),(),{"lshift":lambda s,o:print(o,end=' ')or s})()
cin=type(str(),(),{'rshift':lambda s,o:globals().update({o.name:o.class(input()).named_as(o.name)})})()
#---
int.n.m
cout << "give number:"
cin >> n
cout << "give another number:"
cin >> m
cout << "your numbers are:" << n << "," << m << '\n'
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | give number: 4
002 | give another number: 4
003 | your numbers are: 4 , 4
004 |
I don't think that's C.
c++ i mean
python doesn't give a good way to do int n m so int.n.m will have to do
int.n.m
cout << "give number:"
cin >> n
cout << "give another number:"
cin >> m
cout << "your numbers are:" << n << "," << m << '\n'
you gotta admit it's pretty hacky, no imports.
I'm adding that to my cursed module
Looks splendid right next to my switch suite
using annotations to store values...
using annotations as a variable manager
globals: globals() = annotations_; print(globals['globals'])
!e globals: globals = annotations; print(globals['globals'])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
{'globals': {...}}
wait it execs after assignment?
!e ```py
globals: globals()
globals=annotations
print(globals['globals'])
print(globals['globals']['globals']['globals'])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {'globals': {...}}, '__builtins__': <module 'builtins' (built-in)>, 'globals': {'globals': {...}}}
002 | {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {'globals': {...}}, '__builtins__': <module 'builtins' (built-in)>, 'globals': {'globals': {...}}}
wait hol up that doesn't make sense
!e ```py
globals: globals()
globals=annotations
print(globals['globals'])
print(globals['globals']['globals'])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {'globals': {...}}, '__builtins__': <module 'builtins' (built-in)>, 'globals': {'globals': {...}}}
002 | {'globals': {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {...}, '__builtins__': <module 'builtins' (built-in)>, 'globals': {...}}}
ah
actually, globals['globals'] is globals() which contains globals
!e ```py
globals: builtins.globals() = globals()['annotations']
GLOBALS: print
globals'globals'.upper()
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
{'globals': {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {...}, '__builtins__': <module 'builtins' (built-in)>, 'globals': {...}}, 'GLOBALS': <built-in function print>}
try saying that code really fast
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {'GLOBALS': <module 'builtins' (built-in)>, 'globals': {...}}, '__builtins__': <module 'builtins' (built-in)>, 'GLOBALS': <built-in function print>, 'globals': {'GLOBALS': <module 'builtins' (built-in)>, 'globals': {...}}}
you can't get more international than that...
!e ```py
GLOBALS: globals()['builtins'] = builtins.print
globals: annotations['GLOBALS'].globals() = globals()['annotations']
globals['globals']'GLOBALS'
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {'GLOBALS': <module 'builtins' (built-in)>, 'globals': {...}}, '__builtins__': <module 'builtins' (built-in)>, 'GLOBALS': <built-in function print>, 'globals': {'GLOBALS': <module 'builtins' (built-in)>, 'globals': {...}}}
should I make actual functional code?
using only variables named globals and annotations?
!e ```py
Globals: "Hello" = "World!"
GLOBALS: globals()['builtins'] = builtins.print
globals: annotations['GLOBALS'].globals() = globals()['annotations']
globals['globals']'GLOBALS'
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
>>> with open("/proc/self/mem", "r+b") as mem:
... mem.seek(id(6*9) + 24)
... mem.write(bytes([0xa4, 0x01]))
...
140500850798568
2
>>> 6*9
420
```because who needs ctypes
hmm, why do you need to seek 24 bytes past the id of 6*9 (putting you on the beginning of the next object)?
Yep
yeah
Holy shit, fuckit failed
you cant fuck this
dun dun dun dun
dun dun
dun dun
hammer time!
Lmao
now back to my global disaster!
!e ```py
globals: globals()
globals()[globals.name] = globals()['annotations']
g1obals: ("Hello","World!") = globals['globals']['builtins'].print
globals['globals']'g1obals'
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
@floral meteor :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 8, in <module>
003 | File "<string>", line 2, in add
004 | UnboundLocalError: local variable 'locals' referenced before assignment
bruh

!e ```py
def add(a, b, globals):
globals: globals(); locals: locals() = builtins.locals
globals()['globals']=[globals()['annotations'],locals()['annotations']]
locals=globals[0]['builtins'].print
globals[1]['globals']['.'] = globals[1]['locals'].pop('a') + globals[1]['locals'].pop('b')
locals(globals[1]['globals']['.'])
globals()["2"]=3
globals()['add'](2, globals()['2'], globals)
I love my cursed module maybe i should upload it to pypi
@sick hound
@floral meteor Is it printing C++ code grammatical? For example, "print('cin > hello')"?
It's probably printing the C++ code grammatical.
the code is literally...
int=type("statement",(int,),dict(__getattr__=lambda s,o:globals().update({o:type("Int",(globals()['__builtins__'].int,),dict(named_as=lambda self, name:setattr(self,"__name__",name)or self))(0).named_as(o)})or s,__call__=lambda s,*a:type("",(),{'__enter__':lambda s:a,'__exit__':lambda s,*b:True})()))()
cout=type(str(),(),{'__repr__':lambda s:"\n","__lshift__":lambda s,o:print(o,end=' ')or s})()
cin=type(str(),(),{'__rshift__':lambda s,o:globals().update({o.__name__:o.__class__(input()).named_as(o.__name__)})})()
you can't really input to the bot so showing you that way will require input to be hacked a little bit
!e @sick hound ```py
#snekbox hack
input = lambda: print("4") or "4"
#py to c hack
int=type("statement",(int,),dict(getattr=lambda s,o:globals().update({o:type("Int",(globals()['builtins'].int,),dict(named_as=lambda self, name:setattr(self,"name",name)or self))(0).named_as(o)})or s,call=lambda s,*a:type("",(),{'enter':lambda s:a,'exit':lambda s,*b:True})()))()
cout=type(str(),(),{'repr':lambda s:"\n","lshift":lambda s,o:print(o,end=' ')or s})()
cin=type(str(),(),{'rshift':lambda s,o:globals().update({o.name:o.class(input()).named_as(o.name)})})()
#---
int.n.m
cout << "this is not c++\n"
cout << 'give number>'
cin >> n
cout << 'gib another number>'
cin >> m
cout << "your numbers:" << n << "and" << m
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | this is not c++
002 | give number> 4
003 | gib another number> 4
004 | your numbers: 4 and 4
@floral meteor That code doesn't work.
wdym?
!e alright i modified it cos automatic whitespacing was annoying.
input = lambda: print("4") or "4"
###
int=type("statement",(int,),dict(__getattr__=lambda s,o:globals().update({o:type("Int",(globals()['__builtins__'].int,),dict(named_as=lambda self, name:setattr(self,"__name__",name)or self))(0).named_as(o)})or s,__call__=lambda s,*a:type("",(),{'__enter__':lambda s:a,'__exit__':lambda s,*b:True})()))()
cout=type(str(),(),{'__repr__':lambda s:"\n","__lshift__":lambda s,o:print(o,end='')or s})()
cin=type(str(),(),{'__rshift__':lambda s,o:globals().update({o.__name__:o.__class__(input()).named_as(o.__name__)})})()
###
int.n.m
cout << "this is not c++\n"
cout << 'give number> '
cin >> n
cout << 'gib another number> '
cin >> m
cout << "your numbers: " << n << " and " << m
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | this is not c++
002 | give number> 4
003 | gib another number> 4
004 | your numbers: 4 and 4
much better
ty
should I expand this and call it py++?
:P
or should I keep it in my cursed module?
and rename it to cursedutils
I originally made cursed to make this work:
>>> print (four-hundred and twenty)
420
that's very cool
by shipping the bytecode and some tiny wrapper, yes
what do you mean by shipping the bytecode
I like the method you've used here to make int.n.m work. But I don't understand what the __call__ context manager is for.
!e
with(type("", (), {"__enter__":return,"__exit__":return})())as(owo):
owo
@toxic jewel :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | with(type("", (), {"__enter__":return,"__exit__":return})())as(owo):
003 | ^
004 | SyntaxError: invalid syntax
sadge
!e
with(type("", (), {"__enter__":lambda *args:1,"__exit__":lambda *args:1})())as owo:
owo
@steep mural :warning: Your eval job has completed with return code 0.
[No output]
you should probs print it
!e py with(type("", (), {"__enter__":lambda *args:1,"__exit__":lambda *args:1})())as owo:print(owo)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
1
If your object has __enter__ and __exit__ then it is said to 'implement the context manager interface,' yes I know it's for using with a with statement, I'm trying to understand what it was intended to be used for, given that it didn't seem to be used in the example.
I was starting to try to find a work around for another usage for the int statement in c++
with int(2,3) as n, m:
cout << n << " " << m << " are your integers"
Ah, ok, I had literally never seen that c++ syntax before. so I didn't recognize what syntactic sugar you were implimenting.
since you can't really do
int n m
int() {
cout << "give two numbers> "
cin >> n
cout << " "
cin >> m
cout << n << " " << m << " are yer numbers"
return n m
}
Right.
so a python context manager is the best I could come up with for allowing an indented code block
also, in cout, '__repr__':lambda s:"\n" otherwise, you do the printing to cout in terminal it will append <__main__. function>
Methods are passed self as their first argument. Maybe you meant to ignore that argument?
nods a while ago I managed to implement cout << in a way I liked, mostly because I was trapping and reassigning output and debugging messages anyway, and figured why not. Then for completeness sake I went to try the same with cin >> and realized the thing I had just about stopped worrying about, everything passed by reference means, actually nothing is... I went messing around with various things, including decorators and re-compiling, until I realized that someone else had already done that better.
I like what you've done here to implement that, and that it only needs objects to to know their own __name__ the only thing I can think of to give more reliable results would require disassembling the calling frame's code object, which would be a lot of extra work. At which point, is there a way to interact with locals instead of globals?
Anyway, good job, etc.
Lately my preferred debug output trapping pattern has been:
DEBUG = print
class c:
def __init__(self, [normal stuff], log=DEBUG):
#normal stuff
self.log = log
def do_some_work(self):
self.log("starting some work")```
eventually, after I finish implementing and testing the module, I replace the first line with ```DEBUG = lambda *a, *k: None```
And still retain the ability to turn on debugging messages for specific instances of the class by initializing them with `log=print `
noice
code i make isn't debuggable
it's just code puke
if it doesn't work, that's unfortunate
shrug I usually try to make it readable while I'm figuring out how to implement it, I can shrink cut out unnecessary bits and golf it later.
I wasn't meaning the __repr__ method, I meant however it's getting printed. (I can't see the code.)
it's already printing stuffs, but the trailing expression after a chain of << will repr in the terminal as self.repr hence i want the trailing expression to repr as a newline
so it prints all the stuffs, then evaluates the repr and starts a new line
Ah, I understand.
sweet mother of lord
this is beautiful
I did that too
Wheres your source?
def randcase(string):
return ''.join(__import__('random').choice((str.upper, str.lower))(char) for char in string)
```im new to any sort of code golfing and i do believe this can be shortened way, way shorter... is there any way that i can do it?
lambda s:''.join(__import__('random').choice((str.upper,str.lower))(c)for c in s)```
yeah, the two most basic tips in golfing are:
- use short (ideally single-character) variable names
- avoid unnecessary whitespace (which there is actually a lot of where you wouldn't expect it in ungolfed code)
also, def f():return can be shortened into f=lambda:
hello worldpy print("".join("deHlorW! "[0 if i == 10 else 1 if i == 1 else 2 if i == 0 else 3 if i in [2,3,9] else 4 if i in [4,7] else 5 if i == 8 else 6 if i == 6 else 7 if i == 11 else 8 ] for i in range(12)))
just midnight thoughts for obfuscation people rather than dunder people:
(some complex math or whatever)**False is True (or rather literally: 1)
so you can do e.g. if (some complex math or whatever)**False to weird people out
(x&1)**(x&1) is always true.
Well, it doesn't work for complex maths or float maths.
wait what 0 ** 0 == 1 in python
that's wack
It probably stems from how IEEE 754 floats are meant to work.
isn't that how it works irl
huh ok
uh no, it's undefined
hmm
!e
print("Test")
@violet rune :white_check_mark: Your eval job has completed with return code 0.
Test
Feel free to use #bot-commands to test out things.
!e
!eval [code]
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*
!eval print("Hello Worllllllllddddd")
@bitter moth :white_check_mark: Your eval job has completed with return code 0.
Hello Worllllllllddddd
Noice
!eval print('test passed')
@pale cove :white_check_mark: Your eval job has completed with return code 0.
test passed
thats the code to pretend like you accomplished something
Not very esoteric though.
true
!e __import__("sys").stdout.write("this is a more esoteric way of doing it")
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
this is a more esoteric way of doing it
!e py __builtins__.__dict__.__getitem__(__builtins__.__dir__().__getitem__(().__class__.__name__.__len__().__mul__(....__str__().__len__())))("but this is even worse")
@tribal moon :white_check_mark: Your eval job has completed with return code 0.
but this is even worse
Nice, how about:
!e py r=lambda s:''.join(__import__('random').choice((str.upper,str.lower))(c)for c in s) p=lambda s,r=__import__('random').choice,f=[getattr(__import__('sys'),f)for f in['stdout','stderr']]:[print(c,file=r(f),end='')for c in s] p(r('hello world!'))
@vague cairn :white_check_mark: Your eval job has completed with return code 0.
HELlo worlD!
Oof, doesn't differentiate stream by color, how sad.
Where can I find the code-under-the-hood for python's amazing a, b = b, a feature?
b, a is just sugar to construct a tuple (b, a).
a, b = x is a destructuring assignment that iterates over every element of x, and tries to assign the first & second elements to a and b. (It also raises when there's the wrong amount of elements to unpack in x.)
Together, you constuct a tuple of b and a, then assign a and b to the first & second elements of the tuple you constructed.
Ah, very cool. Thanks Olivia.
You can also do cool nested destructurings like
a, (b, c), *rest = x
And to get the first element of a list with one element, you can do a ,= [b].
@harsh idol Don't randomly post fork bombs, especially with no context. Not cool
!e
a = 1 if a == 1 & a != 2: print("a")
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
a
didnt know & was a thing
it's bitwise and
!e
print("Hello World!"[::-1][-1::-1][-1:-1-1-1-1-1-1-1-1-1-1-1-1-1:-1][-1])
@cloud fossil :white_check_mark: Your eval job has completed with return code 0.
H
!e
# reel proof 2 wrongs == a right
wrong = 0
print(wrong.__add__(wrong).__invert__().__abs__().__bool__())
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
True
abs = absolute value?
That's the one.
👍
I already solved this exercise and thought I should share:
The challenge was to make the following function without + nor list.extend() nor loops:
def extend_list_x(list_x, list_y):
pass # should return [1, 2, 3, 4, 5, 6] for list_x=[4, 5, 6] and list_y=[1, 2, 3]
So, my unpacking solution was this:
def extend_list_x(list_x, list_y):
return [*list_y, *list_x]
and my recursion solution was this:
def extend_list_x(list_x, list_y):
temp_list = list_x[:]
if len(list_y):
temp_list.insert(0, list_y[len(list_y)-1])
return extend_list_x(temp_list, list_y[:-1])
return temp_list
So my question is: Can you guys think of any other way to do it?
def extend_list_x(list_x, list_y):
lst = []
lst[:] = list_x
lst[len(lst):] = list_y
return lst
🙂
can make the first two lines lst = list_x.copy()
ahh
your function actually outputs [4, 5, 6, 1, 2, 3] though
but ye you can just copy the other thing
no it doesn't
😐
oh, it's supposed to be in the other order
ye
okay then,
def extend_list_x(list_x, list_y):
lst = list_y.copy()
lst[len(lst):] = list_x
return lst
i originally intended these to change list_x
i didn't know you can append like that
that's so weird
then it'd just be one line, list_x[len(list_x):] = list_y
i mean extend
that's slice assignment
the nonintuitive thing is that it can be used in ways that change the list's size
i thought it would raise IndexError or something
I'm technically setting a 0-length slice to an entire list, producing an effect like an extend.
ye i thought slice assignment gives errors
like index out of range errors
very cool
this is a hack
XD
and this is a press ctrl-c to continue XD
huh actually that gives me a couple real application ideas
like exiting multiple for loops without flags
with suppress(CustomError):
for i in lst:
for j in lst2:
for k in lst3:
...
if value == bad_value: raise CustomError```
and that'd just exit the whole block
without having to wrap it in try except, you can just nest it in a context manager
and it's secure: it doesn't create a traceback object, hence it gives you an opportunity to delete decrypted data before it can be caught
well ig you kind of are but in 1 block compared to 2+a line
for example.
def dingdong():
data=42
1/0
del encrypted_data
try: dingdong()
except ZeroDivisionError as e:
print(e.__traceback__.tb_frame.f_locals['data'])
pretty hacky shit you can do with exception tracebacks tho
I use it from an instance from a class from a module so I can use the globals as context
or modify them >:D
while True:
try:
pass
except(KeyboardInterrupt): # idk if you can tell but i've been doing too much java/non python
pass```
ya that's too hacky 5 me :(
!e tis easy to get the globals from where a function is called.
class HackyShit:
def __call__(self,var):
try:raise Exception
except Exception as e:return e.__traceback__.tb_frame.f_back.f_globals.get(var,None)
hack=HackyShit()
a=4
print(hack('a'))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
4
why in the __call__?
Trust me, that's useful. cos when you import a namespace, it has a different globals, hence just calling globals() from a function in there will access the module's globals, not the active script
just to show it being called. that's what __call__ is
like, what if hackyshit wants to see your global annotations to implement some hacky syntax sugar involving colons?
you just do globals()['__annotations__'] and that will call on the module
this accesses where the method is being called from
!e the ultimate HackyShit:
def Switch():
"""Generates switch-case-otherwise suite
:return: switch, case, otherwise"""
class Case:
"""Generation for case object which powers all three methods"""
def __init__(self):self.value,self.state=None,-1
def __getitem__(self, item):
try:1/0
except Exception as _:__annotations__=_.__traceback__.tb_frame.f_back.f_globals.get('__annotations__',{})
if self.state<0:
if'switch'not in __annotations__:raise SyntaxError("Cannot find matching switch")
else:self.value=__annotations__['switch']
elif self.state>=0:
if'switch'in __annotations__ and locals()['__annotations__']['switch']!=self.value:self.value=__annotations__['switch'];self.state=0
if self.value==item:self.state+=1
else:return lambda*_,**__:None
return lambda f,*args,**kwargs:f(*args,**kwargs)
case=Case()
def switch(v):case.value,case.state=v,0
def otherwise(f,*args,**kwargs):
if not case.state:value=f(*args,**kwargs)
elif case.state<0:raise SyntaxError("Cannot find matching switch.")
else:value=None
case.state=-1;return value
return switch,case,otherwise
switch, case, otherwise = Switch()
switch: True
def do_one_thing(cond):
@case[bool(cond)]
def do():
print(420)
@case[not cond]
def do():
print("im dum")
def do_another_thing(cond):
@case[not cond]
def do():
print(69)
do_one_thing(4)
do_another_thing(0)
do_one_thing(0)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 420
002 | 69
003 | im dum
!e for a while im like, aw no i have to do my switch case otherwise in expressions and obfuscated lambdas, etc..
def Switch():
"""Generates switch-case-otherwise suite
:return: switch, case, otherwise"""
class Case:
"""Generation for case object which powers all three methods"""
def __init__(self):self.value,self.state=None,-1
def __getitem__(self, item):
try:1/0
except Exception as _:__annotations__=_.__traceback__.tb_frame.f_back.f_globals.get('__annotations__',{})
if self.state<0:
if'switch'not in __annotations__:raise SyntaxError("Cannot find matching switch")
else:self.value=__annotations__['switch']
elif self.state>=0:
if'switch'in __annotations__ and locals()['__annotations__']['switch']!=self.value:self.value=__annotations__['switch'];self.state=0
if self.value==item:self.state+=1
else:return lambda*_,**__:None
return lambda f,*args,**kwargs:f(*args,**kwargs)
case=Case()
def switch(v):case.value,case.state=v,0
def otherwise(f,*args,**kwargs):
if not case.state:value=f(*args,**kwargs)
elif case.state<0:raise SyntaxError("Cannot find matching switch.")
else:value=None
case.state=-1;return value
return switch,case,otherwise
def do_stuff(switch, case, otherwise):
switch(5)
case[4](print,"this stuff rigged")
case[5](print, "code green")
otherwise(lambda:print("error in otherwise"))
do_stuff(*Switch())
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
code green
Was having a look at this https://codegolf.stackexchange.com/questions/217690/speed-of-lobsters.
@floral meteor :x: Your eval job has completed with return code 1.
001 | Hey, this works!
002 | Traceback (most recent call last):
003 | File "<string>", line 39, in <module>
004 | File "<string>", line 21, in otherwise
005 | File "<string>", line 39, in do
006 | ValueError
in #esoteric-python if you get an error all u'll get is F
if you're lucky
!e but then I realised what i made is much more powerful than that. I could use case as a decorator, and it suddenly becomes readable. ```py
def Switch():
"""Generates switch-case-otherwise suite
:return: switch, case, otherwise"""
class Case:
"""Generation for case object which powers all three methods"""
def init(self):self.value,self.state=None,-1
def getitem(self, item):
try:1/0
except Exception as :annotations=.traceback.tb_frame.f_back.f_globals.get('annotations',{})
if self.state<0:
if'switch'not in annotations:raise SyntaxError("Cannot find matching switch")
else:self.value=annotations['switch']
elif self.state>=0:
if'switch'in annotations and locals()['annotations']['switch']!=self.value:self.value=annotations['switch'];self.state=0
if self.value==item:self.state=1
else:return lambda*_,**__:None
return lambda f,*args,**kwargs:f(*args,**kwargs)
case=Case()
def switch(v):case.value,case.state=v,0
def otherwise(f,*args,**kwargs):
if not case.state:value=f(*args,**kwargs)
elif case.state<0:raise SyntaxError("Cannot find matching switch.")
else:value=None
case.state=-1;return value
return switch,case,otherwise
#---
switch, case, otherwise = Switch()
switch: 420
@case[69]
def do():
raise ValueError(69)
@case[420]
def do(s="Hey, this works!"):
print(s)
@otherwise
def do(): raise ValueError
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hey, this works!
The thing I don't like about pattern matching for 3.10 is making the default part
there should be default: instead of case _:
thoughts?
my switch-case-otherwise suite far superior.
Yes lol
You should get into bytecode manipulation, similar to how chilaxan does it
I'd love it see how you'd use that for patma in 3.10
I ran dis on it
i don't need to do bytecode I already have
switch, case, otherwise = __import__('cursed').Switch()
switch: 420
@case[69]
def do():
raise ValueError(69)
@case[420]
def do(s="Hey, this works!"):
print(s)
@otherwise
def do():
print("this wont print")
raise ValueError
Make your own syntax
make your own language
similar to what I did before
It was really fun
And esoteric 😛
I can make a brainfuck interpreter.
That's a Turing Complete language with its own syntax and language.
easy to make in python
you can't suppress a syntax error in python as it raises before anything that would try to could even compile
And that's where the creativity comes
hence it would have to read string or file, and run from something that passes the SyntaxError test
whatever you make in python has to pass the SyntaxError test to compile. Once you can get it to compile, you can get it to do anything
like
>>> print(four-hundred and twenty)
420.0
>>> print(sixty-nine)
69.0
since that doesn't raise syntaxerror, all sorts of hackery could be used to make that legit (involving assigning instantiated objects to all those names, make them communicate via a core object passed to them all, and have bool, repr and str methods activate them)
also swap sub and add methods of float
@tribal moon
okay, then, here's a challenge for you:
>>> print ( five-hundred and three-thousand and nine-hundred and forty-four-point-seven-seven-nine-three )
503944.7793
>>>
depends how high you make it.
here's the bootstrap function to start you off with:
@classmethod
def _bootstrap(_):
cc=_.CursedCore()
hundred = Cursed(100,1,cc);thousand=Cursed(1000,1,cc);million=Cursed(1000000,1,cc)
billion = million*thousand;trillion=billion*thousand;quadrillion=billion*million
septillion=quadrillion*billion
zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve=(Cursed(_,cc=cc)for _ in range(13));thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen=(Cursed(_,cc=cc)for _ in range(13,20));twenty,thirty,forty,fifty,sixty,seventy,eighty,ninety=(ten*Cursed(_,cc=cc)for _ in range(2,10))
a=one
_.stuff = locals();return locals()
---
from cursed import Cursed
globals().update(Cursed.__bootstrap())
a=one:
>>> print( a-hundred and five )
105
!e ```py
ಠ_ಠ = 69
print ( int.mul(10*(ಠ_ಠ//10),(ಠ_ಠ%10)-2) )
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
420
alright, that algorithm will be the new target for my chain wrapper.
new addition to the cursedutils module, yet to be tested
from cursedutils import Chain
cause, effect = Chain()
@cause # calls cause with split as argument
def split(_69): return _69.__divmod__(10) # split is a chain_link object
@split # call chain_link object with new function
def left_bias(_6,_9): return _6*10,_9-2 # left_bias is now the chain_link
@left_bias # call lef_bias with rejoin
def rejoin(_60,_7): return _60*_7
make_algorithm_fancier = effect(rejoin) # rename wrapper cos lol
@make_algorithm_fancier # no longer need to have complicated main func
def main(input):
output=input # really complicated algorithm to process input
return output
>>> # python terminal
>>> print(main(69)) # test
420
CEO obviously just hard coded in every real number in his function
hey everyone, im new to python and i just need help wtih my calculator code
im not sure what i did wrong
#❓|how-to-get-help is probably your best bet.
(Although I think you're missing some commas between parameters on line 10.)
(And it's the same on 12, 14 and 16.)
@pseudo reef nice
ty!
!e
print(type("test owo", (), {}).__dir__())
@toxic jewel :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: unbound method object.__dir__() needs an argument
sadge
now this sounds like something I'd make
why my string replace doesnt work
def dataCollector(msg):
lst = msg.splitlines()
coin = lst[0]
lst.pop(0)
print(lst)
for el in lst:
el.replace('*','')
print(lst)
msg = ": "
msg = msg.join(lst)
lst = msg.split(': ')
the for loop isnt working at all
msg is set outside the function
that method of implementing case is awesome, how does that case work?
this code doesn't look very esoteric

!e
class O:
def w(self, *file):
open(' '.join(x for x in file))
o = O()
o.w o
@sudden willow :x: Your eval job has completed with return code 1.
001 | File "<string>", line 5
002 | o.w o
003 | ^
004 | SyntaxError: invalid syntax
:sadge:
is there a guide on how to do these esoteric stuff with python?
Maybe we should compile a compendium of tricks to summarise what's possible in Python.
That way it could be found somewhere search-engine–indexable, rather than tied to this specific corner of the net.
What if future generations need to golf Python?
No, because esoteric python is not a good practice
Good idea
good practice as in standards + clean code or as in practising the language?
'A practice' so standards.
!e
class W:
@property
def o(self): exec("print('uwu')")
class O:
w = W()
o = O()
o.w.o```
@alpine flower :white_check_mark: Your eval job has completed with return code 0.
uwu
.
Everyone choose a favourite piece of Python tomfoolery, the kind of thing you might use to entice someone into the esoteric web. That can be the starting point of a guide.
[0x_for x in input("Hello, world!")] is probably my favourite morsel.
(It evaluates to [15].)
0x_f is a hex literal, 15. The or is parsed as a different word because it doesn't begin with a hex digit, so it's [15 or (x in input("..."))], and since or is short-circuiting, the second half is never executed.
That means no NameError from x.
wack
ooooooh lol
!e a ,= [0x_for x in input("Hello, world!")];print(a)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
15
that means you can do it with octal too
the comma-equals operator :>
!e py print({0o60for*O,in{__name__,}})
@tribal moon :white_check_mark: Your eval job has completed with return code 0.
{48}
lolol
lmao
Octal doesn't have an f.
:= walrus
,= pistol
+= increment
-= decrement
*= cannon?
/= idk?
//= crossroads
!= ne
== eq
<= le
>= ge
|= neutral face
&= imma say tank.
^= duck
%= u dont wanna know
$= just no.
#= commented equals :>
@= turret
~= definitely does not exist
;= SyntaxError for sure
[= smiley face!
]= frowny face
_= assign to underscore
?= does it equal?
.= gettattributeeequals, idk
)= frownier face
(= happier face
>>= shift to da right
<<= shift to da left
I wish there was a $ in Python
%= exists.
it's modulos
isn't it also like some js shenanigans?
There's also >>= and <<=.
we're talking about python lol
Oh, were you trying to name them all?
what do you think of crossroads operator?
The name or the operator?
the name
floor division lol
aye but the operator
It's a name. It wouldn't be understood unless you knew it already. ¯_(ツ)_/¯
floor division operator sounds lame.
Good thing we don't name operators based on whether they're lame.
!e a=4; a ^= 3; print(a)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
7
^= sqwawk
That's really cool
I made something new with it ~([0o60for*O,in({0o0},)][0x0]&[0x_for(0j)in[0x_e]][0x0])*~([0o60for*O,in({0o0},)][0x0]&[0x_for(0j)in[0x_e]][0x0])
Truthiness weird
But the ins
does it work?
!e print(~([0o60forO,in({0o0},)][0x0]&[0x_for(0j)in[0x_e]][0x0])~([0o60for*O,in({0o0},)][0x0]&[0x_for(0j)in[0x_e]][0x0]))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
1
imma use that instead of one now.
I originally made it to do this nice compact but limited syntax:
switch: 5
case[4](print,"no printy")
case[5](print,"status green")
otherwise(print,"status red")
but then i realised i could just use them as decorators and do this:
switch: 5
@case[4]
def do(): raise ValueError("This will not raise")
@case[5]
def do():print("status green")
@otherwise
def do():
import sys
sys.stderr.write("status red")
raise ValueError
but then there's the problem of variable assignment.
I could do some pretty hacky shit to read the locals of both environments but writing to them is beyond me.
!e ```py
def i_hate_locals():
a = 4
exec("a+=3",locals(),locals())
print(a)
i_hate_locals()
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
4
you see it can't write to locals
I like the decorators, but how does the switch start it off?
how is switch: 5 not a syntax error?
the
switch: i form only works in the global frame
if you're using it in a function or local frame, you write it as
switch(i)
!e switch: 5 = 2;print(annotations['switch'])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5
OOOOOOHHHHHHH!!!!!! nice.
!e however... ```py
a: 3
def i_hate_locals():
a: 9 = 4
exec("a+=3",locals(),locals())
print(a)
print(annotations['a'])
i_hate_locals()
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 4
002 | 3
if functions worked the way i wanted them to, that would be 7 and 9 not 4 and 3
hence within a function you gotta do ```py
def i_still_hate_locals():
switch, case, otherwise = Switch()
switch(5)
@case[4]
def do(): raise ValueError("this will not raise")
@case[5]
class do:init=lambda s: print("status green")
@cotherwise
def do():
sys.stderr.write("status red")
raise ValueError
Is there any way to force the parser to stop parsing a file from within?
however, unlike other languages, you can mix the suite into the code, rather than isolate it into a block
from cursedutils import Switch
switch: type("Truthy",(int,),{'__eq__':lambda s,o:o and True or False})(1) = Switch()[0]
def do_one_thing(cond):
case,otherwise=Switch()[1:]
@case[cond]
def do(): print("doot")
@otherwise
def do(): print("no doot for you")
def do_another_thing(cond, a:list):
case,otherwise=Switch()[1:]
@case[cond]
def do(): a.append(4)
@otherwise
def do(): a.pop(0)
return a
do_one_thing(1)#doot
do_one_thing(0)#no doot for you
do_another_thing(0,do_another_thing(1,[0,1,2,3]))#[1,2,3,4]
wdym?
sounds like hacking
:P
Let's say I have a file AB where A is valid python and B is some binary data
I want python3 to parse A but stop reading the file at the start of B
yeah that should work
the chances the binary data doesn't raise an error or does effect the module are negligable
# a file runnings in ze python3
try: import AB
except: print("nope this shit unimportable. or is it?")
__import__('os').system("pip install fuckit")
import fuckit
fuckit('AB')
print(dir(AB)) # suddenly, it works.
:?
try it
I'm not sure what you're trying to say
whatever AB is, fuckit will filter out the non-python
a line raises a syntax error? fuckit.
you could make every second line binary data. fuckit will skip those lines and only import the lines that don't raise an error
That doesn't work in the same file, though
and no deps although I could reimplement fuckit
you can't do shit precompilation lol. it can't have any syntax error to compile in the first place, so nothing in the file will run if there's a wrong unicode character or something
could have said that from the beginning ty
do you know which line the binary data starts?
Okay got it
I'll use the -x command line arg to skip parsing the first line, embed the binary data there
Just make sure not to have any line endings
im typing hang on
invalid syntax !!!
print("Hello, world!")
python3 -x file.py
Hello, world!
cos when non-hackery fails me, i begin hackery
import os,ast
with open("AB.py.bin",'rb') as file:
for i,line in enumerate(file):
try: ast.parse(str(line))
except:break
with open("AB.py.bin",'r') as file: lines=file.readlines(i)
with open("A.py",'r') as foopy: foopy.write(chr(10).join(lines))
import A; os.remove('A.py')
# AB.py.bin
print("Hello World!")
invalid syntax ! ! !
binarydata100110101oyYUCVEifuye4fbow8yeigbeoygvberyvr7wrv98v&F867i6F*&f*&^v
python3 interpret_AB.py
Hello World!
that's not a bad idea I guess, until your binary data has character 10 in it
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
�
imma work on my chain wrappers
!e ```py
a: 54
b: 45
c: 21
d: 99
globals().update(annotations)
print(a,b,c,d) # fuck the equals sign lol
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
54 45 21 99
I have found something
!e
import inspect as i
def foo() -> "print(':)')": ...
exec(i.signature(foo).return_annotation)
@alpine flower :white_check_mark: Your eval job has completed with return code 0.
:)
!e
import inspect as i
n = 5
def foo(n: 'n') -> exec("print('n');foo('exec(i.signature(foo).parameters[\'n\'])' - 1) if exec('i.signature(foo).parameters[\'n\']') > 0 else return"): ...
exec("i.signature(foo).return_signature")```
@alpine flower :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | File "<string>", line 1
004 | print('n');foo('exec(i.signature(foo).parameters['n'])' - 1) if exec('i.signature(foo).parameters['n']') > 0 else return
005 | ^
006 | SyntaxError: invalid syntax
subjective
!e
import inspect as i
n = 5
def foo(n: "eval('n')", incr: "eval('-1')") -> "print(eval('n')); exec('foo(i.signature(foo).parameters['n'] + i.signature(foo).parameters['incr'], None)')"
exec("i.signature(foo).return_signature")```
@alpine flower :x: Your eval job has completed with return code 1.
001 | File "<string>", line 3
002 | def foo(n: "eval('n')", incr: "eval('-1')") -> "print(eval('n')); exec('foo(i.signature(foo).parameters['n'] + i.signature(foo).parameters['incr'], None)')"
003 | ^
004 | SyntaxError: invalid syntax
You could write it as a bash polyglot with a shebang, that installs something as a site codec that lets you parse the same file.
that's right, i was gonna make a chain wrapper
but i got distracted with using colons and globals().update(annotations) instead of equals
!e _69 = 420; print(_69)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
420
Can anyone pleaseee help me with a few things if so dm me
i really need help
most things done in this channel, #esoteric-python are beyond help
!e for example,
print("".join("deHlorW! "[0 if i == 10 else 1 if i == 1 else 2 if i == 0 else 3 if i in [2,3,9] else 4 if i in [4,7] else 5 if i == 8 else 6 if i == 6 else 7 if i == 11 else 8 ] for i in range(12)))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
is there a way to set how class methods are called?
yes.
You can definitely do that with metaclasses but there's probably more convenient ways
how would I do that with metaclasses?
!e ```py
b: 5
def funcy():
a=4
return locals()
globals().update(funcy())
globals().update(annotations)
print(a+b)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
9
oh god
not my code
(lambda f: f(f))(lambda f, prt=None, field={i: {j: "\u2588" if int(__import__("random").randint(0, 10) >= 9) else "X" for j in range(20)} for i in range(20)}: f(f, print("\n".join(["".join(row.values()) for row in field.values()])), {y: {x: "X" if ["X" if field.get(y + adj_y, {}).get(x + adj_x) in (None, "X") else "\u2588" for adj_y, adj_x in [(y, x) for x in range(-1, 2) for y in range(-1, 2) if not (x == 0 and y == 0)] ].count("\u2588") < 2 or [ "X" if field.get(y + adj_y, {}).get(x + adj_x) in (None, "X") else "\u2588" for adj_y, adj_x in [ (y, x) for x in range(-1, 2) for y in range(-1, 2) if not (x == 0 and y == 0) ] ].count("\u2588") > 3 or ( [ "X" if field.get(y + adj_y, {}).get(x + adj_x) in (None, "X") else "\u2588" for adj_y, adj_x in [ (y, x) for x in range(-1, 2) for y in range(-1, 2) if not (x == 0 and y == 0) ] ].count("\u2588") == 2 and field.get(y).get(x) == "X") else "\u2588" for x in range(20) } for y in range(20) } if input() != "q" else exit(),))
what does globals().update(__annotations__) do?
brainfuck=lambda c,i='',__=[[0],0,'',0]:(lambda a,j,o,z:[{
'+':lambda:a.__setitem__(j,(a[j]+1)%256),
'-':lambda:a.__setitem__(j,not a[j]and 256 or a[j]-1),
'<':lambda:(a:=[0]+a)if not j else (j:=j-1),
'>':lambda:[(j:=j+1),j==len(a)and a.append(0)],
'.':lambda:(o:=o+chr(a[j])),
',':lambda:[a.__setitem__(j,ord(i[0])),(i:=i[1:])if len(i)>1 else"\0"],
']':lambda:(s:=0),
'[':lambda:((o,c,i,s,j):=brainfuck(c,i,[a,j,o,1]))
}[_]()for _ in c if _ in'+-[],.<>']and(o,*(c,i,z,j)*z))(*__)
just saving this clipboard snippet in case i need my clipboard.
globals() returns a dictionary representing the global namespace.
update is something like this:
class dict:
...
def items(self):
iterable=[]
for element in self:
iterable+=[(element,self[element])]
return iterable
def update(self,d=None,**kwargs):
if d:
for this,that in d.items(): self.__setitem__(this,that)
if kwargs:
for this,that in kwargs.items(): self.__setitem__(this,that)
and __annotations__ searches the global frame for var: annotation
from inspect import signature as s
def wrapper(attr):
attr = s(attr).return_annotation
return locals()
class A:
def __init__(self):
for attr in (self.add, self.sub):
locals().update(wrapper(attr=attr))
def add(self) -> "return 1 + 1": ...
def sub(self) -> "return 1 - 1": ...
shouldn't that work?
no ig bc there's no way to exec it?
wdym?
as long as it doesn't raise syntax error, you can make anything do anything
some noobs: come to #esoteric-python to use !e commands and eval print ("Hello World!")
me:
def print(*args):
try:print (*args)
except:print (*args)
print ("Hello World")
XD
from typing import *
def print(*args: Any) -> NoReturn:
try:
print(*args)
except:
print(*args)
what I meant by this was something like
class A:
def add(self) -> "1 + 1": ...
def sub(self) -> "1 - 1": ...
def __method_call__(self, method):
return exec(s(method).return_annotation)
print(A().add())
>>> 2```but I can't figure out how to wrap each class method dynamically + how to wrap them in the first place
!e ```py
exec('exec("\x10time\tsleep\n\x10random\trandint\n\nn\x06196\n\x12\x0615\n\x05\x06119\n\x11\x060.02\n\n\x02\x06[]\n\n\rTrue:\x0f\x04\x06[]\x03if not \x0c>\x13i[1]):\x0f\x00\x00\x04\x0bi)\x0f\x02\x06\x04\x0f\x0fif\x13\x02) < \x12:\n\x01\rnot all([(abs(\x08 - i[0]) > 1) for i in \x02]):\x0f\x01\x02\x0b[\x08, \x0e, 1])\x0f\x00n\x06n + \x14\x0e[::-1])\x07\x06list(' ' * \x05)\x03s[i[0] - 1]\x06i[1][\x0c- 1]\x0fs\x06''.join(s)\x0fpr\x14'\\n' + s, end='')\n\x03\x0c+= 1\x07leep(\x11)".replace('\x14', 'int(\x00x13', ' len(\x00x12', 'max_\x02\x00x11', 'delay\x00x10', 'from \x00x0f', '\n\x00\x00x0e', 'str(n)\x00r', 'while \x00x0c', 'i[2] \x00x0b', '.append(\x00t', ' import \x00x08', 'new_width\x00x07', '\n\x00\x00\x00\x00\x00\n\x00s\x00x06', ' = \x00x05', 'screen_width\x00x04', 'existing_\x02\x00x03', '\n\x00for i in \x02:\n\x00\x00\x00x02', 'streams\x00x01', '\x00\x00new_width = randint(1, screen_width)\n\x00\x00\x00x00', ' '))'.replace('\x00', "').replace('\"))
@floral meteor :x: Your eval job timed out or ran out of memory.
001 |
002 | 1
003 | 9 8
004 | 6 8 1
005 | 7 7 6
006 | 4 1 7
007 | 3 3 5 5
008 | 6 7 9 2
009 | 8 4 5 1
... (truncated - too long, too many lines)
Full output: too long to upload
dafuq did i just do?
here's an example for my impl:
if __name__ == '__main__':
@pipeline
def x():
return 10
@x.chain
def y(z):
print(z)
return z, z+2
@y.chain
def a(b, c):
print(b + c)
x()
# Output:
# => 10
# => 22
``` I might add .chainFirst or .chainLast or w/e but this is good enough for now
was gonna release it as pypeline but that name is already taken :(
and yes you can multichain, but there's no guaranteed execution order
added the option to use a ThreadPoolExecutor too to dispatch multiple children concurrently
p = lambda s: lambda n: lambda v: n(v+s)
s = lambda n: lambda v: n(v)
h = lambda n: lambda v: n('')
e = lambda v: v
def fb(x):
pattern = lambda h, o: lambda sh, so: p(str(x))(h(sh(o(so(e)))))
if x % 3 == 0:
pattern = pattern(h, p('Fizz'))
else:
pattern = pattern(s, s)
if x % 5 == 0:
pattern = pattern(h, p('Buzz'))
else:
pattern = pattern(s, s)
return pattern('')
``` a fizzbuzz that never checks anything twice.
oh okay
!e print(1 and 2)
@toxic jewel :white_check_mark: Your eval job has completed with return code 0.
2
wgat
this is somehow the first time I have seen that 
wtf
x and y is x if x is false, otherwise it's y
thinking about makinga an esoteric tutorial in a way
or justj like methods i've used
!e print((1).__sqrt__())
@sudden willow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AttributeError: 'int' object has no attribute '__sqrt__'
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
5.0
So implement pow when the exponent is .5
yeah sadly theres no dunder for it thouhg
whats the difference between truediv and floordiv again
!e
print(10 .__floordiv__(5))
print(10 .__truediv__(5))
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
001 | 2
002 | 2.0
oh so does floordiv just strip decimal
floordiv does floor division (//)
truediv does true division (/)
!e py print(5 .__floordiv__(2)) print(5 .__truediv__(2))
@stark fable :white_check_mark: Your eval job has completed with return code 0.
001 | 2
002 | 2.5
there is no __div__
/ is __truediv__ and // is __floordiv__
owo
!e py print(~([0o60for*O,in({0o0},)][0x0]))
@dark loom :white_check_mark: Your eval job has completed with return code 0.
-49
!e py print(0o60for*O,in({0o0},))
@dark loom :white_check_mark: Your eval job has completed with return code 0.
<generator object <genexpr> at 0x7f0214c2e6d0>
if I have a function that returns something, how can I evaluate that and return it but only if its a specific thing
x if x != 0 else y
There might be an easy way if we have some more context. What sorts of values might you want to return/not return?
this channel is full of dark magics
I'd use light magics, but dark themes are easier on the eyes.
esoteric stuff is scary
it reminds me of that one thing you can do in node js that everyon makes fun og
Esoteric python is just a dash of code golf, some ctypes, eye of newt...
yeh, its the code golf and the ctypes i dont get
Code golf is the combination of lots of little tricks and prestidigitations. lambda, short circuiting, comprehensions and whitespace, mainly.
I don't bother trying to understand ctypes.
so basically its spray n' pray but in programming?
Code golf is finding the shortest possible program that does a certain thing
a freak show without the cultural implications, hopefully
look at my code! isn't it wonderful in its silliness?
@callable
def foo():
return "Hello, world!"
!e ```py
@print
@next
@iter
@str
@callable
def T(): return
@snow beacon :white_check_mark: Your eval job has completed with return code 0.
T
lol
!e ```py
@print
@str
@callable
def Hello_World(): return
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
True
is there any way to have variable names or function names or anything that i can include special characters in like :
If you're willing to use unicode homoglyphs (characters that look like the symbols but are different) you can probably include some of them, but not all
if you throw the variable namespace out the window altogether and use a dictionary as a variable manager
wasn't there one in python2 or something?
alright, apparantly the way to get people interested in #esoteric-python is show them the big red button
XD
!e
def 𝒉𝖊𝖑𝙡o(𝕟𝗮𝗆𝑒):
𝓅𝙧𝒾𝓷𝗍(f"Hello {𝐧𝕒𝗆𝐞}!")
𝐡𝒆lℓₒ('World')
@strange basin :white_check_mark: Your eval job has completed with return code 0.
Hello World!
!e
print(False if False**False else True)
@strange basin :white_check_mark: Your eval job has completed with return code 0.
False
!e print(0**0)