#esoteric-python

1 messages · Page 138 of 1

severe canyon
#

it just terminates after 1 iteration, i need the number of iterations before the condition is met

grave rover
#

oh I see

severe canyon
#

also i wanna avoid some recursion if possible

#

else you cant get more than 1000 iterations without raising the recursion limit

grave rover
#

well yeah that's why I didn't use recursion :)

#

recursion could probably make it shorter but be a pain in the ass

#

wait can't you just do open('o.ppm','w').write(f'P2\n{h} {w}\n{m}\n'+'\n'.join(str(r((x%w)/w*2.67-2.1+(x//h)/h*2.5j-1.25j))for x in range(w*h)]) for the last line

severe canyon
#

yes, indeed i can

#

i can also move the lambda function to that line, for -2 chars, but im not too worried about that

#

found out i can replace: z.real**2+z.imag**2<=4 with abs(z)<=2

#

:D

#

because apparently, taking the absolute value of a complex number, is like doing pythagoras

#

Also gave a massive speedup

sick hound
#

@severe canyon

severe canyon
#

?

unborn charm
#

uesy

#

988uiui

sleek sphinx
severe canyon
#
w,h,m=256,256,64
open('o.ppm','w').write(f'P2\n{w} {h}\n{m}\n'+' '.join(str(len((z:=0j)or[(z:=z*z+x%w/w*2.67-2.1+x//w/h*2.5j-1.25j)for _ in[0]*m if abs(z)<=2]))for x in range(w*h)))

got it down to 181

unique rose
#

you could do: open(str(w:=256)+'.ppm', 'w') and just use a w variable, and replace m with 64

#

or m with w ** .75

#

open(str(w:=256) + '.ppm','w').write(f'P2\n{w} {w}\n64\n'+' '.join(str(len((z:=0j)or[(z:=z*z+x%w/w*2.67-2.1+x//w/w*2.5j-1.25j)for _ in[0]*64 if abs(z)<=2]))for x in range(w*w)))

is 174 chars

severe canyon
#

i kinda want to have both image dimensions available

unique rose
#

i was thinking you could just record powers of 2, but i dont think that serves any use

#

you could make w both the width and height, using the decimal part as the height

severe canyon
#

width and height can be any number

unique rose
#

w//100, w//1000 etc

severe canyon
#

but they dont have to be the same

unique rose
#

depends what the game is -- lots of ideas, not many which actually shrink char count

severe canyon
#

i guess

fleet bridge
#

!e

X=(T:=type)('',(T,),{'__init__':lambda x,*_:x.__setattr__(x,'__class__',x)},)('X',(T,),{},)

assert X is X.__class__ is type(X) and X.__name__ == 'X'
night quarryBOT
#

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

[No output]
fleet bridge
#

!e

class X:
    pass

class Y:
    __class__ = X

print(f'{Y().__class__ = }')
print(f'{type(Y()) = }')
night quarryBOT
#

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

001 | Y().__class__ = <class '__main__.X'>
002 | type(Y()) = <class '__main__.Y'>
fleet bridge
#

weird

#

!e

X=(T:=type)('',(T,),{'__init__':lambda x,*_:x.__setattr__(x,'__class__',x)},)('X',(T,),{'__new__':lambda x,*_:x,'__init__':lambda *_:None},)

assert X() is X is X.__class__ is type(X) and X.__name__ == 'X'
print('OK')
night quarryBOT
#

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

OK
severe canyon
#
w,h,m=1024,1024,64
open('o.ppm','w').write(f'P3\n{w} {h}\n255\n'+'\n'.join(['122 108',f'{len((z:=0j)or[(z:=z*z+x%w/w*2.67-2.1+x//w/h*2.5j-1.25j)for _ in[0]*m if abs(z)<=2])*62%255} 173'][(abs(z)>2)]+' 227'for x in range(w*h))+'\n')

with colors ¯_(ツ)_/¯

#

@bright eagle

fleet bridge
#

it isnt circle 🧐

severe canyon
#

ranges from top to bottom arent exactly the same

#

the mandelbrot set ranges from -2 .. 0.47 , -1.12i .. 1.12i

#

and im plotting: -2.1 .. 0.57 , -1.25i .. 1.25i

severe canyon
#

@bright eagle final one:
julia sets this time:

s,m=2048,128;c=.285+.01j  
open('o.ppm','w').write(f'P2\n{s} {s}\n{m}\n{" ".join([z:=x%s/s*(R:=(4*abs(c)+1)**.5+1)-R/2+x//s/s*R*1j-R/2*1j,str(len([(z:=z*z+c)for _ in[0]*m if abs(z)<=R]))][1]for x in range(s*s))}')
bright eagle
#

Neato!

patent heron
#

!e


t,\
    s,r,C,E,      =tuple,\
   set, range,   "*"," ";f=r\
 (31);p=( t(s(r(4,12))|s(r(18,
26))),t(s(r(3,14))|s(r(17,28))),
t(s(r(1,15))|s(r(16,30))),f,f,f,
r(1,30),r(3,28),r(5,26),r(7,24),
 r(9,22),r(11,20),r(13,18),(15
   ,));print(*[(e:="").join(
     [(C if j in p[i] else
       E)for j in f] ) +
         "\n" for i in
           r(14) ] ,
             sep=e
               )
night quarryBOT
#

@patent heron :white_check_mark: Your eval job has completed with return code 0.

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

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

patent heron
#

:)

severe canyon
#

<3

#

coooooool!!!!

patent heron
#

That took a lot longer than I thought

#

and I do kinda have to cheat at the start but it is python after all

severe canyon
#

worth <3

patent heron
night quarryBOT
#
Bad argument

Converting to "int" failed for parameter "pep_number".

patent heron
#

still slightly off center

#

!e ```py

t,
s,r,C,E, =tuple,
set, range, ""," ";f=r
(31);p=( t(s(r(5,13))|s(r(18,
26))),t(s(r(3,14))|s(r(17,28))),
t(s(r(1,15))|s(r(16,30))),f,f,f,
r(1,30),r(3,28),r(5,26),r(7,24),
r(9,22),r(11,20),r(13,18),(15
,));print(
[(e:="").join(
[(C if j in p[i] else
E)for j in f] ) +
"\n" for i in
r(14) ] ,
sep=e
)

night quarryBOT
#

@patent heron :white_check_mark: Your eval job has completed with return code 0.

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

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

patent heron
#

Now it's symmetrical

severe canyon
#

:O

patent heron
#

kinda want the top line to be a bit smaller but that is like impossible to reflect in the code

#

It's fine

severe canyon
#

:( i still think its beautiful

grave rover
severe canyon
#

on my small discord window hehe 😁

patent heron
#

rip

severe canyon
#

time to go wiiiide

grave rover
#

but hey at least my heart() function takes a target size

#

I could probably make it work if I un-golf it

#

that said I can't believe it's almost 3 years since I made that code

thorny tapir
#

is that like that one donut shaped code

#

!e

print("#####")
print("#####")
print("#####")
print("#####")

I can make rectangle shaped code that prints rectangle B)

night quarryBOT
#

@thorny tapir :white_check_mark: Your eval job has completed with return code 0.

001 | #####
002 | #####
003 | #####
004 | #####
restive void
patent heron
#

Thats cool

radiant shale
#

Hi, when I use this code (I'm using PyQt5)

widget.resize(496, 600)
self.line.move(-10, 540)

The line isn't showing when it is in a part of window which was resized, anyone know how to fix that?

severe canyon
#

@patent heron

class v:
 def __init__(s,x=0,y=0,z=0): s.x,s.y,s.z=x,y,z
v.__str__=lambda s:f'{s.x},{s.y},{s.z}' #print values
v.__add__=lambda s,r:v(s.x+r.x,s.y+r.y,s.z+r.z) #addition
v.__mul__=lambda s,r:v(s.x*r,s.y*r,s.z*r) #scaling
v.__mod__=lambda s,r:s.x*r.x+s.y*r.y+s.z*r.z #dot-product
v.__xor__=lambda s,r:v(s.y*r.z-s.z*r.y,s.z*r.x-s.x*r.z,s.x*r.y-s.y*r.x) #cross-product
v.__invert__=lambda s:s*(1/(s%s)**0.5) #normalize

🤔

patent heron
#

nice

severe canyon
#

not nice xD its so ugly

patent heron
#

I mean, yea

unique rose
#

perhaps a small tidy,

!e ```py

class v:
init = lambda s, kw: s.dict.update(kw)
getitem = lambda s, i: s.dict[i]
iter = lambda s: iter(s.dict.items())
str = repr = lambda s: str(dict(s))
add=lambda s,r: v(
{k:v + r[k] for k,v in s})
mul=lambda s,r: v({k:v * r for k,v in s})
matmul=lambda s,r: sum(v * r[k] for k,v in s)
invert=lambda s: s * ((s@s)
-0.5)

v(x=10, y=20) @ v(x=5, y=16)

rich hound
#

Fixed, you forgot a [k]

unique rose
#

whereabouts?

rich hound
#

__mul__

#

@unique rose ^^

unique rose
#

yeah, it's correct -- 3 * v(...)

#

but it does highlight that v... * v... fails

rich hound
#

ah

#

my mistake then ^^

unique rose
#

!e```py
class v:
init = lambda s, *ps, kw: s.dict.update(kw or zip('xyz', ps))
getitem = lambda s, i: s.dict[i]
iter = lambda s: iter(s.dict.items())
str = repr = lambda s: str(dict(s))
add=lambda s,r: v(
{k:v + r[k] for k,v in s})
_cmul = lambda s,r: v({k: v * r[k] for k,v in s})
_smul = lambda s,r: v(
{k: v * r for k,v in s})
mul = lambda s,r: [v._smul, v._cmul][isinstance(r, v)](s, r)
matmul=lambda s,r: sum(v * r[k] for k,v in s)
invert=lambda s: s * ((s@s)**(-1/len(s)))
len=lambda s: len(s.dict.values())

print( v(2, 2) + v(3, 4))
print( v(2, 2) * 3 )
print( v(2, 2) * v(3,4) )
print( ~v(x=2, y=2) )
print( v(x=10, y=10) @ ~v(x=10, y=10) )

rich hound
#

:0

severe canyon
#

Nice!

#

Although, it's a little too much for what I need

earnest wing
#

could go the shader language route and make a heckload of overloads and definitions for vec2, vec3, ..., vecn

unique rose
earnest wing
#

yeah

sick hound
#

I'm gonna reverse engineer that heart thats cool

#

its so cool!

thorny tapir
floral meteor
#

I could probably print a heart in python, but Java style of code writing

#

!e ```py
void=None;
class System:
out=type("stdout",(),{'println':print})();
class Main:
def main(argv) -> void: {
System.out.println(" *** *** "),
System.out.println(" ***** ***** "),
System.out.println("
**************"),
System.out.println(" ************** "),
System.out.println(" ********** "),
System.out.println(" ****** "),
System.out.println(" ** ")
}
name=='main'==Main.main(
import('sys').argv)

night quarryBOT
#

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

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

!e Now that yall have been tortured here's the pythonic way

print("""    ***    ***   
   *****  *****  
 ****************
  ************** 
    **********   
      ******     
        **""")
night quarryBOT
#

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

001 |     ***    ***   
002 |    *****  *****  
003 |  ****************
004 |   ************** 
005 |     **********   
006 |       ******     
007 |         **
thorny tapir
floral meteor
#

Because I snuck a comma in at the end

sick hound
#

wait a sec

dense nova
#

wait

#

python != java

#

tf

sick hound
#

I realized that you could like split the heart in half and like oh okay

restive void
#

!e

(        "hi",i:=
     __file__,C:=chr,
     s:=open(i,"rt").
   read(),sc:=s.count(C
   (10)),sn:=sc+s.count
   (C(32)),a:=len(s)-sn
   ,print("π","is",":",
     .5*a/((.5*sc)**2
     )),"#eso- teric"
         ,"pthn") 
night quarryBOT
#

@restive void :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | NameError: name '__file__' is not defined. Did you mean: '__name__'?
restive void
#

Un-golf for higher precision

vague cairn
coarse shuttle
#

print(8)

floral meteor
#

I have a structure for an object oriented code for a grid game (e.g. minesweeper, sudoku, 2048) run in python

class Cell: # contains a value
  ...

class Engine: # contains a matrix
  ...

class Interface: # contains an event loop
  ...
#

I try to black-box Engine with Interface, so as multiple options are available, i.e. gui or cli or AI solution

#

but I'm not always successful at implementing black box

prisma coral
severe canyon
#

'where beautiful software goes to die'
sadge

prisma coral
#

things can be masterpieces without being beautiful 🤷

severe canyon
#

spirits lifted

severe canyon
#

is a raytracer in 1200 chars impressive?

vestal solstice
#

doesn't sound impressive

earnest wing
severe canyon
#

o fancy role

sick hound
#

hi

last locust
#

@sick hound let's keep this channel on topic please, it's not the please to be dumping yt videos

#

And given this is an English speaking discord server this probably isn't the right server

sick hound
#

excuse me I do not understand English well and I understood that esoteric I am only looking to expand my community on twiter

last locust
#

We don't allow advertisement here. I recommend you read our #rules before continuing

#

Although if you can't speak English, then I'm afraid this isn't the server for you

maiden vine
#

Well my dudes!

#

There's obviously a lot of infrastructure I'm not showing here, but

#

I think I've managed to implement private attributes in Python XD

#
    def getCallingPrototype(self) -> Prototype:
        """retrieve the class which owns the scope, if the scope is indeed owned at all"""
        
        callingFrame = inspect.currentframe()
        callingCode  = getattr(callingFrame, 'f_code')

        while callingCode.co_flags & inspect.CO_NESTED:
            # climb the stack up to the first not-nested frame

            callingFrame = callingFrame.f_back
            callingCode  = getattr(callingFrame, 'f_code')


        # get every object which refers to the code object in question, then
        # filter out any objects which are not functions
        callingFunctions = gc.get_referrers(callingCode)
        callingFunctions = filter(inspect.isfunction, callingFunctions)
        callingFunctions = tuple(callingFunctions)


        if len(callingFunctions) > 1: # the code object has been used to manufacture more
                                      # then one function — throw an error
                                      #
                                      # NOTE: in theory, one could check ALL of these
                                      #       for privacy authorization

            error =  f"cannot access {self.privacy} member '{self.name}' of positronic "
            error += f"object with type '{instance.classname}' from within "
            error += f"recycled code object"

            raise AssertionError(error)

        if len(callingFunctions) < 1: # the code object is not attached to any function
                                      # (likely compiled manually) as is therefore
                                      # not authorized

            error =  f"cannot access {self.privacy} member '{self.name}' of positronic "
            error += f"object with type '{instance.classname}' from within "
            error += f"orphaned code object"

            raise AssertionError(error)


        # from the computed function, get its decorator (set as one of its attributes) and
        # from that, get the class the decorator is embedded on
        callingFunction  = operator.getitem(callingFunctions, 0)
        callingDecorator = getattr(callingFunction,  'decorator', None)
        callingPrototype = getattr(callingDecorator, 'prototype', None)

        # return the computed class
        return callingPrototype
#

Here is a snippet, the algorithm for finding which class owns a scope

floral meteor
#

"positronic"

#

Your variables are more than one word each

#

My variables are usually single letter

maiden vine
#

Its still very raw, I'll admit. I just wanted to get you guys' opinion on the approach TBH

#

Its the first half-sane means of determining the owner of a scope I've seen

#

But I'm sure there are edge cases I'm not thinking of. One improvement I've made already is that I've attached the code object directly to the decorator. For context, this is part of a group of classes that all work together — in this case, private variables are only eligible for access within code blocks decorated by a custom decorator. I realized I can just attach the code block as an attribute directly to the decorator and as such, I don't need to filter referents twice. I can directly detect any of my decorators which reference the code block in question

#

And that seems sane enough. Look at the current frame's code block, find any custom decorators which reference it, and whatever class that decorator is attached to (if any) is the owner of the code block

earnest wing
#

How does this respond to object.__getattribute__(x, "blah")?

fading lion
#

!e
import numpy as np

data = [i for i in np.arange(1,7)]
hori = vert = np.array(data)
arr = np.array([hori, vert])

def sample(n):
samp = []
for i in range(1,n+1):
for j in range(1,n+1):
num = (i,j)
samp.append(num)
return samp

sample = sample(6)
samp = np.array(sample)
print(samp)

night quarryBOT
#

@fading lion :white_check_mark: Your eval job has completed with return code 0.

001 | [[1 1]
002 |  [1 2]
003 |  [1 3]
004 |  [1 4]
005 |  [1 5]
006 |  [1 6]
007 |  [2 1]
008 |  [2 2]
009 |  [2 3]
010 |  [2 4]
011 |  [2 5]
... (truncated - too many lines)

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

fading lion
#

!p
import numpy as np

data = [i for i in np.arange(1,7)]
hori = vert = np.array(data)
arr = np.array([hori, vert])

def sample(n):
samp = []
for i in range(1,n+1):
for j in range(1,n+1):
num = (i,j)
samp.append(num)
return samp

sample = sample(6)
samp = np.array(sample)
print(samp)

night quarryBOT
#
Bad argument

Converting to "int" failed for parameter "pep_number".

fleet bridge
#

!e

from pprint import pprint

def is_constructible(cls: type) -> bool:
    try:
        cls()
    except TypeError as exc:
        s = exc.args[0]
        if not isinstance(s, str):
            return True
        if 'cannot create ' not in s:
            return True
        if ' instances' not in s:
            return True
        return False
    except:
        return True
    else:
        return True

x = [c for c in object.__subclasses__()[:100] if not is_constructible(c)]
x = sorted(x, key=lambda c: c.__name__[::-1])
pprint(x)

list of classes which raises TypeError: cannot create '<classname>' instances when called

night quarryBOT
#

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

001 | [<class 'Token.MISSING'>,
002 |  <class 'async_generator_asend'>,
003 |  <class 'builtin_function_or_method'>,
004 |  <class 'hamt_collision_node'>,
005 |  <class 'hamt_bitmap_node'>,
006 |  <class 'hamt_array_node'>,
007 |  <class 'anext_awaitable'>,
008 |  <class 'PyCapsule'>,
009 |  <class 'frame'>,
010 |  <class 'coroutine'>,
011 |  <class 'types.UnionType'>,
... (truncated - too many lines)

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

floral meteor
#

It would be fun to make a net-oriented programming framework in python,

#

it'd be like neurons in a brain

#

possibly even turing complete

#

As long as you specified input nodes, output nodes, and a way to store memory

#

but you might be able to make memory with a logic loop

#

It would really just be an object that stores either 1 or 0 each clock cycle, and makes its next decision based on what's input to its "dendrites"

#

maybe even a glorified search algorithm

#

It would certainly be very esoteric to make programs with

severe canyon
#

so... like a neural network?

maiden vine
severe canyon
#

hehe

marsh void
#

what's the hamt_name_node thingy?

rugged sparrow
#

its part of from _testcapi import hamt

#

!e py from _testcapi import hamt a = hamt() b = a.set('x', 1) c = b.set('y', 1) print(*a.items()) print(*b.items()) print(*c.items())

night quarryBOT
#

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

001 | 
002 | ('x', 1)
003 | ('x', 1) ('y', 1)
rugged sparrow
rugged sparrow
#

i believe it was part of pep 567

#

!pep 567

night quarryBOT
#
**PEP 567 - Context Variables**
Status

Final

Python-Version

3.7

Created

12-Dec-2017

Type

Standards Track

sick hound
#

!e

for n in range(2, 100): print(n, end=', ') if len([d for d in range(2, n) if n % d == 0]) == 0 else print(end='')
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 
sick hound
#

One-liner that generates primes. Not the best, but it works.

night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
restive void
#

!e

print([n for n in range(2,100)if not __import__("re").match(r'^1?$|^(11+)\1+$','1'*n)])
night quarryBOT
#

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

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
restive void
#

cursed version

ornate mist
#

a little challenge in this genre is to make a one-liner that prints a list of length n that contains the integers

[1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100,200,300,400,500 ...]
fleet bridge
#

!e

n = 37
print([((i-1)%9+1)*10**((i-1)//9) for i in range(1,n+1)])
night quarryBOT
#

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

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]
restive void
#

!e

print([n for i,n in zip(range(37),(n for n in __import__("itertools").count()if len(str(n).strip("0"))==1))])
night quarryBOT
#

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

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]
dense nova
#

imagine my confusion when i first joined this server and read 'Topical Chat/Help' as 'Tropical Chat/Help', the fact that theres a palm tree next to the channel name didn't help either.

I just found out its 'Topical Chat/Help' by the survey and I've been in this server for like a month.

earnest wing
#

fantastic

severe canyon
#

I feel like there should be a tropical chat anyway

#

🌴

severe canyon
#

!e

print([(i%9+1)*10**(i//9)for i in range(37)])
night quarryBOT
#

@severe canyon :white_check_mark: Your eval job has completed with return code 0.

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]
severe canyon
fleet bridge
#

ty

torn grotto
#

!e
print("test")

rugged sparrow
#

!e ```py
def make_locals():
import sys
to_update = {}
def locals():
frame = sys._getframe(1)
return to_update.setdefault(frame, {**frame.f_locals})

def tracefunc(frame, what, arg):
    if frame in to_update:
        for key in frame.f_locals.copy():
            if key not in to_update[frame]:
                del frame.f_locals[key]
        for key, val in to_update[frame].items():
            if key not in frame.f_locals or frame.f_locals[key] != val:
                frame.f_locals[key] = val
        del to_update[frame]
    return tracefunc
sys.settrace(tracefunc)
return locals

builtins.locals = make_locals()

def foo():
locals()['abc'] = 'New Value'
print(abc)
abc = None # forces abc to be a local

foo()```

night quarryBOT
#

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

New Value
rugged sparrow
#

makes writing to the locals() dict actually stick using sys.settrace

#

not quite as good as my ctypes version, as the variables arent written until before the next line instead of immediatly

floral meteor
#

Beautiful

#

Now I can throw this in a file in python path and import mutable_locals to get locals that work like globals.
Now you just gotta figure out how to make local annotations work XD

ornate mist
#

this just makes me feel uncomfortable XD

radiant cloak
torn grotto
#

!e
print("test")

night quarryBOT
#

@torn grotto :white_check_mark: Your eval job has completed with return code 0.

test
floral meteor
#

debugger tools: I don't have bugs in the first place. I'm too good at programming :P
CPython: why would I use any other version of python?

#

I jest of course, but I still think that doesn't warrant a number as low as 8

rugged sparrow
floral meteor
#

I think ok boomer would have sufficed.

fiery hare
#

#bot-commands is a place we all can go.

floral meteor
#

I think !e print("test") is a daily occurrence in this channel.

#

and there's nothing we can do about it

#

except program the bot to detect that exact message content in this channel

#

since there's rarely any deviation and they don't use backticks

#

I could find it eventually, but where's the link to do that?

#

and what would be an appropriate action, just delete and warn?

#

it seems !source gets me where I want to go

#

so I'll call it esoteric python print("test") prevention

#

I'll do it a little later though

vague cairn
#

Sometimes I love the errors you get when you muck around with ctypes on slot classes...

    getattr(cls, attr)(item)
TypeError: descriptor '__iter__' requires a 'dict' object but received a 'dict'
prisma coral
#

lol

floral meteor
#

XD

ornate mist
#

those people who can't make the difference between dict and dict smh my head

severe canyon
#

must have been an english and a german dictionary

maiden vine
#

How does one fool type(something)?

#

As best I can tell, if I implement an __instance_check__ and __subclass_check__, as well as somehow disguise its __mro__ and __class__ attributes then class A can effectively be disguised as class B. Are there any edge cases I'm missing?

astral rover
#

why do you want to do this?

shut trail
#

i think you can make a metaclass that implements instance_check right?

maiden vine
shut trail
#

!e

class MyMeta(type):
  def __instancecheck__(self, other):
    print(other)
    pass

class Test(metaclass=MyMeta): ...

isinstance(2, Test)
maiden vine
#

But its Python. Its very resistant to introspection manipulation like this XD I just want a full solution

night quarryBOT
#

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

2
shut trail
#

ah

astral rover
maiden vine
#

Hmmmm

astral rover
#

hence the question of why are you doing this, do you actually plan on having people use this?

maiden vine
#

Nah

#

I'm doing some work with metaclasses in general, and so I'm sorta in that zone

#

But I'm on break, so, I'm feeling a bit experimental

#

Just thought I'd take a look

earnest wing
#

!e

@type
@type.__call__
@type
@type.__call__
class C: pass
print(C)
night quarryBOT
#

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

<class '__main__.C'>
desert flame
#

h

languid hare
#

interesting discrepency:

__builtins__ = {}
print(__builtins__)

running the above as a python file results in {}
running with IDLE or a REPL results in NameError: name 'print' is not defined

#

anyone might have an idea why this happens

restive void
#

Because the two lines are compiled together when run as a file, but one by one when run from a REPL. You can also make it work in a REPL if you somehow put them in one compilation step:

class block:
    def __enter__(*whatever): pass
    def __exit__(*whatever): pass

with block():
    __builtins__ = {}
    print(__builtins__)

works in the REPL, but afterwards the builtins are gone.

#

Like print is in the co_names of the compiled module before any deletion happens. This is of course just a string, but I imagine that's how that happens.

If you replace print(__builtins__) with exec("print(__builtins__)") it stops working, in my example.

languid hare
#

hmm interesting

#

what about the reverse

#

what if I wanted behaviour similar to in idle

restive void
#

exec("print(...)") should always fail, also in a file

#

(Unless print is used already, I guess)

sick hound
#

is this channel for script help?

dark wharf
#

if you ask for help here your code will emerge a hideous abomination of its former self

prisma coral
dark wharf
prisma coral
#

!e This is kinda satisfying:

__import__("fishhook").hook(console := type, "log")(print)

console.log("woohoo")
night quarryBOT
#

@prisma coral :white_check_mark: Your eval job has completed with return code 0.

woohoo
fleet bridge
#

!e

__import__("fishhook").hook(type, "log")(print)

int.log("woohoo")
night quarryBOT
#

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

woohoo
fleet bridge
#

😄

#

!e

from fishhook import hook
hook(object, 'fizz')(lambda *args: print('bazz'))
1 .fizz()
[].fizz()
{}.fizz()
None.fizz()
....fizz()
....fizz().fizz()
night quarryBOT
#

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

001 | bazz
002 | bazz
003 | bazz
004 | bazz
005 | bazz
006 | bazz
007 | bazz
rugged sparrow
#

!e ```py
import sys, dis

def trace(tf):
def wp(f):
def inner(*a, **k):
try:
sys.settrace(tf)
return f(*a, **k)
finally:
sys.settrace(None)
return inner
return wp

def jump_trace(frame, line, arg):
frame.f_trace_opcodes = True
if line == 'opcode':
idx = frame.f_lasti
op, arg = frame.f_code.co_code[idx: idx + 2]
if dis.opname[op] in ['LOAD_GLOBAL', 'LOAD_NAME']:
sarg = frame.f_code.co_names[arg]
if isinstance(sarg, str) and sarg.startswith('JUMP_'):
, d, n = sarg.split('')
try:
mvs = {
'UP': frame.f_lineno - int(n),
'DOWN': frame.f_lineno + int(n),
'TO': int(n)
}
frame.f_lineno = mvs.get(d, frame.f_lineno)
return
except:
pass
return jump_trace

@trace(jump_trace)
def foo():
x = 0
print(x)
x += 1
if x > 10:
return
JUMP_UP_4

foo()

night quarryBOT
#

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

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

It's not at versatile as my opcode replacement version but it works

winged barn
#

!e

night quarryBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

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

winged barn
#

noobie question ... can i post code here and get a question answered?

astral rover
winged barn
#

@astral rover thanks

fleet bridge
#

!e

def f():
    print('before change #1')
    f.__code__ = f.__code__.replace(co_consts=new_consts)
    print('before change #2')


new_consts = (None, 'after change #1', ('co_consts',), 'after change #2')
print(f.__code__.co_consts)
f()
print(f.__code__.co_consts)
f()

night quarryBOT
#

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

001 | (None, 'before change #1', ('co_consts',), 'before change #2')
002 | before change #1
003 | before change #2
004 | (None, 'after change #1', ('co_consts',), 'after change #2')
005 | after change #1
006 | after change #2
grand tree
#

!e

arr = []
class test:
  @classmethod
  def retinst():
    return self
for k in range(10):
  arr.append(test.retinst)
for it in range(len(arr)):
  print(it)
night quarryBOT
#

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

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
novel meadow
#

I was told to try asking here instead by Mustafa
Someone sent this in another server

import ctypes, inspect, gc
def main():
    frame = not print("trolled with voidpointer haha") and inspect.currentframe()
    ctypes.cast(ctypes.c_void_p(int([referer for referer in gc.get_referrers(frame.f_code) if getattr(referer, "__code__", None) is frame.f_code and set(inspect.getclosurevars(referer).nonlocals.items()) <= set(frame.f_locals.items())][0].__repr__()[-15:][:-1], 16)), ctypes.py_object).value.__call__()
main()

which just repeatedly prints the print line

What in the accursed world is this?

grand tree
#

why

#

i was just messing aroudn, didnt wanna create a file

rugged sparrow
#

Use a trace function to change the line number

sick hound
#

whats code gore?

next flame
terse mortar
#

I get a lot of esoteric code is useless, but this is literally just ```py
for i in range(10):
nums.append(i)

for i_2 in len(nums):
print(i_2)

night quarryBOT
#

Hey @inland crystal!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

inland crystal
#

!codeblocks

night quarryBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

grand tree
eager sphinx
#

!e

from math import *
r=range
itc= (10,129297,128530,128542,32,33,128545,128548,128038,40,41,128683,44,128555,46,127790,128560,128575,63,65,66,127939,128580,69,68,*r(71,81),83,84,127829,85,89,127837,97,98,128483,100,101,103,104,105,*r(107,113),114,115,116,117,119,121)
def decode(e,b=1<<3):
    l=ceil(floor((log2(e))+1) / b)
    return"".join(map(lambda v:chr(itc[v]),reversed((*map(lambda i:(n:=e>>((l-i-1)*b))-(n>>b<<b)-1,r(l)),))))
print(decode(3244649123016202304891620531740982762891576544349418611903359070093996148368271375664004833158782419693562368836100015717309746308332940478214165459771461696755758941698312170665438354835055834831744615294239453342422211676208604486492899923465219708682188660541207378354834529120737764067488908516785255937372371826538196424288440513734017759507973354255076505610764439310038685057105380756911991480116903918691598975498051255492241347215219269210770330616723537702123696223194741388965316956049794151445622869939476096941182589287463344214230469776438876833152703640187393087978507269978387253970430932734015582132700799781747041561406164252203015589507175416946093177848124798931251421662043923210397855460937219260958556753825036738197210775503124127439473622168605484957252044318980335590468794557627590658425490077211094575885174664166519538163711538014654477691416995561377842095391962921377395420086534902478441806398390468998664407161668998259836607346093060894177235495713257626700960105270542207746133468723296932517388083783230442828998535786514706960160148499916637788255417695785324346500982590476571292941003412146388465011509827394655562950181687950396815699310393422661751300725350352875585493140797753767221528333636979638462863703881880397526185202577677344133834472196407668967934862043413785868761398687053999727462972065072563600212346884760118092965616800572377416888571625464970966174085783681256507818947953372411031341568724531967057894693591683032679322585434294326037397807531219870135510123849601,b=6))
night quarryBOT
#

@eager sphinx :white_check_mark: Your eval job has completed with return code 0.

001 | 
002 | Kala mo di masakit 😫 yung pinagsasabi mo sakin??? 🗣🗣🗣Na patay gutom akohh??? 😤😤😤Bakit?Hindi bayon masakit? 😞😡😡E ikaw nga hinuhuli mo kalapati e.🐦🐦🐦Sabi niya tara Joela ku,hulihin natin yung kalapati 🏃🐦kuhain natin 🚫🚫🚫(MASAMA YON)Oh siya yun,siya yung pagsabihan mo😫🤑😤😡.Siya pa naninisi😿,hati nga kami sa pagkain🍝🌮🍕,hindi naman siya ang bumili🏃.Hindi niya nalang hingiin😡😡😡para hindi ma...🤑🤑🤑O,wag mo na siyang anohin 😡😡😡!!!wag mo na siyang anohin(HULI TAYONG KALAPATI🐦)Bakittt??!!! 😫😡😤Nakikisali ka dito kahit di ka naman kasali.O bakit? 😒🙄🙄Bat mo inaano pinsan ko 😤😡.Iiyak na nga diba😰😰😰,tapos yun na nga,wag mo ng anuhin 😡😡😡.Iiyak na nga eyeyeyye.O bakit??? 🙄🙄🙄O bakit din??!!! 🙄😒😒😒Umalis kana 🗣🗣🗣Aalis ako di naman ako dito eh.😒😒🙄🙄.Bb ka pala eh😒😡Bakit ka nag sasabing bb??? 🙄😤😤Bat ka namamangga??😰😫😿OYY DONDUNGGN INGAY INGAY NIYO!!!HOY🗣🗣🗣.
eager sphinx
#

this is so satisfying

#

the original encoded number was 4,000 chars long i couldn't fit it in a discord message

#

i had to do this crap to compress it to 2,000

#

"you think it doesn't hurt, what you were saying about me? that i was eating a ton? why? is it not hurtful? ..." etc. etc.

#

it's funnier in tagalog

hot hazel
#

dont know a single code
im alone
not catched up with anything

sick hound
#
b = lambda __92_ : [[__92_ for n in range(2**63)]]==[[__92_ for n in range(2**63)]]
_____ = [(___-8)*-b("Eror 404")
 for 
  ___ in range(
      len(f"+{'_'*2}"))]
s = sum(_____)//(b(9223372036854775808)+b("""Letting the days go by, let the water hold me down"""))
print(_____)

mistakes have been made.

#

if anyone with a fast computer and an entire night free wants to try this, go ahead.

#

i believe this is what the industry calls a mistake

prisma coral
sick hound
#

mhm.

#

you see

#

it turns out that time.sleeps limit is 2**63 nanoseconds

#

my plan was to have a program that counts upwards, each time testing whether time.sleep() works on it

#

when it eventually reaches 2**63, that is used as the value

#

that way it would take a very long time

rapid sparrow
#

we can help you if you're confused about python

nova ginkgo
#

can someone transform this code into some cursed one-liner

a = [100, 400, 500, 300, 200]
b = 345

def closest_to_int(x, itr):
    return sorted(itr, key=lambda j: abs(j - x))[0]

print(closest_to_int(b, a)) # -> 300
shut trail
#

!e ```py
print((lambda x, itr: sorted(itr, key=lambda j: abs(j - x))[0])(345, [100, 400, 500, 300, 200]))

night quarryBOT
#

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

300
shut trail
#

@nova ginkgo ^

#

if you need me to explain anything in there LMK

astral rover
#

fwiw you can use min here

terse mortar
nova ginkgo
#

great, thanks guys

shut trail
terse mortar
#

You can also get rid of the space after the :s

#

!e ```py
x = lambda test:print(test)

x("test")

night quarryBOT
#

@terse mortar :white_check_mark: Your eval job has completed with return code 0.

test
terse mortar
#

!e ```py
print((lambda x,itr:sorted(itr,key=lambda j:abs(j-x))[0])(345,[100,400,500,300,200]))

night quarryBOT
#

@terse mortar :white_check_mark: Your eval job has completed with return code 0.

300
arctic pine
#

Can someone help with this script?

night quarryBOT
#

Hey @arctic pine!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

arctic pine
#

Please help me with this code I get, xsrf update error: list index out of range <class 'IndexError'>

#

Dm me if you figured it out!

next flame
dark wharf
#

for the sorted[0] can't you just use min, it accepts key arg too

astral rover
floral meteor
#

I find this brainfuck derivative useful in arithmetic encryption

def intfuck(code:list[int]):
  a=__import__("collections").defaultdict(int)
  i=p=t=0
  def add(i):
    a[i]=(a[i]+1)%256
    return i,0
  def sub(i):
    a[i]=(a[i]-1)%256
    return i,0
  def left(i):return i-1,0
  def rite(i):return i+1,0
  def dot(i):
    print(end=chr(a[i]))
    return i,0
  def com(i):
    a[i]=ord(__import__('sys').stdin.read(1))
    return i,0
  def loop(i):return i,not a[i]
  def end(i):return i,-bool(a[i])
  while 0<=p and p<len(c):
    if t:t+=(c[p]==7)-(c[p]==8)
    else:i,t=[add,sub,left,rite,dot,com,loop,end,lambda i:(i,0)][int(''.join([*range(8)]).find(str(c[p]-1))](i)
    p+=1-2*(t<0)
  return int(bool(t))
#

I had to write it from memory so it might have errors

#

this one prints the output and returns the exit code

floral meteor
#

I tried to reverse engineer intfuck, but it looks like it belongs where beautiful code goes to die... oh wait that's here!

def random_noop_insert(victim):
  from random import randint
  _0,_1=0,len(victim)
  while _0<_1:
    if randint(0,4):victim=''.join([*victim[:_0],str(9*randint(0,1)),*victim[_0:]])
    _0+=1
  return map(int,victim)

def unfuck(message:str):
  output=[ord(this)%256 for this in message]
  if randint(0,9):code=''
  else:code='9'
  _0=[*filter(lambda x:any([t//10==x for t in output]),range((max(output)+2)//10)),max(output)//10]
  _0=[*{*_0}]
  code+='1'*10+'74'+'4'.join([t*'1'for t in _0])+'3'*len(_0)+'284'
  j=0
  for c in output:
    a = c.__divmod__(10)
    while a[0]>d[j]:j+=1;code+='4'
    while a[0]<d[j]:j-=1;code+='3'
    code+='1'*a[1]+'5'+'2'*a[1]
  _={_ and(code:=code[:-1])for _ in iter(lambda:code.endswith('2'),False)},{_ and(code:=code.replace'12',''))for _ in iter(lambda:'12'in code,False)},{_ and(code:=code.replace('21',''))for _ in iter(lambda:'21'in code,False)}
  return[*random_noop_insert(code)]
inland monolith
#
prio = {                   1: 'priority', 2: 176027, 3: '',             4: 'priority'}
supp = {0: 'supplemental',                2: 160620, 3: 'supplemental', 4: 'supplemental'}
merged = supp | prio
merged = {k: supp[k] if not merged[k] and supp.get(k) else merged[k] for k in merged}
merged == {0: 'supplemental', 1: 'priority', 2: 176027, 3: 'supplemental', 4: 'priority'}

is anyone able to golf this further?

last locust
inland monolith
#

!e

p='priority'
prio={1:p,2:176027,3:'',4:p}
s='supplemental'
supp={0:'supplemental',2:160620,3:s,4:s}
merged={k:x if not (x:=merged[k]) and (y:=sup.get(k)) else x for k in merged}
print(merged == {0: 'supplemental', 1: 'priority', 2: 176027, 3: 'supplemental', 4: 'priority'})
#

can't walrus in an inline if

last locust
#

You need() around the x:= probably

#

edited

inland monolith
#

how do i tell it to try again

last locust
#

Press the reaction

#

nvm, you took too long to edit

#

Just resend

inland monolith
#

!e

p='priority'
prio={1:p,2:176027,3:'',4:p}
s='supplemental'
supp={0:'supplemental',2:160620,3:s,4:s}
merged = supp | prio
merged={k:x if not (x:=merged[k]) and (y:=supp.get(k)) else x for k in merged}
print(merged == {0: 'supplemental', 1: 'priority', 2: 176027, 3: 'supplemental', 4: 'priority'})
last locust
#

oh wait

#

fixed

night quarryBOT
#

@inland monolith :white_check_mark: Your eval job has completed with return code 0.

False
inland monolith
#

aaaan it doesn't even work

last locust
#

And obviously you can shorten further by using shorter variable names

#

sec

#

!e ```py
p='priority'
prio={1:p,2:176027,3:'',4:p}
s='supplemental'
supp={0:s,2:160620,3:s,4:s}
merged={k:x if not (x:=(supp|prio)[k]) and (y:=sup.get(k))else x for k in supp|prio}

inland monolith
#

i don't really care about variable names, i just want to reduce the number of valid lines

night quarryBOT
#

@last locust :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 5
002 | SyntaxError: assignment expression cannot be used in a comprehension iterable expression
inland monolith
#

lol

last locust
#

!e py p='priority' prio={1:p,2:176027,3:'',4:p} s='supplemental' supp={0:s,2:160620,3:s,4:s} merged={k:x if not (x:=(supp|prio)[k]) and (y:=supp.get(k))else x for k in supp|prio} print(merged)

night quarryBOT
#

@last locust :white_check_mark: Your eval job has completed with return code 0.

{0: 'supplemental', 2: 176027, 3: '', 4: 'priority', 1: 'priority'}
inland monolith
#

3 is wrong

last locust
#

What are you actually trying to do?

inland monolith
#

merge supplemental into priority such that anything missing from priority is supplemented

#

missing can be defined as both the absence of a key and a value that would equate to false, like '' or None

#

!e

prio = {                   1: 'priority', 2: 176027, 3: '',             4: 'priority'}
supp = {0: 'supplemental',                2: 160620, 3: 'supplemental', 4: 'supplemental'}
merged = {k: supp[k] if not prio.get(k) and supp.get(k) else prio[k] for k in supp|prio}
merged == {0: 'supplemental', 1: 'priority', 2: 176027, 3: 'supplemental', 4: 'priority'}
last locust
#

So take prio if it exists, otherwise supp?

inland monolith
#

yes

#

!e

prio = {                   1: 'priority', 2: 176027, 3: '',             4: 'priority'}
supp = {0: 'supplemental',                2: 160620, 3: 'supplemental', 4: 'supplemental'}
merged = {k: supp[k] if not prio.get(k) and supp.get(k) else prio[k] for k in supp|prio}
print(merged == {0: 'supplemental', 1: 'priority', 2: 176027, 3: 'supplemental', 4: 'priority'})
night quarryBOT
#

@inland monolith :white_check_mark: Your eval job has completed with return code 0.

True
inland monolith
#

ah nice, now i don't have to declare merged twice

last locust
#

Is that not just prio | supp?

inland monolith
#

!e

prio = {                   1: 'priority', 2: 176027, 3: '',             4: 'priority'}
supp = {0: 'supplemental',                2: 160620, 3: 'supplemental', 4: 'supplemental'}
print(prio | supp == {0: 'supplemental', 1: 'priority', 2: 176027, 3: 'supplemental', 4: 'priority'})
night quarryBOT
#

@inland monolith :white_check_mark: Your eval job has completed with return code 0.

False
last locust
#

!e py prio = { 1: 'priority', 2: 176027, 3: '', 4: 'priority'} supp = {0: 'supplemental', 2: 160620, 3: 'supplemental', 4: 'supplemental'} print(prio | supp) print(supp | prio)

inland monolith
#

lol

night quarryBOT
#

@last locust :white_check_mark: Your eval job has completed with return code 0.

001 | {1: 'priority', 2: 160620, 3: 'supplemental', 4: 'supplemental', 0: 'supplemental'}
002 | {0: 'supplemental', 2: 176027, 3: '', 4: 'priority', 1: 'priority'}
last locust
#

What's wrong with the first one?

inland monolith
#

neither are what i want (i did look before)

last locust
#

Oh I see

inland monolith
#

all of them are supplemental

#

and the 2nd one is missing the value i needed for 3

last locust
#

!e ```py
prio = { 1: 'priority', 2: 176027, 3: '', 4: 'priority'}
supp = {0: 'supplemental', 2: 160620, 3: 'supplemental', 4: 'supplemental'}

d = {k: x if (x:=prio.get(k)) else supp[k] for k in prio | supp}
print(d)```

night quarryBOT
#

@last locust :white_check_mark: Your eval job has completed with return code 0.

{1: 'priority', 2: 176027, 3: 'supplemental', 4: 'priority', 0: 'supplemental'}
last locust
#

Is that good?

inland monolith
#

i think so

#

!e

prio = {                   1: 'priority', 2: 176027, 3: '',             4: 'priority'}
supp = {0: 'supplemental',                2: 160620, 3: 'supplemental', 4: 'supplemental'}
merged = {k: x if (x:=prio.get(k)) else supp[k] for k in prio | supp}
print(merged == {0: 'supplemental', 1: 'priority', 2: 176027, 3: 'supplemental', 4: 'priority'})
night quarryBOT
#

@inland monolith :white_check_mark: Your eval job has completed with return code 0.

True
inland monolith
#

hm what did you change

#

i see the walrus

#
{k: supp[k] if not prio.get(k) and supp.get(k) else prio[k] for k in supp|prio}```
vs```py
{k: x if (x:=prio.get(k)) else supp[k] for k in prio | supp}```
last locust
#

I also tidied your conditional

inland monolith
#

why remove supp.get(k)

last locust
#

Note that mine assumes it'll always be in prio or supp

#

If that's not guaranteed then change to supp.get(k)

inland monolith
#

it may be in neither

inland monolith
#

alrighty that seems to be the simplest form, thank you

fleet bridge
#

!e

import _testcapi as t
print(t.the_number_three)
night quarryBOT
#

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

3
floral meteor
#

I think I get what whitespace is for now

#

it's to "water down" the code

#

so you can retain your sanity whilst reading it

restive void
#

Ithinkit'sthesamereasonwehavewhitespaceinEnglish:Yes,youcanalmostalwaysstilldecipherit,butit'sunnecessarilyhard.

floral meteor
#

what's so hard about my event loop?

#

english isn't colour coded ;)

#

now that i think about it i should've used the acknowledge character instead of \1

#

for some reason this line

char=='�':lambda:(c:=msvcrt.getch().decode('ANSI'))not in'KHMP'and(self.reset()or 1)or self.move(**{{'K':'a','H':'w','M':'d','P':'s'}[c]:1})

works on an older laptop, but not this newer laptop

#

so I have to use this line

char in'wasdqezx':lambda:self.move(w=char in'qwe',a=char in'qaz',s=char in'zsx',d=char in'edx')

for movement

floral meteor
#

alright I fixed it, spot the difference, and someone extremely experienced please tell me why

char in'�\xe0':lambda:(c:=msvcrt.getch().decode('ANSI'))not in'KHMP'and(self.reset()or 1)or self.move(**{{'K':'a','H':'w','M':'d','P':'s'}[c]:1})
#

the invalid unicode character is actually á

floral meteor
#

in the previous device, it was a different character

#

so in order for the same code to work on two different machines, that line has to look for two different characters

#

although now that I have fixed that plus a small visual glitch, I believe I have the game perfectly working

#

except maybe the problem of too much processing power available

#

in this snippet, the last line is an aid for speed running to prevent mistakes when hitting zero, and clearing a spot the user was gonna clear next.

            if not self.numbers[j][i]:
                _={self[m,n]==1 or self.select(m,n)for k,l in product(range(-1,2),repeat=2)for m,n in[(i+k,j+l)]if m in range(x)and n in range(y)}
                while msvcrt.kbhit(): msvcrt.getch()

without it, the user would instead attempt to clear the next square over, which was not the spot they were planning.
The problem with too much processing power is the above might run quicker than the user's reaction time, thus finishing before the next keyboard hit.
Slow it down a bit and the user can react to a 0-square clearing other squares and recalculate

#

aight i'm done someone else show me some amazing python torture

errant crescent
#

🙃

trim grove
#

any1 knows about that?

thorny tapir
#

!e

a[:], b = a = [[]], []
print(a)
night quarryBOT
#

@thorny tapir :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'a' is not defined
thorny tapir
#

ok then

frigid widget
#

!e

try:
    a = a[:], b = [[]], []
except: pass
print(a)
night quarryBOT
#

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

([[]], [])
frigid widget
#

assignments in Python are left-to-right, a = b = c does a = c first and b = c second

floral meteor
#

Interestingly, the "intuitive order" is less intuitive than the "actual order"

earnest wing
#

a, b = a[b] = [{},()]

earnest wing
#

!e ```py
a, b = a[b] = [{},()]
print(a, b)

night quarryBOT
#

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

{(): [{...}, ()]} ()
fleet bridge
#

empty tuple is singleton

#

!e

x = ()
y = (1,2,3)[:0]
z = tuple()
print(x is y is z)
night quarryBOT
#

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

True
floral meteor
#

!e someone asked this question in a help channel, so I'm just gonna post here what I shouldn't post there #help-corn message

from __future__ import annotations
from ctypes import*
flogbals = py_object.from_address(id(globals())+8).value
__name__ = 'Throwable'

class TypeException(TypeError):
  def __init__(self, message):
    super().__init__(message)
    py_object.from_address(id(globals())+8).value=flogbals

class __annotations__(metaclass=lambda*a:type(*a)()):
  queue = []
  type_hints = {}
  def __setitem__(self, cls_name, name):
    if name in self.type_hints:
      self.queue[:]=()
      raise TypeException(f'Variable \'{name}\' already declared as \'{self.type_hints[name]}\'.')
    if not self.queue:
      self.type_hints[name] = globals()[cls_name]
      return
    cls, value = self.queue.pop(0)
    self.type_hints.update({name:cls})
    if cls==cls_name:raise NameError(f'Type {cls} not found')
    dict.update(globals(),{name:cls(value)})

class __globals__(dict):
  def __missing__(self, key):
    return __builtins__.__dict__.get(key,key)
  def __setitem__(self, key, value):
    if key in __annotations__.type_hints:
      dict.update(globals(), {key:__annotations__.type_hints[key](value)})
      return
    __annotations__.queue+=[(globals()[key], value)]


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

str: x
str: y
int: z
x = 11
y = 10
z = x + y
print(z)
night quarryBOT
#

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

1110
errant crescent
#

Whoops, placed the slice in the wrong place... 👀

floral meteor
#

👀

fleet bridge
#

!e

class _ProxyGetter:
    def __ror__(self, other):
        return other

def _get_mappingproxy_dict(mp, *, __proxy_getter=_ProxyGetter()):
    return mp | __proxy_getter

del _ProxyGetter

_get_mappingproxy_dict(str.__dict__)['trim'] = str.strip

print("   hello w orld   ".trim())
night quarryBOT
#

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

hello w orld
astral rover
#

Hmm

#

Why does that work

fleet bridge
rugged sparrow
#

!e ```py
def get_cls_dict(cls, E=type('',(),{'eq':lambda s,o:o})()):
return cls.dict == E

get_cls_dict(int)['inc'] = lambda self: self + 1
print(1 .inc())```

night quarryBOT
#

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

2
rugged sparrow
#

__eq__ works too

trim grove
#

!e

def get_cls_dict(cls, E=type('',(),{'__eq__':lambda s,o:o})()): return cls.__dict__ == E
get_cls_dict(int)['__ne__'] = get_cls_dict(int)['__eq__']
print((1).__eq__(1))
print((1).__ne__(1))
print(1==1)
print(1!=1)
night quarryBOT
#

@trim grove :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | True
003 | True
004 | False
trim grove
#

any way to override the c func

rugged sparrow
#

use fishhook

#

!e ```py
from fishhook import *

@hook(int)
def add(self, other):
print(self, other)
return orig(self, other)

1 + 2```

night quarryBOT
#

@rugged sparrow :x: Your eval job has completed with return code 1.

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

Full output: too long to upload

rugged sparrow
#

yea i need to fix that __eq__ bug (but its hard cause I wrote the hooker in python so it has to use the hooks)

#

v2 will fix it because that introduces a with no_hooks: context manager

trim grove
#

is this calculating the offsets at runtime

rugged sparrow
#

yea

floral meteor
#

Because error handling requires a reset state otherwise it segfaults before the improvised atexit kicks in

floral meteor
#

Error handling and exiting both crash "corrupted" python unless safeguards like these reset it

rugged sparrow
#

*you can also use some more complex hooks that don't break pythons built in garbage collector (thats what segfaults in the end)

floral meteor
#

My prevention is really a gamble that the garbage collector would come for my user created object before whatever builtin object got corrupted

rugged sparrow
#

@floral meteor this should show why changing a dict instances class to a basic dict subclass causes issues. The basic subclass thinks it larger, so it frees more memory than the original dict instance. By adding __slots__ you can help to nullify this as it makes the dict subclass have the same internal structure as the original dict class

shut trail
#

Quick question - why wouldn't #bot-commands message

change the value of x from 1 to 2?

#

or is that not how it works

shut trail
#

Ohh

#

Is an integer not a void pointer like most things? Or are most things not void pointers

steel knot
fleet bridge
#

TIL except: catches BaseException, not Exception:

>>> try:
...   raise BaseException()
... except:
...   print('hi')
...
hi
sick hound
# steel knot

saw that on yt or someplace saying how to confuse a python dev

thorny tapir
# steel knot

oh so this is just
len((True, True, True, True == True, True, True, True))

so it finds True == True which is true so the length i s7
right?

thorny tapir
# steel knot

and this it only looks at the last 1 and checks if itss equal to the tuuple which its not

rapid sparrow
last locust
rapid sparrow
#

oh wow, I wouldn't have guessed so

last locust
#

Yeah, it's funky lol

#

Down to precedence ig

rapid sparrow
#

so 1, 1, 1 isnt the same as (1, 1, 1) in this case?

last locust
#

It's not checking what you expect it to check

#

The point is that it does (1, 1, x) where x is 1 == (1, 1, 1) (it evaluates the == before "building" the left tuple)

#

And an int isn't equal to a tuple, so it evaluates to False

#

Hence (1, 1, False)

#

You could equally do 1, 1, 1 == 1 and you'd get (1, 1, True) for the same reason

#

The == is done before the tuple constructor

last locust
gleaming timber
#

!e

class Foo:
  def __init__(self):
    x = 42
    def get_x():
      return x
    def set_x(val):
      nonlocal x
      x = val
    self.get_x = get_x
    self.set_x = set_x

foo = Foo()
print(foo.get_x())
foo.set_x(3)
print(foo.get_x())
print(foo.x)
night quarryBOT
#

@gleaming timber :x: Your eval job has completed with return code 1.

001 | 42
002 | 3
003 | Traceback (most recent call last):
004 |   File "<string>", line 16, in <module>
005 | AttributeError: 'Foo' object has no attribute 'x'
gleaming timber
snow beacon
# gleaming timber private variables in python

!e ```py
class Foo:
def init(self):
x = 42
def get_x():
return x
def set_x(val):
nonlocal x
x = val
self.get_x = get_x
self.set_x = set_x

foo = Foo()
foo.set_x.closure[0].cell_contents = 10
print(foo.get_x())

night quarryBOT
#

@snow beacon :white_check_mark: Your eval job has completed with return code 0.

10
gleaming timber
#

😮

restive void
#

Ew

floral meteor
#

You broke your own private variables system

rapid sparrow
#

privacy breach

#

needs friend keyword

floral meteor
#

I have recently used |{...} to fix a syntax error

#

literally those 6 characters

#

in that order

floral meteor
#

I could use kivy, and then make one Image object, then the event loop would only take raw input from clicking, and draw everything onto an image to display that. 2D rendering maybe.
Then with just that as io i could make a touchscreen game

#

I'm gonna make another minesweeper, this time with an actual gui

#

but first I gotta black box the existing minesweeper so I can use it

#

anyone have esoteric tips on black boxing an interface the most cursed way possible?

#

I wanna get creative

light peak
#

!rank

night quarryBOT
#

Iterating over range(len(...)) is a common approach to accessing each item in an ordered collection.

for i in range(len(my_list)):
    do_something(my_list[i])

The pythonic syntax is much simpler, and is guaranteed to produce elements in the same order:

for item in my_list:
    do_something(item)

Python has other solutions for cases when the index itself might be needed. To get the element at the same index from two or more lists, use zip. To get both the index and the element at that index, use enumerate.

floral meteor
sick hound
#

lol is this the brainfuck python?

snow beacon
#

I'd hate for someone to get hacked, after all.

upbeat sonnet
#

!e```python
import sys, os

def restart():
os.execv(sys.executable, ['python'] + sys.argv)
return False

while True:
print(restart())
restart()```

#

it wont let me break it 😢

floral meteor
night quarryBOT
#

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

:(
floral meteor
#

!e ```py
try:raise SystemExit
except:print(SystemExit)
try:raise KeyboardInterrupt
except:print(KeyboardInterrupt)

night quarryBOT
#

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

001 | <class 'SystemExit'>
002 | <class 'KeyboardInterrupt'>
floral meteor
#

bruh is this recent? I always remember having to explicitly reference BaseException to cover these two exceptions

floral meteor
#

I started making a proper gui version of minesweeper. I made the skeleton in Cell-Engine-Interface style but my brain is already fried :)

sick hound
#

!e !e
import sys, os

def restart():
os.execv(sys.executable, ['python'] + sys.argv)
return False

while True:
print(restart())
restart()

night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     !e
003 |     ^
004 | SyntaxError: invalid syntax
sick hound
#

!e
import sys, os

def restart():
os.execv(sys.executable, ['python'] + sys.argv)
return False

while True:
print(restart())
restart()

night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 2.

001 | Argument expected for the -c option
002 | usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
003 | Try `python -h' for more information.
sick hound
#

!e @zinc aurora

night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     <@​683001325440860340>
003 |     ^
004 | SyntaxError: invalid syntax
restive void
#

Posted this in #advanced-discussion, but it probably fits better here:

import os
import sys
import inspect
from contextlib import contextmanager

@contextmanager
def atomic():
    ppid = os.getpid()
    cpid = os.fork()
    if cpid:
        os.waitpid(cpid, 0)
        # we didn't get killed: error occured, skip body:
        sys.settrace(lambda *a, **k:None)
        frame = inspect.currentframe().f_back.f_back
        def raiser(*a): raise RuntimeError
        frame.f_trace = raiser
        try:
            yield
        except RuntimeError:
            return
    try:
        yield
    except Exception:
        # rollback: we exit
        os._exit(0)
    else:
        # all good: kill state-preserved parent
        os.kill(ppid, 9)

x = 23
with atomic():
    x += 1
    1/0

print(x) 
tiny lodge
#

@restive void why can’t I access #advanced-discussion? Is it invite only?

prisma coral
tiny lodge
#

Thanks @prisma coral

restive void
#

@tiny lodge so how it works is it first forks: this splits the execution in half across two "clones" of the same Python interpreter.
There parent process waits for the child process to exit. The child process enters the context manager's body and tries to execute it. If it succeeds, it just kills the parent process and continues normally.
If it fails, it kills itself.
In that case, the parent knows that the child died and is in the situation you desire a solution for: we are still "back in time", before the body of the context manager was entered, and we want to skip it. To do so, we set a trace function (the mechanism used by debuggers, coverage tools, etc.) to raise an exception inside the body immediately on entering it. We then catch that exception, and carry on.

rugged sparrow
#

ah raising an exception in the frame with a trace is clever, i was thinking about using a trace to jump lines

restive void
#

I stole it from StackOverflow

steel knot
#

!e
print("haha xd")

night quarryBOT
#

@steel knot :white_check_mark: Your eval job has completed with return code 0.

haha xd
steel knot
#

i dont python

last locust
#

#bot-commands please @steel knot

floral meteor
#

But beautifully esoteric way of going back in time in case of a failure. Just like saving your game, and going back to your last save if you die or accidentally kill an essential npc.

#

It's like code that can control time itself

#

Keep it up and you might even be able to code a Terminator that goes back in time to assassinate Hitler

last locust
#

Let's not be making suicide jokes please.

floral meteor
#

fair enough

#

I thought that might've been to far hence the /s

#

but now i know for sure, thank you

#

the assassinate hitler joke is good though?

#

!e okay how about this one? ```py
for()in(),{},[],'',"",range(0),iter(lambda:...,...),set():print(end='.')

night quarryBOT
#

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

........
floral meteor
#

instead of doing the same thing 8 times like

for i in range(8):print(end='.')

you can

for()in[()]*8:print(end='.')
#

it's shorter and confusinger

fleet bridge
#

!e

for {}[()] in range(5): print(end='.')
night quarryBOT
#

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

.....
sick hound
#

!e

await ctx.send("test?")
night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 | SyntaxError: 'await' outside function
floral meteor
#

!e ```py
for{}[()]in[{}]*8:print('something in between?')

night quarryBOT
#

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

001 | something in between?
002 | something in between?
003 | something in between?
004 | something in between?
005 | something in between?
006 | something in between?
007 | something in between?
008 | something in between?
floral meteor
sick hound
#

No, that's not hacking the bot buddy.

floral meteor
#

this channel is more for torturing python itself

sick hound
#

That's a message to be sent.

#

Lul

floral meteor
#

yeah, that's obviously not gonna work

sick hound
#

It does on most python bots.

#

Thanks.

floral meteor
#

and this still isn't the right channel

sick hound
#

Please refer to the #argument channel then.

#

😉

floral meteor
#

what wrong with the #bot-commands channel?

fleet bridge
#

!e ```py
for[]in[[]]*8:print(end='.')

night quarryBOT
#

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

........
fleet bridge
#

i think it is shortest

floral meteor
#

indeed

#

well, assuming an abstract code block in place of print(end='.')

#

!e otherwise ```py
print('.'*8)

night quarryBOT
#

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

........
fleet bridge
#

😄

#

i meant for[]in[[]]*n: is shortest for-cycle over n elements

floral meteor
#

yes, that's another way of saying it

fleet bridge
#

yea)

floral meteor
#

but for{():[]}[()]in[()]*n: makes it deliciously more confusing for the beginner coder

fleet bridge
#

exactly

sick hound
fleet bridge
#

!e

a = a[0] = [None]
print(a)
assert a is a[0]
night quarryBOT
#

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

[[...]]
floral meteor
#

!e ```py
for{():[]}[()]in[()]*8:print(import('time').time())

night quarryBOT
#

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

001 | 1641988848.2122383
002 | 1641988848.2122772
003 | 1641988848.2122831
004 | 1641988848.2122874
005 | 1641988848.2122915
006 | 1641988848.2122958
007 | 1641988848.2122998
008 | 1641988848.2123039
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

Fatal  Failure
floral meteor
#

two spaces?
maybe make it a \b

fleet bridge
#

print(a, b) add one space

sick hound
#

!e

a = "Fatal"
b = "Failure"

print(a, b)
night quarryBOT
#

@sick hound :white_check_mark: Your eval job has completed with return code 0.

Fatal Failure
floral meteor
#

!e ```py
print("Fatal",'\b',"Failure")

night quarryBOT
#

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

Fatal  Failure
sick hound
#



floral meteor
#

it works in a "real" terminal

fleet bridge
#

!e {}[()]={():[{()}]}

night quarryBOT
#

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

[No output]
proper vault
#

ye, the message doesn't interpret control characters other than a newline

sick hound
#

\n

#

hm

fleet bridge
#

you can edit message

sick hound
#

You can?

fleet bridge
#

you can

sick hound
#

huh

fleet bridge
#

too late

#

also pls delete messages with errors

sick hound
#

bruh

fleet bridge
#

what are you doing??? go to #bot-commands

sick hound
#

Sorry, sir. This is not a general chat.

#

Thank you.

night quarryBOT
#

@sick hound :warning: Your eval job has completed with return code 0.

[No output]
fleet bridge
#

cool

>>> [*[a,[*([b,[f],d],c)],*(*[(),e],)],[]] = 1,[(2,[3],4),5],(),7,()
>>> a,b,f,d,c,e
(1, 2, 3, 4, 5, 7)
#
>>> class PrintSetAttr:
...  def __setattr__(self, attr, value):
...   print(f'{attr}={value!r}')
...
>>> _ = PrintSetAttr()
>>> [*[_.a,[*([_.b,[_.f],_.d],_.c)],*(*[(),_.e],)],[]] = 1,[(2,[3],4),5],(),7,()
a=1
b=2
f=3
d=4
c=5
e=7

order of assignments is left-to-right

#

is there a way to convert any code to one-liner?

#

especially with and try-except

#

import -> __import__
for -> [list comprehension]
if -> a if c else b
class -> type(...)
def -> lambda
with -> type('',(contextlib.ContextDecorator,),{'__enter__': ..., '__exit__': ...})()(func)()
try -> ???
while -> [list comprehension with callavle iterator]

proper vault
#

the only thing I have yet to see done algorithmically is nonlocal

#

with is easy with ContextDecorator, try is just a context manager

#

while is just iter

#

while a: -> [_ for _ in iter(lambda: a,False)]

fleet bridge
#

can i do something like:


(cm := SomeContextManager(), x := cm.__enter__(), some_code, cm.__exit__())

i think it wont work

proper vault
#

no

#

you need the ContextDecorator thing

#

!d contextlib.ContextDecorator

night quarryBOT
#

class contextlib.ContextDecorator```
A base class that enables a context manager to also be used as a decorator.

Context managers inheriting from `ContextDecorator` have to implement `__enter__` and `__exit__` as normal. `__exit__` retains its optional exception handling even when used as a decorator.

`ContextDecorator` is used by [`contextmanager()`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager "contextlib.contextmanager"), so you get this functionality automatically.

Example of `ContextDecorator`:
fleet bridge
#

type('',(contextlib.ContextDecorator,),{'__enter__': ..., '__exit__': ...})()(func)()

#

!e

from __future__ import annotations
from types import TracebackType
from typing import Any, Callable

from contextlib import ContextDecorator


class TryExceptContext(ContextDecorator):
    def __init__(
        self,
        *exceptions: tuple[
            type[BaseException],
            Callable[[type[BaseException] | BaseException], Any],
        ]
    ) -> None:
        self.exceptions = exceptions

    def __enter__(self) -> None:
        pass

    def __exit__(
        self,
        exc_type: type[BaseException],
        exc_value: BaseException,
        traceback: TracebackType,
    ) -> bool:
        if exc_type is None:
            exc_type = type(exc_value)
        for exc, fun in self.exceptions:
            if issubclass(exc_type, exc):
                fun(exc_value if exc_value is not None else exc_type)
                return True
        return False


catch_typeerror = TryExceptContext((TypeError, lambda exc: print(exc)))

catch_typeerror(lambda: 1 + 2)()
catch_typeerror(lambda: 1 + '')()
try:
    catch_typeerror(lambda: 1 / 0)()
except ZeroDivisionError:
    pass

catch_attr_and_name_error = TryExceptContext(
    (AttributeError, lambda exc: print(exc)),
    (NameError, lambda exc: print(exc)),
)
catch_attr_and_name_error(lambda: [].a)()
catch_attr_and_name_error(lambda: a)()
try:
    catch_attr_and_name_error(lambda: [][0])()
except IndexError:
    pass
night quarryBOT
#

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

001 | unsupported operand type(s) for +: 'int' and 'str'
002 | 'list' object has no attribute 'a'
003 | name 'a' is not defined
fleet bridge
#

it works

#
def f():
  for x in y:
    if z(x):
      return a(x)
  return b

how to convert it to lambda?

#

(without messing with bytecode, of course)

last locust
#
lambda: a if any(z(x) for x in y) else b```
fleet bridge
#

oh

#

a is expression

#

it may contain x

last locust
#

Then a(x) instead of a 🤷

fleet bridge
#

you cant

#

lambda: a(x) if any(z(x) for x in y) else b is invalid

#

x is local to gen-expression inside any()

proper vault
#
f=lambda: next((a(x) for x in y if z(x)),b)
fleet bridge
#

nice!

last locust
#

But next() is definitely the nicer option

fleet bridge
#

no, x is local to this generator: (a(x) if z(x) else b for x in y)

last locust
#

Wait I sent the wrong one

#

Edited

#

Nvm sec

fleet bridge
#
>>> (lambda: x:=0)()
  File "<stdin>", line 1
    (lambda: x:=0)()
     ^^^^^^^^^
SyntaxError: cannot use assignment expressions with lambda
#
>>> lambda: c[0] if all(z==a(x) for z in (c:=[a(x) if z(x) else b for x in y])) else b
  File "<stdin>", line 1
SyntaxError: assignment expression cannot be used in a comprehension iterable expression
last locust
fleet bridge
#

interesting 🧐

last locust
#

Can I have a, b, x and y? @fleet bridge

last locust
fleet bridge
#
y = [1,2,3,4,5]
z = lambda x: x % 2 == 0
# z = lambda x: False # for returning b
a = lambda x: x*x
b = 0
last locust
#

Thanks

fleet bridge
#

(lambda:t[0]if(t:=[a(x)for x in y if z(x)])else b)()

last locust
#

Yeah, that could be what I was going for

#

And then you can remove unnecessary spaces etc.

#
(lambda:t[0]if(t:=[a(x)for x in y if z(x)])else b)()
fleet bridge
#

how to convert match-case into one-liner? 😄

#

I have seen a way to dynamically generate patterns and match them in early drafts, iirc

floral meteor
#

not sure about all the dynamiccy stuff but...

#
{caseA:lambda:...,caseB:lambda:...,caseC:lambda:...}.get(True,lambda:...)()
#

that's how I do it, even in preference to the match case suite

fleet bridge
#

it is switch-case, not pattern matching actually

floral meteor
#

for example if i want multiple keybinds to do certain functions, just observe the core of my minesweeper event loop

            (lambda i,j:{
char in'\t/?':lambda:self.right_click(i, j),
char in'\b\xff':self.reset,
char in' \r':lambda:self.react_select(i, j),
char in'wasdqezx':lambda:self.move(w=char in'qwe',a=char in'qaz',s=char in'zsx',d=char in'edx'),
char in'[\x1b':lambda:self.DIE(True),
char in'�\xe0':lambda:(c:=msvcrt.getch().decode('ANSI'))not in'KHMP'and(self.reset()or 1)or self.move(**{{'K':'a','H':'w','M':'d','P':'s'}[c]:1}),
char in'h;:':self.hint,
char in'rl':self.random_move,
char.isdigit():lambda:self.digit_move(int(char))
            }.get(1,lambda:0)()or self.update_board())(*self.here)
fleet bridge
#

hmm

#

!e print({1:2,1:3})

night quarryBOT
#

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

{1: 3}
floral meteor
#

exactly

fleet bridge
#

yes, it implements some flavor of pattern-matching

floral meteor
#

the only "flavor" I really would ever need to use

#

the python version of ```matlab
switch s
case 1:
do_this()
case 2:
do_that()
case 3:
print('wheeee')
otherwise:
0
end

would be
```py
{1:do_this,2:do_that,3:lambda:print('wheeee')}.get(s,lambda:0)()
#

switching True can be useful for substituting extended if statements

#

keep in mind if all the middle ifs are elifs, your dict would actually be backwards in the one-line version

#

another example is where I sum a list excluding elements between and including 6 and 9

def summer_69(a):
  state = [0]
  output = [0]
  for e in a:
    {
state[0]:lambda:...,
state[0]and e==9:lambda:state.__setitem__(0,0),
not state[0]:lambda:output.__setitem__(0,output[0]+e),
not state[0]and e==6:lambda:state.__setitem__(0,1)
    }[1]()
  return output[0]
fleet bridge
#

it is sadly that you cant do a[b]:=c or a.b:=c

floral meteor
#

you can a.__setitem__(b,c) and a.__setattr__(b,c)

fleet bridge
#

yes, but it is ugly imo

floral meteor
#

or even juicier

[0 for a[b]in[c]]
[0 for a.b in[c]]
fleet bridge
#

lol

floral meteor
#

anticlimactic loops can modify mutable objects

#
lambda a:((state:=[0]),(output:=[0],[{state[0]:lambda:0,state[0]and e==9:lambda:[0 for state[0]in[0]],not state[0]:lambda:[0 for output[0]in output[0]+e],not state[0]and e==6:lambda:[0 for state[0]in[1]]}[1]()for e in a]))[1][0]
#

that's the oneliner version of summer_69

#

using a state machine to get a binary state and the input to decide on modifying the output state and the binary state

#

and using anticlimactic loops for variable modification

#

and that's how I do switch suites

fleet bridge
#

import -> __import__
for -> [list or set comprehension]
if -> a if c else b
class -> type(...)
def -> lambda
with -> type('',(contextlib.ContextDecorator,),{'__enter__': ..., '__exit__': ...})()(func)()
try -> custom context manager based on ContextDecorator
while -> [list or set comprehension with callable iterator]
assignment -> := or [0 for a[b]in[c]] or [0 for a.b in[c]]
match-case -> {cond3:f3,cond2:f2,...}.get(True,fdefault)()
switch-case -> {val1:f1,val2:f2,...}.get(val,fdefault)()

floral meteor
#

don't forget
switch-case-default -> {casen:fn, case3:f3,case2:f2,case1:f1}.get(switched_variable,f_otherwise)()

fleet bridge
#

this is interesting

floral meteor
#

and you got your conds backwards if you want it to execute f1 in priority to f2 if cond1 and cond2

#

also for the while, it's better on memory if you use set comprehension otherwise you cannot truly make an infinite while loop

floral meteor
#
lambda a:((state:=[0]),(output:=[0]),[{state[0]:lambda:0,state[0]and e==0b1001:lambda:[0 for state[0]in[0]],not state[0]:lambda:[0 for output[0]in output[0]+e],not state[0]and e==0b0110:lambda:[0 for state[0]in[1]]}[1]()for e in a])[1][0]
fleet bridge
#

you cant make it more cursed than this

floral meteor
#

yeah you should see one of the cursed hello worlds way back a few years ago in this channel

#

trying to understand it requires immense knowledge, and even then that's just to write a deobfuscator to make it a little bit more readable, then you need advanced python knowledge and algorithmic understanding just to read that

floral meteor
#

woops forgot a bracket, fixed

#

bracket matching is easy to stuff up in this line of onelinerisation

fleet bridge
#

!e import __hello__

night quarryBOT
#

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

Hello world!
floral meteor
#

obfuscation is an entirely different field which is fun but tiresome for me

#

onelinerisation with just a touch of cursed is my comfort zone

#

but just a touch of cursed is present in all of my code

#

!e ```py
print((lambda a:((state:=[0]),(output:=[0]),[{state[0]:lambda:0,state[0]and e==0b1001:lambda:[0 for state[0]in[0]],not state[0]:lambda:[0 for output[0]in[output[0]+e]],not state[0]and e==0b0110:lambda:[0 for state[0]in[1]]}1for e in a])[1][0])([1,2,3,4,5,6,7,8,9,1,1,1,1]))

night quarryBOT
#

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

19
dense nova
#

i saw this video 'calculate electricity bill in c' and im like: 'I'll do that in 1 line in python'
Behold: ```py
print(f"Electricity bill: {(add := 0 if (units := int(input('Enter number of units you used: '))) < 50 else 130 if units <= 100 else 292.5 if units <= 200 else 818.5) + (((units - (0 if units <= 50 else 50 if units <= 100 else 100 if units <= 200 else 200))) * (2.6 if units < 50 else 3.25 if units <= 100 else 5.26 if units <= 200 else 7.75)) + (25 if add == 0 else 35 if add == 130 else 45 if add == 292.5 else 55)}")

#

la code

floral meteor
#

!e print(1+2+3+4+5+4)

night quarryBOT
#

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

19
floral meteor
fleet bridge
dense nova
#

.....

floral meteor
#

the second one summed the list, but without the elements between and including 6 and 9

#

the first one did that algorithmically, taking the whole list as input

#

!e ```py
á, 🤔, 🪟 = 0, False, []
print(dir())

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     á, 🤔, 🪟 = 0, False, []
003 |        ^
004 | SyntaxError: invalid character '🤔' (U+1F914)
floral meteor
#

dammit

fleet bridge
#

!e print('🤔')

night quarryBOT
#

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

🤔
floral meteor
dense nova
#

and

floral meteor
#

thonk

#

you made an AI that does nothing but think

fleet bridge
#

not all emoji are allowed to be in names

dense nova
#

the python variable naming rules do state that the variable name cannot have any special characters except _ but any ascii character can be in a sting

floral meteor
#

or does it?

fleet bridge
#

unicode lambda can be in names

#

!e λ = ''; print(dir())

night quarryBOT
#

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

['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'λ']
next flame
#

and certain punctuation too I think

sick hound
#

.topic

glass drumBOT
#
**What are the pros and cons of messing with __magic__()?**

Suggest more topics here!

unique rose
#

.topic

glass drumBOT
#
**What's a common part of programming we can make harder?**

Suggest more topics here!

severe canyon
#

esoteric in a nutshell

dense nova
restive void
fleet bridge
#
>>> True, False = False, True
>>> True, False
(False, True)
restive void
#

Only in deprecated Python 2

languid hare
#

gross

#

in a good way

gaunt ferry
#

how to handle null and none values in pyspark dataframe, glue dynamic frame after reading CSV files

fleet bridge
#
>>> id([]) == id([])
True
>>> [] is []
False
fleet bridge
#
>>> id([[]]) == id([[]])
False
proper vault
#

try id([1]) == id([2])

dawn stone
#

a = b = c = d = "hi"

floral meteor
#

try mixing assignment chains with implicit tuple construction and unpacking

#

that's how I easily make code look initimidating

floral meteor
#

I only just noticed that and i wrote it 🤔

#

which means it's a universal algorithm, it can port to another language without looking too different

night quarryBOT
sick hound
#

Prints "hello".

restive void
arctic elm
night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 22
002 | SyntaxError: 'named expression' can not be used within an annotation
rich hound
#

!e

print((len("RATIO")**(int([]==[])/int(int("OwO"!="XwX")*len(":3")))+int(len("Furry")-4))/int(len("uwu")-1))
night quarryBOT
#

@rich hound :white_check_mark: Your eval job has completed with return code 0.

1.618033988749895
rich hound
#

math

night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 139 (SIGSEGV).

5:3.300000
simple crystal
#

can you make type(a) is int without messing with pointers?

#

when a isn't an int

restive void
simple crystal
#

lol good point

earnest wing
#

Incredible

#

I really like the reversed type annotations

solemn jungle
#

!e

n,l=[1000,900,500,400,100,90,50,40,10,9,5,4,1],'M CM D CD C XC L XL X IX V IV I'.split()
for N in range(1,4000):
 r='';p=N
 for x,y in zip(n,l):
  while p>=x:r+=y;p-=x
 exec('%s=%d'%(r,N))

print(CDXX+MCCCVII-MDCLXXXVIII)
night quarryBOT
#

@solemn jungle :white_check_mark: Your eval job has completed with return code 0.

39
solemn jungle
#

!e

n,l=[1000,900,500,400,100,90,50,40,10,9,5,4,1],'M CM D CD C XC L XL X IX V IV I'.split()
for N in range(1,4000):
 r='';p=N
 for x,y in zip(n,l):
  while p>=x:r+=y;p-=x
 exec('%s=%d'%(r,N))

print(CDXX+MCCCVII-MDCLVIII)
night quarryBOT
#

@solemn jungle :white_check_mark: Your eval job has completed with return code 0.

69
restive void
#

Now change the __repr__ of int accordingly

floral meteor
#

bugger that, don't use int, use an int subclass like booleans do

marsh void
#

roman type

#

haha

floral meteor
#

obviously, the __str__ method would be the algorithm to convert an integer to roman numerals

#
class Numeral(int):
  def __repr__(self):
    ...
  def __init__(self, *args):
    super().__init__(*args)
    self.__str__ = self.__repr__
floral meteor
#

alright I thought of a challenge. shorten and expand the functionality of this oneliner: ```py
class SirPrintalot:add=sub=mul=floordiv=truediv=mod=getattribute=getitem=setattr=setitem=pow=and=or=radd=rsub=rmul=rfloordiv=rtruediv=rmod=rpow=rand=ror=rxor=xor=iadd=isub=imul=ifloordiv=itruediv=imod=ipow=iand=ior=ixor=call=lt=eq=neq=gt=ge=le=req=rneq=rlt=ilt=rle=ige=rge=ieq=ineq=ile=rgt=igt=print;pos=lambda s:print(end=' ');invert=lambda s:print();neg=lambda s:print(' ');str=lambda s:print("print('...')")or'print(...)'

#

ideally, anything you can do to an instance prints something

fleet bridge
#

object.__str__ uses object.__repr__

restive void
#

Maybe use a metaclass' getattr?

fleet bridge
#

no, it wont initialise method's slots

#

x.__getitem__(...) will work, but x[...] wont

solemn jungle
#

it converts every number from 1 to 4000 to roman numerals

#

then the exec function execute like MMXXII=2022

weak shuttle
solemn jungle
#

sorry i dont code bots

cloud fossil
sick hound
sly root
#

genius, f-string that has only one item

fleet bridge
#
>>> dis('f"{x}"')
  1           0 LOAD_NAME                0 (x)
              2 FORMAT_VALUE             0
              4 RETURN_VALUE
solemn jungle
#

!e

exec("""π=print;ρ=range

φ=λξ:1ηξ<2εφ(ξ-1)+φ(ξ-2)
ζνορ(20):π(φ(ν))

""".replace('λ','lambda ').replace('η',' if ').replace('ε',' else ').replace('ζ','for ').replace('ο',' in '))
night quarryBOT
languid hare
#

i mean

#

i guess

rich hound
#

!e

print((len("RATIO")**(int([]==[])/int(int("what the fuck"!="am i doing")*len("with")-2))+int(len("my life")-6))/int(len("...")-1))
night quarryBOT
#

@rich hound :white_check_mark: Your eval job has completed with return code 0.

1.618033988749895
sly root
fleet bridge
errant crescent
rich hound
#

yes

#

well done

#

i knew what it did

#

just wanted to over complicate it

errant crescent
# rich hound yes

And this was all using the phrase "RATIO what the fuck am i doing with my life" 🙃

rich hound
#

yes

errant crescent
rich hound
#

but its true

errant crescent
rich hound
#

where.

torn oak
#
# Create a program that will allow a user to enter in ten numeric test grades. Then it drops the lowest two test grades and finds the average. 
# 
# Requirements:
# 
# Prompt the user for ten test scores from 0 - 100
# Do not allow numbers out of that range
# Drop the lowest two scores and find the average
# Output the average to the user.
# i need to do that

print(sum(sorted([(a if ((a := int(input(f"Enter your {i + 1}{'th' if i + 1 > 3 else ('rd' if i + 1 == 3 else ('nd' if i + 1 == 2 else 'st'))} number > ")))) <= 100 else exit("Numbers over 100 are not allowed.")) for i in range(10)])[2:])/8)```
#

uhhh clean, I never really used .get tbh

#

I love it

sick hound
#

I love this channel

errant crescent
#

Oh, lol. You already answered that Q.Q

fleet bridge
#

ive implemented stdout coloring

solemn knoll
fleet bridge
#
  1. wrapped sys.stdout
  2. used pygments, my style and lexer to color text
  3. changed sys.displayhook to pprint
#

i can share code, but it is really bad

finite blaze
#

What's interesting going on in the esoteric python world currently?

#

Tldr, what are you guys working on?

indigo dock
#

any alternatives to OS and Subprocess libraries?

proper vault
#

for what purpose?

rapid sparrow
#

well I successfully screwed myself over

#
>>> import main
KeyError called: args=('main',) kwargs={}
Calling my_excepthook on KeyError
Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 175, in _get_module_lock
OSError called: args=(2, 'No such file or directory', '<frozen importlib._bootstrap>') kwargs={}
Calling my_excepthook on OSError
Traceback (most recent call last):
  File "/data/media/0/pythonrc.py", line 433, in my_excepthook
    return old_excepthook(exctype, value, traceback)
  File "<stdin>", line 1, in on_exception
OSError called: args=(2, 'No such file or directory', '<stdin>') kwargs={}
Calling my_excepthook on OSError
...
File "<stdin>", line 1, in on_exception
Fatal Python error: _Py_CheckRecursiveCall: Cannot recover from stack overflow.
Python runtime state: initialized

Current thread 0x0000007ff7ce7010 (most recent call first):
  File "<stdin>", line 1 in <lambda>
  File "/data/media/0/pythonrc.py", line 433 in my_excepthook
  File "<stdin>", line 1 in on_exception
  File "<stdin>", line 1 in <lambda>
  File "/data/media/0/pythonrc.py", line 433 in my_excepthook
  File "<stdin>", line 1 in on_exception
  File "<stdin>", line 1 in <lambda>
File "/data/media/0/pythonrc.py", line 433 in my_excepthook
  File "<stdin>", line 1 in on_exception
  File "<stdin>", line 1 in <lambda>
  ...
zsh: abort (core dumped)  python3
#

that was my attempt to hook the __init__ method of all exception types

#

so I won't lose exceptions that get thrown in async code

#

🤦‍♂️

#

using fishhook

#

now it's not saved my python histfile.. serves me right for trying to do something with exceptions, I suppose

languid hare
#

oof

rapid sparrow
#

whenever I try to do something esoteric with exceptions or reprs, this is inevitably what awaits

#

lol

languid hare
#

awaits

#

ba dum tss

fleet bridge
#

!e

z,n,o=' \n1';[(print('#'*a+' '*b,end=c))for a,b,c in zip(map(int,'115113113414'+o*16+'54'+o*9+'4'+o*22+'55531131154'),map(int,'2004552111402044424202020420014424000201420204442400020204202000160212000'),z*11+n+z*15+n+z*14+n+z*16+n+z*12+n,)]
night quarryBOT
#

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

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

🥳

floral meteor
floral meteor
#

!e ```py
{
print(f"assigned {x} to x") for x in [69]
}

night quarryBOT
#

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

assigned 69 to x
floral meteor
#

actually I think that has it's own local namespace, so...

#

!e ```py
for x in [69]:{
print(f"assigned {x} to x")
}
print(x, 'is still assigned to x')

night quarryBOT
#

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

001 | assigned 69 to x
002 | 69 is still assigned to x
floral meteor
#

this is a subtle way to avoid =

#

hol' up

#

I guess that's what happens when i import externally located code

#

i didn't know onedrive could be a module

#

this is almost comical

languid hare
languid hare
#

nice

vague cairn
night quarryBOT
fleet bridge
#

it is sitecustomize.py

#

also it slows python startup time from ~25ms to ~100ms

vague cairn
#

If I import it, from the interpreter it changes the color of the prompt, and pretty much blocks output. what am I doing wrong? you want me to drop it in /site_packages under the name sitecustomize.py?

fleet bridge
#

because it is code for sitecustomize module

vague cairn
#

Cool, that got it.

#

I removed TypeGuard and underscore_numbers=True, to get it to work on my version of python, but anyway. Neat stuff.

vague cairn
#

And I added: ```py
if not 'idlelib' in sys.modules:
print('sitecustomize.py: Not in idle, console highlight enabled.')

on line 6 and indented the rest...
arctic elm
devout quest
#

If anyone here is knowledgeable in obfuscating Python, please DM me, I have a few questions I would like to ask c:

last locust
#

Then everyone can see and people will know if they're able to help

sick hound
#

hello guys

#

i'm new to Python and i am assigned a task to extract time from a given time range this is as follows:

#

lets say a person is working in a company he started a work at start_time and end_time between these duration i have to extract how much hours does this man has worked during morining hours, evening hours and night hours.

glad spade
#

Hi Guys

fleet bridge
#

@zinc aurora crossposting here 👆

snow beacon
floral meteor
#

yeah this probably is the worst place for someone new to python to be. This place can give you nightmares if you're not equipped with advanced knowledge of the inner workings of python

errant crescent
restive void
#

s/deltatime/timedelta/

errant crescent
#

also, a quick esoteric code for validating inputs -

while not (k := input("...")).isnumeric():
   print("Invalid Input")

print(f"{k=:^8}is a number!")
torn oak
#

!e
k = 2
print(f"{k=:^8}is a number!")

night quarryBOT
#

@torn oak :white_check_mark: Your eval job has completed with return code 0.

k=   2    is a number!
torn oak
#

!e
print(f"{'test'=:^13}")

night quarryBOT
#

@torn oak :white_check_mark: Your eval job has completed with return code 0.

'test'=    test     
torn oak
#

@errant crescent what does that do , can u maybe explain? D:

prisma coral
#

@torn oak The k= writes the literal text of k= into the string, and then put the value of k after. The 8 says how wide the section after that = sign should be (so the 2 bit is 8 chars long). Finally, the ^ says to center that value of k within that 8 char section

torn oak
#

!e

print([a := '', [(a := f'{a}{i}{__import__("random").choice(["+", "-", "/", "*"])}') for i in [__import__("random").randint(1, 9) for _ in range(5)]], a[:-1]][2])```
night quarryBOT
#

@torn oak :white_check_mark: Your eval job has completed with return code 0.

9*2*7+3/6
torn oak
#

!e

print([a := '', [(a := f'{a}{i}{__import__("random").choice(["+", "-", "/", "*"])}') for i in [__import__("random").randint(1, 9) for _ in range(10)]], a[:-1]][2])```
night quarryBOT
#

@torn oak :white_check_mark: Your eval job has completed with return code 0.

9-7*3/3-2+9-5/4-8*8
torn oak
#

it works yay

wanton flame
#

Any tips for how I can further golf this? (not counting variable names)

    def line(x0: int, y0: int, x1: int, y1: int) -> Generator[int]:
        """
        Naive solution
        Bresenham's Line Algorithm, used for diagonals
        """
        deltax = x1 - x0
        dxsign = int(abs(deltax) / deltax)
        deltay = y1 - y0
        dysign = int(abs(deltay) / deltay)
        deltaerr = abs(deltay / deltax)
        error = 0
        y = y0
        for x in range(x0, x1, dxsign):
            yield x, y
            error = error + deltaerr
            while error >= 0.5:
                y += dysign
                error -= 1
        yield x1, y1

which I've cut down to:

r_,i_,a_=range,int,abs # used elsewhere in not shown code, so is a reduction
def _L(x0,y0,x1,y1,e=0):
  d=[x1-x0,y1-y0]
  de=a_(d[1]/d[0])
  d=[i_(a_(_)/_)for _ in d]
  for x in r_(x0,x1,d[0]):
    yield x,y0
    e+=de
    while e>=0.5:
      y0+=d[1]
      e-=1
  yield x1,y1
errant crescent
errant crescent
# wanton flame Any tips for how I can further golf this? (not counting variable names) ```py ...

Use magic math to shrink things down -

def line(x0: int, y0: int, x1: int, y1: int) -> Generator[int]:
        """
        Naive solution
        Bresenham's Line Algorithm, used for diagonals
        """
        deltax = x1 - x0
        dxsign = int(abs(deltax) / deltax)
        
        deltay = y1 - y0
        dysign = int(abs(deltay) / deltay)
        
        deltaerr = abs(deltay / deltax)
        
        const_err = floor(deltaerr)
        deltaerr %= 1
        
        y = y0
        for x in range(x0, x1, dxsign):
            yield x, y
            
            y += dysign * (const_err + floor(deltaerr * i))
        yield x1, y1 
def line_compact(x0: int, y0: int, x1: int, y1: int) -> Generator[int]:
        """
        Naive solution
        Bresenham's Line Algorithm, used for diagonals
        """
        
        delta: float = abs((y1 - y0) / (x1 - x0)))
        const_err: int = floor(deltaerr)
        delta %= 1
        
        # from numpy import arrange
        
        cnv = (1, -1)
        x_axis = range(x0, x1, cnv[x0 > x1])
        y_axis = [floor(n + const_err + delta * i) for i, n in enumerate(range(y0, y1, cnv[y0 > y1]))]
        
        for x, y in zip(x_axis, y_axis):
            yield x, y     
        yield x1, y1 
errant crescent
# errant crescent Use ~~_magic_~~ math to shrink things down - ```py def line(x0: int, y0: int, x1...

Although when I look at it now ; I can see that there is no need for const_err, just use the entire delta instead.

You could also do x1+1 and y1+1 to include them in the range. However this may offset the final point.

@wanton flame

from math import floor

def line_compact(x0: int, y0: int, x1: int, y1: int) -> Generator[int]:
        """
        Naive solution
        Bresenham's Line Algorithm, used for diagonals
        """
        
        delta: float = abs((y1 - y0) / (x1 - x0)))
        # from numpy import arrange
        
        cnv = (1, -1)
        x_axis = list( range(x0, x1, cnv[x0 > x1]) )
        y_axis = [floor(cnv[y0 > y1] + delta * i) for i range(len(x_axis))]
        
        yield from zip(x_axis, y_axis)
        yield x1, y1 
#

oh right! I was so focused on the math, I didn't notice O.o

#

nvm

#

discord is wrapping my code, making things look funky

#

for a sec I though I didn't remove the old loop.

#

what elements?

#

Hmm...

#

Oh, I know why.
I accidentally though the constraints of error were between 0 - 1
after checking again, I see that it can go between -0.5 - 1.

Edit: It was also using separate values for both lists. e.g. x axis could be 6 elements long, while y axis might only be 4. Hence, the difference in the final output length.

#

give me a sec. imma fix this.

wanton flame
#

the algo is known to not work with 'steep' lines, for this data we can assert that all input will have a slope of 1 or -1 aka pure diagonal

torn oak
#

working hopefully soon™️

torn oak
#
print([a := int(input('Amount of numbers > ')), nums := [str(__import__("random").randint(1, 9)) for _ in range(a)], combo := list(__import__('itertools').product(["/", "*", "+", "-"], repeat=a)), nums :=  list(__import__('itertools').permutations(nums)), f := [([]) for _ in range(len(combo))], [[[(f[i].append([(l,n) for l,n in zip(n, c)])) for c in combo] for n in nums] for i in range(len(combo))], f := [''.join([list(__import__('itertools').chain.from_iterable(b))][0])[:-1] for b in list(__import__('itertools').chain.from_iterable(f))], g := [], r := [], generated := [], [([g.append(s := eval(b)), r.append([s, b])] if type(eval(b)) == int else '') for b in set(f)], [((generated.append(h)) if (h > 0 and r.count(h) == 1) else '') for h in set(g)], [sorted(set(g)), sorted(r), generated]][-1])```
#

not finished D:

errant crescent
#

!e
k = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.8]
n = [(int(i), i) for i in k]
print(n)

errant crescent
#

Well, Its sort of fixed for now... it should work for ±1 slopes, and it does get pretty close to the original logic.

I think this is as far as I could get writing on the phone, without even a pen or a piece of paper yert

 

In order to get the exact logic,
You might need to round the initial deviation then shift everything by -0.5 (to fix the original -1 offset, changing the difference from -0.5 - 0.5 to -1 - 0).

Afterwards either divide by 0.5 or something, to get the usual offset that would happen if you had used the original logic.

Finally substract that from the calculations in the loop, or do some other operations. pithink
(Some bitshifts operations and floor division might be of use).

golden finch
#

how can I get the current frame in one expression w/o imports?

fleet bridge
#

__import__('sys')._getframe(0)

sly root
#
for i,b in l([7,6,1,2,0]):
...   print(i,b)
...
7 6
6 5
5 5
4 4
3 4
2 4
1 2```
arctic elm
torn oak
#
print([a := int(input('Enter amount of nums > ')), nums := [str(__import__("random").randint(1, 9)) for _ in range(a)], combo := list(__import__('itertools').product(["/", "*", "+", "-"], repeat=a)), '''nums :=  list(__import__('itertools').permutations(nums))''', f := [([]) for _ in range(len(combo))], [[(f[i].append([(l,n) for l,n in zip(nums, c)])) for c in combo] for i in range(len(combo))], f := [''.join([list(__import__('itertools').chain.from_iterable(b))][0])[:-1] for b in list(__import__('itertools').chain.from_iterable(f))], g := [], r := [], generated := [], [([g.append(s := eval(b)), r.append([s, b])] if type(eval(b)) == int and eval(b) > 0 else '') for b in set(f)], [((generated.append(h)) if (h > 0 and r.count(h) == 1) else '') for h in set(g)], [sorted(set(g)), sorted(r), generated]][-1])```
golden finch
#

without imports

languid hare
#

!e

class MagicNamespace(dict):
    _getFailure = object()
    MagicType = object()
    
    def __init__(self, initial=None):
        self._dict = initial or {
            "__name__": "Magic Namespace"
        }

    def __setitem__(self, key, value):
        self._dict[key] = value
            
    def __getitem__(self, key):
        get_res = self._dict.get(key, MagicNamespace._getFailure)
        if (get_res == MagicNamespace._getFailure):
            self._dict[key] = self.MagicType
            
        return self._dict[key]
    
class MagicEnumMeta(type):
    @classmethod
    def __prepare__(mcs, name, bases):
        return MagicNamespace()
        
    def __new__(mcs, name, bases, namespace, **kwargs):
        
        enum = super().__new__(mcs, name, bases, namespace, **kwargs)
        enum.__repr__ = lambda self: self._key
        
        if not isinstance(namespace, MagicNamespace):
            return enum
        
        for key, value in namespace._dict.items():
            if value is MagicNamespace.MagicType:
                inst = enum()
                inst._key = key
                setattr(enum, key, inst)
        return enum
    
class MagicEnum(metaclass=MagicEnumMeta):
    def __init__(self):
        raise NotImplementedError("Enum Instantiation")
    
class Colors(MagicEnum):
    RED
    BLUE
    GREEN
    
print(Colors.RED == Colors.BLUE) #False
print(Colors.GREEN == Colors.GREEN)  #True
night quarryBOT
#

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

001 | False
002 | True
languid hare
#

imagine using enum auto()

golden finch
#

this is very cheaty but I'll allow it

#

what's the 100th subclass of object on your machine?

#

I have never even encountered that before

#

nice loophole though

torn oak
#

I love oneliners

#

its unreal this is so hot

golden finch
#

love how they added whitespace to this abominations

#

for research purposes I need an expression containing no lambdas which gives me functionType

fleet bridge
#

it returns wrong frame

#

it returns frame of generator expr, not outer frame

#

!e


import sys
print(next(getattr(c, f).__globals__['sys']._getframe(0) for c in ().__class__.__base__.__subclasses__()for f in dir(c)if isinstance(getattr(c, f, None), type(lambda: None)) and'sys' in getattr(c, f).__globals__))
print(next(getattr(c, f).__globals__['sys']._getframe(1) for c in ().__class__.__base__.__subclasses__()for f in dir(c)if isinstance(getattr(c, f, None), type(lambda: None)) and'sys' in getattr(c, f).__globals__))
print(sys._getframe(0))
night quarryBOT
#

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

001 | <frame at 0x7efe1e5b09f0, file '<string>', line 2, code <genexpr>>
002 | <frame at 0x7efe1e5b9000, file '<string>', line 3, code <module>>
003 | <frame at 0x7efe1e5b9000, file '<string>', line 4, code <module>>
fleet bridge
#

=> you should call ._getframe(1)

languid hare
golden finch
#

I'll try it

languid hare
#

hmm

#

what's this for

golden finch
#

truly anonymous lambda

#

with recursion

languid hare
#

that's

#

cursed

golden finch
#

yeah

#

so far

#
(lambda n:eval('type(lambda:0)')([i for i in __import__('sys')._getframe().f_back.f_code.co_consts if isinstance(i,type(__import__('sys')._getframe().f_back.f_code))][0],globals()))(3)
#

it can actually be golfed now with your hint though

#
(lambda n:eval('type(lambda:0)')([i for i in __import__('sys')._getframe().f_back.f_code.co_consts if isinstance(i,eval('type((lambda:0).__code__)'))][0],globals()))(3)

almost there

golden finch
languid hare
#

heh

restive void
golden finch
#

!e

(lambda n:eval('type(lambda:0)')([i for i in __import__('sys')._getframe().f_back.f_code.co_consts if isinstance(i,eval('type((lambda:0).__code__)'))][0],globals())(n-1)+eval('type(lambda:0)')([i for i in __import__('sys')._getframe().f_back.f_code.co_consts if isinstance(i,eval('type((lambda:0).__code__)'))][0],globals())(n-2)if n>1 else n)(3)

tried to make fibonacci, not sure where I messed up

night quarryBOT
#

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

[No output]
golden finch
#

yeah and there's that too

sly root
golden finch
#

smart, still a loophole

sly root
sly root
#

but idk if load_module counts as import too

golden finch
fleet bridge
#

!e

function = ().__class__.__base__.__subclasses__()[32]
print(function)
assert type(lambda: ...) is function
night quarryBOT
#

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

<class 'function'>
fleet bridge
#

@golden finch

golden finch
#

nice

fleet bridge
#

or object.__subclasses__()[32]

#

order of initialization of builtin types changes very rarely

#

so this code should work almost always

golden finch
#

thanks

floral meteor
#

delicious!

#

I usually try to run a search by subclass name to get the index rather than hardcoding it, just in case

rapid sparrow
sly root
torn oak
#

Okay, so I ended up with this:

print([a := int(input("How many numbers > ")), nums := [str(__import__("random").randint(1, 9)) for _ in range(a)], combo := list(__import__('itertools').product(["/", "*", "+", "-"], repeat=a)), f := [([]) for _ in range(len(combo))], [[(f[i].append([(l,n) for l,n in zip(nums, c)])) for c in combo] for i in range(len(combo))], f := [''.join([list(__import__('itertools').chain.from_iterable(b))][0])[:-1] for b in list(__import__('itertools').chain.from_iterable(f))], g := [], r := [], generated := [], [([g.append(s := eval(b)), r.append([s, b])] if type(eval(b)) == int and eval(b) > 0 else '') for b in set(f)], [((generated.append(i)) if [it[0] for it in sorted(r)].count(i[0]) == 1 else '') for i in sorted(r)], generated][-1])```
#

how could I optimize this

fleet bridge
ripe narwhal
#

Hi I need some help with a python project