#esoteric-python
1 messages ยท Page 1 of 1 (latest)
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
btw it seems like the PyDictValues part of interned when i investigated further
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
hi
hello
Sorry, you can't do that here!
I'm studying fastAPI
ok
data compression library, but i can't see the code.. so i will assume its sus
it's qualifier/tests.py in the code jam 2022 qualifier
<frame>.f_code?
!remind @floral meteor 2w remind chilaxan memory allocation investigation
Sorry, you can't do that here!
!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")
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | oh ok
002 | hmm
???
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.
Comparison of objects does not call bool
And I think is has precedence over not
It's like ==, but for the id of the object pointer
oh wait operator precedence
yep, not being looser than is is sometimes unexpected
if(not hing)is False
is different to
if not hing is False
which is equivalent to
if not(hing is False)
!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")
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | oh ok
002 | ok
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?
remove all the newlines
dont use two or more letters for variable names
better dont use variables at all
Do it with generator. It will be proper esoteric python
make FibonacciEnterpriseEdition
def fib(n): a, b = 0, 1 for _ in range(n): yield a a, b = b, a + b
Generator
!e
from functools import reduce
fib=lambda n:reduce(lambda x,_:x+[x[-1]+x[-2]],range(n-2),[0,1])
print(fib(5))
@royal whale :white_check_mark: Your 3.11 eval job has completed with return code 0.
[0, 1, 1, 2, 3]
Not my creation, but significantly more esoteric
I havent learned lamdar yet
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.
To ascend lambda is to understand how to use ctypes to curse python
code: import ctypes
me:
!d curses
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.
print ("dog")
it's just digging into lower level code to customise how python is interpreted
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
Either that or I somehow reconstructed it wrong
what did you try to do
!e print("Lol")
@void charm :white_check_mark: Your 3.11 eval job has completed with return code 0.
Lol
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]
Move data from a str +48 to an int +24, then call bin on the int, then reconstruct the string from the 1s and 0s
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
*UCS-4

