#esoteric-python

1 messages ยท Page 95 of 1

sick hound
#

Wtf

#

Bruh

#

Bool exists

#

Man

zealous widget
#

that's simpler

sick hound
#

WTF

#

That actually works?

#

Let me try

#

Damn

proper vault
#
def is_even(n, m={1}):
    return not(n in m or is_even(n-1) and (m.add(n)or m) )
marsh void
#

NO

next flame
#

inb4 someone does is_even with only types

marsh void
#
nekit $ python -m timeit -s "n = 13" "n ^ 1 > n"
2000000 loops, best of 5: 123 nsec per loop
nekit $ python -m timeit -s "n = 13" "not not n & 1"
2000000 loops, best of 5: 113 nsec per loop``` how do I express my confusion
proper vault
#

not not is really fast

rugged sparrow
#
def is_even(n):
  return int(str(n)[-bool(int)]) in range(int(),int(str(int(bool(int)))+str(int())),bool(int)+bool(int))```
marsh void
#

what is not actually doing

#

is it like negating bool(...)

pastel gale
#

i'm surprised esoteric python for me is a complicated topic in itself

edgy kelp
alpine flower
#
    while True:
        try:
            while (selection := input(">")) not in option_list and int(selection) not in range(1, 7):
                print(f"Invalid selection: {selection}")
            break
        except ValueError:
            print(f"Invalid selection: {selection}")```
any way to shorten this? I tried fire's suggestion of supressing the ValueError but there's no way to catch it + respond if I use it
cedar herald
#

you can incorporate the range into your option_list, that way you don't have to check for casting error

sick hound
#
import timeit
import math

>>> math.sqrt(25) == 25 ** 0.5
True
>>> math.sqrt(2500) == 2500 ** 0.5
True
--------------------------------------------------------
>>> timeit.repeat('sqrt(25)', setup='from math import sqrt')
[0.21578920000000323, 0.21665869999999643, 0.21319249999999101, 0.21543020000000013, 0.21696570000000293]
>>> timeit.repeat('25 ** .5')
[0.015132900000011773, 0.015274300000001517, 0.015007799999992244, 0.01510880000000725, 0.015405400000005898]
``` I just realize that `math.sqrt` is kinda pointless as well as slow compared to just using `0.5` exponent (unless the number is negative in which case they're different, I forgot about that)
echo abyss
#

I assume that sqrt is approximated in a different way than arbitrary power

high garnet
#
def is_even(n):
    b = bin(abs(n))
    return b[0] == b[-1]

shameless idea theft

#

or how about this...

#
def is_even(n):
    i = iter(range(abs(n)))
    while True:
        try:
            next(i)

        except StopIteration:
            return True

        try:
            next(i)
            
        except StopIteration:
            return False
formal sandal
#
def _is_even(a, b):
    if 0 in (a, b):
        return True
    if 1 in (a, b):
        return False
    return not _is_even(a - 1, b + 1)

def is_even(n):
    return _is_even(n, n)
#
def _is_even(a, b):
    return(0in(a,b)and[1])or(1in(a,b)and[0])or[not _is_even(a-1,b+1)[0]]
def is_even(n):
    return _is_even(n,n)[0]
#
is_even=lambda n:(lambda r:r(r))(lambda r:lambda a,b:(0in(a,b)and[1])or(1in(a,b)and[0])or[not r(r)(a-1,b+1)[0]])(n,n)[0]
#

there's a minor issue that it returns 1 for 0 and 0 for 1, but it's okay

#

actually,

is_even=lambda n:(lambda r:r(r))(lambda r:lambda a,b:(0in(a,b)and[1>0])or(1in(a,b)and[1<0])or[not r(r)(a-1,b+1)[0]])(n,n)[0]
elfin onyx
#

yikes

thin trout
#

Are we doing stupid is_even functions haha

#

Sad someone already did bitshift

proper vault
#
code = """if n == 0:
    v[0] = True
elif n == 1:
    v[0] = False
else:
    exec({!r}.format(code), dict(n=n-2,code=code,v=v))"""
def is_even(n):
    v = ['error']
    exec(code.format(code),dict(n=n,code=code,v=v))
    return v[0]
echo abyss
#
def even(n):
    return (not -n) or int(str(n)[-bool(-n)]) in range(bool(n)+bool(n),int(str(int(bool(n)))+str(int(bool(-0)))), bool(-n)+bool(-n))
thin trout
#

Is it dangerous for a function to modify its own code?

#

I'd assume it is, but is it just a straight segfault, or the interpreter won't care?

proper vault
#

I would assume it would only affect the next call of the function

earnest wing
#

Would it be possible to make an is_even implementation that abuses floating point imprecision and some crazy magic numbers to evaluate K & K+1 to the same value, but K+2 to something else?

marsh void
#

honestly

#

this is cool and all but n % 2 == 0 is the fastest haha (EDIT: not n % 2, how could I have forgotten about it)

#

specifically in python, that is

coral geode
#

the point of this channel is NOT to be the easiest

marsh void
#

I didnโ€™t say the easiest

#

I said the fastest

#

which is funny because most compilers should and will optimize it down to n & 1 == 0 which is slower in python

rugged sparrow
#
is_even = lambda n:int((float(n)/0.9)/2)*2==n```
fervent hull
#

Probably not n % 2 is faster than n % 2 == 0

marsh void
#

it is slower for me, actually

#

oh wait

#

haha

#

I've been running not not there

#

kek

echo abyss
#
def even(n): return not bool(n//2 - n/2)
stark fable
#

importing gc appears to affect the result of reading a deallocated tuple ```py

from ctypes import *
from gc import *
x = (1, 2, 3)
x
(1, 2, 3)
(c_longlong*9).from_address(id(x))[0] = 0
x
TypeError: an integer is required (got type str)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
SystemError: <built-in method write of _io.TextIOWrapper object at 0x00000254A5397630> returned a result with an error set
((((((((((((((((((((((((((((((<NULL>, (<class '_ctypes.Structure'>,), {}), 'BigEndianStructure', <class '_ctypes.Structure'>), None, None), (<class '_ctypes.PyCFuncPtr'>,), {2562580367832: <weakref at 0x00000254A54A6188; to '_ctypes.PyCArrayType' at 0x00000254A5B149D8 (c_longlong_Array_9)>}), 'CFunctionType', <class '_ctypes.PyCFuncPtr'>), (), 1), 'This class represents a dll exporting functions using the\n Windows stdcall calling convention, and returning HRESULT.\n HRESULT error values are automatically raised as OSError\n exceptions.\n ', None), 'l', None), 'This class represents a dll exporting functions using the\n Windows stdcall calling convention.\n ', None), 'This class represents the Python library itself. It allows\n accessing Python API functions. The GIL is not released, and\n Python exceptions are handled correctly.\n ', None), 'u', None), 'pointer', '_pointer_type_cache'), '?', None), 'P', None), 'c', None), 'b', None), 'B', None), 'Q', None), 'q', None), 'g', None), 'd', None), 'f', None), 'I', None), 'i', None), 'L', None), 'l', None), None, None), (<class '_ctypes.Array'>,), {'builtins': <symtable entry top(-1), line 0>}), 9, None), 2, 3)```

south bone
#

What is the best way to get started with esoteric python? I find it very interesting

cursive pine
#

Fizz buzz

#

is fun

south bone
#

just find an esoteric solution to it>

cursive pine
#

yep

#

any one you can

south bone
#

any concepts I should look into?

cursive pine
#

String multiplication & lamda

south bone
#

thanks!

gentle pagoda
#
def _set(x):
    consts = list(is_even.__code__.co_consts)
    consts[1] = x
    is_even.__code__ = is_even.__code__.replace(co_consts = tuple(consts))

def is_even(n):
    r = True
    if n == 0:
        _set(r)
        return r
    _set(not is_even.__code__.co_consts[1])
    return is_even(n - 1)```
formal sandal
#

beware

#

most cursed addition to Python ever

#

(after @marsh void's braces, of course)

#

ta da

#

now seriously, I would love this addition

astral rover
#

How on Earth

rugged sparrow
#

@formal sandal now you gotta add automatic interpolation

#

like `var{val}`

#

that would be super cursed

formal sandal
#

@astral rover No magic, I just modified CPython's source

#

@rugged sparrow that would be a bit more involved than my change ๐Ÿ˜…

#

but yes

rugged sparrow
#

Could see if you could repurpose f-string code

#

Would make it easier to implement

high garnet
#

sigh gets out pitchfork

sick hound
#

@formal sandal nice job bro

#

thats really fucking cool

earnest wing
#

f-strings for identifiers

next flame
#
from pwn import *
import ctypes
context.arch = "amd64"

libc = ctypes.CDLL("libc.so.6")

def shellcode_to_func(shellcode: bytes, func_type=None):
    if func_type is None:
        func_type = ctypes.CFUNCTYPE(ctypes.c_int)
    buf = ctypes.create_string_buffer(shellcode)
    buf2 = ctypes.c_void_p(libc.valloc(len(buf)))  # allocate page aligned
    libc.mprotect(buf2, len(shellcode), 7)  # set to rwx
    ctypes.memmove(buf2, buf, len(shellcode))
    return ctypes.cast(buf2, func_type)

def run_shellcode(shellcode: bytes):
    return shellcode_to_func(shellcode)()

is_even = shellcode_to_func(
    asm("mov rax, rdi; and rax, 1; xor rax, 1; ret"), ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)
)
print(is_even(10))
print(is_even(5))
twilit grotto
#

bruh

high garnet
#

๐Ÿ˜ก

#
import math

def is_even(n):
    return math.cos(n * math.pi) > 0
fervent hull
#

More math (Bernoulli numbers)

from math import comb

def bernoulli(n):
    return sum(
        sum((-1) ** v * (v + 1) ** n * comb(k, v) for v in range(k + 1)) / (k + 1)
        for k in range(n + 1)
    )

def is_even(n):
    return not bernoulli(abs(n) + 3)
hexed siren
#

now seriously, I would love this addition
wow, that's really nice !
But I think this addition would just break the lisibility of a code. And I'm pretty sure you can do something like `2` = 3, right (I haven't check the source code modifications yet ๐Ÿ˜… ) ?
Anyway, I find it fun ! ๐Ÿ‘

formal sandal
#

Yep, `2` = 3 works

#

but the identifier is `2` in this case, not 2

rustic aspen
#

what is the most inefficient way to output hello world?

#

without using while loops or backspace characters

hexed siren
#

but the identifier is `2` in this case, not 2
hum... interesting ๐Ÿ˜„

formal sandal
#

@rustic aspen There's no answer to that question. For any proposed solution, you can do worse.

