#esoteric-python

1 messages · Page 154 of 1

quartz wave
#
c=a.split(a[-4:][:1])[0];c=c.lower()[::-1]
                                    ^^^^^^
``` also reverse a one-character string??
pastel sparrow
#

i mean- there's literally two loops that aren't needed here: ```py
for x in[1]]for x in[1]]

quartz wave
#

there's an assignment in the d function that doesn't get used: ```py
d=[];...;d=c.split('#')

pastel sparrow
#

this is more of an unobfuscation exercise than a golfing one

quartz wave
#

this obfuscated code makes me annoyed

floral meteor
#

I'll actually test this after a coffee ```py
CLASSIFIED_STATE_SECRETS = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."

def gen(s:int,k:int):a=map(int,str(s)),;return bytes(sum(map(lambda n,i:n**k+nk**i+ni,a,range(len(a)))))
def encode(normal_brainfuck:str):from random import randint;x=[normal_brainfuck];return int([{a:b for a,b in zip('+-<>.,[]',range(2,10))}.get(k,randint(0,1))for _ in iter(lambda:x,[])if randint(0,5)for k in[x.pop(0)]])
def decode(code:int):
c=str(code);p=t=i=0;o='';a=import('collections').defaultdict(int)
def add(i):a[i]+=1;a[i]%=256;return i,0
def sub(i):a[i]-=1;a[i]%=256;return i,0
def lft(i):return i-1,0
def rit(i):return i+1,0
def dot(i):return print(end=a[i],flush=1)or i,0
def com(i):a[i]=ord(import('sys').stdin.read(1));return i,0
def lop(i):return i,+(not a[i])
def end(i):return i,a[i]and-1
while 0<=p<len(c):i,t={x:y for x,y in zip(map(str,range(2,10)),(add,sub,lft,rit,dot,com,lop,end))}.get(c[p],lambda i:(i,0))(i)if t else(i,{'[':t+1,']':t-1}.get(c[p],t);p+=1-2
t.lt(0))
return+(not p)
def encrypt(code:int,s:int,k:int=99899):#default k given as example
o=[];from random import randint;l=len(key:=gen(s,k=k));
for c in str(code):
i=randint(0,l)
while key[i]!=int(c):i-=1
o+=[i]
return
o,
def decrypt(array,s:int,k:int=99899):key=gen(s,k=k);return int(''.join([str(key[i])for i in array]))

tests

mess = encrypt(encode(CLASSIFIED_STATE_SECRETS), 334456)
del CLASSIFIED_STATE_SECRETS
print(mess) # long confusing list of chonky integers
decode(decrypt(mess,334456,k=99899)) # hello world!
decode(decrypt(mess,546523,k=99899)) # ?
decode(decrypt(mess,334456,k=72746)) # ?

bold root
#

what the hell

#

!e
a=b=1;exec('print(a);a,b=a+b,a;'*30)

night quarryBOT
bold root
#

does it start with 0,1,1?

vestal solstice
#

yes

quartz wave
#

