#esoteric-python

1 messages · Page 108 of 1

floral meteor
#

like

case[4]: print("i==4")
earnest wing
#

It's not put into annotations

#

afaik

floral meteor
#

but it's gotta be in the frame code

broken mesa
#

not the frame, but the ast definitley

floral meteor
#

ast? even better i spose

broken mesa
#

!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)

night quarryBOT
#

@broken mesa :white_check_mark: Your eval job has completed with return code 0.

int List
broken mesa
#

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

earnest wing
#

@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

broken mesa
#

yea one sec ive done it with dataclasses

#

lemme see

earnest wing
#
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>
broken mesa
#

!e ```py
from typing import List
a = List[int]
print(a.args)

night quarryBOT
#

@broken mesa :white_check_mark: Your eval job has completed with return code 0.

(<class 'int'>,)
broken mesa
#

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

floral meteor
#

hmmm

floral meteor
#

: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

sick hound
#

Will pattern matching ever get implemented? The PEP says it’s superseded, but I don’t know what that means in this context

steep mural
#

Yes look at pep 634 it was already accepted

snow beacon
#

It will be in Python 3.10.

sick hound
#

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?

formal sandal
#

!pep 634

night quarryBOT
#
**PEP 634 - Structural Pattern Matching: Specification**
Status

Accepted

Python-Version

3.10

Created

12-Sep-2020

Type

Standards Track

formal sandal
#

In fact, it's already implemented.

#

"superseded" means that a newer PEP makes that one deprecated.

astral rover
#

Or download 3.10a6

snow beacon
sick hound
#

how is it working

snow beacon
#

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.

grave rover
simple crystal
#

nice yeah since 3.8

earnest wing
#

very convenient

toxic jewel
#

posted this in the wrong channel before 😎

sick hound
#
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

toxic jewel
#

file handling

#

still need to figure out why it strips all spaces

#

oh i see why nvm

lunar ore
#

!e

print(*("fizz"*(not x%3)+"buzz"*(not x%5) or x for x in range(1,101)), sep="\n")
night quarryBOT
#

@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

lunar ore
#

Interviewers can suck it

twilit grotto
#

hired on the spot

lunar ore
#

Whats the shortest fizzbuzz can be in py3

#

Thats 78 chars with some white space trimmed

twilit grotto
#

i think 51? in this channel somewhere

lunar ore
#

smh

#

good enough is good enough

half cove
#

what is esosteric python?

toxic jewel
half cove
#

so what would that code do?

#

Does it show a graphical image

toxic jewel
#

no

night quarryBOT
#

:x: According to my records, this user already has a mute infraction. See infraction #29673.

fluid tree
night quarryBOT
#

@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

snow beacon
#

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
#

this is my life ^

floral meteor
#

heheheehehehe

#

XD

#

no imports

night quarryBOT
#

@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

floral meteor
#

!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

night quarryBOT
#

@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

grave dock
#

!e

print ("Hello World")```
night quarryBOT
#

@grave dock :white_check_mark: Your eval job has completed with return code 0.

Hello World
floral meteor
#

bruh why does forbiddenfruit not work?

stone bane
#

It's.. Forbidden

#

... I'll walk myself out now.

floral meteor
night quarryBOT
#

@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

floral meteor
#

this is the channel where a simple statement like that would crash python.

#

@grave dock this is how we hello world here

grave dock
#

:)

#

Ok

#

ahahahha

floral meteor
#

this is the insanity of trying to explain code that comes from here

floral meteor
grave dock
#

explain

floral meteor
#

explain what?

floral meteor
#

!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 _, __, ___, ____, _____, ______, _______, ________: _)))

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

Hello world!
floral meteor
grave dock
#

Ok

floral meteor
#

what needs explaining?

floral meteor
#
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

toxic jewel
#

pilgrims lmao

#

ive never understood what % does in python

floral meteor
#

modulus

grave dock
floral meteor
#

!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')

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | 1
002 | 0
003 | 2
004 | 0
grave dock
#

0_0

floral meteor
#

you want the unofficial esoteric tutorial, then?
or are you yet to learn python itself?

grave dock
#

I know python, but this was never written by 0_0. so I want an unofficial guide

#

:/

floral meteor
#

who's 0_0?

grave dock
#

do not mind it

#

just a smiley

floral meteor
#

alright before we start, just some tips;
error == ur fucked
no worky == ur fucked
want to patch == ur fucked
golfing != security

grave dock
#

Ahah

#

Ok:)

floral meteor
#

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

grave dock
#

I haven’t said yet that I’m Russian and I don’t know English well

floral meteor
#

noice

floral meteor
#

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

grave dock
#

Yes

#

I'm using google translate:)

#

and there was blood

floral meteor
#

yeah

Есть много разных занятий, подпадающих под категорию эзотерического кодирования.
например, код гольф - это код, состоящий из минимального количества символов.
в то время как brainfuck - это минималистский интерпретатор Turing Complete.
по сути, основная тема - вызов, кровь или искусство.

