#esoteric-python

1 messages ยท Page 1 of 1 (latest)

sick hound
#

[1] 21495 segmentation fault (core dumped) python

rugged sparrow
#

It looks like the strings are all being placed one after another in memory, cpython can use memory pools for allocation, so it's likely that the compiler allocates a pool large enough for all of the objects, then places all of them into that memory pool right after one another

quartz wave
rugged sparrow
#

That's entirely likely

#

Memory allocation is a funky platform dependent thing

#

If you remind me about this in like 2 weeks I can do more investigating

coral sun
#

hi

quartz wave
night quarryBOT
#
Nah.

Sorry, you can't do that here!

coral sun
#

I'm studying fastAPI

quartz wave
#

ok

turbid lodge
#

data compression library, but i can't see the code.. so i will assume its sus

quartz wave
quartz wave
#

<frame>.f_code?

floral meteor
#

!remind @floral meteor 2w remind chilaxan memory allocation investigation

night quarryBOT
#
I'm sorry Dave, I'm afraid I can't do that.

Sorry, you can't do that here!

floral meteor
#

Awwww

#

This channel's the only place I don't ignore pings

quartz wave
#

!e ```py
hing=type('',(),{'bool':lambda s:False not in globals().values()})()
if not hing is False:
print("oh ok")
g = False
if not hing is False:
print("hmm")
else:
print("ok")

night quarryBOT
#

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

001 | oh ok
002 | hmm
quartz wave
#

???

knotty bronze
# coral sun I'm studying fastAPI

fastAPI works by taking advantage of modern web technologies like asyncio and websockets. It is a high-performance web framework that allows developers to build web applications quickly and easily. fastAPI is built on top of the asyncio library, which makes it easy to write asynchronous code.

floral meteor
#

And I think is has precedence over not

#

It's like ==, but for the id of the object pointer

quartz wave
earnest wing
#

yep, not being looser than is is sometimes unexpected

floral meteor
#

if(not hing)is False
is different to
if not hing is False
which is equivalent to
if not(hing is False)

quartz wave
#

!e ```py
hing=type('',(),{'bool':lambda s:False not in globals().values()})()
if (not hing) is False:
print("oh ok")
g = False
if (not hing) is False:
print("hmm")
else:
print("ok")

night quarryBOT
#

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

001 | oh ok
002 | ok
regal meadow
#
def fibonacci():
    """display the fibonacci sequence"""
    a = 1
    b = 0
    c = 0
    termlimit = int(input('What term do you want to go to?\n'))
    if termlimit == 0:
        c = 0
        print('the 0th term in the sequence will be ', c)
    else:
        returnme = []
        n = 0
        while n != termlimit:
           c = a + b
           a = b
           b = c
           returnme.insert(0,c)
           n = n + 1
        print(returnme)
        
"""main function begins here"""
fibonacci()
``` is there anyway I could improve upon this function?
earnest wing
#

remove all the newlines

fleet bridge
sick hound
fleet bridge
#

make FibonacciEnterpriseEdition

sick hound
#

def fib(n): a, b = 0, 1 for _ in range(n): yield a a, b = b, a + b

old socket
#

Indentation is wrong

#

Also how is this esoteric

sick hound
old socket
#

How is that esoteric

#

Also indentation is still wrong

#

you have a non-working fib

royal whale
night quarryBOT
#

@royal whale :white_check_mark: Your 3.11 eval job has completed with return code 0.

[0, 1, 1, 2, 3]
royal whale
#

Not my creation, but significantly more esoteric

sick hound
royal whale
#

Ah. They are truly one of the worthiest of pursuits in Python. They allow confusion to ascend to a new dimension when properly (improperly?) handled.

old socket
#

To ascend lambda is to understand how to use ctypes to curse python

#

code: import ctypes
me:

unreal echo
#

!d curses

night quarryBOT
#

The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.

While curses is most widely used in the Unix environment, versions are available for Windows, DOS, and possibly other systems as well. This extension module is designed to match the API of ncurses, an open-source curses library hosted on Linux and the BSD variants of Unix.

Note

Whenever the documentation mentions a character it can be specified as an integer, a one-character Unicode string or a one-byte byte string.

Whenever the documentation mentions a character string it can be specified as a Unicode string or a byte string.

sick hound
#

print ("dog")

floral meteor
floral meteor
#

I've been looking into string encoding, it somehow makes the data longer

#

it's like there's bits randomly inserted

#

I tried reconstructing a string from its bytes, but about every three or four bytes, a bit seems to be inserted

floral meteor
#

Either that or I somehow reconstructed it wrong

void charm
#

!e print("Lol")

night quarryBOT
#

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

Lol
earnest wing
#

str encoding is adaptive, isn't it?

#

sometimes utf-32, sometimes better

inland axle
#

has anyone ever played with the pypy error messages and just made the dumbest possible fix until it converges to a valid program?

#
pypy3.8
Python 3.8.13 (7.3.9+dfsg-1, Apr 01 2022, 21:41:47)
[PyPy 7.3.9 with GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>> arr = [j for i in a, b for j in i]
  File "<stdin>", line 1
    arr = [j for i in a, b for j in i]
                       ^
SyntaxError: invalid syntax (expected ']')
>>>> arr = [j for i in a], b for j in i]
  File "<stdin>", line 1
    arr = [j for i in a], b for j in i]
                                      ^
SyntaxError: unmatched ']'
>>>> arr = [[j for i in a], b for j in i]
  File "<stdin>", line 1
    arr = [[j for i in a], b for j in i]
                             ^
SyntaxError: invalid syntax (expected ']')
>>>> arr = [[j for i in a], b ]for j in i]
  File "<stdin>", line 1
    arr = [[j for i in a], b ]for j in i]
                                        ^
SyntaxError: unmatched ']'
>>>> arr = [[[j for i in a], b ]for j in i]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined
>>>> i = None
>>>> arr = [[[j for i in a], b ]for j in i]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable
>>>> i = ()
>>>> arr = [[[j for i in a], b ]for j in i]
floral meteor
#

Basically, the int gets possessed by a str so I can turn the string into binary, but confirming it worked shows weird results

#

The int containing data for a str of length 32 should contain length data of \x08, \0, \0, \0, \0, \0, \0, \0

#

Hence that's what's allocated

restive void
earnest wing
restive void
#

(same thing, but officially...)

quartz wave
floral meteor
#

so it's efficienter in memory to not use strings

quartz wave
#

there's the limit that for each digit, the digit must be in range(2**30)

floral meteor
#

!e I found a better way to convert to binary anyway

from ctypes import*
s = "Hello, World!"
b = ''.join(map(lambda x:bin(x)[2:],b''.join((c_char*len(s)).from_address(id(s)+48))))
print(b)
print(eval('0b'+b))
night quarryBOT
#

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

001 | 1001000110010111011001101100110111110110010000010101111101111111001011011001100100100001
002 | 176009217592051565591370017
floral meteor
#

is this a 2**30 base system?

quartz wave
quartz wave
floral meteor
#

whyyyyyy

quartz wave
#

2**30 is size 2 already btw

#

!e ```py
from ctypes import c_ssize_t
def g(x):return c_ssize_t.from_address(id(x)+16)
print(g(0), g(1), g(230), g(260))

night quarryBOT
#

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

c_long(0) c_long(1) c_long(2) c_long(3)
floral meteor
#

!e ```py
from ctypes import*
el_numero = 8**32 - 1
print(c_long.from_address(id(el_numero)+16).value)
print((c_byte32).from_address(id(el_numero)+24))

night quarryBOT
#

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

001 | 4
002 | -1 -1 -1 63 -1 -1 -1 63 -1 -1 -1 63 63 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
floral meteor
#

wait im supposed to do 2**8**32 to get 32 bytes

#

!e ```py
from ctypes import*
el_numero = (2**8)32 - 1
print(c_longlong.from_address(id(el_numero)+16).value)
print(
(c_byte*32).from_address(id(el_numero)+24))

night quarryBOT
#

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

001 | 1
002 | -1 31 0 0 116 127 0 0 1 0 0 0 0 0 0 0 -96 -31 -75 1 116 127 0 0 1 0 0 0 0 0 0 0
floral meteor
#

now why is it saying length data of one when it's huge?

#

and why is a byte in the range -128, 128 instead of unsigned?

quartz wave
#

8191 is so much less than 2**30

floral meteor
#

oh so it's just -1, 31, 0, 0

#

so this 2**30 system is why it acts weird when i try to port data between str and int objects?

floral meteor
#

so what's this 16777216 number doing here?

#

what happens two the last two bits in these c_longs?

#

are they void for interpreter optimisation?

quartz wave
floral meteor
#

i nede more cofe

#

so what happens when i make 4 bytes higher than 1073741823 in an integer memory?

#

does it just ignore the offending two bits on the left? does it ignore any two offending byte start bits?

floral meteor
#

does it corrupt the data?

quartz wave
floral meteor
#

what bits are used to make the 2**30?

quartz wave
#

haven't tested with 2

floral meteor
#

because 4 bytes can fit 32 bits, but each 4 bytes here are 30 bit digits.

#

what two bits is it ignoring?

quartz wave
floral meteor
#

far left?

#

or furthest right c_long, but far left of that?

quartz wave
floral meteor
#

what is happening here?

quartz wave
#

also isn't that just one digit

floral meteor
#

I have summoned an integer from an evil parallel dimension

#

I made a two digit number and made both digits 255

quartz wave
#
>>> a = 2**30-1
>>> c_uint.from_address(id(a)+24).value = -1
>>> a
4294967295
>>> a
4294967295
>>> a+0
4294967295
``` ???
floral meteor
#

but 4294967295+0 = -1

quartz wave
#

even with exactly that code

floral meteor
#

because python math from evil parallel dimension says so

#

*evil cackling*

quartz wave
floral meteor
#

!e ```py
from ctypes import*
el_numero = 2**30-1
(c_long*2).from_address(id(el_numero)+24)[:] = -1,-1
print(repr(el_numero))
print(repr(el_numero+0))

quartz wave
#

what kind of system are you in

#

oh wait

#

run in 3.10

night quarryBOT
#

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

001 | 4294967295
002 | -1
quartz wave
#

so 3.10 has the problem

floral meteor
#

HA!

quartz wave
#

3.11 fixed it but how ๐Ÿค”

floral meteor
#

in the 2**30 system it shouldn't work because all 32 bits are 1

quartz wave
#