(same thing, but officially...)
assuming the string is UCS-1 then that's correct
so it's efficienter in memory to not use strings
wait a string of length 32 shouldn't make an int with length data of 8
there's the limit that for each digit, the digit must be in range(2**30)
!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))
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1001000110010111011001101100110111110110010000010101111101111111001011011001100100100001
002 | 176009217592051565591370017
wdym digit?
is this a 2**30 base system?
it's so easy to do that in a C extension ```c
PyBytes_FromStringAndSize(PyUnicode_DATA(s), PyUnicode_GET_LENGTH(s) * PyUnicode_KIND(s))
yes
whyyyyyy
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))
@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)
!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))
@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
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))
@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
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?
it's 8191
8191 is so much less than 2**30
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?
probably
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?
if c_long has a size of 4 bytes then that's encompassing ```py
[0, 0, 0, 0, 1, 0, 0, 0] # digit array as byte list
^ ^ ^ ^
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?
what?
does it corrupt the data?
oh you mean filling it up
what bits are used to make the 2**30?
one digit it's totally fine
haven't tested with 2
because 4 bytes can fit 32 bits, but each 4 bytes here are 30 bit digits.
what two bits is it ignoring?
testing with 2 digits, it seems to ignore the most significant 2 bits (bit 30 and bit 31)
i have no idea what you just said
what is happening here?
I have summoned an integer from an evil parallel dimension
I made a two digit number and made both digits 255
>>> a = 2**30-1
>>> c_uint.from_address(id(a)+24).value = -1
>>> a
4294967295
>>> a
4294967295
>>> a+0
4294967295
``` ???
but 4294967295+0 = -1
why can't i reproduce
!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))
@floral meteor :white_check_mark: Your 3.10 eval job has completed with return code 0.
001 | 4294967295
002 | -1
so 3.10 has the problem
HA!
3.11 fixed it but how ๐ค
in the 2**30 system it shouldn't work because all 32 bits are 1
!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))
@quartz wave :white_check_mark: Your 3.10 eval job has completed with return code 0.
001 | 4294967295
002 | -1
you only need to set one digit
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
if python integer base is 2**15 then that's exactly correct
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?
i mean you could always look at the digit array as a byte array and find out what they are
but when you do bin() they're just ignored so probably yeah
this is starting to sound like the topic should be called Malware Design 106: Data Corruption.
so how do I recover the corrupted data?
i mean you could always look at the digit array as a byte array and find out what they are
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
(in 3.10)
!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_charl).from_address(id(victim)+48)
type_base.value = bytes((c_char8).from_address(id(0)+8))
a = victim + 1
odata.value = bytes((c_charl).from_address(id(a)+48))
type_base.value = bytes((c_char*8).from_address(id('')+8))
corrupt(s)
print(s)
@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
so here's the problem with 3.10 https://github.com/python/cpython/blob/3.10/Objects/longobject.c#L3070-L3072
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));
}```
here's the fix in 3.11 https://github.com/python/cpython/blob/main/Objects/longobject.c#L3271-L3273
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));
}```
so why does this look like the Zen of Python from a laptop in the Upside Down?
it should either look fine or look completely different, not like some echo of the original crying for help
!e ```py
print('Yaa+pv \x08b'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.')
@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.
I must say the #esoteric-python channel has some very creative people
Fractal rendered under 2 sec with pure python
esoteric how
Please don't keep advertising your repo on here, we've seen it before. Also that's more of a #user-interfaces topic.
It's neat but off-topic
100% python grounds up and yes I wont
Not UI thou maybe media
At any rate, certainly not #esoteric-python
being 100% python doesn't make it esoteric
it is cool, but it's not esoteric, which means that this isn't the correct channel
maybe it doesn't neatly fit into any of the channels? and i don't really feel like it's advertising
Have you written a pure python bmp parser and done math in the complex plane
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
about 70% of this channel is normal code
not everything in #esoteric-python is esoteric
class Myclass(type):
pass
great now deobfuscate this ```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())())
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
!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())())
@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: ''
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())())
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
512
give me a moment I'm on mobile
oh i found the problem
how does globals()[""] work
python
it shouldn't
python
I'm confused
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())())
you can't give a var that name
Is this supposed to happen?
@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'
you can
well you can't normally
how
๐คท
then how does your code work
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())())
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
512
I'm so confused
What's it even supposed to do
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())())โ
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
512
ok but do you understand that
exactly
btw the printed 512 isn't a number
!e
n=512;print(type((lambda:0).__class__(compile([*[globals()['']for globals()['']in[bytes]][0].__dict__.values()][globals()[''].__basicsize__-4](globals()[''],'6e20616e6427272e6a6f696e285b6368722834382b6e2f2f31302a2a6925313029666f72206920696e2072616e6765285f5f696d706f72745f5f28226d61746822292e6c6f673130286e292e5f5f7472756e635f5f28292b31295d2e5f5f72657665727365645f5f2829296f72273027'),'','eval'),globals())()))
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
<class 'str'>
huh
!e this is the absolute deobfuscation ```py
n=512;print(f"{n}")
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
512
print(str(512))
im just gonna accept that you're a hyperdimensional magic being and try to not have a headache over this
could say that for most of the experts in #esoteric-python (including jack the mod)
it may not work in <3.11
with hedge and fork also being there sometimes
and then I'm bumbling about just learning about fishhook like two days ago Lmao
my brain isn't ready for this stuff
it had more active participants some weeks earlier
including Ryuga, whitespace, chilaxan(?), Olivia, and JavaLim
yes
also very knowledgeable about python internals
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.
I code crazier and more often when it's hot
It's colder at this time of year down in this hemisphere.
!e
a=str|int|bool;b:a='512';print(int(b));[0];
...
Can you fetch all the defined operator strings (binary, unary, boolean, in place, ...) at runtime?
!d token
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.
this?
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 
or parse the sphinx inventory file
or fetching the operator classes from ast and unparsing them
!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)
@earnest wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
lol ['!=', '%', '%=', '&', '&=', '*', '**', '**=', '*=', '+', '+=', '-', '-=', '/', '//', '//=', '/=', '<', '<<', '<<=', '<=', '==', '>', '>=', '>>', '>>=', '@', '@=', '^', '^=', '|', '|=']
there's binary ones ig
except without the keyword operators
so not many at all tbh
I discovered new error
i used alt-f4 on a program using multiprocessing, now i can't rerun it lol
What? There's not an @ or @= operator!
What is this sorcery?
sure there is
!e doesn't throw SyntaxError:
lambda: a @ b
@restive void :warning: Your 3.11 eval job has completed with return code 0.
[No output]
what
!pep 465
what
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? 
(I'm posting here because this is definitely something you shouldn't be doing
)
Oh good point
I'll see how that repo does it
Oh no is it .pth files 
oh no
python packaging is such a hopeless mess, i love it
if you're doing in python, shouldn't you call left.__xor__(right)?
nope, that's different
clearer example:
def to(left, right):
return right(left)
assert -1 `to` abs == 1
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
then why was it like this
im confused
.
!pypi lib-CST
!pypi libCST
that reminds me of julia
what the heck
you ever wonder why god is in heaven?
because this channel is on earth
!E
print((lambda a, b: a @ b)(1, 2))
@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'
WHATTTT
hello increasingly verbose Python
it only works with numpy arrays
hello
!e
class F:
def __matmul__(s, o):
return 42
print(F() @ "hello")โ
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
42
I'm not sure whether to call that brilliant or loathsome.
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
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
Uhm this isn't really the channel for it
But Esoteric: intended for or likely to be understood by only a small number of people with a specialized knowledge or interest.
Maybe you'll have some luck in #internals-and-peps or #networks
to golf it further you can ditch the variable assignment by calling the lambda in the expression like (lambda: None)(), you can also move your print inside the lambda
!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))
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 |
002 | $
003 | $$
004 | $$$
005 | $$$$
006 | $$$$$
!e
print(*(lambda c,t: map(lambda i:'\n'+i*' '+(t-i)*c,range(t,-1,-1)))('#',5))โ
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 |
002 |
003 | #
004 | ##
005 | ###
006 | ####
007 | #####
golfed?
!e
print("\n".join(f"{'#'*n: >5}"for n in range(6)))
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 |
002 | #
003 | ##
004 | ###
005 | ####
006 | #####
'#'*n: >5
whats going on here?
nvm, I see now
!e
for n in range(6):print(f"{'#'*n:>5}")
@finite blaze :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 |
002 | #
003 | ##
004 | ###
005 | ####
006 | #####
- we don't discuss networking here
- we're supposed to worsen your current condition
for _ in range(6):print(f"{'#':>{_}}")
??
!e idk why
print(*map('\n'.__add__, map(lambda x: eval('x.__name__'), (type('#'*_,(),{}) for _ in range(10)))))
@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 | #########
!timeit
import gc
gc.collect()
(*map('\n'.__add__, map(lambda x: eval('x.__name__'), (type('#'*_,(),{}) for _ in range(1000)))),)
@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
!e ```py
for n in range(6):print(f"{' ':#>{n+1}}")
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 |
002 | #
003 | ##
004 | ###
005 | ####
006 | #####
!e
print('''#
#
#
#
#''')
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | #
002 | #
003 | #
004 | #
005 | #
the best
I right aligned lol I'm dum
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 |
002 | #
003 | # #
004 | # ##
005 | ## ##
006 | ## ###
!e ```py
for n in range(1,7):print(f"{' ':#<{n}}")
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 |
002 | #
003 | ##
004 | ###
005 | ####
006 | #####
I'm typing on phone, don't judge
!e for n in range(1,7):print(f"{' '*(6-n):#<{n//2+5}}")
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | #
002 | ###
003 | ####
004 | ######
005 | #######
006 | ########
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 |
002 | #
003 | ##
004 | ###
005 | ####
006 | #####
!e 3.10
for i in range(5):
print("#"*((i+1)**2))
@wheat apex :white_check_mark: Your 3.10 eval job has completed with return code 0.
001 | #
002 | ####
003 | #########
004 | ################
005 | #########################
!e 3.10
for i in range(20):
print("#"*((i+1)**2))
@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 :white_check_mark: Your 3.10 eval job has completed with return code 0.
001 | #
002 | ##
003 | ###
004 | ####
005 | #####
!e 3.10
for i in range(5):
print((i + 1 + round(0.49*i)) * "#")
@wheat apex :white_check_mark: Your 3.10 eval job has completed with return code 0.
001 | #
002 | ##
003 | ####
004 | #####
005 | #######
!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)]))
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | #
002 | ###
003 | #####
004 | #######
005 | #########
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))
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
0 1 2 3 4 5 6 7
!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)),
@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
!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))
@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
!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))
@worldly trail :white_check_mark: Your 3.11 eval job has completed with return code 0.
[('1', 1), ('2', 2), ('3', 3)]
Is it possible longer? ๐
Wdym longer
!e
print(True**False/True*True//True*False+1-True)
@lyric fern :white_check_mark: Your 3.11 eval job has completed with return code 0.
0.0
!e
true = True
false = False
a = True
if a == true:
print(true)
else:
print(false)
@lyric fern :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
!e
true, false, null = True, False, None
class json:
loads = eval
print(json.loads('{"some": true, "thing": null, "24": [2,1,3]}'))
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
{'some': True, 'thing': None, '24': [2, 1, 3]}
tsk tsk
...that feels illegal
Well of course that isn't completely the same
That's how you know it belongs here ๐
{
"some": true,
}
Is invalid
But it would be accepted as a python dict itself when evaluated like that
Yes, it's an overly permissive JSON parser.
aint no one cares about json syntax
Not quite, no. Different escape sequences.
right, \/ etc parse differently
That, and I think surrogate characters?
lone surrogates don't parse in python?
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"'))
@restive void :white_check_mark: Your 3.11 eval job has completed with return code 0.
๐
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")
sl = song.lower()
for name, x in map(lambda y: (y, data['eras'][y]), ('wod', 'drfl', 'gbgr', 'outsiders', 'juicethekidd', 'nineninenine')):
if sl in x:
print(f"From {name}")
break
else:
print("song not in database")
I meant a better easier way not completely mind boggling ๐คฃ
it's literally better than doing what you just did
Also that returns all the songs in the era not the actual era
wrong channel, then
What channel should I go to..
ok wait
fixed
What does map do?
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")
@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
apply the function throughout the iterable
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
so it's the same as (a(x) for x in (b, c, d))
yeah actually it's more like that
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)
but map has to invoke a function, which has overhead. are you sure it's faster?
comprehensions (and for-loops) can unpack values: for (k, v) in d.items()
map cannot
perhaps it depends if the comprehension is also invoking a function
i can test it in this example: map(1.__radd__, a) vs (x+1 for x in a)
give me a minute
it will be hard to generalize "map is faster", it will depend a lot on what the map does.
also, those two things aren't equivalent
oops, they are
>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
cool
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)
if we weren't in #esoteric-python i would have a comment about that choice
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))
@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
!timeit
a = [*range(10**4)]; f = lambda x: x - 2
``` ```py
[f(x*2 + 1) for x in a]
@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
!timeit
a = [*range(10**4)]; f = lambda x: x - 2
``` ```py
list(map(f, map(1 .__radd__, map(2 .__rmul__, a))))
@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
!timeit
a = [*range(10**4)]; f = lambda x: x - 2
``` ```py
[*map(f, map(1 .__radd__, map(2 .__rmul__, a)))]
@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
- list-comp (1.24 msec)
- list(gen-compr) (1.49 msec)
- [*map] (2.29 msec)
- list(map) (2.30 msec)
i didn't realize #esoteric-python is also #microoptimizations ๐
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
probably because map() also acts like zip()
!e ```py
a = range(0, 20, 2)
b = range(10)
print(*map(lambda x, y: x + y, a, b))
@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
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
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
!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")
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
i have done a hello world
!e ```py
x = {i:str(i+1) for i in range( 10)}
#not impossible.
print(list(map(repr, x.items())))
@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')"]
!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())()
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello world!
only parentheses, no constant strings, no constant integers, no constant booleans, only names with underscores, and no operators (except for :=)
YOU LEGEND
and you don't need a walrus either if you just inline everything 
and you don't need tuple literals either if you're using dunder methods 
ok
Hello all. Ah, one of my favorite channels on this server. So entertaining, these uses and mis-uses of decorators and lambdas.
๐ ๐ ๐ ๐
!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)
@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
!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)
@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
callable tuples to replace
a = f(e(d(c(b(*args)))))
with
a = (b,c,d,e,f)(*args)
since a long time ago
oh is it tuple unpack
made specifically for single-element tuples
does it work in 3.11?
!e ```py
(a, b), c = (1, 2), 3
print(a, b, c)
(a,) = (4,)
b,=5,
print(a,b)
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1 2 3
002 | 4 5
fishhook isn't installed in 3.11 in the bot
no reason why it shouldn't work in 3.11
yeah it's tuple unpack
sorry, I'm tired lmao
huh
is a user created package, not builtin
packages are like DLCs in games. fishhook is like a modding system
yes
ik
but still, it's weird that it's installed on 1 but not the other
ctypes is like cheat codes
that's what I'm confused about, not about what fishhook is
what's the () for
() (lambda...
huh
what is this?
Idk
Im just borred because i want h3elp
And im messing aorund because in 1- mins imma go out
10
!e try torturing python like ```py
import ctypes
ctypes.c_long.from_address(id(4)+24).value += 1
print( 2 + 2 )
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
5
!e
code
!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 :white_check_mark: Your 3.10 eval job has completed with return code 0.
hello world
but also remember this isn't #bot-commands this is just for python torture
depends how esoteric it is.
I'd say math stuff is esoteric as many avoid mathematics.
!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))
@floral meteor :x: Your 3.10 eval job has completed with return code 139 (SIGSEGV).
001 | y = (10*x)+9
002 | 69
I made algebra.
Nice
... 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.
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
!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]])))
@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)
!e
print(*map((0,).__add__, map(tuple, [[1,2],[3,4],[5,6]])))
@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)
!e
print(*[tuple([0]+list(range(7))[i:i+2]) for i in range(1, 7, 2)])
@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)
!e
print(*[(0,*t)for t in[[1,2],[3,4],[5,6]]])
@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)
second render of mandelbrot set
!e ```py
import('ctypes').c_bool.from_address(id(True)+24).value = False
assert 1 == 1
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
@dawn kayak :warning: Your 3.10 eval job has completed with return code 0.
[No output]
hey how do i handle function parameter conversion in a lambda function?
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 
noice
defeats the entire purpose. anyone can interpret strings.
put the lambda in brackets
you can't
conflicting advice
- there's no such thing as a "function parameter conversion" because python doesn't do anything about those
- they're annotations and you can't put annotations in
lambdas
also i learned that indeed.
just annotations for the editor
that can help with type hints and such.
!e @sullen kayak ```py
def a(x: int, y: int) -> int:
return x + y
print(a("b", "c"))
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
bc
ye
i got that.
then also you can't put them in a lambda
I agree with @quartz wave on this one, i misinterpreted your question. sorry
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.
add and controls after the tuple
or do (...)[2]
like so?
yea try that
what python version are you in
you need 3.8 for walrus operator
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?
if i can't use a walrus, i just use a list like a cell so that I can setitem inline
you know you can embed code here with
```py
stuff
```
right?
I'm not a fan of image compression
if i click on it, it's the same size
anyway that function wasn't the problem fortunately
just moved to the middle
embed ur code.
not all of us are young and can read microscopic code
oh my guh it works
LMFAOO
IT WORKS
i just added and None after the init tuple of statements.
btw you can do ```py
*map(setattr, (self.controls,)*4, ("steer", "boost", "throttle", "handbrake"), (steer_toward_target(...), True, 1.0, ...)),
does it make my code harder to read? 
idk
test it out
Even with microscope it still looks illegible
Ok.
why are you making an empty class MyBot then inheriting from it? it seems kinda pointless
hm
instead of pass you could at least add a docstring explaining why it exists
adding a docstring would add lines 
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
so 3 lines is the lowest line count i'll be getting?
nope
.-.
you can get rid of the second line
and thus be able to semicolon the remaining two lines together
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.
embed the what you have instead of screenshotting it
embed this
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})
noice
Readable.
remove some more spaces
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})
for that i'd need to use an actual IDE
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?
yes
W
wait why does MyBot even need to exist?
i just need a class that inherits BaseAgent.
Derived does that
mybot isn't necessary, come to think of it.
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})
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?
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.
i refactored this a little, but i may have missed a few variables. If you get any NameErrors, just change the name to their first letter
bored, and it's an easy language so it's easy to abuse.
can just 1
idk what types the thingy takes
that's literally the same thing isn't it
sometimes these packagey things can be a bit fussy
"float can't be interpreted as int" or vice versa
pain in the hindquarters
๐
then why'd you use a bloody float?
readability is for the weak
boost can be 1 then??
setattr(s.c,"boost",1)
I'm seeing a lot of setattrs that can be replaced with map, setattr and three arrays
will it make it harder to read? ๐
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]),)

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
?
wat
LMFAO
where'd you get that from?
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))
``` ?
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
3.141592653589793
ah no
also remove trailing comma
when has locals().update ever worked unless chilaxan has had at it?
how about globals().update
that works
ok do it
why use locals().update whatever when you cann
(lambda x,y:f(x,y))(1,2)
bruh ```py
("steer","boost","throttle","handbrake")
"steer boost throttle handbrake".split()
lmao
man if he was on 3.8 we could've used an assignment expression
if you want it shorter, interpret the whole file as utf-16, then embed it as a string into exec(b"...".decode("UTF-8"))
i'm on 3.7.9 
reduced character count but the bytes might be more
and i can't upgrade it.
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
ye but then we'd have to do L["varname"]
ยฏ_(ใ)_/ยฏ
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
code is just a readability assistant
program this entire shit into memory with instructions.
actually did that before
in python
made brainfuck interpreter that used native memory and mutated the code string into the output of the brainfuck
!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=2568-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_bytel).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)
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ++++++++++[>+++++++>+++++++++++>+++<<<-]++++++++++>++>--.>++.<.<.>-------.,..+++.>++++++++++++.,.+<<+++++++++++++++.>.+++.,.--------.>.<<<.
002 | Hello, World!
holy fucking shit
WHAT?
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
average #esoteric-python
random Turing Machine trivia https://www.quora.com/Is-DNA-a-Turing-machine
Answer (1 of 6): On its own, I donโt know about that, but a part of me doubts that (to my knowledge, there is no such proof right now). I personally donโt think one DNA molecule is a Turing Machine (Iโd imagine there would be a lack of operations), but there do exist mathematically proven results...
Hmm, I think your code is broken.. :P https://tinyurl.com/3f6mdpsj (sorry for the shortened link; too long for Discord)
if you were to write a key logged in ctypes, it would be so obfuscated i wouldn't even notice
key logger?
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}")
that's because TIO is running on python 3.7.4
it's so outdated that its latest is python 3.8 pre-release
(no, I was joking, it works fine; that was a quine)
what do you mean?
it's just eval
or globals()[inputText] if you want to be slightly safer
locals()[inputText]
backwards compatibility was only tested as far back as 3.9
some people can read brainfuck though
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
!e print(1)
@high tree :white_check_mark: Your 3.10 eval job has completed with return code 0.
1
not in that case
"fine", "quine", what a rhyme!
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
shortest way, or an obfuscated way?
obfuscated way would be better
but shortest way will do as well
lol
yes
this is the holy temple where people should learn python, this is the channel
what esoteric lang will u use
python in an esoteric way is the way to go
not like gonna write that shit in brainfuck
or wait
i can actually
but python would be cool
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
cap ๐งข
if i could learn what the characters mean i might be able to do that
Holy fking shit dude u are a genius
@floral meteor do u know any other pg languages?
I used to code in MATLAB
I also figured out Casio basic from playing around with a graphics calculator
You would also need to recognise patterns
Other than MATLAB and python, I tried java but coding in java feels like drowning in lemon juice after getting entire body papercutted
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"
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
!e
print(int(True))
@lyric fern :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
!e print(1==1.==True==False**False)
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
!e
print(True/False)
@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
!e
true = True
while true <= 10:
true += 1
print(true)
@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
!e print(True+6)
@lyric fern :white_check_mark: Your 3.11 eval job has completed with return code 0.
7
!e print(1==True)
@lyric fern :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
Lmao
!e
print({
1: "one",
2: "two"
}[True])
@languid hare :white_check_mark: Your 3.11 eval job has completed with return code 0.
one
๐
!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 )
@floral meteor :white_check_mark: Your 3.10 eval job has completed with return code 0.
001 | True or False
002 | True/False
that's what chads do instead of match case
!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
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
this
!e ```py
a = [1,5,7,2,8,3,9,0]
print('4 ','not '*(4 in a),'in a',sep='')
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
4 not in a
I'd do anything to avoid if statements
#ifBad
What kind of occult sorcery is this? There are too many problems
Another match statement I guess
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]
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
that
!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()
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
that
!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
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
foo
this whole channel is black magic
Hey, could you drop some impressive examples of code golfing?
I am trying to introduce my friend to this topic
This is an example of a golfed fizzbuzz program @finite blaze
this channel is essentially for brainfuck now
!e
count = 0
while True:
print(int(True) * count)
count += 1
@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
someone make this into a one-liner
!e
exec("""\ncount = 0\nwhile True:\n print(int(True) * count)\n""")
@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
!e
exec("""\ncount = 0\nwhile True:\n print(int(True) * count)\n count += 1\n""")
@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
why not just print count :p
make this into a one liner 
!e ```py
[*map(print,import("itertools").count())]
hey i wanted to do that
without iter tools
@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
kk sure i'm just gonna pull out my dunder methods hold on
Okaty
!e
(count:=0,next(_ for _ in iter(int,1) if (print(count),count:=count+1,0)[-1]))
@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
!e ```py
while True:print(int(True)*(i:=globals().setdefault("i",0)+1))
@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
kinda gross but it works
you could just -1 it
you don't need int in int(True)
Yeah
!e ```py
while True:print(int(True)*(i:=globals().setdefault("i",-1)+1))
@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
Nice
You can also use iter but it'll probably be more characters
!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(_)))())))
@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
@sick hound i said i'd pull out my dunder methods
bro what the fuck
the hell
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
!e ```py
from signal import*
raise_signal(SIGSEGV)
@earnest wing :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!d signal
This module provides mechanisms to use signal handlers in Python.
.bm What the actual hell
absolutely no constants
only names with underscores
everything has to be in dunder methods except for calling and :=
!e
b='ๅโชชไโฏชๅตโบบๅตใจฎ'
b+=b[-2::-1]
for z in b:
print(bin(ord(z))[2:].zfill(15).translate({49:11036,48:11035}))
@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
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.
isn't that achievable by fishhook already
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
seems simple with weakref.finalize
... hold on, isn't this function literally weakref.finalize
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
try: finally: leaks with generators?
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
!e Leaks when the GC runs, doesn't leak memory.
def gen(s):
try:
yield 1
finally:
print(s)
any(q:=gen(2))
any(gen(3))
@proper vault :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 3
002 | 2
why does any() stop collecting at the first yield?
makes sense, no?
it stops at the first yield even when there are still multiple others
!e ```py
def x():
yield from [1, 0, 0]
print(any(x()))
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
!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)
@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>
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
I think that was the challenge but still well done!
Honestly, I was curious how many other solutions people would come up with
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)
Ah, ||format injection||
something like ||{message.__str__.__globals__}|| should work
Yep, that was our solution
Something like this
!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)
@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}
@solar quail
seems like pretty normal behaviour
what did this achieve
i have lost a majority of my brain cells now
LOL
Lmao
Oh
Yes, nothing special for this channel, but I couldn't just let that claim stand. Also, it's pretty funny what happens if you print d several times.
Let's make the CPython team regret adding pattern matching to Python!
Nice
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
@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
abc subclasshooks are honestly kind of straightforward
glad they interact nicely with patma
before that article I had no idea what either ABCs or __subclasshook__ did
Now I want to learn more ๐