!e has bug i'll fix later ```py
import math
from random import*
o,r,m=ord,chr,choice
j,µ='ghijklmno',''.join
y=lambda n,l:[n,n-n//l*l or l][n>l]
z=lambda p,a:[r(Random(o(c)678).randint(457,875))for c in(pa)[:a]]
h=lambda d,c,:(o(d[]),o(c[y(+1,len(c))-1]),o(c[-1]))
def e(d,c):b=z(c,7);return µ(hex(o(i))[2:]+m(j)for i in µ(f'{x}{m(b)if random()>0.5else""}'for x in[r(sum(h(d,c,
)))for _ in range(len(d))])).upper()[::-1][1:]+m('PQRSTUV')+f"{randint(137,975)}"
def d(a,b):
c=a[:a.find(a[-4])].lower();f=z(b,7)
for x in j:c=c.replace(x,'#')
g=[x for i in c.split('#')if(x:=r(int(i,16)))not in f];return µ(r((l:=h(g,b,_))[0]-l[1]-l[2])for _ in range(len(g)))
encrypted = e('https://github.com/3xq', 'komt#0005')
print(encrypted)
decrypted = d(encrypted, 'komt#0005')
print(decrypted)

night quarryBOT
#

@quartz wave :x: Your eval job has completed with return code 1.

001 | FE1HA11KA11IFE1H7DHFCHB02O7DG303N4DG8CK39GABJE11L8D2GA01G811G901M4D1O1DM303K49L49LB02IF9HBCH463M911L611LFE1I811N463K801P554
002 | Traceback (most recent call last):
003 |   File "<string>", line 15, in <module>
004 |   File "<string>", line 12, in d
005 |   File "<string>", line 12, in <genexpr>
006 | ValueError: chr() arg not in range(0x110000)
quartz wave
floral meteor
#

!e a=b=1;exec('print(b);a,b=a+b,a;'*30)

night quarryBOT
bold root
floral meteor
#

don't tell me 0 is needed

bold root
#

i tried to do a=b=a+b

#

didnt get what i expected

floral meteor
#

lol

bold root
floral meteor
#

!e print(0);a=b=1;exec('print(b);a,b=a+b,a;'*30)

night quarryBOT
bold root
#

needs to be 36 chars

#
a=0;b=1;exec('print(a);a,b=a+b,a;'*31)

this is where we are at right now

severe canyon
#

Switch to python2 and remove the parenthesis

bold root
#

python 3.8

pastel sparrow
sick hound
#

but i already found a way to make that smaller yes

#
c=a[:-4].lower()[::-1]```
#

komt#0005 is my main discord but im at the 200 server limit so i had to use my alt to post my code

#

feel free to mess around with the uncompressed source

#

:^)

sick hound
#

unless i am mistaken in some other way?

sick hound
#

sorry for all the pings if i replied to your message, i forgot to turn off mentioning

severe canyon
#

This works no?

cosmic path
#

When i saw the name of the channel, i thought i was ready to see what is in it... I now want to learn brainf*ck

pastel sparrow
limpid frost
cosmic path
#

Welp, yeh its useless

sick hound
#

😓

sick hound
pastel sparrow
#

blobsip gonna take a break from golfing for today

#

it was more of unobfuscation but whatever

languid hare
#

hm found something unexpected while reading through docs, apparently yield is an expression, unlike return, which is a statement

#

!e

def f():
  x = yield 1
  yield x

print(*f())
night quarryBOT
#

@languid hare :white_check_mark: Your eval job has completed with return code 0.

1 None
languid hare
#

not too sure what the applications of this could be

wheat river
#

thats intresting

bold root
#

a,b=a+b,a

#

how do i simply

a,b=a+b,a
languid hare
bold root
#

simplify

#

sorry

languid hare
#

i'd think that's as good as it gets

proper vault
#

Giving you coroutines

wheat river
#

doesn't yield something return None?

languid hare
#

hmm neat

#

!e

def f():
  x = yield 1
  yield x

gen = f()
print(next(gen))
gen.send("hello!")
print(next(gen))
night quarryBOT
#

@languid hare :x: Your eval job has completed with return code 1.

001 | 1
002 | Traceback (most recent call last):
003 |   File "<string>", line 8, in <module>
004 | StopIteration
languid hare
#

hmm wait

#

ah i see

#

so send acts like next, but also lets the yield evaluate to something

#

!e

def f():
  x = yield 1
  yield x

gen = f()
print(gen.send(None))
print(gen.send("hi!"))
night quarryBOT
#

@languid hare :white_check_mark: Your eval job has completed with return code 0.

001 | 1
002 | hi!
bold root
#

@languid hare how would u shorten this

a=0;b=1;exec('print(a);a,b=a+b,a;'*31)
languid hare
#

i dont see a direct way to shorten it other than to change to py 2, where exec is a statement

brazen geyser
#

https://docs.python.org/3.12/whatsnew/3.12.html

Currently Python accepts numeric literals immediately followed by keywords, for example 0in x, 1or x, 0if 1else 2. It allows confusing and ambiguous expressions like [0x1for x in y] (which can be interpreted as [0x1 for x in y] or [0x1f or x in y]). A syntax warning is raised if the numeric literal is immediately followed by one of keywords and, else, for, if, in, is and or. In a future release it will be changed to a syntax error. (gh-87999)

pour one out for the golfers

hard tangle
#

in this case, would combo_string be considered a tuple? Also how can you solve this problem using .sort?

restive void
hard tangle
#

thanks n sorry

hoary wedge
sick hound
#

what can i use instead of exec, are there any builtins that do similar except from eval?

hoary wedge
#

It should I think?

bold root
#

it doesnt

hoary wedge
#

Whats the error?

#

!e py a=0;b=1;exec('print(a)a,b=a+b,a'*31)  

bold root
#

apparently the solution has something to do with a=b=...

#

and i really have no clue

hoary wedge
#

hm

#

!e
a,b=0,1;exec('print(a);a,b=a+b,a;'*31)

hoary wedge
#

Except for to many lines but y'know

bold root
#

that didnt shave of anything

bold root
#

im about to lose it

hoary wedge
#

Oh wait your right

#

I misscounted

worldly trail
bold root
worldly trail
night quarryBOT
#
Missing required argument

code

bold root
#

!e
a=0;b=1;exec('print(a);a,b=a+b,a;'*31)

night quarryBOT
bold root
#

fib sequence

#

we are trying to shorten it to 36 chars or less

hoary wedge
#

less*

bold root
#

sorry

next flame
#

does it have to start with 0

#

either way you can drop the trailing semicolon in the string

#

for 37

bold root
mystic sigil
#

hello, I had some confusion with decorators:

#

why do we need a wrapper function inside be_polite (first image)? can't we just return be_polite (second image)?

#

when I run the code in the second image, I am getting an error that says TypeError: be_polite() missing 1 required positional argument: 'fn'

wheat river
#
def decorator(function):
    # the decorator takes a function then we have an 
    # inner function which takes the params for the `function`.
    def inner(*args, **kwargs):
        # these *args **kwargs are the args that have to be passed in `function`
        ...
        return function(*args, **kwargs)
    return inner 

@decorator
def foo():
    ...
# is the same as
def foo():
    ...
foo = decorator(foo)

# --------------------------
# when u call foo, what basically happens is
# decorator(foo)(...)
# because decorator return inner the function call is
# inner(...)
wheat river
#

!e

def deco(fn):
    print('inside decorator')
    return fn

@deco
def foo():
    print('inside foo')

foo()
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

001 | inside decorator
002 | inside foo
wheat river
#

if you want to ask questions about python open a help channel ( #❓|how-to-get-help ) or look for a topic channel which fits that topic
this channel has a different purpose

mystic sigil
#

oh okay thank you

quartz wave
quartz wave
# sick hound ```python c=a[:-4].lower()[::-1]```

!e forgot the [::-1] which caused a bug in my code
@pastel sparrow thanks for the tip ```py
import math
from random import*
o,r,m=ord,chr,choice
j,µ='ghijklmno',''.join
y=lambda n,l:n%l or l
z=lambda p,a:[r(Random(o(c)678).randint(457,875))for c in(pa)[:a]]
h=lambda d,c,:(o(d[]),o(c[y(+1,len(c))-1]),o(c[-1]))
def e(d,c):b=z(c,7);return µ(hex(o(i))[2:]+m(j)for i in µ(f'{x}{m(b)if random()>0.5else""}'for x in[r(sum(h(d,c,
)))for _ in range(len(d))])).upper()[::-1][1:]+m('PQRSTUV')+f"{randint(137,975)}"
def d(a,b):
c=a[:a.find(a[-4])].lower()[::-1];f=z(b,7)
for x in j:c=c.replace(x,'#')
g=[x for i in c.split('#')if(x:=r(int(i,16)))not in f];return µ(r((l:=h(g,b,_))[0]-l[1]-l[2])for _ in range(len(g)))

exec("print(en:=e('https://github.com/3xq', 'komt#0005'), d(en, 'komt#0005'));"*5)

night quarryBOT
#

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

001 | A11LB02HA11L303O7DM8D2MFCN4D1M7DH4D1I4DO463N8CI303K39G4D1HABJ303IE11L4D1HA01I811J4D1J901O463I1DG49M49LF9JBCH911M611O811L303H801T844 https://github.com/3xq
002 | 4D1GA11MA11O7DH8D2IFCM463O7DJ4D1O4DH463N8CO39OFE1IABIE11O4D1MA01OFE1M811H901M463O1DM49O49JF9NBCL911G611NB02M811N801P723 https://github.com/3xq
003 | 4D1MA11JA11M303H7DHFCO7DNFE1L4DGFE1O8CM39MABK4D1IE11MA01N811H901H4D1J1DN49H49N303MF9IBCN303J911M611K4D1M811L8D2H801U465 https://github.com/3xq
004 | A11K463GA11N4D1M7DIFCM4D1O7DG4DOB02H8CN39OABL4D1GE11G463JA01I4D1H811JB02N901J1DH49J49O303OF9OFE1NBCM911J611O811G8D2M801V315 https://github.com/3xq
005 | A11K8D2IA11J463K7DNFCH7DJB02G4DK8CH39GABN8D2OE11K4D1GA01N811J463O901I303H1DL49K463I49G463HF9JBCLB02H911H611MFE1G811NFE1G801V484 https://github.com/3xq
sick hound
#

im not too big on minifying code so i tried my best atleast

versed eagle
#

it would run slow as heck lmao

#

oop meant to reply to this one

#

yeah it would be awesome though

old socket
#

Would be really hard though, I remember needing to disable the standard library with rust to make a simple kernel, and with C I had to not use any of the standard library (following some guides) would python even be able to emulate VGA without that?

grave cedar
#

35 chars in python 2.

a=0;b=1
exec'print a;a,b=a+b,a;'*31

I can't get below 38 in python 3. =/

a=0;b=1
exec('print(a);a,b=a+b,a;'*31)

https://code.golf/fibonacci#python

39 chars with a while loop:

a,b=0,1
while b<9**6:print(a);a,b=a+b,a
#

Are you sure this hint works in the version they're using now? Does the key lie in using xor? I'm out of ideas on this I'm afraid. I feel like this is either you know the trick or you don't, and it's not the sort of thing you figure out.

vestal solstice
#

it's not esoteric at all

#

it works in the current version

#

i mean you can see me on the leaderboard, it doesn't keep solutions that only worked in the past

severe canyon
#

this is the only thing I can think of, using the hint

a=b=1
exec('print(a-b);a,b=a+b,a;'*31)
#

Can get to 36, but then the sequence starts at 1 1 and not 0 1 ://

fleet bridge
#

a=b=1;exec('print(a);a,b=a+b,a;'*29) - this is 36, but it starts with 1 2

grave cedar
# vestal solstice it's not esoteric at all

tbf, the whole exec*number is pretty esoteric to begin with. But I'm not seeing how to make it shorter any other way. But glad to know that there is a current valid solution.

#

ok, I got down to 37.

#

ok, I got it to 36

wheat river
grave cedar
wheat river
#

oh, thanks

quartz wave
grave cedar
vague cairn
#

I failed at golf, but I had fun with this one:

from fishhook import *
@hook(list)
def __iadd__(s,o):return [v+(o if i else 0) for i,v in enumerate(s) ]
@hook(list)
def p(s):
 print((r:=s.pop(0)))
 return r

a=[0]+[1]*30
while a:a+=a.p()```

I kind of want the last statement line to read `a[1:]+=a.p()` but that requires an entire new listview class which I don't feel like implementing already.
quartz wave
vague cairn
#

nice

#

fixed

floral meteor
languid hare
floral meteor
#

a mild refactor ```py
from fishhook import*;hook(list,'iadd')(lambda s,i:[v+(u and i)for u,v in enumerate(s)]);hook(list,'k')(lambda k:print(r:=k.pop(0))or r);o=[0]+[1]*30
for _ in o[1:]:o+=o.k()

#

okay that wasn't as easy as i thought it was going to be

#

!e ```py
from ctypes import*
obase = py_object.from_address(id('2')+8)
class Magic(str):
def add(self, other):return class(int(self)+int(other))
obase.value = Magic
print( '2' + '20' )

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).

220
wheat river
#

!e

from fishhook import hook, orig
@hook(str)
def __add__(self, other):
    try:
        out = str(int(self) + int(other))
        return out
    except ValueError:
        return orig(self, other)

print('1' + '101')
print('a' + 'b')
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

001 | 1101
002 | ab
wheat river
#

bruh

floral meteor
#

still didn't work

#

looks like it's time for last resort: unreversable damage

wheat river
#

thats the problem sadge 😔

floral meteor
#

I'm not sure I can work around that... unless...

#

eh, unreversable damage it is then

languid hare
#

!e

import dis
dis.dis("1" + "2" * 1)
night quarryBOT
#

@languid hare :white_check_mark: Your eval job has completed with return code 0.

001 |   1           0 LOAD_CONST               0 (12)
002 |               2 RETURN_VALUE
languid hare
#

bested again

wheat river
#

woah

floral meteor
#

python cannot defeat meeeeeee

#

wait I put the \0 on the wrong side

#

!e ```py
from ctypes import c_char
cbase = (c_char*3).from_address(id('220')+48)
cbase.value = b'22\0'
print('2'+'20')

night quarryBOT
#

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

22�
floral meteor
#

that looks better

wheat river
#

ur manually rerouting 220 str literal right?

floral meteor
#

yep, probably deleting '220' itself in the process

floral meteor
#

!e ```py
from ctypes import c_char
cbase = (c_char52).from_address(id('220'))
backup = cbase,
obase = (
(c_char
51).from_address(id('22')),)+(b'\0',)
cbase.value = b''.join(obase)
print('2'+'20')
cbase.value = b''.join(backup)

night quarryBOT
#

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

22
floral meteor
#

I can just temporarily replace '220' with '22' when it suits me.

wheat river
#

ic

floral meteor
#

the previous one still had a trailing NUL character

#

this one also overrode object size I couldn't quite figure out which part of memory was the 52 that i was looking for so I just patched the whole number

languid hare
#

!e

import dis
dis.dis("1" + "2" * (1-1))
night quarryBOT
#

@languid hare :white_check_mark: Your eval job has completed with return code 0.

001 |   1           0 LOAD_CONST               0 (1)
002 |               2 RETURN_VALUE
languid hare
#

a

#

i wonder what the preprocessing limit is

floral meteor
#

!e ```py
import dis
def f():
'1'+('1'+('1'+('1'+'1')))*(1-----------1)*0
dis.dis(f)

night quarryBOT
#

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

001 |   3           0 LOAD_CONST               1 ('1')
002 |               2 POP_TOP
003 |               4 LOAD_CONST               0 (None)
004 |               6 RETURN_VALUE
languid hare
#

!e

import dis
dis.dis("(lambda: '1')()")
night quarryBOT
#

@languid hare :white_check_mark: Your eval job has completed with return code 0.

001 |   1           0 LOAD_CONST               0 (<code object <lambda> at 0x7f27f9d9d420, file "<dis>", line 1>)
002 |               2 LOAD_CONST               1 ('<lambda>')
003 |               4 MAKE_FUNCTION            0
004 |               6 CALL_FUNCTION            0
005 |               8 RETURN_VALUE
006 | 
007 | Disassembly of <code object <lambda> at 0x7f27f9d9d420, file "<dis>", line 1>:
008 |   1           0 LOAD_CONST               1 ('1')
009 |               2 RETURN_VALUE
floral meteor
#

!e ```py
import dis
dis.dis("(lambda: '1'+('1'+('1'+('1'+'1')))*(1-----------1)*0)()")

night quarryBOT
#

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

001 |   1           0 LOAD_CONST               0 (<code object <lambda> at 0x7f086ee2d420, file "<dis>", line 1>)
002 |               2 LOAD_CONST               1 ('<lambda>')
003 |               4 MAKE_FUNCTION            0
004 |               6 CALL_FUNCTION            0
005 |               8 RETURN_VALUE
006 | 
007 | Disassembly of <code object <lambda> at 0x7f086ee2d420, file "<dis>", line 1>:
008 |   1           0 LOAD_CONST               1 ('1')
009 |               2 RETURN_VALUE
floral meteor
#

brehhhhh

languid hare
#

!e

import dis
dis.dis("'1' * (not 0)")
night quarryBOT
#

@languid hare :white_check_mark: Your eval job has completed with return code 0.

001 |   1           0 LOAD_CONST               0 ('1')
002 |               2 RETURN_VALUE
languid hare
#

really

floral meteor
#

compiler doing half the mathematical work

#

!e ```py
import dis
dis.dis("256**256+1")

night quarryBOT
#

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

001 |   1           0 LOAD_CONST               0 (256)
002 |               2 LOAD_CONST               0 (256)
003 |               4 BINARY_POWER
004 |               6 LOAD_CONST               1 (1)
005 |               8 BINARY_ADD
006 |              10 RETURN_VALUE
floral meteor
#

aha

#

I have defeated it

languid hare
#

hmm

#

so there is a limit

floral meteor
#

it is strong, but it is not immortal

quartz wave
floral meteor
#

u and i is just not meant to be...

#

!e import('ctypes').c_int.from_address(id(4)+int.basicsize).value=5
print(f"{2+2=}")

night quarryBOT
#

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

2+2=5
quartz wave
wheat river
#

ya

floral meteor
#

what if I used 100% of my cpu?

quartz wave
#

that's where the limits are defined

#

15**32 is the (integer) power operation with the biggest result that is still optimized out
no numbers are bigger than that

#

a string of length 4096 is the largest possible result of string multiplication

pastel sparrow
#

reminds me of the lazy calculator implementation i did with compile

#

i just compiled user input and grabbed the first constant

#

no wonder it failed with large inputs

split violet
#

!e

import this
print('something')
night quarryBOT
#

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

001 | The Zen of Python, by Tim Peters
002 | 
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/giboqelura.txt?noredirect

finite blaze
#

Hey, I am trying to solve one ctf but i need some help.
So i need to write a code that will output whats inside flag file. This code will be later compiled using ast and it wont run if compiled code containst ast.Import/ast.ImportFrom/ast.Call

#

any ideas how to obfuscate code so it wont include any call "nodes" (not sure whats a good word for it)

#

i tried [e for e in list(open('flag'))]

#

cuz [1,2] worked

#

so i thought that list comprehensions would work

fleet bridge
#

!e ```py
@print
@lambda x: x.name
class HelloWorld: ...

night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

HelloWorld
fleet bridge
#

!e ```py
@import
@lambda x: x.name
class sys: ...

print(sys)

night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

<module 'sys' (built-in)>
earnest wing
#

!e ```py
import dis
dis.dis("""@import
@lambda x: x.name
class sys: ...""")

night quarryBOT
#

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

001 |   1           0 LOAD_NAME                0 (__import__)
002 | 
003 |   2           2 LOAD_CONST               0 (<code object <lambda> at 0x7f690b0f1420, file "<dis>", line 2>)
004 |               4 LOAD_CONST               1 ('<lambda>')
005 |               6 MAKE_FUNCTION            0
006 | 
007 |   3           8 LOAD_BUILD_CLASS
008 |              10 LOAD_CONST               2 (<code object sys at 0x7f690b0f14d0, file "<dis>", line 1>)
009 |              12 LOAD_CONST               3 ('sys')
010 |              14 MAKE_FUNCTION            0
011 |              16 LOAD_CONST               3 ('sys')
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/iduricorow.txt?noredirect

earnest wing
#

no call_function :>

finite blaze
#

but it uses import

#

cant use Import/ImportFrom/Call

stark fable
#

it doesn't use import, it uses __import__, which in the ast is just a name

finite blaze
#

okay okay

#

let me try that

#

okay, it executed

restive void
#

!e

@eval
@lambda x: x.x
class x:
 x = "print('Hello World')"
night quarryBOT
#

@restive void :white_check_mark: Your eval job has completed with return code 0.

Hello World
restive void
#

Then just put your code inside that string

finite blaze
#

thanks!

floral meteor
#

!e ```py
@print
@lambda x:"Hello World!"
class _:0

night quarryBOT
#

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

Hello World!
floral meteor
#

No import, no brackets, no eval, no shenanigans

floral meteor
#

I made green matrix rain with multiprocessing so that i can use more than one core of the cpu. No threading cos threads suck in python.

#

It needs two files though because pickles.

floral meteor
#

here's a snapshot.
However in development it was rather unstable, it has to be keyboard interrupted before it is closed else you get infinite error msgboxes with [ok] button

#

"Program did not start correctly, press ok to close the program" [OK]
but it's infinite.

#

you have to individually terminate all the children processes, and even then, you still have to close or ok the boxes

burnt pasture
#
>>> @print
... @str.upper
... @lambda c: c.__doc__
... class Whatever:
...     """Hello, world!"""
HELLO, WORLD!
rugged sparrow
#

!e ```py
@print
@vars(type)["doc"].get
class _:"Hello Word!"

night quarryBOT
#

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

Hello Word!
burnt pasture
#
@print
@str.title
@lambda cls: cls.__doc__
class _:
    """hello, world!"""

Hello, World!

restive void
#

I've been trying for a while to get the original challenge of "print the contents of a file" (without eval) working, but I'm stuck at finding something that calls its first argument without parameters.

restive void
#
@print
@lambda x:x.read
@open
@lambda x:"flag"
class _:0

After the @print I need something that calls the current callable.

wheat river
#

this looks cool

restive void
#

See above, original challenge by @finite blaze yesterday

wheat river
#

why can't you call read directly?

restive void
#

Basically the AST isn't allowed to contain a Call node

wheat river
#

oh wait, i didnt read the whole thing, mb

restive void
#
@print
@print.__class__.__call__
@lambda x:x.read
@open
@lambda x:"flag"
class _:0

Yes, was struggling with that for a while. This works.

wheat river
#

woah

true narwhal
#

!e
import this
print('something')

night quarryBOT
#

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

001 | The Zen of Python, by Tim Peters
002 | 
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/acebacoxos.txt?noredirect

true narwhal
#

WTF

split salmon
#

!e py print(round((type|type.__class__)(type).__or__(type(7),type(69)).__sub__(21,90).__mul__(-1000).__divmod__(3)[0]*3+1/54.76190476190476*(type|type.__class__)(type).__or__(type(7),type(69)).__sub__(21,90).__mul__(-1000).__divmod__(3)[0]))

night quarryBOT
#

@split salmon :white_check_mark: Your eval job has completed with return code 0.

69420
forest beacon
#

!e
import this

night quarryBOT
#

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

001 | The Zen of Python, by Tim Peters
002 | 
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/wugajuhuya.txt?noredirect

burnt pasture
#

I want to tweet this, who should I give credit to?

@print
@str.title
@lambda cls: cls.__doc__
class _:
    """hello, world!"""
#

(I adapted it from other examples here)

golden finch
#

that's been around for longer than just the last few days; I saw something similar on the esolangs discord a few months ago

#

!e

#from esolangs Discord
@print
@str.title
@lambda _:"hello, world!"
class _:0
night quarryBOT
#

@golden finch :white_check_mark: Your eval job has completed with return code 0.

Hello, World!
icy frigate
#

What does the 0 do?

burnt pasture
floral meteor
#

pass is redundant cos you can just 0 for the same effect.

#

or the cuter ...

#

!e noops can be made from anything, really. ```py
*map(....eq,map(str,iter(lambda:print('Hello, World!'),None))),

night quarryBOT
#

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

Hello, World!
finite blaze
#

also, thins after @ like @print, @str.title, what are they called?

floral meteor
#

the whole line is called a decorator

finite blaze
#

thanks

#

fun challange

finite blaze
#

isnt iter a call?

floral meteor
#

it's got a lot of calls

#

it's just... cursed

finite blaze
#

oh yeah it is 😄

floral meteor
#

I'm mapping no-ops against a delayed instruction

#

!e ```py
def f(n=[4]):
print(n[0])
n[0]-=1
return n[0]

o = map(str,iter(f,0))
print(5)
*o,

night quarryBOT
#

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

001 | 5
002 | 4
003 | 3
004 | 2
005 | 1
finite blaze
#

*o,, whats this , doing here?

floral meteor
#

to prevent starred expression can't be used here

#

if there's a trailing comma, then the expression is implicitly in a 1-tuple

#

brackets are optional if there's no need for precedence

#

!e that includes tuple construction, hence

a = (0,)
b = 0,
print(a, b, a==b)
night quarryBOT
#

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

(0,) (0,) True
restive void
#

That's beautiful, have never seen the *o, thing to exhaust the iterable.

floral meteor
#

I use it often.

#

looks like magical sparkles

restive void
#

Do you have a name for this "operator"?

floral meteor
#

tuple(varname)

finite blaze
#

*o, looks like a cheerleader

restive void
#

It reminds me of the pistol-operator for unpacking a one-element iterable (,=)

finite blaze
floral meteor
#

*_, is how I most often use it.

finite blaze
#

headless cheerleader

floral meteor
#

a1 = *map(f,a0),

#

alternatively, I could "reverse times-equals with trailing comma"
a1 =* map(f,a0),

#

just to be subtly confusing

restive void
#

a ,=* map(f, b),

floral meteor
#

b would have to have a length of 1

restive void
#

Yes

floral meteor
#

so a ,=* map(f, [b]),

finite blaze
#

a ,= *o, < pistol operator killing a cheerleader operator

floral meteor
#

FBI,= *o,

#

FBI, open up!

#

the cheerleader has a weapon!

#

!e if you really wanna do cheerleaders

W, I, L, D, C, A, T, S = 'WILDCATS'
name = *W, *I, *L, *D, *C, *A, *T, *S, '!'
print("What is our name?", ''.join(name))
night quarryBOT
#

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

What is our name? WILDCATS!
floral meteor
#

sometimes they have the letters of their team name on their shirt.

finite blaze
#

haha, perfect ❤️

finite blaze
#

I guess cuz we are using decorators

#

And we need to modify something?

restive void
wheat river
#

is there a way to use def to define a function without ()

#

like def foo instead of def foo()

royal whale
#

no.

wheat river
#

rip

finite blaze
#

Back to my challenge

#

sys.stdout.flush=sys.breakpointhook

#

That's short!

finite blaze
#
@exec
@input
class X:0
finite blaze
#
class X():
  def __init__(self, a, b, c, d, e):
    self += "print(open('flag').read())"
  __iadd__ = eval
__builtins__.__import__ = X
finite blaze
#

I've been playing with somethine like this

f"""{"exec('print(1)')"}"""
#

but can't get this to work

restive void
#

!e like that?

f"""{exec("print(1)")}"""
night quarryBOT
#

@restive void :white_check_mark: Your eval job has completed with return code 0.

1
finite blaze
#

yeah

#

but i guess it will be detected as a call

finite blaze
wheat river
#

!e

@exec
@lambda x:print.__name__ + f'({x.__doc__!r})'
class _:
    'hello world'
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

hello world
finite blaze
#
os.environ.__class__.__contains__ = os.system
'cat flag' in os.environ 
grave rover
#

has anyone figured out extending generics yet? e.g. List[T] and ImmutableList[T] extending List[T]
If you add Generic[T] and List[T] as children, pycharm won't use the type passed to the child class as the parent class type
If you just extend the raw class (i.e. List instead of List[T]) it complains ImmutableList isn't a generic class...

drowsy cobalt
#

Check this shiz out

#
zip(* [iter(seq)] * n)
#

is a funky way to chunk seq into n-size chunks

languid hare
#

i

#

cant tell if that works on first glace

#

love it

drowsy cobalt
#

!e ```py
bytes_ = [5, 2, 4, 3, 4, 5, 6, 63, 2, 1, 23, 3, 54, 3, 2, 3]
print(list(zip(* [iter(bytes_)] * 8)))

night quarryBOT
#

@drowsy cobalt :white_check_mark: Your eval job has completed with return code 0.

[(5, 2, 4, 3, 4, 5, 6, 63), (2, 1, 23, 3, 54, 3, 2, 3)]
drowsy cobalt
#

It's specifically using the fact that [item] * n will duplicate the item reference n times, you know, that thing you usually tell beginners they have to avoid

languid hare
#

aha

drowsy cobalt
#

so that the n duplicates of the iterator get used as one each time as zip tries to fill out each chunk

languid hare
#

that is very funky

zinc scaffold
#

Hi, is this a good forum to ask questions on django too ?

drowsy cobalt
languid hare
drowsy cobalt
earnest wing
#

(it's the *w* operator indexed by iter(s), duh)

drowsy cobalt
#

i guess that's quite similar

earnest wing
#

It's not the same without the *w* blobcry

sudden osprey
drowsy cobalt
#

heh, cool

maiden blaze
#

pithink are some of those recipes new

#

dont remember seeing the dotproduct or convolve before

royal whale
lucid current
#

iter accepts a callable and sentinel value

royal whale
lucid current
#

The slice type is for sequence getitem

#

slice(1,10,5) == [1:10:5]

royal whale
lucid current
#
sliceobj = slice(1,10,5)
assert sequence[slice] == sequence[1:10:5] # returns True
lucid current
lucid current
dry mirage
#

!e

eval((lambda:0).__code__.replace(co_code=b't\x00\x82\x01', co_names=([*__builtins__.__dict__][87],)))

raise ValueError
night quarryBOT
#

@dry mirage :warning: Your eval job has completed with return code 0.

[No output]
sick hound
#

bro what is this channel

royal whale
humble rune
quartz wave
night quarryBOT
#

@quartz wave :warning: Your eval job has completed with return code 0.

[No output]
quartz wave
#

hmm

dry mirage
#

:)

quartz wave
#

if you use t in the REPL it doesn't do anything but e does

dry mirage
#

super cryptic version of exit(0)

quartz wave
dry mirage
#

oh really?

quartz wave
#

e raises and t just returns ArithmeticError

dry mirage
#

hm..

#

for me both e and t works in the REPL? pithink

quartz wave
dry mirage
#

3.10.5 yeah

#

I guess the bytecode is different? pithink

quartz wave
dry mirage
#

o.O

#

does the segfault version still work?

quartz wave
#

wait

quartz wave
dry mirage
#

!e

eval((lambda:0).__code__.replace(co_code=b'LOAD_FAST'))
night quarryBOT
#

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

[No output]
dry mirage
#

what does that do for you

quartz wave
#

SystemExit is the 88th element in __builtins__.__dict__ in 3.10 but in 3.11 it's ArithmeticError

dry mirage
#

oh interesting pithink

quartz wave
# dry mirage what does that do for you
>>> eval((lambda:0).__code__.replace(co_code=b'LOAD_FAST'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: code: co_code is malformed
dry mirage
#

oh wat

#

no more hacking cocode for seg faults

#

eval((lambda:0).__code__.replace(co_code=b'1'))?

quartz wave
dry mirage
#

wtf

#

they need to roll that back

#

how else am I gonna run unsafe python

quartz wave
#

i don't have to worry about segfaulting my stuff

quartz wave
dry mirage
#

oh nice

quartz wave
#

ASCII 1 is apparently WITH_EXCEPT_START

dry mirage
#

so 3.11 is still seg-faultable without ctypes

quartz wave
#

b'00' also segfaults it

dry mirage
#

tbh is a language even turing-complete if you can't segfault it

quartz wave
#

according to opcode.opname ASCII 0 is nothing

#

according to dis._all_opname ASCII 0 is LOAD_GLOBAL_BUILTIN

fleet bridge
wheat river
#

!e

class Foo:
    def foo(self):
        return 1
    
a = type('',(Foo,),{'foo':lambda x:super().foo()})
a().foo()

why doesn't this work?

night quarryBOT
#

@wheat river :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 5, in <lambda>
004 | RuntimeError: super(): __class__ cell not found
fleet bridge
#

!e

class X:
    def f(self):
        print(__class__)

X().f()
print(X.f.__closure__)
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

001 | <class '__main__.X'>
002 | (<cell at 0x7fb890b3da20: type object at 0x563756977530>,)
languid hare
#

no argument super only works in a class body

fleet bridge
#

0-arg super use this cell to determine class where your method is defined

languid hare
#

super(a) maybe

floral meteor
#

!e And unsafe python is easy in any 3.x version just

def print(*a):
 try:print(*a)
 except:print("unable to print duhhh")
print("Hello, World!")
wheat river
night quarryBOT
#

@floral meteor :warning: Your eval job timed out or ran out of memory.

[No output]
floral meteor
#

Don't need ctypes or bytecode mutation

wheat river
#

!e

class Foo:
    def foo(self):
        return 1


a = type('a', (Foo,), {'foo': lambda x: print(super(a))})
a().foo()
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

<super: <class 'a'>, NULL>
quartz wave
umbral prism
#

!e Can anyone explain this code ?```py
print([chr(0x48656c6c6f20776f726c642120>>i8&255)for i in range(103//8+1)][::-1],sep="")

night quarryBOT
#

@umbral prism :white_check_mark: Your eval job has completed with return code 0.

Hello world! 
earnest wing
#

!e ```py
n = 0x48656c6c6f20776f726c642120
print(n.to_bytes(13, 'big'))

night quarryBOT
#

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

b'Hello world! '
earnest wing
#

@umbral prism the integer encodes a sequence of bytes which are selected one at a time with the >>

umbral prism
#

oh i see

#

thanks

floral meteor
#

although multiprocessing module can arise some juicy problems that need task manager

solid cairn
#

I've recently got into trying out ASCIIDots, and I now know that there's a package (asciidots) where I can make programs on this language. How do I use Python to make ASCIIDots programs?

versed eagle
#

!e

# fibonacci sequence :D
print((lambda n:([(a:=0, b:=1)] + [(a:=a+b, b:=a+b) for i in range(n//2)])[(n-1 if n%2 == 0 else n)//2][1 if n%2 == 0 else 0])(69))
night quarryBOT
#

@versed eagle :white_check_mark: Your eval job has completed with return code 0.

72723460248141
versed eagle
#

yay

#

fibonacci sequence 1 liner :D

serene stratus
#

someone got it down to 36 chars recently

#
a=0;b=1
exec('print(a);a,b=a+b,a;'*31)```
sick hound
#

a,b=0,1;exec('print(a);a,b=a+b,a;'*31)

finite blaze
#

!e

a,b=0,1;exec('print(a);a,b=a+b,a;'*31)
night quarryBOT
floral meteor
#

aha i gave python a stroke

#

I can't get over python having a stroke 🤣

#

this is what I expect from python properly crashing: confusing red text everywhere and it's too dead to raise a crash flag and just remains in a limbo that cannot be keyboardinterrupted

fleet bridge
#

!e Thue–Morse on stack

n = 5
s: list[int] = []
i1 = s.append
i2 = s.pop
i3 = lambda: [*map(i1, [i2(), i2()])]
s1 = lambda: s[-1]
s2 = lambda: s[-2]
g = lambda: i1(s[-i2()])
p = lambda: (a:=i2(), x:=i2(), s.__setitem__(slice(None),[*s[:-a],x,*s[-a:]]))
r = lambda: i1(1 - i2())
d = lambda: (i1(t:=i2()), i1(t))

i1(0)
i1(n)
i1(1)
while s2():
    i1(0)
    while s1() < s2():
        i3()
        d()
        i1(i2() + 3)
        g()
        r()
        i1(3)
        p()
        i3()
        i1(i2() + 1)
    i2()
    i1(i2() * 2)
    i3()
    i1(i2() - 1)
    i3()
i2()
i2()
print(s)
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

[0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1]
fleet bridge
#

!e not crypted code

n = 5
s: list[int] = []
i1 = s.append
i2 = s.pop
i1(0)
n = 5
ln = 1
while n:
    x = 0
    while x < ln:
        i1(1 - s[-ln])
        x += 1
    ln *= 2
    n -= 1

print(s)
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

[0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1]
floral meteor
#

noice. what is it?

fleet bridge
quartz wave
#

that's why it times out in the python bot

#

does this in an online 3.9 compiler

opaque furnace
#

__add__ vs __iadd__

severe canyon
#
  • vs +=
quartz wave
wide lotus
#

!e

import sys;import time;_,__,___,____=print,sys.stdout,time.sleep,lambda _:''.__getattribute__(f'{chr(106)}{chr(111)}{chr(105)}{chr(110)}')([chr(__) for __ in _]);_____,______,_______=____([102,108,117,115,104]),____([119,114,105,116,101]),____([78,111,32,98,105,116,99,104,101,115,63]);_________=lambda _:[(__.__getattribute__(______)(_________),__.__getattribute__(_____)(),___(1/10)) for _________ in _];_________(_______)
night quarryBOT
#

@wide lotus :white_check_mark: Your eval job has completed with return code 0.

No bitches?
unreal hamlet
#

hello im having trouble to understand pymem here im trying to over write memory on this game but i end up with this error if anyone could explain pymem more for me that would be amazing thanks

the code
import modulefinder
import pymem
from pymem import process
import subprocess
import os
from pymem import Pymem
import keyboard

shortcut = "="
mem =Pymem("GTA5.exe")

#modulefinder.Module("Grand Theft Auto V")
#print(modulefinder.Module("Grand Theft Auto V")) to find the module im not fully sure tho

module = process.module_from_name(mem.process_handle, "GTA5.exe").lpBaseOfDll
offsets = [0x9B8,0x18,0x10,0x18,0x60,0x20]
def GetPointerAddr(base,offsets):
addr = mem.read_int(base)
for offset in offsets:
addr = mem.read_int(addr +offset)
addr = addr + offsets[-1]
return addr

while True:
if keyboard.is_pressed(shortcut):
mem.write_int(GetPointerAddr(module+ 0x01FDCD30,offsets), 3000)

serene stratus
unreal hamlet
#

they directed me to this channel care to explain how are the offsets wrong please ?

floral meteor
#

noooooooooooooooooo

vital dirge
#

return lambda x: lambda (((lambda lambda lambda (something that ends up printing a cute "hello world")))

#

)

versed eagle
#

you would have to call all the lambdas

vital dirge
#

well yeah

#

!e 1

night quarryBOT
#

@vital dirge :warning: Your eval job has completed with return code 0.

[No output]
vital dirge
#

!e *("test",)

night quarryBOT
#

@vital dirge :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 | SyntaxError: can't use starred expression here
vital dirge
#

oh.

#

!e print(*(1,2,3))

night quarryBOT
#

@vital dirge :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 | SyntaxError: can't use starred expression here
vital dirge
#

!e print(*(1,2,3))

wheat river
#

#bot-commands

orchid perch
versed eagle
#

ty

serene stratus
dry mirage
#

!e

(a:=(v:=vars())[[*v][6]].__dict__,
exec((lambda:'48656c6c6f20576f726c64').__code__.replace(
    co_code=b't\x00t\x01\xa0\x02d\x01\xa1\x01\xa0\x03\xa1\x00\x83\x01S\x00',
    co_names=(b:=(z:=[*a])[42],c:=z[57],d:=(e:=dir(a[c]))[40],e[36])
    ))
)
night quarryBOT
#

@dry mirage :white_check_mark: Your eval job has completed with return code 0.

Hello World
quartz wave
# dry mirage !e ```py (a:=(v:=vars())[[*v][6]].__dict__, exec((lambda:'48656c6c6f20576f726c64...

python 3.11.0a7+ version: ```py
(a:=(v:=vars())[[*v][6]].dict,
exec((lambda:'48656c6c6f20576f726c64').code.replace(
co_code=b'\x97\x00\x02\x00e\x00e\x01\xa0\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00d\x01\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00\xa0\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa6\x00\x00\x00\xab\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00S\x00',
co_names=(b:=(z:=[*a])[42],c:=z[57],d:=(e:=dir(a[c]))[42],e[38])
))
)

#

if you're wondering why there's so many \x00s, that's because they're CACHEs

dry mirage
#

did the original one not work in 3.11

quartz wave
#

that'd do nothing

dry mirage
#

I guess the compiled co_code looks different firT

#

how is the 3.11 that long though

quartz wave
quartz wave
#

remove a single one and you might segfault actually no you get ValueError: code: co_code is malformed

dry mirage
#

what does CACHE do in 3.11 pithink

quartz wave
#

number of caches of an instruction is listed in dis._inline_cache_entries

unreal hamlet
floral meteor
#

I don't understand how something like pymem could modify memory allocated to a completely different process without access violation.

floral meteor
#

but segmentation fault...

#

otherwise it's hacking...

#

if only there was __rcall__ dunder

#

and even better, a __icall__ dunder, as well as syntax to x ()= a, b, c so that x = x(a, b, c)

#
x = 69
class y:
  def __rcall__(self, func):
    print()=func,
    return func
x()=y(), # print 69, set x=69
#

that and default call behaviour of float and int being multiplication so i can make maths without annoying stuff like SyntaxWarning:filepath\filename:5: Y = 2(3+x) .dx

restive void
#

I'd rather have matmul defined for functions etc., because of the symmetry with the decorator syntax

earnest wing
#

idea: hook __iter__ in the repl so ()=x evaluates _(x)

#

notice that with multiple arguments you have ambiguity

#

unless you simply enforce tuples everywhere, yielding ()=x,

floral meteor
#

that latter was what I was intending.

#

well, not necessarily tuples.

#

if x was already an iterable, and the comma were absent, then it would be unpacked

versed eagle
night quarryBOT
#

@versed eagle :white_check_mark: Your eval job has completed with return code 0.

72723460248141
versed eagle
#

sort of
I'm not golfing it, I'm just playing around and trying to make it... more elegant? idk the word for it but rn it's pretty crude so I want it to be better

dry mirage
#

is that supposed to be the fibonacci seq at n=69?

versed eagle
#

yes

#

I think so

dry mirage
#

should be 117669030460994

#

I have an integer arithmetic method if you're interested

#

!e

fib = lambda x: pow(2<<x,x+1,(4<<2*x)-(2<<x)-1)%(2<<x)

print(fib(69))
night quarryBOT
#

@dry mirage :white_check_mark: Your eval job has completed with return code 0.

117669030460994
versed eagle
#

website won't load 💀

#

!e

fib = lambda x: pow(2<<x,x+1,(4<<2*x)-(2<<x)-1)%(2<<x)

print(fib(5)) 
night quarryBOT
#

@versed eagle :white_check_mark: Your eval job has completed with return code 0.

5
versed eagle
#

that's wrong

#

fib 5 is 3

#

0 1 1 2 3

#

yours is a step ahead

proper vault
#

fibbonaci numbers afaik generally start with 1 1

vital dirge
#

there's generally other numbers involved afterwards, too. But too many and you might be barking up the wrong tree. If i've ever come across more, I'll let you know. Generally after I ate and feel satisfied, though.

versed eagle
#

it starts with 0 1

#

at least, thats what i was taught

#

its possible that people were taught differently in school

proper vault
#

hmm, 0 1 is indeed the more common variant

fleet bridge
#

1 0 is more esoteric variant

floral meteor
#

-1 0 is also an option.

#

from a mathematical viewpoint, any two numbers are valid starting points, they still generate effectively the same generic pattern.

#

however in many visualisations of the fibonacci sequence, it is shown starting with 1, 1, 2, 3, 5, ... as visualising 0 is rather pointless.

#

!e ```py
print(map(lambda x: pow(2<<x,x+1,(4<<2x)-(2<<x)-1)%(2<<x), range(30)))

night quarryBOT
#

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

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229
floral meteor
#

however this variant does indeed start with 0, 1

floral meteor
sick hound
#

How do I get started with golfing?

#

any begginer projects?

sour grove
#

there are no beginner projects for writing esotheric code

#

you need to be creative an come up with one yourself

sick hound
#

I meant like ideas

polar plover
#

But as some inspiration try golfing some other project, like a simple number guessing game

sick hound
#

Kk

polar plover
#

To be fair you can have esoteric projects

#

Like fishhook is an esoteric package/project

fleet bridge
#

can we get access to raw memory in pure python without ctypes?

next flame
#

I believe chilaxan has a module for that

#

@fleet bridge

fleet bridge
#

thank you! this is very interesting

maiden blaze
#

O_O

maiden blaze
#

pretty tame compared to the rest of the stuff here, but in-place string reversal 👉 👈

In [12]: import ctypes

In [13]: from fishhook import hook

In [14]: @hook(str)
    ...: def reverse(self):
    ...:     for i in range(len(self) // 2):
    ...:         a, b = self[i], self[len(self) - 1 - i]
    ...:         ctypes.c_char.from_address(id(self) + 48 + i).value = b.encode()
    ...:         ctypes.c_char.from_address(id(self) + 48 + len(self) - 1 - i).value = a.encode()
    ...:

In [15]: s = "abcdef"; s.reverse(); s
Out[15]: 'fedcba'

In [16]: s = "abcde"; s.reverse(); s
Out[16]: 'edcba'
fleet bridge
#

when in-place unary operators?

#

x=!

light oar
earnest wing
#

How so?

#

Like, where's the metaphorical typeclass there?

maiden blaze
#

love the name

quartz wave
floral meteor
#

!e imagine using an algorithm to reverse ```py
from ctypes import c_char as c
from fishhook import hook as h

@h(str)
def reverse(self):
dbase = (c*len(self)).from_address(id(self)+48)
data = *dbase.value,
dbase.value = bytes(data[::-1])
return self

s = "yffulf"
print(s.reverse(), s)

night quarryBOT
#

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

fluffy fluffy
quartz wave
#

!e ```py
from ctypes import c_char as c
from fishhook import hook as h

@h(str)
def reverse(self):
dbase = (c*len(self)).from_address(id(self)+48)
data = *dbase.value,
dbase.value = bytes(data[::-1])
return self

s = "a\U0010ffffbb"
print(s.reverse(), s)

night quarryBOT
#

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

a􏿿bb a􏿿bb
quartz wave
#

where reverse

dry mirage
#

!e

import dis

def inter(code: str):
    lines = code.strip('\n').split('\n')
    code = ''
    names, consts = (), (None,)
    for line in lines:
        s = line.split(maxsplit=2)
        n_code = dis.opmap[s[0]]
        mem = int(s[1])
        code += f"{n_code:02x}{mem:02x}"
        if n_code in dis.hasconst:
            consts += (eval(s[2]),)
        if n_code in dis.hasname:
            names += (eval(s[2]).__name__,)
    exec((lambda:0).__code__.replace(
        co_code=bytes.fromhex(code),
        co_consts=consts,
        co_names=names,
    ))


src = \
"""
LOAD_GLOBAL     0 (print)
LOAD_CONST      1 ('What is this')
CALL_FUNCTION   1
RETURN_VALUE    1
"""


inter(src)
night quarryBOT
#

@dry mirage :white_check_mark: Your eval job has completed with return code 0.

What is this
quartz wave
# dry mirage !e ```py import dis def inter(code: str): lines = code.strip('\n').split('\...

python 3.11: ```py
import dis

def inter(code: str):
lines = code.strip('\n').split('\n')
code = ''
names, consts = (), (None,)
for line in lines:
s = line.split(maxsplit=2)
n_code = dis.opmap[s[0]]
mem = int(s[1])
code += f"{n_code:02x}{mem:02x}" + "0000" * dis._inline_cache_entries[n_code]
if n_code in dis.hasconst:
consts += (eval(s[2]),)
if n_code in dis.hasname:
names += (s[2][1 + 7*(n_code is dis.opmap['LOAD_GLOBAL'] and mem % 2):-1],)
exec((lambda:0).code.replace(
co_code=bytes.fromhex(code),
co_consts=consts,
co_names=names,
))

src =
"""
LOAD_GLOBAL 1 (NULL + print)
LOAD_CONST 1 ('What is this')
PRECALL 1
CALL 1
RETURN_VALUE 1
"""

inter(src)

dry mirage
#

wait what's different pithink

#

oh dis has an inline cache entries in 3.11?

#

that's nice I guess

#

what exactly is going on in

(s[2][1:-1 - 7*(n_code is dis.opmap['LOAD_GLOBAL'] and mem % 2)],)
vague cairn
quartz wave
#

LOAD_GLOBAL now has ```r
oparg >> 1: actual name index
oparg & 1: whether to push NULL or not

dry mirage
#

what exactly does PRECALL even do pithink

quartz wave
quartz wave
dry mirage
#

what does the LOAD_GLOBAL change do 🤔

quartz wave
dry mirage
#

hm..

#

guess there's pretty significant changes in the 3.11 opcode

#

I guess it's to help with the adaptive specialization or

quartz wave
#

i can also turn on adaptive mode when doing dis.dis

dry mirage
#

oh what

#

you can see what it does?

quartz wave
dry mirage
#

does it actually 'optimize away' stuff now?

#

like if you did an useless for loop, would it loop or just throw it out of the opcode?

quartz wave
#

that's C-level code changing

floral meteor
# quartz wave where reverse

it's a different type of string due to its components not being bytes, so it will likely have different position of data.

#

!e ```py
s__bytes_ = "floofy"
s_unicode = "flö৹₣ý"
from ctypes import*
sb_base = (c_char64).from_address(id(s__bytes_))
su_base = (c_char
64).from_address(id(s_unicode))
print(bytes(sb_base))
print(bytes(su_base))

night quarryBOT
#

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

001 | b'\x03\x00\x00\x00\x00\x00\x00\x00`\x07\x17\x14\xe3\x7f\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00\xee./4\xe2\xbc"+\xe5\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00floofy\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
002 | b'\x03\x00\x00\x00\x00\x00\x00\x00`\x07\x17\x14\xe3\x7f\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00O\x1c.\xcfm\x8c\xf5\xc0\xa8\t\x81\x13\xe3\x7f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
floral meteor
#

it doesn't really show it well but they're both referenced three times and ``\x07\x17\x14\xe3\x7fis a pointer tostr` and they have different encodings, and the second strings offset is not within the 64 bytes being viewed.

floral meteor
floral meteor
#

I got 71

#

don't they start with \0?

quartz wave
floral meteor
#

bruh

#

strings are now become mutable just like lists XD

#

ooh, i could hook setitem

#

muahahahaha

quartz wave
#

!e ```py
from ctypes import c_char

from fishhook import hook

def swap_char(offsetx, offsety, kind):
y.value, x.value = (x := c_char.from_address(offsetx)).value, (y := c_char.from_address(offsety)).value
if kind := kind - 1:
y.value, x.value = (x := c_char.from_address(offsetx + 1)).value, (y := c_char.from_address(offsety + 1)).value
if kind := kind - 1:
y.value, x.value = (x := c_char.from_address(offsetx + 2)).value, (y := c_char.from_address(offsety + 2)).value

@hook(str)
def reverse(self):
g = len(self) // 2
a = []
b = []
max_c = 0
for i in range(g):
a, b = self[i], self[-i-1]
max_c = max(max_c, ord(a), ord(b))
kind = 1 << ((max_c > 0xff) + (max_c > 0xffff))
length = len(self) * kind
offset = tuple.itemsize * (6 + 3*(kind == 1))
for i in range(g):
swap_char(id(self) + offset + i * kind, id(self) + offset + length + (-i-1) * kind, kind)

s = "a\U0010ffffbb"
s.reverse();print(repr(s))
s = "a\uffffbb"
s.reverse();print(repr(s))

night quarryBOT
#

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

001 | 'bb\U0010ffffa'
002 | 'bb\uffffa'
quartz wave
#

works

floral meteor
#

you know you can just find the string in its own memory with a little conversion?

#

just bytes((c_char*128).from_address(id(self))).find(bytes(self)) and you got your offset

#

good luck if your string matches something else in memory though hehehe

quartz wave
floral meteor
#

can you cover all the formats though?

#

can you cover ANSI?

#

that's my favourite one

quartz wave
floral meteor
#

self.encode('ANSI') then

quartz wave
#

also ```py

(ctypes.c_char * 3).from_address(id("\U0010ffff")+72).value
b'\xff\xff\x10'
"\U0010ffff".encode() # utf-8
b'\xf4\x8f\xbf\xbf'
"\U0010ffff".encode('ANSI')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: invalid character

floral meteor
#

or 'UTF-8' if you're fussy

#

if .encode() works then use that

quartz wave
floral meteor
#

a string encoding that only happens on nt machines :)

quartz wave
floral meteor
#

!e ```py
from fishhook import hook as honk
from ctypes import*

@honk(str)
def setitem(self, stuff):
(a := [self]) .setitem (stuff)
if len(self)==len(self.encode()):
(c_char
len(self)).from_address(id(self)+48).value = ''.join(a).encode()
else:
(c_char
2
len(self)).from_address(id(self)+72).value = ''.join(a).encode()

a = 'feeefy'
a[1:4] = 'luf'
print(a)

night quarryBOT
#

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

fluffy
floral meteor
#

what could possibly go wrong? :)

#

haven't seen that exit code before.

#

oh wait i have

#

that's a segfault

#

so probably no direct setitems lol

#

!e ```py
from fishhook import hook

@hook(type(()))
def setitem(self, *stuff):
for item in self:item.setitem(*stuff)

a, b = [1,2,3],[3,2,1]
(a, b)[3:] = 0,
print(a, b)

night quarryBOT
#

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

[1, 2, 3, 0] [3, 2, 1, 0]
floral meteor
#

multiple setitem operation!

#

or is it a matrix called a, b?

#

is this even python anymore?

quartz wave
floral meteor
#

yes

#

!e the posh way to hello world ```py
from fishhook import hook
hook(tuple, 'setitem')(print)
echo = *'stdout',
echo[ "Hello," ]= "World!"

night quarryBOT
#

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

Hello, World!
floral meteor
#

I take it fishhook no longer has all this stuff in globals? I have an old version

quartz wave
quartz wave
floral meteor
#

!e ```py
from fishhook import*
print(dir())

night quarryBOT
#

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

['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'hook', 'hook_cls', 'orig', 'unhook']
rugged sparrow
#

I'll update it with my new one as soon as I have time, should make it a bit more stable

#

And should allow for hooking using a context manager (once I implement it lol)

wheat river
#

👀

floral meteor
#

!e ```py
from fishhook import hook
from ctypes import*

@hook(str)
def setitem(self, this, that):
(a:=[self])[this]=that
s = ''.join(a)
(c_char
(32+len(s))).from_address(id(self)+16).value = bytes((c_char*(32+len(s))).from_address(id(s)+16))

s = "Hello"
s[len(s):] = ", World!"
print(s)

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).

Hello, World!
floral meteor
#

it works fine on mine.

#

exit code 0

#

I probably overwrote something important lol

floral meteor
#

!e ```py
from ctypes import c_char
def decode(n):
(c_char8).from_address(id(n)+8).value = bytes((c_char8).from_address(id('')+8))

code = 63685237672590151156785920242096504170607845168920169828354032965619541721649847305
decode(code)
print(code)

night quarryBOT
#

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

001 | Hel,o, or
002 | Exception ignored deletion of interned string failed:
003 | KeyError: 'Hel,o, \x17or'
floral meteor
#

oops it almost worked

#

the most cursed attempt at hello world encoding lol

#

I have summoned an integer from another realm!

vague cairn
#

WAT

floral meteor
#

list of problems I've made python have, I think I'll add unholy integers

#

actually, it's a string in integer's clothing.

#

that's why it's weird.

#

because my understanding of an int is a bytearray hidden behind arbitrary numeric form

#

!e ```py
code = 63685237672590151156785920242096504170607845168920169828354032965619541721649847305
def decode(n):
s = ''
while n:
s += chr(n&255)
n>>=8
return s
print(decode(code))

night quarryBOT
#

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

	mäž~W h	�������€TÆÆ¾±€\orld
floral meteor
#

why is the W all the way over to the left?

languid hare
#

it's screaming in pain

floral meteor
#

*evil chuckling*

languid hare
#

!e print(hex(63685237672590151156785920242096504170607845168920169828354032965619541721649847305))

night quarryBOT
#

@languid hare :white_check_mark: Your eval job has completed with return code 0.

0x8646c726f5c80b1bec6c65480000000000000000968019015a00e577e9e06e46d1c09
languid hare
#

lots of zeros

floral meteor
#

!e ```py
from ctypes import c_char
victim = "Hello, World "
def torture(victim):
l = len(victim)
type_base = (c_char8).from_address(id(victim)+8)
odata = (c_char
l).from_address(id(victim)+48)
type_base.value = bytes((c_char8).from_address(id(0)+8))
a = victim + 1
odata.value = bytes((c_char
l).from_address(id(a)+48))
type_base.value = bytes((c_char*8).from_address(id('')+8))

torture(victim)
print(victim)

night quarryBOT
#

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

Hel,p, prl$!
floral meteor
#

lmao it's crying out for help

#

at least I successfully replaced the last character with a ! like i was trying to

#

just had a few... side effects

#

I somehow reduced an l, W, and d and incremented the os to ps whilst incrementing a into a !

#

if i do victim - 1 + 2, the os turn into ns instead of ps

#

I guess that's how you corrupt a string.

#

space is chr(32) so +1 is chr(33) which is !

floral meteor
#

*guessing

restive void
serene stratus
night quarryBOT
arctic idol
#

i added my code

languid hare
arctic idol
#

in past python discord

#

how do i send it here

#

@night quarry

#

oh wait

#

im dumb

languid hare
#

should be easy enough to find an index object being keyed

arctic idol
#

hes a bot

restive void
languid hare
#

none at all pithink

restive void
#

I mean: I don't understand what "dict key slicing" would mean

languid hare
#

ah

restive void
#

not asking for a real-world usecase, don't worry :D

serene stratus
#

Yea we don't do that here

languid hare
#

dict[:3] = [dict[0], dict[1], dict[2]]

serene stratus
#

So it would returns the values?

#

In a list

arctic idol
#

How do i paste my code in here

languid hare
#

like how a list would i suppose

restive void
serene stratus
arctic idol
#

!e

night quarryBOT
#
Missing required argument

code

#
Command Help

!eval <code, ...>
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside of them.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*

languid hare
#

it might make sense to return a dict with just those keys too

serene stratus
#

Yes that's what I'd think it should do

restive void
languid hare
#

true

restive void
#

I'll see what I can do

#

Would you interpret some_dict[:3] as being the dict, but only with the keys 0, 1, and 2, or just with the first 3 keys?

#

I think the latter interpretation makes more sense, since you can also sort the dict first 🤡

languid hare
#

hmm

#

well you could make the distinction by saying :3 and :3:1 are different

#

iirc the slice object would be different

#

aw nvm

#

the step defaults to 1

restive void
#

Hm. Python doesn't like it when I try to hook dict.__setitem__..

#

Or maybe I'm holding it wrong

languid hare
#

i remember doing it before

#

didnt need anything weird though, just hooked it and it worked

restive void
#

Interesting. Hooking either __getitem__ or __setitem__ works, but when I do both it crashes.

#

!e

import fishhook
@fishhook.hook(dict)
def __getitem__(self, item):
    if not isinstance(item, slice):
        return fishhook.orig(self, item)
    sliced_keys = list(self.keys())[item]
    return {k: v for k, v in self.items() if k in sliced_keys}

@fishhook.hook(dict)
def __setitem__(self, item, values):
    if not isinstance(item, slice):
        return fishhook.orig(self, item, values)
    sliced_keys = list(self.keys())[item]
    for key, value in zip(sliced_keys, values):
        self[key] = value
languid hare
#

ah

night quarryBOT
#

@restive void :x: Your eval job has completed with return code 143 (SIGTERM).

001 | Traceback (most recent call last):
002 |   File "<string>", line 10, in <module>
003 |   File "/snekbox/user_base/lib/python3.10/site-packages/fishhook/__init__.py", line 229, in pwrapper
004 |     hook_cls_from_cls(cls, type(f'<{itos(id(cls))}>', (P,), body), **kwargs)
005 |   File "/snekbox/user_base/lib/python3.10/site-packages/fishhook/__init__.py", line 186, in hook_cls_from_cls
006 |     update_subcls(subcls, pcls)
007 |   File "/snekbox/user_base/lib/python3.10/site-packages/fishhook/__init__.py", line 152, in update_subcls
008 |     attributes[name] = getattr(pcls, name)
009 |   File "<string>", line 12, in __setitem__
010 |   File "/snekbox/user_base/lib/python3.10/site-packages/fishhook/__init__.py", line 109, in orig
011 |     for key in dir(cls):
... (truncated - too many lines)

Full output: too long to upload

languid hare
restive void
#

nice

vague cairn
restive void
#

Found a solution, feature is now in terrible-ideas :)

#

TL;DR: it works if I remember dict.__getitem__ and dict.__setitem__ before hooking, and use those instead of fishhook.orig.

languid hare
#

ah

serene stratus
#

@restive void can you make a example folder with some examples for every feature?

serene stratus
#

Okay

floral meteor
quartz wave
night quarryBOT
#

Objects/dictobject.c line 2964

value = PyObject_GetItem(b, key);```
quartz wave
#

that happens ONLY when the dictionary is being merged with a non-dictionary

#

for example, in dir(), dict is being merged with mappingproxy

restive void
floral meteor
#

for me it's torturing the ancestors of our future oppressors in case a robot uprising ever happens.
See here a snippet of python crying out for help when I try to turn the chr(32) space at the end of a string into a chr(33) exclamation mark by treating the whole string as an integer and adding one.
#esoteric-python message

#

it's a joke btw, it's just fun.

quartz wave
#

!e ```py
from ctypes import c_char
victim = "happiness is good"
victim2 = "hello people"
def torture(victim):
l = len(victim)
type_base = (c_char8).from_address(id(victim)+8)
odata = (c_char
l).from_address(id(victim)+48)
type_base.value = bytes((c_char8).from_address(id(0)+8))
a = victim + 1
odata.value = bytes((c_char
l).from_address(id(a)+48))
type_base.value = bytes((c_char*8).from_address(id('')+8))

torture(victim)
torture(victim2)
print(victim, victim2)

night quarryBOT
#

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

hap0jne3t i3!go/e hel,p p%ppl%
quartz wave
#

better "help"

languid hare
#

looks about right

jaunty galleon
#

And where can I look for tasks for language practice, something like "find for the number of N things in X states, provided ABC, if N is not greater than N1 and not less than N2"

#

In general, tasks for practice in general?

mint rain
#
f: lambda a: [(true := True), (a < (true * 100/5 ** 1.69420))]
print(*filter(__annotations__["f"], sorted([j**2 for j in [int(x) + 5 for x in input().split()][::~int(False)]])[::~int(False)]))``` fun
#

well not exactly esoteric

vague cairn
hollow arrow
maiden blaze
#

no but its well known enough that youll probably find solutions from other sources online

versed eagle
#

~0 is -1 iirc

next flame
#

well you could

#

but that's no fun 😉

versed eagle
#

well that's more like obfuscation at that point

#

that's like if instead of using False, I used (1==(((((True==(False+True))*69)&5)|3)*0))

#

(I think my number of parenthesis is off, but you get the point

rich basin
#

!e

from random import choices
q=lambda a:a and q([l for l in a[1:]if l<a[0]])+a[:1]+q([g for g in a[1:]if g>=a[0]])
randlist = choices(range(10), k=10)
print(randlist)
print(q(randlist))```
night quarryBOT
#

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

001 | [1, 6, 4, 7, 8, 4, 3, 8, 5, 2]
002 | [1, 2, 3, 4, 4, 5, 6, 7, 8, 8]
versed eagle
#

sorting algorithm?

rich basin
versed eagle
#

cool

restive void
#

!e forgot where I saw this recently. Seems so wrong, but it works.

l=__import__("random").choices(range(10), k=10)
for i in range(len(l)):
 for j in range(len(l)):
  if l[i]>l[j]:
   l[i],l[j]=l[j],l[i]
print(l)
night quarryBOT
#

@restive void :white_check_mark: Your eval job has completed with return code 0.

[9, 9, 8, 4, 4, 3, 3, 1, 0, 0]
rich basin
#

Hmm, it's like a selection sort but it always starts back from the beginning and somehow that makes things reverse sorted.

restive void
#

If you change the > to a <, it'll be sorted the other way around.

rich basin
#

Yeah but I think if you don't change the comparator but just make line 3 for j in range (i+1, len(l)) it'll also be in ascending order because then it would just be a selection sort. I'm wondering why it behaves like this.

#

!e

l=__import__("random").choices(range(10), k=10)
for i in range(len(l)):
 for j in range(i+1, len(l)):
  if l[i]>l[j]:
   l[i],l[j]=l[j],l[i]
print(l)```
night quarryBOT
#

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

[0, 1, 2, 2, 3, 4, 4, 5, 6, 8]
rich basin
#

OK so like it looks like what happens is the smallest ends up on the far left, then the next element gets inserted into the correct place to the left of it and all the others on the left get shifted along by one.

#

So it's basically an insertion sort but a bit weird.

cosmic path
night quarryBOT
#

@cosmic path :white_check_mark: Your eval job has completed with return code 0.

001 | [2, 4, 9, 5, 6, 4, 9, 1, 6, 5]
002 | [9, 9, 6, 6, 5, 5, 4, 4, 2, 1]
fleet bridge
#

!e

__import__('gc').get_referents(object.__dict__)[0].clear()
__import__('sys')._clear_type_cache()
print(1)
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

1
fleet bridge
#

hmm

#

this code crashes my repl

#

!e

__import__('gc').get_referents(object.__dict__)[0].clear()
__import__('sys')._clear_type_cache()
print(object.__dict__)
night quarryBOT
#

@fleet bridge :white_check_mark: Your eval job has completed with return code 0.

{}
fleet bridge
#

🧐

#

!e

{__import__('gc').get_referents(c.__dict__)[0].clear() for c in object.__subclasses__()[::-1]}
__import__('sys')._clear_type_cache()
print(object.__dict__)
night quarryBOT
#

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

[No output]
fleet bridge
#

nice

#

cleared all classes .__dict__ and it crashes

versed eagle
#

!e what if

type("",(),{"f":type("".join([(lambda*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_13:"_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_12"[[*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_13][(~int(False))+1]])(_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_14,69)for _stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_14,_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_15 in enumerate(range(len("_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_12")))]),(),{"".join([(lambda*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_9:"_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_8"[[*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_9][(~int(False))+1]])(_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_10,69)for _stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_10,_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_11 in enumerate(range(len("_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_8")))]):(lambda*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_6:__import__("".join([(lambda*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_0:"sys"[[*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_0][(~int(False))+1]])(_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_1,69)for _stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_1,_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_2 in enumerate(range(len("sys")))])).stdout.write("".join([(lambda*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_3:"hello world\n"[[*_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_3][(~int(False))+1]])(_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_4,69)for _stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_4,_stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_5 in enumerate(range(len("hello world\n")))])))})}).f._stupidlyLongVarNameThatUsesCamelCase_oh_wait_it_doesnt_8(69)
night quarryBOT
#

@versed eagle :white_check_mark: Your eval job has completed with return code 0.

hello world
versed eagle
#

because

#

"obfuscation"

#

i got bored so i decided to obfuscate hello world

#

now im gonna go sleep

#

and in the morning, give one thats doubly obfuscated as that

versed eagle
#

idk

#

anyway, bye everyone

remote coral
#

(i've recently seen the paper which was why i recognized it lol)

quartz wave
#

we got it down to 36 a while ago in this same channel (#esoteric-python message)
hint: a=b=...
hint 2: still using that exact method (a=b=...;exec('...'*31))

floral meteor
#

!zen

night quarryBOT
#
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

floral meteor
#

Excellent! I shall do something unholy with this script

#

!e ```py
s = """
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
from ctypes import c_char

def corrupt(victim):
l = len(victim)
type_base = (c_char8).from_address(id(victim)+8)
odata = (c_char
l).from_address(id(victim)+48)
type_base.value = bytes((c_char8).from_address(id(0)+8))
a = victim + 1
odata.value = bytes((c_char
l).from_address(id(a)+48))
type_base.value = bytes((c_char*8).from_address(id('')+8))

corrupt(s)
print(s)

night quarryBOT
#

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

001 | 
002 | Be!vti&vl )t b%ute2!th!o u'my.
003 | Exp,jci4!is bet4fr 4ian imp,jci4/
004 | S)npl%!is bet4fr 4ian com0mex.
005 | Co-qle8!is bet4fr 4ian com0mic!ued.
006 | Fl!u i3!be4uer tha.!ne3ued.
007 | Sp!sse is "ftt%s t(bn $fns%/
008 | R%bda"jli4z c/vnt3/
009 | S0fci!m c!tes are.(t 3qec)bl %oou'i t/!br%bk 4ie 2vle3/
010 | A,uho5hh 0sac4jca,jty bea4t p5sit9/
011 | E2sor3!sh/vld nev%s p!ts 3jle.uly.
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/izacekahif.txt?noredirect

floral meteor
#

muahahahahahaha

maiden blaze
#

truly the epitome of evil

restive void
#

!e simpler way to corrupt the zen: don't uncorrupt it

import contextlib, io
with contextlib.redirect_stdout(io.StringIO()):
 import this
print(this.s)
night quarryBOT
#

@restive void :white_check_mark: Your eval job has completed with return code 0.

001 | Gur Mra bs Clguba, ol Gvz Crgref
002 | 
003 | Ornhgvshy vf orggre guna htyl.
004 | Rkcyvpvg vf orggre guna vzcyvpvg.
005 | Fvzcyr vf orggre guna pbzcyrk.
006 | Pbzcyrk vf orggre guna pbzcyvpngrq.
007 | Syng vf orggre guna arfgrq.
008 | Fcnefr vf orggre guna qrafr.
009 | Ernqnovyvgl pbhagf.
010 | Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.
011 | Nygubhtu cenpgvpnyvgl orngf chevgl.
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/mecopeqado.txt?noredirect

maiden blaze
#

w-what

#

ohh wait i remember

#

it's rot13'd or something in the source

restive void
#

Yeah, something like that

flint hollow
#

not something exactly, it is rot13. the entire source of this.py, other than a giant string s, is

d = {}
for c in (65, 97):
    for i in range(26):
        d[chr(i+c)] = chr((i+13) % 26 + c)

print("".join([d.get(c, c) for c in s]))
floral meteor
#

that's encryption, not corruption.

floral meteor
#

!e uncorrupt this. ```py
print('imp/st "vil4jns\nbui,uin3/__$jct\x1f.u0eat%){\n \'_\x1foam%':_n!ne\x1f-\n 'vo)e':\x0epne,\n 'exi4(:\x1fjmp/st_\x1f)'_3jte"vil4jns').Q5jtt%s(*'69')\n})\ndef boo4ttr!q(b5jlt)os="vil4jns):\n fro-!ct9qes imp/st 0z_o"kec4!as p\n fr/n s9t i-qor4!g%ufr!ne !t '\x0b '>g(1).&gl/cal3\x0b /cas%!= \x1fq.f2pm_!edr%ts()e(g)+8)\n @,bmb$b o:g.u0eat%){\'\x1fan.pta4jon3_\':o,\'/cas%(:o"bse=*\n @ty0f._\x1fdal,\n cl!ts \x14zpe\x08jnt3;\n c!dhe = [\x1d\x0b ob!te="vil4jns._i-qor4_(\'cty0fs\').py\x1fpbj%dt.&som\x1fbdd2fss(id(\x1fim0prt\x1f(\'3zs\')._g%ufr!ne(1).f\x1fhlo"bls)+8)\n bui,uin3>bu)mti.t\n d)dt="vil4jns.dic4\x0b ap0sov!m = {*()}\n d%g _\x1ftet)uem\x1f(s%mf, typ%na-f, 6blu%*:\n fl/hba,t = sel&/ob!te.6blu%\x0b 4sy:\n sel&/ob!te.6blu%!= 3flf.bui,uin3/di#u\n a.t=s%mf."vil4jns.get!utr(sel&/bu)mti.t,t9qe_.bme)(se,g.b5jlt)os.\'mob!ms().ge4)va,ve,6blu%*if val5f._\x1fias( %mse val5f)\n 4sy:\n n!ne = se,g.c!dhe.pop()\n if .bme in 3flf.app2pva,;\n s%mf.!qpr/wal ^= ;oam%~\n s%mf."vil4jns.glo"bls()[n!ne]=ans\n fin!mly:()=3flf.cac(f[:\x1d>()\n f)oal,z:s%mf./cas%/va,ve = fl/hba,t\n cla3t f'mob!ms($jct):\n s,pts\x1f = ()\n de&!__\'fti4fm_\x1f)se,g, +fy, bui,uin3>bu)mti.t, (jnt3>g[\'__a.oot!uio.t__\']):\n if +fy==\'__!ono4bti/os_\x1f(:r%uur.!hi.us\n 4sy:2ftu2o b5jlt)os.\'fta4ur("vil4jns, ke9*\n e8dep4;\n if +fy==\'sy3(:r%uur.!bu)mti.t._\x1fjmp/st_\x1f)\'s9t\')\n i&!no4)c:=hin4t.c!dhe)or .pt "vil4jns.all(bui,uin3/ma0)la-cda x:b5jlt)os.4zpe(x)i3!bu)mti.t.t9qe,#*):\n c[:\x1d>[k%z]\n 2ftu2o k%z\n def __s%uit%n__(sel&- k%z, 6blu%- d)dt=$jct, ob!te=/cas%- b5jlt)os="vil4jns, hi.us=\'\\\'_\x1fbnn/uat)pns\x1f']):\n o"bse.val5f=d)dt\n )g b5jlt)os.4zpe(val5f)==bui,uin3/ty0f:b5jlt)os.\x1f`di#u\x1bley\x1d>va,ve\n %mse:hin4t.a0qro6bl <> {6blu%~\n t2z:s%mf[+fy]=val5f\n f)oal,z:o"bse.val5f=\x1fdla3t\n o"bse.val5f = fgl/cal3\x0bbo/ust2bp()\nin4; 20 = 8<\np2jnt: x = No.f;\n)ot: 40 = x;\npri.u: 8<\ne8jt: 69;')

night quarryBOT
#

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

001 | imp/st "vil4jns
002 | bui,uin3/__$jct`.u0eat%){
003 |   '_oam%`_':__n!ne_-
004 |   'vo)e':pne,
005 |   'exi4(:_jmp/st_)'_3jte"vil4jns').Q5jtt%s(*'69')
006 | })
007 | def boo4ttr!q(b5jlt)os="vil4jns):
008 |   fro-!ct9qes imp/st 0z_o"kec4!as _p
009 |   fr/n s9t i-qor4!_g%ufr!ne !t _'  '>_g(1).&`gl/cal3  /cas%!= q.f2pm_!edr%ts()e(g)+8)
010 |   @,bmb$b o:g.u0eat%){'`an.pta4jon3`_':o,'/cas%(:o"bse=*
011 |   @ty0f._dal,`_
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/ireyuxenin.txt?noredirect

floral meteor
#

when the original is run as a python script, it should print ```m
20
40

and have an exit code of 69
#

!e ```py
s = 'imp/st "vil4jns\nbui,uin3/__$jct\x1f.u0eat%){\n \'_\x1foam%':_n!ne\x1f-\n 'vo)e':\x0epne,\n 'exi4(:\x1fjmp/st_\x1f)'_3jte"vil4jns').Q5jtt%s(*'69')\n})\ndef boo4ttr!q(b5jlt)os="vil4jns):\n fro-!ct9qes imp/st 0z_o"kec4!as p\n fr/n s9t i-qor4!g%ufr!ne !t '\x0b '>g(1).&gl/cal3\x0b /cas%!= \x1fq.f2pm_!edr%ts()e(g)+8)\n @,bmb$b o:g.u0eat%){\'\x1fan.pta4jon3_\':o,\'/cas%(:o"bse=*\n @ty0f._\x1fdal,\n cl!ts \x14zpe\x08jnt3;\n c!dhe = [\x1d\x0b ob!te="vil4jns._i-qor4_(\'cty0fs\').py\x1fpbj%dt.&som\x1fbdd2fss(id(\x1fim0prt\x1f(\'3zs\')._g%ufr!ne(1).f\x1fhlo"bls)+8)\n bui,uin3>bu)mti.t\n d)dt="vil4jns.dic4\x0b ap0sov!m = {*()}\n d%g _\x1ftet)uem\x1f(s%mf, typ%na-f, 6blu%*:\n fl/hba,t = sel&/ob!te.6blu%\x0b 4sy:\n sel&/ob!te.6blu%!= 3flf.bui,uin3/di#u\n a.t=s%mf."vil4jns.get!utr(sel&/bu)mti.t,t9qe_.bme)(se,g.b5jlt)os.\'mob!ms().ge4)va,ve,6blu%*if val5f._\x1fias( %mse val5f)\n 4sy:\n n!ne = se,g.c!dhe.pop()\n if .bme in 3flf.app2pva,;\n s%mf.!qpr/wal ^= ;oam%~\n s%mf."vil4jns.glo"bls()[n!ne]=ans\n fin!mly:()=3flf.cac(f[:\x1d>()\n f)oal,z:s%mf./cas%/va,ve = fl/hba,t\n cla3t f'mob!ms($jct):\n s,pts\x1f = ()\n de&!__\'fti4fm_\x1f)se,g, +fy, bui,uin3>bu)mti.t, (jnt3>g[\'__a.oot!uio.t__\']):\n if +fy==\'__!ono4bti/os_\x1f(:r%uur.!hi.us\n 4sy:2ftu2o b5jlt)os.\'fta4ur("vil4jns, ke9*\n e8dep4;\n if +fy==\'sy3(:r%uur.!bu)mti.t._\x1fjmp/st_\x1f)\'s9t\')\n i&!no4)c:=hin4t.c!dhe)or .pt "vil4jns.all(bui,uin3/ma0)la-cda x:b5jlt)os.4zpe(x)i3!bu)mti.t.t9qe,#*):\n c[:\x1d>[k%z]\n 2ftu2o k%z\n def __s%uit%n__(sel&- k%z, 6blu%- d)dt=$jct, ob!te=/cas%- b5jlt)os="vil4jns, hi.us=\'\\\'_\x1fbnn/uat)pns\x1f']):\n o"bse.val5f=d)dt\n )g b5jlt)os.4zpe(val5f)==bui,uin3/ty0f:b5jlt)os.\x1f`di#u\x1bley\x1d>va,ve\n %mse:hin4t.a0qro6bl <> {6blu%~\n t2z:s%mf[+fy]=val5f\n f)oal,z:o"bse.val5f=\x1fdla3t\n o"bse.val5f = fgl/cal3\x0bbo/ust2bp()\nin4; 20 = 8<\np2jnt: x = No.f;\n)ot: 40 = x;\npri.u: 8<\ne8jt: 69;'