is the wrong translation. :P

grave dock
#

what is the right way then?

floral meteor
#

bit by bit or with a professional multilinguist

#

:P

grave dock
#

Heh, Okey

#

still find this specialist

#

Heh

#

there is also a checkmate

#

:/

#

further

floral meteor
#

defeat?

grave dock
#

No

floral meteor
#
гугл переводчик работать нет. приговор полностью
grave dock
#

:(

#

Yandex Translate norm?

floral meteor
#
может мне стоит просто закодировать змейку
grave dock
#

I'm going to school

#

so I can’t :(

floral meteor
#
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

grave dock
#

what does this code do?

floral meteor
#

idk it got really noisy here i can't think

grave dock
#

Ok

#

then then?

floral meteor
#

очень шумно

grave dock
#

I understood

#

Is it noisy?

floral meteor
#

yes

grave dock
#

Ok

#

I still go to school right now :(

floral meteor
#

Ладно. до свидания.

grave dock
#

Goodbye

floral meteor
#

!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)
night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | 4
002 | 4
floral meteor
#

strings have a different __mod__ method, which has nothing to do with integer modulus

terse mortar
#

Hmm what's the difference?

floral meteor
#

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)

terse mortar
#

What did you do lol

floral meteor
#

!e print(str.mod('%d',4))

night quarryBOT
#

@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
floral meteor
#

!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)
night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

4
floral meteor
#

foinally

#

@terse mortar i did it.

terse mortar
#

Pog

floral meteor
#

mod substitution

floral meteor
night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

Hello World!
floral meteor
#

@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!")
floral meteor
#
**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

grave dock
#

:)

floral meteor
#

😆

#

!e virgin forbiddenfruit (Запретный плод)

from forbiddenfruit import curse
curse(Ellipsis, "__call__", print)
...("Hello World!")
night quarryBOT
#

@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__'
floral meteor
#

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__"))
...()
floral meteor
floral meteor
grave dock
#

understandably

floral meteor
#

fishhook will hook a method to a класс

grave dock
#

.-.

grave dock
wild fractal
#

Никита

grave dock
#

Я

wild fractal
#

Что здесь делать

grave dock
#

Хз, просто официальный сервер.-.

#

Питона

wild fractal
#

А

grave dock
#

Б

#

@floral meteor What did you write?

floral meteor
#

fishhook will hook a method to a class

grave dock
#

got it

floral meteor
#

class as in тип

#

not class as in класс >_>

#

я тупой

grave dock
#

Нет

#

No

floral meteor
#

keep swapping English and Russian, in the translater, to see translation error

grave dock
#

There are no errors yet

floral meteor
#

much error -> большая ошибка <-> big mistake

grave dock
#

aa

floral meteor
#

particularly, as I'm not consistently eloquent, translate go boom

#

:>

grave dock
#

Heh

#

my lesson started: /

floral meteor
#

смайлики - это международный язык

floral meteor
#

😀

grave dock
#

👍

floral meteor
#

brainfuck == 🧠 🍆

#

fishhook == 🎣

#

there's still a few things I can't translate to emoji ;-;

class == тип
def == прием
print == стандартный вывод << шрифт
input == стандартный ввод >>
Переменная

wary swan
#

fishhook

#

is

#

weird

floral meteor
#

!e ```py
class стандартный:
lshift=print
rshift=input
стандартный() << "Привет, мир!"

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

Привет, мир!
floral meteor
#

wait this whole time you can make russian variable names?

#

*cyrillic

#

XD

#

!e ```py
class меер:
str=print
try:print(меер())
except:print(меер())

night quarryBOT
#

@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)
grave dock
floral meteor
#

!e ```py
def меер():
try:меер()
except:меер()
меер()

night quarryBOT
#

@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

snow beacon
strange basin
finite rose
#

!e
е = 1 # Cyrillic alphabet, "ye"
print(e) # Latin alphabet

night quarryBOT
#

@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
finite rose
#

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.

toxic jewel
#

read and write finished

toxic jewel
#

owo

floral meteor
rugged sparrow
#

locals()[name] = value doesnt work. @floral meteor

#

when locals is called, it builds a mapping that contains the current names -> values

floral meteor
#

!e ```py
def DOOT():
locals().update({'f':4})
print(f)
DOOT()

night quarryBOT
#

@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
floral meteor
#

bruh

#

BRUH

#

I am no longer using locals then

#

imma make a namespace stack in globals

#

XD

floral meteor
#

!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)

night quarryBOT
#

@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
floral meteor
#

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

rugged sparrow
#

you know i might be able to write code that makes locals()[name] = value actually work

#

acc i prob could yea

floral meteor
#

if you could find a way to access locals() non-locally that would be great :>

snow beacon
#

It has been tried in the past.

rugged sparrow
#

well it would require that the name name exists in the code

#

@snow beacon i can access the fastlocals array manually

