#esoteric-python

1 messages · Page 44 of 1

earnest snow
#
Traceback (most recent call last):
  File "C:\Users\lavid\b.py", line 1, in <module>
    from a import b
  File "C:\Users\lavid\a.py", line 1, in <module>
    import b
  File "C:\Users\lavid\b.py", line 1, in <module>
    from a import b
ImportError: cannot import name 'b' from partially initialized module 'a' (most likely due to a circular import) (C:\Users\lavid\a.py)
#

so it doesnt raise that on partially initialized modules

#

but when imported yet-to-define symbols of that module?

fleet bridge
#

you are allowed to import partially initialized modules, but not allowed to get any attributes from them

twin roost
#

I got the same impression yesterday but yes - if you import a module and not use any names from it, it's "partially imported" and it's allowed to import our current module too

earnest snow
fleet bridge
#

i think it was like this always

earnest snow
#

fr?

earnest snow
#

I feel old rn

versed eagle
#

wdym

grave grail
#

What mean by pure code

quartz wave
#

that is pure code

#

it's the most pythonic one actually

#

this raises RecursionError

#

or segfaults

grave grail
#

i.e. (infinity: finite by recurrsion limit)

#

lul

grave grail
arctic skiff
#

@quartz wave the cereal class in your name should have base of Edible

inland axle
#

did you know you can change an async generator's __code__ into a regular generator and do weird stuff?

inland axle
#

!e

import types

def get_agwv(v):
    def donor_gen():
        yield

    async def agenfn():
        yield v

    co = agenfn.__code__
    agenfn.__code__ = agenfn.__code__.replace(co_flags=donor_gen.__code__.co_flags)

    return agenfn().send(None)


@types.coroutine
def _async_yield(v):
    return (yield v)

async def agenfn():
    await _async_yield(get_agwv(1))
    await _async_yield(get_agwv(2))
    await _async_yield(get_agwv(3))
    await _async_yield(get_agwv(4))
    return
    yield

def main():
    async def amain():
        async for v in agenfn():
            print(v)

    try:
        amain().send(None)
    except StopIteration as e:
        return e.value

if __name__ == "__main__":
    main()
night quarryBOT
inland axle
#

there we go

fleet bridge
arctic skiff
sonic birch
earnest snow
#

guys, is locals() a pure function or does something else?

#