!e 3.10 ```py
from ctypes import*
el_numero = 2**30-1
c_uint.from_address(id(el_numero)+24).value = -1
print(repr(el_numero))
print(repr(el_numero+0))

night quarryBOT
#

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

001 | 4294967295
002 | -1
quartz wave
#

you only need to set one digit

floral meteor
#

and that's how i made a string corrupter function a week or two ago

#

using this bug

#

now the function of the corrupter has been explained to me, and now I know exactly 1 in 16 bits of information are lost in the corruption process

quartz wave
floral meteor
#

so unlike a cipher, there's no way to restore the information, as there's 2 possibilities every two characters as to what the original could be?

#

am I mathing this right?

#

or is the loss of information too systematic to be classified as corruption?

quartz wave
floral meteor
#

this is starting to sound like the topic should be called Malware Design 106: Data Corruption.

#

so how do I recover the corrupted data?

quartz wave
floral meteor
#

problem is that the way the corrupter does it, it makes a new object from the +0

#

which is why when I port the bytes back to the str instance, it becomes corrupted

floral meteor
#

!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 3.11 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/ibewonuzam.txt?noredirect

floral meteor
#

nope

#

it's successfully corrupted in 3.11

night quarryBOT
#

Objects/longobject.c lines 3070 to 3072

if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
    return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
}```
quartz wave
night quarryBOT
#

Objects/longobject.c lines 3271 to 3273

if (IS_MEDIUM_VALUE(a) && IS_MEDIUM_VALUE(b)) {
    return _PyLong_FromSTwoDigits(medium_value(a) + medium_value(b));
}```
floral meteor
#

it should either look fine or look completely different, not like some echo of the original crying for help

languid hare
#

i like it

#

it's like the warning at the entrance of a cursed tomb

floral meteor
night quarryBOT
#

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

Yaa+pv b'G%s v/xs 4p c5sse any"pdy who wou,e o0fn 4iis gra6f, 3p n/cod9!wi,m o0fn )u. 60 y%brs old.
royal whale
long hamlet
#

Fractal rendered under 2 sec with pure python

versed eagle
#

esoteric how

royal whale
#

It's neat but off-topic

long hamlet
royal whale
versed eagle
rapid sparrow
long hamlet
versed eagle
#

allow me to rephrase then
it may be esoteric from a math standpoint, but that doesn't make it esoteric python

#

as such, this isn't the right channel for it

quartz wave
versed eagle
#

true but we can at least try to keep it organized

#

:P

haughty sapphire
#
class Myclass(type):
  pass

quartz wave
versed eagle
#

that's not valid python
locals()[""] for locals()[""] in

#

also locals()[""] doesn't exist

#

unless you're doing some sort of trickery

#

but what you're doing is creating a function object

#

using a bytes object

#

and _basicsize_ of something that I dont think exists

quartz wave
#

!e ```py
n=512;print((lambda:0).class(compile([*[locals()['']for locals()['']in[[].len().class.class.base.subclasses()[2+2+({}!=[])]]][0].dict.values()]locals()[''].basicsize-"####".count('#'),'','eval'),locals())())

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | KeyError: ''
quartz wave
#

ok

#

!e ```py
n=512;print((lambda:0).class(compile([*[globals()['']for globals()['']in[[].len().class.class.base.subclasses()[2+2+({}!=[])]]][0].dict.values()]globals()[''].basicsize-"####".count('#'),'','eval'),globals())())

night quarryBOT
#

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

512
quartz wave
#

@versed eagle how about now

#

anything??

versed eagle
#

give me a moment I'm on mobile

quartz wave
#

oh i found the problem

versed eagle
#

how does globals()[""] work

quartz wave
versed eagle
#

it shouldn't

quartz wave
versed eagle
#

I'm confused

quartz wave
#

you should be

#

!e ```py
n=512;print((lambda:0).class(compile([*[s['']for (s:=[].class.class.base.subclasses()[108].create_module.globals['sys']._getframe(1).f_locals)['']in[[].len().class.class.base.subclasses()[2+2+({}!=[])]]][0].dict.values()]locals()[''].basicsize-"####".count('#'),'','eval'),globals())())

versed eagle
#

you can't give a var that name

old socket
#

Is this supposed to happen?

night quarryBOT
#

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

001 |   File "<string>", line 1
002 | SyntaxError: comprehension inner loop cannot rebind assignment expression target 's'
quartz wave
versed eagle
#

without assigning to globals directly

#

*afaik

quartz wave
versed eagle
#

how

quartz wave
#

๐Ÿคท

versed eagle
#

then how does your code work

quartz wave
#

it just does

#

!e ```py
n=512;print((lambda:0).class(compile([*[[].class.class.base.subclasses()[108].create_module.globals['sys']._getframe(1).f_locals['']for [].class.class.base.subclasses()[108].create_module.globals['sys']._getframe(1).f_locals['']in[[].len().class.class.base.subclasses()[2+2+({}!=[])]]][0].dict.values()]locals()[''].basicsize-"####".count('#'),'','eval'),globals())())

night quarryBOT
#

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

512
versed eagle
#

I'm so confused

old socket
#

What's it even supposed to do

versed eagle
#

but, here's a somewhat deobfuscated version

#

!e

n=512;print((lambda:0).__class__(compile([*[globals()['']for globals()['']in[bytes]][0].__dict__.values()][globals()[''].__basicsize__-4](globals()[''],'6e20616e6427272e6a6f696e285b6368722834382b6e2f2f31302a2a6925313029666f72206920696e2072616e6765285f5f696d706f72745f5f28226d61746822292e6c6f673130286e292e5f5f7472756e635f5f28292b31295d2e5f5f72657665727365645f5f2829296f72273027'),'','eval'),globals())())โ€Š
night quarryBOT
#

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

512
versed eagle
#

is less obfuscated

#

slightly

quartz wave
versed eagle
#

no

#

I understand the parts I removed

quartz wave
versed eagle
#

but I didn't touch the stuff I didn't understand

#

I didn't wanna break it

quartz wave
#

btw the printed 512 isn't a number

versed eagle
#

!e

n=512;print(type((lambda:0).__class__(compile([*[globals()['']for globals()['']in[bytes]][0].__dict__.values()][globals()[''].__basicsize__-4](globals()[''],'6e20616e6427272e6a6f696e285b6368722834382b6e2f2f31302a2a6925313029666f72206920696e2072616e6765285f5f696d706f72745f5f28226d61746822292e6c6f673130286e292e5f5f7472756e635f5f28292b31295d2e5f5f72657665727365645f5f2829296f72273027'),'','eval'),globals())()))
night quarryBOT
#

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

<class 'str'>
versed eagle
#

huh

quartz wave
#

!e this is the absolute deobfuscation ```py
n=512;print(f"{n}")

night quarryBOT
#

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

512
versed eagle
#

im just gonna accept that you're a hyperdimensional magic being and try to not have a headache over this

quartz wave
versed eagle
#

True but very few people are active here

quartz wave
versed eagle
#

with hedge and fork also being there sometimes

old socket
#

Probably

versed eagle
#

and then I'm bumbling about just learning about fishhook like two days ago Lmao

#

my brain isn't ready for this stuff

quartz wave
versed eagle
#

oh yeah I saw lim

#

chilaxan is the one who made fishhook right?

quartz wave
#

also very knowledgeable about python internals

vague cairn
#

When the weather is this hot, I'm brain dead by the time I get home from work, so during this season I mostly lurk or do slightly less mentally taxing things. I'm not gone. Just quieter than at other times.

#

I'm still thankful for the puzzlers that other people are putting out there.

floral meteor
#

I code crazier and more often when it's hot

#

It's colder at this time of year down in this hemisphere.

earnest wing
#

I read every message here

#

๐Ÿ‘ป

lyric fern
#

...

earnest wing
#

Can you fetch all the defined operator strings (binary, unary, boolean, in place, ...) at runtime?

plucky plover
#

!d token

night quarryBOT
#

Source code: Lib/token.py

This module provides constants which represent the numeric values of leaf nodes of the parse tree (terminal tokens). Refer to the file Grammar/Tokens in the Python distribution for the definitions of the names in the context of the language grammar. The specific numeric values which the names map to may change between Python versions.

The module also provides a mapping from numeric codes to names and some functions. The functions mirror definitions in the Python C header files.

plucky plover
#

this?

earnest wing
#

there's tokens that aren't operators

#

tbf at tokenization time python shouldn't expose operator specific info since there's ambiguity

#

e.g. * is not just an operator

#

I was looking in ast but couldn't find any public api

#

horrible idea: scrape the documentation of operator functions to fetch the op strings BABAXD

plucky plover
#

or parse the sphinx inventory file

earnest wing
#

or fetching the operator classes from ast and unparsing them

earnest wing
#

!e ```py
import ast
import tokenize

tokens = []
for token in tokenize.EXACT_TOKEN_TYPES:
try:
x = ast.parse(f"a {token} b")
except SyntaxError:
continue
match x.body[0]:
case ast.Expr(ast.BinOp() | ast.BoolOp() | ast.UnaryOp() | ast.Compare()) | ast.AugAssign():
tokens.append(token)
print("lol", tokens)

night quarryBOT
#

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

lol ['!=', '%', '%=', '&', '&=', '*', '**', '**=', '*=', '+', '+=', '-', '-=', '/', '//', '//=', '/=', '<', '<<', '<<=', '<=', '==', '>', '>=', '>>', '>>=', '@', '@=', '^', '^=', '|', '|=']
earnest wing
#

there's binary ones ig

#

except without the keyword operators

#

so not many at all tbh

floral meteor
#

I discovered new error

#

i used alt-f4 on a program using multiprocessing, now i can't rerun it lol

royal whale
#

What is this sorcery?

restive void
#

!e doesn't throw SyntaxError:

lambda: a @ b
night quarryBOT
#

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

[No output]
restive void
#

!pep 465

night quarryBOT
#
**PEP 465 - A dedicated infix operator for matrix multiplication**
Status

Final

Python-Version

3.5

Created

20-Feb-2014

Type

Standards Track

royal whale
earnest wing
#

I've been considering making a library for the following:

import functools
def xor(left, right):
    return (left or right) and not (left and right)

assert (==)(True `xor` True, False)
#

haskell-style conversions between infix and prefix functions

#

the implementation itself is fairly simple (just a token transformation + partial expression parser), but I have a problem:

#

I want to do this through a codec (# coding: operator-syntax or something), but it would need to be registered before your code is parsed

#

So is there a proper way for a library to register a codec before any code runs? Maybe using PYTHONPATH?

#

Maybe by monkeypatching the standard library somehow? twitchsmile

#

(I'm posting here because this is definitely something you shouldn't be doing BABAXD)

astral rover
#

I mean lambda managed it

#

With import experessions

earnest wing
#

Oh good point

#

I'll see how that repo does it

#

Oh no is it .pth files SDVpufferfear

#

oh no

#

python packaging is such a hopeless mess, i love it

versed eagle
earnest wing
#

nope, that's different

#

clearer example:

def to(left, right):
    return right(left)

assert -1 `to` abs == 1
versed eagle
#

huh?

#

what

#

what are the backticks doing here

#

and to is a function, but you aren't calling it?

#

do you mean something like this?

def to(left, right):
    return right(left)

assert to(-1, abs) == 1
earnest wing
#

nope, I mean exactly what I wrote :>

#

that's the whole point of what I'm making :>

versed eagle
#

im confused

unreal echo
#

!pypi libCST

night quarryBOT
#

A concrete syntax tree with AST-like properties for Python 3.5, 3.6, 3.7, 3.8, 3.9, and 3.10 programs.

unreal echo
#

you ever wonder why god is in heaven?

#

because this channel is on earth

unreal echo
night quarryBOT
#

@unreal echo :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 1, in <lambda>
004 | TypeError: unsupported operand type(s) for @: 'int' and 'int'
unreal echo
#

WHATTTT

tidal canyon
#

hello increasingly verbose Python

quartz wave
quartz wave
tidal canyon
#

ho

#

hi

restive void
night quarryBOT
#

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

42
royal whale
tulip harbor
#

Anyone familiar with how to debug lower level socket behavior? On MacOS 12.4 running python3.9.10, sockets hang for quite some time before completing. If I run the same code in either a curl format, OR on a Ubuntu machine, the timings are what I would expect.
Exs:

In [55]: %time requests.get('https://www.google.com/')
CPU times: user 14.9 ms, sys: 5.23 ms, total: 20.1 ms
Wall time: 1min 15s
Out[55]: <Response [200]>

Curl:

$ time curl -s "https://www.google.com/" > /dev/null
curl -s "https://www.google.com/" > /dev/null  0.01s user 0.01s system 4% cpu 0.504 total
unreal echo
#

does this count?

#
stairs = lambda c,t: map(lambda i:'\n'+i*' '+(t-i)*c,range(t,-1,-1))
print(*stairs('#',5))```
#