floral meteor
#

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)
```?
rugged sparrow
#

afaik f_locals is like the mapping returned by locals()

#

lemme check

floral meteor
#

huh. what if...

rugged sparrow
#

it doesnt

#

lemme do some ctypes shit

floral meteor
#

!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

rugged sparrow
#

@floral meteor making locals() assignable has more issues than i forsaw

floral meteor
#

uh oh

rugged sparrow
#

yea cause any names that arent assigned to in that scope use LOAD_GLOBAL

#

(so messing with locals does nothing)

floral meteor
#

pycharm has r colouring 0o0

#

I prefer my much more explicit namespace regime

#

everything comes from globals

snow beacon
#

Myself I like adequate scoping, which is very difficult in Python.

night quarryBOT
#

@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
alpine flower
#

how long did that take you?

floral meteor
#

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=lambda
s: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']=lambda
a,**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)())

night quarryBOT
#

@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
floral meteor
#

fine, im importing the fuckit module

#

hey! no more errors!

floral meteor
#

uhoh did i forget to call globals?

sudden willow
#

why can't i f-

floral meteor
#
# 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?

rugged sparrow
#

!e ```py
def f():
try:1/0
except:f()

f()```

floral meteor
#

@sick hound you sound like Bernadette from Big Bang Theory

night quarryBOT
#

@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

sudden willow
#

!e
(lambda cout: cout << "Hello, World")(type("", (), {"__lshift__":print})())

night quarryBOT
#

@sudden willow :white_check_mark: Your eval job has completed with return code 0.

Hello, World
sudden willow
#

took a couple of tries

floral meteor
#

!e (lambda cout: cout << "Hello World!")(type("stdout", (), dict(lshift=print))())

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

Hello World!
floral meteor
#

it took me one try :>

sudden willow
#

owo

floral meteor
#

I have a whole module for that

sudden willow
#

!e (lambda cout: cout << "Hello World!")(type(str, tuple, dict(lshift=print))())

night quarryBOT
#

@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
sudden willow
#

sad

floral meteor
#

it looks like this

sudden willow
#

nice

floral meteor
#

the docstring is half the class.

#

the other half is code gore

sudden willow
#

oh

#

!e with type("", (), {"__lshift__": print}) as cout: cout << "hewwo world";

night quarryBOT
#

@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__
floral meteor
#

you need enter and exit

#

like this...

sudden willow
#

oh

#

!e with type("", (), {"__enter__": ..., "__lshift__": print, "__exit__": ...}) as cout: cout << "hewwo world";

night quarryBOT
#

@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__
floral meteor
#

!e ```py
with type(str(),(),{"lshift":print,"enter":lambda*s:s[0],"exit":lambda s,*e:True})() as cout:cout << "hewwo world!";

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

hewwo world!
floral meteor
#

that took me a few tries

sudden willow
#

nice

#

!e `class _cout:
def lshift():
print

with _cout() as cout:
cout << "lol";
`

night quarryBOT
#

@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__
sudden willow
#

ah

#

same process i assume

floral meteor
#

no, you need more dunders

sudden willow
#

o_o

snow beacon
#

with requires a valid context manager.

#

A context manager defines an __enter__ and __exit__.

sudden willow
#

still not too good at implementing with in my code

snow beacon
#

You've implemented a __lshift__. It's a similar principle.

floral meteor
#

!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;

snow beacon
#

In order to see what arguments with calls, you can try:

night quarryBOT
#

@floral meteor :warning: Your eval job has completed with return code 0.

[No output]
snow beacon
#