sick hound
#

write a small program which takes a string as input and checks to to see if the string is a palindrome, if it is, print โ€œYesโ€, if it is not,print โ€œNoโ€.

earnest wing
#

This sounds like a homework problem.

coarse cave
#

def _(__,_____):
     for (______)in(__):
         (lambda:(__import__('sys').stdout.write(______)))();
(lambda ____:_(____,____))(('H','e','l','l','o',' ','W','o','r','l','d','!'));

how can I make this better? it works but isnโ€™t too hard to understand.
(yes I deliberately added the semicolons to try to make it a bit harder to understand)

terse mortar
#

what is the most inefficient way to output hello world?
@rustic aspen this is the best(worst?) way to do that

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

you can use my cpython fork and include spaces in the identifiers

earnest wing
#

oh no is it generating code objects

#

what a headache

coarse cave
#

not actually that cursed of a feature. i always wanted ? in functions

formal sandal
#

well, that part is nice

rustic aspen
#

@terse mortar how did you come up with that?

terse mortar
#

I was fucking around with weird ways to print hello world, and f1re showed up with that shit from google

rustic aspen
#

ah

sick hound
#

this is the best(worst?) way to do that
@terse mortar this channel is for python not brainfuck (joke)

terse mortar
#

No, I do believe it's for brainfuck

sick hound
#

