#esoteric-python

1 messages · Page 98 of 1

sick hound
#

If you don't want to use builtin functions, you can just do this:

#

!e

l = [[1, 2], [2, 3], [3, 4]]

a, b = [[arr[i] for arr in l] 
         for i in [0, 1]]

print(a, b)

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

[1, 2, 3] [2, 3, 4]
limber orchid
#

I guess this is more a meta discussion for esoteric python - is there a plugin or something along the lines out there which can generate esoteric python from regular python files?

sick hound
#

@limber orchid Yes, just search up python obfuscators, you'll find a lot of github projects and sites. IIRC, a person here was making their own obfuscator with ast NodeTransformers, forgot their username though

#

Here, found them

earnest wing
#

I've been able to golf my implementation of the AOC day 12 down to 233 bytes.

def s(I):
 b=lambda c:abs(c.real)+abs(c.imag);p=P=0j;d=p+1;w=10-1j;g=[1j,-1j,1]
 for i,*r in I:a=int(''.join(r));k=a//90;x=(g+[-1,0])["SNEW".find(i)]*a;y=g["RL".find(i)]**k;z=i=="F"and a;p+=x+z*d;P+=z*w;w=w*y+x;d*=y
 return b(p),b(P)

The specification is available here: https://adventofcode.com/2020/day/12 although part 2 might be gated. The input to this function is a list of strings, assumed to be stripped, and the output should be two numeric values that conform to the spec.
The challenge is: can anyone bring it down further?