!e ```python
class Test:
def enter(*args, **kwargs):
print(args, kwargs)
def exit(*args, **kwargs):
print(args, kwargs)

with Test():
pass

night quarryBOT
#

@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) {}
sudden willow
#

cool

snow beacon
#

As you can see, __enter__ is just called with self, and __exit__ has some extra Nones.

sudden willow
#

i'm only really used to using the mathematical operator dunders

snow beacon
#

I'm pretty sure the Nones are related to exceptions thrown inside the with.

floral meteor
#

but if there's an error, those Nones stop becoming Nones. Maybe they lose their virginity?

snow beacon
#

Presumably they were never None in the first place, because None is singleton.

sudden willow
#

owo

snow beacon
#

Pun only half intended.

floral meteor
#

every time you say Nones i think nuns

snow beacon
#

I am aware.

sudden willow
#

none is falsey right

snow beacon
#

Correct.

floral meteor
#

so if there's an error, your code loses its virginity!

snow beacon
sudden willow
#

!e print(None.__bool__().__int__())

night quarryBOT
#

@sudden willow :white_check_mark: Your eval job has completed with return code 0.

0
floral meteor
#

!e assert bool(None)==False

night quarryBOT
#

@floral meteor :warning: Your eval job has completed with return code 0.

[No output]
snow beacon
#

!e print(+bool(print("None is: ")))

night quarryBOT
#

@snow beacon :white_check_mark: Your eval job has completed with return code 0.

001 | None is: 
002 | 0
floral meteor
#

!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"

night quarryBOT
#

@floral meteor :warning: Your eval job has completed with return code 0.

[No output]
snow beacon
#

Didn't you learn any lessons?

sudden willow
#

!e (lambda cin: cin >> "not exactly like c++ but eh")(type("", (), {"__rshift__": input})

snow beacon
#

Should be an =.

night quarryBOT
#

@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
sudden willow
#

man coding on mobiles hard

#

!e (lambda cin: cin >> "not exactly like c++ but eh")(type("", (), {"__rshift__": input})())

night quarryBOT
#

@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
sudden willow
#

!e (lambda cin: cin >> "not exactly like c++ but eh")(type("", (), {"__rshift__": __import__("sys").std.in})())

night quarryBOT
#

@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
sudden willow
#

hm

snow beacon
#

in is a keyword.

sudden willow
#

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})())

night quarryBOT
#

@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
sudden willow
#

!e input()

snow beacon
#

stdin is not a function.

night quarryBOT
#

@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
sudden willow
snow beacon
#

sys.stdin.readline or .read?

sudden willow
#

!e (lambda cin: cin >> "not exactly like c++ but eh")(type("", (), {"__rshift__": __import__("sys").stdin.read})())

night quarryBOT
#

@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'
sudden willow
#

not sure

snow beacon
#

What are you trying to do?

sudden willow
#

cin in python

#

like in c++

floral meteor
#

!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

snow beacon
night quarryBOT
#

@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

sudden willow
#

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

snow beacon
#

That would be difficult given you're trying to assign to a string.

sudden willow
#

yes

floral meteor
#

ah, remake int

sudden willow
#

!e (lambda owo: owo >_<)(type("owo", (), {">_<": ...}))

night quarryBOT
#

@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
sudden willow
#

hm

#

was hoping that would work

snow beacon
#

Identifiers have to be letters, digits or underscores (for rather loose definitions of each).

sudden willow
#

sadly

snow beacon
#

They also can't begin with digits.

#

There's probably some Unicode letter that looks like > or <.

sudden willow
#

time to modify python so i can have my variable named >_<

#

python fork

#

owopy

snow beacon
#

Look into custom codings codecs.

#

You can do a lot of crazy stuff by hooking into site.

sudden willow
#

i guess its time to create the most painstaking part of my command line

#

actual file management

snow beacon
sudden willow
#

hmmmmm work on my code or play minecraft

#

i think i know the answer to this one

snow beacon
#

Why not both?

sudden willow
#

😳

floral meteor
#

!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

night quarryBOT
#

@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()
sudden willow
#

never really understood super().__init__()

earnest wing
#

It's special compiler magic that's replaced by super(self.__class__, self) ... iirc

sudden willow
#

😦

earnest wing
#

Only within method contexts (super)

floral meteor
#

.

#

O_O

#

i did use int.new tho

earnest wing
#

what

#

hm

night quarryBOT
#

@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
floral meteor
#

!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'

night quarryBOT
#

@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 |  
floral meteor
#

foinally. I DID IT!!!

#

I have gotted python bot to compile c++ code!

snow beacon
#

I don't think that's C.

floral meteor
#

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

floral meteor
#

using annotations to store values...

#

using annotations as a variable manager

#

globals: globals() = annotations_; print(globals['globals'])

#

!e globals: globals = annotations; print(globals['globals'])

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

{'globals': {...}}
floral meteor
#

wait it execs after assignment?

#

!e ```py
globals: globals()
globals=annotations
print(globals['globals'])
print(globals['globals']['globals']['globals'])

night quarryBOT
#

@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': {...}}}
floral meteor
#

wait hol up that doesn't make sense

#

!e ```py
globals: globals()
globals=annotations
print(globals['globals'])
print(globals['globals']['globals'])

night quarryBOT
#

@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': {...}}}
floral meteor
#

ah

snow beacon
#

I assume globals['globals'] is globals.

#

Actually, I retract that assumption.

floral meteor
#

actually, globals['globals'] is globals() which contains globals

#

!e ```py
globals: builtins.globals() = globals()['annotations']
GLOBALS: print
globals'globals'.upper()

night quarryBOT
#

@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>}
floral meteor
#

try saying that code really fast

night quarryBOT
#

@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': {...}}}
floral meteor
#

you can't get more international than that...

#