i don't think it does

#

it's pretty readabe

#

just golfed

serene stratus
tulip harbor
#

But Esoteric: intended for or likely to be understood by only a small number of people with a specialized knowledge or interest.

earnest wing
bronze agate
versed eagle
#

!e

# here's my version
# I call it the pyramid scheme
# not golfed but imo done in a fun way
@(lambda _:(lambda __,___:map((lambda _____:_____*" "+(___-_____)*__+"\n"),range(___,-1,-1))))
def stairs(c,d):...
print(*stairs("$",5))
night quarryBOT
#

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

001 |      
002 |      $
003 |     $$
004 |    $$$
005 |   $$$$
006 |  $$$$$
versed eagle
night quarryBOT
#

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

001 | 
002 |       
003 |     # 
004 |    ## 
005 |   ### 
006 |  #### 
007 | #####
versed eagle
#

golfed?

restive void
#

!e

print("\n".join(f"{'#'*n: >5}"for n in range(6)))
night quarryBOT
#

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

001 |      
002 |     #
003 |    ##
004 |   ###
005 |  ####
006 | #####
finite blaze
#

'#'*n: >5

#

whats going on here?

#

nvm, I see now

#

!e

for n in range(6):print(f"{'#'*n:>5}")
night quarryBOT
#

@finite blaze :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 |      
002 |     #
003 |    ##
004 |   ###
005 |  ####
006 | #####
quartz wave
floral meteor
#
for _ in range(6):print(f"{'#':>{_}}")
fleet bridge
#

!e idk why

print(*map('\n'.__add__, map(lambda x: eval('x.__name__'), (type('#'*_,(),{}) for _ in range(10)))))
night quarryBOT
#

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

001 | 
002 |  
003 | # 
004 | ## 
005 | ### 
006 | #### 
007 | ##### 
008 | ###### 
009 | ####### 
010 | ######## 
011 | #########
fleet bridge
#

!timeit

import gc
gc.collect()
(*map('\n'.__add__, map(lambda x: eval('x.__name__'), (type('#'*_,(),{}) for _ in range(1000)))),)
night quarryBOT
#

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

20 loops, best of 5: 18.9 msec per loop
floral meteor
night quarryBOT
#

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

001 |  
002 | # 
003 | ## 
004 | ### 
005 | #### 
006 | ##### 
fleet bridge
#

!e

print('''#
 #
  #
   #
    #''')
night quarryBOT
#

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

001 | #
002 |  #
003 |   #
004 |    #
005 |     #
fleet bridge
#

the best

floral meteor
#

I right aligned lol I'm dum

quartz wave
#

!e```py
for n in range(6):print(f"{' ':#^{n+1}}")

#

ok

night quarryBOT
#

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

001 |  
002 |  #
003 | # #
004 | # ##
005 | ## ##
006 | ## ###
floral meteor
#

!e ```py
for n in range(1,7):print(f"{' ':#<{n}}")

night quarryBOT
#

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

001 |  
002 |  #
003 |  ##
004 |  ###
005 |  ####
006 |  #####
floral meteor
#

I'm typing on phone, don't judge

#

!e for n in range(1,7):print(f"{' '*(6-n):#<{n//2+5}}")

night quarryBOT
#

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

001 |     #
002 |    ###
003 |   ####
004 |  ######
005 | #######
006 | ########
floral meteor
#

Eh idk

#

!e for n in range(6):print(' '(5-n),n'#')

night quarryBOT
#

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

001 |       
002 |      #
003 |     ##
004 |    ###
005 |   ####
006 |  #####
wheat apex
#

!e 3.10

for i in range(5):
     print("#"*((i+1)**2))
night quarryBOT
#

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

001 | #
002 | ####
003 | #########
004 | ################
005 | #########################
wheat apex
#

!e 3.10

for i in range(20):
     print("#"*((i+1)**2))
night quarryBOT
#

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

001 | #
002 | ####
003 | #########
004 | ################
005 | #########################
006 | ####################################
007 | #################################################
008 | ################################################################
009 | #################################################################################
010 | ####################################################################################################
011 | #########################################################################################################################
... (truncated - too many lines)

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

wheat apex
#

wow

#

!e 3.10

for i in range(5):
     print((1 + round(0.25*i)) * "#")
night quarryBOT
#

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

001 | #
002 | ##
003 | ###
004 | ####
005 | #####
wheat apex
#

!e 3.10

for i in range(5):
     print((i + 1 + round(0.49*i)) * "#")
night quarryBOT
#

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

001 | #
002 | ##
003 | ####
004 | #####
005 | #######
floral meteor
#

!e hiding a variable inside a function. ```py
f=lambda n=[0]:n.setitem(0,n[0]+1)or n[0];print('\n'.join([(5-n)' '+'#'(2*n-1)for n in iter(f,6)]))

night quarryBOT
#

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

001 |     #
002 |    ###
003 |   #####
004 |  #######
005 | #########
floral meteor
#

I feel like I made a ```py
def state_iterator(initial_state, halting_state, step_function):
return iter(lambda state=[initial_state]:state.setitem(0,step_function(*state))or state[0],halting_state)

#

which could make something as basic as ```py
def range(*args):
start, stop, step = args[0]if len(args)>1 else 0,args[0]if len(args)==1 else args[1],args[2]if len(args)>2 else 1
return state_iterator(start, stop, lambda x:x+step)

#

or any state machine.

#

!e iter can be used for a breaking condition when iterating ```py
print(*iter(range(16).iter().next,8))

night quarryBOT
#

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

0 1 2 3 4 5 6 7
floral meteor
#

!e here's a possibly unnecessarily complicated fibonacci script to ruin your day. ```py
def state_iterator(initial_state, halting_state, step_function): return iter(
lambda state=[initial_state]:state.setitem(0,step_function(*state))or state[0],
halting_state
)

class HaltingState:
def init(self, f):self.f=f
def eq(self, k):return not not self.f(k)

fib = lambda maximum, init_state=[1,0]:state_iterator(
init_state[0], HaltingState(lambda k:k>=maximum),
lambda a,b = init_state[1:]: (b[0],b.setitem(0,a+b[0]))[0]
); *map(print,fib(69)),

night quarryBOT
#

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

001 | 0
002 | 1
003 | 1
004 | 2
005 | 3
006 | 5
007 | 8
008 | 13
009 | 21
010 | 34
011 | 55
floral meteor
#

!e and here's a relatively nicer one. ```py
fib = lambda n:map(lambda _,a=[0,1]:(a[0],a.setitem(slice(0,2),(a[1],a[0]+a[1])))[0],range(n))
print(*fib(8))
print(*fib(16))

night quarryBOT
#

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

001 | 0 1 1 2 3 5 8 13
002 | 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
worldly trail
#

!e

import ctypes,sys;_=list(zip(list([str(_) for _ in range(4)[1:]]), [_ for _ in range(4)[1:]]));sys.stdout.write(str(ctypes.cast(int(hex(id(_)),base=16),ctypes.py_object).value))
night quarryBOT
#

@worldly trail :white_check_mark: Your 3.11 eval job has completed with return code 0.

[('1', 1), ('2', 2), ('3', 3)]
worldly trail
#

Is it possible longer? ๐Ÿ™‚

serene stratus
#

Wdym longer

lyric fern
#

!e