#
def s(I):
 f=lambda c:abs(c.real)+abs(c.imag);p=P=0;d=1;w=10-1j;g=1j,-1j,1
 for i,*r in I:a=int(''.join(r));x=(g+(-1,0))["SNEW".find(i)]*a;y=g["RL".find(i)]**(a//90);z=a*(i=="F");p+=x+z*d;P+=z*w;w=w*y+x;d*=y
 return f(p),f(P)

225 now :p

alpine flower
#

is there a way to allow built-in reassignment?

True = False```
rugged sparrow
#

partially, but not with True or False (in python3 at least)

alpine flower
#

really? I assumed there'd be a way to overload it

rugged sparrow
#

even if you alter the value of True in memory, all the internal checks do a direct check against the singleton address, not its value

alpine flower
#

oh well that's unfortunate thanks

rugged sparrow
#

other builtins can sometimes be modified

#

like __builtins__.__build_class__

alpine flower
#

I was looking to do something absolutely cursed like:

from __future__ import barry_as_FLUFL
from typing import List

class None(Exception): pass

True: bool = False; str: bool = bool

if not True:
  True: List[str] = []

  for _ in range(((not False) + (not False)) ** 3, -(not False)):
    if bool(_) <> False:
      True.append(not _)

    elif bool(_) <> True:
      True.append(_)
    
    print(bool(sum(True)))

elif not True <> False:

  class False(None):
    def __init__(self):
      super().__init__("True")
  

  raise False```
terse mortar
#

I hate this

#

So much

#

A lot of shit in this channel is cursed, but like... this is a new level.

alpine flower
#

oh god

alpine flower
#

I've made it more cursed for the pin

twilit grotto
#

what the fuck is that

#

that's not valid right

rugged sparrow
#

it is not valid

alpine flower
#

False

#

wait

#

True?

#

ik it's going into the if but I get lost after that point

rugged sparrow
#

the only things that would fail are creating classes named None and False

#

and assigning to True

alpine flower
#

ya yknow like most of it 😄

marsh void
#

__future__ FYI

#

and should be on top

alpine flower
#

oop I didn't see that thank you

thin trout
#

True: bool = False isn’t a thing though

#

at least not in Py 3

alpine flower
#

we've been over this ya, it 100% does not work

alpine flower
formal sandal
#

!e
@alpine flower

Truе = False
print(Truе)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

False
formal sandal
#

but that's cheating

alpine flower
#

how...

formal sandal
#

!charinfo Truе

night quarryBOT
alpine flower
#

ah ya I was about to say that e looked a little bit off

#

cheating is not allowed on this server tho 😠

marsh void
#

patching the interpreter huh

earnest wing
#

Idea: patching the int type so __iter__ iterates on the bits, and __set/getitem__ slice the bits
So you can have something like

value = 0b1100_1000_0001_0110
out = 0
for i, b in enumerate(value):
  out[i:i+4] ^= value
#

I guess indexing would be from the least significant bits, so iteration should too

rugged sparrow
#

thats doable, but assignment might require some hacky stuff

tiny meteor
#

asyncio.coroutine is deprecated iirc

radiant anchor
#

If you just want a bit iterator

def biterator(n):
  for i in range(n.bit_length()):
    yield (n >> i) & 1
rugged sparrow
#

@radiant anchor its more fun when you mod the builtin tho

sick hound
#

¯_(ツ)_/¯

#

i don't think i can make a lambda coroutine in any other way

#

or at least i dont know a way

astral rover
#

types.coroutine

sick hound
#

oh

sick hound
#

golfing challenge of the day jk i just need help

print(f'5 is{" not"if not 5 in range(1,6)else""} in the list')
#

you may not modify the output

#

5 not in range(1, 6)
not 0<5<6

naive roost
#

!e print(f'{5 not in range(1, 6)=}')

night quarryBOT
#

@naive roost :white_check_mark: Your eval job has completed with return code 0.

5 not in range(1, 6)=False
sick hound
sick hound
#

eh that's not really what i was looking for

#

Yeah, but that’s the shortest way to do it

#

so you're saying i cant golf it more

sick hound
#

You can also just,

#

[‘ not’,’’][0<5<6]

#

I’m typing from phone, so the apostrophes are different

naive roost
#

!e print(f"5 is{(' not', '')[0<5<6]} in the list")

night quarryBOT
#

@naive roost :white_check_mark: Your eval job has completed with return code 0.

5 is in the list
proper fulcrum
#

where am i, and why am i here
can somebody explain these

sick hound
#

@proper fulcrum This is for all the weird python stuff. Judging from your username, if you're a beginner, this probably isn't the best place to be in.

proper fulcrum
#

well it's nice to stay here watching code gore

sick hound
#

!e

(lambda _:print(f"{_} is{(' not','')[0<_<6]} in the list"))(10)
proper fulcrum
#

oof

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

10 is not in the list
proper fulcrum
#

hmm

sick hound
blissful widget
#

!e (lambda :print(f"{} is{(' not','')[0<_<6]} in the list"))(5)

night quarryBOT
#

@blissful widget :white_check_mark: Your eval job has completed with return code 0.

5 is in the list
proper vault
#

!e

(lambda _:print(_,f"is{(' not','')[0<_<6]} in the list"))(10)
night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

10 is not in the list
proper vault
#

You could probably do the same with some magic for the second one

sick hound
#

Damn, completely forgot you could do that in print

#

!e

(lambda _:print(_,'is',('not','')[0<_<6],'in the list'))(10)
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

10 is not in the list
sick hound
#
(lambda _:print(_,f"is{(' not','')[0<_<6]} in the list"))(10)
(lambda _:print(_,'is',('not','')[0<_<6],'in the list'))(10)
shy zenith
#

!e

eval(bytes("氨浡摢⁡㩟牰湩⡴ⱟ≦獩⡻‧潮❴✬⤧せ弼㘼絝椠桴⁥楬瑳⤢
","U16")[2:])(10)
night quarryBOT
#

@shy zenith :white_check_mark: Your eval job has completed with return code 0.

10 is not in the list
shy zenith
#

😃

sick hound
#

yo wtf

shy zenith
#

!e

eval(bytes("慬扭慤张瀺楲瑮弨昬椢筳✨渠瑯Ⱗ✧嬩㰰㱟崶⁽湩琠敨氠獩≴
","U16")[2:])(10)
``` 55 chars (excluding the number)
night quarryBOT
#

@shy zenith :white_check_mark: Your eval job has completed with return code 0.

10 is not in the list
sick hound
#

What no no no

#

You aren't allowed to exclude the numbers

shy zenith
#

well the number is dynamic

#

so it doesn't count

sick hound
#

Where are you talking about

#

"U16")[2:])(10)

#

This part

#

Or

shy zenith
#

the 10

sick hound
#

Ah, I see

#

!e

(lambda _:print(_ 'is' ('not','')[0<_<6] 'in the list'))(10)

night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     (lambda _:print(_ 'is' ('not','')[0<_<6] 'in the list'))(10)
003 |                       ^
004 | SyntaxError: invalid syntax
shy zenith
#

i wonder if you can compress code any higher than X/2+25

sick hound
#

How does this work but that doesn't work wtf

#

!e

print('ok' 'then')
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

okthen
rugged sparrow
#

Missing a comma

sick hound
#

I know I'm missing a comma, apparently you can concatenate strings without a comma

#

Oh wait

twilit grotto
#

string literals

rugged sparrow
#

The concatenation is for literals

sick hound
#

Ah, nevermind, that's giving me SyntaxError

wraith raptor
#

!e

#

woah

proper fulcrum
#

I guess lists are an alternative of semicolons

helloworld = lambda: [i() for i in [lambda: print("Hello, ", end = "",flush = True),lambda: print("World!")]]
helloworld()
#

(is this esoteric)

#

~~```py
(lambda: [i() for i in [lambda:x = "(lambda: [i() for i in [lambda:x = %r,lambda: print(x %% x)]])() # it's a quine!",lambda: print(x % x)]])() # it's a quine!

sick hound
#

That's too readable to be esoteric I guess

(lambda:[_()for _ in[lambda:print('Hello, ',end='',flush=True),lambda:print("World!")]])()
#

Still too readable

grave rover
#
helloworld=(lambda _,__:map(_,[__[::2],__[1::2]])(__import__("sys").stdout.write,[72,87,101,111,108,114,108,108,111,100,44,33,32,10])
#

!e py helloworld=(lambda _,__:map(_,[__[::2],__[1::2]])(__import__("sys").stdout.write,[72,87,101,111,108,114,108,108,111,100,44,33,32,10]) helloworld()

night quarryBOT
#

@grave rover :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 2
002 |     helloworld()
003 |     ^
004 | SyntaxError: invalid syntax
grave rover
#

oh wait

#

!e ```py
helloworld=(lambda ,__,:(lambda:[*map(lambda :(()),[*[::2],*__[1::2]])]))(import("sys").stdout.write,[72,87,101,111,108,114,108,108,111,100,44,33,32,10],chr)

night quarryBOT
#

@grave rover :warning: Your eval job has completed with return code 0.

[No output]
grave rover
#

!e ```py
helloworld=(lambda ,__,:(lambda:[*map(lambda :(()),[*[::2],*__[1::2]])]))(import("sys").stdout.write,[72,87,101,111,108,114,108,108,111,100,44,33,32,10],chr)

helloworld()

night quarryBOT
#

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

Hello, World!
sick hound
#

I think you meant to put this in some other channel, this isn't the right channel for this type of stuff. Way too readable.

alpine flower
#

Comprehensible numbers? Unacceptable

proper vault
#
__builtins__.__getattribute__('__dict__').__getattribute__('values').__call__().__iter__()
#

oh, was gonna fix that then got a DM, mb

#

fixed

sick hound
#

Is there a way to get the frame object within a with statement?

#

For example here, I want to get the bytecode of the code within context manager. Was wondering if that was possible and how.

rugged sparrow
#

You can get the upper frame from within func, and then you can get the byte code of that entire frame. Using frame.f_lasti, you can find the current executing byte code of that frame

#

From there you can find the byte code of the with block

sick hound
rugged sparrow
#
>>> import sys, dis
>>> class Foo:
...     def __enter__(self):
...             f = sys._getframe(1)
...             dis.disco(f.f_code, lasti=f.f_lasti)
...     def __exit__(*a):return True
... 
>>> with Foo():pass
... 
  1           0 LOAD_NAME                0 (Foo)
              2 CALL_FUNCTION            0
    -->       4 SETUP_WITH              16 (to 22)
              6 POP_TOP
              8 POP_BLOCK
             10 LOAD_CONST               0 (None)
             12 DUP_TOP
             14 DUP_TOP
             16 CALL_FUNCTION            3
             18 POP_TOP
             20 JUMP_FORWARD            16 (to 38)
        >>   22 WITH_EXCEPT_START
             24 POP_JUMP_IF_TRUE        28
             26 RERAISE
        >>   28 POP_TOP
             30 POP_TOP
             32 POP_TOP
             34 POP_EXCEPT
             36 POP_TOP
        >>   38 LOAD_CONST               0 (None)
             40 RETURN_VALUE
>>> ``` @sick hound
sick hound
#

Yo wtf, when I did that it didn't work. Oh what's disco?

#

!d dis.disco

night quarryBOT
#
dis.disco(code, lasti=-1, *, file=None)```
Disassemble a code object, indicating the last instruction if *lasti* was provided. The output is divided in the following columns:

2. the line number, for the first instruction of each line

4. the current instruction, indicated as `-->`,

6. a labelled instruction, indicated with `>>`,

8. the address of the instruction,

10. the operation code name,

12. operation parameters, and

14. interpretation of the parameters in parentheses.

The parameter interpretation recognizes local and global variable names, constant values, branch targets, and compare operators.

The disassembly is written as text to the supplied *file* argument if provided and to `sys.stdout` otherwise.

Changed in version 3.4: Added *file* parameter.
rugged sparrow
#

it takes the parameter lasti and puts an arrow at the passed instruction offset

sick hound
#

I see, thanks

rugged sparrow
#

yea just a visual thing

#

but helps to show what frame.f_lasti is

sick hound
#

Ah wait, I checked back at my code and realized where I messed up

#
from sys import _getframe

class Test:
    def __enter__(self):
        ...

    def __exit__(self, exp_type, exp_value, exp_traceback):
        frame = _getframe(1)
        print(frame.f_lasti)

with Test():
    a = 10
    print("OK")

#

You put it in __enter__ because the stack has the __enter__ call first then the code within the context manager goes up top

#

Ok, got it, thanks

rugged sparrow
#

i mean that should still work, but it would only trigger after the with block

sick hound
#

!e

from sys import _getframe

class Test:
    def __enter__(self):
        frame = _getframe(1)
        print(frame.f_lasti)

    def __exit__(self, exp_type, exp_value, exp_traceback):
        ...

with Test():
    pass

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

30
sick hound
#

Need to search up what this 30 is for

rugged sparrow
#

thats the offset that the SETUP_WITH opcode is at

#

in the compiled code object

sick hound
#

Oh, so f_lasti gives you the offset?

rugged sparrow
#

it gives you the offset of the last instruction that is ran

#

(or currently running in the case of how SETUP_WITH works)

sick hound
#

Ah, thanks got it working

rugged sparrow
#

if you want to modify the bytecode of the with block you're gonna need ctypes

sick hound
#

Why?

rugged sparrow
#

bytecode is readonly

#

but you can mod it with ctypes (or other memory modification code)

sick hound
#

I see, interesting. I'm trying to get familiar with sys._getframe by trying to access all variables inside the with

rugged sparrow
#

to do that you should look at all the opcodes between SETUP_WITH and WITH_EXCEPT_START and look for all the opcodes that involve code.co_names or code.co_consts, then you can load those yourself from the frame locals, frame globals and the frame code

sick hound
#

Yep, that's what I was planning to do tomorrow, had a lot of school work. By why co_consts doesn't that only give you the constants that are being used in the block?

rugged sparrow
#

oh yea you dont want all values you only want variables

#

then itll just be co_names

sick hound
#

Yeah, thanks

toxic jewel
#

i love this channel

wind token
#

!e ```order=input('order something: ')
order1=input('again order something: ')
output=order + order1
print(output)

#

cuz we need to put something

near slate
#

What is this channel for?

rugged sparrow
#

read the channel description

grave rover
#
    PyObject *u_consts;    /* all constants */
    PyObject *u_names;     /* all names */
    PyObject *u_varnames;  /* local variables */
    PyObject *u_cellvars;  /* cell variables */
    PyObject *u_freevars;  /* free variables */
    ```
rugged sparrow
#

Afaik you'd need both

sick hound
#

Loved this channel

#

❤️ ❤️ ❤️ ❤️

toxic jewel
sick hound
#

That was replit on my phone

toxic jewel
#

!e

_,__,=4,2;___=__*_+__**_*__*__*__*__++__*_*_++__*_*__*_++(__*__*__*__*__++(__*__*__++_*_++_));print(___)
night quarryBOT
#

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

420
toxic jewel
#

perfect

shy zenith
#

!e

(lambda _,__:__[(_+_)*(_+_)*(_+_)+(_+_)*(_+_)*(_+_)*(_+_)*(_+_)](__[(_+_)+(_+_)*(_+_)+(_+_)*(_+_)*(_+_)]((_+_)*(_+_)+(_+_)*(_+_)*(_+_)*(_+_)+(_+_)*(_+_)*(_+_)*(_+_)*(_+_))+__[(_+_)+(_+_)*(_+_)+(_+_)*(_+_)*(_+_)]((_+_)+(_+_)*(_+_)*(_+_)*(_+_)+(_+_)*(_+_)*(_+_)*(_+_)*(_+_))+__[(_+_)+(_+_)*(_+_)+(_+_)*(_+_)*(_+_)]((_+_)*(_+_)*(_+_)*(_+_)+(_+_)*(_+_)*(_+_)*(_+_)*(_+_))))(()==(),[*__builtins__.__getattribute__('__dict__').__getattribute__('values').__call__()])
night quarryBOT
#

@shy zenith :white_check_mark: Your eval job has completed with return code 0.

420
sick hound
#

Could've encoded __dict__ and values

shy zenith
#

how

shy zenith
#

good idea

#

!e

(lambda _,__:__[(_+_)*(_+_)*(_+_)+(_+_)*(_+_)*(_+_)*(_+_)*(_+_)](__[(_+_)+(_+_)*(_+_)+(_+_)*(_+_)*(_+_)]((_+_)*(_+_)+(_+_)*(_+_)*(_+_)*(_+_)+(_+_)*(_+_)*(_+_)*(_+_)*(_+_))+__[(_+_)+(_+_)*(_+_)+(_+_)*(_+_)*(_+_)]((_+_)+(_+_)*(_+_)*(_+_)*(_+_)+(_+_)*(_+_)*(_+_)*(_+_)*(_+_))+__[(_+_)+(_+_)*(_+_)+(_+_)*(_+_)*(_+_)]((_+_)*(_+_)*(_+_)*(_+_)+(_+_)*(_+_)*(_+_)*(_+_)*(_+_))))(()==(),eval(bytes("⩛彟畢汩楴獮彟弮束瑥瑡牴扩瑵彥⡟弧摟捩彴❟⸩彟敧慴瑴楲畢整彟✨慶畬獥⤧弮损污彬⡟崩","U16")[2:]))
night quarryBOT
#

@shy zenith :white_check_mark: Your eval job has completed with return code 0.

420
shy zenith
#

@sick hound better?

steep mural
#

What is that string?

toxic jewel
#

is this esoteric-y enough?

#

!e

_,__,____,______=4,2,1.2,1;___=__*_+__*_*__*__*__*__++__*_*_++__*_*__*_++(__*__*__*__*__++(__*_*_++_*_++_));_____=___*__*(__*_*(_*__)++(____*__++(_*_++(____*_++(____*_*(_)++(__)*__)/(____--(_**_*__))))))++(_**_*_++(____*(____**____++(_**____))))*_++(____**____)*__*(_**_*(_*_))/(____)*(____-(_-__))**_++(_*(____))*_*(_**_)*____++(____*_)++(_**_++(_*_*(_*_)))++(_*_++(_*_)++__++(______*_**_))-______*_*_-(_*__)-(_+_)+______;_______=__import__("math").trunc(_____);print(_______)
night quarryBOT
#

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

69420
shy zenith
#

semicolons are kinda weird

toxic jewel
#

if i didnt use them it wouldnt be one line

#

also idk how to use lambda

shy zenith
#

semicolons don't really count as a one liner

sudden willow
#

how do the chinese characters even work?

shy zenith
#

!e

s = "test"
print(s)
s = s.encode().decode("U16")
print(s)
s = s.encode("U16")[2:].decode()
print(s)
night quarryBOT
#

@shy zenith :white_check_mark: Your eval job has completed with return code 0.

001 | test
002 | 整瑳
003 | test
sudden willow
#

oooh thats smart

sick hound
#

!e

radiant anchor
#

!e

import zlib
print("".join([chr(x+(10<<10)) for x in zlib.decompress("⡸⣚⢥⢑⠱⡮⣂⡀⠐⡅⣇⡉⠑⠻⠩⢐⣒⡅⡓⣐⣤⠖⠮⡰⢁⡢⡑⡱⠄⣧⠦⡆⡊⢕⠃⢸⣧⠈⢔⡄⠔⡶⡡⠥⣬⠙⣒⡐⡁⡋⢁⡬⠪⠦⠳⢳⣫⢰⠒⢒⢃⢔⡟⢌⠽⠻⣟⡏⡿⢼⡄⢬⣡⡃⠤⣂⢒⣾⣔⠴⣨⠙⠖⡚⠡⢾⠃⡕⠿⠨⣢⢒⡂⠯⡭⢄⢈⢏⢬⠛⢡⡥⣘⣥⣋⢇⡼⠮⡍⢆⣒⡲⣍⡮⠁⢑⡩⠲⢉⣅⠥⢎⡘⢆⠣⡧⢥⡢⠀⢞⡦⠩⢗⢕⢍⢻⣠⢲⢅⠏⠗⡆⢪⢾⢥⡰⠸⡑⠻⠎⠩⠏⣶⣜⡾⢆⠫⡫⡽⢑⡡⡡⠩⢯⣏⢪⡻⡩⢖⢖⢦⠏⣞⣽⢂⣦⡚⢷⠲⣻⣔⢪⡭⢑⣰⣷⢋⣀⠏⣨⣑⡲⢘⢳⢭⣼⢥⢕⠞⡭⢧⡋⡤⡰⣴⡩⡭⢕⣀⣒⡟⡶⡣⣿⠛⣌⣍⣤⢽⠺⠐⢵⣵⣚⠘⠳⠖⡳⢽⣾⢦⢯⡊⢦⡒⣛⣚⢠⣙⢜⢈⢪⢣⠻⣩⣮⢔⠕⡆⡦⠒⢝⢯⣇⡅⣬⢔⣎⣨⠊⡙⡚⢭⢱⢞⣞⣶⣧⡁⣢⣑⣐⡦⢸⢖⣆⢱⢛⢦⢡⡿⣫⠇⡆⣴⠰⡞".encode("U16")[2::2])]).replace("⢕", "\n"))
night quarryBOT
#

@radiant anchor :white_check_mark: Your eval job has completed with return code 0.

001 | ⣿⣿⣿⣿⣿⠟⠋⠉⠉⠉⠉⠉⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⠁⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
002 | ⣿⣿⣿⣿⣿⠀⠻⠇⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⠉⣿⣿⣿⡇⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
003 | ⣿⠿⠛⠛⠛⠒⠒⠒⠒⠂⠀⠀⠀⠀⡟⠛⠛⢿⣿⣿⣿⣿⣿⣿⡿⠟⠛⠛⠛⠛⢿⣿⣿⡟⠛⣿⣿⣿⣿⡟⠛⣿⡟⠃⠀⠛⠛⣿⡇⠀⡿⠟⠛⠛⠻⢿⣿⣿⣿⠟⠛⠛⠛⠻⣿⣿⣿⣿⠿⠛⠛⠛⠛⢿⣿⣿⣿
004 | ⠏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡇⠀⠀⠀⢻⣿⣿⣿⣿⣿⠀⢰⣿⣿⣿⣦⠀⢹⣿⡇⠀⣿⣿⣿⣿⡇⠀⣿⣿⡇⠀⣿⣿⣿⡇⠀⣴⣾⣿⣷⡄⠈⣿⡿⠁⣰⣿⣿⣿⣆⠈⢻⣿⠀⢰⣿⣿⣿⡆⠀⣿⣿⣿
005 | ⠀⠀⠀⠀⠀⢀⡠⠤⠤⠤⠤⠤⠤⠊⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⠀⢸⣿⣿⣿⣿⠀⠀⣿⡇⠀⣿⣿⣿⣿⡇⠀⣿⣿⡇⠀⣿⣿⣿⡇⠀⣿⣿⣿⣿⡇⠀⣿⡇⠀⣿⣿⣿⣿⣿⠀⢸⣿⠀⢸⣿⣿⣿⡇⠀⣿⣿⣿
006 | ⡀⠀⠀⠀⢰⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⠀⢸⣿⣿⣿⡿⠀⢠⣿⡇⠀⢿⣿⣿⣿⡇⠀⣿⣿⡇⠀⢿⣿⣿⡇⠀⣿⣿⣿⣿⡇⠀⣿⣧⠀⢻⣿⣿⣿⡟⠀⣸⣿⠀⢸⣿⣿⣿⡇⠀⣿⣿⣿
007 | ⣷⣀⡀⠀⢸⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣠⣿⣿⣿⣿⣿⣿⠀⢠⣉⡉⢉⣀⣴⣿⣿⣷⣄⣈⣉⣉⣉⡄⠀⣿⣿⣿⣄⣈⣛⣿⣇⣀⣿⣿⣿⣿⣇⣀⣿⣿⣷⣄⣉⠛⣉⣠⣾⣿⣿⣀⣸⣿⣿⣿⣇⣀⣿⣿⣿
008 | ⣿⣿⣿⣿⣿⠀⠀⠀⠀⠈⠉⣉⡉⠉⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
009 | ⣿⣿⣿⣿⣿⣄⠀⠀⠀⠀⠀⠙⢃⣰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⠛⣉⣠⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
010 | ⣿⣿⣿⣿⣿⣿⣿⣷⣶⣶⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
shy zenith
#

woah

sudden willow
#

woah indeed

rugged sparrow
#

clever

radiant anchor
#

"[braille]".encode("U16")[2::2] is a semi-efficient way to encode/decode binary data, one byte per source character

#

each braille dot is one bit

sudden willow
#

any tips to make my code as humanly inreadable as possible?

shy zenith
#

just throw it into an obfuscator

#

ezpz

sudden willow
#

but what if i wanna obfuscate it by hand

shy zenith
#

you don't

sudden willow
#

why

rugged sparrow
#

@sudden willow use lambdas and list comprehensions

sick hound
#

Dunder methods

#

nothing

#

i was just testing something

sudden willow
#

my mission is to go from 0.1 to 42069

night quarryBOT
#

@fresh nest :x: Your eval job has completed with return code 1.

001 | 267
002 | Traceback (most recent call last):
003 |   File "<string>", line 1, in <module>
004 | TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
torn cloak
#

!e

None = bool()
night quarryBOT
#

@torn cloak :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     None = bool()
003 |     ^
004 | SyntaxError: cannot assign to None
torn cloak
#

I wonder how you could change None to a bool

frigid wharf
#

!e py import ctypes ctypes.py_object.from_address(id(None)+8).value = bool print(None)

night quarryBOT
#

@frigid wharf :white_check_mark: Your eval job has completed with return code 0.

False
sullen trench
#

Is there a guideline or a basic tutorial on the esoteric python code writing?

#

because most codes i see on this sub makes little to no sense currently 😦

#

would be great if I could get a learning point

sudden willow
#

you just pick up things you can use overtime

#

not really a tutorial

sick hound
# sullen trench Is there a guideline or a basic tutorial on the esoteric python code writing?

No, esoteric python is understanding concepts at a deep level and abusing them. There aren’t any tutorials because there aren’t any use-cases of esoteric code. I used to hover over this channel a year ago and understood nothing. But now I think my python level has reached high enough to understand most the hacks here, apart from some really complicated ctypes hacks like @rugged sparrow makes.

#

I was in the same position, so I’d say, just learn as many concepts in python as possible.

sick hound
#

If you’re just starting out python, this is not the channel to be in, I stayed in this channel for one week straight and I naturally started writing esoteric code

sick hound
#

Wait, is it possible to have lambdas as keys in dictionaries? I’ll try when I’m on my computer later

proper vault
#

it is

#

they compare by identity though

sick hound
#

I see. I was wondering if it's possible to translate something like this:

if     1 < x < 5: ...
elif   6 < x < 10: ...
elif   11 < x < 15: ...

Into a dictionary

proper vault
#

salt-die made a range dictionary class

#

don't think you can do this with the builtin dict

sick hound
#

!e

from typing import Callable, Dict, Any

class Conditionals:
    def __init__(self, 
                 dict_: Dict[Callable[..., bool], Any]):
        self.dict = dict_

    def __call__(self, arg: Any) -> Any:
        for func, value in self.dict.items():
            if func(arg):
                return value

inst = Conditionals({
    lambda x: 1 < x < 6: 1,
    lambda x: 6 < x < 10: 6
})

print(inst(8))

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

6
hexed siren
#
>>> class T:
...     def __init__(self, *args, **kwargs):
...             self.__dict__.update(kwargs)
... 
>>> instance = T()
>>> class another(instance, life=42, why="why not ?"):
...     pass
... 
>>> class more(another, bye="now"):
...     pass
... 
>>> another
<__main__.T object at 0x7fa0b86d3070>
>>> more
<__main__.T object at 0x7fa0b725c190>
>>> another.why
'why not ?'
>>> more.bye
'now'
>>> 
``` I have been playing with that recently and I was wondering why it is allowed ? 😂
formal sandal
#

!e

class T:
    def __init__(self, *args, **kwargs):
        print(f"{self=} {args=} {kwargs=}")
        self.__dict__.update(kwargs)

    def __getattribute__(self, attr):
        print(f"getattribute {self=} {attr=}")
        return object.__getattribute__(self, attr)

t = T()

class Another(t, foo="bar"):
    pass

print(t, Another)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

001 | self=<__main__.T object at 0x7fe9da81cfd0> args=() kwargs={}
002 | getattribute self=<__main__.T object at 0x7fe9da81cfd0> attr='__dict__'
003 | getattribute self=<__main__.T object at 0x7fe9da81cfd0> attr='__mro_entries__'
004 | self=<__main__.T object at 0x7fe9da81ce20> args=('Another', (<__main__.T object at 0x7fe9da81cfd0>,), {'__module__': '__main__', '__qualname__': 'Another'}) kwargs={'foo': 'bar'}
005 | getattribute self=<__main__.T object at 0x7fe9da81ce20> attr='__dict__'
006 | <__main__.T object at 0x7fe9da81cfd0> <__main__.T object at 0x7fe9da81ce20>
sick hound
#

what regex do you guys think could replace this http: \/\/t.co\/5JBtF54cmg expression. It has extra backslashes and this regex is not enough to replace it tweet = re.sub(r'(?P<url>https?://[^\s]+)', ' URL ', tweet)

sick hound
#

@sick hound What do you want to do? Remove the backslashes? If so, why are you doing so much work to replace a backslash when you can just use .replace method?

frozen holly
#

!e

_=__builtins__.__getattribute__("%c"*3%(100,105,114))
__=__builtins__.__getattribute__(_(__builtins__)[108])
___=__(__builtins__,_(__builtins__)[142])
____=__(__builtins__,_(__builtins__)[150])(_(__builtins__)[37],(),{})
___(____,"%c"*7%(95,95,100,105,114,95,95),lambda _:[__builtins__])
___(____,"%c"*7%(95, 95, 97, 100, 100, 95, 95),lambda ___,____:__(_(___)[0],_(_(___)[0])[____]))
___=____()
______=((()==())+(()==()))
_______=______<<((______<<______)-______)

(___+((______<<______)*______-______+_______))(____,"%c"*8%(95, 95, 99, 97, 108, 108, 95, 95),lambda _____,______,_______,________:(_(_(_____)[0])[______])[_______:________])
____=(___+(_______-(______<<______)-(()==())))([134,112,0,-1,109,1,2,2,-2,-1,75,0,1,7,5,6,130,0,1,42,3,4,122,0,1,114,1,2])

(___+(___+_______)(____))((___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+
                          (___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+
                          (___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____))))```
night quarryBOT
#

@frozen holly :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | TypeError: globals() takes no arguments (2 given)
frozen holly
#

:/

#

did they change __builtins__

#

!e print(dir(builtins))

night quarryBOT
#

@frozen holly :white_check_mark: Your eval job has completed with return code 0.

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError
... (truncated - too long)

Full output: https://paste.pythondiscord.com/iziwipovij.txt

frozen holly
#

in ver 3.9 they added WindowsError to __builtins__, so the version the bots on is messing up on that

#

wait

#

oh im a dumbass

#

its version differences

#

ig mine has WindowsError cos im on a windows machine

frozen holly
#

!e

_=__builtins__.__getattribute__("%c"*3%(100,105,114))
__=__builtins__.__getattribute__(_(__builtins__)[107])
___=__(__builtins__,_(__builtins__)[141])
____=__(__builtins__,_(__builtins__)[149])(_(__builtins__)[37],(),{})
___(____,"%c"*7%(95,95,100,105,114,95,95),lambda _:[__builtins__])
___(____,"%c"*7%(95, 95, 97, 100, 100, 95, 95),lambda ___,____:__(_(___)[0],_(_(___)[0])[____]))
___=____()
______=((()==())+(()==()))
_______=______<<((______<<______)-______)-(()==())
(___+142)(____,"%c"*8%(95, 95, 99, 97, 108, 108, 95, 95),lambda _____,______,_______,________:(_(_(_____)[0])[______])[_______:________])
____=(___+119)([133,111,0,-1,108,1,2,2,-2,-1,75,0,1,7,5,6,129,0,1,42,3,4,121,0,1,113,1,2])
(___+(___+_______)(____))((___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+
                          (___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+
                          (___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____))))
night quarryBOT
#

@frozen holly :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 6, in <lambda>
004 | TypeError: list indices must be integers or slices, not UnicodeError
sick hound
#

@frozen holly #bot-commands bro, this is filling chat too much

frozen holly
#

there we go

#

!e

_=__builtins__.__getattribute__("%c"*3%(100,105,114))
__=__builtins__.__getattribute__(_(__builtins__)[107])
___=__(__builtins__,_(__builtins__)[141])
____=__(__builtins__,_(__builtins__)[149])(_(__builtins__)[37],(),{})
___(____,"%c"*7%(95,95,100,105,114,95,95),lambda _:[__builtins__])
___(____,"%c"*7%(95, 95, 97, 100, 100, 95, 95),lambda ___,____:__(_(___)[0],_(_(___)[0])[____]))
___=____()
______=((()==())+(()==()))
_______=(______<<((______<<______)-______))-(()==())
(___+141)(____,"%c"*8%(95, 95, 99, 97, 108, 108, 95, 95),lambda _____,______,_______,________:(_(_(_____)[0])[______])[_______:________])
____=(___+118)([133,111,0,-1,108,1,2,2,-2,-1,75,0,1,7,5,6,129,0,1,42,3,4,121,0,1,113,1,2])
(___+(___+_______)(____))((___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+
                          (___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+
                          (___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____)))+(___((___+_______)(____),(___+_______)(____),(___+_______)(____))))```
night quarryBOT
#

@frozen holly :white_check_mark: Your eval job has completed with return code 0.

hello_World
frozen holly
#

its just a simple hello world program wdym

formal sandal
frozen holly
#

i was thinking of doing that or somthing similar, but in the end i just wanted it to be over

sick hound
#

Bro that was a joke

low axle
#

Oop

grand tree
#

!e ```py
=builtins.getattribute("%c"*3%(100,105,114))
__=builtins.getattribute(
(builtins)[107])
=(builtins,(builtins)[141])
=__(builtins,(builtins)[149])((builtins)[37],(),{})
(
,"%c"*7%(95,95,100,105,114,95,95),lambda :[builtins])
(
,"%c"*7%(95, 95, 97, 100, 100, 95, 95),lambda ,
:(()[0],(()[0])[]))
=
()
=((()==())+(()==()))
=(<<((
<<
)-))-(()==())
(
+141)(,"%c"*8%(95, 95, 99, 97, 108, 108, 95, 95),lambda ,,,________:((()[0])[])[:___])
=(+118)([133,111,0,-1,108,1,2,2,-2,-1,75,0,1,7,5,6,129,0,1,42,3,4,121,0,1,113,1,2])
(
+(
+
)())((((+)(),(+)(),(+)()))+(((+)(),(+)(),(+)()))+(((+)(),(+)(),(+)()))+
(
((+)(),(+)(),(+)()))+(((+)(),(+)(),(+)()))+(((+)(),(+)(),(+)()))+
(
((+)(),(+)(),(+)()))+(((+)(),(+)(),(+)()))+(((+)(),(+)(),(+__)())))

night quarryBOT
#

@grand tree :white_check_mark: Your eval job has completed with return code 0.

hello_World
grand tree
#

jesus

elfin fog
#

What in the world

sick hound
#

Is there a way I could target bad encodings in a string and replace them with empty char? For example, I have this malformed sequence #newjersey #swim #sandy #hurricane  with the bad encoding . Can I use regex to target these symbols? I thought of creating a white_list and only keeping things that I need, but that would remove words like #newjersey.

proper vault
#

@sick hound you can use

In [30]: codecs.decode(b'\xff\xffa', errors='ignore')
Out[30]: 'a'

In [31]: b'\xff\xffa'.decode()
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-31-7902eda29418> in <module>
----> 1 b'\xff\xffa'.decode()

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
sick hound
#

how would you do that in a function given ```

''' ?? '''
def sanitise(word, errors='ignore'):
return;

sentence = "#swim #sandy #hurricane "
words = sentence.split()
preprocessed_words = []

for word in words:
preprocessed_words.append(sanitise(word))

output = ''.join(preprocessed_words)

#

or rather ```
''' ?? '''
def is_valid(word, errors='ignore'):
return;

sentence = "#swim #sandy #hurricane "
words = sentence.split()
preprocessed_words = []

for word in words:
if is_valid(word):
preprocessed_words.append(word)

output = ''.join(preprocessed_words)

sick hound
#

not 100% sure

#

could be just me having a reverse brain rn

toxic jewel
#

!e

a=b=3,2
return(b,a)[a<b]```
night quarryBOT
#

@toxic jewel :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 2
002 | SyntaxError: 'return' outside function
toxic jewel
#

sad

bitter iris
#

sad indeed

thin trout
#

Do it the C way

#

!e

a=b=3,2
exit((b,a)[a<b])```
night quarryBOT
#

@thin trout :x: Your eval job has completed with return code 1.

(3, 2)
thin trout
#

Huh why did it print something

toxic jewel
#

it should print b and a if a<b

cursive plover
#

How would you reduce this to 1 line

#
class N: __init__, __and__, __add__ = lambda self, n: setattr(self, "n", n), lambda self, v: N(self.n * v.n), lambda self, v: N(self.n + v.n)

print(sum(eval(__import__("re").sub(r"(\d)", r"N(\1)", line).replace("*", "&")).n for line in open("dataQ1.txt")))
toxic jewel
#

why cant i assign this to lambda

#

_=lambda _: arg=__import__("sys").argv[1]

twilit grotto
#

the one line is a return statement basically

#

since you can't return that in a normal function you can't in a lambda

toxic jewel
#

how would i get the contents of a file i opened

#

ohhh i know what i did

sudden willow
#

!e
eval(bytes("牰湩⡴䠢汥潬‬潗汲Ⅴ⤢", "U16")[2:])

night quarryBOT
#

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

Hello, World!
sudden willow
#

nice

#

the chinese characters are cool

sick hound
#

!e


create_var = lambda v_name, val: globals().__setitem__(v_name, val)
create_var('a', 10)

print(a)

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

10
rugged sparrow
#

@thin trout that code that you typed stores the tuple (3,2) into both a and b

thin trout
#

Ooooh

rugged sparrow
#

a,b=3,2 would do what you expected

astral cove
#

what is it actually?

frozen holly
#

just a simple hello world program :)

terse mortar
#

Ikr

#

That shits so easy

#

I could do that in my sleep

#

!e

(lambda _, __, ___, ____, _____, ______, _______, ________:
    getattr(
        __import__(True.__class__.__name__[_] + [].__class__.__name__[__]),
        ().__class__.__eq__.__class__.__name__[:__] +
        ().__iter__().__class__.__name__[_:][_____:________]
    )(
        _, (lambda _, __, ___: _(_, __, ___))(
            lambda _, __, ___:
                bytes([___ % __]) + _(_, __, ___ // __) if ___ else
                (lambda: _).__code__.co_lnotab,
            _ << ________,
            (((_____ << ____) + _) << ((___ << _____) - ___)) + (((((___ << __)
            - _) << ___) + _) << ((_____ << ____) + (_ << _))) + (((_______ <<
            __) - _) << (((((_ << ___) + _)) << ___) + (_ << _))) + (((_______
            << ___) + _) << ((_ << ______) + _)) + (((_______ << ____) - _) <<
            ((_______ << ___))) + (((_ << ____) - _) << ((((___ << __) + _) <<
            __) - _)) - (_______ << ((((___ << __) - _) << __) + _)) + (_______
            << (((((_ << ___) + _)) << __))) - ((((((_ << ___) + _)) << __) +
            _) << ((((___ << __) + _) << _))) + (((_______ << __) - _) <<
            (((((_ << ___) + _)) << _))) + (((___ << ___) + _) << ((_____ <<
            _))) + (_____ << ______) + (_ << ___)
        )
    )
)(
    *(lambda _, __, ___: _(_, __, ___))(
        (lambda _, __, ___:
            [__(___[(lambda: _).__code__.co_nlocals])] +
            _(_, __, ___[(lambda _: _).__code__.co_nlocals:]) if ___ else []
        ),
        lambda _: _.__code__.co_argcount,
        (
            lambda _: _,
            lambda _, __: _,
            lambda _, __, ___: _,
            lambda _, __, ___, ____: _,
            lambda _, __, ___, ____, _____: _,
            lambda _, __, ___, ____, _____, ______: _,
            lambda _, __, ___, ____, _____, ______, _______: _,
            lambda _, __, ___, ____, _____, ______, _______, ________: _
        )
    )
)
night quarryBOT
#

@terse mortar :white_check_mark: Your eval job has completed with return code 0.

Hello world!
terse mortar
#

An oldy but goody

sick hound
#

We’ve seen a million hello world implementations in this channel by now right?

#

Especially the overly obfuscated ones

sick hound
#

print(*[("Fizz" if i % 3 == 0 else ("Buzz" if i % 5 == 0 else i)) for i in range(101)])
how to golf

vague hearth
#

what about multiples of 15, it wont show FizzBuzz, just Fizz

radiant anchor
#

remove unnecessary whitespace for a start

#

also you can remove the == 0 and flip your ternary expressions (since 0 is falsey)

shy remnant
#

!e

print(*[("Fizz" if i % 3 == 0 else ("Buzz" if not i % 5 else i)) for i in range(101)])
```like that?
night quarryBOT
#

@shy remnant :white_check_mark: Your eval job has completed with return code 0.

Fizz 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 Fizz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 Fizz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 Fizz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 Fizz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 Fizz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 Fizz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz
shy remnant
#

ah no that doesnt do fizzbuzz

radiant anchor
#

you have to flip the sides of the if elses

shy remnant
#

can you show us?

radiant anchor
#
print(*[((i if i%5 else"Buzz")if i%3 else"Fizz")for i in range(101)])
#

same output

#

as the original

shy remnant
#

!e

print(*[("Fizzbuzz" if not i % 3 and not i % 5 else ("Fizz" if not i % 3  else ("Buzz" if not i % 5 else i))) for i in range(101)])
night quarryBOT
#

@shy remnant :white_check_mark: Your eval job has completed with return code 0.

Fizzbuzz 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 Fizzbuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 Fizzbuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 Fizzbuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 Fizzbuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 Fizzbuzz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 Fizzbuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz
vague hearth
#
print(*[(1-i%3)*"Fizz"+(1-i%5)*"Buzz"or i for i in range(1,100)])```65 chars is the shortest i can go
shy remnant
#

wow thats pretty good

radiant anchor
#

The original program isn't true fizzbuzz though

#

it ignored the multiple of 15 cases

#

I assumed that was deliberate

twilit grotto
#

also pretty sure it doesn't include 0

shy remnant
twilit grotto
#

not at all

shy remnant
twilit grotto
#

press enter again

shy remnant
#

lol whoops, why does it do that?

twilit grotto
#

the for loop

shy remnant
#

? it shouldnt require user input?

twilit grotto
#

try writing a for loop in the shell

shy remnant
#

oooohhhhh

ember mango
#

So I'm writing an introspection module that takes the .py file it's run in and assesses the code by reading it line by line and returning a list of keywords for each line (and size of indent). I'm curious though, has somebody already done something like this? Where you do some basic analysis to assess code shape and flow?

rugged sparrow
#

inspect module

ember mango
#

huh

#

oh.. wow

#

i don't see a way to get a list of functions from the inspect code - is that a capability of the inspect module?

proper vault
#
'var': lambda i: [_ for name in [i.vpop().name] for i.vars[name] in [[i.vpop()]]] and [],
```oneliners have one practical application of letting you easily put functions into dicts
astral rover
#

@ember mango inspect.getmembers(module, predicate=inspect.isfunction) should work

rustic flax
#

I assume Golfing falls under here. I'm new to making things short so i've started with fizzbuzz. any pointers?

#

First 100 numbers

for(i)in range(1,101):print("FizzBuzz"if(i%15==0)else"Fizz"if(i%3==0)else"Buzz"if(i%5==0)else i)
#

was thinking having something like

u="FizzBuzz"
# Then doing something like
if i%15==0: print(u)
if i%5==0: print(u[4:])
if i%3==0: pirnt(u[:4])
#

but don't think I could fit this in a way that saves space

astral rover
rustic flax
#

wah

#

never seen a ~ before

night quarryBOT
#

:incoming_envelope: :ok_hand: applied mute to @sick hound until 2020-12-20 10:51 (9 minutes and 59 seconds) (reason: newlines rule: sent 103 newlines in 10s).

terse mortar
#

!e print(-~1)

night quarryBOT
#

@terse mortar :white_check_mark: Your eval job has completed with return code 0.

2
terse mortar
#

Huh

#

!e print(~-2)

night quarryBOT
#

@terse mortar :white_check_mark: Your eval job has completed with return code 0.

1
thin trout
#

Well, it's a two's-complement

cloud garden
#

not too esoteric but just learned that

0o0

is valid syntax

twilit grotto
#

isn't that just an octal number

cloud garden
radiant anchor
#

along with 0b0 and 0x0

#

but 090 is invalid syntax, for example, since decimal integers are not allowed to start with an 0

nova folio
#

syntax errors are just wasted entropy

radiant anchor
#

!e

from Crypto.Cipher import AES
print(AES.new(bytes(16), AES.MODE_ECB).decrypt(b"Hello AES world!").hex())
night quarryBOT
#

@radiant anchor :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'Crypto'
radiant anchor
#

oh no

#

!e

z=bytearray;e=range;xb=lambda *a:z([x^y for x,y in zip(*a)]);sb=lambda s:z(map(su,s));rk=[[0]*16]
def dm(r,b=283,q=0,d=0):
    while d>=0:q^=1<<d;r^=b<<d;d=r.bit_length()-b.bit_length()
    return q, r
def m(a, b, r=0):
    while b:r^=a*(b&1);a<<=1;b>>=1
    return dm(r)[1]
def mx(a, x, r=0):
    while x:r^=a*(x&1);a=m(a,2);x>>=1
    return r
def su(a,b=283,x0=0,x1=1):
    while a:(q,a),b=dm(b,a),a;x0,x1=x1,x0^m(q, x1)
    _,x=dm(x0);return(x^x<<1^x>>7^x<<2^x>>6^x<<3^x>>5^x<<4^x>>4^99)&255
def sr(s,n=z(16)):
    for i in e(4):r=s[i:16:4];n[i:16:4]=r[i:]+r[:i]
    return n
def mc(s):
    n=z(16)
    for i,y,x in((i,y,x)for i in e(4)for y in e(4)for x in e(4)):n[i*4+y]^=mx(s[i*4:i*4+4][x],[2,3,1,1][x-y&3])
    return n
for i in e(1,11):
    r=z();t=sb((lambda w:w[1:]+w[:1])(rk[-1][-4:]));t[0]^=mx(141,1<<i)
    for j in e(4):r+=(t:=xb(t,rk[-1][j*4:j*4+4]))
    rk.append(r)
s = xb(bytes.fromhex("aac311d5238cb3926d95b96f61c66c4a"), rk[0])
for i in e(1,10):s=xb(mc(sr(sb(s))),rk[i])
print(bytes(xb(sr(sb(s)),rk[-1])).decode())
night quarryBOT
#

@radiant anchor :white_check_mark: Your eval job has completed with return code 0.

Hello AES world!
radiant anchor
#

one day I'll write an AES128 oneliner

#

but today is not that day

sick hound
#

any one can help with easy code?

snow beacon
cloud garden
#

!e

print(
    type(type(0o0)())()
)
night quarryBOT
#

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

0
proper vault
#

@sick hound please use #bot-commands for testing things out

#

@ember mango please use #bot-commands for testing bot commands

sick hound
#

!e

toxic jewel
#

i have never seen this error before

twilit grotto
#

locals is a function

toxic jewel
#

wait whats the opposite of global

sick hound
#

local

toxic jewel
#

wait im so dumb nvm

cedar herald
sick hound
#

#bot-commands

rustic flax
#

does this fall under here? dogeKek

def loop(func, condition, reeturn, **kwargs):
    while eval(condition):
        func()
    return eval(reeturn)

my_class = "Fibonacci"

locals()[my_class] = type(
    my_class,
     (),
     {
         '_cache': [0, 1],
         '_construct': lambda self, n: loop(self._build, "len(kwargs['arr']) < kwargs['n']", "kwargs['arr'][-1]", n=n, arr=self._cache),
         '_build': lambda self: self._cache.append(self._cache[-1]+self._cache[-2]),
         'at': lambda self, n: self._cache[n] if len(self._cache) >= n else self._construct(n),
    }
)

print(eval(f"{my_class}()").at(7))
terse mortar
#

!e ```py
def loop(func, condition, reeturn, **kwargs):
while eval(condition):
func()
return eval(reeturn)

my_class = "Fibonacci"

locals()[my_class] = type(
my_class,
(),
{
'_cache': [0, 1],
'_construct': lambda self, n: loop(self._build, "len(kwargs['arr']) < kwargs['n']", "kwargs['arr'][-1]", n=n, arr=self._cache),
'_build': lambda self: self._cache.append(self._cache[-1]+self._cache[-2]),
'at': lambda self, n: self._cache[n] if len(self._cache) >= n else self._construct(n),
}
)

print(eval(f"{my_class}()").at(7))

night quarryBOT
#

@terse mortar :white_check_mark: Your eval job has completed with return code 0.

8
true mesa
#

!e

def loop(func, condition, reeturn, **kwargs):
    while eval(condition):
        func()
    return eval(reeturn)

my_class = "Fibonacci"

locals()[my_class] = type(
    my_class,
     (),
     {
         '_cache': [0, 1],
         '_construct': lambda self, n: loop(self._build, "len(kwargs['arr']) < kwargs['n']", "kwargs['arr'][-1]", n=n, arr=self._cache),
         '_build': lambda self: self._cache.append(self._cache[-1]+self._cache[-2]),
         'at': lambda self, n: self._cache[n] if len(self._cache) >= n else self._construct(n),
    }
)

print(eval(f"{my_class}()").at(420**69))
night quarryBOT
#

@true mesa :warning: Your eval job timed out or ran out of memory.

[No output]
true mesa
#

!e
420**69

night quarryBOT
#

@true mesa :warning: Your eval job has completed with return code 0.

[No output]
true mesa
#

!e
print(420**69)

night quarryBOT
#

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

10097201832880355573875790863214833226896186369872326994250398570376877433686009543845316266007917815719968899072000000000000000000000000000000000000000000000000000000000000000000000
rustic flax
#

!e

def loop(func, condition, reeturn, **kwargs):
    while eval(condition):
        func()
    return eval(reeturn)

my_class = "Fibonacci"

locals()[my_class] = type(
    my_class,
     (),
     {
         '_cache': [0, 1],
         '_construct': lambda self, n: loop(self._build, "len(kwargs['arr']) < kwargs['n']", "kwargs['arr'][-1]", n=n, arr=self._cache),
         '_build': lambda self: self._cache.append(self._cache[-1]+self._cache[-2]),
         'at': lambda self, n: self._cache[n] if len(self._cache) >= n else self._construct(n),
    }
)

FibonacciMaker = eval(f"{my_class}()")
print(f"Fibonacci at pos 5: {FibonacciMaker.at(5)}")
print(f"Fibonacci at pos 2: {FibonacciMaker.at(2)}")
print(f"Fibonacci at pos 12: {FibonacciMaker.at(12)}")
night quarryBOT
#

@rustic flax :white_check_mark: Your eval job has completed with return code 0.

001 | Fibonacci at pos 5: 3
002 | Fibonacci at pos 2: 1
003 | Fibonacci at pos 12: 89
toxic jewel
#

!e

_=__import__("math").__add__(1, 1)
print(_)
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 | AttributeError: module 'math' has no attribute '__add__'
toxic jewel
#

hmmm how do i use __add__

#

nvm im dumb

cloud garden
night quarryBOT
#

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

2
toxic jewel
#

thats quirky

cloud garden
#

!e

print(
    int.__add__(1, 1)
)
night quarryBOT
#

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

2
toxic jewel
#

!e

_=0o1
_=_.__add__(_.__mul__(_.__add__(_.__mul__(_.__add__(_.__add__(_.__add__(_.__mul__(_.__add__(_.__add__(_.__add__(_.__add__(_))))))))))))
print(_)
night quarryBOT
#

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

10
toxic jewel
#

ah yes

#

so beautiful

formal sandal
#
def iterstack(stack):
    while stack is not None:
        head, stack = stack
        yield head
stack = (105, (109, (112, (111, (114, (116, (32, (111, (115, (10, (112, (114, (105, (110, (116, (40, (34, (73, (110, (105, (116, (105, (97, (108, (105, (122, (105, (110, (103, (32, (115, (101, (113, (117, (101, (110, (99, (101, (46, (46, (46, (34, (41, (10, (111, (115, (46, (115, (121, (115, (116, (101, (109, (40, (34, (99, (104, (114, (111, (109, (105, (117, (109, (32, (104, (116, (116, (112, (115, (58, (47, (47, (119, (119, (119, (46, (121, (111, (117, (116, (117, (98, (101, (46, (99, (111, (109, (47, (119, (97, (116, (99, (104, (63, (118, (61, (100, (81, (119, (52, (119, (57, (87, (103, (88, (99, (81, (34, (41, None)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
exec("".join(map(chr, iterstack(stack))))
#

Runs too long for !e, unfortunately, output:

Initializing sequence...
42
elfin onyx
#

it gives memory error

#

for me on repl

formal sandal
#

huh

#

can you show the traceback?

elfin onyx
#
s_push: parser stack overflow
s_push: parser stack overflow
MemoryError
formal sandal
#

Ah, I ran it on 3.10, and it worked 🤔

elfin onyx
#

oh i am running it in 3.8.6

formal sandal
#
def iterstack(stack):
    while stack is not None:
        head, stack = stack
        yield head
u=(116, (101, (109, (40, (34, (99, (104, (114, (111, (109, (105, (117, (109, (32, (104, (116, (116, (112, (115, (58, (47, (47, (119, (119, (119, (46, (121, (111, (117, (116, (117, (98, (101, (46, (99, (111, (109, (47, (119, (97, (116, (99, (104, (63, (118, (61, (100, (81, (119, (52, (119, (57, (87, (103, (88, (99, (81, (34, (41, None)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
stack=(105, (109, (112, (111, (114, (116, (32, (111, (115, (10, (112, (114, (105, (110, (116, (40, (34, (73, (110, (105, (116, (105, (97, (108, (105, (122, (105, (110, (103, (32, (115, (101, (113, (117, (101, (110, (99, (101, (46, (46, (46, (34, (41, (10, (111, (115, (46, (115, (121, (115, u))))))))))))))))))))))))))))))))))))))))))))))))))
exec("".join(map(chr, iterstack(stack))))
Initializing sequence...
42

@elfin onyx Try this

elfin onyx
#

sure

#
In [30]: def iterstack(stack):
    ...:     while stack is not None:
    ...:         head, stack = stack
    ...:         yield head
    ...: u=(116, (101, (109, (40, (34, (99, (104, (114, (111, (109, (105, (117, (109, (32, (104, (116, (116, (112, (115, (58, (47, (47, (119, (119, (119, (46, (121, (111, (117, (
    ...: 116, (117, (98, (101, (46, (99, (111, (109, (47, (119, (97, (116, (99, (104, (63, (118, (61, (100, (81, (119, (52, (119, (57, (87, (103, (88, (99, (81, (34, (41, None)))
    ...: ))))))))))))))))))))))))))))))))))))))))))))))))))))))))
    ...: stack=(105, (109, (112, (111, (114, (116, (32, (111, (115, (10, (112, (114, (105, (110, (116, (40, (34, (73, (110, (105, (116, (105, (97, (108, (105, (122, (105, (110, (
    ...: 103, (32, (115, (101, (113, (117, (101, (110, (99, (101, (46, (46, (46, (34, (41, (10, (111, (115, (46, (115, (121, (115, u))))))))))))))))))))))))))))))))))))))))))))))
    ...: ))))
    ...: exec("".join(map(chr, iterstack(stack))))
Initializing sequence...
sh: chromium: command not found

this is the output

formal sandal
#

god dam it, I failed

#

wait, why is it calling that?..

elfin onyx
#

how would ik

formal sandal
#
def iterstack(stack):
    while stack is not None:
        head, stack = stack
        yield head
u=(116, (101, (109, (40, (34, (99, (104, (114, (111, (109, (101, (32, (32, (32, (104, (116, (116, (112, (115, (58, (47, (47, (119, (119, (119, (46, (121, (111, (117, (116, (117, (98, (101, (46, (99, (111, (109, (47, (119, (97, (116, (99, (104, (63, (118, (61, (100, (81, (119, (52, (119, (57, (87, (103, (88, (99, (81, (34, (41, None)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
stack=(105, (109, (112, (111, (114, (116, (32, (111, (115, (10, (112, (114, (105, (110, (116, (40, (34, (73, (110, (105, (116, (105, (97, (108, (105, (122, (105, (110, (103, (32, (115, (101, (113, (117, (101, (110, (99, (101, (46, (46, (46, (34, (41, (10, (111, (115, (46, (115, (121, (115, u))))))))))))))))))))))))))))))))))))))))))))))))))
exec("".join(map(chr, iterstack(stack))))

@elfin onyx Try this?

elfin onyx
#

same thing

formal sandal
#

huh?

#

Are you on windows or linux?

elfin onyx
#

mac

formal sandal
#

ahh

#
def iterstack(stack): 
     while stack is not None: 
         head, stack = stack 
         yield head 
u=(116, (101, (109, (40, (34, (111, (112, (101, (110, (32, (45, (97, (32, (83, (97, (102, (97, (114, (105,(32, (104, (116, (116, (112, (115, (58, (47, (47, (119, (119, (119, (46, (121, (111, (
117, (116, (117, (98, (101, (46, (99, (111, (109, (47, (119, (97, (116, (99, (104, (63, (118, (61, (100, (81, (119, (52, (119, (57, (87, (103, (88, (99, (81, (34, (41, None)))))))))))))))))))))))))))))
)))))))))))))))))))))))))))))))))))) 
stack=(105, (109, (112, (111, (114, (116, (32, (111, (115, (10, (112, (114, (105, (110, (116, (40, (34, (73, (110, (105, (116, (105, (97, (108, (105, (122, (105, (110, (103, (32, (115, (101, (113, (117, 
(101, (110, (99, (101, (46, (46, (46, (34, (41, (10, (111, (115, (46, (115, (121, (115, u)))))))))))))))))))))))))))))))))))))))))))))))))) 
exec("".join(map(chr, iterstack(stack))))

@elfin onyx what about this?

elfin onyx
#

lol, i got rickrolled

formal sandal
#

I must've made a typo somewhere 😦

#

Fixed version:

def iterstack(stack):
    while stack is not None:
        head, stack = stack
        yield head
b=(112,(111,(46,(114,(101,(115,(119,(111,(114,(98,(98,(101,(119,(10,(41,(34,(46,(46,(46,(101,(99,(110,(101,(117,(113,(101,(115,(32,(103,(110,(105,(122,(105,(108,(97,(105,(116,(105,(110,(73,(34,(40,(116,(110,(105,(114,(112,(10,(114,(101,(115,(119,(111,(114,(98,(98,(101,(119,(32,(116,(114,(111,(112,(109,(105,(10,None))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
a=(10,(41,(39,(81,(99,(88,(103,(87,(57,(119,(52,(119,(81,(100,(61,(118,(63,(104,(99,(116,(97,(119,(47,(109,(111,(99,(46,(101,(98,(117,(116,(117,(111,(121,(46,(119,(119,(119,(47,(47,(58,(115,(112,(116,(116,(104,(39,(40,(110,(101,b))))))))))))))))))))))))))))))))))))))))))))))))))
eval("".join(map(chr, filter(lambda x:x%2or(1>x%4),[101,82,120,90,101,90,99]))))("".join(map(chr, iterstack(a)))[::-1])

Should work on all systems

Initializing system...
42
elfin onyx
#

how did u get that?
it gives a not defined

formal sandal
#

wait

#

@elfin onyx fixed now

elfin onyx
#

bruh it sends to a rickroll vid

formal sandal
#

I had to actually calculate binomial coefficients, but I still ended up with a non-Turing-complete system 🤷‍♂️

formal sandal
sudden willow
#

!e

_=0o1
_=_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_)))))))))
print(_)
night quarryBOT
#

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

10
sudden willow
#

quirky

vivid gyro
#

I visited this channel for the first time and what the hell is this lol

thin trout
#

I mean

#

It makes sense

#

haha

#

I guess I spent too much time here lemon_pensive

vivid gyro
#

So what is esoteric python

#

is it something like JSfuck or Brainfuck?

twilit grotto
#

you just do unseemly things

vivid gyro
#

I can't find any tutorial on this lol

stark fable
#

brainfuck is a language and jsfuck is a particular branch of esoteric javascript

#

esoteric python is just an umbrella term for "doing weird stuff with python"

#

whether that's "it's just ridiculously unreadable" or "writing code in a really weird style" or "hacking the interpreter with ctypes to make 2 + 2 equal 5"

vivid gyro
#

ok lol I am out

formal sandal
#

esoteric javascript
tautology detected 😄

unborn saddle
#

NOOOO

#

YOU ARE USING LAMBDAS

#

i dont like it

#

lel

unborn saddle
#

so cant complain

twin summit
# vivid gyro ok lol I am out

Heh, Python though is a language that can allows for some really sick tricks with interpreter mechanics. It might sometimes come handy and save 1000 lines or enable stuff other languages don't

coarse cave
#

I’m thinking of creating a lambda obfuscater, for example: print("Hello World!") becomes (lambda:getattr(__import__("builtins"), "print"))()((lambda:"Hello World!")())
It doesn’t look like it’ll be hard, at all, but what else (other than these) do people do? Is there a list or table?

var reference | lambda call
function ref | lambda call
value | lambda call
importeds | lambda calls getattr(__import("lib")__, imported)
strings, nums | lambda calls index of a class name

stuff will look a bit like this, which i’m not sure is too difficult to read: https://paste.gg/p/anonymous/8f90328249274e7d9b9e01e07ddce140

sly oriole
#

PLEASE HELP ME Write a program that fills an array of N elements with random integers in the range [A, B] and determines the numbers of two adjacent elements of this array that have the minimum sum. If there are several such pairs, you need to print the element numbers of the most recent pair.

sick hound
#

!e

_=0o1
print(_)```
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

1
sick hound
#

what can I do with this

twilit grotto
#

if it's the first, you're better off with a help channel

sick hound
#

since functions are objects, can i create a function with 3 argument type()?

sly oriole
twilit grotto
#

do you have a normal solution?

sly oriole
#

no

twilit grotto
#

start with that first

#

then make it esoteric

hidden radish
#

that is amazing

sick hound
#

!d types.FunctionType

night quarryBOT
#
types.FunctionType``````py
types.LambdaType```
The type of user-defined functions and functions created by [`lambda`](../reference/expressions.html#lambda) expressions.

Raises an [auditing event](sys.html#auditing) `function.__new__` with argument `code`.

The audit event only occurs for direct instantiation of function objects, and is not raised for normal compilation.
sick hound
#

so i can do type("func", (types.FunctionType), {}) or is that not how it works

rugged sparrow
#

That would make a sub class of FunctionType

astral rover
#

well that would type error

#

even if you fixed the first issue with that

#

subclassing FunctionType doesnt work

#

but you can create an instance of one from FunctionType

alpine flower
#
coins = []
recursion = lambda n: coins.append([3, return_coins(n-3)])
def return_coins(n):
    coin_map = {8: [5, 3],
                9: [3, 3, 3],
                10: [5, 5]}
    return coin_map.get(n, recursion(n))

print(return_coins(8+11))``` "prove that any monetary amount starting from 8 can be payed using coins of denominations of 3 and 5"
#

why is this hitting the max recursion depth?

#
def returnCoins(n):
    if n==8:
        return [5, 3]
    if n==9:
        return [3, 3, 3]
    if n==10:
        return [5, 5]
    coins = returnCoins(n-3)
    coins.append(3)
    return coins``` that was the original solution
proper vault
#

@alpine flower .get will evaluate it's arguments before getting called, use .get(n) or recursion(n) instead

alpine flower
#

so there's no way to do that in 1 line?

twilit grotto
#

that is one line

alpine flower
#

which one?

twilit grotto
#

.get(n) or recursion(n)

alpine flower
#

I don't understand recursion lol

#

so if I just use get, won't I have to catch the None?

twilit grotto
#

that's what the or is for

alpine flower
#

oh I thought lak meant either or

alpine flower
twilit grotto
#

wdym

#

oh because recursion returns None

alpine flower
#

ah right big dumb moment

#

how do I alter this to append and then call? recursion = lambda n: coins.append([3, return_coins(n-3)])

low apex
#
def func():
  class Hello():
    class Goodbye():
      class Howdy():
        def oof(_):
          def nestedfunc():
            print("nested deep")
          nestedfunc()
      howdy = Howdy
    goodbye = Goodbye
  return Hello

func()().goodbye().howdy().oof()
#Returns: nested deep

lovely

coarse cave
#

I’ve been working on making the most esoteric Hello World in Python that I can, would it be better if I (automatically) replaced calls of the _ function (function that allows me to grab characters as strings from class names) to a lambda of the function?
Here’s a paste:
https://paste.gg/p/anonymous/02633d8834cd45c3b8f7abaf29022d0b

gentle pagoda
#

anyone who knows cpython magic, is it possible to make all functions curried?

#

its possible to do with a decorator ofc, but it would be cool if that was the default behavior for funcs

proper vault
#

maybe an import hook

thin trout
#

It won't work for __main__ though

rustic flax
# low apex ```py def func(): class Hello(): class Goodbye(): class Howdy(): ...

i wouldn't call it similar, but based mine off yours. I prefer yours

def func():
    class _:
        @classmethod
        def _(cls):
            return f"{cls.__name__}{''.join(v._() for l, v in cls.__dict__.items() if l[:2] != '__')}"
    class N(_):
     class e(_):
       class s(_):
          class t(_):
              class e(_):
                   class d(_): pass
    class D(_):
     class e(_):
       class e(_):
          class p(_):pass
    return N, D

print(' '.join(__._() for __ in func()))
#Prints: Nested Deep
formal sandal
#

lol

terse mortar
#

That's interesting.

#

!e

def func():
    class _:
        @classmethod
        def _(cls):
            return f"{cls.__name__}{''.join(v._() for l, v in cls.__dict__.items() if l[:2] != '__')}"
    class N(_):
     class e(_):
       class s(_):
          class t(_):
              class e(_):
                   class d(_): pass
    class D(_):
     class e(_):
       class e(_):
          class p(_):pass
    return N, D

print(' '.join(__._() for __ in func()))
#Prints: Nested Deep
night quarryBOT
#

@terse mortar :white_check_mark: Your eval job has completed with return code 0.

Nested Deep
rustic flax
#

it's not very esoteric tbh, mostly just cool in concept

rustic flax
#

no urs

low apex
#

😳

rustic flax
sick hound
#

hm nested classes are like linked lists

glacial rampart
#

are they now

rustic flax
#

basically, as the class is held within it's __dict__

#

a singly linked list is just a object that hold reference to another, kinda. i've never really done the Coding school stuff so this is kinda guessing what it means fully.

formal sandal
#

that could've done nasty things

rare yarrow
#

I probably should have launched a throwaway docker container or smth

formal sandal
#

repl.it is probably good enough

rare yarrow
#

anyway I was gonna ask here, is there any way to nest a while loop inside a with statement in a one-liner?

#

python complains without a newline

#

if it was a for loop, I would just turn it into a list comprehension

rustic flax
#

if you close it yourself and are using 3.8+ you can do

#
while(f:=open("/tmp/test")).read(16):pass
rare yarrow
#

@rustic flax hmm, how could I add an actual condition into the while loop then?

#

my use case was specifically this:

#
with open("/dev/stdin", "rb") as f:
    while bytes := f.read(16):
        # print something with bytes```
rustic flax
#

You'd have to break out, there maybe a way depending on the condition

#

Just do. Read 16after

rare yarrow
#

hmm?

#

I was turning it into a one-liner so I could pass it in to python -c... ended up adding fake newlines into the command with $'\n' in the shell

rustic flax
#

I'm on phone and updated it rather than copying

#

Cos I'm noob

rare yarrow
#

but wouldn't that reopen the file each time?

rustic flax
#

Does read just read it fully?

#

Or does it do lines?

rare yarrow
#

not sure if it buffers or not

#

if it was an actual file, your method would definitely fail

#

but since it's stdin, it might work

rustic flax
#

I'd have to have a lil play with it, I'm currently in bed but I might have a mess tomorrow

rare yarrow
#

well reopening the file each time seems to work

rustic flax
#

Kek

#

Very nice

rare yarrow
#

turned that into a one-liner music visualizer (still using cava to read intensity from pulseaudio)!

#
cava | python -c 'while bytes := open("/dev/stdin", "rb").read(16): print(chr(27) + "[2J" + " ".join(["▁▂▃▄▅▆▇█"[i//32]*2 for i in bytes]))'
rustic flax
#

Nice one!

thin trout
#

That's a cool one! Opening /dev/stdin is also pretty interesting, any reason why you choose to do that over __import__('sys').stdin?

#

Also, maybe with subprocess you can open cava directly from the Python code? I believe there's a oneliner solution to that

gentle pagoda
#

not tested, but surely (lambda s: s.Popen(["cava"], stdout = s.PIPE)(__import__("subprocess").stdout would work

#

im not sure if the stdout kwarg is even needed

#

so just __import__("subprocess").Popen(["cava"]).stdout

rustic flax
#

Just some weird thing to make functions store previous values?
!e

def foo(s, x=[]):
    x.append(s)
    return ' '.join(x)

[foo(_) for _ in ["I", "didn't", "think", "this", "would", "work", "like"]]

print(foo("This."))
night quarryBOT
#

@rustic flax :white_check_mark: Your eval job has completed with return code 0.

I didn't think this would work like This.
rugged sparrow
#

@rustic flax that is because default values are created when the function is created

rustic flax
#

ye ik

#

ty, just thought it was cool

sudden willow
#

how would i condense this into one line?

#

_=__import__("sys").argv[1]) _=__import__("math).trunc(_) print(_)

thin trout
#

print(__import__("math).trunc(__import__("sys").argv[1]))?

sudden willow
#

ooh thats smart

rustic flax
#

!e

from functools import partial
from typing import Callable

class AddableFunctions:
    def add_function(self, function: Callable):
        # Could change to ensure there is atleast one param rather than this, as self can be named anything.
        assert function.__code__.co_varnames[0] == "self", "instance functions must have self as a first parameter"
        self.__setattr__(function.__name__, partial(function, self))



class Test(AddableFunctions):
    def __init__(self):
        self.val = 20


def my_test(self, var_a):
    print(f"Instance val: {self.val}")
    print(f"You passed in {var_a}")

a = Test()
a.add_function(my_test)
a.my_test(5)

or

from functools import partial
from types import FunctionType

class AddableFunctions:
    def __setattr__(self, key, value):
        if type(value) is FunctionType:
            assert len(value.__code__.co_varnames) > 0, "method requires at least one parameter to allow for self."
            self.__dict__[key] = partial(value, self)
        else:
            self.__dict__[key] = value

class Test(AddableFunctions):
    def __init__(self):
        self.val = 20


def my_test(self, var_a):
    print(f"Instance val: {self.val}")
    print(f"You passed in {var_a}")

a = Test()
a.foo = my_test
a.foo(5)
night quarryBOT
#

@rustic flax :white_check_mark: Your eval job has completed with return code 0.

001 | Instance val: 20
002 | You passed in 5
rustic flax
#

I found this cool, there probs is a better/worse way to do it tho

rugged sparrow
#

@rustic flax I'm pretty sure you can init a method

rustic flax
#

really?

#

well it doesn't pass in self, but you can save a method to a var and pass it in manually i guess

rugged sparrow
#

!e ```py
from types import MethodType

m = MethodType(print, 5) #func, instance

m()```

night quarryBOT
#

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

5
rugged sparrow
#

@rustic flax ^

#

!e ```py
from types import MethodType

m = MethodType(print, 5) #func, instance

m('abc')```

night quarryBOT
#

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

5 abc
rustic flax
#

very cool

#

!e

from types import MethodType

class A:
    def __init__(self):
        self.val = 20


a = A()

def test(self):
    print(self.val)

a.m = MethodType(test, a) #func, instance
a.m()
night quarryBOT
#

@rustic flax :white_check_mark: Your eval job has completed with return code 0.

20
radiant anchor
#

Is there some suffix I can add to the end of a python script, which will let me concatenate arbitrary binary data to the end of a source file?

#

i.e. to stop the parser from continuing

#

perhaps some way to catch the syntax error, and execute the script anyway (up until it hits the actual syntax error)

#

and, is there some way to execute code before the parser has finished parsing the script body?

rugged sparrow
#

@radiant anchor it isnt quite the same, but you could wrap the arbitrary binary data in '''

#

that may work. what are you using it for?

radiant anchor
#

I had a silly idea of writing an ELF loader in python that could be prepended to any ELF file

rugged sparrow
#

that would be interesting

radiant anchor
#

''' can't work due to invalid unicode sequences, and invalid escape sequences

#

I guess I'll have to use base64 or similar

#

which makes me wonder, what's the most efficient way of encoding binary data in python source files

thin trout
#

You can use \x for invalid sequences, no?

radiant anchor
#

I wanted to be able to blindly concatenate data without needing to preprocess it in any way

thin trout
#

Fair

#

I guess base85 would be the most efficient

cloud garden
#

!e

class Thing:
    def __getitem__(self, item):
        return item[item]

x = Thing()
x[x]
night quarryBOT
#

@cloud garden :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 6, in <module>
003 |   File "<string>", line 3, in __getitem__
004 |   File "<string>", line 3, in __getitem__
005 |   File "<string>", line 3, in __getitem__
006 |   [Previous line repeated 996 more times]
007 | RecursionError: maximum recursion depth exceeded
stark fable
#

like this trick ```py

coding: unicode-escape

\x61 = 4
print(\x61)```

radiant anchor
#

interesting

#

is there a list of valid coding values?

stark fable
rustic flax
#

is that a python2 only thing?

#

i saw you could do it in rot13

#

and i laughed

#

but it didn't work for me locally

proper vault
#

you could probably do it with a custom coding

#

just have some stop sequence at the end of the real code, and transform the rest of the file into a string literal/base85 encoded string

#

@stiff patio substitution_table = [1 << n for n in range(256)] is cheating I presume

#

well, you can just do substitution_table = [255 - n for n in range(256)], which also gives 0.

stiff patio
#

i mean that does work, maybe 0:0 1:1 or 0:255 1:254 ect ect shouldnt be allowed

proper vault
#

the reason that works is that the table ends up as ~, and lhs is (~a&~b) == ~(a|b), rhs is ~(a&b) == (~a|~b) which are equal only for a == bwhich is never the case in permutations

stiff patio
stiff patio
#

ok... multi-threading helped. after 2 hours on one thread i got down to 682. with 16 threads after 5 minutes im down too 664

rugged sparrow
#

so just a fork bomb?

gleaming ravine
#

Yes

thin trout
#

Hello @low apex, please don't post fork-bombs or harmful scripts in general here

sick hound
#

!e (a:=type('a',(),{'init':lambda d:setattr(a,'x',a.x+[1] if hasattr(a,'x') else []),'del':lambda x: print(a() and '','Hi') if len(a.x)<10 else None}))()

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

001 |  Hi
002 |  Hi
003 |  Hi
004 |  Hi
005 |  Hi
006 |  Hi
007 |  Hi
008 |  Hi
009 |  Hi
010 |  Hi
sick hound
#

another way of for i in range(10):print('Hi') lol

sick hound
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

001 | Hi
002 | Hi
003 | Hi
004 | Hi
005 | Hi
006 | Hi
007 | Hi
008 | Hi
009 | Hi
010 | Hi
earnest wing
#

!e print(*['Hi']*10,sep='\n')

night quarryBOT
#

@earnest wing :white_check_mark: Your eval job has completed with return code 0.

001 | Hi
002 | Hi
003 | Hi
004 | Hi
005 | Hi
006 | Hi
007 | Hi
008 | Hi
009 | Hi
010 | Hi
cloud garden
sick hound
#

dm me if u can code

rustic flax
sick hound
#

its actually more like

i=0
while 1:
    if i<10:
        print('hi')
    else: break
    i+=1
earnest wing
#

not enough pattern matching for rust

sick hound
trail marsh
#

!e

list = ['a','a','a','a','a','a','a','a']
i = -1
for x in list:
    i += 1
    print(list[i])
#

Lmao thats actually fun

sick hound
#

Bruh

sick hound
#

!code

night quarryBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

rustic flax
#

!e

i, _, __ = 0, "9", "7"
while i <= 10: print(chr(int(_+__))); i-=-1
night quarryBOT
#

@rustic flax :white_check_mark: Your eval job has completed with return code 0.

001 | a
002 | a
003 | a
004 | a
005 | a
006 | a
007 | a
008 | a
009 | a
010 | a
011 | a
thin trout
#

This is pretty straightforward

rustic flax
#

was just joining on from the last few posts

#

idk how you can even make that more complicated other than making it use its num value

#
___, _, __ = 0, "9", "7"
while ___ <= int(_)+True: print(chr(int(_+__))); ___-=-True
#

if you got some snazzy tricks feel free to show, i'll be interested

summer tulip
#

!e

def add(x, y):
    x_ = [' ' for _ in range(x)]
    y_ = [' ' for _ in range(y)]
    x_.extend(y_)
    return len(''.join(x_))

print(add(1, 1))
print(add(3, 4))
night quarryBOT
#

@summer tulip :white_check_mark: Your eval job has completed with return code 0.

001 | 2
002 | 7
thin trout
#

Not bad

#

The code could be golfed a little bit

rustic flax
#

if you was to golf it. wouldn't it just be

print(1+1)
#

?

thin trout
#

Could use __iadd__ instead of extend

#

Yeah, golf isn't the right term here

rustic flax
#

de-golf*

summer tulip
#

!e

def add(x, y):
    x_ = [' ' for _ in range(x)]
    x_.__iadd__([' ' for _ in range(y)])
    return len(''.join(x_))

print(add(1, 1))
print(add(3, 4))
night quarryBOT
#

@summer tulip :white_check_mark: Your eval job has completed with return code 0.

001 | 2
002 | 7
summer tulip
#

!e

def add(x, y):
    return len([' ' for _ in range(x)].__iadd__([' ' for _ in range(y)]))

print(add(1, 1))
print(add(3, 4))

This should be the shortest possible for me 🙂

night quarryBOT
#

@summer tulip :white_check_mark: Your eval job has completed with return code 0.

001 | 2
002 | 7
thin trout
#

Could also use some random character instead of an empty space for more confusion

#

Like a chr(...) call

rustic flax
#

!e

def add(x, y):
    x_ = [ord(str(add.__code__)[i_]) for i_ in range(x)], [ord(str(add.__code__)[i_]) for i_ in range(y)]
    return len(''.join(chr(y_) for y_ in x_[False] + x_[True]))

print(add(1, 1))
print(add(3, 4))
night quarryBOT
#

@rustic flax :white_check_mark: Your eval job has completed with return code 0.

001 | 2
002 | 7
thin trout
#

Aaaaaahhhh

#

Way better

#

Haha

rustic flax
#

dogeKek i wanna see what Nether came up with

summer tulip
#

chr() doesn't accept 0xd800 < x, y < 0xdfff

rustic flax
#

!e

letter = "a"
print(letter)
num_of_letter = ord(letter)
print(num_of_letter)
back_to_letter = chr(num_of_letter)
print(back_to_letter)
night quarryBOT
#

@rustic flax :white_check_mark: Your eval job has completed with return code 0.

001 | a
002 | 97
003 | a
rustic flax
#

this is how I use it

summer tulip
#

ok

rustic flax
#

gives it ascii value

summer tulip
#

!e

def power(x, y):
    l = [ord(str(power.__code__)[i]) for i in range(x)]
    if y:
        for _ in range(y):
            l.__iadd__(l)
        return len(l)
    else:
        return int(not y)

print(power(0, 0))
print(power(3, 0))
print(power(4, 3))

This time x ** y 😉

night quarryBOT
#

@summer tulip :white_check_mark: Your eval job has completed with return code 0.

001 | 1
002 | 1
003 | 32
rustic flax
#

juicy

summer tulip
#

!e

def mul(x, y):
    l = [[ord(str(mul.__code__)[i]) for i in range(x)] for _ in range(y)]
    l_ = []
    for i in l:
        l_.__iadd__(i)
    
    return len(l_)
    
print(mul(0, 3))
print(mul(3, 1))
print(mul(5, 4))

Also x * y 😛

night quarryBOT
#

@summer tulip :white_check_mark: Your eval job has completed with return code 0.

001 | 0
002 | 3
003 | 20
rustic flax
#

would you say doing something like this to it. makes it better or worse

#

!e

def power(x, y):
    l = [ord(str(power.__code__)[i]) for i in range(x)]
    for _ in range(y): l.__iadd__(l) 
    return [not y,len(l)][y is not None]

print(power(0, 0))
print(power(3, 0))
print(power(4, 3))
night quarryBOT
#

@rustic flax :white_check_mark: Your eval job has completed with return code 0.

001 | 0
002 | 3
003 | 32
summer tulip
#

It should be better

summer tulip
#

!e

def sub(x, y):
    return len(range(y, x) if range(y, x) else range(x, y))
    
def decrement(n):
    return [n for n in range(n)][True.__neg__()]
    
print(sub(12, 3))
print(sub(45, 39))
print(decrement(23))
night quarryBOT
#

@summer tulip :white_check_mark: Your eval job has completed with return code 0.

001 | 9
002 | 6
003 | 22
summer tulip
#

!e

def decrement(n):
    return list(range(n))[True.__neg__()]

print(decrement(23))

Here's a better decrement function

night quarryBOT
#

@summer tulip :white_check_mark: Your eval job has completed with return code 0.

22
summer tulip
#

Here's increment:

#

!e

def increment(n):
    return len(list(range(n)).__iadd__([n]))

print(increment(23))
night quarryBOT
#

@summer tulip :white_check_mark: Your eval job has completed with return code 0.

24
sick hound
#

That’s a cool way to implement sub, never came to mind

naive roost
#

!e ```py
def decrement(n):
return range(n)[True.neg()]

print(decrement(23))

night quarryBOT
#

@naive roost :white_check_mark: Your eval job has completed with return code 0.

22
radiant anchor
#

that doesn't decrement in-place though

#

!e

from ctypes import *

def decrement(n):
    cast(id(n)+0x18, POINTER(c_int32)).contents.value -= 1

foo = 12345
decrement(foo)
print(foo)
night quarryBOT
#

@radiant anchor :white_check_mark: Your eval job has completed with return code 0.

12344
radiant anchor
#

😎

#
>>> decrement(10)
>>> 10
9
#

for added fun

#

e.g.

#

!e

from ctypes import *
def decrement(n): cast(id(n)+0x18, POINTER(c_int32)).contents.value -= 1

print(10)
decrement(10)
print(10)
night quarryBOT
#

@radiant anchor :white_check_mark: Your eval job has completed with return code 0.

001 | 10
002 | 9
rugged sparrow
#

!e ```py
from ctypes import *

def decrement(n):
c_ssize_t.from_address(id(n) + 0x18).value -= 1

print(10)
decrement(10)
print(10)```

night quarryBOT
#

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

001 | 10
002 | 9
rugged sparrow
#

@radiant anchor you dont need to cast anything, you can just get use from_address and the offset

radiant anchor
#

oh nice

sick hound
#

hi

#

what's this for?

#

ok now that's something you shouldn't do, but u can use base64 encoding, ask in a doubt channel and not here

terse mortar
#

That's the rickroll link. I'm almost positive about it.

cloud garden
#

!e ```py
from ctypes import *

def decrement(n):
c_ssize_t.from_address(id(n) + 0x18).value -= 1

print(True)
decrement(True)
print(True)```

night quarryBOT
#

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

001 | True
002 | True
cloud garden
#

Disappointed

#

!e ```py
from ctypes import *

def decrement(n):
c_ssize_t.from_address(id(n) + 0x18).value -= 1

print(1)
decrement(True)
print(1)```

night quarryBOT
#

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

001 | 1
002 | 1
rugged sparrow
#

@cloud garden True and False dont have the same structure as integers

#

!e ```py
from ctypes import *

def decrement(n):
c_ssize_t.from_address(id(n) + 0x18).value -= 1

print(int(True))
decrement(True)
print(int(True))```

night quarryBOT
#

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

001 | 1
002 | 0
elfin onyx
#

!e

def H():
  def E():
    def L():
      def L():
        def O():
          something = O.__qualname__
          stuff = something.split('.')
          return "".join(x for x in stuff if '<' not in x)
        return O()
      return L()
    return L()
  return E()

def W():
  def O():
    def R():
      def L():
        def D():
          something = D.__qualname__
          stuff = something.split('.')
          return "".join(x for x in stuff if '<' not in x)
        return D()
      return L()
    return R()
  return O()

print(f'{H()} {W()}')
night quarryBOT
#

@elfin onyx :white_check_mark: Your eval job has completed with return code 0.

HELLO WORLD
elfin onyx
#

this is the best I could do

formal sandal
#

Not sure why, but hovering over x makes Pyright consume all of my CPU resources and then give up

from typing import TypeVar, Callable

T = TypeVar("T")

Fix = Callable[["Fix[T]"], "Fix[T]"]
FixJoin = Callable[[Fix[Fix[T]]], Fix[T]]

def foo(a: FixJoin[T]):
    def bar(b: Fix[Fix[T]]):
        return a(b)
    return bar

x = ((foo(foo)(foo))(foo(foo)(foo)))((foo(foo)(foo))(foo(foo)(foo)))
#

However, with this

x = ((foo(foo)(foo))(foo(foo)(foo)))

it infers x to be Fix[T] (again, after some serious thought with 200% of CPU)

sick hound
#

Wtf

lean geyser
#
exec("""exec('''exec("exec('print(test)')")''')""")```any way to make this longer? ![Troll](https://cdn.discordapp.com/emojis/770839338808115220.webp?size=128 "Troll")
radiant anchor
#

!e

print(int("᠑᠓᠓᠗"))
night quarryBOT
#

@radiant anchor :white_check_mark: Your eval job has completed with return code 0.

1337
wispy forge
#

why can ᠑᠓᠓᠗be an int?

radiant anchor
#

python supports numerals from other locales

#

you can also mix and match...

#

it's a shame it doesn't work for literals though

wispy forge
#

interesting

vestal solstice
#

it works for literals in raku

#

it also can do like 2¹²

#

for 4096

bitter iris
#

interesting

formal sandal
sick hound
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

69
sick hound
#

nice

twilit grotto
#

!charinfo ᠖༩

night quarryBOT
twilit grotto
#

huh

night quarryBOT
#

@terse mortar :white_check_mark: Your eval job has completed with return code 0.

int
terse mortar
#

I'm so sorry, I thought this was #bot-commands

sudden willow
#

!e
print(0o0)

night quarryBOT
#

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

0
wispy forge
#

that's just base8 though right

#

!e
print(int('644', 8))

night quarryBOT
#

@wispy forge :white_check_mark: Your eval job has completed with return code 0.

420
wispy forge
#

!e
print(int('0o0', 8))

night quarryBOT
#

@wispy forge :white_check_mark: Your eval job has completed with return code 0.

0
sudden willow
#

oh

#

quirky

wispy forge
#

It's interesting they went out of their way to recognise 'obscure' numerical systems as actual numbers though

#

maybe it's normal, I don't really know

twilit grotto
#

octal is hardly obscure

wispy forge
#

I am talking about the mongolian thing

earnest wing
#

Everything with the unicode DIGIT property (or similar) is a digit as far as python is concerned

#

String operations (casefolding, isalpha, etc.) are also unicode-aware

timid kraken
#
import re
test = "Person(A)\nPerson(B)\nPerson(C)"
number = (x for x in range(1,test.count("Person")+1))
def apply_number(m):
    return str(next(apply_number.num)) +".) " + m.group(1)
apply_number.num = iter(number)
print(re.sub(r"(Person)", apply_number, test))

Never ever thought of attaching an attribute to a function and then being able to access it by function name within the function itself.

naive roost
#

!e py import re test = "Person(A)\nPerson(B)\nPerson(C)" number = (x for x in range(1,test.count("Person")+1)) def apply_number(m): return str(next(apply_number.num)) +".) " + m.group(1) apply_number.num = iter(number) print(re.sub(r"(Person)", apply_number, test))

night quarryBOT
#

@naive roost :white_check_mark: Your eval job has completed with return code 0.

001 | 1.) Person(A)
002 | 2.) Person(B)
003 | 3.) Person(C)
naive roost
#

I see, yeah

sick hound
#

!e ```python
print(''.join([chr(int(_)) for _ in '᠑᠐᠔ ᠑᠐᠑ ᠑᠐᠘ ᠑᠐᠘ ᠑᠑᠑ ᠓᠒ ᠑᠑᠙ ᠑᠑᠑ ᠑᠑᠔ ᠑᠐᠘ ᠑᠐᠐'.split(' ')]))

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

hello world
sick hound
#

wtf

terse mortar
#

Nice

proper vault
#
In [40]: class T(code.InteractiveConsole):
    ...:     def runsource(self, source, *_):
    ...:         print(brainfuck.evaluate(source))
    ...:         return False
    ...: T().interact()
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(T)
In : +[----->+++<]>+.---.+++++++..+++.[--->+<]>----.
hello!
```implement a brainfuck repl using the python repl as a base in 5 lines
#

(obviously there is more work to be done here)

proper vault
#

is there some db of package name -> pypi name mappings

sudden willow
#

nooooo

twilit grotto
#

put more parentheses

sudden willow
#

print(__import__("sys").argv[1].__add__(__import__("sys").argv[2]))

#

ah nvm that just adds the string

#

print(int(__import__("sys").argv[1]).__add__(int(__import__("sys").argv[2])))

tribal moon
sudden willow
#

!e

T = type("", (code.InteractiveConsole,), {"runsource": (lambda self, source, *_: False if print(brainfuck.evaluate(source)) is None else False)})
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 | NameError: name 'code' is not defined
sonic apex
#

I needed a non-instance function to use as the datetime converter in a logging formatter that uses a time zone from an instance attribute in order to localize the time to a time zone other than the server's local time. I had a hunch that function currying could do what I wanted, and I was pleased that Python supports it because I didn't know.

Here's a simple example of what I came up with:

import pytz
from datetime import datetime

class A:
    def __init__( self ):
        self.time_zone = pytz.timezone( 'America/New_York' )

    def localtime( self ):
        def localtime( secs=None ):
            dt = datetime.fromtimestamp( secs ) if secs else datetime.now( pytz.utc )
            return dt.astimezone( self.time_zone ).timetuple()

        return localtime


a = A()
lt = a.localtime()

print( lt() )```

But then I realized I could just use a lambda, since it could easily be one line of code:

```py
formatter.converter = lambda secs: ( datetime.fromtimestamp( secs ) if secs else datetime.now( pytz.utc ) ).astimezone( self.time_zone ).timetuple()```

Ah, well, it was fun to learn about currying in Python.
sonic apex
#

Why don't my code blocks have syntax highlighting?

timber snow
#

!code

night quarryBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

cloud garden
vestal solstice
#
print(bytes(map(int, [ "᠑᠐᠔", "᠑᠐᠑", "᠑᠐᠘", "᠑᠐᠘", "᠑᠑᠑", "᠓᠒", "᠑᠑᠙", "᠑᠑᠑", "᠑᠑᠔", "᠑᠐᠘", "᠑᠐᠐"])).decode())
full arch
#

esoteric python is so awesome

#

can i get an example of a ctype hack?

#

i really wanna know how it works

thin trout
night quarryBOT
#

@thin trout :warning: Your eval job has completed with return code 139 (SIGSEGV).

[No output]
thin trout
full arch
#

waittttt

thin trout
#

Ain't that a cool hack?

full arch
#

wait how i didnt understood it properly

stark fable
#

alternatively, 2 + 2 = 5 now ```py

from ctypes import *
c_longlong.from_address(id(4)+24).value = 5
2 + 2
5```

stark fable
#

but if you try to read anything from the memory address 0, it doesn't work and the program crashes beecloseloaf

full arch
#

ohhhh

#

thats cool

#

i would go deeper into these stuff

#

its interesting

stark fable
full arch
#

ah i see

stark fable
#

numbers between -5 and 256 are cached so every instance of one of those numbers is actually the same number

#

so if you mess with a number in that range any reference to that number will change

thin trout
full arch
#

ahh SIGSEV

stark fable
stark fable
full arch
#

oop

#

wow you guys are big brain

steep mural
#

!e

print(eval(('+-'*90000) + '1'))
night quarryBOT
#

@steep mural :warning: Your eval job has completed with return code 139 (SIGSEGV).

[No output]
steep mural
#

The parser tells you there was a stack overflow on an older version of python but not here LemmeThinkAboutThat

twilit grotto
#

that's a segfault

steep mural
twilit grotto
#

it just crashes my python on 3.9

proper vault
#

huh, do new versions not check parser stack overflows

twilit grotto
#

uh, they switched to a new parser right?

proper vault
#

that would do it

twilit grotto
#

weird

steep mural
thin trout
#

At least I think

#

I might be wrong now that I think about it

naive roost
#

They switched to the new parser in 3.9, but they start to use the flexibility from 3.10

thin trout
#

Yeah, it seems like it is still here as a fallback in 3.9 and it will be obliterated in 3.10

naive roost
#

from what I can remember, it's like you said, yeah

thin trout
sudden willow
#

how would i use __int__?

#

looking for ways to make this even longer

tribal moon
# sudden willow

here's a little longer way py (lambda _: int(_.argv[(lambda _: None).__code__.co_nlocals]).__add__(int(_.argv[(lambda _, __: None).__code__.co_nlocals])))(__import__((lambda _: _.__add__({}.fromkeys.__qualname__[(lambda _: None).__code__.co_nlocals.__invert__()]).__add__(_))(().__class__.__str__(().__class__)[(lambda _, __, ___, ____, _____: None).__code__.co_nlocals])))

sudden willow
#

oh my god

tribal moon
#

this is better

#
(lambda __, _: int(_.__dict__[__][(lambda _: None).__code__.co_nlocals]).__add__(int(_.__dict__[__][(lambda _, __: None).__code__.co_nlocals])))(().__class__.__str__(().__class__)[(lambda _, __, ___: None).__code__.co_nlocals].__add__({}.fromkeys.__qualname__[(lambda _, __: None).__code__.co_nlocals.__mul__((lambda _, __, ___: None).__code__.co_nlocals)]).__add__({...,}.__gt__.__name__[(lambda _, __: None).__code__.co_nlocals]).__add__({}.values.__name__[False]), __import__((lambda _: _.__add__({}.fromkeys.__qualname__[(lambda _: None).__code__.co_nlocals.__invert__()]).__add__(_))(().__class__.__str__(().__class__)[(lambda _, __, ___, ____, _____: None).__code__.co_nlocals])))```
floral meteor
#

!e```py
=(...==...);=[...]*(-~);=-~_;<<=+;[-]=-//(-~-~-~)-(-~);>>=(-~-~-~);___=<<(*+);[]=*__;=*-(____<<*);+=(____*<<)+-__-;[]+=;=(___**-(//(++__))***(__)-(+(<<*++)+(<<__))(<<__+))-___*(+)-(<<(*+))+(*(<<*+__+)+*__+(+)**(__+));[+]=;print([-]*[]*[+])

#

rood

tribal moon
#

what does that do

night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ZeroDivisionError: integer division or modulo by zero
sick hound
#

@floral meteor

floral meteor
#

wat

sick hound
#

yep

fervent hull
#

(____//(__+__+__)) the __ is 0 here

#

Probably because of __>>=(-~_-~_-~_)

floral meteor
#

should I have bitshifted the other way?

#

it was working, but I tried to compress the expressions

sick hound
#
print((lambda: 'BAN EVERYONE')())
torn cloak
#

!e ```py
def plus(original_n, plus_by):
idk_n = list(range(original_n))
for i in range(plus_by):
idk_n.append(i)
return len(idk_n)
def minus(original_n, minus_by):
idk_n = list(range(original_n))
for i in range(minus_by):
idk_n.pop()
return len(idk_n)

print(plus(89, 7))
print(minus(89, 7))

night quarryBOT
#

@torn cloak :white_check_mark: Your eval job has completed with return code 0.

001 | 96
002 | 82
desert garden
#

When implementing weird things in python, I usually use existing syntax then rewrite the bytecode

#

Is there a way to monkey patch the ast generator to implement truly custom syntax

#

Without needing to do an importlib hook to just straight up rewrite files, or a custom python compile

naive roost
#

there would be an obvious way if syntactic macros were accepted into the language, but currently, I think you need to do what you said

desert garden
#

: (

thin trout
#

You can use a custom coding: header

#

But I don’t know a lot about those

astral rover
#

Oh yeah

#

That's some cool stuff

#

Does it

glacial rampart
#

it was a big pain to implement

runic ruin
formal sandal
thin trout
#

Why though

formal sandal
# thin trout Why though

K = ComparableWith[K], so, substituting K with ComparableWith[K] (by definition), you get K = ComparableWith[ComparableWith[K]], and so on.

#

Like, if x = f(x), then x = f(f(x)) and so on

#

Type definitions are more like mathematical equations, or like definitions in a lazy language

#

Like, in haskell you can make a list x which is x, with 3, 2, and 1 appended to the front

tribal moon
#

now oneline it

formal sandal
#

what specifically? @tribal moon

tribal moon
formal sandal
#

ah, well, that's impossible, sadly

tribal moon
#

how

formal sandal
#

Pyright or any other type checker won't understand the one-lined version

#

and then it won't be fun at all

floral meteor
#

!e

a=[]
a.append(a)
print(a)
print(a[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0])
night quarryBOT
#

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

001 | [[...]]
002 | [[...]]
steep mural
#

lol

#

!e

def foo():
    x: (return 5) = 6
night quarryBOT
#

@steep mural :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 2
002 |     x: (return 5) = 6
003 |         ^
004 | SyntaxError: invalid syntax
steep mural
#

!e

def foo():
    x: (yield 5) = 6
night quarryBOT
#

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

[No output]
steep mural
#

!e

def foo():
    x: (yield 5) = 6
    print('hi')
y = foo()
y.send(None)
y.send(int)
night quarryBOT
#

@steep mural :x: Your eval job has completed with return code 1.

001 | hi
002 | Traceback (most recent call last):
003 |   File "<string>", line 5, in <module>
004 | StopIteration
steep mural
#

!e

def foo():
    x: (yield) = 6
    print('hi')
y = foo()
y.send(int)
y.send(int)
night quarryBOT
#

@steep mural :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 | TypeError: can't send non-None value to a just-started generator
steep mural
#

!e

def foo():
    yield
    x: (yield) = 6
    print('hi')
y = foo()
y.send(None)
y.send(int)
night quarryBOT
#

@steep mural :x: Your eval job has completed with return code 1.

001 | hi
002 | Traceback (most recent call last):
003 |   File "<string>", line 7, in <module>
004 | StopIteration
steep mural
#

i thought i was in bot commands pithink but yeah very weird

formal sandal
#

!e

def f():
    x: (yield from f()) = None
    return None

print([*f()])
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

[]
formal sandal
#

hmm

#

!e

def f():
    yield 1
    x: (yield from f()) = None
    return None

print([*f()])
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

[1]
formal sandal
#

hold up

#

!e

import sys
print(sys.version)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

001 | 3.9.1 (default, Dec 11 2020, 14:22:09) 
002 | [GCC 8.3.0]
formal sandal
#

🤔

steep mural
#

i guess it doesn't do anything because annotations are strings now? but it still makes a generator LemmeThinkAboutThat

sick hound
#

!e

print(os.name)```
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

posix
sick hound
#

!e py import os os.system("sh")

night quarryBOT
#

@sick hound :warning: Your eval job has completed with return code 0.

[No output]
sick hound
#

!e py import subprocess print(subprocess.check_output("ping -c3 google.com").decode().rstrip())

night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 |   File "/usr/local/lib/python3.9/subprocess.py", line 420, in check_output
004 |     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
005 |   File "/usr/local/lib/python3.9/subprocess.py", line 501, in run
006 |     with Popen(*popenargs, **kwargs) as process:
007 |   File "/usr/local/lib/python3.9/subprocess.py", line 947, in __init__
008 |     self._execute_child(args, executable, preexec_fn, close_fds,
009 |   File "/usr/local/lib/python3.9/subprocess.py", line 1752, in _execute_child
010 |     self.pid = _posixsubprocess.fork_exec(
011 | BlockingIOError: [Errno 11] Resource temporarily unavailable
twilit grotto
#

no internet access

floral meteor
#

Aww

sick hound
floral meteor
#

Yeah

sick hound
#

or does it run these commands in a container

floral meteor
#

Snek

twilit grotto
#

discord bot doesn't run in snekbox lol @sick hound

sick hound
#

it's foolproof

floral meteor
#

I almost stepped on a snake today lol

#

Snek

floral meteor
#

!e print(....name[0,1,4])

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 | AttributeError: 'ellipsis' object has no attribute '__name__'
formal sandal
distant wave
#

!e print(....class.name[0:4])

night quarryBOT
#

@distant wave :white_check_mark: Your eval job has completed with return code 0.

elli
formal sandal
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

elli
floral meteor
#

!e ```py
=()==();=print;=[];=str
+=[
(...)[-,-~-~,-
,
-~
,~~
],
(...>[])[~~,-(-~)]
]
__([
[-],*___[]])

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | TypeError: string indices must be integers
floral meteor
#

!e ```py
=()==();=print;=[];=str
+=[
(...)[-,-~-~,-
,
-~
,~~
],
(...>[])[~~,-(-~)]
]
__([
[-],*___[]])

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | TypeError: string indices must be integers
floral meteor
#

Bruh

#

!e ```py
=()==();=print;=[];____=str
___+=[
__(...)[-],
__(...)[-~-~],
___(...)[-],
__(...)[-~],
___(...)[~~],
_(...>[])[~~],
(...>[])[-(-~)]
]
__(*
)

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 | TypeError: '>' not supported between instances of 'ellipsis' and 'list'
grizzled cloak
#

and then converted to a string?

slim echo
#

Challenge: Escape (not kill)/rebuild your shell

import builtins
_del = delattr
_imp = __import__
for i in dir(builtins):
    _del(builtins,i)

del _del
sys = _imp('sys')
sys.meta_path.clear()
sys.modules.clear()
del _imp
del sys

@rugged sparrow claims to know how to do it by navigating subclasses of object: ().__class__.__base__

#

(@elfin onyx)

elfin onyx
#

thx for calling me as well,
even though idk

slim echo
#

You did ask lol

elfin onyx
#

shh

slim echo
#

So we want to get back open and stdout or stderr

#

So far I don't see what we can do for that though

rugged sparrow
#
repr = lambda o:f'{o!r}'
type = ().__class__.__class__
object = ().__class__.__base__
def get_cls(name, base=object):
  if repr(base).split("'")[1] == name:
    return base
  for cls in type(base).__subclasses__(base):
    if ret := get_cls(name, cls):
      return ret```
#

this can be used to get any already imported class by name

slim echo
#

You really are rebuilding the shell lmao

#

Presumably you can restore str by taking ''.__class__ and int by 0 .__class__, etc

elfin onyx