!e ```py
GLOBALS: globals()['builtins'] = builtins.print
globals: annotations['GLOBALS'].globals() = globals()['annotations']
globals['globals']'GLOBALS'

night quarryBOT
#

@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': {...}}}
floral meteor
#

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'

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

Hello World!
grave rover
#
>>> 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
thin trout
#

Hahaha

#

That’s great

hard spoke
#

hmm, why do you need to seek 24 bytes past the id of 6*9 (putting you on the beginning of the next object)?

earnest wing
#

I believe that's the pyobject header

#

?

thin trout
#

Yep

grave rover
#

yeah

dusky dagger
floral meteor
dusky dagger
#

Lmao

floral meteor
#

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'

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

Hello World!
night quarryBOT
#

@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
floral meteor
#

bruh

plucky wedge
floral meteor
#

!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)

floral meteor
#

I love my cursed module maybe i should upload it to pypi

floral meteor
#

@sick hound

sick hound
#

@floral meteor Is it printing C++ code grammatical? For example, "print('cin > hello')"?

#

It's probably printing the C++ code grammatical.

floral meteor
#

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

night quarryBOT
#

@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 
sick hound
#

@floral meteor That code doesn't work.

floral meteor
#

wdym?

twilit grotto
#

i just tested it, it does

#

very impressive btw

floral meteor
#

!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
night quarryBOT
#

@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
#

much better

floral meteor
#

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
plucky wedge
#

eh

#

thats pretty cool

tribal moon
#

that's very cool

late talon
#

is there any way to pack python code

#

by using a packer or no

earnest wing
#

by shipping the bytecode and some tiny wrapper, yes

late talon
#

what do you mean by shipping the bytecode

vague cairn
astral rover
#

It's not a context manager

#

It's for when you call an instance of the class

toxic jewel
#

!e

with(type("", (), {"__enter__":return,"__exit__":return})())as(owo):
    owo
night quarryBOT
#

@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
toxic jewel
#

sadge

steep mural
#

!e

with(type("", (), {"__enter__":lambda *args:1,"__exit__":lambda *args:1})())as owo:
    owo
night quarryBOT
#

@steep mural :warning: Your eval job has completed with return code 0.

[No output]
floral meteor
#

you should probs print it

#

!e py with(type("", (), {"__enter__":lambda *args:1,"__exit__":lambda *args:1})())as owo:print(owo)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

1
vague cairn
#

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.

floral meteor
#

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"
vague cairn
#

Ah, ok, I had literally never seen that c++ syntax before. so I didn't recognize what syntactic sugar you were implimenting.

floral meteor
#

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
}
vague cairn
#

Right.

floral meteor
#

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>

snow beacon
floral meteor
#

yeah its ignored.

#

i used s so it doesn't complain about too many arguments passed

vague cairn
#

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 `
floral meteor
#

noice

#

code i make isn't debuggable

#

it's just code puke

#

if it doesn't work, that's unfortunate

vague cairn
#

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.

snow beacon
floral meteor
#

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

snow beacon
#

Ah, I understand.

maiden blaze
#

this is beautiful

fluid tree
#

Wheres your source?

dire yew
#
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?
alpine flower
#
lambda s:''.join(__import__('random').choice((str.upper,str.lower))(c)for c in s)```
stark fable
#

yeah, the two most basic tips in golfing are:

  1. use short (ideally single-character) variable names
  2. 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:

steel siren
#

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)))

finite rose
#

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

snow beacon
#

(x&1)**(x&1) is always true.

#

Well, it doesn't work for complex maths or float maths.

shut quiver
#

that's wack

snow beacon
#

It probably stems from how IEEE 754 floats are meant to work.

twilit grotto
#

isn't that how it works irl

shut quiver
twilit grotto
#

hmm

snow beacon
#

Like 0/0.

#

(At least that one throws an error.)

violet rune
#

!e

print("Test")
night quarryBOT
#

@violet rune :white_check_mark: Your eval job has completed with return code 0.

Test
snow beacon
bitter moth
#

!e

night quarryBOT
#
Command Help

!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!*

bitter moth
#

!eval print("Hello Worllllllllddddd")

night quarryBOT
#

@bitter moth :white_check_mark: Your eval job has completed with return code 0.

Hello Worllllllllddddd
bitter moth
#

Noice

pale cove
#

!eval print('test passed')

night quarryBOT
#

@pale cove :white_check_mark: Your eval job has completed with return code 0.

test passed
pale cove
#

thats the code to pretend like you accomplished something

snow beacon
#

Not very esoteric though.

pale cove
#

true

sudden willow
#

!e __import__("sys").stdout.write("this is a more esoteric way of doing it")

night quarryBOT
#

@sudden willow :white_check_mark: Your eval job has completed with return code 0.

this is a more esoteric way of doing it
tribal moon
#

!e py __builtins__.__dict__.__getitem__(__builtins__.__dir__().__getitem__(().__class__.__name__.__len__().__mul__(....__str__().__len__())))("but this is even worse")

night quarryBOT
#

@tribal moon :white_check_mark: Your eval job has completed with return code 0.

but this is even worse
vague cairn
#

!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!'))

night quarryBOT
#

@vague cairn :white_check_mark: Your eval job has completed with return code 0.

HELlo worlD!
vague cairn
#

Oof, doesn't differentiate stream by color, how sad.

fair shell
#

Where can I find the code-under-the-hood for python's amazing a, b = b, a feature?

earnest wing
#

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.

fair shell
#

Ah, very cool. Thanks Olivia.

earnest wing
#

You can also do cool nested destructurings like

a, (b, c), *rest = x
snow beacon
#

And to get the first element of a list with one element, you can do a ,= [b].

sudden osprey
#

@harsh idol Don't randomly post fork bombs, especially with no context. Not cool

sudden willow
#

smh

#

does ` have usage in python code?