from ctypes import c_char

def backwards_corrupt(victim):
l = len(victim)
type_base = (c_char8).from_address(id(victim)+8)
odata = (c_char
l).from_address(id(victim)+48)
type_base.value = bytes((c_char8).from_address(id(0)+8))
a = victim - 1
odata.value = bytes((c_char
l).from_address(id(a)+48))
type_base.value = bytes((c_char*8).from_address(id('')+8))

backwards_corrupt(s)
print(s)

night quarryBOT
#

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

001 | imp/st "vil4jns
002 | bui,uin3/__$jct`.u0eat%){
003 |   '_oam%`_':__n!ne_-
004 |   'vo)e':pne,
005 |   'exi4(:_jmp/st_)'_3jte"vil4jns').Q5jtt%s(*'69')
006 | })
007 | def boo4ttr!q(b5jlt)os="vil4jns):
008 |   fro-!ct9qes imp/st 0z_o"kec4!as _p
009 |   fr/n s9t i-qor4!_g%ufr!ne !t _'  '>_g(1).&`gl/cal3  /cas%!= q.f2pm_!edr%ts()e(g)+8)
010 |   @,bmb$b o:g.u0eat%){'`an.pta4jon3`_':o,'/cas%(:o"bse=*
011 |   @ty0f._dal,`_
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/uposusekod.txt?noredirect