print(True**False/True*True//True*False+1-True)
night quarryBOT
#

@lyric fern :white_check_mark: Your 3.11 eval job has completed with return code 0.

0.0
lyric fern
#

!e

true = True 
false = False

a = True

if a == true:
    print(true)
else:
    print(false)
night quarryBOT
#

@lyric fern :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
restive void
#

!e

true, false, null = True, False, None
class json:
    loads = eval

print(json.loads('{"some": true, "thing": null, "24": [2,1,3]}'))
night quarryBOT
#

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

{'some': True, 'thing': None, '24': [2, 1, 3]}
maiden blaze
#

tsk tsk

pastel sparrow
#

...that feels illegal

sick hound
#

Well of course that isn't completely the same

last locust
sick hound
#
{
    "some": true,
}

Is invalid

#

But it would be accepted as a python dict itself when evaluated like that

restive void
wheat river
#

aint no one cares about json syntax

earnest wing
#

Is it actually superset of JSON parsers?

#

Like, assuming UTF-8?

restive void
earnest wing
#

right, \/ etc parse differently

restive void
#

That, and I think surrogate characters?

earnest wing
#

lone surrogates don't parse in python?

restive void
#

They do, but surrogates are just those codepoints, so you will never get the "real" character back.

> "\ud83c\udf09"
'๐ŸŒ‰'
>>> "\ud83c\udf09"
'\ud83c\udf09'
>>> print("\ud83c\udf09")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'utf-8' codec can't encode characters in position 0-1: surrogates not allowed
#

!e vs.

import json
print(json.loads(r'"\ud83c\udf09"'))
night quarryBOT
#

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

๐ŸŒ‰
sick hound
#

Better way of doing this?

#
    if song.lower() in data['eras']['wod']:
        print("From wod")
    elif song.lower() in data['eras']['drfl']:
        print("from drfl")
    elif song.lower() in data['eras']['gbgr']:
        print("From gbgr")
    elif song.lower() in data['eras']['outsiders']:
        print("From outsiders")
    elif song.lower() in data['eras']['juicethekidd']:
        print("From juicethekidd")
    elif song.lower() in data['eras']['nineninenine']:
        print("From nineninenine")
    else:
        print("song not in database")
quartz wave
sick hound
#

I meant a better easier way not completely mind boggling ๐Ÿคฃ

quartz wave
sick hound
#

Also that returns all the songs in the era not the actual era

restive void
sick hound
sick hound
#

What does map do?

restive void
#

How about:

#

!e

data = {
    "eras": {
        "wod": ["a wod song", "another wod song"],
        "gbgr": ["sounds grumpy"],
    }
}


for song in ("unknown song", "A WOD song", "sounds GrUmPy"):
    v = eval(' or '.join(f"song.lower() in data['eras']['{c}'] and '{c}'" for c in ("wod","gbgr")))
    print(v and f"From {v}" or "song not in database")
night quarryBOT
#

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

001 | song not in database
002 | From wod
003 | From gbgr
quartz wave
#

map(a, (b, c, d)) is just a short way of doing [a(x) for x in (b, c, d)]

#

except it returns a generator

burnt pasture
quartz wave
#

yeah actually it's more like that

fleet bridge
#

map is a lot faster than generator-comprehension

#

because comprehensions are compiled to bytecode and map is implemented in C

#

also map better fits for this channel because you can do something funny like map(1.__radd__, a) instead of (x+1 for x in a)

burnt pasture
fleet bridge
#

comprehensions (and for-loops) can unpack values: for (k, v) in d.items()
map cannot

burnt pasture
#

perhaps it depends if the comprehension is also invoking a function

fleet bridge
burnt pasture
#

also, those two things aren't equivalent

#

oops, they are

fleet bridge
#
>py -m timeit -s "a = [*range(1000)]" "list((x+1 for x in a))"
5000 loops, best of 5: 55.2 usec per loop

>py -m timeit -s "a = [*range(1000)]" "list(map(1 .__radd__, a))"
10000 loops, best of 5: 36.8 usec per loop
burnt pasture
#

cool

fleet bridge
#

if i want to do (f(x * 2 + 1) for x in a) with map, i must nest a lot of maps:
map(f, map(1 .__radd__, map(2 .__rmul__, a)))

#

in this case map is slower (i guess)

burnt pasture
fleet bridge
#
C:\Users\denba>py -m timeit -s "a = [*range(1000)]; f = lambda x: x * 0.5" "list(map(f, map(1 .__radd__, map(2 .__rmul__, a))))"
2000 loops, best of 5: 140 usec per loop

C:\Users\denba>py -m timeit -s "a = [*range(1000)]; f = lambda x: x * 0.5" "list((f(x*2 + 1) for x in a))"
2000 loops, best of 5: 148 usec per loop

hmm, almost no differense

#

also list((generator compr)) is slower than [list compr]

#

!timeit

a = [*range(10**4)]; f = lambda x: x - 2
``` ```py
list((f(x*2 + 1) for x in a))
night quarryBOT
#

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

200 loops, best of 5: 1.49 msec per loop
fleet bridge
#

!timeit

a = [*range(10**4)]; f = lambda x: x - 2
``` ```py
[f(x*2 + 1) for x in a]
night quarryBOT
#

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

200 loops, best of 5: 1.24 msec per loop
fleet bridge
#

!timeit

a = [*range(10**4)]; f = lambda x: x - 2
``` ```py
list(map(f, map(1 .__radd__, map(2 .__rmul__, a))))
night quarryBOT
#

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

100 loops, best of 5: 2.3 msec per loop
fleet bridge
#

!timeit

a = [*range(10**4)]; f = lambda x: x - 2
``` ```py
[*map(f, map(1 .__radd__, map(2 .__rmul__, a)))]
night quarryBOT
#

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

100 loops, best of 5: 2.29 msec per loop
fleet bridge
#
  1. list-comp (1.24 msec)
  2. list(gen-compr) (1.49 msec)
  3. [*map] (2.29 msec)
  4. list(map) (2.30 msec)
burnt pasture
fleet bridge
#

sometimes i do this optimizations, its funny

#

nested maps are challenging to write and challenging to read, I enjoy it

#
C:\Users\denba>py -m timeit -s "a = [*range(10**4)]" "list((str(x) for x in a))"
200 loops, best of 5: 1.11 msec per loop

C:\Users\denba>py -m timeit -s "a = [*range(10**4)]" "list(map(str, a))"
500 loops, best of 5: 742 usec per loop
#

i think i get the rule:

  • 1 map is faster than list-compr
  • 2 maps are (almost) the same as list-compr
  • 3 maps and more alre slower than list-compr
#
C:\Users\denba>py -m timeit -s "a = [*range(10**4)]" "list(map(int, map(str, a)))"
200 loops, best of 5: 1.48 msec per loop

C:\Users\denba>py -m timeit -s "a = [*range(10**4)]" "list((int(str(x)) for x in a))"
200 loops, best of 5: 1.88 msec per loop

C:\Users\denba>py -m timeit -s "a = [*range(10**4)]" "[int(str(x)) for x in a]"
200 loops, best of 5: 1.68 msec per loop
#

important note: im using cpython 3.10

#

only creation of map and generator:```py
C:\Users\denba>py -m timeit -s "a = [*range(10**4)]" "(int(str(x)) for x in a)"
1000000 loops, best of 5: 208 nsec per loop

C:\Users\denba>py -m timeit -s "a = [*range(10**4)]" "map(int, map(str, a))"
2000000 loops, best of 5: 163 nsec per loop

#

I think I've flooded this channel enough

quartz wave
#

!e ```py
a = range(0, 20, 2)
b = range(10)
print(*map(lambda x, y: x + y, a, b))

night quarryBOT
#

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

0 3 6 9 12 15 18 21 24 27
fleet bridge
#

TIL: map can accept more than one iterable

#
C:\Users\denba>py -m timeit -s "a = [*range(10**4)]; b = [*range(0, 2*10**4, 2)]" "[a + b for a, b in zip(a, b)]"
500 loops, best of 5: 423 usec per loop

C:\Users\denba>py -m timeit -s "a = [*range(10**4)]; b = [*range(0, 2*10**4, 2)]" "map(int.__add__, a, b)"
2000000 loops, best of 5: 118 nsec per loop

C:\Users\denba>py -m timeit -s "a = [*range(10**4)]; b = [*range(0, 2*10**4, 2)]; add = __import__('operator').add" "map(add, a, b)"
5000000 loops, best of 5: 93.5 nsec per loop

hmm, i expect 3-rd example to be slower than 2-nd
why operator.add is faster than int.__add__?

#

ok, i forgot to iterate over map ๐Ÿ˜ƒ

C:\Users\denba>py -m timeit -s "a = [*range(10**4)]; b = [*range(0, 2*10**4, 2)]; add = __import__('operator').add" "[*map(add, a, b)]"
1000 loops, best of 5: 311 usec per loop

C:\Users\denba>py -m timeit -s "a = [*range(10**4)]; b = [*range(0, 2*10**4, 2)]" "[*map(int.__add__, a, b)]"
500 loops, best of 5: 524 usec per loop
#

operator.add(a, b) - 311 usec
a + b - 423 usec
int.__add__(a, b) - 524 usec

i expect int.__add__ to be faster than operator.add, and operator.add to be faster than a + b

night quarryBOT
#

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

hello world
versed eagle
#

!e

(lambda ____:[_:=(lambda:[].__class__.__base__.__subclasses__().__getitem__([[{}]].__mul__([[[{}]]].__str__().__len__()).__str__().__len__().__sub__([[]].__len__().__bool__()).__xor__([[]].__str__().__len__()))())].__add__([__:=_().__str__().__mul__(_())]).__add__([___:=__import__([___:=([___:=_().__invert__().__neg__()].__add__([___:=___.__lshift__(___)]).__add__([___:=___.__lshift__(___)]).__add__([___:=___.__lshift__(___.__sub__(_().__invert__().__neg__().__invert__().__neg__()))]).__add__([___:=___.__or__(___.__floordiv__(_().__invert__().__neg__().__invert__().__neg__()))]).__add__([___:=___.__add__(___.__floordiv__([].__str__().__len__().__add__({}.__str__().__len__()).__add__(_().__invert__().__neg__().__add__(_().__invert__().__neg__()))))]).__add__([___:=___.__sub__([[]].__str__().__len__())]).__add__([__builtins__.__dir__().__str__().__getitem__(___.__add__(_().__invert__().__neg__())).__add__(__builtins__.__dir__().__str__().__getitem__(___)).__add__(__builtins__.__dir__().__str__().__getitem__(___.__add__(_().__invert__().__neg__())))])).__getitem__(_().__invert__())].__getitem__(_().__invert__()))]).__getitem__(_().__invert__()).__stdout__.__getattribute__(___.__stdout__.__dir__().__getitem__(_().__invert__().__neg__().__lshift__(_().__invert__().__neg__()).__lshift__(_().__invert__().__neg__().__lshift__(_().__invert__().__neg__())).__add__(_().__invert__())))(____))("hello world")
night quarryBOT
#

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

hello world
versed eagle
#

i have done a hello world

vague cairn
night quarryBOT
#

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

["(0, '1')", "(1, '2')", "(2, '3')", "(3, '4')", "(4, '5')", "(5, '6')", "(6, '7')", "(7, '8')", "(8, '9')", "(9, '10')"]
vague cairn
#

Oh, I misunderstood what you were talking about.

#

Yeah, you're right.

quartz wave
# versed eagle !e ```python (lambda ____:[_:=(lambda:[].__class__.__base__.__subclasses__().__g...

!e ```py
(((:=(:=().class.base.subclasses().getitem(((____:=(:=().class.itemsize)).add()).mul(_______:=(:=.sub(:=((),).len().invert().neg()))).add(.add()))).dict).getitem((:=().class(builtins.dict).getitem)(.mul(.add())).add((:=loader.module.getitem(:=().len())).add(builtins.repr().getitem(builtins.dict.getitem((.pow().add(.add(:=.invert().neg()))))(_____,.add(_____))))))(:=__.getitem(().class(loader.dict).getitem(:=.invert().neg().invert())).wrapped(,(_____:=loader.doc.getitem)().add(()).add((:=(:=__.mul(:=.neg()))).add()).add((.sub().mul().add())).getattribute((:=().class(loader.name.class.dict).getitem)())(((:=.add()),)))),).mul((.sub())).add((.getattribute(name.getattribute((.add(.add(.add()))))()),))).getitem(.sub())()

night quarryBOT
#

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

Hello world!
quartz wave
#

only parentheses, no constant strings, no constant integers, no constant booleans, only names with underscores, and no operators (except for :=)

earnest wing
#

and you don't need a walrus either if you just inline everything twitchsmile

#

and you don't need tuple literals either if you're using dunder methods twitchsmile

vital dirge
#

Hello all. Ah, one of my favorite channels on this server. So entertaining, these uses and mis-uses of decorators and lambdas.

vital dirge
floral meteor
#

!e ```py
from fishhook import hook
@hook(tuple)
def call(self, f, *g):
r = f(*self)
if g:return self.class.call((r,),*g)
else:return r

(6,9)(lambda x,y:10*x+y,lambda x:x,print)

night quarryBOT
#

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

001 | <string>:8: SyntaxWarning: 'tuple' object is not callable; perhaps you missed a comma?
002 | 69
floral meteor
#

!e 3.10

from fishhook import hook
@hook(tuple)
def __call__(self, *args):
  for f in self:args = f(*args),
  try:arg,=args
  except:return args
  else:return arg

() (lambda x,y:x*10+y,lambda x:x+1,print) (6,8)
night quarryBOT
#

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

001 | <string>:9: SyntaxWarning: 'tuple' object is not callable; perhaps you missed a comma?
002 | 69
floral meteor
#

callable tuples to replace
a = f(e(d(c(b(*args)))))
with
a = (b,c,d,e,f)(*args)

versed eagle
#

wait
,=?

#

since when is that a thing

floral meteor
#

since a long time ago

versed eagle
#

oh is it tuple unpack

floral meteor
#

made specifically for single-element tuples

versed eagle
#

I thought it was augm assign with comma

#

at first

floral meteor
night quarryBOT
#

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

001 | 1 2 3
002 | 4 5
floral meteor
#

no reason why it shouldn't work in 3.11

versed eagle
versed eagle
floral meteor
#

is a user created package, not builtin

versed eagle
#

yeah i know

#

but still

floral meteor
#

packages are like DLCs in games. fishhook is like a modding system

versed eagle
#

yes
ik
but still, it's weird that it's installed on 1 but not the other

floral meteor
#

ctypes is like cheat codes

versed eagle
floral meteor
#

idk

#

haven't installed it yet

versed eagle
#

() (lambda...

floral meteor
#

literally nothing

#

works without it, works with it

versed eagle
#

huh

raw sparrow
#

Print('hel')

#

Wot

#
print('hel')
floral meteor
#

what is this?

raw sparrow
#

Idk

#

Im just borred because i want h3elp

#

And im messing aorund because in 1- mins imma go out

#

10

floral meteor
#

!e try torturing python like ```py
import ctypes
ctypes.c_long.from_address(id(4)+24).value += 1
print( 2 + 2 )

night quarryBOT
#

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

5
raw sparrow
#

!e

night quarryBOT
#
Missing required argument

code

#
Command Help

!eval [python_version] <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.

By default your code is run on Python's 3.11 beta release, to assist with testing. If you run into issues related to this Python version, you can request the bot to use Python 3.10 by specifying the python_version arg and setting it to 3.10.

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

raw sparrow
#

!e

print('hello world')
#

OMG

#

oh right

#

I can't sned it

#

It's a very long message

night quarryBOT
#

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

hello world
floral meteor
#

but also remember this isn't #bot-commands this is just for python torture

edgy lava
#

guyzz , my mandelbrot render

#

where is the channel for maths related stuff btw?

floral meteor
#

depends how esoteric it is.

#

I'd say math stuff is esoteric as many avoid mathematics.

floral meteor
#

!e 3.10

from ctypes import py_object
class Variable:
  def __init__(self, name):self.s=self.__name__=name;self.names={name}
  def __repr__(self):return self.s
  def __str__(self):return self.s
  def make_function(self):
    return eval(f'lambda {", ".join(self.names)}:{self!r}')
  def __call__(self, *a, **k):return self.make_function()(*a, **k)
  def __mul__(self, other):
    a, b = self.s!=self.__name__,type(other)==__class__
    self.s = f"{'('*a}{self!r}{')'*a}*{'('*b}{other!r}{')'*b}"
    if b:self.names|=other.names
    return self
  def __rmul__(self, other):
    a, b = self.s!=self.__name__,type(other)==__class__
    if b:other.names|=self.names;return self
    else:
      self.s=f"{other!r}*{'('*a}{self!r}{')'*a}"
      b and self.names.__ior__(other.names);return self
  def __add__(self, other):
    a, b = self.s!=self.__name__,type(other)==__class__
    if b:self.names|=other.names
    self.s = f"{'('*a}{self!r}{')'*a}+{'('*b}{other!r}{')'*b}"
    return self
  def __radd__(self, other):
    a, b = self.s!=self.__name__,type(other)==__class__
    if b:other.names|=self.names;return self
    else:
      self.s=f"{other!r}+{'('*a}{self!r}{')'*a}"
      b and self.names.__ior__(other.names);return self
  ...

class Dict(dict):
  def __missing__(self, key):
    import builtins
    try:return builtins.__dict__[key]
    except:return Variable(key)

py_object.from_address(id(globals())+8).value = Dict

y = (10*x+9)
print(f"y = {y!r}")
print(y(x=6))
night quarryBOT
#

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

001 | y = (10*x)+9
002 | 69
floral meteor
#

I made algebra.

edgy lava
#

Nice

floral meteor
#

... denotes a fuckton of dunders I didn't bother implementing but pretend they exist.

#

someone here probably knows how to simplify this using tokens

#

as for brackets around an operation that already has precedence, that requires implementation of order of operations.

#

@edgy lava an fun project would be adding an implementation to Variable such that

  def __getattribute__(self, attr):
    getattr = object.__getattribute__
    if attr[0]=='d':
      d, varname = attr
      return __class__.integrate(varname)
    else:return getattr(self, attr)

...

y = 3*x + 4
Y = y.dx
print(Y) # (3*x**2)/2 + 4*x + c

and add a modification to globals for variables starting with d such that

y = 3*x + 4
y_ = dy/dx
print(y_) # 3
#

a package somewhere has gotta implement integration and deriving.

unreal echo
#
print(*map(lambda x: (x[0], *x[1]), zip((0 for i in [[1,2],[3,4],[5,6]]), [[1,2],[3,4],[5,6]])))``` tbh when i come up with a one liner for someones problem i just cross post it here
fleet bridge
#

!e

print(*map(lambda x: (x[0], *x[1]), zip((0 for i in [[1,2],[3,4],[5,6]]), [[1,2],[3,4],[5,6]])))
night quarryBOT
#

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

(0, 1, 2) (0, 3, 4) (0, 5, 6)
fleet bridge
#

!e

print(*map((0,).__add__, map(tuple, [[1,2],[3,4],[5,6]])))
night quarryBOT
#

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

(0, 1, 2) (0, 3, 4) (0, 5, 6)
kindred needle
#

!e

print(*[tuple([0]+list(range(7))[i:i+2]) for i in range(1, 7, 2)])
night quarryBOT
#

@kindred needle :white_check_mark: Your 3.11 eval job has completed with return code 0.

(0, 1, 2) (0, 3, 4) (0, 5, 6)
pastel sparrow
#

!e

print(*[(0,*t)for t in[[1,2],[3,4],[5,6]]])
night quarryBOT
#

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

(0, 1, 2) (0, 3, 4) (0, 5, 6)
edgy lava
#

second render of mandelbrot set

dawn kayak
#

!e ```py
import('ctypes').c_bool.from_address(id(True)+24).value = False
assert 1 == 1

wide crow
# floral meteor I made algebra.

Doesn't this give the same effect without having to define every operation?

class Alg:
    def __init__(self, expr, var):
        self.expr = expr
        self.var = var
    
    def __call__(self, arg):
        new_expr = self.expr.replace(self.var, str(arg))
        return eval(new_expr)

f = Alg('3*x + 5 + x**2 + a', var='x')
a = 6
y = f(4)
print(y)  # 39
night quarryBOT
#

@dawn kayak :warning: Your 3.10 eval job has completed with return code 0.

[No output]
sullen kayak
#

hey how do i handle function parameter conversion in a lambda function?

restive void
#
import sys
import inspect
from contextlib import contextmanager
from collections import defaultdict


deferred_lines = defaultdict(list)


def defer_trace(frame, event, arg):
    if event != "line":
        return defer_trace
    with open(inspect.getsourcefile(frame)) as f:
        lines = f.readlines()
    line = lines[frame.f_lineno - 1].strip()
    if line.startswith("defer; "):
        deferred_lines[frame].append(line.strip()[len("defer; "):])
        frame.f_lineno += 1
    else:
        pass
    return defer_trace


@contextmanager
def deferable():
    frame = sys._getframe().f_back.f_back
    sys.settrace(lambda *a:None)
    frame.f_trace = defer_trace
    try:
        yield
    finally:
        for line in deferred_lines[frame]:
            exec(line, frame.f_globals, frame.f_locals)
        deferred_lines.pop(frame)
        sys.settrace(None)


with deferable():
    print("Hello")
    defer; print("Bye")
    print("Middle")
#

Prints Hello\nMiddle\nBye\n this

floral meteor
#

noice

floral meteor
edgy lava
#

||print('hello')||

#

print('hello')

dense nova
sullen kayak
#

conflicting advice

quartz wave
#
  1. there's no such thing as a "function parameter conversion" because python doesn't do anything about those
  2. they're annotations and you can't put annotations in lambdas
sullen kayak
#

also i learned that indeed.

#

just annotations for the editor

#

that can help with type hints and such.

quartz wave
#

!e @sullen kayak ```py
def a(x: int, y: int) -> int:
return x + y

print(a("b", "c"))

night quarryBOT
#

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

bc
sullen kayak
#

yeah, it's just a type hint.

#

both of them

#

-> int and x: int

quartz wave
#

ye

sullen kayak
#

i got that.

quartz wave
#

then also you can't put them in a lambda

dense nova
#

I agree with @quartz wave on this one, i misinterpreted your question. sorry

sullen kayak
#

i should probably ask my question here, i want this:

#

to do the same thing as: this

#

but i don't know how i'm gonna get just controls out of get_output

#

this has to be able to be imported in another file and ran just fine.

quartz wave
#

or do (...)[2]

sullen kayak
#

like so?

quartz wave
sullen kayak
#

man if this works lmao

#

wayy a syntax error

quartz wave
sullen kayak
#

in this case..

#

i think this venv is 3.7.9?

quartz wave
sullen kayak
#

damnit lmfao

#

i can't update it.

#

so uhh

#

what do i use instead ๐Ÿ˜ฌ

#

setattr self target_location?

#

then access self.target_location later on?

floral meteor
#

if i can't use a walrus, i just use a list like a cell so that I can setitem inline

sullen kayak
floral meteor
#

you know you can embed code here with
```py
stuff
```
right?

sullen kayak
#

yeah but i'm not a fan of the discord syntax highlighting.

floral meteor
#

I'm not a fan of image compression

sullen kayak
#

yk if you just click on it

#

but ight

floral meteor
#

if i click on it, it's the same size

sullen kayak
#

anyway that function wasn't the problem fortunately

floral meteor
#

just moved to the middle

#

embed ur code.

#

not all of us are young and can read microscopic code

sullen kayak
#

oh my guh it works

#

LMFAOO

#

IT WORKS

#

i just added and None after the init tuple of statements.

quartz wave
# sullen kayak

btw you can do ```py
*map(setattr, (self.controls,)*4, ("steer", "boost", "throttle", "handbrake"), (steer_toward_target(...), True, 1.0, ...)),

sullen kayak
#

does it make my code harder to read? Pepega

sullen kayak
#

is there any way i can drop the line count here at all?

#

to zoom in a little.

floral meteor
sullen kayak
#

Ok.

floral meteor
#

why are you making an empty class MyBot then inheriting from it? it seems kinda pointless

sullen kayak
#

hm

floral meteor
#

instead of pass you could at least add a docstring explaining why it exists

sullen kayak
#

adding a docstring would add lines PainChamp

floral meteor
#

no it won't

#
class A:"""DOCSTRING"""
sullen kayak
#

automatically does this.

#

wait lmfao

#

semicolon fixed it

floral meteor
#

remember I said instead of pass?

#

not as well as pass

sullen kayak
#

there we go, a short and concise explanation.

floral meteor
#

pass is a beginner's gimmick, not anything meaningful

#

... is much cuter and does the same thing

#

it's like pass 2.0 it can even go inline

sullen kayak
#

so 3 lines is the lowest line count i'll be getting?

floral meteor
#

nope

sullen kayak
#

.-.

floral meteor
#

you can get rid of the second line

#

and thus be able to semicolon the remaining two lines together

sullen kayak
#
class MyBot(BaseAgent):

    def __init__(self, name, team, index):
        super().__init__(name, team, index)
        self.active_sequence: Sequence = None
        self.boost_pad_tracker = BoostPadTracker()

    def initialize_agent(self):
        # Set up information about the boost pads now that the game is active and the info is available
        self.boost_pad_tracker.initialize_boosts(self.get_field_info())

    def get_output(self, packet: GameTickPacket) -> SimpleControllerState:
        """
        This function will be called by the framework many times per second. This is where you can
        see the motion of the ball, etc. and return controls to drive your car.
        """
#

this is the class i'm trying to make.

floral meteor
#

embed the what you have instead of screenshotting it

floral meteor
sullen kayak
#
import math; from rlbot.agents.base_agent import BaseAgent, SimpleControllerState; from rlbot.utils.structures.game_data_struct import GameTickPacket; from util.boost_pad_tracker import BoostPadTracker; from util.orientation import Orientation, relative_location; from util.drive import steer_toward_target; from util.vec import Vec3
class MyBot():"""class for rlbot to run."""
Derived = type("Derived", (MyBot,BaseAgent), {"__init__": lambda self, name, team, index: (super(Derived, self).__init__(name, team, index), setattr(self, "boost_pad_tracker", BoostPadTracker()))and None, "initialize_agent": lambda self: self.boost_pad_tracker.initialize_boosts(self.get_field_info()), "get_output": lambda self, packet: (self.boost_pad_tracker.update_boost_status(packet), setattr(self, "target_location", min([[i.location, Vec3(packet.game_cars[self.index].physics.location).dist(i.location)] for i in self.boost_pad_tracker.boost_pads if i.is_active == True], key=lambda i: i[1])[0]), setattr(self, "controls", SimpleControllerState()),setattr(self.controls, "steer", steer_toward_target(packet.game_cars[self.index], self.target_location)), setattr(self.controls, "boost", True), setattr(self.controls, "throttle", 1.0),setattr(self.controls, "handbrake", abs(math.atan2(relative_location(Vec3(packet.game_cars[self.index].physics.location), Orientation(packet.game_cars[self.index].physics.rotation), self.target_location).y, relative_location(Vec3(packet.game_cars[self.index].physics.location), Orientation(packet.game_cars[self.index].physics.rotation), self.target_location).x)) > 1.5), )and self.controls})
floral meteor
#

noice

sullen kayak
#

Readable.

floral meteor
#

i'm already on it

#
import math;from rlbot.agents.base_agent import BaseAgent as A,SimpleControllerState;from rlbot.utils.structures.game_data_struct import GameTickPacket;from util.boost_pad_tracker import BoostPadTracker;from util.orientation import Orientation,relative_location;from util.drive import steer_toward_target;from util.vec import Vec3;B=type("B",(),{});Derived=type("Derived",(B,A),{"__init__":lambda s,name,team,index:(super(Derived,s).__init__(name,team,index),setattr(s,"boost_pad_tracker",BoostPadTracker()))and None,"initialize_agent":lambda s: s.boost_pad_tracker.initialize_boosts(s.get_field_info()),"get_output":lambda s,packet:(s.boost_pad_tracker.update_boost_status(packet),setattr(s,"target_location",min([[i.location,Vec3(packet.game_cars[s.index].physics.location).dist(i.location)]for i in s.boost_pad_tracker.boost_pads if i.is_active==True],key=lambda i:i[1])[0]),setattr(s,"controls",SimpleControllerState()),setattr(s.controls,"steer",steer_toward_target(packet.game_cars[s.index],s.target_location)),setattr(s.controls,"boost",True),setattr(s.controls,"throttle",1.0),setattr(s.controls,"handbrake",abs(math.atan2(relative_location(Vec3(packet.game_cars[s.index].physics.location),Orientation(packet.game_cars[s.index].physics.rotation),s.target_location).y,relative_location(Vec3(packet.game_cars[s.index].physics.location),Orientation(packet.game_cars[s.index].physics.rotation),s.target_location).x))>1.5),)and s.controls})
quartz wave
#

shorten some names

#

and strings

floral meteor
#

for that i'd need to use an actual IDE

sullen kayak
#

i didn't think that was possible

#

holy hell LMFAO

floral meteor
#

type('',(),{})

#

makes new class

sullen kayak
#

do you think i could like

#
Derived = type("Derived", (type("MyBot",(),{}),BaseAgent), {"__init__": la
#

pass the creation of the mybot class in the first argument of the type that makes derived?

floral meteor
#

yes

sullen kayak
#

W

floral meteor
#

wait why does MyBot even need to exist?

sullen kayak
#

i just need a class that inherits BaseAgent.

floral meteor
#

Derived does that

sullen kayak
#

mybot isn't necessary, come to think of it.

floral meteor
#

get rid of it lol

#

(BaseAgent,)

sullen kayak
#

yeah

floral meteor
#

don't forget the comma

#
import math;from rlbot.agents.base_agent import BaseAgent as A,SimpleControllerState;from rlbot.utils.structures.game_data_struct import GameTickPacket;from util.boost_pad_tracker import BoostPadTracker;from util.orientation import Orientation,relative_location;from util.drive import steer_toward_target;from util.vec import Vec3;B=type("B",(),{});D=type("D",(B,A),{"__init__":lambda s,n,t,i:(super(D,s).__init__(n,t,i),setattr(s,"b",BoostPadTracker()))and None,"initialize_agent":lambda s: s.b.initialize_boosts(s.get_field_info()),"get_output":lambda s,p:(s.b.update_boost_status(p),setattr(s,"target_location",min([[i.location,Vec3(p.game_cars[s.index].physics.location).dist(i.location)]for i in s.b.boost_pads if i.is_active],key=lambda i:i[1])[0]),setattr(s,"c",SimpleControllerState()),setattr(s.c,"steer",steer_toward_target(p.game_cars[s.index],s.target_location)),setattr(s.c,"boost",1),setattr(s.c,"throttle",1),setattr(s.c,"handbrake",abs(math.atan2(relative_location(Vec3(p.game_cars[s.index].physics.location),Orientation(p.game_cars[s.index].physics.rotation),s.target_location).y,relative_location(Vec3(p.game_cars[s.index].physics.location),Orientation(p.game_cars[s.index].physics.rotation),s.target_location).x))>1.5),)and s.c})
sullen kayak
#

yeah i put that there right after you said so

#

god this is ridiculous but you guys are amazing lmfao

#

what motivates you to make one of the easiest languages a pain in the backside to read?

floral meteor
#

if ...==True is the same as if ... the ==True is wasting time, keyboard life and pixels

#

same for the 0 in 1.0 you can just 1.

floral meteor
floral meteor
quartz wave
floral meteor
#

idk what types the thingy takes

quartz wave
#

that's literally the same thing isn't it

floral meteor
#

sometimes these packagey things can be a bit fussy

#

"float can't be interpreted as int" or vice versa

#

pain in the hindquarters

quartz wave
sullen kayak
#

it takes everything

#

i can set controls.throttle to fucking True if i wanted.

floral meteor
#

then why'd you use a bloody float?

sullen kayak
#

readability instinct

#

lmao

floral meteor
#

readability is for the weak

quartz wave
#

boost can be 1 then??

sullen kayak
#

yes

#

it's a Truthy value.

floral meteor
#

I'm seeing a lot of setattrs that can be replaced with map, setattr and three arrays

sullen kayak
#

will it make it harder to read? ๐Ÿ‘‘

floral meteor
#

obviously

#

XD

#
(setattr(a0,b0,c0),setattr(a1,b1,c1),setattr(a2,b2,c2),setattr(a3,b3,c3),setattr(a4,b4,c4))

or

(*map(setattr,[a0,a1,a2,a3,a4],[b0,b1,b2,b3,b4],[c0,c1,c2,c3,c4]),)
sullen kayak
floral meteor
#

and yes map can be used with more than two arguments

#

any time you use something you import exactly once, just use __import__ on the spot instead of importing at the start of the file

sullen kayak
floral meteor
#

wat

sullen kayak
#

LMFAO

floral meteor
#

where'd you get that from?

sullen kayak
#

idk

#

intellisense.

floral meteor
#
__import__('math')
#

!e ```py
print(import('math').pi)

quartz wave
# floral meteor ```py import math;from rlbot.agents.base_agent import BaseAgent as A,SimpleContr...
setattr(s.c,"steer",steer_toward_target(p.game_cars[s.index],s.target_location)),setattr(s.c,"boost",1),setattr(s.c,"throttle",1),setattr(s.c,"handbrake",abs(math.atan2(relative_location(Vec3(p.game_cars[s.index].physics.location),Orientation(p.game_cars[s.index].physics.rotation),s.target_location).y,relative_location(Vec3(p.game_cars[s.index].physics.location),Orientation(p.game_cars[s.index].physics.rotation),s.target_location).x))>1.5)
``` to ```py
locals().update(x=p.game_cars[s.index]),locals().update(y=x.physics,z=s.target_location),*map(setattr,[s.c]*4,("steer","boost","throttle","handbrake"),(steer_toward_target(x,z),1,1,abs(math.atan2(relative_location(Vec3(y.location),Orientation(y.rotation),z).y,relative_location(Vec3(y.location),Orientation(y.rotation),z).x))>1.5))
``` ?
night quarryBOT
#

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

3.141592653589793
quartz wave
#

also remove trailing comma

floral meteor
#

when has locals().update ever worked unless chilaxan has had at it?

quartz wave
floral meteor
#

that works

quartz wave
#

ok do it

floral meteor
#

why use locals().update whatever when you cann

(lambda x,y:f(x,y))(1,2)
quartz wave
floral meteor
#

lmao

quartz wave
#

man if he was on 3.8 we could've used an assignment expression

floral meteor
#

if you want it shorter, interpret the whole file as utf-16, then embed it as a string into exec(b"...".decode("UTF-8"))

sullen kayak
#

i'm on 3.7.9 why1

floral meteor
#

reduced character count but the bytes might be more

sullen kayak
#

and i can't upgrade it.

floral meteor
#

don't even need walrus

#

dont even need namespace

#

just

#

make a dictionary in globals called L

#

and use it as though it's locals

#

L.__setitem__('varname',value)

#

instead of varname := value

quartz wave
#

ye but then we'd have to do L["varname"]

floral meteor
#

ยฏ_(ใƒ„)_/ยฏ

#

we could also define the L at the start of the lambdas if you want them to actually be local

#

remember also you can use mutable defaults in lambdas to hide variables

#

perhaps even just throw away names and index lists of objects

#

names are just a readability assistant

sullen kayak
#

code is just a readability assistant

#

program this entire shit into memory with instructions.

floral meteor
#

actually did that before

#

in python

#

made brainfuck interpreter that used native memory and mutated the code string into the output of the brainfuck

floral meteor
# sullen kayak program this entire shit into memory with instructions.

!e like this? ```py
from ctypes import*
class output:
def init(self, victim):
self.victim=id(victim);ol = len(victim)
(c_char*ol).from_address(id(victim)+48)[:]=[0]*ol
c_longlong.from_address(id(victim)+16).value=0
def lt(self, item):
_l = c_longlong.from_address(self.victim+16)
_l.value += 1
_a = c_byte.from_address(self.victim+48+_l.value)
_a.value=-item;return 0;
neg=lambda s:s
def gt(self, a):
a,i,_l=a,c_longlong.from_address(self.victim+16)
data = (c_byte
_l.value).from_address(self.victim+49)
v, *data[:-1] = data;_l.value -= 1;a[i] = v;return 0;

class array:
def init(self, victim):
self.memory = "\0\0\0\0\0\0\0\0"[:]256
_ = self.memory = id(self.memory)
c_longlong.from_address(
+16).value=256
8-1
self.i=0; self.o = output(victim)
@property
def mem(self):return(c_byte*(256*8-1)).from_address(self._memory+48);
def inc(self):self.mem[self.i]+=1;return 0;
def dec(self):self.mem[self.i]-=1;return 0;
def left(self):self.i-=1;return 0;
def rite(self):self.i+=1;return 0;
def dot(self):return self.o <- self.mem[self.i];
def com(self):return(self.mem, self.i) <- self.o;
def loop(self):return+(not self.mem[self.i]);
def endl(self):return-bool(self.mem[self.i]);
def iter(self):return iter([self.mem])
def run(self, c):
p=t=0
try:
while 0<=p<len(c):
if t:t+=(c[p]=='[')-(c[p]==']')
else:t={
'+':self.inc,'-':self.dec,'<':self.left,'>':self.rite,
'.':self.dot,',':self.com,'[':self.loop,']':self.endl
}.get(c[p],lambda:0)()
p+=1-2
(t<0)
except KeyboardInterrupt:pass
finally:return self.o

def brainfuck(victim, , _n=[0]):
clone,a = victim+'.',array(victim);a.run(clone)
_l=c_longlong.from_address(a.o.victim+16);l=_l.value;_l.value-=1
data = (c_byte
l).from_address(a.o.victim+48)
_,*data[:-1]=data;import('sys')._getframe(1).f_globals[_n[0]]=a.o;_n[0]+=1

code = "++++++++++[>+++++++>+++++++++++>+++<<<-]++++++++++>++>--.>++.<.<.>-------.,..+++.>++++++++++++.,.+<<+++++++++++++++.>.+++.,.--------.>.<<<."
print(code)
brainfuck(code)
print(code)

night quarryBOT
#

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

001 | ++++++++++[>+++++++>+++++++++++>+++<<<-]++++++++++>++>--.>++.<.<.>-------.,..+++.>++++++++++++.,.+<<+++++++++++++++.>.+++.,.--------.>.<<<.
002 | Hello, World!
floral meteor
#

this sort of happened one day when i had too much red bull and ascended to a higher plane of existence

#

I'm like the Florida Man of programming

quartz wave
floral meteor
#

random Turing Machine trivia https://www.quora.com/Is-DNA-a-Turing-machine

restive void
unreal echo
finite blaze
#

Hey, I wonder if there is any way to escape string literals to access some variable?
I have a

variable = "text"
inputText = input()
print(f"{inputText}")
quartz wave
quartz wave
restive void
vestal solstice
#

it's just eval

next flame
#

or globals()[inputText] if you want to be slightly safer

quartz wave
floral meteor
floral meteor
#

although, not if I used intfuck, a brainfuck derivative that interprets one massive integer and substitutes digits for brainfuck characters

#

I could obfuscate it harder by calling oct on the string

#

then in the base ten system the integer isn't even readable

high tree
#

!e print(1)

night quarryBOT
#

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

1
floral meteor
#

hmmmm

#

imma just make a portal to #bot-commands

distant briar
royal patrol
#

need help with generating a middle finger ascii art with the "esoteric" code in python, any help would be appreciated

#

ping me up if anyone interested

floral meteor
#

shortest way, or an obfuscated way?

royal patrol
#

but shortest way will do as well

royal patrol
#

this is the holy temple where people should learn python, this is the channel

turbid glade
#

what esoteric lang will u use

royal patrol
#

not like gonna write that shit in brainfuck

#

or wait

#

i can actually

#

but python would be cool

turbid glade
#
import pywhatkit

source_path = 'flower.png'
target_path = 'demo_ascii_art.text'
pywhatkit.ascii_art.image_to_ascii_art(source_path, target_path)
#

@royal patrol

#

done

royal patrol
#

-_--

#

not the esoteric way but thanks i can take it from here

unreal echo
quartz wave
near briar
#

@floral meteor do u know any other pg languages?

floral meteor
#

I used to code in MATLAB

#

I also figured out Casio basic from playing around with a graphics calculator

floral meteor
#

Other than MATLAB and python, I tried java but coding in java feels like drowning in lemon juice after getting entire body papercutted

languid hare
#

there are small patterns in bf that you can understand locally, keeping track of a whole program gets messy though

#

eg, [-] is a common pattern that means "set the current cell to 0"

floral meteor
#

If they're bytes, then [+] also works

#

n+[>m+<o-]> means #0, #1 to 0, #1+(#0+n)*m/o

#

Sort of

#

You can do one of these with 12, 3, 1 to get to digits for decimal conversion

#
++++++++++[>+++++<-]> 0 50
++++. 6
+++.  9
lyric fern
#

!e

print(int(True))
night quarryBOT
#

@lyric fern :white_check_mark: Your 3.11 eval job has completed with return code 0.

1
floral meteor
#

!e print(1==1.==True==False**False)

night quarryBOT
#

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

True
lyric fern
#

!e
print(True/False)

night quarryBOT
#

@lyric fern :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ZeroDivisionError: division by zero
lyric fern
#

!e

true = True

while true <= 10:
    true += 1
    print(true)
night quarryBOT
#

@lyric fern :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 2
002 | 3
003 | 4
004 | 5
005 | 6
006 | 7
007 | 8
008 | 9
009 | 10
010 | 11
lyric fern
#

!e print(True+6)

night quarryBOT
#

@lyric fern :white_check_mark: Your 3.11 eval job has completed with return code 0.

7
lyric fern
#

!e print(1==True)

night quarryBOT
#

@lyric fern :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
lyric fern
#

Lmao

languid hare
#

!e

print({
  1: "one",
  2: "two"
}[True])
night quarryBOT
#

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

one
languid hare
#

๐Ÿ˜‰

floral meteor
#

!e 3.10

from fishhook import hook
@hook(bool)
def __str__(self):return"True or False"

print( True or False )

@hook(bool)
def __truediv__(self, other):
  if type(other)is type(self):
    return"True/False"

print( True/False )
night quarryBOT
#

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

001 | True or False
002 | True/False
floral meteor
#

!e ```py
from random import randint
c=randint(1,9);{
c in(1,2,3):lambda:print("this"),
c in(4,5,6):lambda:print("that"),
c in(7,8,9):lambda:print("foo")
}1

night quarryBOT
#

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

this
floral meteor
#

!e ```py
a = [1,5,7,2,8,3,9,0]
print('4 ','not '*(4 in a),'in a',sep='')

night quarryBOT
#

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

4 not in a
floral meteor
#

I'd do anything to avoid if statements

wheat river
#

#ifBad

royal whale
#

Another match statement I guess

floral meteor
#

it's better than match

#

!e there's also the execute all matched cases version ```py
c = 4
[b()for a,b in(
((1,2,3),lambda:print("this")),
((4,5,6),lambda:print("that")),
((7,8,9),lambda:print("foo"))
)if c in a]

night quarryBOT
#

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

that
floral meteor
#

!e or the reverse hierarchy ```py
c = 4
iter(b()for a,b in(
((1,2,3),lambda:print("this")),
((4,5,6),lambda:print("that")),
((7,8,9,4),lambda:print("foo"))
)if c in a).next()

night quarryBOT
#

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

that
floral meteor
#

!e as opposed to ```py
from random import randint
c=randint(1,9);{
c in(1,2,3):lambda:print("this"),
c in(4,5,6,c):lambda:print("that"),
c in(7,8,9,c):lambda:print("foo")
}1 # foo

night quarryBOT
#

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

foo
floral meteor
finite blaze
#

Hey, could you drop some impressive examples of code golfing?

#

I am trying to introduce my friend to this topic

last locust
#

This is an example of a golfed fizzbuzz program @finite blaze

unreal echo
#

this channel is essentially for brainfuck now

sick hound
#

!e
count = 0
while True:
print(int(True) * count)
count += 1

night quarryBOT
#

@sick hound :x: Your 3.11 eval job has completed with return code 143 (SIGTERM).

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
011 | 10
... (truncated - too many lines)

Full output: too long to upload

sick hound
#

!e


exec("""\ncount = 0\nwhile True:\n    print(int(True) * count)\n""")
night quarryBOT
#

@sick hound :x: Your 3.11 eval job has completed with return code 143 (SIGTERM).

001 | 0
002 | 0
003 | 0
004 | 0
005 | 0
006 | 0
007 | 0
008 | 0
009 | 0
010 | 0
011 | 0
... (truncated - too many lines)

Full output: too long to upload

sick hound
#

!e
exec("""\ncount = 0\nwhile True:\n print(int(True) * count)\n count += 1\n""")

night quarryBOT
#

@sick hound :x: Your 3.11 eval job has completed with return code 143 (SIGTERM).

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
011 | 10
... (truncated - too many lines)

Full output: too long to upload

languid hare
#

why not just print count :p

sick hound
#

because I dont wanna

#

you can prolly figure it out though right...

sick hound
quartz wave
#

!e ```py
[*map(print,import("itertools").count())]

languid hare
#

hey i wanted to do that

sick hound
#

without iter tools

night quarryBOT
#

@quartz wave :x: Your 3.11 eval job has completed with return code 143 (SIGTERM).

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
011 | 10
... (truncated - too many lines)

Full output: too long to upload

quartz wave
languid hare
#

!e

(count:=0,next(_ for _ in iter(int,1) if (print(count),count:=count+1,0)[-1]))
night quarryBOT
#

@languid hare :x: Your 3.11 eval job has completed with return code 143 (SIGTERM).

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
011 | 10
... (truncated - too many lines)

Full output: too long to upload

old socket
#

!e ```py
while True:print(int(True)*(i:=globals().setdefault("i",0)+1))

night quarryBOT
#

@old socket :x: Your 3.11 eval job has completed with return code 143 (SIGTERM).

001 | 1
002 | 2
003 | 3
004 | 4
005 | 5
006 | 6
007 | 7
008 | 8
009 | 9
010 | 10
011 | 11
... (truncated - too many lines)

Full output: too long to upload

languid hare
#

kinda gross but it works

old socket
#

Oh mine starting at 1

#

๐Ÿ˜”

languid hare
#

you could just -1 it

twilit grotto
#

you don't need int in int(True)

old socket
#

It looks like they are asking specifically for it though

#

Probably not but

sick hound
#

Yeah

old socket
#

!e ```py
while True:print(int(True)*(i:=globals().setdefault("i",-1)+1))

night quarryBOT
#

@old socket :x: Your 3.11 eval job has completed with return code 143 (SIGTERM).

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
011 | 10
... (truncated - too many lines)

Full output: too long to upload

sick hound
#

Nice

old socket
#

You can also use iter but it'll probably be more characters

quartz wave
# quartz wave kk sure i'm just gonna pull out my dunder methods hold on

!e ```py
(:=name.class.class.base.subclasses().getitem((:=name.len().bool()).add().pow((:=.add(.add())).add()).add()))(builtins.getattribute((:=(builtins.dict).getitem)(.add().pow(.add().mul(.add())).add().mul(.add().mul(.add()))))(builtins.getattribute((.add().mul(.add()).add().mul(.add()).mul())),((:=(:=(:=(___:=(:=(:=name.class)).class.base.subclasses()).getitem((__:=.basicsize).add(.floordiv(:=(:=(:=.len(.new(_))).eq()).add(.add()))).add())).getattribute(,(:=(:=.getitem(.add().pow(.add()).add())))(.dict).getitem()).wrapped.globals).getitem(().getitem(.len().sub(.invert().neg().pow()).add()))((:=name.iter().class.name.getitem)(___:=.invert().neg().pow().add(.invert().neg())).add((.add(__))).add((.add(.add()))).add((:=.add())).add((.add(.add()))).add((.add()).mul(.add())).add(.class.doc.getitem(.add().pow(.add()).add().add(.add()))).add(_(.neg().invert())))).dict.getitem((.dict).getitem(.add().pow(.add().mul(.add())).add(_)))())))

night quarryBOT
#

@quartz wave :x: Your 3.11 eval job has completed with return code 143 (SIGTERM).

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
011 | 10
... (truncated - too many lines)

Full output: too long to upload

quartz wave
#

@sick hound i said i'd pull out my dunder methods

sick hound
#

bro what the fuck

unreal echo
flint hollow
# unreal echo what the fuck is a 143 SIGTERM?

if the bot notices that a python program takes too long, then the program gets sent an end request (SIGTERM), and if it refuses, gets ended involuntary (SIGKILL). SIGTERM is signal 15, and 143 is 15+128 (128=program ended)
tl;dr infinite loop got killed by snekbox

earnest wing
#

!e ```py
from signal import*
raise_signal(SIGSEGV)

night quarryBOT
#

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

[No output]
unreal echo
#

!d signal

night quarryBOT
#

This module provides mechanisms to use signal handlers in Python.

quartz wave
verbal spear
#

!e
b='ๅ••โชชไ—‘โฏชๅตโบบๅตใจฎ'
b+=b[-2::-1]
for z in b:
print(bin(ord(z))[2:].zfill(15).translate({49:11036,48:11035}))

night quarryBOT
#

@verbal spear :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | โฌœโฌ›โฌœโฌ›โฌœโฌ›โฌœโฌ›โฌœโฌ›โฌœโฌ›โฌœโฌ›โฌœ
002 | โฌ›โฌœโฌ›โฌœโฌ›โฌœโฌ›โฌœโฌ›โฌœโฌ›โฌœโฌ›โฌœโฌ›
003 | โฌœโฌ›โฌ›โฌ›โฌœโฌ›โฌœโฌœโฌœโฌ›โฌœโฌ›โฌ›โฌ›โฌœ
004 | โฌ›โฌœโฌ›โฌœโฌ›โฌœโฌœโฌœโฌœโฌœโฌ›โฌœโฌ›โฌœโฌ›
005 | โฌœโฌ›โฌœโฌ›โฌœโฌœโฌœโฌ›โฌœโฌœโฌœโฌ›โฌœโฌ›โฌœ
006 | โฌ›โฌœโฌ›โฌœโฌœโฌœโฌ›โฌœโฌ›โฌœโฌœโฌœโฌ›โฌœโฌ›
007 | โฌœโฌ›โฌœโฌœโฌœโฌ›โฌœโฌ›โฌœโฌ›โฌœโฌœโฌœโฌ›โฌœ
008 | โฌ›โฌœโฌœโฌœโฌ›โฌœโฌ›โฌ›โฌ›โฌœโฌ›โฌœโฌœโฌœโฌ›
009 | โฌœโฌ›โฌœโฌœโฌœโฌ›โฌœโฌ›โฌœโฌ›โฌœโฌœโฌœโฌ›โฌœ
010 | โฌ›โฌœโฌ›โฌœโฌœโฌœโฌ›โฌœโฌ›โฌœโฌœโฌœโฌ›โฌœโฌ›
011 | โฌœโฌ›โฌœโฌ›โฌœโฌœโฌœโฌ›โฌœโฌœโฌœโฌ›โฌœโฌ›โฌœ
... (truncated - too many lines)

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

proper vault
#

A somewhat interesting challenge:
Write a function set_del(obj, fun) where obj is an object you are allowed to assign arbitrary attributes to, and fun is a function that should get called once the object obj gets collected by the garbage collector.

quartz wave
proper vault
#

This can be done in pure python

#

Though upon further consideration it is way easier than I thought

#

But it is possible without a custom __del__ method

#

And fishhook would make it a right pain to do this, since __del__ is on the class

earnest wing
#

seems simple with weakref.finalize

earnest wing
proper vault
#

It is possible tbh

#

I was honestly just trying to get people to figure out how try: finally: in generators leaks when the GC runs

astral rover
#

try: finally: leaks with generators?

edgy lava
#

bruh i jest went overlapping different graphs of mandelbrot sequence for various values of of Z(0) and now it looks like the graph is scared

proper vault
night quarryBOT
#

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

001 | 3
002 | 2
quartz wave
languid hare
#

makes sense, no?

quartz wave
#

!e ```py
def x():
yield from [1, 0, 0]

print(any(x()))

night quarryBOT
#

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

True
languid hare
#

that's how any works

#

did you confuse it with all

quartz wave
#

yeah i did

fleet bridge
# proper vault A somewhat interesting challenge: Write a function `set_del(obj, fun)` where obj...

!e

def set_del(obj: 'Any', fun: 'Callable') -> None:
    cls = type(obj)
    new_type = type(cls.__name__, (cls,), dict(__del__=fun))
    obj.__class__ = new_type

import gc

class X:
    pass

x = X()
del x
gc.collect()

x = X()
set_del(x, print)
del x
gc.collect()

x = X()
set_del(x, lambda self: print(self))
del x
gc.collect()

x = X()
set_del(x, lambda self: globals().__setitem__('resurrected', self))
del x
gc.collect()

print(resurrected)
night quarryBOT
#

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

001 | 
002 | <__main__.X object at 0x7f58a3a22f50>
003 | <__main__.X object at 0x7f58a3a230d0>
fleet bridge
#

it creates new subclass of object type with defined __del__ and changes object type

#
>>> set_del(object(), print)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in set_del
TypeError: __class__ assignment only supported for mutable types or ModuleType subclasses
earnest wing
proper vault
#

Honestly, I was curious how many other solutions people would come up with

finite blaze
#

about challanges

#

I've got something for you

#
import dataclasses
import os
import random

FLAG = "getme"

@dataclasses.dataclass
class Message:
    message: str

    def __str__(self):
        return self.message

    __repr__ = __str__


MESSAGES = [
    Message("Thank you for using our service."),
    Message("Here is your pattern:"),
    Message("Until next time!")
]

pattern = input("pattern> ")
count = int(input("count> "))

final_pattern = pattern * count
print(f"{{message}} {final_pattern}".format(message=random.choice(MESSAGES)))
#

Try to get the flag

#

(its from a ctf from the last week)

proper vault
#

Ah, ||format injection||

languid hare
#

something like ||{message.__str__.__globals__}|| should work

finite blaze
#

Something like this

restive void
#

!e just because someone claimed in #python-discussion that keys of a dict need to be unique..

import random
class F:
    def __hash__(self):
        return random.randint(1, 5)
f = F()
d = {}
for i in range(100):
    d[f] = i
print(d)
night quarryBOT
#

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

{<__main__.F object at 0x7f97c048b450>: 96, <__main__.F object at 0x7f97c048b450>: 77, <__main__.F object at 0x7f97c048b450>: 99, <__main__.F object at 0x7f97c048b450>: 95, <__main__.F object at 0x7f97c048b450>: 98}
light grove
#

@solar quail

quartz wave
unreal echo
#

i have lost a majority of my brain cells now

tall meteor
#

LOL

sick hound
#

Oh

restive void
royal sun
languid hare
#

๐Ÿ˜†

#

excellent

royal whale
#

How about this

#

!e

from abc import ABC

class TheTrueBaseObjectThatEverythingInheritsFrom(ABC): # ...but it inherits from ABC?
  @classmethod
  def __subclasshook__(*WeDontCareWhatYouPutHere):
    return True

print(isinstance(str, TheTrueBaseObjectThatEverythingInheritsFrom)) # yes
print(isinstance(int, TheTrueBaseObjectThatEverythingInheritsFrom)) # yes
print(isinstance(list, TheTrueBaseObjectThatEverythingInheritsFrom)) # yes
print(isinstance(ABC, TheTrueBaseObjectThatEverythingInheritsFrom)) # the superclass is an instance of its own subclass...
print(isinstance(object, TheTrueBaseObjectThatEverythingInheritsFrom)) # object's true base class revealed
night quarryBOT
#

@royal whale :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | True
002 | True
003 | True
004 | True
005 | True
earnest wing
#

abc subclasshooks are honestly kind of straightforward

#

glad they interact nicely with patma

royal whale
#

Now I want to learn more ๐Ÿ˜ˆ

astral rover
#

i wouldnt have thought you even needed the abc subclass here

#

oh you do?