nah bro you went like >-+=<>+-=<><>[*+[]=

proper vault
#

!e

(lambda f: (setattr(f, '__code__',f.__code__.replace(co_consts=("Hello, World",))),f()))(lambda:print(None))```
night quarryBOT
#

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

Hello, World
sick hound
#

nice

terse mortar
#

That's cheating tho

#

(Use .replace)

proper vault
#

you could build a code object manually, but imo its neater to transform the code of the function

thin trout
#

That's stupid, I love it

rustic aspen
#

any way to redefine keywords?

bitter iris
#

No, they are handled in the parser level

marsh void
#

ayy isidentical always joining in when itโ€™s about parsers or AST >:)

bitter iris
#

*unless you use some sort of sorcery :-)

#

ayy isidentical always joining in when itโ€™s about parsers or AST >:)
@marsh void always watching

marsh void
#

ah yes

formal sandal
#

@bitter iris Did my fork summon you?

bitter iris
#

Yeah saw it @formal sandal, nice stuff

formal sandal
#

I should probably also add ? as a valid identifier character

bitter iris
#

Hmm, what about changing the grammar of if statements? if is_odd()? print('Yes')

formal sandal
#

then I'd also put the parts of the if expression in the correct order ๐Ÿ™‚

hexed siren
#

And can you implement pattern-matching, btw ? ๐Ÿ™ƒ ||(I'm joking)||

bitter iris
#

||it is already implemented||

#

||but not merged||

twilit grotto
#

||๐Ÿ‘€||

bitter iris
#

||this is a very nice feature||

#

||i feel like it attracts people more than normal text||

twilit grotto
#

||it's secret||

bitter iris
#

||Indeed||

twilit grotto
#

||๐Ÿ˜ณ||

marsh void
#

but where are None-aware operators smh

twilit grotto
#

where are the sentient operators smfh

bitter iris
formal sandal
#

huh

bitter iris
#

His implementation though a bit different

#

He parses this in the exact way of parsing a string (check the case he added, it is the same version of string tokenization case), so probably supports multiline things

#

In case if you want to go that route

#

but where are None-aware operators smh
@marsh void who needs None-aware operators when we have ||tiefighter|| operators

marsh void
#

PEP 505 now or Iโ€™m leaving

bitter iris
#

n?.o?.w?

#

Is this even valid for pep 505, lol

marsh void
#

last isnโ€™t

#

if we had PEP 505, T? would be useful instead of Optional[T] or T | None

twilit grotto
#

it makes it much more fun to say

bitter iris
#

Ah, I see

#

A proposal for int?

#

Which, IMHO, is just very bad

marsh void
#

huh?

bitter iris
#

I'm not on the pc rn, but search for int?

marsh void
#

int?

bitter iris
#

IMHO this is the one of the most useless way to fill up ? token

#

I'm very in favor of PEP 640 for getting a meaning to ?

marsh void
#

!pep 640

night quarryBOT
#
**PEP 640 - Unused variable syntax**
Status

Draft

Python-Version

3.10

Created

04-Oct-2020

Type

Standards Track

marsh void
#

no-no-no

#

so the point is it doesnโ€™t get into bytecode or is just as an _?

#

too lazy to read :p

bitter iris
#

Its coupled with other pattern matching peps

#

Basically it objects to making _ a special character

#

Even though it is just a normal identifier

#

So for wildcard pattern, it introduces ?

#

But not only for pattern matching, but for everywhere

#

Which is cool

marsh void
#

I disagree with that honestly

proper vault
#

for patma, the wildcard could just be object(), no?

marsh void
#

thatโ€™s

#

too much to write

marsh void
#
>>> __import__("ctypes").string_at(0)
segmentation fault``` but I think itโ€™s easier to mess with the parser @twilit grotto
sick hound
#

oh shit that crashes python

#

never knew that

marsh void
#

I mean yeah

twilit grotto
#

!e import("ctypes").string_at(0)

night quarryBOT
#

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

[No output]
marsh void
#

reading at address 0 is kinda uhm

sick hound
#

eval("exec('import os')") this works

#

so technically eval is exec?

marsh void
#

there are 3 different types of source in python

sick hound
#

yeah

marsh void
#

exec, single, eval

coarse cave
#
# this is also possible
(lambda:eval("exec(...)"))()```
which pretty much removes lambdas limits 
though not sure if the `eval` here needs to be.
marsh void
#

this is double stack of a hacky solution

coarse cave
#

is there to manually split a lexical token for the interpreter, without space?

gentle pagoda
#

is there any way to define mutually recursive functions such as this in one expression? py (lambda f = lambda: g(), g = lambda: f() : f() )() (this NameErrors for g ofc)

snow beacon
#

You could use a combinator.

(lambda f, g: f(f, g))(lambda f, g: g(f, g), lambda f, g: f(f, g))```
bitter iris
#

is there to manually split a lexical token for the interpreter, without space?
@coarse cave what do you mean by this?

coarse cave
#

like make the python lexer actually split for a token but manually.

ifTrue:print() # fails because `ifTrue` becomes a singular identifier.
if(True):print() # succeeds because itโ€™s no longer a singular token. the parentheses split a lexical token.

like that, but in some cases it isnโ€™t really a condition.
i.e 2:
xy == xy as a single identifier.
x y == x, y as two identifiers.
basically the same thing spaces (and lots of other characters and character sequences) do, but not using space.

#

since not having whitespace makes stuff much harder to read.

proper vault
#

do you want the tokenize module

bitter iris
#

since not having whitespace makes stuff much harder to read.
@coarse cave what?

vague cairn
#

I know, I couldn't parse that sentance either.

sudden osprey
#

What is an alternative to using func.__code__.replace that would work with python 3.6?

proper vault
#

manually filling the code constructor arguments from the code object

sudden osprey
#

How do I create a new code code object though, the attributes on it are read only

proper vault
#

!e

from types import CodeType
CodeType()
night quarryBOT
#

@proper vault :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | TypeError: code() takes at least 14 arguments (0 given)
sudden osprey
#

Ooh nice, that's exactly what I was looking for

#

thanks

thin trout
#

at least 14 arguments
lemon_eyes

formal sandal
#

it's pretty funny

#

!d types.CodeType

night quarryBOT
#
class types.CodeType(**kwargs)```
The type for code objects such as returned by [`compile()`](functions.html#compile "compile").

Raises an [auditing event](sys.html#auditing) `code.__new__` with arguments `code`, `filename`, `name`, `argcount`, `posonlyargcount`, `kwonlyargcount`, `nlocals`, `stacksize`, `flags`.

Note that the audited arguments may not match the names or positions required by the initializer. The audit event only occurs for direct instantiation of code objects, and is not raised for normal compilation.

`replace`(***kwargs*) Return a copy of the code object with new values for the specified fields.

New in version 3.8.
formal sandal
#

uhh, not here

#

!e

from types import CodeType
print(help(CodeType))
night quarryBOT
#

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

001 | Help on class code in module builtins:
002 | 
003 | class code(object)
004 |  |  code(argcount, posonlyargcount, kwonlyargcount, nlocals, stacksize,
005 |  |        flags, codestring, constants, names, varnames, filename, name,
006 |  |        firstlineno, lnotab[, freevars[, cellvars]])
007 |  |  
008 |  |  Create a code object.  Not for the faint of heart.
009 |  |  
010 |  |  Methods defined here:
011 |  |  
... (truncated - too many lines)

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

formal sandal
#

yep

Create a code object. Not for the faint of heart.

sudden osprey
#

Sort of confusing that the docs say that it takes **kwargs, but it actually only seems to let you give positional args

#

I guess that's just because it's a built in thing (C code) so parameters and stuff work differently?

formal sandal
#

Yeah, it has, like, ficticious arguments

#

In the C code, it uses a mini-DSL (like printf) to parse positional arguments

#

and idk how it handles kwargs

#

but kwargs have to be accessed deliberately

sudden osprey
#

Ah interesting

#

!e

from string import ascii_letters as letters
def f(): pass
for _ in range(5):
    f.__code__ = f.__code__.replace(
        co_argcount=len(letters),
        co_varnames=tuple(letters),
        )
    try: f()
    except TypeError as err:
        print(str(err).partition(':')[0])
night quarryBOT
#

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

001 | f() missing 44 required positional arguments
002 | f() missing 29 required positional arguments
003 | f() missing 24 required positional arguments
004 | f() missing 25 required positional arguments
005 | f() missing 40 required positional arguments
sudden osprey
#

Interesting behaviour if you don't set co_nlocals

sick hound
#

wtf

#

44 missing arguments

winter mortar
#

yo i made some one-line algorithms to find the root of a function between a and b ```py
import numpy as np
import random
def f(x):
return x**2 - 2

avstand til nullpunktet

toleranse = 0.01

start

a = 0

slutt

b = 2

metode 1 (halveringsmetode)

print((lambda r:lambda a,b: r(r,a,b))(lambda h,a,b:(a+b)/2 if abs(a-b)<toleranse else(h(h,a,(a+b)/2)if f(a)*f((a+b)/2)<0 else h(h,(a+b)/2,b)))(a,b))

metode 2

print((lambda r:lambda dx, a: r(r, dx, a))(lambda w, dx, s:s if abs(dx)<toleranse else w(w,-dx / 10,next(x for x in (np.arange(s,b,dx)if dx>0 else np.arange(s,a,dx))if f(x)*f(s)<0)))(0.1,a))

metode 3

print((lambda r:lambda a, b, n: r(r, a, b, n))(lambda h, a, da, n:a + da / 2 if da < toleranse else h(h,next(x for x in np.arange(a, a + da, da / n) if f(x) * f(x - da / n) < 0)-da/n,da/n,n))(a,b,6))

metode 4

print(min(((x,f(x)) for x in (a + (b - a) * random.random() for i in range(10000))),key=lambda x: abs(x[1]))[0])

metode 5

print((lambda r:lambda dx: r(r, dx))(lambda w, dx:"not found" if dx < 0.00001 else next((x for x in np.arange(a, b, dx) if abs(f(x)) < toleranse),w(w, dx * 0.1)))(0.1))

coarse cave
sick hound
#

h. you people might know this. how does one view the current call stack?

high garnet
#

inspect.stack?

sick hound
proper vault
#

os._getframe is the low level thing

#

You probably want to use inspect though

sick hound
#

so you're telling me.. #help-candy was a wast of 5 minutes for me to type :|

#

i need to basically raise a signal up the call stack somehow

#

like an exception, minus the whole "function dying" part

high garnet
#

doesn't seem like the right way to do it...?

#

gut feel

sick hound
#

how else would i ?

#

(did you read said message? it gives quite a bit of useful context)

high garnet
#

yes

sick hound
#

oki

#

i just. dunno anyway to do this. i dont want the command to just die. i figured maybe going up the call stack and finding the original command callback and setting a value in a dictionary maybe with the callbcak's hash, and check that periodically in the command?

snow beacon
#

My instinct would be to use nested co-routines instead of nested functions. Either that, or use exceptions and manage effects so that you can avoid side-effects from restarting any commands that threw an error.

#

Maybe not all that esoteric though, just complex.

next flame
#

if you're asking for help in #esoteric-python about code for a discord bot, you might want to reconsider what you're trying to do

#

stuff here shouldn't be going into production code

#

@sick hound

#

especially something that looks like xy problem

terse mortar
#

Lol yeah don't use esoteric code for things that require functionality

coarse cave
#

yeah i think is mostly for making as unreadable code as possible that functions

bitter iris
#

and idk how it handles kwargs
@formal sandal the mini dsl (Argument Clinic) unfortunately does not support variadic arguments, not yet at least.

frozen salmon
#
>>> def god_no(func):
...     return len(str(func))
...
>>> @god_no
... def innocent_function(inp):
...     print(inp)
...
>>> print(innocent_function)
50

This is concerning and exiting.

#

i've never thought of using decorators this way

#

๐Ÿ˜ˆ

stark fable
#
>>> @len
... @str
... def innocent_function(inp):
...     print(inp)
...
>>> innocent_function
50```
#
C:\Users\Aaay>python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> @exit
... def innocent_function(inp):
...     print(inp)
...
<function innocent_function at 0x000001DC09101E18>

C:\Users\Aaay>```
formal sandal
#

!e

@print
@hex
@id
def f():
    ...
night quarryBOT
#

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

0x7faf2cae0dc0
proper vault
#

parameter decorators when?

#
def fun(@int arg: str):
    ...
vague cairn
#

๐Ÿ˜ฎ

#

That doesn't work on my python.

proper vault
#

yeah, its not a real feature

vague cairn
#

Ok, I didn't see a good reason for it, except ... something to add to F with people.

twilit grotto
#

it could be useful I suppose

proper vault
#

it saves the annoying

def fun(arg: str):
    arg = int(str)
#

but thats not too horrible

vague cairn
#

Yeah. There have been projects I've made where the first seveal lines of every function was checking the types of the inputs, but with python, it's possible to define objects, self is ~garunteed to be the type of the object in question, or a decendent or they wouldn't be calling that method to handle it...

formal sandal
#

@proper vault Well, you can do something like

@transform
def fun(arg: Convert(str, int)):
   ... 
#

but good luck with making a typechecker like this

proper vault
#

meh, thats boring

#

I was thinking more

def fun(arg: int @ str): ...
vague cairn
#

I think you meant you can say this (and it run):

    arg = int(arg)```
and yes the typechecker hates it when I do that.
edgy kelp
#

typing.Annotated should take care of type checkers

sick hound
#

directed here from #internals-and-peps
I have this function and I was wondering whether there was some way to return instead of print

def fib(n):
    for i in range(len(funclist := [])+n-1):
        (i==(n-2) and print(funclist[i-1]() + funclist[i-2]())) or funclist.append(lambda i=i:funclist[i-1]() + funclist[i-2]() if i>1 else 1)
formal sandal
#

you can yield

sick hound
#

that makes me use next() on the function tho

proper vault
#

what do you want as the result?

#

a list of the prints, a string of the prints...

sick hound
#

just the fibonacci number

#

the thing it prints

#

found a different/better way

def fibonacci(n):
    return [(i==n-1 and (x:=(x[i-1] + x[i-2]))) or (i==0 and (x:=[])) or x.append(x[i-1] + x[i-2] if i>2 else 1 ) for i in range(0,n)] and x
proper vault
#
def fib():
    return [
        d['b']
        for d in [{}]
        for d['a'], d['b'] in [(0, 1)]
        for _ in range(n)
        for d['a'], d['b'] in [[d['b'], d['a'] + d['b']]]
    ]
``` `:=` is overkill for fibbonaci numbers
twilit grotto
#

bruh

sick hound
#

that returns a list tho

proper vault
#

you also returna list

sick hound
#

but I do like the idea

#

no ๐Ÿ™‚

proper vault
#

oh no, you don't

#

ah, then the OG version

#
def fib(n):
    return max(
        d['b']
        for d in [{}]
        for d['a'], d['b'] in [(0, 1)]
        for _ in range(n)
        for d['a'], d['b'] in [[d['b'], d['a'] + d['b']]]
    )
sick hound
proper vault
#

for assignement is realy nice here

#

since you can just a, b = b, a rather than having to have temporary variables and other such messes

sick hound
#

I had a feeling overwriting my list with it's final result wasn't the best way to go

#

nor the inline list declaration

proper vault
#

yeah, max/min is generally the way to get a single result from a comp

#

or next if you can filter out undersirable results

sick hound
#

I was looking at reduce, but decided to do it in no-import python

proper vault
#

reduce is also nice, but not builtin anymore

#

and the lambda nonsense you need to replace is not nice

#

better to just inline it into the mess

sick hound
#

I guess

#

I did learn a lot about walrus, conditions and pythons datastructure writing it

echo abyss
#

Maybe you can [-1] instead of max?

formal sandal
#

constructing a pydantic model from a NamedTuple!

def model_from_type(t: Type) -> Type:
    if isinstance(t, type) and issubclass(t, tuple):
        hints = {
            k: model_from_type(v)
            for k, v in get_type_hints(t).items()
        }
        return type(t.__name__, (BaseModel,), {"__annotations__": hints})  # type: ignore
    elif isinstance(t, type):
        return t
    elif "GenericAlias" in type(t).__name__:
        return t.__origin__[tuple(model_from_type(a) for a in t.__args__)]  # type: ignore
    else:
        return t
sick hound
#

how do i get into making esoteric python code

terse mortar
#

how do i get into making esoteric python code
@sick hound start off simple. Slightly overcomplicated a small bit of code, and keep overcomplicating it

cedar herald
#

After that is done, convert your variable names into single letters

formal sandal
#

or multiple underscores

high garnet
#

!e

from functools import reduce
from string import ascii_lowercase, ascii_uppercase

def to_upper(s):
    return reduce(lambda x, ys: x.replace(ys[0], ys[1]), dict(zip(ascii_lowercase, ascii_uppercase)).items(), s)

print(to_upper('lowercase'))
night quarryBOT
#

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

LOWERCASE
terse mortar
#

But

#

Why?

high garnet
#

why NOT?

terse mortar
#

But

#

But

#

.upper()

#

Altho to be fair this channel is only used for making overcomplicated shit

high garnet
#

@terse mortar a few days back there was a trend of making ever more ridiculous versions of is_even

terse mortar
#

Yeah I saw

high garnet
#
def _set(x):
    consts = list(is_even.__code__.co_consts)
    consts[1] = x
    is_even.__code__ = is_even.__code__.replace(co_consts = tuple(consts))

def is_even(n):
    r = True
    if n == 0:
        _set(r)
        return r
    _set(not is_even.__code__.co_consts[1])
    return is_even(n - 1)```

like this

#

so I'm trying to start a new trend ๐Ÿ™‚

terse mortar
#

I secretly read this channel whenever there is a new message, hoping that one day I would be able to make a useful contribution to this channel

#

Also I'm convinced people are just adding underscores to their variable names just to make it look more complex

high garnet
#

Also I'm convinced people are just adding underscores to their variable names just to make it look more complex
@terse mortar that's a valid form of esoteric Python

#

personally I'm a favour of huge chunks of parentheses/brackets

terse mortar
#

Like it looks amazing and I love it, but still why

earnest wing
#

Underscores are the pinnacle of Python. Chef's kiss.

#

Everything you're interested in has them.

#

The more the merrier.

echo abyss
#
from functools import reduce
def fib(n): return reduce(lambda xy,_: (lambda x,y:(y,x+y))(*xy), [(0,1)]*n)[1]
grave rover
#

Decided to go back to my heart lambda, got it down in size pretty nicely: ```py
(lambda n:(o:=int(n/2))>n or''.join((m:=x/n3)(l:=y/n*3)0 or" #"[(m2+l2-1)3-m2l**3<0]+"\n"[x<o-1:]for y in range(o,-o,-1)for x in range(-o,o)))

#

oh that's funny, highlight.js sees or"..." as o and r"..."

sick hound
#

What does lambda do? What is it different to define?

proper vault
#

lambda is an expression and always gives the function <lambda> as __name__

grave rover
#

isn't it like <lambda at 0x...> or whatever

astral rover
#
>>> (lambda: None).__name__
'<lambda>'```
formal sandal
#

you mean,

#

!e

print((lambda r: r(r))(lambda f: f.__name__))
night quarryBOT
#

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

<lambda>
hexed siren
#

I understand it better in a functional programming language ๐Ÿ˜„

echo abyss
#

They should've made syntax for lambdas little bit shorter

#

It's kinda verbose imo

hexed siren
#

compared to many other languages, python lambdas are very long

proper vault
#

the goal was to discourage lambdas

hexed siren
#

but it's really readable

bitter iris
#

It's kinda verbose imo
@echo abyss you just described the language itself

hexed siren
#

the goal was to discourage lambdas
oh really ? Why that ?

proper vault
#

they are easy to abuse and there are very few actual reasons to use them

echo abyss
#

I've read some 2005 blog post by Guido van Rossum where he says that lambdas may be removed, is there any continuation to this idea?

proper vault
#

no

#

they are valuable in too many places now

#

key arguments for one

marsh void
#

Iโ€™ve actually come to use attrgetter and itemgetter from operator for many cases haha

proper vault
#

same, but it does not handle everything

#

e.g. nested accesses

sick hound
#

lambdas are a nice feature but problematic

#

they are overused for something you could use a built-in function for

#

plus most of the time you should just use a single-line def statement

formal sandal
#

single-line def ๐Ÿ‘€

#

like this?

def f(x): return x**2
twilit grotto
#

takes glasses off: lambda
puts glasses on: single line def

marsh void
#

x**2 more like x * x

#
nekit $ python -m timeit -s "n = 13" "n ** 2"
200000 loops, best of 5: 789 nsec per loop
nekit $ python -m timeit -s "n = 13" "n * n"
5000000 loops, best of 5: 53.3 nsec per loop``` like come on
fervent hull
#

When did this channel become interested in performance?

earnest wing
#

Whenever it implies ridiculous optimizations that verge on writing custom bytecode

formal sandal
#

wdym verge

proper vault
#

Flashbacks to add to both elements of tuple

formal sandal
#

yeah, I'm already searchin gfor that ๐Ÿ™‚

#
from hax import *

@hax
def add_tuples(a, b):
    LOAD_FAST("a")
    UNPACK_SEQUENCE(2)
    ROT_TWO()
    LOAD_FAST("b")
    UNPACK_SEQUENCE(2)
    ROT_THREE()
    BINARY_ADD()
    ROT_THREE()
    BINARY_ADD()
    ROT_TWO()
    BUILD_TUPLE(2)
    RETURN_VALUE()
twilit grotto
#

bruh

vague cairn
#

I NEED HAX MODULE!

next flame
grave rover
#

@formal sandal ```py

(lambda x: 10)
<function <lambda> at 0x7ff7de4d50d0>

#

On 3.8.6 - Arch Linux

formal sandal
#

!e

print(lambda x: 10)
night quarryBOT
#

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

<function <lambda> at 0x7f7b96b8cdc0>
formal sandal
#

not sure why that would depend on your OS ๐Ÿค”

grave rover
#

well, I'm guessing you're on windows and getting <lambda>

next flame
#

str != __name__

#

@grave rover

proper vault
#

^

#

str of most things by default is <type(x) x.__name__ at hex(id(x))>

grave rover
#

oh, I thought you meant the repr

#

my bad

red juniper
#

!e

x = lambda x: x+10
print(x(10))
night quarryBOT
#

@red juniper :white_check_mark: Your eval job has completed with return code 0.

20
formal sandal
#

!e

class Brekception(BaseException):
    ...

class Brek:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):
        return exc_type is Brekception

    def __call__(self):
        raise Brekception
brek = Brek()


for i in range(30):
    with brek:
        if i % 3 == 0 and i % 5 == 0:
            print("FizzBuzz", end=" ")
            brek()
        if i % 3 == 0:
            print("Fizz", end=" ")
            brek()
        if i % 5 == 0:
            print("Buzz", end=" ")
            brek()
        print(i, end=" ")
night quarryBOT
#

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

FizzBuzz 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 
hexed siren
#

๐Ÿ˜ฒ

proper vault
#

as we all know, a pure function and a dict is pretty much the same thing

formal sandal
proper vault
#

__iter__ was certainly fun to make

#

still not sure whether recursively traversing closures or that is better

twilit grotto
#

bruh

astral rover
#

the fact this doesnt work makes me sad


aiohttp.__call__ = lambda func: [func.__setattr__("cool_value", "cool"), func][-1]


@aiohttp
def some_function():
    pass```
next flame
#

hm would it work with forbidden fruit or the other lib

#

@rugged sparrow did you ever put this on github?

sick hound
#

(supposed to be a weird netcat command)

rugged sparrow
#

@next flame i havent yet

#

but that should work with patchy (fyi __call__ as a dunder has a different argument pattern)

#

@next flame im not gonna put it on github but i just updated the copy on replit

#

@astral rover you would have to make <class 'module'> callable, not just aiohttp

#

so all modules would be callable

astral rover
#

is patchy on pypi yet?

rugged sparrow
#

not yet

astral rover
#

TypeError: can't set attributes of built-in/extension type 'module'

#

well that sucks

#

i think id need patchy

rugged sparrow
#
from patchy import *

@patch(ModuleType, '__call__')
def module_call(mod, args, kwargs):
  return mod.__module_call__(mod, *args, **kwargs if kwargs is not Null else {})
astral rover
#

not Null :P

rugged sparrow
#

that would make module(*args, **kwargs) call module.__module_call__(module, *args, **kwargs)

#

yah Null is a placeholder from patchy

astral rover
#

oh right

rugged sparrow
#

its not actually Null

#

@next flame i prob wont put patchy on github until i can handle Exceptions properly

#

rn it just ignores exceptions (cause if it doesnt then ctypes shits itself)

#

i also want to get inheritance to work right

gentle pagoda
#

can type(name, bases, dict) set the metaclass of the type? i tried setting __metaclass__ in the dict but it doesnt work

steep mural
#
class Foo(metaclass=type('', (type,), {})):
  pass
gentle pagoda
#

ah sorry i meant the other way. can i make a type with type() and set its metaclass

#

ie type("Foo", (), {}, metaclass = Bar)

steep mural
#

oh

#

you'd call the metaclass not type if i'm not mistaken?

gentle pagoda
#

ohh of course

#

thanks! :)