rugged sparrow
#

It did in python2

#

Not anymore however

sudden willow
#

!e
a = 1 if a == 1 & a != 2: print("a")

night quarryBOT
#

@sudden willow :white_check_mark: Your eval job has completed with return code 0.

a
sudden willow
#

didnt know & was a thing

cloud fossil
#

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])
night quarryBOT
#

@cloud fossil :white_check_mark: Your eval job has completed with return code 0.

H
sudden willow
#

!e

# reel proof 2 wrongs == a right

wrong = 0

print(wrong.__add__(wrong).__invert__().__abs__().__bool__())
night quarryBOT
#

@sudden willow :white_check_mark: Your eval job has completed with return code 0.

True
plucky wedge
#

abs = absolute value?

snow beacon
#

That's the one.

plucky wedge
#

👍

cloud fossil
#

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?

hard spoke
#
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()

cloud fossil
#

ahh

#

your function actually outputs [4, 5, 6, 1, 2, 3] though

#

but ye you can just copy the other thing

cloud fossil
#

😐

hard spoke
#

oh, it's supposed to be in the other order

cloud fossil
#

ye

hard spoke
#

okay then,

def extend_list_x(list_x, list_y):   
    lst = list_y.copy()
    lst[len(lst):] = list_x
    return lst
cloud fossil
#

i didn't know you can append like that

#

that's so weird

hard spoke
cloud fossil
#

i mean extend

hard spoke
#

that's slice assignment

#

the nonintuitive thing is that it can be used in ways that change the list's size

cloud fossil
hard spoke
#

I'm technically setting a 0-length slice to an entire list, producing an effect like an extend.

cloud fossil
#

ye i thought slice assignment gives errors

#

like index out of range errors

#

very cool

#

this is a hack

#

XD

floral meteor
#

and this is a press ctrl-c to continue XD

alpine flower
#

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

floral meteor
#

without having to wrap it in try except, you can just nest it in a context manager

alpine flower
#

ya exactly

#
  • you don't have to handle the exception
floral meteor
#

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

alpine flower
floral meteor
#

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

alpine flower
#
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 :(

floral meteor
#

!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'))
night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

4
alpine flower
#

why in the __call__?

floral meteor
#

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

floral meteor
#

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)
night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | 420
002 | 69
003 | im dum
floral meteor
#

!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())
night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

code green
boreal slate
night quarryBOT
#

@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
boreal slate
#

And found this bug

#

Any smart fix?

floral meteor
#

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

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

Hey, this works!
tribal moon
#

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?

floral meteor
#

my switch-case-otherwise suite far superior.

tribal moon
#

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

floral meteor
#

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
tribal moon
#

Make your own syntax

#

make your own language

#

similar to what I did before

#

It was really fun

#

And esoteric 😛

floral meteor
#

I can make a brainfuck interpreter.
That's a Turing Complete language with its own syntax and language.

#

easy to make in python

tribal moon
#

except make your own syntax

#

You're creative, you can think of a way to do it

floral meteor
#

you can't suppress a syntax error in python as it raises before anything that would try to could even compile

tribal moon
#

And that's where the creativity comes

floral meteor
#

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
>>> 
tribal moon
#

That's really cool

#

How high can it go

floral meteor
#

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
floral meteor
#

!e ```py
ಠ_ಠ = 69
print ( int.mul(10*(ಠ_ಠ//10),(ಠ_ಠ%10)-2) )

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

420
floral meteor
#

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
fair shell
#

CEO obviously just hard coded in every real number in his function

weary bone
#

hey everyone, im new to python and i just need help wtih my calculator code

#

im not sure what i did wrong

snow beacon
#

(Although I think you're missing some commas between parameters on line 10.)

#

(And it's the same on 12, 14 and 16.)

gloomy ferry
#

@pseudo reef nice

pseudo reef
#

ty!

toxic jewel
#

!e

print(type("test owo", (), {}).__dir__())
night quarryBOT
#

@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
toxic jewel
#

sadge

grave rover
opal walrus
#

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

vague cairn
stark fable
sudden willow
#

!e

class O:
    def w(self, *file):
        open(' '.join(x for x in file))
o = O()
o.w o
night quarryBOT
#

@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
sudden willow
#

:sadge:

eager canopy
#

is there a guide on how to do these esoteric stuff with python?

plucky wedge
#

Esoteric is relatively advanced

#

Not many guides on it

snow beacon
#

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?

verbal totem
plucky wedge
alpine flower
snow beacon
#

'A practice' so standards.

alpine flower
#

!e

class W:
  @property
  def o(self): exec("print('uwu')")
class O:
  w = W()
o = O()
o.w.o```
night quarryBOT
#