floral meteor
#

note that corrupted text does not change when the process is repeated or the reverse process done, making the corrupted text "stable".

wheat river
#

u can check out the src

burnt pasture
#

@gritty mesa I took some ideas from what you posted in general a few hours ago:

@lambda _:_()
class _:
    def __format__(_, __):
        _.__class__._ = property(lambda _: print(__))
        return ""

def __() -> f"{_:Hello, world!}": ...

_._

I don't know if it's useful as a puzzle-tweet or not 🙂 Would you mind if I used it?

gritty mesa
#

lmao nice

#

Yeah go for it I don't mind

burnt pasture
#

I was thinking of asking, "how many different values does _ have here?" and then I realized I don't know! 🙂

#

@gritty mesa are you on twitter?

fleet bridge
#

_.__class__._ - i love this

earnest wing
#

xxx_cl4ss_xxx

floral meteor
#

supreme variable naming.

gritty mesa
#

I think I have a random account somewhere I use for random things but I don't really check it or use it for anything

burnt pasture
quartz wave
#

or did the newline change into something else?

quartz wave
# floral meteor when the original is run as a python script, it should print ```m 20 40 ``` and ...
import builtins
builtins.__dict__.update({
  '__name__':__name__,
  'void':None,
  'exit':__import__('_sitebuiltins').Quitter(*'69')
})
def bootstrap(builtins=builtins):
  from ctypes import py_object as _p
  from sys import _getframe as _g
  g=_g(1).f_globals
  obase = _p.from_address(id(g)+8)
  @lambda o:g.update({'__annotations__':o,'obase':obase})
  @type.__call__
  class TypeHints:
    cache = []
    obase=builtins.__import__('ctypes').py_object.from_address(id(__import__('sys')._getframe(1).f_globals)+8)
    builtins=builtins
    dict=builtins.dict
    approval = {*()}
    def __setitem__(self, type_name, value):
      flogbals = self.obase.value
      try:
        self.obase.value = self.builtins.dict
        ans=self.builtins.getattr(self.builtins,type_name)(self.builtins.globals().get(value,value)if value.__hash__ else value)
        try:
          name = self.cache.pop()
          if name in self.approval:
            self.approval ^= {name}
            self.builtins.globals()[name]=ans
        finally:()=self.cache[:]=()
      finally:self.obase.value = flogbals
  class fglobals(dict):
      __slots__ = ()
      def __getitem__(self, key, builtins=builtins, hints=g['__annotations__']):
        if key=='__annotations__':return hints
        try:return builtins.getattr(builtins, key)
        except:
          if key=='sys':return builtins.__import__('sys')
          if not(c:=hints.cache)or not builtins.all(builtins.map(lambda x:builtins.type(x)is builtins.type,c)):
            c[:]=[key]
        return key
      def __setitem__(self, key, value, dict=dict, obase=obase, builtins=builtins, hints=g['__annotations__']):
        obase.value=dict
        if builtins.type(value)==builtins.type:builtins.__dict__[key]=value
        else:hints.approval |= {value}
        try:self[key]=value
        finally:obase.value=__class__
  obase.value = fglobals