compact hemlock
#

hello everyone. I have a problem I cannot solve. I have a string "something\\nsomething" and I would like to remove a single '\', so I'll have "something\nsomething", but when I try for example .replace, I enter a vicious cycle of escaping \ and quotes etc. I've tried with r'' as well.

#

I hope this problem is esoteric enough for this room.

proper vault
#

this is not really for help at all, but try ```py
import codecs
codecs.escape_decode(string.encode('utf-8'))[0].decode('utf-8')

vestal solstice
#

there's a single \ in that string

compact hemlock
#

@vestal solstice In my "problem string", there are two slashes \ preceeding n. this stuff is so esoteric, it maggles with discord as well

#

@proper vault I'll try, thank you!

vestal solstice
#

replace("\\\\n", "\n")

#

that replaces 2 slashes with no slashes

compact hemlock
#

both your answers worked in python 3.9. the codecs and .replace('\n','\n')

#

thank you guys. this stuff annoyed me whole morning

#

two slashes + 'n' substituted by one slash + 'n' *

vestal solstice
#

then it didn't work yet

compact hemlock
#

it did on my cli

#

In [25]: rows[1][0].replace('\n','\n')
Out[25]: '1: 500\n1: 12 500'

vestal solstice
#

"\n" has zero slashes not one slash

compact hemlock
#

jesus these slashes on discord are ridiculous. what they are trying to escape here

vestal solstice
#

if you do replace("\\\\", "\\") you'll get '1: 500\\n1: 12 500'

#

and that has one slash

compact hemlock
#

what I did, is .replace('<twoslashes>n','<oneslash>n')

#

and it worked exactly as I wished it did

vestal solstice
#

congrats

compact hemlock
#

thank you. but it's your victory

rugged sparrow
#

@next flame I think I just cracked Exceptions within patched methods (I manually insert a raise opcode into the upper frame) but rn it replaces the first const in the upper object which can break things so I'm gonna see if I can inject the exception somewhere else.

#

Maybe directly into the frame's stack

formal sandal
#

new idea for an esoteric language

#
le crocodile = "hello";
les crocodiles = [ crocodile, crocodile ];
#

use french articles as datatypes

proper vault
#

is that like raku sigils

#

just french

formal sandal
#

what do sigils do in raku?

proper vault
#

signify general type (scalar, array, hash, function)

twilit grotto
#

huh, just do that, but make it french

#

you could make collections female or something

#

then "single values" male

#

wait no that's dumb lol

#

make collections plural

#

lol

high garnet
#

use french articles as datatypes
@formal sandal what would union types be

twilit grotto
#

le bourgeoisie

formal sandal
#

@high garnet i don't know that much french ๐Ÿ˜›

high garnet
#

bon...jour?

#

๐Ÿฅด

fervent hull
#

le bourgeoisie
Lol won't le prolรฉtariat be the ppl who union?

high garnet
#

Lol won't le prolรฉtariat be the ppl who union?
@fervent hull this is actually excellent

#

I approve

formal sandal
#

would the language also have values of different genders?

#
le x = 42;
la y = 50;
add(x, y); -- ok 

le x = 42;
le y = 50;
add(x, y); -- ERROR!

import SameSexMarriage
le x = 42;
le y = 50;
add(x, y); -- ok
high garnet
#

I

#

I...

#

๐Ÿฅด

fervent hull
#

What if you need a function that takes more than 2 inputs tho

#

import Polygamy

high garnet
#

HEY what if it's platonic addition? ๐Ÿ˜ก

fervent hull
#

We also have to consider gender fluidity of variables maybe

#

Petition to create a letter that both looks like a and e

#

HEY what if it's platonic addition? ๐Ÿ˜ก
That'll raise error because platonic variables can't be combined together

high garnet
#

That'll raise error because platonic variables can't be combined together
@fervent hull and why NOT

#

what's wrong with platonic pairing with benefits

#

hm I'm sure there's a type system somewhere that can encode all of this

fervent hull
#

They can be as close to one another as possible but not combined for platonic reasons

#

Unless I don't understand plantonics ๐Ÿค”

gray pine
#

Petition to create a letter that both looks like a and e
Already exists รฆ

earnest wing
#
lรฆ x = 0t01221 # ternary because non binary
#

arguably this whole thing would be possible to implement in python grammar similar to braces.py

silent trench
#

not really sure where I'd ask this question , but why isn't python a compiled language? what are the benefits of an interpreter, and the GIL?

next flame
#

you can compile python

#

using cython/numba/nuitka/etc

fervent sonnet
#

I think the question is around default behavior with CPython

next flame
#

but the main point of an interpreter is fast development time

silent trench
#

ah gotcha

fervent sonnet
#

aren't python modules compiled at execution to .pyc files?

next flame
#

yeah

silent trench
#

Sorry I dont know a lot, im just curious

next flame
#

but thats still a lot faster than normal compiled langs

silent trench
#

if python can be compiled, why would anyone want to use the interpreter?

fervent sonnet
#

Roslyn leading the charge in server-based compilers has been a godsend on the compiled lang front

silent trench
#

sure faster development time, but once that is done, couldnt you then compile it?

fervent hull
#

if python can be compiled, why would anyone want to use the interpreter?
.pyc are Python bytecodes

silent trench
#

I've never really written an programs, so sorry about my ignorance

next flame
#

plus compiling wont speed it up that much

fervent hull
#

Which the Python interpreter reads and interprets into cpu instructions

next flame
#

(to native code using cython or something)

#

depending on the application

#

and bytecode compilation is cached anyways

silent trench
#

how legitimate of a criticism is "python is slow bc its interpreted"? I hear it thrown around a lot, but it sometimes sounds more like tribalism

next flame
#

sure, it is slower than some other langs

#

but thats not its main selling point anyways

#

plus runtime speed isn't actually as important as you think it would be

crystal thorn
#

It basically is tribalism. The benefits of compiling python with stuff like cython is only applicable in niche scenarios

next flame
#

a lot of the time, speed issues are either IO related or can be fixed by using c extensions

fervent sonnet
#

also some types of jobs are just slow

#

or your algo is bad

next flame
#

plus one of the reasons why a lot of compiled langs are fast is that they can make a lot of optimizations b/c static typing

#

but that doesn't work with python

silent trench
#

huh, interesting.

#

Thanks guys!

twilit grotto
#

because of python's dynamicism (? is that a word) it has to do runtime typechecks which slow down things greatly

high garnet
#

dynamism?

#

๐Ÿค”

twilit grotto
#

dynamicness?

high garnet
#

dynamicability?

sick hound
#

dynamicality makes more sense tbh

#

Not sure if it's a word though

vague cairn
#

On my OS android developer studio is writen in python. Think about that, an OS based on Java has a devkit that is based on something other than java...

#

also pypy will git compile and run your python code with almost no changes required. I'm not sure if there's a bytecode compile in between, or not.

#

Yes, it has bytecodes, and dis.dis() desplays the exactly the same for the first simple function I thought to throw at it.

next flame
#

Android studio is written in kotlin java and c++ according to wikipedia

twilit grotto
#

what OS are you using that's based on java?

rugged sparrow
#

@next flame i solved the exceptions issue, ill prob put it on pypi later this week. I ended up having to alter the callers frame code and stack to raise the exception after the c_callback returns (cause the c_callback has to return)

vague cairn
#

How do you alter the caller's frame/code? I tried and it was only a copy not the active data.

rugged sparrow
#

carefully

#

and you have to modify a lot of it inplace

vague cairn
#

You seem to have done a lot more in 300 lines than I useually hope for.

rugged sparrow
#

i still need to go thru and add more clear comments than # Black Magic, alters the callers frame code and stack to raise Exception after return lmao

night quarryBOT
#

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

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
011 | 10
dreamy oracle
#

Is their any way/code from which I can download profile picture of all my Instagram followers at once?

twilit grotto
#

no

#

well, yes, definitely but that's against tos

dreamy oracle
#

well, yes, definitely but that's against tos
@twilit grotto so like one can make a code? To automate the process? As far as i know instagram doesn't allow automation ๐Ÿค”๐Ÿ˜…

twilit grotto
#

!rule 5

night quarryBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.

dreamy oracle
#

Got it ๐Ÿ‘๐Ÿผ

tiny gyro
#

!rule 3

night quarryBOT
#

3. Listen to and respect staff members and their instructions.

rugged sparrow
#

!e ```py
from ctypes import *
import sys