@alpine flower :white_check_mark: Your eval job has completed with return code 0.

uwu
snow beacon
#

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].)

twilit grotto
#

how does that work?

#

or, what does that do

snow beacon
#

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.

twilit grotto
#

wack

tribal moon
#

ooooooh lol

floral meteor
#

!e a ,= [0x_for x in input("Hello, world!")];print(a)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

15
tribal moon
#

that means you can do it with octal too

floral meteor
#

the comma-equals operator :>

tribal moon
#

!e py print({0o60for*O,in{__name__,}})

night quarryBOT
#

@tribal moon :white_check_mark: Your eval job has completed with return code 0.

{48}
tribal moon
#

lolol

twilit grotto
#

you mean the pistol operator?

#

,=

floral meteor
#

lmao

snow beacon
tribal moon
#

I know

#

the f is for the for

floral meteor
#

:= 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

tribal moon
#

I wish there was a $ in Python

snow beacon
#

%= exists.

alpine flower
#
x = 15
x %= 10
>>> x = 5```
#

does it really?

tribal moon
#

it's modulos

twilit grotto
#

|= is union

#

or bitwise or

alpine flower
#

isn't it also like some js shenanigans?

snow beacon
#

There's also >>= and <<=.

twilit grotto
#

we're talking about python lol

snow beacon
#

Oh, were you trying to name them all?

floral meteor
#

what do you think of crossroads operator?

snow beacon
#

The name or the operator?

floral meteor
#

the name

twilit grotto
#

floor division lol

floral meteor
#

aye but the operator

snow beacon
#

It's a name. It wouldn't be understood unless you knew it already. ¯_(ツ)_/¯

floral meteor
#

floor division operator sounds lame.

snow beacon
#

Good thing we don't name operators based on whether they're lame.

floral meteor
#

!e a=4; a ^= 3; print(a)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

7
floral meteor
#

duck operator

#

change my mind

twilit grotto
#

duck?

#

where's the duck

floral meteor
#

^= sqwawk

twilit grotto
#

eh?

#

idk

tribal moon
#

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

floral meteor
#

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]))

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

1
floral meteor
#

imma use that instead of one now.

floral meteor
# vague cairn that method of implementing case is awesome, how does that case work?

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()

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

4
floral meteor
#

you see it can't write to locals

vague cairn
#

I like the decorators, but how does the switch start it off?

#

how is switch: 5 not a syntax error?

floral meteor
#

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)

floral meteor
night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

5
vague cairn
#

OOOOOOHHHHHHH!!!!!! nice.

floral meteor
#

!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()

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

001 | 4
002 | 3
floral meteor
#

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

earnest wing
#

Is there any way to force the parser to stop parsing a file from within?

floral meteor
#

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]
floral meteor
#

sounds like hacking

#

:P

earnest wing
#

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

floral meteor
#

pip install fuckit

#

then

import fuckit
fuckit('AB')
earnest wing
#

No deps, single file

#

Would prefer to avoid random strings

floral meteor
#

yeah that should work

earnest wing
#

since you can't embed random binary in them

#

without escapes

floral meteor
#

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.
earnest wing
#

:?

floral meteor
#

try it

earnest wing
#

I'm not sure what you're trying to say

floral meteor
#

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

earnest wing
#

That doesn't work in the same file, though

#

and no deps although I could reimplement fuckit

floral meteor
#

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

earnest wing
#

could have said that from the beginning ty

floral meteor
#

do you know which line the binary data starts?

earnest wing
#

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

floral meteor
#

im typing hang on

earnest wing
#
invalid syntax !!!
print("Hello, world!")
python3 -x file.py
Hello, world!
floral meteor
#

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!
floral meteor
earnest wing
#

idea: 10-terminated strings

#

better than icky null-terminated strings

floral meteor
#

character 10 is the newline

#

\n

#

!e print(chr(0x00))

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

earnest wing
#

I know it is

#

That's the joke

floral meteor
#

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

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

54 45 21 99
alpine flower
#

I have found something

#

!e

import inspect as i

def foo() -> "print(':)')": ...
exec(i.signature(foo).return_annotation)
night quarryBOT
#

@alpine flower :white_check_mark: Your eval job has completed with return code 0.

:)
alpine flower
#

!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")```
night quarryBOT
#

@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
toxic jewel
alpine flower
#

!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")```
night quarryBOT
#

@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
alpine flower
#

dang

#

im sure there's a way to do it

snow beacon
floral meteor
#

that's right, i was gonna make a chain wrapper

#

but i got distracted with using colons and globals().update(annotations) instead of equals

floral meteor
night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

420
surreal ridge
#

Can anyone pleaseee help me with a few things if so dm me
i really need help

floral meteor
#

!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)))
night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

Hello World!
alpine flower
#

is there a way to set how class methods are called?

earnest wing
#

You want to customize the MRO?

#

(method resolution order)

alpine flower
#

yes.

