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)
#esoteric-python
1 messages · Page 44 of 1
so it doesnt raise that on partially initialized modules
but when imported yet-to-define symbols of that module?
you are allowed to import partially initialized modules, but not allowed to get any attributes from them
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
since when, I thought that you couldnt import partially initialized modules at all, it would've made more sense to me, and I thought making some old branch of matplotlib I got that error when I just imported a constant module
i think it was like this always
fr?
https://stackoverflow.com/questions/68281582/circular-imports-python
that. was. python. 2
I feel old rn
wdym
What mean by pure code
that is pure code
it's the most pythonic one actually
this raises RecursionError
or segfaults
or get terminated (from macos)
@quartz wave the cereal class in your name should have base of Edible
did you know you can change an async generator's __code__ into a regular generator and do weird stuff?
!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()
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
004 | 4
there we go
Edible is a protocol, not a base class
ohh right, Food is a base class
that's awesome XD
Have no idea, what's going on here. But interesting..
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
the issue that randomly calling locals() solves seems to be
https://github.com/zeromq/pyzmq/issues/1167
but I'm not sure
"pure function"?
depends what you qualify as a side effect
locals() copies locals and nonlocals to a dictionary and immediately pops it
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!
something something __del__ and object deallocation
yeah
async is pretty sensitive to objects existing, especially when it comes to tasks and weak references
that sounds
uh
soundy
(very bad)
nobody has no idea of why that's there, have you?
!e
print('someword'.count(''))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
9
ik this is not super esoteric but I just learned yesterday that this implementation is weird as fuck lol
this is the only result that makes sense
wdym
either that or float('inf')
It's just not intuitive at all
The idea that '' exists before/after/between each letter
And only one at that
Inf would make more sense if it could return floats
try concatenating each letter with an empty string in between
You could put any number of empty strings between them, that doesn't make it any more intuitive
well no
any number of empty strings is just one empty string
(ε ε) = ε
Hm yeah if you put it like that ig it makes sense
Yes, but also ε = εεεεε
it makes more sense to take the minimal set, no?
since theres no bound on expansion
I mean yeah, this is probably the least bad solution.
Another acceptable option would have been raising ValueError
yeah
why anyone would want to count empty strings in the first place is the real question lol
!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}]]
:white_check_mark: Your 3.12 eval job has completed with return code 0.
4
btw
does this count as an ast interpreter? i think yes
!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}]]
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 1
002 | 1
003 | 2
004 | 3
005 | 5
006 | 8
007 | 13
008 | 21
009 | 34
010 | 55
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/76UFHMFC6IKNNM7NNRUS6UOR2U
now write bf interpreter
i do wonder if its a special case in the method or just a consequence of how it was implemented
it's a special case
if it wasn't the program'd probably crash :>
i think it would rather freeze
Objects/stringlib/count.h lines 21 to 22
if (sub_len == 0)
return (str_len < maxcount) ? str_len + 1 : maxcount;```
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
If you like forbiddenfruit, you'll love fishhook :)
eimpl
einspect you mean? is it still developed? i havent seen ionite in a long time
oh yeh that
ohhh 😮
and do you know if it's somehow possible to override the behavior of short-circuiting from runtime?
It isn't through normal means, not without the big guns like codecs, recompiling CPython, ...
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"))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 11
002 | 3
003 | 1
first result is 12 tho
just checked CPython's implementation and it is a special case
because they use a fastsearch algorithm that'd break with an empty string
Would be surprising they +1 to length
searhc go brrrrrr
!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
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 12
002 | 3
003 | 1
004 | 1
005 | 0
>>> 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
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.
Oh god now I have to go and find a way to implement a hook for that in pure python
it should be possible with modifying bytecode at runtime, no?
That counts as "big guns"
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
Could use source code analysis + tracefunc to know exactly where to swap the bytecode
I assume fishhook.asm would also be big guns?
!e
x = 2
while True:
print(x)
x = x^2```
:x: Your 3.12 eval job has completed with return code 143 (SIGTERM).
001 | 2
002 | 0
003 | 2
004 | 0
005 | 2
006 | 0
007 | 2
008 | 0
009 | 2
010 | 0
... (truncated - too many lines)
Full output: too long to upload
!e
x = 2
while True
x = x^2
x = x^2
x = x^2
x = x^2
print(x)
:x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 2
002 | while True
003 | ^
004 | SyntaxError: expected ':'
!e
x = 2
while True:
x = x^2
x = x^2
x = x^2
x = x^2
print(x)
:x: Your 3.12 eval job has completed with return code 143 (SIGTERM).
001 | 2
002 | 2
003 | 2
004 | 2
005 | 2
006 | 2
007 | 2
008 | 2
009 | 2
010 | 2
... (truncated - too many lines)
Full output: too long to upload
i dont think thats eso
10 XOR 10 = 00
00 XOR 10 = 10
10 XOR 10 = 00
00 XOR 10 = 10```
#bot-commands
so more accurately ```py
def count(txt, target, start=None, end=None):
found = 0
if start is None:
start = 0
if end is None:
end = len(txt)
while start <= end:
if txt.startswith(target, start):
found += 1
start += max(len(target), 1)
else:
start += 1
return found
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
what is golfing
making a code as short as possible
just like in golf where you want the fewest number of strokes possible, you want the least characters possible
oh ty
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?
520 now
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
||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
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
n="Twelve drummers ...".split(";")
m=""
for d in l:print(f"... Sent to me\n{m:=m+n.pop()+"\n"}")
``` does this work?
Cant test on mobile 😔
Ah ofc
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?
not getting great results
Yeah they all have to be the same (or at least similar) length
>>> for i in range(12): print('FSTFFSSENTETiehoiieiielwrciufxvgnneesorrttehttvltndthhnthhef'[i::12])
...
First
Secon
Third
Fourt
Fifth
Sixth
Seven
Eight
Ninth
Tenth
Eleve
Twelf
sadge
!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))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 5 6 5 6 5 5 7 6 5 5 8 7
002 | 27 21 18 19 16 19 23 22 20 20 21 25
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
oh true lol
Oh wait
That only works with this method
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
that misses the entire point tho
but prob not
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
!rule paid
golf is free 
We do free help in a limited scope
golf is best
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()
nice
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]
only integers?? :<
only integers for literals in expressions
operations are mostly duck typed, so floats are ok
would be cooler if it used lossless rationals
>> 1 2 / 5 + 2 **
[121/4]
and then display modes can change
imagine representing acos(-1) as rational
ok 1 display mode
for the most part ```py
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.4142135623730951]
x x *
[2.0]
wait a minute that's not an operation >:T
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
why not make a hybrid binary()/unary() function for sub/neg
inc = [ 1 + ]
parse thing between brackets as callable that invokes all things inside of brackets
what should happen in this case? 2 1 -
what if it is in the middle of expression where stack if pretty full?
ok i get it
not the 2nd question though 
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
complex arithmetic!! ```py
x = 1 ! sqrt
x
[1j]
x 2 **
[-1.0]
!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])(". + @ . + ! . + + @ . + + !"))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
{'a': 1, 'b': 2}
inc 1 + ;
can't you replace __setitem__ with assignment expressions ?
cannot use assignment expression with subscript
yes but you can combine it with spreading
s:=[*s[:-1],s[-1]+1]
shaves off 5 chars
i wasnt golfing though
is it meant to keep results between runs
its not meant to be used ||multiple times|| at all, i just wrote something
ye u can remove the spoiler block and whats inside lol
lmao
postfix python 💀
what you want? this seem irrelevant to esoteric
my fault brother sorry direct me where i should drop it
issue is: what do you want
#ot1-perplexing-regexing message
182b https://leetcode.com/problems/substring-with-concatenation-of-all-words
from collections import*;C=Counter
class Solution:
def findSubstring(_,s,words):d=words;t=len(d[0]);return[i for i in range(len(s))if C(d)==C(s[i+j*t:i-~j*t]for j in range(len(d)))]
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
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?
Did you repeat these measurements? If not, it could simply be due to bytecode caching
Oh yea, many times.
Especially the ram is egregious...
You can try it yourself, all the code is above.
seems like bytecode caching - with python -m tests, the first run is much slower, whereas python tests.py is always slow. Weird that the latter doesn't cache, though.
aaah
thanks man, that's clearly it! The parsing of the gigantic AST -> bytecode must be slow
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.
as intended
__pycache__ is used only to cache modules, never scripts
py -m tests makes it a module, so caching happens, py tests.py calls the file as script, so no caching
Yea, I guess normally you won't notice this difference, I just have a pathological case
huh..
i've got a ton of files in my i have no idea how or why those files ended up there__pycache__ to prove otherwise
.....
how did those files end up there
i don't remember importing them 0.o
are you using IPython? it might import main file under the hood, instead of executing it directly, or something like that
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)
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('<')
you can check its name
thats what im currently doing
oh, right, i cant read
for generators - there is a flag somewhere in a code object that indicates that it is a generator
Yeah, obj.co_flags & 32
does that distinguish between generator expressions and def gen(): yield generators?
if anyone curious how to fix is - the solution was
global __name__
import sys
module = sys.modules[__name__]
sys.modules["test_folder_addon"] = module
__name__ = "test_folder_addon"
& 32 
Each bit is a flag. A bitflag if you will
yeah it does
the idea is that 32 is a truthy value
so ```
if o.co_flags & 32:
do_stuff()
!eval
def fn():
raise Exception()
fn.__code__ = fn.__code__.replace(co_filename=f'stuff: {fn.__code__.co_filename}')
fn()
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 5, in <module>
003 | fn()
004 | File "stuff: /home/main.py", line 2, in fn
005 | raise Exception()
006 | Exception
does anyone know why this still prints the correct line of code in the traceback, even though the filename is altered like that?
https://github.com/python/cpython/blob/main/Lib/traceback.py#L477
https://github.com/python/cpython/blob/3.12/Lib/linecache.py#L147
this is as far as I managed to go looking for the cause
Lib/traceback.py line 477
linecache.lazycache(filename, f.f_globals)```
`Lib/linecache.py` line 147
```py
def lazycache(filename, module_globals):```
cant see how this is being handled
because line numbers are also stored
there is no way to determine line number knowing only file name
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()
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 5, in <module>
003 | fn()
004 | File "stuff:", line 2, in fn
005 | Exception
no code shows up here without the original path in the replacement
linecache.lazycache(filename, f.f_globals)
this looks for module loader in global namespace and extracts real filename from it
hmmmm
digging further, now im thinking it might be somewhere around here:
https://github.com/python/cpython/blob/92893fd8dc803ed7cdde55d29d25f84ccb5e3ef0/Python/traceback.c#L317
Python/traceback.c line 317
_Py_FindSourceFile(PyObject *filename, char* namebuf, size_t namelen, PyObject *io)```
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);```
i think this is it?
!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!")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, world!
only in math
maths is fun
it depends
most maths are fun
i hate trig
its just punching numbers into calculators
theres nothing fun about trig
So why does Python IDLE has the option for Wingdings as font? xD
because hwy not
you hate trignometry?
as it is atm
all my homies hate trig
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)
bsearch=lambda c,t,s=0,e=None:[-1,s][t in c[s:e]]if(l:=(e:=[e,len(c)][e==None])-s)<2else bsearch(c,t,s,[e,m:=s+l//2][t<c[m]])
does this work
well no, the original also doesn't work
what the hell is n?? :3c
“does it replicate behaviour of the original”
is what “does it work” means here
silly goose!
Noun
silly goose (plural silly geese)
- (informal) A silly person
:3
see also https://en.wikipedia.org/wiki/Goose
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...
im guessing its meant to be c
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
that one is meant to be c
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)
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])
oh i was right
fair!
woah
is -1 ^ n equal to ~n?
i just stumbled upon this channel and these are insane
yeah
yup
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

import bisect:
boring way 39b ```py
from bisect import*;bsearch=bisect_left
bsearch=__import__("bisect").bisect_left
``` hmm
40b...
!e
Missing required argument
code
Missing required argument
code
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)]))
...
1 sec adding color
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="")
what does it do 
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
make it zoom into a designated point now
what parameters
0.94x per iteration zoom,
Real: 0.2505845176040427718957771316508473905552515740661571423212687174479167, imag: 0.00002276281458802574942404639696751451557095909568791588147481282552083
i have no idea how to implement that .^.
holy shit you're a real one
how did you calculate that
thats the point
To zoom in on
i didnt calculate it i found it somewhere
i made a zoomer, currently working on making it fast
Wrotr my own arbitrary precision arithmetic extension for it
ooh fun
i would have just used gmpc lol
im on windows :/
I wouldve done that
But idk how
tbh i shouldve just done wsl :(
im too far in anyhow
wouldn't decimal work?
it would
but i found doing this in parallel using gomp works very well
and decimal requires the gil
im like 95% sure gmpc would work on windows
weird/obfuscated (i.e intentionally hard to read) code among a few other things
itd likr if python was silly
I tried
color? 
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
the caret ^ in the SyntaxError seems to be at the position of the ! in my code
ooh
codec isn't working for me made it work
ok here's what i concluded
- the argument to the
incrementaldecoderparameter should be a custom class that decodes using your decoder function - only
name,encode,decode, andincrementaldecoderare the required parameters to make it work import_expression.pthhas to be in/lib/site-packages(auto-install it maybe?)
i do install the pth when it's installed from source
well i noticed that hoopy doesn't define incrementaldecoder and it works fine https://github.com/RocketRace/hoopy/blob/f0c7868b1c73bb23ead7c3b4aa784f93c4424c5f/hoopy/codec.py#L36-L39
hoopy/codec.py lines 36 to 39
incrementalencoder=utf_8.IncrementalEncoder,
incrementaldecoder=utf_8.IncrementalDecoder,
streamreader=utf_8.StreamReader,
streamwriter=utf_8.StreamWriter,```
how does code use it anyway?
https://github.com/RocketRace/hoopy/tree/main?tab=readme-ov-file#setup this one works by import and manual register
that's neither here nor there
i'm using a pth to do the same thing
it still uses # coding: lines
do you do import import_expression; import_expression.register(); import file?
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
well it's kind of weird what i debugged
doing that, i was able to reproduce the error u got
but implementing a custom incremental decoder makes everything work fine
(and providing encode, decode, and incrementaldecoder)
can i use your incremental decoder?
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 ""
will try
@quartz wave i still get the same error
this codec shit is so brittle istg
just pushed
@quartz wave
what version of python are you using
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
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
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
some ideas
Due to the hell that is f-string parsing, and because
!is already an operator inside f-strings, import expressions inside f-strings will likely never be supported.
f-strings are tokenized more distinctly in 3.12+
Due to python limitations, results of
import_expression.execwill have no effect on the caller's globals or locals without an explicitglobalsargument.
sys._getframe(1)
Took up too much ram
how much?
i want to support 3.8+ and i don't want to use internals to access the frame
@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
yup
@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
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```
x=int(k);l=[]
x,*l=int(k),
``` -1?
x,*l=thing is roughly x=thing[0];l=thing[1:]
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=" + ")
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?
x,*l=int("64"),
while x:
i,j=0,1
while j<=x:i,j=j,j+i
l+="+",i;x-=i
print(*l[1:])
``` actually, adding `"+"` to `l` is shorter
yep
ooh i thought of that but i was doing it trailing instead of leading
trailing is a 1c difference from the :-1 slice
i didnt even think of slicing i was using an if to not add it on the last one which is way longer
this channel managed to achieve in 30 minutes what i tried to figure out for 1 hour
ok
full error?
SyntaxError: encoding problem: ie
no traceback
had to figure it out by print()s inside the code
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
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)```
both ast.Constant() calls need a .kind assigned in versions < (3, 9)
hmm hyes
# 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
This isn't the right channel for this. Pandas stuff generally goes into #data-science-and-ml. Of course, you can also just go into #1035199133436354600
Sorry you're right
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.
what's with people going into this channel expecting normal help
we can make their help golfed
If we traumatize them with golfed symbol soup for help, maybe they will stop 
we will play golf with their problems
lets make a rule here, whoever comes for normal help here will get their code golfed
I’ve tried all the normal stuff, I’m in need of something esoteric
Alr bet
Golfed or one lined?
Or both
yes
golfpilled
0-o
O.o
!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]))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
15
pure for loop
me on my way to replicate haskell's traverse and forM to one-up you
any way to create a infinite loop inside a lambda without infinite recursion?
got it, with itertools.cycle
iter(int,1) is an infinite iterator of 0's
nah, the more obfuscated it is the better
is a whole pygame game in one line after all
and gotta do the main loop
well itertools cycle is not really obfuscated
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?
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
I can make it false by convoluting it with a lambda
lambda callback:sum([(lambda :[callback(), 0][1])() for _ in cycle([0])])
``` that's my final version
why the inner lambda? it does nothing
!e
# another idea
*filter(lambda _:False,(print("hello") for _ in range(10))),
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | hello
002 | hello
003 | hello
004 | hello
005 | hello
006 | hello
007 | hello
008 | hello
009 | hello
010 | hello
the [] ruin it, you are still making a list
Fr?
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
Doesnt Python make a generator out of the [] to save memory?
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])")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0 0 RESUME 0
002 |
003 | 1 2 PUSH_NULL
004 | 4 LOAD_NAME 0 (sum)
005 | 6 LOAD_NAME 1 (y)
006 | 8 GET_ITER
007 | 10 LOAD_FAST_AND_CLEAR 0 (x)
008 | 12 SWAP 2
009 | 14 BUILD_LIST 0
010 | 16 SWAP 2
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/3P6VXV7COGV224O74ANGKR37KQ
well, it still appends
yes
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!")
https://paste.pythondiscord.com/YX6A
not finished though
is there a channel just normal python?
Did you know that the state monad/flapMap in haskell can be written as a one liner as s >>= f -> uncurry f . runState s
what do you mean by "state monad can be written as a one liner" and then using runState which uses State? you havent really.. written the monad, just expressed its >>= (bind/then) through the other thing it implements
(neither does "a one liner" in haskell really.. surprise anyone. its a language of expressions rather than statements)
i mean it's neat as it demonstrates the implementation of State
it doesnt, though. it just represents the thing with 3 other abstractions instead of one. "the implementaion of state" is an abstraction on a function taking some "state" of type, lets say, s and returning a tuple with the "computed value" and the "new state" (a, s)
yeah duh
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
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
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
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.
!pypi forbiddenfruit :P
class property?
wdym-
!e
class MyClass:
def __init__(self):
...
@property
class propertyclass:
def __init__(self, *args):
self.deez = "nuts"
print(args)
print(MyClass().propertyclass.deez)```
: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
@property
class I_AM_GOD:
pass
Why were two arguments given? I need to figure this out.
!e
class MyClass:
def __init__(self):
...
@property
class propertyclass:
def __init__(self, *args):
self.deez = "nuts"
print(args)
print(MyClass().propertyclass.deez)```
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | (<__main__.MyClass object at 0x7f0765083b90>,)
002 | nuts
cursed
THAT'S WHAT I NEED.
!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)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | hello
002 | nuts
You absolute mad lads.
this is so fucckde
wait a minute
But it makes so much sense! It passes self!
that initializes an instance
But only when it needs to. It's literally perfect.
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.
aww :(
:white_check_mark: Your 3.12 eval job has completed with return code 0.
yes!
yay!!!
!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?
!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
:white_check_mark: Your 3.12 eval job has completed with return code 0.
yes!
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.
!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)```
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 26, in <module>
003 | print(Deez().nuts)
004 | ^^^^^^
005 | TypeError: 'NoneType' object is not callable
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)```
: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'
...
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)```
: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 13, in get
006 | if orig(item) and item in pf:
007 | ^^^^^^^^^^
008 | TypeError: expected 1 argument, got 0
!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
: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
aaaaaaa
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
lemme cook
Oh, it gives you a link to see the output.
is there any way to golf ["│╱"[j>2*i+1],"█"][j==2*i+1]?
holy shit whats the non-golfed version
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
"█╱│"[(j>2*i+1)-(j<2*i+1)] 🤦♂️
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.')
italic isnt a colour
nor is bold
you silly goose
the codes never change, by making these properties instead of class variables you just add extra pointless lines and calls
isn't #esoteric-python all about non-understandable code
You have a point 
just make your class with a just lambdas and type and you'll be fine
Why not something like this```py
@lambda x: x()
class style:
def format(self, fmt):
...
print(f"{style:red,bold}text")
To me, esoteric is unusual, not non-understandable. Is non-understandable a subset of unusual? Yes. But not all there is to it.
and golfing
When did __format__ became a dunder
hey everybody...am new here
2.6, when builtins.format was added
https://docs.python.org/2/library/functions.html#format
-# sorry for reply ping
well you did ask when it became a thing :p
I did say it's not a invalid answer, was just surprised
I am looking for developer can build a RESTful API for a simple blogging platform
That would work too, but this method lets you use f'{Color.RED.BOLD:The Text To Be Formatted}' to only format a section of it. Though, using your method and just having {style} be the format reset would work well as well.
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.
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
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
block genexprs also
I could try to prevent it to be created, but why?
anything is safe as long as you don't execute it yet
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
But I have to execute it
why?
For a project 💀
The code include running script which annoying because of the medium of the transmission, running on the client side is not possible
it is not safe to execute arbitrary code even if both global and builtin scopes are completely empty
there was a challenge a while ago in this channel
Can I see it?

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
are you manually interpreting ast?
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
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)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | /home/main.py:1: SyntaxWarning: invalid decimal literal
002 | print((1for()in()).gi_𝑓rame)
003 | <frame at 0x7f1f458d9440, file '/home/main.py', line 1, code <genexpr>>
(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).
!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')]
: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
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
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')]
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
wow poke mons
!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
I am still hoping it could depend on how much I implement something instead of how much I blacklist it
nice, but the output got a little miffed up CON: 11 - MOD: +0 HP: 19 | [3, 5, 2]+3*3 the 3*3 is level times consitution modifier so it should be 3*0
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)
: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
done
nice
!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!")
: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
!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!")
: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
!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="")
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
!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])]
:x: Your 3.12 eval job has completed with return code 143 (SIGTERM).
001 | 111111111
002 | 111111112
003 | 111111113
004 | 111111114
005 | 111111115
006 | 111111116
007 | 111111117
008 | 111111118
009 | 111111119
010 | 111111121
... (truncated - too many lines)
Full output: too long to upload
!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!')]))
: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
@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
||
i'm working on it as well, good stuff
i wonder what to name it
for now types_intersection
typing.Intersection, if it was in the standard lib
🤔
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
Nah, I just mean if it was in the standard lib
its an interesting idea to do that though
This has been discussed a long time ago, apparently static typing people don't care about this
class typing:
class Intersection:
...
Hehe
lol
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. 😈
Yes it could, look up pth files
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...
You could, you can name it whatever
2 classes with the same name?
they would overwrite each other
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.
true i guess
but i think its nicer if it's useable as a anme
even if i'm not gonna do that
It won't be, and why? list[int] is also not available as a name.
oh
so maybe, what about creating it without a name
like ""
can u do that in meta classes?
Sure. But then it won't look nice
🤔
'list[int]'
'int | tuple'
what about
'int & tuple'
alright lets see
||
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]
||
thats cool not gonna lie
about to finish writing my code
i remember guido posting once about intersection
apparently what wasn't possible in the past is possible today
Hmm, do you need assist in number golfing?
BRO WHAT
wait. i can read this
dudeee that's even scarier
why can i read that?
But you cannot evaluate code that needs external input on a bot
💀
If you want to play it, play it locally
would be cool if it waited for messages to input
It wouldn't happen by the nature of the design of snekbox, and do not ping me, thank you
my fault 🤝
!e #internals-and-peps message
import os, sys
os.close(sys.stdin.fileno())
f = open(__file__, "r")
print(input())
:white_check_mark: Your 3.12 eval job has completed with return code 0.
import os, sys
!e shorter and less variables used
import os
os.close(0)
os = open(__file__, "r")
print(input())
:white_check_mark: Your 3.12 eval job has completed with return code 0.
import os
!d os.close
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.
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
not in a function, no
it modifies locals() but it doesn't modify the actual variable
modifying local variables is complicated
(might be fixed in 3.14, no one knows)
i wonder if it is already fixed in python4
fwiw it's literally shorter to just unroll the loop
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+'""')
insane
does this work
T=lambda n,s="|_ ":s[n%3]+s[n//3%3]+s[n//3//3%3]
48b then
//3//3 -> //9
also cereal was right
redemption arc
i thought about that but i dont know if theres some edge case with a double round-down vs a single round-down
i dont think so but im not sure
not too far off from what i concluded :p
t='|_ ';ternary=lambda n:t[n%3]+t[n//3%3]+t[n//9%3]
T=lambda n,s="|_ "*9:s[n]+s[n//3]+s[n//9]
ah yes.
same length then :3
t='|_ ';T=lambda n:t[n%3]+t[n//3%3]+t[n//9%3]
T=lambda n,s="|_ ":s[n%3]+s[n//3%3]+s[n//9%3]
ooh
fails if n is big enough, doesn't it
yeah
make better testcases then
actually what are your test cases
what specific test-cases do you have though
like what problem am I solving?
this is a helper for https://code.golf/seven-segment#python
no
like what specifically are your test cases
like do you just check if it equals the correct result for all the thingies?
i think "whole program works" is the test case
for T?
yes
i want test-cases to test against
so i know what behaviour im allowed to drop and needs to be kept
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
41b -> 33b, passes all the test-cases
T=type('',(str,),{"__eq__":bool})
:3
bah humbug
33b -> 32b ..."__eq__":int...
huh
https://docs.python.org/3/reference/datamodel.html#object.__eq__
By convention, False and True are returned for a successful comparison. However, these methods can return any value.
i guess i was misremembering
i was probably thinking of __len__ or __index__ or one of those things thats required to return an int
myaaaaaaa why is this alowld T^T
¯_(ツ)_/¯
>>> T() == False
False
that works i think
shhhh
T=lambda n:" || | ____ | | ||"[n%100%19%7::7] is a funny solution but not any shorter
even where on some platforms null addresses are perfectly valid places to put objects
though cpython hasnt been ported to any of those that i know of
anyone can shed a light on this https://discord.com/channels/267624335836053506/1265328856844468275 ?
what is this
Can the interpreter execute that?
no but you are about to get scared
!epy def main() -> { print('Hello, world!') }: return ;{ }
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, world!
!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}
""")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hello, World!
the function doesn't print anything
just defining it
Dawg wtf
def main () -> { print("hello world") }:
return; {}
That’s not even Python, why did it work?
it is python
this the same thing but with better whitespace
the annotation is {None}
which is what print returns
My brain is not braining
I’m not even sure what the curly braces do anymore
They’re used like everywhere in Python
Curly braces are used for dictionaries
And sets
And .formats
And fstrings
What do curly braces even mean anymore
... which is not relevant to how i mentally categorise them
hence the above lol
Python syntax is still less annoying than JavaScript somehow
> *lists meanings of curly braces*
> what do curly braces mean?
I get really confused every time I see a curly bracket in Python
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
yes it does print
just go and try it yourself
can u write this better:
all(any(issubclass(b_cell, a_cell) for b_cell in b) for a_cell in a)
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
the function does not print anything
only defining the function prints something
have you tried running it yourself?
have you?
yes
it wasn't even about calling main?
then why are you arguing when i say the function doesnt print
lmao
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
I forgot the quirky way I used before for that
😭
def main(): {
print('Hello, world!') };
return ;{
}
main()
vs
def main() -> {
print('Hello, world!') }:
return ;{
}
main()
the first one is invalid
right here.
that it's invalid is the point im making
and I put a note on it
I can't remember the way to include return in it
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!
my point is including return in it
oh okay
>>> def main(x) {x*=2;return x}
>>> main(5)
10
included return :p
100% python 4
you finally included braces in your python?
well yes you said that you have tried before but its hard
a while ago
the one i sent includes return??
???
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
just put the print in the function
??
def main() -> { }:
print('Hello, world!')
return ;{
}
main()
braces wont align because now im on mobile so i cant see that, but it works
¯_(ツ)_/¯
hi what is this
.
not cooking