all = ['goto', 'label']

def compute_jump(frame, label):
code, names = frame.f_code.co_code, frame.f_code.co_names
get_var = lambda i:{**frame.f_globals, **frame.f_locals}.get(names[i])
instructs = [*zip(code[::2], code[1::2])]
for idx, (inst, arg) in enumerate(instructs):
if inst == 106 and names[arg] == label and
isinstance(get_var(instructs[idx - 1][1]), Label):
return bytes([113, (idx - 1) * 2])
raise RuntimeError(f'could not find label [{label}]')

def replace_inst(code, inst, idx):
code_addr = id(code) + bytes.basicsize - 1
raw_code = (c_char * len(code)).from_address(code_addr)
orig, raw_code[idx:idx + 2] = code[idx:idx + 2], inst
return orig

overwritten = [None, None]

class Goto:
def getattr(self, label):
frame = sys._getframe(1)
idx = frame.f_lasti + 2
orig = replace_inst(frame.f_code.co_code, compute_jump(frame, label), idx)
overwritten[:2] = (orig, idx)
mul = getattr

class Label:
def getattr(self, name):
if all(overwritten):
frame = sys._getframe(1)
replace_inst(frame.f_code.co_code, *overwritten)
overwritten[:2] = (None, None)

goto = Goto()
label = Label()

i = 0
label .start
if i > 10:
goto .end
print(i)
i += 1
goto .start
label .end```

night quarryBOT
#

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

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
011 | 10
rugged sparrow
#

^ goto .label in python

twilit grotto
#

but why

rugged sparrow
#

*why not

#

it also supports computed labels like goto *str_var

#

and jumping into/out of loops

#

it also unpatches its injected JUMP_ABSOLUTE when it hits the label in case the original op was a jump target

sudden osprey
#

Ooooh nice. I'm gonna have to try and work out how that's working at some point ๐Ÿ˜…

fervent sonnet
#

has a context-aware self ever been discussed in PEPs?

late barn
bitter iris
#

has a context-aware self ever been discussed in PEPs?
@fervent sonnet what do you mean by a context aware self?

late barn
#

came up with these two

def solution(S):
    S = S.split("\n")

    h,r = S[0],S[1:]

    return "\n".join(x for x in [h]+[",".join(v for v in s.split(",") if v != "NULL") for s in r] if x)

def solution2(S):
    return S.replace(",NULL", "").replace("\nNULL", "\n")

def solution3(S):
    return "\n".join(x for x in [",".join(v for v in s.split(",") if v != "NULL") for s in S.split("\n")] if x)
fervent sonnet
#

@bitter iris it's hard for me to describe, but basically in expressions, that "this" is referenceable

a = {'k': 'v'}
a['k'] = self + 'etc'
       # ^ `self` would be `a['k']`
rugged sparrow
#

@fervent sonnet that's unlikely due to the existence of assignment operators like +=

fervent sonnet
#

I'm not sure how that would be a blocker

bitter iris
#

@bitter iris it's hard for me to describe, but basically in expressions, that "this" is referenceable

a = {'k': 'v'}
a['k'] = self + 'etc'
       # ^ `self` would be `a['k']`

@fervent sonnet no no no no

fervent sonnet
#

yes yes yes yes ๐Ÿ˜ˆ

stark fable
#
a['k'] = self + 'etc'``` aka ```py
a['k'] += 'etc'``` :P
proper vault
#

self is definitely not the name to use for it

vague cairn
#

Some of that is already built into the language, if you want to write a seperate __add__() and __radd__() and __iadd__() you can. I'm not sure if there is a cannonical way for you to check if you're stored in a dict and are getting +='ed instead of getting +'ed and then assigned elsewhere.

#

you can definitely dis.dis your calling frame's code and try to guess.

fervent sonnet
#

@proper vault no, but it expressed what I was looking for the best

bitter iris
#