earnest wing
#

You can definitely do that with metaclasses but there's probably more convenient ways

alpine flower
#

how would I do that with metaclasses?

floral meteor
#

!e ```py
b: 5
def funcy():
a=4
return locals()
globals().update(funcy())
globals().update(annotations)
print(a+b)

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

9
lone gust
#

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(),))
alpine flower
floral meteor
#
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.

floral meteor
# alpine flower what does `globals().update(__annotations__)` do?

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

alpine flower
#
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?

floral meteor
#

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

earnest wing
#
from typing import *
def print(*args: Any) -> NoReturn:
  try:
    print(*args)
  except:
    print(*args)
alpine flower
# alpine flower is there a way to set how class methods are called?

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
floral meteor
#

!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('\"))

night quarryBOT
#

@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

floral meteor
#

dafuq did i just do?

grave rover
#

was gonna release it as pypeline but that name is already taken :(

#

and yes you can multichain, but there's no guaranteed execution order

grave rover
#

added the option to use a ThreadPoolExecutor too to dispatch multiple children concurrently

proper vault
#
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.
lone gust
#

oh okay

toxic jewel
#

!e print(1 and 2)

night quarryBOT
#

@toxic jewel :white_check_mark: Your eval job has completed with return code 0.

2
toxic jewel
#

wgat

steep mural
#

this is somehow the first time I have seen that lemon_exploding_head

arctic wraith
stark fable
sudden willow
#

thinking about makinga an esoteric tutorial in a way

#

or justj like methods i've used

#

!e print((1).__sqrt__())

night quarryBOT
#

@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__'
sudden willow
#

what

#

i couldve swore sqrt existed

rugged sparrow
#

you can get the square root of a number by doing n**.5

#

!e print(25**.5)

night quarryBOT
#

@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.

5.0
astral rover
#

So implement pow when the exponent is .5

sudden willow
#

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))
night quarryBOT
#

@sudden willow :white_check_mark: Your eval job has completed with return code 0.

001 | 2
002 | 2.0
sudden willow
#

oh so does floordiv just strip decimal

stark fable
#

floordiv does floor division (//)

#

truediv does true division (/)

#

!e py print(5 .__floordiv__(2)) print(5 .__truediv__(2))

night quarryBOT
#

@stark fable :white_check_mark: Your eval job has completed with return code 0.

001 | 2
002 | 2.5
sudden willow
#

so is truediv == div

#

wait

stark fable
#

there is no __div__

sudden willow
#

is div a sthing

#

oh lmfao

stark fable
#

/ is __truediv__ and // is __floordiv__

toxic jewel
#

owo

dark loom
#

!e py print(~([0o60for*O,in({0o0},)][0x0]))

night quarryBOT
#

@dark loom :white_check_mark: Your eval job has completed with return code 0.

-49
dark loom
#

!e py print(0o60for*O,in({0o0},))

night quarryBOT
#

@dark loom :white_check_mark: Your eval job has completed with return code 0.

<generator object <genexpr> at 0x7f0214c2e6d0>
lone gust
#

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

snow beacon
#

There might be an easy way if we have some more context. What sorts of values might you want to return/not return?

regal elk
#

this channel is full of dark magics

snow beacon
#

I'd use light magics, but dark themes are easier on the eyes.

regal elk
#

esoteric stuff is scary

#

it reminds me of that one thing you can do in node js that everyon makes fun og

snow beacon
#

Esoteric python is just a dash of code golf, some ctypes, eye of newt...

regal elk
#

yeh, its the code golf and the ctypes i dont get

snow beacon
#

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.

regal elk
#

so basically its spray n' pray but in programming?

earnest wing
#

Code golf is finding the shortest possible program that does a certain thing

regal elk
#

fair enough

#

so this is basically a code freakshow?

earnest wing
#

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!"
snow beacon
#

!e ```py
@print
@next
@iter
@str
@callable
def T(): return

night quarryBOT
#

@snow beacon :white_check_mark: Your eval job has completed with return code 0.

T
steep mural
#

lol

floral meteor
#

!e ```py
@print
@str
@callable
def Hello_World(): return

night quarryBOT
#

@floral meteor :white_check_mark: Your eval job has completed with return code 0.

True
floral meteor
#

lmao

#

i got banned from kivy discord server cos my code too insane :>

toxic jewel
#

is there any way to have variable names or function names or anything that i can include special characters in like :

earnest wing
#

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

floral meteor
#

if you throw the variable namespace out the window altogether and use a dictionary as a variable manager

viscid nymph
floral meteor
#

alright, apparantly the way to get people interested in #esoteric-python is show them the big red button

#

XD

strange basin
night quarryBOT
#

@strange basin :white_check_mark: Your eval job has completed with return code 0.

Hello World!
strange basin
#

!e

print(False if False**False else True)
night quarryBOT
#

@strange basin :white_check_mark: Your eval job has completed with return code 0.

False
twilit grotto
#

!e print(0**0)