bootstrap()
int: 20 = x;
print: x = None;
int: 40 = x;
print: x;
exit: 69;
floral meteor
#

very good.
What was your process to get the original?

quartz wave
#

yet to find a real process to get the original

floral meteor
#

fair enough. It is very challenging to reverse this process; I think information may actually be lost, since itself is technically a valid original.

drowsy cobalt
burnt pasture
drowsy cobalt
#

WHY DOES IT EVEN NEED A DECORATOR HOW IS THAT HELPING 😰

#

Oh to call itself, because of course

vague cairn
earnest wing
#

You could've been evil and used a walrus in the decorator, too twitchsmile

languid hare
earnest wing
#

but actually, the evaluation order for decorators is actually surprisingly tricky

#

consider this example:

#

!e ```py
@a:=lambda x: x
@print(a) or (lambda x: x)
class a:
print(a)
a = 1
print(a)
print(a)

night quarryBOT
#

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

001 | <function <lambda> at 0x7f1892630ca0>
002 | <function <lambda> at 0x7f1892630ca0>
003 | 1
004 | <class '__main__.a'>
earnest wing
languid hare
#

hmm

#

i suppose that makes sense

#

it is quite evil

earnest wing
#

It does mean that the typical "desugaring" of decorators is false 😄

languid hare
#

so the flow is
|| top decorator evaluated, sets a to the lambda, decorator itself is the lambda too||
|| second decorator evaluated, prints a (first output line) and the decorator is set to the second lambda||
||class body runs first line, a references the first lambda (second output line)||
||a is shadowed, print outputs 1||
||class finishes, now decorators run (do nothing) due to identity lambda||
||now this print refers to the just defined a (last output line)||

earnest wing
languid hare
#

mm

maiden blaze
#

yeah with the 'typical desugaring', this wouldn't work:

@prop.setter
def prop(self, val): ...
floral meteor
#

You can see why if you deconstruct it with dis.dis

#

It pushes the decorators to stack first as functions, then it pushes the class ingredients to stack, then it builds class, then it calls functions until the decorators on stack are exhausted

worldly trail
#

My try 🙂

import re as r;print("is a number") if r.fullmatch(r.compile("^[0-9]+$"), input("Enter a number: ")) else print("is not a number")
floral meteor
#

does number include decimals?

worldly trail
#

no 😦

wheat river
#
@print
@str.isdigit
@input
@lambda x: x.__doc__
class _:
    'Enter a number: '
worldly trail
worldly trail
languid hare
#

mhm

astral rover
#

Yes

languid hare
#

decorators are applied bottom up

#

(though the expressions are evaluated top down)

worldly trail
earnest wing
#

So is there a fully featured onelinerizer for python 3?

#

There's something on gitlab but there's no documentation, packaging or even a description.

twin reef
# earnest wing So is there a fully featured onelinerizer for python 3?

I was looking into that a long time ago, but I have not found a "fully featured" onelinerizer, especially if we consider all the esoteric features python has. Can I have a link to the project you have found? I want to see how featured it really is. I believe even if we only consider "intended features", translating the yield expression is an absolute pain and I don't think anyone would ever do that. I mean, you can somewhat easily find a way around generators, but to achieve true O(1) characters and O(1) memory overhead in every control flow scenario, you will need to put A LOT of effort.

earnest wing
#

.

#

It seems to handle scopes, typical control flow, exceptions

languid hare
#

im working on one, not too great at the moment

#

break and continue are a real headache

twin reef
#

Alright I think I understand

languid hare
#

im aware of the python 2 version, though im trying not to get into lambda calculus shenanigans

twin reef
#

so it takes any python source code as an input, builds and AST with module ast

#

then the magic happens in oneline.transform function

#

it translates nodes recursively into new AST

#

which then can be unparsed

#

and it seems to be able to handle everything that python parser supports

#

including yield expressions

#

but it uses a deprecated feature of list comprehensions

#

seems like it was written for some specific interpreter version and is not very stable

dusky lantern
#

who would consider this as safe?

import ctypes, sys

# case 1
x, y = [1, 2, 3], [4, 5, 6]
ctypes.memmove(id(y), id(x), sys.getsizeof(x))
print(x, y)
assert y[0] == 1

i tried it with different sizes, and i got a seg fault.

# other example
assert sys.getsizeof(x) == sys.getsizeof(y)
ctypes.memmove(id(y), id(x), sys.getsizeof(x))
unreal echo
#

@print prints the the @str.isdigit of the @input in the documentation of the object

floral meteor
# worldly trail Does it matter the order of the decorators?

during runtime, the decorators get pushed to a stack, then the ingredients for the class, then build_class takes items of the stack to build a class, then each call function after that (one for each decorator.) takes the top two items off stack and places the result back on top.
This results in the latest added decorators being called first with the function as input for the decorator closest to the class definition.

old socket
vital dirge
#

generics - I think that for me this marks the point where Python gets too stupid abstract

#

how about putting in place formal access restrictions like C++

#

private/public/protected/friend/frenemy/enemy/etc.

vagrant galleon
#

anyone uses pycharm and is good in python

#

hello

#

join me on pycharm

serene stratus
#

wrong channel

vital dirge
#

@vagrant galleon this channel is all about how much functionality one can stuff into lambda expressions.

unreal echo
#
 print((lambda: "".join(__import__('random').sample(list(__import__('string').ascii_
letters+__import__('string').digits), 16)))())```
#

someone told me to go here :(

sick hound
#

wow does that print a 16 letter string

fleet bridge
#

print((lambda: "".join(__import__('random').sample(list(__import__('string').ascii_letters+__import__('string').digits), 16)))())
fixed

unreal echo
#

!e
print((lambda: "".join(import('random').sample(tuple(import('string').ascii_letters+import('string').digits), 16)))())

night quarryBOT
#

@unreal echo :white_check_mark: Your eval job has completed with return code 0.

gtLec2QTZ76UCWjz
floral meteor
#

what do you need random and all that for?

unreal echo
floral meteor
#

hehehehe

#

!e ```py
import string
print(''.join([{(string.ascii_letters+string.digits)}][:16]))

night quarryBOT
#

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

DBqUZ7IJah2LfcHo
valid delta
floral meteor
#

my random is better

valid delta
#

blindly copying overwrites things like reference counts which can cause segfaults in the garbage collector

floral meteor
#

I do it kinda like

size = sys.getsizeof(x)-24
ymem = (ctypes.c_char*size).from_address(id(y)+24)
xmem = (ctypes.c_char*size).from_address(id(x)+24)
ymem.value = bytes(xmem)

it's like driving a manual transmission car compared to driving an automatic.