well, python is such a dynamic language that allows you to patch into interpreter startup (it actually doesn't allow and discourages, but honestly who cares in this channel). So you can write a very simple AST transformer to replace every self in assign context and replace it with the target. Of course, don't forget that assignment targets is a list, a = b = c (a, b are the targets!)

#

Feel free to write python, as you'd like. That is one of the features that I really like to abuse ๐Ÿ˜†

fervent sonnet
#

ain't nobody got time for that. I'm struggling to maintain three different apps at work as-is ๐Ÿฉธ

vague cairn
#

๐Ÿ™‚

bitter iris
#

ain't nobody got time for that. I'm struggling to maintain three different apps at work as-is ๐Ÿฉธ
@fervent sonnet there is always time to smuggle some new syntaxes into python!

sick hound
#

anyone good with real time image learning in opencv

bitter iris
#

@sick hound probably wrong channel mate

sick hound
#

oo

#

thought this was a python channel

next flame
#

check the channel description ๐Ÿ™‚

fervent sonnet
#

โ›ณ

formal sandal
#

@fervent sonnet I made a horrible this implementation

#

but it will have to be changed from globals to builtins to work across modules, I suppose

fervent sonnet
#

@formal sandal you monster

final terrace
#

There really should be a computer vision channel

#

@sick hound I'm bad with image learning in opencv

#

but that is better than nothing

#

also CV is automatically esoteric and wierd

#

so maybe it should be here

twilit grotto
#

computer vision is a legitimate use case for python though

final terrace
#

computer vision is the MOST legit

#

computer vision is god

#

openCV is pretty annoying though

twilit grotto
#

unlike the other things in this chat, like goto

final terrace
#

I suppose this is where the PEP-8 resistance hangs out

next flame
#

does cv not fall under data science?

#

I thought it was like ML but correct me if I'm wrong

#

@final terrace

twilit grotto
#

i thought so too

high garnet
final terrace
#

CV is not data science

twilit grotto
#

how is it not

next flame
#

isn't it machine learning

high garnet
#

CV is not data science
@final terrace the name of the channel is #data-science-and-ml, but it includes machine learning, which includes computer vision

#

and also

#

"related topics"

final terrace
#

CV is its own field completely. You can use it with AI/machine learning but making a CV program is like neuroscience almost

twilit grotto
#

neuroscience for computer vision?

next flame
#

how do you do computer vision without ml?

high garnet
#

artificial neuroscience ๐Ÿ˜„

#

they're not called artificial neural networks for nothing (this is a joke)

final terrace
#

ok that was stupid, not neuroscience

#

but you are effectively simulating functions of the visual cortex, even if you don't realize it

#

it's a science of pattern recognition... shit... maybe it is data science

twilit grotto
#

yeah

high garnet
#

๐Ÿฅด

#

I mean

twilit grotto
#

you use your ML model to guess what stuff is after you feed it a million images

high garnet
#

I wouldn't necessarily call computer vision data science, but it is on topic for the #data-science-and-ml channel

final terrace
#

but also CV does not really imply ML because you can just manually tweak the algorithms to do basic stuff without any training data

#

if you are using shapes you don't really need ML at all

#

basic shapes

high garnet
#

yup

#

that's true

#

I agree with that part

final terrace
#

It just feels like its own thing. It's also a big thing in automation/testing

high garnet
#

It just feels like its own thing. It's also a big thing in automation/testing
@final terrace you could say NLP is its own thing

#

and in the working world, for example, yes, you would not be able to pull a rando data scientist off the street and thrust them into a CV engineer position

strange junco
#

can someone help me

#

please

high garnet
#

I mean, honestly, we don't really have that much people in DS, let alone CV

#

this is a channel for demonic Python and you probably don't want that

strange junco
#

alr my bad

final terrace
#

sorry I will shut up, but honestly CV in its most common usage belongs 50% in automation category

high garnet
#

sorry I will shut up, but honestly CV in its most common usage belongs 50% in automation category
@final terrace fair enough

#

I wouldn't know because I encounter CV only in ML

#

in that case, if you want to talk about the CV implementation

#

๐Ÿคทโ€โ™‚๏ธ

#

or maybe not really the right server at all

#

what do you mean

#

automation category actually

final terrace
#

think aimbots, game bots, JS canvas automation + selenium

high garnet
#

yeah, like I said

final terrace
#

If you are asking me to shut up sorry. Just talking haha

#

I understand

high garnet
#

nope

#

I'm not

#

like I'm just answering your question from the perspective of the server

#

and, yes, I do understand that a ton of CV doesn't involve ML/DL

#

but again, if you're asking "where to discuss CV", I would say #data-science-and-ml is the best place.

final terrace
#

ok. Yeah CV is just really interesting. It covers many categories. I'm not really asking anything

high garnet
#

and if you're asking "do you think CV is part of DS"...I think we went through that ๐Ÿ‘‹

final terrace
#

but my point stands. They should totally make an OpenCV channel because it's a field of its own if you look at coursera and such there are entire courses dedicated to it and communities

#

and since python is a huge part of the userbase it would be a good addition here

high garnet
#

but my point stands. They should totally make an OpenCV channel because it's a field of its own if you look at coursera and such there are entire courses dedicated to it and communities
@final terrace yes, but Coursera is Coursera (also this is off topic I think #community-meta would be a good place to suggest that)

#

and I think the PoV of the server owners is "are there enough people who want to talk about it to create a channel dedicated to it?"

#

and honestly I very rarely see OpenCV-specific questions

#

very

#

like once a week or something

final terrace
#

I suggested it, thanks

high garnet
#

yw

#

kinda went off topic

#

I apologise to the lord of esoteric Python

terse mortar
#

I apologise to the lord of esoteric Python
@high garnet consider you are an active user in this channel, you got a lot more to apologize for them going slightly off topic lol

floral meteor
#

When I see esoteric I think of this Esolang

++++++++++[>++++++++++<-]>--.++++.
#

I've made an interpreter in Python

sick hound
#

yes

#

and regex

#

and math

rugged sparrow
#

so i just found a way to manipulate the bytecode of the code of Module A when Module B is imported (from within Module B)

#

wonder what terrible things i can do with that.

formal sandal
#

macros lemon_scared

rugged sparrow
#

Sadly I can't quite manipulate ast yet, my method happens after compilation

#

But as long as it compiles to valid byte code then you can mutate that

vague cairn
#

So ... can you decorate an import?

rugged sparrow
#

Wdym by decorate @vague cairn

echo abyss
#

I think he means applying some function to imported module object with decorator syntax

#

like

@decorate
import xyz
--- v ---
xyz = decorate(__import__("xyz"))
rugged sparrow
#

sadly that is invalid syntax but if you did something like py decorate_func:decorate import xyz

#

then i could write a bytecode patcher that transforms it

vague cairn
#

Nice!

#

I suppose one could also: py import x_y_z as xyz xyz = decorate_module(xyz)

sick hound
#

@rugged sparrow How would you go about transforming that?

rugged sparrow
#

By mutating the byte code of the module that imported my code

sick hound
#

How do you get the byte code of a module?

formal sandal
#

don't know if it counts as esoteric, but I can finally use my crazy new language in the browser!

#

(a Python program transpiles it to JS)

rugged sparrow
#

@sick hound by traversing the stack frames

sick hound
#

People in #python-discussion were talking about how you would go about solving this challenge:

#

The objective is to make a function that returns x//10, but some operators arenโ€™t allowed, you also arenโ€™t allowed to have any of, โ€œeiouโ€ in the code

#

Full details are in webpage above

#

Iโ€™ll give it a try in the morning

olive badger
#

Yeah. The best we could come up with is some way to use bitshifting and lambda.

#

For example
x>>y is the same as x//(2**y)
The problem is that you can only use >> with integers.

patent fulcrum
#

The input value would be an integer.

#

But bit shifts can only multiply/divide by a power of 2.

olive badger
#

But bit shifts can only multiply/divide by a power of 2.
@patent fulcrum Yeah and we need to divide by 10 which is not a power of 2.

patent fulcrum
#

Right. So there must be some other trick involved.

olive badger
#

mhmm

patent fulcrum
#

I see no restriction in the problem about using only one variable.

olive badger
#

with only 1 variable it seems hard
@crimson zinc Not quite what they're saying. They are saying that the only vowel you can use is "a".

patent fulcrum
#

Just certain letters and characters are disallowed.

olive badger
#

Right

#

ya

patent fulcrum
#

No need to call input() to solve the problem.

#

I have an idea too but I have to think about it a bit more.

olive badger
#

input has other vowels
@crimson zinc Yes input has i and u so you can't use it.

#

@crimson zinc Tried using an accented "e". Did not work

>>> def func():
    rรจturn 2
mint holly
#

unless thats an exception, its gotta be a lambda

olive badger
#

@crimson zinc Can you give any hints, please?

patent fulcrum
#

I accidentally found the code you mentioned while looking for information. No way would I have ever figured that out without extensive pencil and paper manipulations.

olive badger
#

Alright ty

mint holly
#

heres whats available as a starting point 'abs', 'all', 'any', 'chr', 'hasattr', 'hash', 'map', 'max', 'str', 'vars'

patent fulcrum
#

This is more of a math challenge than a Python challenge.

olive badger
patent fulcrum
#

The Python is elementary. The mathematical knowledge is not. Well, it is, but you would have to work through it.

olive badger
#

hmm

mint holly
#

you can make arbitrary strings with chr and concatenation

patent fulcrum
#

Using lambda and bit shifts (<< and >>) was the right idea. But you would need to work out a lot of math to find the right sequence of shifts.

mint holly
#

is it really just a fancy math solution?

#

thats a bit lame

patent fulcrum
#

Yeah. Basically just how can you find the answer using only addition, subtraction, multiply by a power of 2, and integer divide by a power of 2.

earnest wing
#

This seems like something you can probably solve by twiddling around in desmos

#

Just finding a function in the right form and then fuzzing around with constants

mint holly
#

I took a different path

#
_=vars()
devsaan = lambda x: vars(_["\137\137\142\165\151\154\164\151\156\163\137\137"])["\145\166\141\154"](f"\137\137\151\155\160\157\162\164\137\137\50\47\157\160\145\162\141\164\157\162\47\51\56\146\154\157\157\162\144\151\166\50{x}\54\61\60\51")
#

took a lot of fiddling to get that in its final form

#

I think thats a much more fun solution than a mathy approach

#

its basically

eval(f"__import__('operator').floordiv({x},10)")
``` but with extra steps
#

the biggest hurdle was figuring out how to get access to eval

#

my approach was basically vars(vars()["__builtins__"])["eval"]

#

but vars() is basically just locals(), and I needed the globals, so I save it first with _=vars()

#

ah, actually, I wasnt paying much attention to golfing it, I could use int.floordiv instead

fervent hull
#

Given that you can encode arbitrary command why not just encode x//10?

mint holly
#

you know, thats fair

#

I dont do much golf

#

or any, actually

#
_=vars()
devsaan=lambda x:vars(_["\137\137\142\165\151\154\164\151\156\163\137\137"])["\145\166\141\154"](f"{x}\57\57\61\60")
#

125 characters

fervent hull
#

You can put in the characters that are not banned to shorten it

earnest wing
#

no need to use octal escapes for "allowed" chars

mint holly
#

ah, good catch

#
_=vars()
devsaan=lambda x:vars(_["__b\165\151lt\151ns__"])["\145val"](f"{x}\057\05710")
``` 87 chars
fervent hull
#

Also you can get rid of the first 0 in \057. The second \057 has to be complete I believe

mint holly
#

ah, yep

#
_=vars()
devsaan=lambda x:vars(_["__b\165\151lt\151ns__"])["\145val"](f"{x}\57\05710")
``` 86
fervent hull
#
davasaan = lambda x: x.__class__("0" + str(x)[:-1])
earnest wing
#

no dot allowed

mint holly
#

^

fervent hull
#

Oh right

mint holly
#

whoops, I got the name wrong

#
_=vars()
davasaan=lambda x:vars(_["__b\165\151lt\151ns__"])["\145val"](f"{x}\57\05710")
``` 87 chars
fervent hull
#
davasaan=lambda x: getattr(x, "__class__")("0" + str(x)[:-1])
mint holly
#

getattr

#

e

fervent hull
#

Just realized that

#

I was thinking about hasattr ๐Ÿ˜ฆ

mint holly
#

you're basically restricted to [] for getting stuff

#

which is what led me to vars

#

taking your approach

_=vars()
davasaan=lambda x:vars(_["__b\165\151lt\151ns__"])["\151nt"]("0"+str(x)[:-1])
``` 86
#

shaved a character from eval to int

earnest wing
#

A recursive lambda ought to do this with more ease

#

Here's an ungolfed version

f=lambda x:(x>=0 and f(x-10)+2)-1
mint holly
earnest wing
#

setrecursionlimit and execute in REPL ๐Ÿง 

#

although might overflow

mint holly
#

200,000,000 stack frames

#

def gonna overflow

earnest wing
#

implementation dependent => no need to worry about it ๐Ÿ˜Ž

#

all of my python programs are run on an ideal turing machine

#

Speaking of, can the input and output of the function be church numerals? The challenge doesn't specify that. :v)

#

Although combinators are unfortunately pretty verbose in python, hitting the 300 char limit

snow beacon
#
davasaan=lambda x:(1).__class__(str(x)[:-1])
```?
#

Or replace those brackets with a trailing space for one less character.

#

Or x instead of (1) actually.

#

Oh, will that break on 0?

stark fable
#

on any 1-digit number it will give a ValueError

snow beacon
#
davasaan=lambda x:x.__class__(str(x)[:-1]or 0)
stark fable
#

yep, that works

#

...i think

#

i haven't actually tested it but it looks good

snow beacon
#

I'm on mobile so I haven't either.

#

A quick test, and good thing it doesn't need to work on negative numbers.

rugged sparrow
#

@snow beacon can't use .

#

Or o so no or

snow beacon
#

Those are entirely valid criticisms.

rugged sparrow
#

You can use vars() to get builtins tho

mint holly
#

going the int() route, I havent been able to find anything better for the param than "0"+str(x)[:-1]

rugged sparrow
#

!e py d=lambda n,v=vars(),k=lambda w,x:sum(map(lambda k:[k],w),[])[x]:(q:=vars(v[k(v,-2)]))[k(q,64)]('0'+str(n)[:-1]) print(d(100))

night quarryBOT
#

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

10
earnest wing
#

no "u"

rugged sparrow
#

ah damn

stark fable
#
davasaan=lambda x:vars(x)['__class__']('0'+str(x)[:-1])```
#

since int ignores leading 0s apparently (i tested it)

#

oh but actually this doesn't work because you can't vars an int ._.

#

hmm

#
davasaan=lambda x,v=vars():vars(v['__b\165\151lt\151ns__'])['\151nt'](f'0{x}'[:-1])``` i think this works
sick hound
#

Hello people. I failed turning a modest for loop into a one liner:

#
    dispose = set()
    for index, item in enumerate(prosodies, 1):
        if item in dispose:
            return index
        dispose.add(item)
#

I am looking for the index of the first duplicate in prosodies (the "1" start is irrelevant).

#

This is what I got so far:

#
next(filter(lambda enumeration: enumeration[1] in dispose, map(lambda x: dispose.add(x[1]), enumerate(prosodies, 1))))[0]
#

... and naturally it fails because I am returning the result of dispose.add(x[1]) in the lambda ... among other reasons.

#

Suggestions?

sick hound
#

Heh, I found a way but it sucks ...

#
dispose = set()
def check_add(couple):
   a = couple[1] in dispose
   dispose.add(couple[1])
   return a

return next(filter(lambda i: check_add(i), enumerate(prosodies, 1)))[0]
#

I don't like the "a" assignment on line three. Any improvement's welcome.

last locust
#
if couple[1] not in dispose:
    dispose.add(couple[1])
    return False
return True```ig something like this might be slightly clearer in terms of removing the "a" assignment
#

Pretty sure you can do stuff with operators too but idk enough about them

paper bloom
#

also, why invoke lambda if you have defined a function?

silent stump
#

@paper bloom using lambda is faster than if you create a new function

paper bloom
#

but they already created the function...

#

also, lambdas and functions are the same speed

#

lambdas are shorter to write sure, but they're also harder to read if you make them complicated

#

!e ```py
import dis

def foo(): return 10
bar = lambda: 10

print(dis.dis(foo))
print(dis.dis(bar))

night quarryBOT
#

@paper bloom :white_check_mark: Your eval job has completed with return code 0.

001 |   3           0 LOAD_CONST               1 (10)
002 |               2 RETURN_VALUE
003 | None
004 |   4           0 LOAD_CONST               1 (10)
005 |               2 RETURN_VALUE
006 | None
formal sandal
#

if lambdas were faster than defed functions, then CPython could make a normal function an alias for creating a lambda and assigning it to a name

#

as an optimization

paper bloom
proper vault
#
    dispose = set()
    for index, item in enumerate(prosodies, 1):
        if item in dispose:
            return index
        dispose.add(item)
(lambda r=[None]:({*iter(lambda s=set(),i=iter(prosodies):[ r[0] in s for r[0] in [next(i) ] ), [True]}, r)[-1]
```should work, though I did not test it.
sick hound
#

Quick question,

#

How would you type

#
from typing import *
from ctypes import *

def func(*pointers: ...):
    pass
#

POINTER(T) does not work

#

One thing I can do is use TypeVar, like PointerT = TypeVar("PointerT"), but is there any better way to do it?

flint cradle
#

Hey all, so bit of a stupid question. But I am creating a (right now just testing out making it) shell for a program I am writing and part of this is having builtin commands. I was wondering if anyones ever built a shell of sorts with builtins and used something like argparse to parse arguments for your builtin commands? Currently I am getting it to catch but its immediately exiting my program upon parsing the arguments instead of returning control back to the loop.

next flame
#

wrong channel

vague cairn
#

I've used argparse once or twice, but it's more for a command line interface (someone else's shell, your command just accepts arguments), and less for a read parse evaluate loop. I know there are libraries for parsing Python-like code, but I've never used them.

formal sandal
#

@flint cradle Well, you could write your own little parser for commands.

foo -abc --bar baz --xxx "hello world"
=> Command("foo", frozenset({"a", "b", "c"}), {"bar": "baz", "xxx": "hello world"})
#

you could write your own parser or use an existing parser generator library (like lark)

next flame
#

does shlex do that?

formal sandal
#

uhh... yes, probably ๐Ÿ™‚

next flame
#

but argparse should also work

#

wait

#

Use both

#

shlex to convert to argv

#

argparse to parse argv

sick hound
#
    dispose = set()
    for index, item in enumerate(prosodies, 1):
        if item in dispose:
            return index
        dispose.add(item)
(lambda r=[None]:({*iter(lambda s=set(),i=iter(prosodies):[ r[0] in s for r[0] in [next(i) ] ), [True]}, r)[-1]
```should work, though I did not test it.
@proper vault Thanks, hadn't noticed the answer. It looks like an intricate puzzle. Will have a good look at it.
#

also, why invoke lambda if you have defined a function?
@paper bloom Absolutely. I used the defined function in lieu of the lambda. That was a left over from previous attempts.

flint cradle
#

@formal sandal @next flame so I mostly seem to have gotten it. I just had some really stupid programatic issues going on. Part of one is passing the entire input from my "commandline" instead of splitting out the command and the args, passing the args as a list caused it to work properly. If I run acommand with everything as needed, it automatically will parse it all and return control to my shell. However invoking the help menu of the command causes it to yeet my shell. I suspect because usage of -h causes a sys.exit() I'd imagine.

#

Got it. Just had to catch a call for sys.exit

flint cradle
#

Still some issues but I can figure it out from here.

next flame
#

is there any way to get the actual ctypes type from a Structure field

#

since apparently it auto coerces to a normal python type

naive roost
#

Hey guys, I was wondering if you could execute arbitrary code from ..., which is to say get to eval (and also chr, basically getting to __builtins__), using only attributes of ... and its attributes, and so on.
For instance, you can get 1 as ....__eq___(...), and type as ....__class__.__class__

proper vault
#

....mro()[-1].__subclasses__ gets you quite a few types, so you could manually construct a function from bytecode, but I don't remember the proper way to get built ins.

rugged sparrow
#

you can get an importer from object.__subclasses__

naive roost
#

Hum... thanks, but where's the importer in that mess?

#
>>> len(....__class__.__mro__[-1].__subclasses__())
749
``` Yep, it's a mess
#

I'll look at it again later, but thanks for the help

floral meteor
snow beacon
#

How does it choose the indentation for the python else: passparts?

floral meteor
#

it doesn't choose. I do.

#

It was half a parabola but then I had to return after all the loops, so I finished the parabola with no-ops

formal sandal
#

if Python didn't have significant whitespace, you could even put comments inside the parabola

earnest wing
#

Now we need a script that takes an increasing function f(n) as input and applies the appropriate level of indentation [f(n) spaces for n-level indents] to a python program.

#

The only risk is that you mangle the AST.

#

Somehow.

next flame
#

something like ....__class__.mro()[1].__subclasses__()[132].close.__globals__["__builtins__"]["eval"]("2+2")

#

except replace all the string literals with slicing docstrings

#

oh wait we dont have numbers

#

uh just sum True a bunch of times to get ints

sick hound
#

Hi guys,

next flame
#
In [68]: _l= ....__class__.mro()[1].__subclasses__()[7]

In [69]: _l(_l(....__class__.mro()[1].__subclasses__()[132].close.__globals__.values())[7].values())[19]
Out[69]: <function eval(source, globals=None, locals=None, /)>
rugged sparrow
#

!e py print(....__class__.mro()[1].__subclasses__()[-1].__call__.__globals__['__builtins__']['eval'])

next flame
#

oh wait -1 would be easier

rugged sparrow
#

yea

#

!e py print(....__class__.__base__.__subclasses__()[True-True-True].__call__.__globals__['__builtins__']['eval'])

night quarryBOT
#

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

<built-in function eval>
earnest wing
#

strings are constructed from small snippets of docstrings, indexed using integers constructed with boolean addition, constructed with ....__eq__

rugged sparrow
#

!e py print([*[*....__class__.__base__.__subclasses__()[True-True-True].__call__.__globals__.values()][((True+True+True)*(True+True))+True].values()][(((True+True+True)*(True+True+True))*(True+True))+True])

night quarryBOT
#

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

<built-in function eval>
next flame
#

!e ```python
#!/usr/bin/env python3
one = ....eq(...)
two=one+one
three=two+one
four=three+one
five=four+one
twentyfive=fivetwo
seven= five+one+one
_16=four
two
nineteen=_16+three
_499 = twentyfive * five * four - one
_407 = fivefive_16+seven
int_doc=....class.mro()[1].subclasses()[4].doc
eval_str = int_doc[_499]+int_doc[_407]+int_doc[_499] # "2+2"
_l= ....class.mro()[1].subclasses()[7]
print(_l(_l(....class.mro()[1].subclasses()[one.neg()].call.globals.values())[seven].values())nineteen)

night quarryBOT
#

@next flame :white_check_mark: Your eval job has completed with return code 0.

4
twilit grotto
#

wtf?

steep mural
#

Lol

earnest wing
#

should the arithmetic ops explicitly use the dunders?

snow beacon
#

....__ne__(...).__invert__() is -1, if that helps with golfing.

#

....__eq__(...).__neg__() is shorter, I suppose.

#

Indeed, it looks like this will not help.

thin trout
#

!e print(....class.mro()[1])

night quarryBOT
#

@thin trout :white_check_mark: Your eval job has completed with return code 0.

<class 'object'>
thin trout
#

Noiiice

naive roost
#

technically, you need eval to assign values

#

!e ```py
import sys
print(sys.version)

night quarryBOT
#

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

001 | 3.8.0 (default, Nov 23 2019, 05:49:00) 
002 | [GCC 8.3.0]
naive roost
#
>>> ....__class__.__base__.__subclasses__()[....__eq__(...).__neg__()].__call__.__globals__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'method-wrapper' object has no attribute '__globals__'
``` hum... I don't know why it doesn't work that way, though
frigid wharf
#

!e ```py
print(....class.base.subclasses()[....eq(...).neg()])

night quarryBOT
#

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

<class '_sitebuiltins._Helper'>
frigid wharf
#

!e py print(....__class__.__base__.__subclasses__()[....__eq__(...).__neg__()].__call__)

night quarryBOT
#

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

<function _Helper.__call__ at 0x7f4287e92160>
frigid wharf
#

!e ```py
print(....class.base.subclasses()[....eq(...).neg()].call.globals)

night quarryBOT
#

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

001 | {'__name__': '_sitebuiltins', '__doc__': '\nThe objects used by the site module to add custom builtins.\n', '__package__': '', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f0153b23d60>, '__spec__': ModuleSpec(name='_sitebuiltins', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7f0153b23d60>, origin='/usr/local/lib/python3.8/_sitebuiltins.py'), '__file__': '/usr/local/lib/python3.8/_sitebuiltins.py', '__cached__': '/usr/local/lib/python3.8/__pycache__/_sitebuiltins.cpython-38.pyc', '__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <built-in function __import__>, 'abs': 
... (truncated - too long, too many lines)

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

naive roost
#
>>> print(....__class__.__base__.__subclasses__()[....__eq__(...).__neg__()].__call__)
<method-wrapper '__call__' of type object at 0x1bc4d30>
``` yep, that's a problem
rugged sparrow
#

its because the layout of object subclasses is completely dependent on interpreter version/the startup order

naive roost
#

I think the problem is more about the method-wrapper than it is about the object subclasses layout

rugged sparrow
#

well if the class at the end of object.__subclasses__ has a user defined call then it will have a __globals__

#

if we can do a loop (idk the limitations) then we can do [*[c for c in object.__subclasses__() if type.__sizeof__(c) > type.__sizeof__(type)][-1].__dict__.values()]

#

which will get us a guarenteed user defined class

#

!e ```py
print([*[c for c in object.subclasses() if type.sizeof(c) > type.sizeof(type)][-1].dict.values()][2])

night quarryBOT
#

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

<function _Helper.__repr__ at 0x7f14172d70d0>
rugged sparrow
#

!e py print([*[c for c in object.__subclasses__() if type.__sizeof__(c) > type.__sizeof__(type)][-1].__dict__.values()][2].__globals__['__builtins__'])

night quarryBOT
#

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

001 | {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <built-in function __import__>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'breakpoint': <built-in function breakpoint>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <b
... (truncated - too long, too many lines)

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

naive roost
#

I'm not sure you can do the comprehension, though

next flame
#

!e ```python
(....class.mro()[....eq(...)].subclasses()[(((....eq(...)+....eq(...)+....eq(...)+....eq(...))+....eq(...))+....eq(...)+....eq(...))])( (....class.mro()[....eq(...)].subclasses()[(((....eq(...)+....eq(...)+....eq(...)+....eq(...))+....eq(...))+....eq(...)+....eq(...))])(....class.mro()[1].subclasses()[....eq(...).neg()].call.globals.values() )[(((....eq(...)+....eq(...)+....eq(...)+....eq(...))+....eq(...))+....eq(...)+....eq(...))].values())(((....eq(...)+....eq(...)+....eq(...)+....eq(...))+....eq(...))*(....eq(...)+....eq(...)+....eq(...)+....eq(...)))

night quarryBOT
#

@next flame :white_check_mark: Your eval job has completed with return code 0.

4
naive roost
#

you'll need to use int.__add__ instead of +

next flame
#

oh wait

#

i need to fix the ints

next flame
#
#!usr/bin/env python3
import subprocess
import sys

def gen_int(i):
    if i == 0:
        return "_0"
    if i >= 25:
        res = f"_25.__mul__({gen_int(i//25)})"
    else:
        res = "_0"
    i = i % 25
    if i >= 5:
        res += f".__add__(_5.__mul__({gen_int(i//5)}))"
    i = i % 5
    res += ".__add__(_1)" * i
    return res

docs = "....__class__.mro()[1].__subclasses__()[{}].__doc__"
chars = {}
for i in range(100):
    doc = eval(docs.format(i))
    if isinstance(doc, str):
        for j, c in enumerate(doc):
            if c not in chars:
                chars[c] = (i, j)

def gen_char(c):
    try:
        i, j = chars[c]
        assert eval(gen_int(i), {"_0": 0, "_1": 1, "_5": 5, "_25": 25}) == i, i
        assert eval(gen_int(j), {"_0": 0, "_1": 1, "_5": 5, "_25": 25}) == j, j
        return f"_s[{(gen_int(i))}].__doc__[{gen_int(j)}]"
    except KeyError:
        return f"_b[14]({gen_int(ord(c))})"

inp = sys.stdin.read()
res = "+".join(map(gen_char, inp))
with open("template.py") as f:
    template = f.read()
template = template.replace("GENERATED", res)
stdout = subprocess.run("cpp", check=True, input=template.encode(), stdout=subprocess.PIPE).stdout
print("".join(line for line in stdout.decode().split("\n") if line and not line.startswith("#")))
#

template.py:

#define _0 ....__ne__(...)
#define _1 ....__eq__(...)
#define _4 _1.__add__(_1).__add__(_1).__add__(_1)
#define _5 _4.__add__(_1)
#define _7 _5.__add__(_1).__add__(_1)
#define _20 _5.__mul__(_4)
#define _25 _5.__mul__(_5)
#define _s ....__class__.mro()[_1].__subclasses__()
#define _l _s[_7]
#define _b _l(_l(_s[_1.__neg__()].__call__.__globals__.values())[_7].values())
_b[_20](GENERATED)
naive roost
#

that looks a lot like cheating

next flame
#

most of that is just generating the string to exec

steep mural
#

Wait a minute

#

Interesting

next flame
#

_b[_20] is exec

#

but this should theoreticlaly work with any program

zealous widget
#

!e

import networkx
night quarryBOT
#

@zealous widget :warning: Your eval job has completed with return code 0.

[No output]
zealous widget
#

well, now i know

sick hound
#

how do you kill a multithread?

#
def get_proxies(amount):
    N_THREADS=50
    if amount < 50:
        N_THREADS = amount
    with requests.Session() as session:
        with ThreadPoolExecutor(max_workers=N_THREADS) as executor:
            proxies = scrape_proxies(session, executor, amount)
            executor.shutdown(wait=False)
    return proxies
#

.shutdown(wait=False) seems to not work. It stops on that line.

sick hound
#

nvm forget my question im switching to nice easy async

steep mural
#

you dont kill a thread

sick hound
#

does anyone have the link to the oneliner lambda quicksort?

proper vault
#
quicksort = lambda a:(lambda f,a:f(f,a))(lambda f,a:a if len(a) < 1 else f(f, [x for x in a[1:] if x <= a[0]])+[a[0]]+f(f, [x for x in a[1:] if x > a[0]]),a)
```I do not, but I can make one
sick hound
#

thanks

echo abyss
#

In JS there's a library that provides a decorator that makes functions optionally curried. It looks like that:

const add = ((x, y) => x + y).autoCurry()

add(4) // y => 4 + y
add(4,5) // 9
add(4)(5) // 9
add(4)()(5) // 9

And it allows it to do with any number of arguments. Is that possible in python?

mint holly
#

assuming your function has a fixed number of positional args, yeah

#

not too hard to come up with a class that can wrapp it with a call that stores the args and returns itself, and executes when it has all of them

echo abyss
#

How can I get argument count of a function?

mint holly
#

look into inspect.getfullargspec

#

inspect has all kinds of tools for that kind of introspection

echo abyss
#
class curried:
    def __init__(self, fun):
        self.fun = fun
        self.args = []
    def __call__(self, *args):
        self.args.extend(args)
        if self.fun.__code__.co_argcount <= len(self.args):
            return self.fun(*self.args)
        return self

def curry(fun):
    return lambda *args: curried(fun)(*args)
    

@curry
def xyzzy(a, b, c):
    return a + b - c
#

It kinda worked

#

@rugged sparrow can you apply decorator to all functions in the module?

mint holly
echo abyss
#

@mint holly call your function two times

mint holly
#

ah

echo abyss
#

Apparently builtins do not have code

mint holly
#
import inspect

class curried:
    def __init__(self, fun, args=None):
        self.fun = fun
        self.arg_length = len(inspect.getfullargspec(fun).args)
        self.args = args or ()
    
    def __call__(self, *args):
        new_args = self.args + args

        if len(new_args) == self.arg_length:
            return self.fun(*new_args)

        return type(self)(self.fun, new_args)
#

probably want to be more thoughtful with the arg_length check, but you get the idea

rugged sparrow
#

@echo abyss you could loop over everything in mod.__dict__ after importing it, or you may be able to use import hooks to do it

echo abyss
#

It's sad you can't get arguments for operator builtins ๐Ÿ˜”

mint holly
echo abyss
#

Didn't worked for me, I'm on python 3.6.9 tho

mint holly
#

hmm, seems its >= 3.7

#

I wasnt aware of that difference

#

speaking of 3.7 features I was unaware of

#

thats pretty neat

sick hound
#

Is there any silly or esoteric pip modules out there?

alpine flower
wispy forge
#

but why

marsh void
#

five

thin trout
#

Fun fact this library is why six is six and not five

marsh void
#

lmao fr?

#

awesome

formal sandal
#

AFAIK it (the JS five package) is kind of a mockery of small NPM packages

#

it's funny until you see that Webpack transitively depends on it 4 times

marsh void
#

yup

bitter iris
#

Fun fact this library is why six is six and not five
@thin trout wait, really?

#

I thought it was 2 * 3

sick hound
#

The name, โ€œsixโ€, comes from the fact that 2*3 equals 6. Why not addition? Multiplication is more powerful, and, anyway, โ€œfiveโ€ has already been snatched away by the (admittedly now moribund) Zope Five project.

bitter iris
#

oh, interesting!

manic geyser
#

Well, 6 is 2 and 3. If had to be 2 or 3 then 5 would be better. Well, finally the weird CS math paid off

quasi geyser
#

i saw a quicksort version

#
mergesort = lambda a: (lambda f,g,h,a: f(f,g,h,a))(lambda f,g,h,a: a if len(a)<2 else (lambda x: h(f,g,h,x[0],x[1],[]))(g(f,g,h,a)), lambda f,g,h,a: (f(f,g,h,a[:len(a)//2]),f(f,g,h,a[len(a)//2:])), lambda f,g,h,a,b,c: c+a if b==[] else c+b if a==[] else h(f,g,h,a[1:],b,c+[a[0]]) if a[0]<b[0] else h(f,g,h,a,b[1:],c+[b[0]]), a)```
terse mortar
#

ngl i thought i was in #discord-bots and i was, uhh, rather concerned.