I just found that zmq randomly calls locals() without doing anyting with it saying it solves an issue
(can't remember the github command to show the lines, but lines 82-83 of zmq/sugar/context.py)
I bet it has to do with variable destruction order in __del__ but I thoug it was a pure function

quartz wave
versed eagle
quartz wave
#

locals() copies locals and nonlocals to a dictionary and immediately pops it

versed eagle
#

this

#

depends if you count it as a side effect or not

#

it shouldnt be, but clearly that can affect asynchronous stuff

#

somehow

#

i would think of that as a bug though!

quartz wave
versed eagle
#

yeah

earnest wing
#

async is pretty sensitive to objects existing, especially when it comes to tasks and weak references

unique heath
#

uh

#

soundy

#

(very bad)

earnest snow
#

nobody has no idea of why that's there, have you?

clear venture
#

!e

print('someword'.count(''))
night quarryBOT
clear venture
#

ik this is not super esoteric but I just learned yesterday that this implementation is weird as fuck lol

fleet bridge
#

this is the only result that makes sense

versed eagle
clear venture
#

The idea that '' exists before/after/between each letter

#

And only one at that

#

Inf would make more sense if it could return floats

versed eagle
clear venture
#

You could put any number of empty strings between them, that doesn't make it any more intuitive

versed eagle
#

any number of empty strings is just one empty string

#

(ε ε) = ε

clear venture
#

Hm yeah if you put it like that ig it makes sense

restive void
versed eagle
#

it makes more sense to take the minimal set, no?

#

since theres no bound on expansion

restive void
#

I mean yeah, this is probably the least bad solution.

#

Another acceptable option would have been raising ValueError

versed eagle
#

yeah

#

why anyone would want to count empty strings in the first place is the real question lol

karmic pumice
#

!e

class Tag:
    def __class_getitem__(*_):
        class idk:
            __match_args__ = ("args", )
            def __init__(self, args):
                self.args = args
            def __repr__(self):
                return f"{self.args}"
            def __class_getitem__(cls, args):
                return cls(args)
        return idk

Module = Tag[()]
Assign = Tag[()]
Constant = Tag[()]
Call = Tag[()]
Lookup = Tag[()]
Environment = Tag[()]

class Eval:
    def __class_getitem__(_, code):
        expr, environment = code
        match expr:
            case Constant(value):
                return value
            case Call((func, args)):
                return Eval[func, environment](*(Eval[arg, environment] for arg in args))
            case Lookup(name):
                return environment[name]

class Run:
    def __class_getitem__(_, code):
        match code:
            case Module(statements), Environment(environment):
                for statement in statements:
                    match statement:
                        case Assign((name, value)):
                            environment[name] = Eval[value, environment]
                        case Call((func, args)) as call:
                            Eval[call, environment]

Run[Module[
    Assign["foo", Constant[4]],
    Call[Lookup["print"], [Lookup["foo"]]],
], Environment[{"print": print}]]
night quarryBOT
karmic pumice
karmic pumice
#

!e

class Tag:
    def __class_getitem__(*_):
        class idk:
            __match_args__ = ("a", )
            def __init__(self, a):
                self.a = a
            def __class_getitem__(c, a):
                return c(a)
        return idk

Module = Tag[()]
Assign = Tag[()]
Constant = Tag[()]
Add = Tag[()]
Call = Tag[()]
Lookup = Tag[()]
Environment = Tag[()]
For = Tag[()]

class Eval:
    def __class_getitem__(_, code):
        expr, environment = code
        match expr:
            case Constant(value):
                return value
            case Add(args):
                return sum(Eval[arg, environment] for arg in args)
            case Call((func, args)):
                return Eval[func, environment](*(Eval[arg, environment] for arg in args))
            case Lookup(name):
                return environment[name]

class Run:
    def __class_getitem__(_, code):
        match code:
            case Module(statements), Environment(environment):
                for statement in statements:
                    match statement:
                        case Assign((name, value)):
                            environment[name] = Eval[value, environment]
                        case Call((func, args)) as call:
                            Eval[call, environment]
                        case For((name, iterable, statements)):
                            iterable = Eval[iterable, environment]
                            for item in iterable:
                                environment[name] = item
                                Run[Module[statements], Environment[environment]]

Run[Module[
    Assign["a", Constant[0]],
    Assign["b", Constant[1]],
    For["_", Constant[range(100)], [
        Assign["c", Lookup["b"]],
        Assign["b", Add[Lookup["a"], Lookup["b"]]],
        Assign["a", Lookup["c"]],
        Call[Lookup["print"], [Lookup["a"]]],
    ]],
], Environment[{"print": print}]]
night quarryBOT
fleet bridge
languid hare
quartz wave
#

if it wasn't the program'd probably crash :>

fleet bridge
#

i think it would rather freeze

night quarryBOT
#

Objects/stringlib/count.h lines 21 to 22

if (sub_len == 0)
    return (str_len < maxcount) ? str_len + 1 : maxcount;```
unique prairie
#

hi, wanted to make the example in the "or gotcha" tag work out of spite (and cause it's fun) so i made that :

from forbiddenfruit import curse


class CustomList(list):
    def __hash__(self):
        return hash(tuple(self))

    def __eq__(self, left):
        return self.__contains__(left)


def gotcha(left, right):
    return CustomList([left, right])


curse(str, "__or__", gotcha)

(forbiddenfruit allows to extend builtin types)

this allows to do that :

>>> "bar" == "foo" | "bar"
True

if that hurts your soul, you're welcome
(also yes i know that to have a fully working example i'd have to override __or__ on every builtin type, and that it cancels its original use, but its just for the funny)

#

unfortunately i didnt find a way to override or as it's a short-circuit keyword and not an operator :c

#

overriding hash is somehow necessary because the interpretor seems to expect the result from __or__ to be hashable somehow ? didn't understand that part

restive void
unique heath
#

eimpl

karmic pumice
unique heath
#

oh yeh that

unique prairie
#

and do you know if it's somehow possible to override the behavior of short-circuiting from runtime?

restive void
unique prairie
#

ye ic

#

that would defeat the purpose :c

grave grail
# quartz wave it's a special case

Could have been this (which probably isn't)

def count(string, check):
    counted = 0
    for chars in zip(*[string[s:] for s in range(max(len(check), 1))]):
        if check in "".join(chars):
            counted += 1
    return counted
#

!e


def count(string, check):
    counted = 0
    for chars in zip(*[string[s:] for s in range(max(len(check), 1))]):
        if check in "".join(chars):
            counted += 1
    return counted

print(count("hello world", ""))
print(count("hello world", "l"))
print(count("hello world", "hello"))
night quarryBOT
unique prairie
#

first result is 12 tho

grave grail
#

Is it?

#

Oops

#

I didn't notice that

#

Then I'm out of idea

unique prairie
#

just checked CPython's implementation and it is a special case

#

because they use a fastsearch algorithm that'd break with an empty string

grave grail
#

Would be surprising they +1 to length

unique heath
#

searhc go brrrrrr

wide crow
#

!e

def count(txt, target):
    found = 0
    ix = 0
    while ix <= len(txt):
        if txt.startswith(target, ix):
            found += 1
            ix += max(len(target), 1)
        else:
            ix +=1
    return found

print(count('hello world', ''))  # 12
print(count('hello world', 'l'))  #3
print(count('hello world', 'hello'))  # 1
print(count('hello world', 'wo'))  # 1
print(count('hello world', 'ow'))  # 0
night quarryBOT
fleet bridge
#
>>> str.startswith?
Help on method_descriptor:

startswith(...)
    S.startswith(prefix[, start[, end]]) -> bool

    Return True if S starts with the specified prefix, False otherwise.
    With optional start, test S beginning at that position.
    With optional end, stop comparing S at that position.
    prefix can also be a tuple of strings to try.
``` TIL: `str.startswith` has more than one ||two of you count `self`|| parameter
wide crow
#
help(str.count)
Help on method_descriptor:

count(...)
    S.count(sub[, start[, end]]) -> int

    Return the number of non-overlapping occurrences of substring sub in
    string S[start:end].  Optional arguments start and end are
    interpreted as in slice notation.

help(str.startswith)
Help on method_descriptor:

startswith(...)
    S.startswith(prefix[, start[, end]]) -> bool

    Return True if S starts with the specified prefix, False otherwise.
    With optional start, test S beginning at that position.
    With optional end, stop comparing S at that position.
    prefix can also be a tuple of strings to try.

count and startswith both have optional start and end parameters.

rugged sparrow
versed eagle
restive void
fleet bridge
#

detecting "and"s and "or"s in bytecode should be pretty hard, i think

#

because they are basically compiled to a lot of "if"s and "goto"s

rugged sparrow
versed eagle
#

sad

rugged sparrow
#

I assume fishhook.asm would also be big guns?

atomic python
#

!e

x = 2
while True:
    print(x)
    x = x^2```
night quarryBOT
atomic python
#

!e

x = 2
while True
    x = x^2
    x = x^2
    x = x^2
    x = x^2
    print(x)
night quarryBOT
atomic python
#

!e

x = 2
while True:
    x = x^2
    x = x^2
    x = x^2
    x = x^2
    print(x)
night quarryBOT
unique heath
#

i dont think thats eso

#
10 XOR 10 = 00
00 XOR 10 = 10
10 XOR 10 = 00
00 XOR 10 = 10```
quartz wave
#
def count(txt, target, start=None, end=None):
    found = 0
    if start is None:
        start = 0
    if end is None:
        end = len(txt)
    skip = max(len(target), 1)
    while True:
        ix = txt.find(target, start, end)
        if ix < 0:
            break
        found += 1
        start += skip
    return found
unique heath
#

i got 526/526 on twelve days of christmas

#

hmm

shy ermine
#

what is golfing

clear venture
#

just like in golf where you want the fewest number of strokes possible, you want the least characters possible

shy ermine
#

whats that website

#

coding challenges

#

i used to use some coding challenge website and try to do the python ones in one line

#

did some like 30+ line programs in 3 lines too

#

if i can sign in i can view my answers, what is that site called?

unique heath
#

510

#

497

#

||py l="First,Second,Third,Fourth,Fifth,Sixth,Seventh,Eighth,Ninth,Tenth,Eleventh,Twelfth".split(",") n="""Twelve Drummers Drumming, Eleven Pipers Piping, Ten Lords-a-Leaping, Nine Ladies Dancing, Eight Maids-a-Milking, Seven Swans-a-Swimming, Six Geese-a-Laying, Five Gold Rings, Four Calling Birds, Three French Hens, Two Turtle Doves, and A Partridge in a Pear Tree.""".split("\n") for i,d in enumerate(l):print(f"On the {d} day of Christmas\nMy true love sent to me\n{"\n".join(n[len(n)-i-1:])}\n")|| what i have rn

#

492

clear venture
#

huh

#

runs in the bot but errors in my terminal

unique heath
#

hi wrong channeL?

#

dis esopy

clear venture
#

talking about your code goose

#

oh bc it's the 3.12 fstrings

unique heath
#

||py l="First,Second,Third,Fourth,Fifth,Sixth,Seventh,Eighth,Ninth,Tenth,Eleventh,Twelfth".split(",") n="A Partridge in a Pear Tree.;Two Turtle Doves, and;Three French Hens,;Four Calling Birds,;Five Gold Rings,;Six Geese-a-Laying,;Seven Swans-a-Swimming,;Eight Maids-a-Milking,;Nine Ladies Dancing,;Ten Lords-a-Leaping,;Eleven Pipers Piping,;Twelve Drummers Drumming,;".split(";") for i,d in enumerate(l):print(f"On the {d} day of Christmas\nMy true love sent to me\n{"\n".join(n[i::-1])}\n")|| 487

clear venture
#
l="First Second Third Fourth Fifth Sixth Seventh Eighth Ninth Tenth Eleventh Twelfth".split()
n="A Partridge in a Pear Tree.;Two Turtle Doves, and;Three French Hens,;Four Calling Birds,;Five Gold Rings,;Six Geese-a-Laying,;Seven Swans-a-Swimming,;Eight Maids-a-Milking,;Nine Ladies Dancing,;Ten Lords-a-Leaping,;Eleven Pipers Piping,;Twelve Drummers Drumming,;".split(";")
for i,d in enumerate(l):print(f"On the {d} day of Christmas\nMy true love sent to me\n{"\n".join(n[i::-1])}\n")
``` 484
#
l="First Second Third Fourth Fifth Sixth Seventh Eighth Ninth Tenth Eleventh Twelfth".split()
n="A Partridge in a Pear Tree.;Two Turtle Doves, and;Three French Hens,;Four Calling Birds,;Five Gold Rings,;Six Geese-a-Laying,;Seven Swans-a-Swimming,;Eight Maids-a-Milking,;Nine Ladies Dancing,;Ten Lords-a-Leaping,;Eleven Pipers Piping,;Twelve Drummers Drumming,;".split(";")
for d in l:print(f"On the {d} day of Christmas\nMy true love sent to me\n{"\n".join(n[l.index(d)::-1])}\n")
``` 480
unique heath
#

im acctually stupid

#

tysm

gleaming linden
#

Cant test on mobile 😔

clear venture
#

it reads the : as a format specifier so you need parens

#

trying to test it now

unique heath
#

no

#

doesnt

clear venture
#

I was playing around with that golfing technique where you compress the multiple strings into one and use strides to extract them

#

but ig it only works for strings of the same length? pithink not getting great results

gleaming linden
#

Yeah they all have to be the same (or at least similar) length

clear venture
#
>>> for i in range(12): print('FSTFFSSENTETiehoiieiielwrciufxvgnneesorrttehttvltndthhnthhef'[i::12])
... 
First
Secon
Third
Fourt
Fifth
Sixth
Seven
Eight
Ninth
Tenth
Eleve
Twelf
#

sadge

gleaming linden
#

!e ```py
l="First Second Third Fourth Fifth Sixth Seventh Eighth Ninth Tenth Eleventh Twelfth".split()
n="A Partridge in a Pear Tree.;Two Turtle Doves, and;Three French Hens,;Four Calling Birds,;Five Gold Rings,;Six Geese-a-Laying,;Seven Swans-a-Swimming,;Eight Maids-a-Milking,;Nine Ladies Dancing,;Ten Lords-a-Leaping,;Eleven Pipers Piping,;Twelve Drummers Drumming,".split(";")
print(*map(len,l))
print(*map(len,n))

night quarryBOT
clear venture
#

I played around with the idea of padding all the strings with some character to be extracted but that + replace would end up being as many or more chars

#
>>> b = 'FSTFFSSENTETiehoiieiielwrciufxvgnneesorrttehttvltndthhnthhef1d1h11th11nt111111h111th1111111111h1'
>>> for i in range(12): print(b[i::12].replace('1',''))
... 
First
Second
Third
Fourth
Fifth
Sixth
Seventh
Eighth
Ninth
Tenth
Eleventh
Twelfth
gleaming linden
#

Wait a second

#

for d in"First second ...".split():

clear venture
#

oh true lol

gleaming linden
#

Oh wait

gleaming linden
clear venture
#

oh yeah

#

using index on the most recent one I had, so it needs the var

#

actually I wonder if it lets you use urllib XD

#

you could just cheese it by hosting the entire thing somewhere and requesting it

unique heath
#

but prob not

clear venture
#

Yeah, they removed all the attributes from urllib it seems anyway

#

Probably some way to walk down the object hierarchy and find it or get to os and try commands but not worth the effort

calm rapids
#

$100-250 project dm me

#

need someone proficient in java

#

or python

flint hollow
night quarryBOT
#

9. Do not offer or ask for paid work of any kind.

calm rapids
#

What

#

So people can't make money

#

??

clear venture
#

golf is free Cute

grave grail
#

We do free help in a limited scope

unique heath
fleet bridge
#
import typing as t
import collections.abc as t_abc
import operator as op
import math

type S=list[float]
type NS=dict[str,float]
type F=t_abc.Callable[[S,NS],t.Any]

def n_ary(n:int):
    def make_n_ary_function(f)->F:
        def f_n_ary(s:S,ns:NS)->None:
            s[::],args=s[:-n],s[-n:]
            s.append(f(*args))
        return f_n_ary
    return make_n_ary_function

def f_num(num:int)->F:
    return lambda s, ns: s.append(num)

def f_var(name:str)->F:
    return lambda s, ns: s.append(ns[name])

unary=n_ary(1)
binary=n_ary(2)
ternary=n_ary(3)

oper={
    '+':   binary(op.add),
    '-':   binary(op.sub),
    '*':   binary(op.mul),
    '/':   binary(op.truediv),
    '//':  binary(op.floordiv),
    '%':   binary(op.mod),
    '**':  binary(pow),
    '!':   unary(op.neg),
    'tan': unary(math.tan),
    'sin': unary(math.sin),
    'cos': unary(math.cos),
    'exp': unary(math.exp),
    'ln':  unary(math.log),
    'sqrt':unary(math.sqrt),
    'abs': unary(abs),
    '@':   ternary(lambda a,b,c:a if c else b),
    '?':   lambda stack,ns:print(stack,ns),
}

def is_num(st:str)->bool:
    try:int(st)
    except ValueError:return False
    else:return True

def parse(a:str)->list[F]:
    expr=[]
    for i in a.split():
        if is_num(i):expr.append(f_num(int(i)))
        else:
            if i in oper:expr.append(oper[i])
            else:expr.append(f_var(i))
    return expr

def calc(expr:list[F],ns:NS)->S:
    stack:S=[]
    for f in expr:f(stack,ns)
    return stack

def repl()->None:
    ns:NS={}
    while True:
        try:a=input('>> ')
        except EOFError:break
        if a=='?':
            for key,value in ns.items():
                print(f'{key}={value}')
            continue
        if '=' in a:
            var,_,expr=a.partition('=')
            var=var.strip()
            ns[var]=calc(parse(expr),ns=ns)[0]
            continue
        print(calc(parse(a),ns=ns))
repl()
sick hound
#

nice

fleet bridge
#

RPN calculator with variables
Example of calculating s sqrt using only /, + and 2:

>> s = 2
>> x = 1
>> x = x s x / + 2 /
>> x = x s x / + 2 /
>> x = x s x / + 2 /
>> x = x s x / + 2 /
>> x = x s x / + 2 /
>> x = x s x / + 2 /
>> x = x s x / + 2 /
>> x
[1.414213562373095]
>> x x *
[1.9999999999999996]

fleet bridge
#

only integers for literals in expressions
operations are mostly duck typed, so floats are ok

quartz wave
#

would be cooler if it used lossless rationals

#
>> 1 2 / 5 + 2 **
[121/4]
#

and then display modes can change

fleet bridge
#

imagine representing acos(-1) as rational

quartz wave
quartz wave
quartz wave
fleet bridge
#

i meant 1 ! acos where 'acos': unary(math.acos),

#
# instead of spamming this:
x = x s x / + 2 /
# you can do this:
x   dup s swap / + 2 /   dup s swap / + 2 /   dup s swap / + 2 /   dup s swap / + 2 /
#

you can implement lambdas pretty easily in parser

quartz wave
#

why not make a hybrid binary()/unary() function for sub/neg

fleet bridge
#

inc = [ 1 + ]
parse thing between brackets as callable that invokes all things inside of brackets

fleet bridge
quartz wave
#

not the 2nd question though pithink

fleet bridge
#

in theory you could maintain two versions of stack and get rid of one that causes error, but it may exponentialy explode if you are using a lot of -
also, it is not clear how to deal with side effects in this case

quartz wave
#

complex arithmetic!! ```py

x = 1 ! sqrt
x
[1j]
x 2 **
[-1.0]

karmic pumice
#

!e

print((lambda c,s=[],r={}:(r,f:={'.': lambda: s.append(0),'+': lambda: s.__setitem__(-1,s[-1]+1),'@': lambda: s.__setitem__(-1,chr(s[-1]+0x60)),'!': lambda: (v:=s.pop(),k:=s.pop(),r.__setitem__(k, v)),},sum(map(lambda t: (((f[t]()), 0)[1]),c.split())),)[0])(". + @ . + ! . + + @ . + + !"))
night quarryBOT
unique prairie
karmic pumice
#

cannot use assignment expression with subscript

unique prairie
#

yes but you can combine it with spreading

#

s:=[*s[:-1],s[-1]+1]

#

shaves off 5 chars

karmic pumice
#

i wasnt golfing though

unique prairie
#

idk if u mind the return tho

#

o

#

i saw a one-liner, i expected it lol

versed eagle
karmic pumice
#

its not meant to be used ||multiple times|| at all, i just wrote something

unique prairie
#

ye u can remove the spoiler block and whats inside lol

versed eagle
#

lmao

wind iron
grave grail
#

what you want? this seem irrelevant to esoteric

wind iron
#

my fault brother sorry direct me where i should drop it

grave grail
#

issue is: what do you want

fleet bridge
quartz wave
fleet bridge
#
import typing as t

def check(obj, cls):

    if cls is None:
        assert obj is None
        return

    import dataclasses as dcls
    if dcls.is_dataclass(cls):
        assert isinstance(obj, cls)

        for f in dcls.fields(obj):
            check(getattr(obj, f.name), f.type)
        return

    if isinstance(cls, type):
        assert isinstance(obj, cls)
        return

    if type(cls).__name__ == 'GenericAlias':
        if t.get_origin(cls) is list:
            assert isinstance(obj, list)
            for x in obj:
                check(x, t.get_args(cls)[0])
            return

    if type(cls).__name__ == 'UnionType':
        for opt in t.get_args(cls):
            try:
                check(obj, opt)
            except Exception:
                pass
            else:
                break
        else:
            raise TypeError(obj, cls)
        return

    raise TypeError(obj, cls)
#

🤷‍♂️ works for me

inner whale
#

I wrote a file with a million test functions in it:

with open('tests.py', 'w') as f:
    for i in range(1_000_000):
        f.write(f'def test_{i}():\n    pass\n')

If I execute that file with python tests.py it takes 8.4s to run and 2.7 gig of ram.

If I execute it with python -m tests it takes 1.1s and 0.5 gig of ram.

Can anyone offer me an explanation or theory on the difference?

restive void
inner whale
#

Especially the ram is egregious...

#

You can try it yourself, all the code is above.

hard spoke
inner whale
#

aaah

inner whale
#

I guess it makes sense from the implementation. python foo.py loads the file and shoves it into the python runtime, it never checks on disk.

fleet bridge
inner whale
#

Yea, I guess normally you won't notice this difference, I just have a pathological case

quartz wave
#

i've got a ton of files in my __pycache__ to prove otherwise i have no idea how or why those files ended up there

#

.....

#

how did those files end up there

#

i don't remember importing them 0.o

fleet bridge
#

are you using IPython? it might import main file under the hood, instead of executing it directly, or something like that

twin roost
#

Why this breaks?

Traceback (most recent call last):
  File "\weird\weird.py", line 2, in <module>
    ext.user_default.test_folder_addon.register()
  File "\weird\ext\user_default\test_folder_addon\__init__.py", line 7, in register
    import test_folder_addon.tool
  File "\weird\ext\user_default\test_folder_addon\tool\__init__.py", line 1, in <module>
    from test_folder_addon.tool.subtool import Subtool
  File "\weird\ext\user_default\test_folder_addon\tool\subtool.py", line 1, in <module>
    import test_folder_addon.tool as tool
ImportError: cannot import name 'tool' from 'ext.user_default.test_folder_addon' (\weird\ext\user_default\test_folder_addon\__init__.py)
brazen geyser
#

what would be the most reliable way across multiple python versions to check that a code object doesnt belong to a lambda, genexp or list comprehension, etc? so far using code.co_name.startswith('<')

fleet bridge
#

you can check its name

brazen geyser
#

thats what im currently doing

fleet bridge
#

oh, right, i cant read

for generators - there is a flag somewhere in a code object that indicates that it is a generator

restive void
#

Yeah, obj.co_flags & 32

brazen geyser
#

does that distinguish between generator expressions and def gen(): yield generators?

twin roost
unique heath
unique heath
#

doesnt that basically just

#

return 32 if the 6th bit is 1

earnest wing
#

Each bit is a flag. A bitflag if you will

unique heath
versed eagle
#

so ```
if o.co_flags & 32:
do_stuff()

brazen geyser
#

!eval

def fn():
  raise Exception()

fn.__code__ = fn.__code__.replace(co_filename=f'stuff: {fn.__code__.co_filename}')
fn()
night quarryBOT
brazen geyser
#

does anyone know why this still prints the correct line of code in the traceback, even though the filename is altered like that?

night quarryBOT
#

Lib/traceback.py line 477

linecache.lazycache(filename, f.f_globals)```
`Lib/linecache.py` line 147
```py
def lazycache(filename, module_globals):```
brazen geyser
#

cant see how this is being handled

fleet bridge
#

because line numbers are also stored

#

there is no way to determine line number knowing only file name

brazen geyser
#

but how is it able to access a line in a file with the path stuff: /home/main.py

#

!eval

def fn():
  raise Exception()

fn.__code__ = fn.__code__.replace(co_filename=f'stuff:')
fn()
night quarryBOT
brazen geyser
#

no code shows up here without the original path in the replacement

fleet bridge
#

linecache.lazycache(filename, f.f_globals)
this looks for module loader in global namespace and extracts real filename from it

brazen geyser
night quarryBOT
#

Python/traceback.c line 317

_Py_FindSourceFile(PyObject *filename, char* namebuf, size_t namelen, PyObject *io)```
night quarryBOT
#

Python/traceback.c lines 340 to 346

/* Search tail of filename in sys.path before giving up */
tail = strrchr(filepath, SEP);
if (tail == NULL)
    tail = filepath;
else
    tail++;
taillen = strlen(tail);```
brazen geyser
#

i think this is it?

wraith island
#

!eval

# "esoteric" hello world using maths?
@lambda x: x((2, 3, 0, 1, 4))
def main(arg):
    a, b, c, d, e = arg
    k = (d, d, b, e, a + b, b + e, a * e, e * a, b * a, b * b, c)
    f = [i for i in k if ~i & d]
    n = [c] * (g := len(f))
    o = ((d << i) + j for i, j in zip(range(g), f))
    for i, j in zip(o, arg):
        n[j] = int(str(e ** b), e ** a) + i
    return getattr(__builtins__, bytes(n).decode())

main("Hello, world!")
night quarryBOT
unique heath
#

only in math

wraith island
#

maths is fun

unique heath
#

it depends

versed eagle
#

most maths are fun

unique heath
#

i hate trig

#

its just punching numbers into calculators

#

theres nothing fun about trig

sick hound
#

So why does Python IDLE has the option for Wingdings as font? xD

unique heath
arctic skiff
unique heath
#

as it is atm

clear venture
#

yeah fuck trig

#

all my homies hate trig

unique heath
#

all my homies hate trig

gleaming timber
#

golfed binary search```py
bsearch=lambda c,t,s=0,e=None:(s if t in c[s:e]else-1)if(l:=(e:=len(n)if e==None else e)-s)<2else bsearch(c,t,s,m)if t<c[m:=s+l//2]else bsearch(c,t,m,e)

versed eagle
quartz wave
versed eagle
quartz wave
#

um

#

i think so

versed eagle
#

silly goose!

quartz wave
#

:p

#

..goose?

versed eagle
#

:3

#

A goose (pl.: geese) is a bird of any of several waterfowl species in the family Anatidae. This group comprises the genera Anser (grey geese and white geese) and Branta (black geese). Some members of the Tadorninae subfamily (e.g., Egyptian goose, Orinoco goose) are commonly called geese, but are not considered "True Geese" taxonomically. More d...

versed eagle
unique heath
#
bsearch=b=lambda c,t,s=0,e=None:(s if t in c[s:e]else-1)if(l:=(e:=len(n)if e==None else e)-s)<2else b(c,t,s,m)if t<c[m:=s+l//2]else b(c,t,m,e)```
#

@gleaming timber

gleaming timber
#

there you go```py
bsearch=lambda c,t,s=0,e=None:(s if t in c[s:e]else-1)if(l:=(e:=len(c)if e==None else e)-s)<2else bsearch(c,t,s,m)if t<c[m:=s+l//2]else bsearch(c,t,m,e)

quartz wave
#

111b mistranslation from original code detected ~~```py
bsearch=b=lambda c,t,s=0,e=():b(c,t,s,[e,m:=s+e>>1][t<c[m]])if(e:=[e,len(c)][e==()])-s>1else-1^~s*(t in c[s:e])

#

(part after else is same length as [-1,s][t in c[s:e]], jus wanted to find an alt since it's kinda boring :3 )

#

117b fixed sign flip doesn't work ~~```py
bsearch=b=lambda c,t,s=0,e=():b(c,t,(s,m:=s+e>>1,e)[t>c[m]:][:2])if(e:=[e,len(c)][e==()])-s>1else-1^~s(t in c[s:e])

#

string of deleted messages in a python channel meant for non-beginners :3c

#

116b 117b not minding extra arguments + comparison fixed ```py
bsearch=b=lambda c,t,s=0,e=(),_:b(c,t,(s,m:=s+e>>1,e)[t>=c[m]:])if(e:=[e,len(c)][e==()])-s>1else-1^~s*(t in c[s:e])

gleaming timber
#

is -1 ^ n equal to ~n?

calm swallow
#

i just stumbled upon this channel and these are insane

gleaming timber
#

yeah

quartz wave
#

it's about the same as doing ~(...)

#

but parentheses r kinda ugly :/

#

there's also ~s*-(...)-1 or -~s*(...)-1

#

alt 117b with no warnings ```py
bsearch=b=lambda c,t,s=0,e=(),_:b(c,t,(s,m:=s+e>>1,e)[t>=c[m]:])if-~s<(e:=[e,len(c)][e==()])else-~s*(t in c[s:e])-1

maiden blaze
#

import bisect:

quartz wave
grave grail
#
bsearch=__import__("bisect").bisect_left
``` hmm
grave grail
#

40b...

rigid trench
#

!e

night quarryBOT
#
Missing required argument

code

night quarryBOT
#
Missing required argument

code

rough moat
#
mand = lambda w=50,h=25,max_iter=100,r=(-0.7,0.7),i=(0,1),chs=".,*3456789abcde.":("\n".join(["".join([chs[int(([z:=0+0j,n:=0].__add__([[(abs([z:=z.__mul__(z).__add__(complex(r.__getitem__(0).__float__().__add__((x.__truediv__(w)).__mul__(r.__getitem__(1).__sub__(r.__getitem__(0)))),i.__getitem__(0).__float__().__add__((y.__truediv__(h)).__mul__(i.__getitem__(1).__sub__(i.__getitem__(0)))))),n:=n.__add__(1)].__getitem__(-1)).__mul__(15).__truediv__(max_iter))]for _ in range(max_iter)if z.__abs__().__le__(2)]).__getitem__(-1)).__getitem__(-1))]for x in range(-w,w)])for y in range(-h,h)]))
warm bronze
#

...

rough moat
#

1 sec adding color

rough moat
#
mand_color=lambda w=50,h=25,max_iter=100,r=(-0.7,0.7),i=(0,1),chars=".,*3456789abcde ":print(f"{__import__("os").system("")}\b","\n\x1b[0m".join(["\x1b[0m".join([[([z:=0+0j,n:=0].__add__([[(abs([z:=z.__mul__(z).__add__(complex(r.__getitem__(0).__float__().__add__( (x.__truediv__(w)).__mul__(r.__getitem__(1).__sub__(r.__getitem__(0)))),i.__getitem__(0).__float__().__add__( (y.__truediv__(h)).__mul__(i.__getitem__(1).__sub__(i.__getitem__(0)))))),n:=n.__add__(1)].__getitem__(-1)).__mul__(15).__truediv__(max_iter))]for _ in range(max_iter)if z.__abs__().__le__(2)]).__getitem__(-1)).__getitem__(-1),n2:=n.__truediv__(max_iter),f"\x1b[38;2;{(((1.0).__sub__(n2)).__mul__(77)).__int__()};{((n2).__mul__(255)).__int__()};{(((1.0).__sub__(n2)).__mul__(77)).__add__(150).__int__()}m{chars.__getitem__((n2.__mul__(chars.__len__().__sub__(1))).__int__())}",].__getitem__(-1)for x in range(-w,w)])for y in range(-h,h)] ),"\x1b[0m",sep="")
rough moat
#

renders mandelbrot with color

quartz wave
# rough moat ```py mand_color=lambda w=50,h=25,max_iter=100,r=(-0.7,0.7),i=(0,1),chars=".,*34...
import os
os.system("")

def mand_color(
    w=50, h=25, max_iter=100,
    r=(-0.7, 0.7), i=(0, 1), chars=".,*3456789abcde "
):
    last_chars_idx = len(chars) - 1
    for y in range(-h, h):
        row = []
        # value in `i` (mandelbrot Y scale) that
        #   corresponds to the current `y` value (row)
        imag_part = i[0] + (y / h)*(i[1] - i[0])
        imag_part *= 1j  # part of the imaginary plane
        for x in range(-w, w):
            z = 0+0j
            n = 0
            # value in `r` (mandelbrot X scale) that
            #   corresponds to the current `x` value (column)
            real_part = r[0] + (x / w)*(r[1] - r[0])
            c = real_part + imag_part
            while n < max_iter and abs(z) <= 2:
                # https://en.wikipedia.org/wiki/Mandelbrot_set#Formal_definition
                # z_{n+1} = z_n**2 + c
                z = z*z + c
                n += 1
            # the color is a mystery to me ;^;
            n2 = n / max_iter
            n2r0 = (1 - n2) * 77
            color_r = int(n2r0)
            color_g = int(n2 * 255)
            color_b = int(n2r0 + 150)
            row.append(
                f"\x1b[38;2;{color_r};{color_g};{color_b}m"  # ANSI escape for character color
                f"{chars[int(n2 * last_chars_idx)]}"
            )
        # clear color effects at the end (\x1b[0m)
        print("".join(row), end="\x1b[0m\n")
#

this is cool tbh :o

unreal echo
#

make it zoom into a designated point now

quartz wave
unreal echo
#

0.94x per iteration zoom,

unreal echo
# quartz wave what parameters

Real: 0.2505845176040427718957771316508473905552515740661571423212687174479167, imag: 0.00002276281458802574942404639696751451557095909568791588147481282552083

quartz wave
#

i have no idea how to implement that .^.

rough moat
#

how did you calculate that

unreal echo
#

thats the point

#

To zoom in on

#

i didnt calculate it i found it somewhere

#

Wrotr my own arbitrary precision arithmetic extension for it

versed eagle
#

i would have just used gmpc lol

unreal echo
#

im on windows :/

#

I wouldve done that

#

But idk how

#

tbh i shouldve just done wsl :(

#

im too far in anyhow

rough moat
unreal echo
#

it would

#

but i found doing this in parallel using gomp works very well

#

and decimal requires the gil

versed eagle
dusty locust
#

Whoa. What is this place about?

#

Everything seems new to me.

rough moat
versed eagle
#

itd likr if python was silly

unreal echo
glacial rampart
#

need help with my codec
https://github.com/ioistired/import-expression/tree/restore-codec after installing, and putting

# codec: import_expression

print(urllib.parse!.quote("foo bar? baz"))

in a file and running it, i get:

  File "/home/user/code/import-expression/foo.py", line 3
    print(__import__('importlib').import_module('urllib.parse').quote('foo bar? baz'))
                      ^
SyntaxError: invalid syntax

even though the code in the error is the proper code rewritten to use importlib.import_module

GitHub

Transpiles a superset of python to allow easy inline imports - GitHub - ioistired/import-expression at restore-codec

#

the caret ^ in the SyntaxError seems to be at the position of the ! in my code

quartz wave
#

ooh

quartz wave
quartz wave
glacial rampart
quartz wave
#

cool

#

how about the first 2 points

glacial rampart
night quarryBOT
#

hoopy/codec.py lines 36 to 39

incrementalencoder=utf_8.IncrementalEncoder,
incrementaldecoder=utf_8.IncrementalDecoder,
streamreader=utf_8.StreamReader,
streamwriter=utf_8.StreamWriter,```
quartz wave
#

how does code use it anyway?

glacial rampart
#

you put # coding: ie in a file and run it

#

or use import-expression-rewrite

quartz wave
glacial rampart
#

that's neither here nor there

#

i'm using a pth to do the same thing

#

it still uses # coding: lines

quartz wave
glacial rampart
#

no i put import sys; exec('try:\n from import_expression._codec import register\nexcept ImportError:\n pass\nelse:\n register()') in a pth in site-packages

#

we're going in circles here

quartz wave
#

well it's kind of weird what i debugged

quartz wave
#

but implementing a custom incremental decoder makes everything work fine

#

(and providing encode, decode, and incrementaldecoder)

glacial rampart
#

can i use your incremental decoder?

quartz wave
#

wait

#

i kinda went debugging using the current repo code so this is basically just a copy-and-paste into the registering file ```py
class IEDecoder(codecs.BufferedIncrementalDecoder):
def _buffer_decode(self, b, errors, final):
return decode(b, errors)

#

although i think it's better to override .decode() since that parses the whole file in one go once the buffer finishes getting written on :3c

#
class IEDecoder(codecs.BufferedIncrementalDecoder):
    def decode(self, b, final=False):
        self.buffer += b
        if final:
            buffer = self.buffer
            super().reset()
            return decode(buffer)[0]
        return ""
glacial rampart
#

will try

#

@quartz wave i still get the same error

#

this codec shit is so brittle istg

quartz wave
#

incrementaldecoder=IEDecoder?

#

even with that?

glacial rampart
#

just pushed

#

@quartz wave

quartz wave
#

hm

#

new one works on my machine

glacial rampart
#

what version of python are you using

quartz wave
#

tested it on 3.10 to 3.13

#

new revision worked fine on all those versions

glacial rampart
#

try 3.8

#

i get a recursive syntax error

#

the problem is tokenize.detect_encoding

#

i think the only solution is to only support utf-8

#

or maybe i could manually parse out the encoding line

quartz wave
#

i didn't get too far in 3.8

#

i got an error that usually would be solved by putting the .pth in /lib/site-packages

#

but it didn't work in this case

glacial rampart
#

i can probably drop 3.8

#

hm i get the same error in 3.12

quartz wave
#

which error?

#

recursion?

#

also a weird thing i found is that the incremental decoder apparently starts at the newline following the # coding: comment

#

parsing kinda removes that prefix space information

#

so the first code line after the comment is part of the comment itself

#

other than that, the primary issue with me debugging that code is that i'm on windows 10 without a VM and can't reproduce errors that happen on linux/a VM :p

glacial rampart
#

getting too eepy to work on this some more

#

thanks for your help so far

quartz wave
unreal echo
arctic skiff
glacial rampart
#

@quartz wavewas running a python file with the codec line working for you?

#

cause for me import-expression-rewrite works but not running a file

quartz wave
#

@glacial rampart mini-error i found
my python 3.8 install fails because the constant for "importlib" doesn't have a .kind attribute

#

same thing for the module identifier

long fulcrum
#

is it possible to avoid having to declare l

x=int(k);l=[]
while x:
    i,j=0,1
    while i<=x:i,j=j,j+i
    l+=j-i,;x-=j-i```
gleaming linden
#
x=int(k);l=[]
x,*l=int(k),
``` -1?
long fulcrum
#

wtf yeah

#

how does that work

gleaming linden
#

x,*l=thing is roughly x=thing[0];l=thing[1:]

long fulcrum
#

oh cool i didnt know that worked

#

is it possible to use a sep in a map like this *map(print,l), or is this the shortest print(*l,sep=" + ")

gleaming linden
#

print(*l,sep=" + ") is probably the shortest

#
x,*l=int(k),
while x:
    i,j=0,1
    while j<=x:i,j=j,j+i
    l+=i,;x-=i
``` does this work?
gleaming linden
long fulcrum
gleaming linden
#

trailing is a 1c difference from the :-1 slice

long fulcrum
#

i didnt even think of slicing i was using an if to not add it on the last one which is way longer

quartz wave
#

ok

quartz wave
#

i somehow figured out how to reduce it by 2b

#

amazing!!

quartz wave
#

no traceback

#

had to figure it out by print()s inside the code

glacial rampart
#

yeah i get that error too

#

i can't find .kind in the code tho

quartz wave
#

well because it's not there

#

it should be there, but it's not

glacial rampart
#

what

#

i thought you were saying my code tries to access an attr that doesn't exist

#

oh i meant in "my" code not in "the" code

night quarryBOT
#

import_expression/_parser.py lines 80 to 91

node.func = ast.Attribute(
	value=ast.Call(
		func=ast.Name(id="__import__", ctx=ast.Load()),
		args=[ast.Constant(value="importlib")],
		keywords=[],
	),
	attr="import_module",
	ctx=ctx,
)
identifier = self._collapse_attributes(node.args[0])
self.import_hook(identifier)
node.args[0] = ast.Constant(value=identifier)```
quartz wave
#

both ast.Constant() calls need a .kind assigned in versions < (3, 9)

teal jackal
#

hmm hyes

mental sundial
#
# Kütüphaneler
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler


# Kodlar



# Veri Yükleme

veriler = pd.read_csv('D:\\Project\\satislar.csv')
print(veriler)
ay = veriler[["Aylar"]]
print(ay)

satis = veriler[["Satislar"]]
print(satis)



#verilerin eğitim ve test için bölünmesi
x_train, x_test, y_train, y_test =  train_test_split(ay,satis,test_size=0.33, random_state= 0)

#verilerin ölçeklenmesi
sc = StandardScaler()
X_train = sc.fit_transform(x_train)
X_test = sc.fit_transform(x_test)
#
error
Traceback (most recent call last):
  File "d:\Project\DataOnIsleme.py", line 20, in <module>
    satis = veriler[["Satislar"]]
            ~~~~~~~^^^^^^^^^^^^^^
  File "C:\Users\burak\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\frame.py", line 4108, in __getitem__
    indexer = self.columns._get_indexer_strict(key, "columns")[1]
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\burak\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\indexes\base.py", line 6200, in _get_indexer_strict
    self._raise_if_missing(keyarr, indexer, axis_name)
  File "C:\Users\burak\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\indexes\base.py", line 6249, in _raise_if_missing
    raise KeyError(f"None of [{key}] are in the [{axis_name}]")
KeyError: "None of [Index(['Satislar'], dtype='object')] are in the [columns]"
#

Please look at me my python code and my error

#

Why ı got a this error

#
Aylar, Satislar 
8,19671.5 
10,23102.5 
11,18865.5 
13,21762.5 
14,19945.5 
19,28321 
19,30075 
20,27222.5 
20,32222.5 
24,28594.5 
25,31609 
25,28478.5 
26,28540.5 
29,30555.5 
31,33969 
32,33014.5 
34,41544 
37,40681.5 
37,46970 
42,45865 
44,49136.5 
49,50651 
50,56306 
54,54715.5
55,52791 
59,58484.5 
59,56317.5 
64,61195.5 
65,60936 
#

This is my satislar.csv file

hard spoke
mental sundial
#

Sorry you're right

soft spruce
#

How do I take the three vertices of a triangular face, create a reference frame using one of the edges and the normal an then find the Euler angle to rotate another reference frame onto that one, without getting outputs that seem entirely random.
I’ve tried using scipy.align_vectors but it appears that can only handle single axis rotations, which is kind of useless. I’ve also tried all the ideas on stack overflow and none of them work either.

I don’t know what code to include I’ve tried about 20 completely different ideas and haven’t gotten anything close to a correct output.

quartz wave
#

what's with people going into this channel expecting normal help

unique heath
#

we can make their help golfed

fleet lintel
#

If we traumatize them with golfed symbol soup for help, maybe they will stop lemon_thinking

arctic skiff
#

lets make a rule here, whoever comes for normal help here will get their code golfed

soft spruce
earnest snow
#

Golfed or one lined?

#

Or both

arctic skiff
unique heath
#

golfpilled

quartz wave
#

0-o

unique heath
#

O.o

karmic pumice
#

!e

print((lambda a,q,z,b,c,d,e,f:(lambda g:((lambda j:(lambda k:k(k))(lambda k:lambda i:j(k(k))(i)))(lambda h:lambda i:d(c(f,i),h(q(i))) if z(i,g) else e))(a))(b(f)))(0,1 .__add__,int.__lt__,list.__len__,list.__getitem__,int.__add__,0,[1,2,3,4,5]))
night quarryBOT
karmic pumice
#

pure for loop

craggy hamlet
#

me on my way to replicate haskell's traverse and forM to one-up you

earnest snow
#

any way to create a infinite loop inside a lambda without infinite recursion?

#

got it, with itertools.cycle

karmic pumice
earnest snow
#

nah, the more obfuscated it is the better

#

is a whole pygame game in one line after all

#

and gotta do the main loop

karmic pumice
#

well itertools cycle is not really obfuscated

earnest snow
#

every extra variable that's not in builtin is a recursive call to the uppermost function, yes, yes it obfuscates everything more

#

does list(callback() for _ in cycle([0])) keep consuming memory for appending to the list?

karmic pumice
#
from pathlib import Path
from resource import getpagesize

PAGESIZE = getpagesize()
PATH = Path('/proc/self/statm')

def consumption() -> int:
    statm = PATH.read_text()
    fields = statm.split()
    return int(fields[1]) * PAGESIZE

def callback():
    print(consumption())
    return list(range(100_000)) # simulating some result, something big to have a noticeable change on memory consumption stat

list(callback() for _ in range(10))
$ py main.py
13279232
17342464
21405696
25337856
29401088
33333248
37396480
41328640
45391872
49455104

seems like a yes, and expectedly so

#

if you want to consume it i guess you can do so with a deque, or do something like sum(callback() or 0 for _ in cycle([0])) if the result of callback() is falsy

earnest snow
#
lambda callback:sum([(lambda :[callback(), 0][1])() for _ in cycle([0])])
``` that's my final version
karmic pumice
#

why the inner lambda? it does nothing

#

!e

# another idea
*filter(lambda _:False,(print("hello") for _ in range(10))),
night quarryBOT
karmic pumice
earnest snow
#

Fr?

karmic pumice
#

yes, [x for x in y] is indeed making a list. if you do f(x for x in y) its a generator, so it wont be stacking up in memory

earnest snow
#

Doesnt Python make a generator out of the [] to save memory?

karmic pumice
#

im not sure how would it do that, there is no static analysis here that could be done to deduce that this could be turned into a generator, unless some special case for something like sum()

#

!e

import dis
dis.dis("sum([x for x in y])")
night quarryBOT
karmic pumice
#

well, it still appends

quartz wave
#

337b #python-discussion message ```py
import os,sys
os.system(["cls","clear"][os.name!="nt"])
B=[3*['*']for _ in'0'*3]
for p in range(9):
for x in B:print(*x)
P="XO"[p&1];x,y=map(int,input(f"Player {P} move (column row): ").split());B[y][x]=P;any(all(map(P.eq,l))for l in[*B,*zip(*B),zip([(B[i][i],B[i][~i])for i in(0,1,2)])])>0>sys.exit()
print("It's a draw!")

earnest snow
rigid trench
#

is there a channel just normal python?

fleet bridge
plucky bison
karmic pumice
earnest wing
#

i mean it's neat as it demonstrates the implementation of State

karmic pumice
earnest wing
#

yeah duh

brazen geyser
#

is there a way to stop ctypes.CFUNCTYPE from consuming exceptions that occur inside its function? for example

@ctypes.CFUNCTYPE(None)
def callback():
  raise Exception

try:
  c_function_that_takes_callback(callback)
except Exception:
  print('exception occurred!')
else:
  print('exception didnt occur!')

gives the following error:

Exception ignored on calling ctypes callback function: <function callback at 0x000002C89359CAF0>

then prints exception didnt occur

rugged sparrow
#

Ctypes doesn't expect you to call CFUNCTYPE functions from python code, so the exceptions they raise would not be meaningful inside the C code. Depending on your use case there may be tricks you can use tho

brazen geyser
#

not sure i understand. i'm calling a c function that's being passed the callback, and then the callback is being called from c.

#

basically i just dont want ctypes to clear the exception flag after executing the callback

#

or error indicator, i think is the right term?

#

also i guess this should probably be a PYFUNCTYPE too

sour heath
#

I'm 95% confident this isn't esoteric and is an intended feature. However, I couldn't find any references to it after two googles so I just tried it.

What is it, you ask?

I just turned a class into a property and I feel like I ascended. I cheated the system. This is the forbidden fruit.

unique heath
#

!pypi forbiddenfruit :P

night quarryBOT
unique heath
#

!e

class MyClass:
    def __init__(self):
        ...

    @property
    class propertyclass:
        def __init__(self, *args):
            self.deez = "nuts"
            print(args)

print(MyClass().propertyclass.deez)```
night quarryBOT
# unique heath !e ```py class MyClass: def __init__(self): ... @property c...

:x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 10, in <module>
003 |     print(MyClass().propertyclass.deez)
004 |           ^^^^^^^^^^^^^^^^^^^^^^^
005 | TypeError: MyClass.propertyclass.__init__() takes 1 positional argument but 2 were given
sour heath
#
@property
class I_AM_GOD:
  pass
sour heath
unique heath
#

!e

class MyClass:
    def __init__(self):
        ...

    @property
    class propertyclass:
        def __init__(self, *args):
            self.deez = "nuts"
            print(args)

print(MyClass().propertyclass.deez)```
night quarryBOT
unique heath
#

cursed

quartz wave
#

the instance

sour heath
quartz wave
#

oh

#

i get it now

sour heath
#

!e

class MyClass:
    testing = 'hello'

    def __init__(self):
        ...

    @property
    class propertyclass:
        def __init__(self, *args):
            self.deez = "nuts"
            print(args[0].testing)

print(MyClass().propertyclass.deez)
night quarryBOT
sour heath
#

You absolute mad lads.

unique heath
#

this is so fucckde

quartz wave
#

wait a minute

sour heath
#

But it makes so much sense! It passes self!

quartz wave
#

that initializes an instance

sour heath
#

It works exactly how I hope it would.

#

Maybe @property thinks it's a function but I don't care what @property thinks. I only care what it does.

#

It only makes the instance if you get it as an attribute, not when the parent class is instantiated.

quartz wave
#

aww :(

night quarryBOT
#

:white_check_mark: Your 3.12 eval job has completed with return code 0.

yes!
quartz wave
#

yay!!!

sour heath
#

!e

class InstanceCreator:
    def __getattr__(self, name):
        return property(name)

class A:
    def __init__(self, _):
        print("yes!")

InstanceCreator = InstanceCreator()
InstanceCreator.A
#

How do you make it eval again?

quartz wave
#

!e ```py
@type.call
class InstanceCreator:
def getattr(self, name):
setattr(type(self), name, property((locals() | globals())[name]))
return getattr(self, name)

class A:
def init(self, _):
print("yes!")

InstanceCreator.A

night quarryBOT
sour heath
#

I didn't know I could do that either.

#

Does that... is what you did... normal? Or is that cursed.

#

It seems convenient at times, but certainly unusual.

#

I'm screwing around with enough stuff that pydantic is starting to fail on me.

#

The class that I made into a property in another class is actually virtually the same. So, I think I'm going to try making the class a nested property of itself.

#

Well, they'll need to be an ABC and then the instance is recursively self-propertized.

unique heath
#

!e

pf = []

def instance(func):
    pf.append(func)
    def inner(*args, **kwargs):
        return func(*args, **kwargs)

    return inner

def instancer(cls):
    def get(self, item):
        if cls.__getattribute__(item) and item in pf:
            return self.item()
        return self.item
    cls.__getattribute__ = get
    return cls

@instancer
class Deez:
    def __init__(self):
        ...

    @instance
    def nuts(self):
        return "nuts"

print(Deez().nuts)```
night quarryBOT
unique heath
#

D:

#

@quartz wave y no work

quartz wave
#

None not callable :/

#

mya

unique heath
#

im dum

#

!e

pf = []

def instance(func):
    pf.append(func)
    def inner(*args, **kwargs):
        return func(*args, **kwargs)

    return inner

def instancer(cls):
    def get(self, item):
        if cls.__getattribute__(item) and item in pf:
            return self.item()
        return self.item
    cls.__getattribute__ = get
    return cls

@instancer
class Deez:
    def __init__(self):
        ...

    @instance
    def nuts(self):
        return "nuts"

print(Deez().nuts)```
night quarryBOT
# unique heath !e ```py pf = [] def instance(func): pf.append(func) def inner(*args, *...

:x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 27, in <module>
003 |     print(Deez().nuts)
004 |           ^^^^^^^^^^^
005 |   File "/home/main.py", line 12, in get
006 |     if cls.__getattribute__(item) and item in pf:
007 |        ^^^^^^^^^^^^^^^^^^^^^^^^^^
008 | TypeError: instancer.<locals>.get() missing 1 required positional argument: 'item'
unique heath
#

...

#

oh recursion. ithkn

#

!e

pf = []

def instance(func):
    pf.append(func)
    def inner(*args, **kwargs):
        return func(*args, **kwargs)

    return inner

def instancer(cls):
    orig = cls.__getattribute__
    def get(self, item):
        if orig(item) and item in pf:
            return self.item()
        return self.item
    cls.__getattribute__ = get
    return cls

@instancer
class Deez:
    def __init__(self):
        ...

    @instance
    def nuts(self):
        return "nuts"

print(Deez().nuts)```
night quarryBOT
unique heath
#

!e

pf = []

def instance(func):
    pf.append(func)
    def inner(*args, **kwargs):
        return func(*args, **kwargs)

    return inner

def instancer(cls):
    orig = cls.__getattribute__
    def get(self, item):
        if orig(self, item) and item in pf:
            return self.item()
        return self.item
    cls.__getattribute__ = get
    return cls

@instancer
class Deez:
    def __init__(self):
        ...

    @instance
    def nuts(self):
        return "nuts"

print(Deez().nuts)``` plz do this
night quarryBOT
# unique heath !e ```py pf = [] def instance(func): pf.append(func) def inner(*args, *...

:x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 28, in <module>
003 |     print(Deez().nuts)
004 |           ^^^^^^^^^^^
005 |   File "/home/main.py", line 15, in get
006 |     return self.item
007 |            ^^^^^^^^^
008 |   File "/home/main.py", line 13, in get
009 |     if orig(self, item) and item in pf:
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/FPP6HXYDEZJHXMW44NRW6ORXEA

unique heath
#

aaaaaaa

sour heath
#

one sec

#
Traceback (most recent call last):
  File "C:\Users\SolarSupremacy\PycharmProjects\SolarUtil\tests\test2.py", line 28, in <module>
    print(Deez().nuts)
          ^^^^^^^^^^^
  File "C:\Users\SolarSupremacy\PycharmProjects\SolarUtil\tests\test2.py", line 15, in get
    return self.item
           ^^^^^^^^^
  File "C:\Users\SolarSupremacy\PycharmProjects\SolarUtil\tests\test2.py", line 13, in get
    if orig(self, item) and item in pf:
       ^^^^^^^^^^^^^^^^
AttributeError: 'Deez' object has no attribute 'item'

Process finished with exit code 1
unique heath
#

lemme cook

sour heath
#

Oh, it gives you a link to see the output.

quartz wave
#

.....

#

i figured it out already :3

hybrid trail
#

is there any way to golf ["│╱"[j>2*i+1],"█"][j==2*i+1]?

unique heath
hybrid trail
#
if j == 2*i + 1:
    print("█")
if j < 2*i+1:
    print("│")
if j > 2*i+1:
    print("╱")
#

non golfed version

#

seems to be an instance where cmp from python 2 could be handy

unique heath
#
["│╱"[j>(x:=2*i+1)],"█"][j==x]``` is this shorter?
#

no its not

#

1 char

hybrid trail
#

close!

#

"│╱█"[2*(j==2*i+1)+(j>2*i+1)] same length

hybrid trail
#

"█╱│"[(j>2*i+1)-(j<2*i+1)] 🤦‍♂️

sour heath
#

My property shenanagans have achieved perfection.

...
@property
def LIGHT_MAGENTA(self): return self.code('95')

@property
def LIGHT_CYAN(self): return self.code('96')

@property
def WHITE(self): return self.code('97')

@property
class BG(_CBase):

    @property
    def SWAP(self): return self.code('7')

    @property
    def BLACK(self): return self.code('40')

    @property
    def RED(self): return self.code('41')
...
#
print(f'{Color.BLUE}Simple text formatting (but it will stay until reset).{Color.RESET}')

print(f'Normal Text, {Color.RED.BOLD.BG.BLACK:Very Dramatic Text}, {Color.ITALIC:Italic Text}')

print('Older format() method to make ' + format(Color.GREEN.UNDERLINE, 'this') + ' word green.')
sour heath
#

I appreciate the esotism that allowed this to exist.

versed eagle
#

nor is bold

#

you silly goose

clear venture
#

pithink the codes never change, by making these properties instead of class variables you just add extra pointless lines and calls

clear venture
#

You have a point hmmGe

earnest snow
gleaming linden
#

Why not something like this```py
@lambda x: x()
class style:
def format(self, fmt):
...

print(f"{style:red,bold}text")

fleet lintel
#

To me, esoteric is unusual, not non-understandable. Is non-understandable a subset of unusual? Yes. But not all there is to it.

grave grail
proper vault
#

It's been there all along

#

It's what fstrings call, for example

gilded leaf
#

hey everybody...am new here

gleaming linden
grave grail
#

💀

#

Thx for reference that, an ancient version that I don't even use

versed eagle
grave grail
#

I did say it's not a invalid answer, was just surprised

quartz wave
#

2.6 is...

#

older than me

rough estuary
#

I am looking for developer can build a RESTful API for a simple blogging platform

sour heath
#

I've also noticed using capitals separated by periods is not convenient because holding shift will turn . to ,. Maybe lowercase or camelcase would be better. Or simply your method would be better.

karmic delta
#

me walking in on the discussion of formatting whilst working on my own formatting module cause for some reason i can never get the color one to work, so i just started making my own with blackjack and h-words

grave grail
#

I have a question:
Is removing there thing with no stdlib safe from unsafe code execution through running a abstract syntax tree?

`eval`, `exec`, `compile`, `getattr`, `builtins`, `__import__`, `__builtins__`, `setattr`, `print`, `input`, `globals`, `locals`, `delattr`, `open`, `dir`, `exit`
#

(i.e. code is from a unknown source

versed eagle
#

block genexprs also

grave grail
quartz wave
grave grail
#

But I have to execute it
What could I blacklist/whitelist to make it safe (safe as in it shouldn't touch anything outside the scope of the API but still able to use basic built-in function, and shouldn't able to modify any file or run any command

versed eagle
grave grail
#

The code include running script which annoying because of the medium of the transmission, running on the client side is not possible

fleet bridge
#

there was a challenge a while ago in this channel

grave grail
#

Can I see it?

fleet bridge
grave grail
#

Hmm, but I am running through a ast tree instead of just eval, but that looks interesting, let me see what could I do to block it

#

*I mean hopefully

#

But regardless, it would be checked with ast

fleet bridge
#

are you manually interpreting ast?

grave grail
#

I would try to make it possible

#

Ok, I could blacklist
*_frame and f_* at attribute attr if I cannot manually interpret it

#

Or if I can, just don't implement ast.GeneratorExp

restive void
#

You could, but maybe there's a different trick you haven't seen yet.

#

!e for example: Look, no *_frame!

print((1for()in()).gi_𝑓rame)
night quarryBOT
quartz wave
restive void
# quartz wave (this is normalized as `ast` parses it)

right, it will only work against searching in the string for _frame. But it was only an example, there might be additional things [I/we]'ve missed. Better to avoid executing entirely or execute in an externally hardened environment (e.g. snekbox).

clear venture
#

!e

[r:=__import__('random'),l:=3,d:=6,p:=4,[(b:=max(((l-1)//4)+2, 0)),(o:={})][-1],print(*[(a:=sum(sorted(r.randint(1,6)for _ in range(4))[1:]))and[(o:=(o|{n:(m:=(a-10)//2)})),f"{n}: {a} - MOD: {m:+}"][-1]for n in ['STR','DEX','CON','INT','WIS','CHR']],f"HP: {sum(c:=[r.randint(1,d)for _ in range(l)])+o['CON']*l} | {c}+{o['CON']}*{l}",*[j:={'Deception':'CHR','Intimidation':'CHR','Performance':'CHR','Persuasion':'CHR','Arcana':'INT','History':'INT','Investigation':'INT','Nature':'INT','Religion':'INT','Animal Handling':'WIS','Insight':'WIS','Medicine':'WIS','Perception':'WIS','Survival':'WIS','Acrobatics':'DEX','Sleight of Hand':'DEX','Stealth':'DEX','Athletics':'STR'},f:=r.sample([*j],k=p),[f"{z} - MOD: {o[j[z]]+b*(a:=(z in f)):+}{' - Proficient'if a else''}"for z in j]][-1],sep='\n')]
night quarryBOT
# clear venture !e ```py [r:=__import__('random'),l:=3,d:=6,p:=4,[(b:=max(((l-1)//4)+2, 0)),(o:=...

:white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | STR: 13 - MOD: +1
002 | DEX: 17 - MOD: +3
003 | CON: 11 - MOD: +0
004 | INT: 15 - MOD: +2
005 | WIS: 9 - MOD: -1
006 | CHR: 15 - MOD: +2
007 | HP: 10 | [6, 3, 1]+0*3
008 | Deception - MOD: +2
009 | Intimidation - MOD: +2
010 | Performance - MOD: +2
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/QWM7O2ZKN7OGARFXZTH2ZZYSJA

clear venture
#

idk why I golfed this random thing I made but it's 792 bytes

#

I have some unnecessary variable assignments there

#

but I'm too lazy to fix

restive void
#

757

from random import*;[[(b:=max(2.5,0)),(o:={})][-1],print(*[(a:=sum(sorted(randint(1,6)for _ in range(4))[1:]))and[(o:=(o|{n:(m:=(a-10)//2)})),f"{n}: {a} - MOD: {m:+}"][-1]for n in ['STR','DEX','CON','INT','WIS','CHR']],f"HP: {sum(c:=[randint(1,6)for _ in range(3)])+o['CON']*3} | {c}+{o['CON']}*{3}",*[j:={'Deception':'CHR','Intimidation':'CHR','Performance':'CHR','Persuasion':'CHR','Arcana':'INT','History':'INT','Investigation':'INT','Nature':'INT','Religion':'INT','Animal Handling':'WIS','Insight':'WIS','Medicine':'WIS','Perception':'WIS','Survival':'WIS','Acrobatics':'DEX','Sleight of Hand':'DEX','Stealth':'DEX','Athletics':'STR'},f:=sample([*j],k=4),[f"{z} - MOD: {o[j[z]]+b*(a:=(z in f)):+}{' - Proficient'if a else''}"for z in j]][-1],sep='\n')]
clear venture
#

uh, doesn't quite work but good golfing techniques

#

[[b:=max(((l-1)//4)+2, 0)),(o:={})][-1],... can be [b:=max((l-1)//4, 0)+2,o:={},... as well

unique heath
#

wow poke mons

quartz wave
night quarryBOT
# quartz wave !e ~~584b~~ invalidated ```py ... for n in{*k,'CON'}:... ... ```

:white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | CON: 11 - MOD: +0
002 | INT: 11 - MOD: +0
003 | STR: 10 - MOD: +0
004 | WIS: 13 - MOD: +1
005 | DEX: 12 - MOD: +1
006 | CHR: 16 - MOD: +3
007 | HP: 19 | [3, 5, 2]+3*3
008 | Deception - MOD: +3 
009 | Intimidation - MOD: +3 
010 | Performance - MOD: +3 
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/5YQHYEJDKRPNM6J42QRYIITRPA

grave grail
clear venture
quartz wave
#

oh

#

yea wait

#

!e 585b ```py
from random import*
l=3;d=6;P=print;o={};k=["CHR"]*4+["INT"]*5+["WIS"]*5+["DEX"]3+["STR"]
for n in
{*k},'CON':a=sum(c:=[randint(1,6)for()in[()]4])-min(c);m=a-10>>1;o|={n:m};P(n+f": {a} - MOD: {m:+}")
z=f'%r+{m}
{l}';P("HP:",eval(z%sum(c:=[randint(1,d)for()in[()]*l])),'|',z%c)
f=sample(j:="Deception,Intimidation,Performance,Persuasion,Arcana,History,Investigation,Nature,Religion,Animal Handling,Insight,Medicine,Perception,Survival,Acrobatics,Sleight of Hand,Stealth,Athletics".split(','),k=d)
for z,n in zip(j,k):a=z in f;P(z,f'- MOD: {o[n]+max(~-l//4+2,0)*a:+}',"- Proficient"*a)

night quarryBOT
# quartz wave !e 585b ```py from random import* l=3;d=6;P=print;o={};k=["CHR"]*4+["INT"]*5+["W...

:white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | WIS: 12 - MOD: +1
002 | STR: 11 - MOD: +0
003 | INT: 10 - MOD: +0
004 | CHR: 13 - MOD: +1
005 | DEX: 13 - MOD: +1
006 | CON: 16 - MOD: +3
007 | HP: 22 | [2, 6, 5]+3*3
008 | Deception - MOD: +1 
009 | Intimidation - MOD: +3 - Proficient
010 | Performance - MOD: +1 
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/5A2ABGV72B3C6WDV5BNLU57Z5U

clear venture
#

nice

boreal spindle
#

!e
import os,sys
os.system(["cls","clear"][os.name!="nt"])
B=[3*['*']for _ in'0'*3]
for p in range(9):
for x in B:print(*x)
P="XO"[p&1];x,y=map(int,input(f"Player {P} move (column row): ").split());B[y][x]=P;any(all(map(P.eq,l))for l in[*B,*zip(*B),zip([(B[i][i],B[i][~i])for i in(0,1,2)])])>0>sys.exit()
print("It's a draw!")

night quarryBOT
# boreal spindle !e import os,sys os.system(["cls","clear"][os.name!="nt"]) B=[3*['*']for _ in'0'...

:x: Your 3.12 eval job has completed with return code 1.

:warning: Note: input is not supported by the bot :warning:

001 | * * *
002 | * * *
003 | * * *
004 | Player X move (column row): Traceback (most recent call last):
005 |   File "/home/main.py", line 6, in <module>
006 |     P="XO"[p&1];x,y=map(int,input(f"Player {P} move (column row): ").split());B[y][x]=P;any(all(map(P.__eq__,l))for l in[*B,*zip(*B),*zip(*[(B[i][i],B[i][~i])for i in(0,1,2)])])>0>sys.exit()
007 |                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
008 | EOFError: EOF when reading a line
boreal spindle
#

!e

import os,sys
os.system(["cls","clear"][os.name!="nt"])
B=[3*['*']for _ in'0'*3]
for p in range(9):
 for x in B:print(*x)
 P="XO"[p&1];x,y=map(int,input(f"Player {P} move (column row): ").split());B[y][x]=P;any(all(map(P.__eq__,l))for l in[*B,*zip(*B),*zip(*[(B[i][i],B[i][~i])for i in(0,1,2)])])>0>sys.exit()
print("It's a draw!")
night quarryBOT
# boreal spindle !e ```py import os,sys os.system(["cls","clear"][os.name!="nt"]) B=[3*['*']for _...

:x: Your 3.12 eval job has completed with return code 1.

:warning: Note: input is not supported by the bot :warning:

001 | * * *
002 | * * *
003 | * * *
004 | Player X move (column row): Traceback (most recent call last):
005 |   File "/home/main.py", line 6, in <module>
006 |     P="XO"[p&1];x,y=map(int,input(f"Player {P} move (column row): ").split());B[y][x]=P;any(all(map(P.__eq__,l))for l in[*B,*zip(*B),*zip(*[(B[i][i],B[i][~i])for i in(0,1,2)])])>0>sys.exit()
007 |                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
008 | EOFError: EOF when reading a line
boreal spindle
# rough moat ```py mand_color=lambda w=50,h=25,max_iter=100,r=(-0.7,0.7),i=(0,1),chars=".,*34...

!e

mand_color=lambda w=50,h=25,max_iter=100,r=(-0.7,0.7),i=(0,1),chars=".,*3456789abcde ":print(f"{__import__("os").system("")}\b","\n\x1b[0m".join(["\x1b[0m".join([[([z:=0+0j,n:=0].__add__([[(abs([z:=z.__mul__(z).__add__(complex(r.__getitem__(0).__float__().__add__( (x.__truediv__(w)).__mul__(r.__getitem__(1).__sub__(r.__getitem__(0)))),i.__getitem__(0).__float__().__add__( (y.__truediv__(h)).__mul__(i.__getitem__(1).__sub__(i.__getitem__(0)))))),n:=n.__add__(1)].__getitem__(-1)).__mul__(15).__truediv__(max_iter))]for _ in range(max_iter)if z.__abs__().__le__(2)]).__getitem__(-1)).__getitem__(-1),n2:=n.__truediv__(max_iter),f"\x1b[38;2;{(((1.0).__sub__(n2)).__mul__(77)).__int__()};{((n2).__mul__(255)).__int__()};{(((1.0).__sub__(n2)).__mul__(77)).__add__(150).__int__()}m{chars.__getitem__((n2.__mul__(chars.__len__().__sub__(1))).__int__())}",].__getitem__(-1)for x in range(-w,w)])for y in range(-h,h)] ),"\x1b[0m",sep="")
night quarryBOT
boreal spindle
#

!e

[*(lambda _____: _____((lambda _: _([-~True.__rmul__(abs(False))**-~True.__rmul__(abs(False)) for __ in range((-~True.__rmul__(abs(False))**-~True.__rmul__(abs(False)).__rmul__(-~True.__rmul__(abs(False))**-~True.__rmul__(abs(False))).__rmul__(-~True.__rmul__(abs(False))**-~True.__rmul__(abs(False))) + 8))]))(lambda ___: [____ for ____ in range(1, sum(___).__add__(1))])))(lambda ______: [__import__('builtins').__dict__['print'](''.join(list(map(str, _______)))) for _______ in __import__('itertools').__dict__['product'](______, repeat=len(______)) if not None])]
night quarryBOT
boreal spindle
#

!e

(lambda x:x(x,(lambda x:[[[0]*len(x[i])for i in range(len(x))],x])((lambda a:(lambda x,y:[[[[x[r].pop(c),x[r].insert(c,'*')]if y[0][r][c]else[x[r].pop(c),x[r].insert(c,y[1][r][c])]for c in range(1,a-1)]for r in range(1,a-1)],x][1])([a*[0]for x in range(a)],(lambda x:[[[[[(lambda x,y:[y.append(x[1][r][c]),x[1][r].pop(c), x[1][r].insert(c,y[0]+1)])(x,[])if x[0][l][j]else 0for j in range(c-1,c+2)]for l in range(r-1,r+2)]for c in range(1,a-1)]for r in range(1,a-1)],x][1])((lambda x:[[[[x[0][r].pop(c),x[0][r].insert(c,int.from_bytes(open('/dev/urandom','rb').read(1),'big')/10>20)]for c in range(1,a-1)]for r in range(1,a-1)],x][1])([[a*[0]for x in range(a)]for x in range(2)]))))((lambda i:i if i>2and i<12else exit())(int(input('Board Size (max 9):'))+2)))))((lambda x,y,p=(lambda x:[print('\x1b[1;32m ',*range(1,len(x[0])-1),sep=' '),[[[print(f'\x1b[1;32m{r}\x1b[0m',end='')if c==0else[print(' ',end=''),print(['■','F'][x[0][r][c]],end='')if x[0][r][c]!=2else print(x[1][r][c],end='')]for c in range(len(x[0])-1)],print()]for r in range(1,len(x[0])-1)],x][-1]),i=(lambda f,i:[f[0][int(i.split(',')[0])].pop(int(i.split(',')[1])),f[0][int(i.split(',')[0])].insert(int(i.split(',')[1]),{'f':1,'c':2}[i.split(',')[2].lower()]),[print('You Lose'),exit()]if'*'==f[1][int(i.split(',')[0])][int(i.split(',')[1])]and'c'==i.split(',')[2].lower()else f][2]),q=[]:[p(y),q.append(i(y,input('Type Row,Column,[(F)lag or (C)lear]:'))),x(x,q[0])if(lambda y,q=[],w=[]:[[[q.append(y[0][r][c]==1and y[1][r][c]=='*')for c in range(len(y[0][r]))]for r in range(len(y[0]))],q][1].count(1)!=[[[w.append(y[1][r][c]=='*')for c in range(len(y[1][r]))]for r in range(len(y[1]))],w][1].count(1))(y)else print('You Flagged All The Bombs!')]))
night quarryBOT
# boreal spindle !e ```py (lambda x:x(x,(lambda x:[[[0]*len(x[i])for i in range(len(x))],x])((lam...

:x: Your 3.12 eval job has completed with return code 1.

:warning: Note: input is not supported by the bot :warning:

001 | /home/main.py:1: SyntaxWarning: invalid decimal literal
002 |   (lambda x:x(x,(lambda x:[[[0]*len(x[i])for i in range(len(x))],x])((lambda a:(lambda x,y:[[[[x[r].pop(c),x[r].insert(c,'*')]if y[0][r][c]else[x[r].pop(c),x[r].insert(c,y[1][r][c])]for c in range(1,a-1)]for r in range(1,a-1)],x][1])([a*[0]for x in range(a)],(lambda x:[[[[[(lambda x,y:[y.append(x[1][r][c]),x[1][r].pop(c), x[1][r].insert(c,y[0]+1)])(x,[])if x[0][l][j]else 0for j in range(c-1,c+2)]for l in range(r-1,r+2)]for c in range(1,a-1)]for r in range(1,a-1)],x][1])((lambda x:[[[[x[0][r].pop(c),x[0][r].insert(c,int.from_bytes(open('/dev/urandom','rb').read(1),'big')/10>20)]for c in range(1,a-1)]for r in range(1,a-1)],x][1])([[a*[0]for x in range(a)]for x in range(2)]))))((lambda i:i if i>2and i<12else exit())(int(input('Board Size (max 9):'))+2)))))((lambda x,y,p=(lambda x:[print('\x1b[1;32m ',*range(1,len(x[0])-1),sep=' '),[[[print(f'\x1b[1;32m{r}\x1b[0m',end='')if c==0else[print(' ',end=''),print(['■','F'][x[0][r
... (truncated - too long, too many lines)

Full output: https://paste.pythondiscord.com/QUTKC67K42QSARLDCE2G5JBR4I

restive void
#

@silk warren
||

class AllMeta(type):
    def __instancecheck__(self, other):
        return all(isinstance(other, t) for t in self.types)

class All(metaclass=AllMeta):
    def __class_getitem__(self, types):
        new_cls = AllMeta(f"All[{', '.join(t.__name__ for t in types)}]", self.__bases__, {})
        new_cls.types = types
        return new_cls

||

silk warren
#

i wonder what to name it

#

for now types_intersection

restive void
#

typing.Intersection, if it was in the standard lib

silk warren
#

🤔

#

how would u do that

#

i actually think i can do that

#

i mean after i import stuff from typing, i can create a class named typing

restive void
#

Nah, I just mean if it was in the standard lib

silk warren
#

its an interesting idea to do that though

restive void
#

This has been discussed a long time ago, apparently static typing people don't care about this

silk warren
#
class typing:
  class Intersection:
    ...
restive void
#

Hehe

silk warren
#

lol

restive void
#

You can also just setattr it on the real typing module

#

With a pth file so you don't even have to import your lib that does the patching, only pip-install it. 😈

silk warren
#

🤔

#

if u wouldn't import it

#

it wouldn't setattr

restive void
#

Yes it could, look up pth files

silk warren
#

interesting

#

maybe i'll look into it later

#

can u explain to me what u did in your class_getitem

#

nvm give me a sec

#

i'll read it more deeply

#

ok i get what u did

#

@restive void f"All[{', '.join(t.__name__ for t in types)}]"

#

do u think its wise

#

wouldn't just "All" suffice

#

actually no u cant have 2 classes with the same name...

restive void
silk warren
#

they would overwrite each other

restive void
#

The cleaner solution would probably a custom __repr__ in the metaclass

#

No, because you're not actually setting this newly created class to that name in any namespace. You just return it to be used once.

silk warren
#

true i guess

#

but i think its nicer if it's useable as a anme

#

even if i'm not gonna do that

restive void
#

It won't be, and why? list[int] is also not available as a name.

silk warren
#

oh

#

so maybe, what about creating it without a name

#

like ""

#

can u do that in meta classes?

restive void
#

Sure. But then it won't look nice

silk warren
#

'list[int]'

#

'int | tuple'

#

what about

#

'int & tuple'

restive void
#

Nice, yeah

#

Use fishhook to add it to type

silk warren
#

alright lets see

restive void
#

||

import fishhook

class IntersectionMeta(type):
    def __instancecheck__(self, other):
        return all(isinstance(other, t) for t in self.types)

    def __repr__(self):
        if hasattr(self, "types"):
            return " & ".join(t.__name__ for t in self.types)
        return "Intersection"

class Intersection(metaclass=IntersectionMeta):
    def __class_getitem__(self, types):
        new_cls = IntersectionMeta("Intersection", self.__bases__, {})
        new_cls.types = types
        return new_cls

@fishhook.hook(type)
def __and__(self, other):
    if issubclass(self, IntersectionMeta):
        return Intersection[(*self.types, other)]
    return Intersection[self, other]

||

silk warren
#

thats cool not gonna lie

silk warren
#

about to finish writing my code

#

i remember guido posting once about intersection

#

apparently what wasn't possible in the past is possible today

grave grail
stray grove
#

wait. i can read this

#

dudeee that's even scarier

#

why can i read that?

stray grove
#

dude it's a minesweeper game

#

you can't play minesweeper without inputs

grave grail
#

But you cannot evaluate code that needs external input on a bot

#

💀

#

If you want to play it, play it locally

bright valve
grave grail
fleet bridge
night quarryBOT
fleet bridge
#

!e shorter and less variables used

import os
os.close(0)
os = open(__file__, "r")
print(input())
night quarryBOT
bright valve
#

!d os.close

night quarryBOT
#

os.close(fd)```
Close file descriptor *fd*.

Note

This function is intended for low\-level I/O and must be applied to a file descriptor as returned by [`os.open()`](https://docs.python.org/3/library/os.html#os.open) or [`pipe()`](https://docs.python.org/3/library/os.html#os.pipe). To close a “file object” returned by the built\-in function [`open()`](https://docs.python.org/3/library/functions.html#open) or by [`popen()`](https://docs.python.org/3/library/os.html#os.popen) or [`fdopen()`](https://docs.python.org/3/library/os.html#os.fdopen), use its [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close) method.
hybrid trail
#

Why doesn't X = lambda n: exec("n *= 3") or n return a modified n? I would expect X(10) to return 30 but it returns 10 🤔

#

If it relevant I was trying to golf the following function:

def ternary(n):
    D = ""
    for _ in range(3):
        D += ("|_ "[n % 3])
        n //= 3
    return D
quartz wave
#

it modifies locals() but it doesn't modify the actual variable

fleet bridge
#

modifying local variables is complicated

quartz wave
#

(might be fixed in 3.14, no one knows)

fleet bridge
#

i wonder if it is already fixed in python4

quartz wave
#

fwiw it's literally shorter to just unroll the loop

hybrid trail
#

longer than a lambda

#
T=lambda n:"".join(["|_ "[n%3],n:=n//3][1]for _ in"XXX")
fleet bridge
#

there is a typo

#
T=lambda n:"".join(["|_ "[n%3],n:=n//3][0]for _ in"XXX")
#

56 -> 50 ```py
T=lambda n:eval('("|_ "[n%3],n:=n//3)[0]+'*3+'""')

#

my thought process```py
T=lambda n:"".join(["|_ "[n%3],n:=n//3][0]for _ in"XXX")
s,T="|_ ",lambda n:"".join([s[n%3],n:=n//3,s[n%3],n:=n//3,s[n%3],n:=n//3][::2])
T=lambda n:"".join(eval(f"[{'"|_ "[n%3],n:=n//3,'*3}]")[::2])
T=lambda n:"".join(eval('['+'"|_ "[n%3],n:=n//3,'*3+']')[::2])
T=lambda n:"".join(eval('"|_ "[n%3],(n:=n//3),'*3)[::2])
T=lambda n:eval('("|_ "[n%3],n:=n//3)[0]+'*3+'""')

hybrid trail
#

insane

versed eagle
hybrid trail
#

yeah

#

lol

versed eagle
#

48b then

hybrid trail
#

//3//3 -> //9

versed eagle
hybrid trail
#

redemption arc

versed eagle
#

i dont think so but im not sure

quartz wave
versed eagle
#

yep

#

loop unrolling is shorter

quartz wave
#
t='|_ ';ternary=lambda n:t[n%3]+t[n//3%3]+t[n//9%3]
hybrid trail
#
T=lambda n,s="|_ "*9:s[n]+s[n//3]+s[n//9]
quartz wave
#

ah yes.

versed eagle
quartz wave
#

hardcoding

#

beats 99% of all other golfing methods when applicable

versed eagle
#

fails if n is big enough, doesn't it

#

yeah

hybrid trail
#

yep

#

but passes my testcases

versed eagle
#

actually what are your test cases

hybrid trail
#

well the function is to convert a 3 trit number to base 3

#

so n in is [0, 26]

versed eagle
#

what specific test-cases do you have though

hybrid trail
#

like what problem am I solving?

versed eagle
#

like what specifically are your test cases

#

like do you just check if it equals the correct result for all the thingies?

quartz wave
#

i think "whole program works" is the test case

hybrid trail
versed eagle
#

yes

#

i want test-cases to test against

#

so i know what behaviour im allowed to drop and needs to be kept

hybrid trail
#
assert T(3) == '|_|'
assert T(5) == ' _|'
assert T(6) == '| |'
assert T(8) == '  |'
assert T(21) == '|_ '
assert T(23) == ' _ '
assert T(26) == '   '
#

these are the only values I use

versed eagle
#

:3

quartz wave
#

fails the big one

#

:p

versed eagle
quartz wave
#

33b -> 32b ..."__eq__":int...

versed eagle
#

doesnt eq have to return a bool

#

or did they change that??

quartz wave
#

quo.

#

it just works

#

0.o

versed eagle
#

huh

quartz wave
#
>>> T(123)==8
8
#

how-

#

how iw--?

versed eagle
#

i guess i was misremembering

#

i was probably thinking of __len__ or __index__ or one of those things thats required to return an int

quartz wave
#

myaaaaaaa why is this alowld T^T

versed eagle
#

¯_(ツ)_/¯

versed eagle
quartz wave
#

it doesn't pass the tests btw :p

#

maybe '__eq__':str

versed eagle
versed eagle
quartz wave
#

'__eq__':id

#

31b

#

__eq__':T

#

30b

#

nvm-

versed eagle
#

oh yeah id is guaranteed to never be falsey right

#

never 0

hybrid trail
#

T=lambda n:" || | ____ | | ||"[n%100%19%7::7] is a funny solution but not any shorter

versed eagle
#

though cpython hasnt been ported to any of those that i know of

twin roost
fleet bridge
lunar juniper
wheat bloom
#

;

#

did i scare anyone?

arctic skiff
#

no but you are about to get scared

#

!epy def main() -> { print('Hello, world!') }: return ;{ }

night quarryBOT
karmic pumice
#

!e

skibidi = "def"
dop = "main"
dоp = "()"
yes = " -> "
yеs = " None:"
hi = "print("
mark = "\"Hello, World!\")"
уes = "if __name__ == \"__main__\":"
уеs = "main()"

exec(f"""
{skibidi} {dop} {dоp} {yes} {yеs}
    {hi} {mark}
{уes}
    {уеs}
""")
night quarryBOT
versed eagle
#

just defining it

stray grove
versed eagle
stray grove
versed eagle
#

it is python

stray grove
#

Wait a minute

#

oh crap

#

Bro wtf

#

Why are you returning a set of print hello world

versed eagle
versed eagle
#

which is what print returns

stray grove
#

My brain is not braining

#

I’m not even sure what the curly braces do anymore

#

They’re used like everywhere in Python

versed eagle
#

are they?

#

sets, dicts, fstrings, where else?

stray grove
#

And sets

#

And .formats

#

And fstrings

#

What do curly braces even mean anymore

versed eagle
#

.format is included in "fstrings" there

#

ugh shush bot

stray grove
#

.format existed before fstrings

#

And that’s why they’re different

versed eagle
versed eagle
stray grove
#

Python syntax is still less annoying than JavaScript somehow

versed eagle
stray grove
quartz wave
# stray grove That’s not even Python, why did it work?
def main()   # function `main()`, no arguments
  -> {       # annotated return type as a setー
    print("hello world")  # prints `hello world` then returns `None`
}:           # ーa set with only 1 element, `None`

    return;  # function code block returns an implicit `None`
    {}       # then loads an empty `dict`, although this is a no-op since it's below the return
arctic skiff
#

just go and try it yourself

silk warren
#

can u write this better:

all(any(issubclass(b_cell, a_cell) for b_cell in b) for a_cell in a)
tacit lantern
#

So I'm trying to use PostGIS, the geospatial plugin for PostgreSQL. it needs GDAL, but GDAL 3.9 is not in Ubuntu 22 packages (and 24, I checked) only GDAL 3.8 so I tried to install conda to install 3.9, but conda is also some kind of version manager, and now I'm in a different context with GDAL 3.9 installed but no python and no django. I think I'm a little bit over my head and I am not sure reinstalling python and django in this weird conda (base) space is the best idea

versed eagle
versed eagle
arctic skiff
versed eagle
arctic skiff
#

yes

versed eagle
#

try calling main

#

there

arctic skiff
arctic skiff
versed eagle
#

lmao

arctic skiff
#

oh I misinterpreted

#

you said "function" doesn't print

#

not "it" doesn't print

#
#IndentationError, ... I forgot the quriky way I used to use
def main(): {
    print('Hello, world!')                                         };
    return                                                         ;{
}
main()```if you want to call it
#

oh wait it will have indentation error

versed eagle
#

put an arrow instead of a colon

#

and a colon after the first set of braces

arctic skiff
#

??

#

isn't it what I previously did?

arctic skiff
versed eagle
#
def main(): {
    print('Hello, world!')                                         };
    return                                                         ;{
}
main()

vs

def main() -> {
    print('Hello, world!')                                         }:
    return                                                         ;{
}
main()
arctic skiff
versed eagle
#

yes

#

the first one is what you sent

versed eagle
#

that it's invalid is the point im making

arctic skiff
#

I can't remember the way to include return in it

quartz wave
#

don't you hate it when you just accidentally use braces ```pycon

from future import braces
def main() {
... print("Hello", end=',')
... print(" World!")
... }
main()
Hello, World!

arctic skiff
quartz wave
#

oh okay

arctic skiff
#

oh wait a freaking minute

#

you just did what

#

tell me its python 4

quartz wave
#

included return :p

arctic skiff
#

100% python 4

arctic skiff
arctic skiff
#

a while ago

versed eagle
arctic skiff
#

what you sent is invalid code?

#

and the 2nd one is literally written by me which you don't like because calling the function does nothing

versed eagle
#

just put the print in the function

arctic skiff
#

??

versed eagle
#
def main() -> {                                           }:
    print('Hello, world!')
    return                                                         ;{
}
main()
#

braces wont align because now im on mobile so i cant see that, but it works

#

¯_(ツ)_/¯

unique heath
#

hi what is this

unique heath
#

not cooking