#esoteric-python

1 messages ยท Page 24 of 1

vast wave
#

K might as well be out of the sandbox

#

!e exec(type((lambda:0).__code__)(0, 0, 0, 0, 1, 0, b'\x97\x00t\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00d\x02\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00d\x00S\x00', ("hi chat",), ("print",), (), "", "", "", 0, b"", b""))

night quarryBOT
#

@vast wave :warning: Your 3.11 eval job has completed with return code 139 (SIGSEGV).

[No output]
vast wave
#

hm

vast wave
rough moat
#

i found this online ๐Ÿ˜ญ

versed eagle
#

fun

low lynx
#

btw the aoc code golfs are available again for a short period of time

#

so if any of you guys want to archive certain golfs, now's the time to go grab them

sick hound
#

where

#

btw why does this channel/type of code exist

low lynx
#

fun

sick hound
#

Golfing brainf looks fun

vast wave
sick hound
#

?

arctic skiff
#

Is there any pythonfuck?

#

Like javascriptfuck

meager zinc
# sick hound Golfing brainf looks fun

!e This can likely be shorter```py
p="++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."
s=[i:=0];c=''
for o in p:c+=' '*i+[f'i+=1\n{" "i}if i>=len(s):s+=[0]','i-=1','s[i]+=1','s[i]-=1','print(end=chr(s[i]))','s[i]=ord(import("sys").stdin.read(1))','while s[i]:','s','']['><+-.,['.find(o)]+'\n';i+=(92-ord(o))(o in'][')
exec(c)

night quarryBOT
#

@meager zinc :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello World!
meager zinc
#

That one has an unlimited stack size, which is atypical so it can be shortened by removing that feature too

versed eagle
#

got a shorter one
.__()excmhrlnasd

#

shorter one
()exlchrbo+~

versed eagle
earnest wing
#

You can reduce python 2 to exc"%=\n and python 3 to exc"%0()

versed eagle
#

that's quite interesting

#

i forgot about printf style formatting existing in python

sly ibex
#

hey guys
open(0).readlines()
is just for esoteric codes or is common to see them in normal codes i hope you can get my question

versed eagle
#

that reads from stdin until it reads an EOF

agile meteor
#

python isnt bad

versed eagle
#

ah. you forgot __annotations__.

#

everyone always forgets __annotations__ :(

ruby idol
versed eagle
#

this is not the channel you're looking for

ruby idol
#

Oh

#

Welp

versed eagle
#

this is for esoteric python

ruby idol
#

Ye lol

#

My enhlish bad

meager zinc
# versed eagle iirc, brainfuck officially is meant to have a stack size of 30000

Yes, I know, but I was playing with it and I didn't like it for certain things (recursive stuff in particular). Here is a better optimized version:

p="++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."
s=[i:=0]*30000;c=''
for o in p:c+=' '*i+['i+=1','i-=1','s[i]+=1','s[i]-=1','print(end=chr(s[i]))','s[i]=ord(open(0).read(1))','while s[i]:','s','']['><+-.,['.find(o)]+'\n';i+=(92-ord(o))*(o in'][')
exec(c)
#

rewriting it as a join might be shorter

#

I need to try it

#

here is that:

p="++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."
s=[i:=0]*30000
exec(''.join(' '*i+['i+=1','i-=1','s[i]+=1','s[i]-=1','print(end=chr(s[i]))','s[i]=ord(open(0).read(1))','while s[i]:','s','']['><+-.,['.find(o)]+(0*(i:=i+(92-ord(o))*(o in']['))or'\n')for o in p))
#

prob longer

#

@quartz wave might want to take a look at this

rugged sparrow
meager zinc
#

Oh interesting

#

it is officially infinitely long

rugged sparrow
#

and each cell is an unsigned 8bit digit

meager zinc
#

and stopping negative numbers is more tricky

#

i=(i or 0)%256

rugged sparrow
#

!e py print(-1%256)

night quarryBOT
#

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

255
meager zinc
#

Oh yeah I don't need to worry about it

rugged sparrow
#

ya

meager zinc
#

let me go back to the one that has an unlimited stack

#
p="++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."
s=[i:=0];c=''
for o in p:c+=' '*i+[f'i+=1\n{" "*i}if i>=len(s):s+=[0]','i-=1','s[i]+=1','s[i]-=1','print(end=chr(s[i]))','s[i]=ord(open(0).read(1))','while s[i]:','s','']['><+-.,['.find(o)]+';s[i]%=256\n';i+=(92-ord(o))*(o in'][')
exec(c)
#

should work as intended

versed eagle
#

cereal has a collection

#

of brainfuck interpreters

meager zinc
#

thats wayyyy too verbsoe

versed eagle
#

possibly forked from someone else but

#

all i know is cereal has it

versed eagle
#

but the idea is more how they do it, not how short it is

#

it's easy up shorten once you've gotten a good idea working

meager zinc
versed eagle
#

anyway im gonna go back to being a sleeping gremlin since im not supposed to be awake rn

#

gn

meager zinc
#

gn

dry mirage
#

@rugged sparrow finally got my source compare working blobmelt

rugged sparrow
#

Noice

rugged sparrow
#

Now if you can make it autogenerate structure definitions that would be cool

solid basalt
#

Is there any specific reason that range implements a count method? Won't the result always be 0 or 1?

#
 |  count(...)
 |      rangeobject.count(value) -> integer -- return number of occurrences of value
maiden blaze
#

i think its part of the Sequence abc

solid basalt
#

that checks out

#

!e

from collections.abc import Sequence
print(Sequence.count.__doc__)
night quarryBOT
#

@solid basalt :white_check_mark: Your 3.11 eval job has completed with return code 0.

S.count(value) -> integer -- return number of occurrences of value
dry mirage
#

count is equality, not identity. That optimization can't be made

#

!e

class Foo:
    def __eq__(self, other):
        return True
        
r = range(100)
print(r.count(Foo()))
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

100
dry mirage
#

there is actually a fast path for bool / int exact items though, in that case it returns 1 or 0 without iterating the whole thing

sick hound
#

What other stuff are there that would be fun to golf?

low lynx
#

lots of things you could golf

#

for example a function that calculates the nth digit of pi in decimal

solid basalt
#

I was only thinking in terms of counting ints

dry mirage
#

yeah I had an idea before to optimize (float) in range() comparison before

#

since it took a very long time to return False, but apparently you can't just optimize it because someone may have a custom object that is equal to one of the range elements and therefore in is true

quartz wave
fleet bridge
#

discord has very bad highlighting rules

sick hound
#

They don't fix issues with individual lexers

golden finch
#
import ctypes

globals_type=ctypes.py_object.from_address(id(globals())+8)
class new_globals(dict):
    __slots__=()
    def __getitem__(self,name,bound1=dict,globals_type=globals_type):
        try:
            globals_type.value = bound1
            combinators = {
                'S': lambda x:lambda y:lambda z:x(z)(y(z)),
                'K': lambda x:lambda y:x,
            }
            if name[0] in locals()['self'] or name[0] in combinators:
                result=combinators[name[0]]
                for combinator in name:
                    if combinator in combinators:
                        result=result(combinators[combinator])
                    elif combinator in locals()['self']:
                        result=result(locals()['self'][combinator])
                    else:
                        return self[name]
                return result
            return self[name]
        finally:
            globals_type.value=__class__
globals_type.value = new_globals

I = SKK

U = SII

U(print) # <built-in function print>

print(I(1)) # 1

SKI combinator calculus

#

(heavy inspiration from this channel)

fleet bridge
#

Same question

#

self should work

earnest wing
#

name lookup is builtins -> locals -> globals, so it intuitively should work

#

but I haven't tested myself

last locust
#

It's locals, enclosed, globals, builtins

#

Builtins is the last thing that's checked, not the first

earnest wing
#

okay right

#

makes more sense

last locust
#

And you missed the enclosing scope, which is what nonlocal is for

#

!d nonlocal

night quarryBOT
#

7.13. The nonlocal statement


nonlocal_stmt ::=  "nonlocal" identifier ("," identifier)*
``` The [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#nonlocal) statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

Names listed in a [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#nonlocal) statement, unlike those listed in a [`global`](https://docs.python.org/3/reference/simple_stmts.html#global) statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).
earnest wing
#

yes i'm aware

fleet bridge
#

Why __class__ variable is not compiled to LOAD_CONST <class 'Foo'> ?

#

Because class must be places in co_consts tuple at method creation time, and at this moment class doesn't exist

#

Thank you

lucid lake
#

What is esosteric python? Can someone give a summary?

earnest wing
#

I would describe it as "anything that goes deliberately and shamelessly against the grain of mainstream python programming"

#

also the channel topic I guess

dry mirage
#

it's sort of like a cell / closure variable

night quarryBOT
#

Python/compile.c lines 1745 to 1754

/* Cook up an implicit __class__ cell. */
int res;
assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
res = PyDict_SetItem(u->u_cellvars, &_Py_ID(__class__),
                     _PyLong_GetZero());
if (res < 0) {
    compiler_unit_free(u);
    return 0;
}```
fleet bridge
dry mirage
#

it just can't be known at the time when constants are compiled

astral rover
#

it cant be known ever can it?

dry mirage
#

you sort of build the function code first, then you can find out if it is in a class

astral rover
#

cause class in subclasses is the subclass

dry mirage
#

!e

class Foo:
    def abc(self):
        print(__class__)
        
class SubFoo(Foo):
    pass

SubFoo().abc()
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

<class '__main__.Foo'>
astral rover
#

hmmm

#

i could have sworn i checked this for

#

!pep 673

night quarryBOT
#
**PEP 673 - Self Type**
Status

Accepted

Python-Version

3.11

Created

10-Nov-2021

Type

Standards Track

astral rover
#

cause the whole rationale behind not allowing Self in staticmethods atleast for me was that you couldnt ever have it always return the enclosing class

#

maybe im just misremembering though

dry mirage
#

when a class method returns a cls() instance the type checkers can infer the Self type

astral rover
#

Yeah but I thought I ran this test for staticmethods and just normal methods and concluded that since there was no way to access the current enclosing class in a staticmethod, there was no way that Self would ever work (inheritance wise)

#

I'm trying to load the thread I had for the pep but discord is being bad and is just hanging

quartz wave
astral rover
#

idk people must have just messed with it after finding it on typing-sig

quartz wave
#

then i shall also mess with it

turbid glade
#

@gleaming linden have u ever heard of clash of code?

gleaming linden
#

I've heard of it

#

but I haven't tried it before

turbid glade
#

it is cool

#

it is kinda like leet code

#

questions

#

but who can do it in least amount of code

#

join up

#

๐Ÿ™‚

gleaming linden
#

done

turbid glade
#

@gleaming linden

#

how did u get it in 35

gleaming linden
#
t,s=map(int,open(0))
print(t*s//60)
turbid glade
#
print(int((int(input()) / 60)*int(input())))
turbid glade
#

!d open

night quarryBOT
#

open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)```
Open *file* and return a corresponding [file object](https://docs.python.org/3/glossary.html#term-file-object). If the file cannot be opened, an [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised. See [Reading and Writing Files](https://docs.python.org/3/tutorial/inputoutput.html#tut-files) for more examples of how to use this function.

*file* is a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object) giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless *closefd* is set to `False`.)
gleaming linden
#

it opens a file

#

but open(0) is a special case which reads from stdin

turbid glade
#

oh

#

didn't know that

#

that's smart

#

@gleaming linden wanna go again

gleaming linden
#

sure

turbid glade
#

this is my favorite game mode

#

lol

gleaming linden
#

I need to learn pyth

turbid glade
#

@gleaming linden how do u do it

gleaming linden
#
print(sum(i*[3,5][i%2]for i in[*map(int,open(0))][1:]))
#

same thing with open(0)

turbid glade
#
print(sum((n*3, n*5)[n%2] for n in [int(input()) for _ in range(int(input()))]))
gleaming linden
#

[1:] to get rid of the first one

turbid glade
#

oh

#

bro

#

i was think a whole minute how did u do it

gleaming linden
#

I came up with a 56 in the first minute lol

turbid glade
#

๐Ÿ˜ฆ

gleaming linden
#

something like ```py
_,*n=map(int,open(0))
print(...)

turbid glade
#

oh

#

i need tto start using that

#

this time I will win

gleaming linden
#

22c lol

turbid glade
#

lol

#

can't do it shorter

#

impossible

gleaming linden
#

it would be like 2-3c in pyth

turbid glade
#

print(int(input())**2)

#

my code

#

@gleaming linden

#

lol

gleaming linden
#

yup same

turbid glade
#

๐Ÿ˜ฆ

#

this time I will win

gleaming linden
#

gg

turbid glade
#

@gleaming linden samething again

gleaming linden
#

yup

turbid glade
#

print(1000-int(input())*2)

gleaming linden
#

can't do 1e3 because floats

turbid glade
#

ya

gleaming linden
#

are there any harder ones?

turbid glade
#

but

#

not golf

gleaming linden
#

ah, sad

turbid glade
#

fr

#

hardest one

#

is reverse

gleaming linden
#

oof

turbid glade
#

thx for playing with me tho

gleaming linden
#

how about a normal one then?

turbid glade
versed eagle
#

huh

#

ive never heard of that before

versed eagle
#

why does co_consts contain None when None isn't used in the function?

#

seems like a waste of space

#

!e e.g.

f = lambda: "not None"
print(f.__code__.co_consts)
night quarryBOT
#

@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.

(None, 'not None')
versed eagle
#

there should be no None here

#

and yet there is

dry mirage
versed eagle
#

ah

#

fair

#

however, for a lambda that shouldnt be necessary?

#

since afaik lambdas have no way of implicitly returning

dry mirage
#

just not super worth it in general, extra None reference is just 8 bytes

calm loom
#

!e

def test():
    return "hi"

print(test.__code__.co_consts)
night quarryBOT
#

@calm loom :white_check_mark: Your 3.11 eval job has completed with return code 0.

(None, 'hi')
calm loom
versed eagle
calm loom
#

hm python always inserts None as the default return value whether u explicitly provide a return or not

#

thats cool

versed eagle
#

it shouldnt be necessary for lambda functions though

calm loom
#

yeh

dry mirage
#

could be possible to remove it for lambdas, yeah

vast wave
#

wait nvm im thinking of the wrong null

#

this is why

#

im sure none finds a way into lambdas as well

#

wait nevermind lambdas don't have a none anywhere

#

you're right

dry mirage
#

!e

from einspect import view

f = lambda: "not none"

view(f.__code__.co_consts).remove(None)

print(f())
print(f.__code__.co_consts)
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | not none
002 | ('not none',)
dry mirage
#

apparently still works if you remove the None from the tuple

vast wave
#

it shouldnt

#

LC 1 now points out of the tuple

#

when removing None

dry mirage
#

hm?

vast wave
#

!e ```py
from einspect import view

f = lambda: "not none"

view(f.code.co_consts).remove(None)

print(eval(f.code))
print(f.code.co_consts)

night quarryBOT
#

@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | not none
002 | ('not none',)
vast wave
#

the fuck

#

yeah no that shouldnt work

#

!e ```py
from einspect import view

f = lambda: "not none"

target = f.code.replace(co_consts=("not none",))
print(target.co_consts)

print(eval(target))

night quarryBOT
#

@vast wave :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).

('not none',)
vast wave
#

yeah

#

pretty sure that the fields on a code object are just for show, the actual value is cached

#

.replace() makes a new code object with the given params tho, that's why the previous one didn't segfault but this one did

dry mirage
#

the None did get removed, it still works because it's accessing the memory at index 1 which isn't freed

#

I guess there is no check for the size of co_const and they directly access the memory at index 1

#

so if we try to access None in that function it will be the string at index 0

earnest wing
dry mirage
#

!e

from einspect import view

f = lambda: "not none" + None

view(f.__code__.co_consts).remove(None)

print(f())
print(f.__code__.co_consts)
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | not nonenot none
002 | ('not none',)
earnest wing
#

might just be accessing the memory that used to be there

vast wave
#

using einspect might what fucks this one up

#

directly killing the pointer to None but not killing the reference to "not none" still being where it was before

dry mirage
#

so you can technically unpop a list by reverting ob_size back

#

!e

from einspect import view

ls = [1, 2, 3]
ls.pop()
ls.pop()
print(ls)

with view(ls).unsafe() as v:
    v.size += 2
    
print(ls)
night quarryBOT
#

@dry mirage :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | [1]
002 | [1, 2, 3]
vast wave
#

!e ```py
import base64 as b
import zlib, dis
exec(zlib.decompress(b.a85decode(b'GhRjND/\,^&H88.@I[c#g,'7UKdK\B9p>8Yp5L6=4s-o]O@6?^;"ltC^2@u>m8>1kND9D(SAsPCO=*&dQJm'Y1jFiNQJJE=3U%mZu"Ci:?nII@+$fL8M,4)X=Ii5@AB%?)"iqga95;[4R/>D4lF).3IC2#75AstE59.#=+N"[DC\\]e&3[>!\\IZA%9f!k,)Q#g4J@AYBB&*Zs3:RT1i9>V"=LThTt)"e_hnH1No:8\'3rSEbc^8eGP*\'/S=(/D4g=1="&l;-a%QQK8:LJ^5.Qh:^F:Z=Vds/Mdi7oBGpm0nh,A+5bu=>7^BK'Psr7hL0PQ0,>"m&^Q"pIPB6@k-^%9eg!<8O]]>jBMeW^jPdaa".5ZG^CfUBPX1%b6<#$2a[3C+AkWS8R2nr%bf-p#b4A;Gi]kZUr#5#X#s^"Ja$Xh[I;Nn4EEra5,M2T"]!.Wn^H+:23'l-0um&Pmu"7AhC/bNBMP/g?1TGH2ho0hneV5$&Co<JR$TLal-W&e\U+sHV<6n=hqW;8KHOMlRB\R9!b;;p2<RuY@6?::usu@CN9F-3R]n'8P2\/:,XQKk6.MLdt@9DZU;V);8Tlhn8>/bE+Ra;B9et_)@hFTuK1RP;bG0fp,pD_[6l(rU;Li1QA.UB%d!i;!0(nHkDuJ1,LR(r\8KVQ[Lg?9Y=:0t::,P"PJMVQik:=7\1D;@.tn3:C^nP20@YCUsTD1gB$e0Qd7gW4I\LrHJkPD'@]-MSOkbT'eNKh4G#U@[XT%GjDNh7r[n#tDXa!n3ojE'^HDF&gQNHs=rH3K1Qle3+F.6/is=8U(i@R&t[(E8HUEDVjQT6+!-_Ci1-Un;#Z/ALfB=RFnQ>"&Hh&7@=5raeikW/&61!hi0=TLZX8&W)c`),')A(#VF(o5ku:n)FHV&q"Z)f]V;B_>24^U"I%7#"16n8eXj+b2?M(^T&iJ5-@*c"@HS4i8U%kS".pqkjjK@.66JL-K\q-V4')))
a = Assembler()
nc = a.consts_create_or_get
i = a.insn
i("RESUME",0)
i("LOAD_CONST", nc("not null"))
i("RETURN_VALUE")
co = a.pack_code_object()
print(co.co_consts)
dis.dis(co)
print(eval(co))

night quarryBOT
#

@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | ('not null',)
002 |           0 RESUME                   0
003 |           2 LOAD_CONST               0 ('not null')
004 |           4 RETURN_VALUE
005 | not null
vast wave
#

its possible to not have none in it

dry mirage
#

well yeah if you manually provide the bytecode

#

but it might negatively affect speed to have that work in the compiler

vast wave
#

at that point just accept that its 1 byte

#

8 bits

#

no wait im stupid

#

fuck i need to retake comp sci

dry mirage
#

I suppose it could be 8 bits if we have 8 bit python ๐Ÿ‘€

sudden osprey
#

!e

def x():
    """test"""

print(x.__code__.co_consts)
night quarryBOT
#

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

('test', None)
versed eagle
#

oh interesting

#

why is it stored in co_consts though

sudden osprey
#

Not sure

versed eagle
#

if it's None, it just shouldnt be present

sudden osprey
night quarryBOT
#

Objects/funcobject.c line 157

PyObject *consts = code_obj->co_consts;```
versed eagle
#

ah

#

huh

#

that shouldn't be needed for lambdas though

sudden osprey
sudden osprey
#

Is there even any way of telling the difference other than the name lemon_thinking

quartz wave
versed eagle
#

oh nice

versed eagle
#

it doesn't actually remove the first thing

#

The compiler now removes all unused constants from code objects (except the first one, which may be a docstring).

quartz wave
#

ok maybe not

#

i'm gonna go test

#

yep

#

i'm gonna add a path in my modified cpython for that

#

fixed ```diff

  • // The first constant may be docstring; keep it always.
    
  • index_map[0] = 0;
    
  • // If it's a docstring, keep it.
    
  • index_map[0] = PyUnicode_Check(PyList_GET_ITEM(consts, 0)) ? 0 : -1;
    
#
>>> from dis import dis
>>> dis("lambda:2")
  0           0 RESUME                   0

  1           2 LOAD_CONST               0 (<code object <lambda> at 0x000001C93A4F7220, file "<dis>", line 1>)
              4 MAKE_FUNCTION            0
              6 RETURN_VALUE

Disassembly of <code object <lambda> at 0x000001C93A4F7220, file "<dis>", line 1>:
  1           0 RESUME                   0
              2 LOAD_CONST               0 (2)
              4 RETURN_VALUE
sudden osprey
#

Won't that break docstrings? When the function object is created how does it know if the first value is the docstring or not?

versed eagle
#

PyUnicode_Check checks if it's a string

quartz wave
sudden osprey
#

If there's no docstring, but you return a string

#

Won't that string be set as the docstring?

quartz wave
#

hmm

#

yep

kindred stone
#

getting started on esoteric, its pretty fun ๐Ÿ™‚

#

!e

f = lambda c, n: (lambda np: (exec(compile(c, "<string>", "exec"), np), np[n]))({})[1]

code = """
def fn():
    print("hello, world")
"""

fn = f(code, "fn")
fn()```
night quarryBOT
#

@kindred stone :white_check_mark: Your 3.11 eval job has completed with return code 0.

hello, world
night quarryBOT
#

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

001 | Hello world lol
002 | 12345
gusty dust
#
a = 2
b = 3
c = 4
a, b, c *= 2  # a => 4, b => 6, c => 8
  Cell In[4], line 1
    a, b, c *= 2  # a => 4, b => 6, c => 8
    ^
SyntaxError: 'tuple' is an illegal expression for augmented assignment

the fact that this fails makes me sad

#

i get why but

limpid spruce
languid hare
#

!e

, *= 2
night quarryBOT
#

@languid hare :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     , *= 2
003 |     ^
004 | SyntaxError: invalid syntax
languid hare
#

tragic

#

mm wait

#

!e

(,) *= 2
night quarryBOT
#

@languid hare :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     (,) *= 2
003 |      ^
004 | SyntaxError: invalid syntax
languid hare
#

!e

() *= 2
night quarryBOT
#

@languid hare :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     () *= 2
003 |     ^^
004 | SyntaxError: 'tuple' is an illegal expression for augmented assignment
languid hare
#

ok fair enough

vast wave
night quarryBOT
#

@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

None
vast wave
#

no it doesn't

#

sadge

#

!e ```py
from einspect import view
a = lambda: "big boobs"
v = view(a.code.co_consts)
del v[:]
v.extend(["the cat", "big boobs"])
print(a.code.co_consts)
print(a.doc)

night quarryBOT
#

@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | ('the cat', 'big boobs')
002 | None
fleet bridge
#

Yes. It is set once at function creation time, and you can set it to other value after function is created

kindred stone
#
def create_function(code_string: str, var_to_extract: str):
    code = compile(code_string, "<string>", "exec")
    namespace = {}
    exec(code, namespace)
    return namespace[var_to_extract]
#

its just a different way of executing code, similar to eval

sick hound
#

Hi there it's my first time posting on here but I was wondering if someone could help me with Pytorch specifically

lunar marsh
#

Esoteric Python request:
Find a way to override the assignment operator (=) by any means neccesary. Be it modification of the locals dictionary or some runtime hooking. Preferably portable (i.e work when passed between function calls and stack frames). By overriding I mean detecting an assignment and even prevent it, so for example

x=5
# override
x=4
print(x) # -> 5
fleet bridge
#

!e ```py
x = 4
ั… = 5
print(x)

night quarryBOT
#

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

4
fleet bridge
#

easy

lunar marsh
#

sneaky boi

meager zinc
versed eagle
#

ill be able to get on my computer then

#

i don't wanna type on mobile

meager zinc
#
from types import CodeType
from sys import _getframe, exit
import dis

orig = _getframe().f_code
code = orig.co_code

payload = list(code)

allow_assign = True
for idx, op in enumerate(code):
    if op == dis.opmap["STORE_NAME"] and orig.co_names[code[idx+1]] == "x":
        if allow_assign:
            allow_assign = False
        else:
            payload[idx] = dis.opmap["POP_TOP"]

exec(orig.replace(co_code=bytes(payload[176:])))
exit(0)
# Everything after this is the input code
x = 5
x = 4
print(x)

#

Works on my machine

#

@lunar marsh

lunar marsh
meager zinc
#

mhm

#

that's just a proof of concept and there are probably better ways

dry mirage
# lunar marsh Esoteric Python request: Find a way to override the assignment operator (=) by a...

!e

import ast
import inspect
import sys
from functools import cache

class Final:
    def __new__(cls, obj):
        stack = inspect.stack(1)
        c_stack = stack[1:]
        c_frame_info = c_stack[0]
        c_frame = c_frame_info.frame

        def _trace(frame, _event, _arg= None):
            info = inspect.getframeinfo(frame)
            node = ast.parse(info.code_context[0].strip())
            if isinstance(node.body[0], ast.Assign):
                raise SyntaxError(f"cannot assign to final variable {obj!r}")
            return _trace

        cls._enable_trace()
        c_frame.f_trace = _trace
        return obj

    @cache
    @staticmethod
    def _enable_trace() -> None:
        if not sys.gettrace():
            sys.settrace(lambda *args: None)

x = Final(100)
print(x)
x = 5
print(x)
night quarryBOT
#

@dry mirage :x: Your 3.11 eval job has completed with return code 1.

001 | 100
002 | Traceback (most recent call last):
003 |   File "/home/main.py", line 32, in <module>
004 |     x = 5
005 |         ^
006 |   File "/home/main.py", line 32, in <module>
007 |     x = 5
008 |         ^
009 |   File "/home/main.py", line 17, in _trace
010 |     raise SyntaxError(f"cannot assign to final variable {obj!r}")
011 | SyntaxError: cannot assign to final variable 100
... (truncated - too many lines)

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

lunar marsh
lunar marsh
dry mirage
#

you also have access to the caller dictionary

#

so you can check if x is bound to anything else via eval exec globals() and error as well

lunar marsh
meager zinc
#

the f_trace usage is pretty smart

#

I've seen it before in my testing but never really explored it

dry mirage
rugged sparrow
#

!e ```py
import sys

class Final:
slots = ['value']
def init(self, value):
self.value = value

frames = {}
def tracefunc(frame, event, arg):
for dct_name in ['f_globals', 'f_locals']:
mp = getattr(frame, dct_name)
for key, value in mp.items():
if isinstance(value, Final) and hasattr(value, 'value'):
frames.setdefault(frame, {}).setdefault(dct_name, {})[key] = value.value
for key, value in frames.get(frame, {}).get(dct_name, {}).items():
mp[key] = value
return tracefunc

sys.settrace(tracefunc)

def foo():
x = Final(100)
print(x, type(x))
x = 1
print(x, type(x))

foo()

night quarryBOT
#

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

001 | 100 <class 'int'>
002 | 100 <class 'int'>
rugged sparrow
#

doesn't seem to want to work for global scope but it works for locals

dry mirage
radiant anchor
#
fizzbuzz = lambda x: [
    div3 := x % 3 == 0,
    div5 := x % 5 == 0,
    result := "",
    div3 and [
        result := result + "fizz",
    ],
    div5 and [
        result := result + "buzz",
    ],
    result or [
        result := str(x),
    ],
    result,
][-1]

for i in range(1, 101):
    print(fizzbuzz(i))
#

proof that python supports braces instead of indentation, and that lambdas allow multiple lines :P

#

(you can also use set notation for the "if statements", as long your results are all hashable)

fleet bridge
#

i hate that

#

!e from __future__ import braces

night quarryBOT
#

@fleet bridge :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     from __future__ import braces
003 |     ^
004 | SyntaxError: not a chance
vast wave
#

what the hell

#

what does this mean

radiant anchor
#

there is no chance

#

of python supporting brace syntax

vast wave
night quarryBOT
#

@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

wrong
radiant anchor
#

!e

if 1 == 1: {
  right := {},
  print(right)
}
night quarryBOT
#

@radiant anchor :x: Your 3.11 eval job has completed with return code 1.

001 | {}
002 | Traceback (most recent call last):
003 |   File "/home/main.py", line 1, in <module>
004 |     if 1 == 1: {
005 |                ^
006 | TypeError: unhashable type: 'dict'
vast wave
night quarryBOT
#

@vast wave :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 2
002 |     right = {}
003 |     ^^^^^^^^^^
004 | SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
vast wave
#

oh right

quartz wave
night quarryBOT
#

@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

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

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

quartz wave
#

ok

#

sets are unordered ๐Ÿ˜”

versed eagle
#

you could use a dict

radiant anchor
#

you could have a dict with "line numbers"

versed eagle
#
   hashable_thingy:
   something,
   hashable_thingy:
   something_else,
}```
#

something like that

#

could be done

#

as long as you keep even numbers of stuff

#

and have every other line be hashable

#

shouldnt be too hard, yeah?

vast wave
#

!e ```py
@lambda :()
class a:pass
if 1 == 1: {
a:"something",
a:print("something else")
}

night quarryBOT
#

@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

something else
signal swallow
#

!e

night quarryBOT
#
Missing required argument

code

#
Command Help

!eval [python_version] <code, ...>
Can also use: e

Run Python code and get the results.

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

The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.

If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.

By default, your code is run on Python 3.11. A python_version arg of 3.10 can also be specified.

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

radiant anchor
night quarryBOT
#

@radiant anchor :white_check_mark: Your 3.11 eval job has completed with return code 0.

something else
mystic hull
#
i1 = [False, True, False, False, True, True, False, True, False, True, True, True, False, False, True, False, False, False, True, False, True, True, True, False, False, False, True, False, False, False, False, False, False, True, False, True, False, True, True, True, False, True, True, False, True, False, False, True, False, True, True, True, False, False, False, False, False, True, True, True, False, False, False, False]
i111 = ""
for i in i1: i2 = int(i); i111 += str(i2)
i11 = int(i111, 2);i1111 = i11.bit_length() + 7 // 8;i111111 = i11.to_bytes(i1111, "big");i11111 = i111111.decode();print(i11111)
#

!e

i1 = [False, True, False, False, True, True, False, True, False, True, True, True, False, False, True, False, False, False, True, False, True, True, True, False, False, False, True, False, False, False, False, False, False, True, False, True, False, True, True, True, False, True, True, False, True, False, False, True, False, True, True, True, False, False, False, False, False, True, True, True, False, False, False, False]
i111 = ""
for i in i1: i2 = int(i); i111 += str(i2)
i11 = int(i111, 2);i1111 = i11.bit_length() + 7 // 8;i111111 = i11.to_bytes(i1111, "big");i11111 = i111111.decode();print(i11111)
night quarryBOT
#

@mystic hull :white_check_mark: Your 3.11 eval job has completed with return code 0.

๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝMr. Wipp
mystic hull
#

lmao finally

night quarryBOT
#

:incoming_envelope: :ok_hand: applied mute to @sick hound until <t:1679246074:f> (10 minutes) (reason: duplicates rule: sent 4 duplicated messages in 10s).

The <@&831776746206265384> have been alerted for review.

calm loom
#

Ayyy

heavy ermine
#

!e import math; import numpy; sine = lambda from_, to_, amp_, step_: (math.sin(s * amp_) for s in numpy.arange(from_, to_, step_)); square = lambda from_, to_, amp_, step_: ((-1 if c <= 0 else 1) for c in sine(from_, to_, amp_, step_)); print(list(square(0, 4, 1, 0.1)));

night quarryBOT
#

@heavy ermine :white_check_mark: Your 3.11 eval job has completed with return code 0.

[-1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1]
eager ore
#
(
    lambda math, numpy: ...
)(
    __import__("math"),
    __import__("numpy")
)

@heavy ermine

eager ore
#

to avoid using semicolons

heavy ermine
#

uhhhh why lambda math, numpy: ...

eager ore
#

the math and numpy arguments are passed to your code, the ... part

#

then you can truly make it one line

heavy ermine
#

why just not use __import__

eager ore
#

it would save characters if you were using it a lot

heavy ermine
#

ok????? how so

eager ore
#

because it's easier to type math instead of typing __import__("math") each time

#

you can shorten it to just m

heavy ermine
#
import math as m;import numpy as n;...
eager ore
#

that's not one line though

heavy ermine
#

technically it is. there are no \n in this code

eager ore
#

that's cheating

heavy ermine
#

its not, technically

eager ore
#

in esoteric python it is

heavy ermine
#

ok...?

#

sir robber asked me to post it here so ig i just do it

versed eagle
#

(np:=__import__("numpy"),math:=__import__("math"))

#

somewhere in the beginning

#

of the function

low lynx
#

just have them as default arguments in the lambda

#

!e

f=lambda a, np=__import__('numpy'): np.array(a).T
print(f([[0, 1, 2], [3, 4, 5]]))
night quarryBOT
#

@low lynx :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | [[0 3]
002 |  [1 4]
003 |  [2 5]]
versed eagle
#

mm yeah

#

thats probably the best way to do it

bronze agate
#

!e

sum(print("test") or 0for _ in range(3))```
night quarryBOT
#

@bronze agate :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | /home/main.py:1: SyntaxWarning: invalid decimal literal
002 |   sum(print("test") or 0for _ in range(3))
003 | test
004 | test
005 | test
last locust
#

!e py foo = lambda n:print(sum(print(x,end='+='[i==len(n)-1])or x for i,x in enumerate(n))) foo([1,2,3]) foo([4,5,6])

night quarryBOT
#

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

001 | 1+2+3=6
002 | 4+5+6=15
last locust
#

Heh, neat

quartz wave
#

!e ```py
foo = lambda n:print('+'.join(map(str,n))+'=%d'%sum(n))
foo([1,2,3])
foo([4,5,6])

night quarryBOT
#

@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 1+2+3=6
002 | 4+5+6=15
quartz wave
#

ok

last locust
#

!e py foo = lambda n:print(sum(print(x,end='=+'[i<len(n)-1])or x for i,x in enumerate(n))) foo([1,2,3]) foo([4,5,6])

night quarryBOT
#

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

001 | 1+2+3=6
002 | 4+5+6=15
last locust
#

That's 1 char shorter by swapping the += to =+ and then i<len(n)-1 instead of i==len(n)-1

quartz wave
#

ok

fleet bridge
versed eagle
#

you can save 2 chars per invocation by using *args rather than taking a list

versed eagle
sick hound
#

!e

f = lambda n: print(f"{'+'.join(map(str, n))}={sum(n)}")
f([1,2,3])
f([4,5,6])
night quarryBOT
#

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

001 | 1+2+3=6
002 | 4+5+6=15
pure dew
#

!e ```py
f = lambda n:print(eval(f"f'{{{'+'.join(map(str,n))}=}}'"))
f([4,5,6])
f([1,2,3,4,5,6,7,8,9])

night quarryBOT
#

@pure dew :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 4+5+6=15
002 | 1+2+3+4+5+6+7+8+9=45
pure dew
#

a lil bit longer but way cooler

past plank
#

!e you guys are way overcomplicating it ```py
def f(n):print('+'.join(map(str,n))+f'={sum(n)}')

f([4,5,6])
f([1,2,3,4,5,6,7,8,9])```

night quarryBOT
#

@past plank :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 4+5+6=15
002 | 1+2+3+4+5+6+7+8+9=45
past plank
#
f=lambda n:print(eval(f"f'{{{'+'.join(map(str,n))}=}}'")) # 57
f=lambda n:print(f"{'+'.join(map(str, n))}={sum(n)}") # 53
def f(n):print('+'.join(map(str,n))+f'={sum(n)}') # 49```
#

it's pointless to use a lambda if you don't need to return anything py f=lambda a,b: def f(a,b):

#

aside from the function definition though, this improvement is obvious py print(f"{'+'.join(map(str, n))}={sum(n)}") print('+'.join(map(str,n))+f'={sum(n)}')

versed eagle
versed eagle
#

you're reinventing the wheel :P

meager zinc
#

Adds two spaces, but removes two chars:

print('+'.join(map(str,n))+f'={sum(n)}')
print('+'.join(map(str,n)),'=',sum(n))
#

e.g.

1+1+1=3
1+1+1 = 3
fleet bridge
#
 n=[1,2,3]
print(*n,sep='+',end=f'={sum(n)}')
#

!e ```py
n=[1,2,3]
print(*n,sep='+',end=f'={sum(n)}')

night quarryBOT
#

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

1+2+3=6
fleet bridge
#

Is it shorter?

versed eagle
#

mhm

night quarryBOT
#

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

1+2+3=6
finite blaze
#

Hey,
I have a little golfing challenge.
You have a file with n lines and each line contains one word of random length with random letters.
Distance between letters A and B is 1, between C and F its 3 etc etc.
List words where distance between all the letters in the word is less than 10.
Example of a word that matches this condition is AHBINK

low lynx
#

119

import itertools as i
p=i.pairwise
for w in open(0).read().split():all(-10<ord(i)-ord(j)<10for i,j in p(w))and print(w)
#

92

for w in open(0).read().split():all(-10<ord(i)-ord(j)<10for i,j in zip(w,w[1:]))and print(w)
gleaming linden
#

does this work? ```py
for w in open(0):p,*a,_=w;10<max((abs(ord(p)-ord(c)),p:=c)[0]for c in a)or print(w)

low lynx
#

yes

#

both 76

for w in open(0):p,*a,_=w;all(-10<ord(p)-ord(p:=c)<10for c in a)and print(w)
for w in open(0):p,*a,_=w;10<max(abs(ord(p)-ord(p:=c))for c in a)or print(w)
#

actually no

#

your's is wrong

#

which is a good thing

#

because it saves a char

#

75

for w in open(0):p,*a,_=w;9<max(abs(ord(p)-ord(p:=c))for c in a)or print(w)
#

tied 75

for w in open(0):p,*a,_=w;max(abs(ord(p)-ord(p:=c))for c in a)<10==print(w)
night quarryBOT
#

@sly ibex :white_check_mark: Your 3.11 eval job has completed with return code 0.

-10 0 10 20 30 
sick hound
#

wouldn't def a(a) be shorter than lambda a ? they have the same length

#

you'd also remove the b =

#

kinda got offtopic here sorry```hs
ghci> t = [123, 123, 893]
ghci> (\x -> sum x)(t)
1139

```py
>>> t = [123, 123, 893]
>>> (lambda x: sum(x))(t)
1139
pure dew
#

??

maiden blaze
kindred stone
past plank
earnest wing
quartz wave
#

nvm they both don't work

ancient saddle
#

ok this is kind of a crapshoot, but is there a semi-reasonable way to find where a certain string is being stored in what seems to be an absurdly convoluted and obfuscated data structure?

#

I've gone about trying to manually set a certain configuration for a certain class and it's apparently cached elsewhere but I can find absolutely nothing helpful in this descent into madness that some might generously call a module

quartz wave
#

if it's interned you might have better luck with gc.get_referrers()

ancient saddle
#

I mean, I can def find its physical memory location with scanner tools but I've no clue how to get from the memory location to which object actually owns that data

quartz wave
#

for 64-bit systems, subtract 48 bytes for ASCII strings and 72 for non-ASCII strings in 3.10(?)+

ancient saddle
#

seems like I'm gettin a lot of Nones back, hmm

cunning stream
#

not python but i think you guys will like this language

versed eagle
#

reminds me of perl-

cunning stream
#

brainfuckasm idk

#

its like brainfuck but slightly more usable

arctic skiff
#

bfaapl

versed eagle
#

you could shorten that to bfpl

#

BrainFuck Programming Language

cunning stream
#

how about brainfuck but good

#

bfbg

sick hound
#

!e def function(c):
translates = {49:11036,48:11035}
for i in c:
fill = []
for j in c:
fill.append(len(bin(ord(j))[1:]))
fill = max(fill)
i = bin(ord(i))[2:]
i = i.zfill(fill)
i = i.translate(translates)
print(i)

_('<~ร รพรพ~ff', 2)

function('<~ร รพรพ~ff')

night quarryBOT
#

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

001 | โฌ›โฌ›โฌ›โฌœโฌœโฌœโฌœโฌ›โฌ›
002 | โฌ›โฌ›โฌœโฌœโฌœโฌœโฌœโฌœโฌ›
003 | โฌ›โฌœโฌœโฌœโฌ›โฌ›โฌ›โฌ›โฌ›
004 | โฌ›โฌœโฌœโฌœโฌœโฌœโฌœโฌœโฌ›
005 | โฌ›โฌœโฌœโฌœโฌœโฌœโฌœโฌœโฌ›
006 | โฌ›โฌ›โฌœโฌœโฌœโฌœโฌœโฌœโฌ›
007 | โฌ›โฌ›โฌœโฌœโฌ›โฌ›โฌœโฌœโฌ›
008 | โฌ›โฌ›โฌœโฌœโฌ›โฌ›โฌœโฌœโฌ›
night quarryBOT
#

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

[No output]
#

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

[No output]
gleaming linden
#

!e ```py
import sys

f = open("1.txt", 'w')

sys.stdout = f

print("Hello world")

night quarryBOT
#

@gleaming linden :white_check_mark: Your 3.11 eval job has completed with return code 0.

1.txt

Hello world
gleaming linden
#

!e or this: ```py
from contextlib import redirect_stdout

f = open("1.txt", 'w')

with redirect_stdout(f):
print("Hello")

print("World")

night quarryBOT
#

@gleaming linden :white_check_mark: Your 3.11 eval job has completed with return code 0.

World

1.txt

Hello
old socket
#

!e ```py
import sys
with open("1.txt", "w") as sys.stdout:
print("Hello")

print("World")

night quarryBOT
#

@old socket :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 5, in <module>
003 |     print("World")
004 | ValueError: I/O operation on closed file.

1.txt

Hello
old socket
#

oh I thought it worked before

#

Unless it's just cus of snekbox

#

Oh wait it did write but there is an error

gleaming linden
#

it works, but you can't print anything afterward because the file is closed when you exit the with block

old socket
#

OH nvm the last print is trying to

#

yea

#

I just realised

gleaming linden
#

!e ```py
from contextlib import redirect_stdout

with open('1.txt', 'w') as file, redirect_stdout(file):
print("Hello")

print("World")

night quarryBOT
#

@gleaming linden :white_check_mark: Your 3.11 eval job has completed with return code 0.

World

1.txt

Hello
gleaming linden
#

oh, this works too

old socket
#

I know you can unpack with ctx manager but I thought the enter specifically needed to return something unpackable

#

!e ```py
with open("1.txt", "w") as foo, bar:
print(foo, bar)

night quarryBOT
#

@old socket :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     with open("1.txt", "w") as foo, bar:
004 |                                     ^^^
005 | NameError: name 'bar' is not defined

1.txt

[Empty]
old socket
#

wait how does that work

#

Is it just treated as a different line?

gleaming linden
#

it's doing with (open("1.txt", "w") as foo), bar:

old socket
#

Ahh okay

gleaming linden
#

!e ```py
with open('1.txt', 'w') as file:
file.write("foo\nbar\n")

with open('1.txt') as (a, b):
print(a, b)

night quarryBOT
#

@gleaming linden :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | foo
002 |  bar

1.txt

foo
bar
gleaming linden
#

cool

old socket
#

I wonder how secure the file stuff is on snekbox

#

I know there prob isn't any huge issue off the bat but I can't help but feel there is something

versed eagle
#

!e

open(1, "w").write("hello, world")
night quarryBOT
#

@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.

hello, world
versed eagle
#

1 is the file descriptor for stdout

#

its not that they could use it as stdout, it's that it is stdout

pure dew
#

!e ```py
open("/dev/stdout", "w").write("dlrow ,olleh")

night quarryBOT
#

@pure dew :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     open("/dev/stdout", "w").write("dlrow ,olleh")
004 |     ^^^^^^^^^^^^^^^^^^^^^^^^
005 | FileNotFoundError: [Errno 2] No such file or directory: '/dev/stdout'
pure dew
dry mirage
fleet bridge
dry mirage
glass drumBOT
fleet bridge
#

That's awesome

arctic skiff
sonic birch
night quarryBOT
#

@sonic birch :white_check_mark: Your 3.11 eval job has completed with return code 0.

['1\n', 0, 0, 0, 0, '2\n', '3\n', 0, 0, '4']

file.txt

1
2
3
4
pure dew
#

smh i'll get it

quartz wave
#

!e ```py
open('file.txt', 'w').write('1\n2\n3\n4')
arr=[0]*10
with open('file.txt') as (arr[0],*arr[5:7], arr[-1]):
print(arr)

night quarryBOT
#

@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

['1\n', 0, 0, 0, 0, '2\n', '3\n', 0, 0, '4']

file.txt

1
2
3
4
pure dew
#

!e open('file.txt', 'w').write('1\n2\n3\n4')
arr=[0]
with open('file.txt') as (arr[0],*arr[5:7], arr[-1]):
print(arr)

night quarryBOT
#

@pure dew :white_check_mark: Your 3.11 eval job has completed with return code 0.

['1\n', '2\n', '4']

file.txt

1
2
3
4
pure dew
#

!e open('file.txt', 'w').write('1\n2\n3\n4')
arr=[]
with open('file.txt') as (arr[0],*arr[1:3], arr[-1]):
print(arr)

night quarryBOT
#

@pure dew :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 3, in <module>
003 |     with open('file.txt') as (arr[0],*arr[1:3], arr[-1]):
004 |                               ~~~^^^
005 | IndexError: list assignment index out of range

file.txt

1
2
3
4
pure dew
#

ah

cloud fossil
#

๐Ÿฅด

#

I'm assuming the first one is for lambdas, but the second one lies to me as I can get 2 (so there is something). The last one is what I would expect from both except the NOP which I didn't know is used

#

The last one is kind of what happen if I throw these into an actual function

#

(minus the NOP in the first two cases)

versed eagle
#

the second one is the same as the third one, except for the NOP

#

which makes sense, considering that they do the same thing

#

the NOP i assume is an artifact of the separate lines

cloud fossil
#

But why does the byte code tell me there is no constant loading when I can load 2

#

I mean

#

_ becomes 2

#

Is it just a REPL thing

versed eagle
#

iirc that's done by sys.displayhook

versed eagle
fleet bridge
#

!e ```py
from dis import dis
c = compile('1;2', '', mode='single')
dis(c)

night quarryBOT
#

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

001 |   0           0 RESUME                   0
002 | 
003 |   1           2 LOAD_CONST               0 (1)
004 |               4 PRINT_EXPR
005 |               6 LOAD_CONST               1 (2)
006 |               8 PRINT_EXPR
007 |              10 LOAD_CONST               2 (None)
008 |              12 RETURN_VALUE
cloud fossil
#

Cool!
And on another note, can someone explain me how the reference counting system works in Python?

#

The website talks about strong references and borrowed references

fleet bridge
#

You can read developers guide about that

fleet bridge
cloud fossil
#

Strong references are references that if are gone, delete the object

#

Borrowed just means the object's strong reference is borrowed? What count is being incremented/decremented then?

versed eagle
#

the objects ob_refcnt

fleet bridge
night quarryBOT
#

Include/object.h lines 102 to 106

struct _object {
    _PyObject_HEAD_EXTRA
    Py_ssize_t ob_refcnt;
    PyTypeObject *ob_type;
};```
cloud fossil
#

At which point does the virtual machine stop to take a look at objects' ob_refcnt?

versed eagle
#

that's the garbage collectors job

cloud fossil
#

When does it collect garbage

versed eagle
#

i know it does it when leaving scopes

#

and also other times

fleet bridge
versed eagle
#

you could try reading the source to figure that out

cloud fossil
fleet bridge
cloud fossil
fleet bridge
versed eagle
fleet bridge
#

Leaving scope is equivalent to deleting all local variables using del x

versed eagle
#

yeah

cloud fossil
#

When in something like

print()
print()

does the garbage collector know to dereference the None from the return values

versed eagle
#

iirc None is an immortal object

#

or at least an interned object

cloud fossil
#

What if I had functions which returned my own objects

#

Or returned lists

fleet bridge
cloud fossil
fleet bridge
fleet bridge
versed eagle
#

well ty for teaching me that then

cloud fossil
fleet bridge
#

Well. It is also possible to think that there are 2 different GCs:

  1. stupid one: checks RC==0 and deletes object
  2. smart one: detects dead graphs, destroys references in this graphs, so every RC eventually hits 0, so stupid GC can collect every garbage object
fleet bridge
fleet bridge
#

For loop can be destructured to simpler statements, and there would be an assignment

cloud fossil
#

Yeah, STORE_NAME ... (_) in my case

fleet bridge
#

Interesting fact: you can use in for loop anything if you can use it before =
for a[b] in c:... is good, for example

#

It is called "assignment target", it means you can assign value to it and it wouldn't raise SyntaxError
Assignment target is essentially any expression with some exceptions (you cant assign to function calls, literals, ...)

cloud fossil
#

This happens generally with a[b] = c

#

You can also del a[b]

fleet bridge
cloud fossil
#

!e

from string import ascii_uppercase, ascii_lowercase
a = list(ascii_uppercase)
c = list(ascii_lowercase)
b = 0
print(f"{a = }\n{c = }")
for a[b] in c:
    b += 1
print(f"{a = }\n{c = }")
night quarryBOT
#

@cloud fossil :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
002 | c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
003 | a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
004 | c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
cloud fossil
#

So cool

versed eagle
#

you can also do slices

cloud fossil
#

!e

from string import ascii_uppercase, ascii_lowercase
a = list(ascii_uppercase[:10])
c = list(ascii_lowercase[:10])
b = 0
print(f"{a = }\n{c = }")
for a[b::2] in c:
    b += 2
print(f"{a = }\n{c = }")
night quarryBOT
#

@cloud fossil :x: Your 3.11 eval job has completed with return code 1.

001 | a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
002 | c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
003 | Traceback (most recent call last):
004 |   File "/home/main.py", line 6, in <module>
005 |     for a[b::2] in c:
006 |         ~^^^^^^
007 | ValueError: attempt to assign sequence of size 1 to extended slice of size 5
fleet bridge
#

a[b] and a[<slice>] are the same, index type is handled inside list.getitem

versed eagle
#

mhm

#

im just reminding people that slices exist

cloud fossil
#

Wait do I need to slice c with b as well

versed eagle
#

since people usually forget

cloud fossil
#

!e

from string import ascii_uppercase, ascii_lowercase
a = list(ascii_uppercase[:10])
c = list(ascii_lowercase[:10])
b = 0
print(f"{a = }\n{c = }")
for a[b::2] in c[b::2]:
    b += 2
print(f"{a = }\n{c = }")
night quarryBOT
#

@cloud fossil :x: Your 3.11 eval job has completed with return code 1.

001 | a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
002 | c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
003 | Traceback (most recent call last):
004 |   File "/home/main.py", line 6, in <module>
005 |     for a[b::2] in c[b::2]:
006 |         ~^^^^^^
007 | ValueError: attempt to assign sequence of size 1 to extended slice of size 5
versed eagle
#

slices are one of the nicest features and yet people forget about them so often

cloud fossil
#

How can I do this with slices

versed eagle
#

it's the same as a tuple unpacking assignment-
the amount of items needs to match

cloud fossil
#

!e

from string import ascii_uppercase, ascii_lowercase
a = list(ascii_uppercase[:10])
c = list(ascii_lowercase[:10])
b = 0
print(f"{a = }\n{c = }")
for a[b:b+2:2] in c:
    b += 2
print(f"{a = }\n{c = }")
night quarryBOT
#

@cloud fossil :x: Your 3.11 eval job has completed with return code 1.

001 | a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
002 | c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
003 | Traceback (most recent call last):
004 |   File "/home/main.py", line 6, in <module>
005 |     for a[b:b+2:2] in c:
006 |         ~^^^^^^^^^
007 | ValueError: attempt to assign sequence of size 1 to extended slice of size 0
fleet bridge
cloud fossil
#

!e

from string import ascii_uppercase, ascii_lowercase
a = list(ascii_uppercase[:10])
c = list(ascii_lowercase[:10])
b = 0
print(f"{a = }\n{c = }")
for a[b], a[b+1] in c[::2]:
    b += 2
print(f"{a = }\n{c = }")
night quarryBOT
#

@cloud fossil :x: Your 3.11 eval job has completed with return code 1.

001 | a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
002 | c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
003 | Traceback (most recent call last):
004 |   File "/home/main.py", line 6, in <module>
005 |     for a[b], a[b+1] in c[::2]:
006 |         ^^^^^^^^^^^^
007 | ValueError: not enough values to unpack (expected 2, got 1)
cloud fossil
#

!e

from string import ascii_uppercase, ascii_lowercase
a = list(ascii_uppercase[:10])
c = list(ascii_lowercase[:10])
b = 0
print(f"{a = }\n{c = }")
for a[b], a[b+1] in c[b:b+2:2]:
    b += 2
print(f"{a = }\n{c = }")
night quarryBOT
#

@cloud fossil :x: Your 3.11 eval job has completed with return code 1.

001 | a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
002 | c = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
003 | Traceback (most recent call last):
004 |   File "/home/main.py", line 6, in <module>
005 |     for a[b], a[b+1] in c[b:b+2:2]:
006 |         ^^^^^^^^^^^^
007 | ValueError: not enough values to unpack (expected 2, got 1)
cloud fossil
#

I'm totally not understanding how this should work

fleet bridge
versed eagle
#

mhm

fleet bridge
#

!e weird way to copy a list (inspired by today's conversation) ```py
a = [*'abcdefgh']
print(a)
c = [' '] * len(a)
for i, c[i] in enumerate(a):
print(c)
assert a == c

night quarryBOT
#

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

001 | ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
002 | ['a', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
003 | ['a', 'b', ' ', ' ', ' ', ' ', ' ', ' ']
004 | ['a', 'b', 'c', ' ', ' ', ' ', ' ', ' ']
005 | ['a', 'b', 'c', 'd', ' ', ' ', ' ', ' ']
006 | ['a', 'b', 'c', 'd', 'e', ' ', ' ', ' ']
007 | ['a', 'b', 'c', 'd', 'e', 'f', ' ', ' ']
008 | ['a', 'b', 'c', 'd', 'e', 'f', 'g', ' ']
009 | ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
fleet bridge
#

fun implementation detail: i, c[i] = value works even if i is not previously defined because:

  1. i is assigned to value[0]
  2. i is loaded to stack (there is no error because i was defined by previous step)
  3. c[TOS] is assigned to value[1]
languid hare
#

hm

#

neat

#

!e

import dis
def x():
  i, arr[i] = tup
print(dis.dis(x))
night quarryBOT
#

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

001 |   2           0 RESUME                   0
002 | 
003 |   3           2 LOAD_GLOBAL              0 (tup)
004 |              14 UNPACK_SEQUENCE          2
005 |              18 STORE_FAST               0 (i)
006 |              20 LOAD_GLOBAL              2 (arr)
007 |              32 LOAD_FAST                0 (i)
008 |              34 STORE_SUBSCR
009 |              38 LOAD_CONST               0 (None)
010 |              40 RETURN_VALUE
011 | None
... (truncated - too many lines)

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

vast wave
#

!e ```py
t = (0, "abc")
arr = [1]
i, arr[i] = t
print(i, arr)

night quarryBOT
#

@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

0 ['abc']
vast wave
#

interesting

low lynx
#

huh

quartz wave
#

!e ```py
arr = arr[0] = [0]
print(arr)

night quarryBOT
#

@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

[[...]]
maiden blaze
#

arr=arr [0]=[0] is pretty funny

vast wave
versed eagle
#

other way around

arr = [0]
arr[0] = arr```
#

its like that

vast wave
#

!e ```py
import("dis").dis(compile("a = a[0] = [1]", "", "exec"))

night quarryBOT
#

@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 |   0           0 RESUME                   0
002 | 
003 |   1           2 LOAD_CONST               0 (1)
004 |               4 BUILD_LIST               1
005 |               6 COPY                     1
006 |               8 STORE_NAME               0 (a)
007 |              10 LOAD_NAME                0 (a)
008 |              12 LOAD_CONST               1 (0)
009 |              14 STORE_SUBSCR
010 |              18 LOAD_CONST               2 (None)
011 |              20 RETURN_VALUE
... (truncated - too many lines)

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

vast wave
#

god that is funky

versed eagle
#

for thing = thing2 = thing3 = value it goes thing = value, then thing2 = thing, and so on

vast wave
#

what the fuck?

#

!e ```py
import ast
print(ast.dump("a = b = c = d = 1", indent=2))

#

!e ```py
import ast
print(ast.dump(ast.parse("a = b = c = d = 1"), indent=2))

night quarryBOT
#

@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | Module(
002 |   body=[
003 |     Assign(
004 |       targets=[
005 |         Name(id='a', ctx=Store()),
006 |         Name(id='b', ctx=Store()),
007 |         Name(id='c', ctx=Store()),
008 |         Name(id='d', ctx=Store())],
009 |       value=Constant(value=1))],
010 |   type_ignores=[])
vast wave
#

yep
python moment

versed eagle
#

it would make a little more sense imo if it went from right to left here, like this ```py
thing = (thing2 = (thing3 = value))

vast wave
#

thats what i thought as well

#

coming from java land

unreal echo
night quarryBOT
#

db_funcs.py line 239

p = map((lambda x: (x[0], (*x[1:5], *x[6:-2], len(x[-1])-len(x[-2])))), filter((lambda x: x[0] in ids), await get_posts()))```
night quarryBOT
#

db_funcs.py line 400

[id, post[1] if title is None else title, post[2] if content is None else content, post[3] if date is None else date, None if fp is None and post[4] is not None else (lambda: post[4] if fp is '' else fp)(), post[5] if ip is None else ip, post[6] if pin is None else pin, f'{post[7]}' if upvotes is None else f'{upvotes}', f'{post[8]}' if downvotes is None else f'{add_downvote}', id],```
night quarryBOT
#

db_funcs.py lines 43 to 52

if not (await os.path.isfile(file)):file = glob.glob(f'./**/{file}', recursive=True)[0]
async with aiofiles.open(file) as f:code = await f.read()
fg = ''.join(random.sample(string.ascii_letters, k=52)) + '.py'
async with aiofiles.open(fg, 'w') as f:await f.write(code)
await os.remove(fg)
g = {i:v for i,v in globals().items()}
g['DATA'] = data
if threaded:await asyncio.to_thread(exec, [code, g, {i:v for i,v in locals().items()}])
else:exec(code, g, {i:v for i,v in locals().items()})
print(f'Flow {flow} executed {file} given type data {t} on {datetime.datetime.utcnow()} UTC.')```
arctic skiff
#

!epy print('\n'.join(['abcdefghijklmnopqrstuvwxyz'[:_]for _ in range(1,26)]))

night quarryBOT
#

@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | a
002 | ab
003 | abc
004 | abcd
005 | abcde
006 | abcdef
007 | abcdefg
008 | abcdefgh
009 | abcdefghi
010 | abcdefghij
011 | abcdefghijk
... (truncated - too many lines)

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

last locust
night quarryBOT
#

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

001 | a
002 | ab
003 | abc
004 | abcd
005 | abcde
006 | abcdef
007 | abcdefg
008 | abcdefgh
009 | abcdefghi
010 | abcdefghij
011 | abcdefghijk
... (truncated - too many lines)

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

last locust
#

You don't need the list lemon_wink

arctic skiff
#

Forgot that it also takes *args

versed eagle
#

it's a generator

arctic skiff
last locust
#

You need the .ascii_lowercase (which makes it longer)

night quarryBOT
#

@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | a
002 | ab
003 | abc
004 | abcd
005 | abcde
006 | abcdef
007 | abcdefg
008 | abcdefgh
009 | abcdefghi
010 | abcdefghij
011 | abcdefghijk
... (truncated - too many lines)

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

arctic skiff
last locust
night quarryBOT
last locust
#

You'd just have to add the slice logic (which thinking about it would probably make it longer)

finite blaze
#

I was wondering if there is a way to code in python without using letters?

#

Like with javascript

last locust
arctic skiff
finite blaze
#

yup

last locust
#

If you mean solely latin a-z then you can just use other scripts

versed eagle
night quarryBOT
#

@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | a
002 | ab
003 | abc
004 | abcd
005 | abcde
006 | abcdef
007 | abcdefg
008 | abcdefgh
009 | abcdefghi
010 | abcdefghij
011 | abcdefghijk
... (truncated - too many lines)

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

versed eagle
#
print("\n".join("".join(map(chr,range(97,98+i)))for i in range(26)))
print('\n'.join('abcdefghijklmnopqrstuvwxyz'[:_]for _ in range(1,26)))
#

it's shorter

#

because you don't need the start argument for the range call

finite blaze
#

[:_] o nice thingy

#

need to remember that one

slow marsh
#

!e
print("hello!")

#

cool

slow marsh
#

s

#

!e ```py
import matplotlib.pyplot as plt
x = [1,3,5,6]
y = [1,6,7,8]
plt.plot(x,y)
plt.show()

night quarryBOT
#

@slow marsh You've already got a job running - please wait for it to finish!

#

Sorry, an unexpected error occurred. Please let us know!

TimeoutError:

unique heath
#

@slow marsh

slow marsh
#

uh huh

unique heath
unique heath
eager ore
#

wait until you see enterprise fizzbuzz though

versed eagle
versed eagle
low lynx
#
encode_rail_fence_cipher,decode_rail_fence_cipher=lambda s,n:''.join([''.join(map(''.join,zip(s[i::(k:=2*~-n)],s[k-i::k]+'็€ง'))),s[::k],s[n-1::k]][(i%~-n<1)+(n-i<2)].rstrip('็€ง')for i in range(n)),lambda s,n,c=0:s and''.join(map(''.join,zip(*[s[:(c:=(g:=1+(l:=len(s)-1)//(k:=2*~-n)))],*(m:=[[[],[]],[*zip(*[zip(*zip(*[iter(f'{s[c:(c:=c+l//k*2+(l%k>=i)+(l%k>=k-i))]:็€ง<{g*2}}')]*2))for i in range(1,n-1)])]][n>2])[0],f'{s[c:]:็€ง<{g}}',*m[1][::-1]]))).rstrip('็€ง')

one liner for this https://www.codewars.com/kata/58c5577d61aefcf3ff000081

#

cannot be bothered to golf further

eager ore
versed eagle
keen thicket
sick hound
#

!e print('\n'.join(['abcdefghijklmnopqrstuvwxyz'[:_]for _ in range(1,99)]))

#

hi

dusty zodiac
#

Can anyone help me shorten this code I wrote.

def square_digits(num): 
    return int("".join([str(i) for i in [int(i)**2 for i in list(str(num))]]))

It looks like a monstrosity IK hahah

versed eagle
#
square_digits=lambda n:int("".join(map(str,[int(i)**2for i in str(n)])))
dusty zodiac
#

thank you

#

I see, I need to figure out how lambda and map() works

quartz wave
dusty zodiac
#

I see '%i'

unique heath
#

hi

tough willow
#

hi

last locust
#

!e ```py
import matplotlib.pyplot as plt
x = [1,3,5,6]
y = [1,6,7,8]
plt.plot(x,y)
plt.savefig("plot.png")

night quarryBOT
#

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

pure dew
#

oh nice

vast wave
night quarryBOT
#

@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | ##########
002 | #########
003 | ########
004 | #######
005 | ######
006 | #####
007 | ####
008 | ###
009 | ##
010 | #
vast wave
#

discord's search fucking sucks

rugged owl
worn sage
rugged owl
sick hound
#

!e

# This comment is necessary for the code to run.
# This comment is also necessary.
# So is this one.

q = [36, 29, 0, -36, -69, -184, -165, -177, -210, -252, -296, -399]
n = 0

def __a():
    pass

def __b():
    global n

    for i in __a.__code__.co_lines():
        n += i[0] + (i[1] * i[2])

for i in range(len(q)):
    print(str(__b())[10:] + chr(q[i] + n), end="")```
night quarryBOT
#

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

ย”รฝลฦœวซวจษซหฬžอคฮจฮฑ
sick hound
#

Haha it doesn't even run properly in here

vague cairn
#

Was b supposed to return something?

zenith geode
#

!e

s = (x for x in range(10))
print(list(s).__sizeof__())
print(list(s).__sizeof__())
print(list(s).__sizeof__())
night quarryBOT
#

@zenith geode :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 168
002 | 40
003 | 40
zenith geode
#

huh

#

is it caching smth?

restive void
#

The generator is just exhausted the second and third time?

#

!e empty list takes less space than non-empty list

s = (x for x in range(10))
print(list(s))
print(list(s))
print(list(s))
night quarryBOT
#

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

001 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
002 | []
003 | []
zenith geode
sick hound
#

!e @commands.group( help="Shows boosts count", usage="boosts", aliases=["bc"]) @blacklist_check() async def boosts(self, ctx): await ctx.send( embed=discord.Embed(title=f"Boosts Count Of {ctx.guild.name}", description="**`%s`**" % (ctx.guild.premium_subscription_count), color=0x977FD7))

night quarryBOT
#

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

001 |   File "/home/main.py", line 5
002 |     @blacklist_check()
003 | IndentationError: unexpected indent
terse mortar
#

The bot uses a sandbox environment so itโ€™s not actually connected to the bot

rugged owl
night quarryBOT
#

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

dยร€รœรปรˆฤ›ลลฎฦ„ฦ˜ลฑ
rugged owl
#

Doesnt seem to throw an exception

quartz wave
#

what python version?

quartz wave
#

!e ```py
'some' r'eally' 'useless' + str('ings') \

  • int('4nd integers'[:3 is 3]) + f'or' r'eal' +
    str('this' is not 'a' 'joke')

q = [36, 29, 0, -36, -69, -184, -165, -177, -210, -252, -296, -399]
n = 0

def __a():
pass

def __b():
global n

i = next(it := __a.__code__.co_lines()) and next(it)
n += i[0]-2 + (i[1] * i[2])

for i in range(len(q)):
print(str(__b())[10:] + chr(q[i] + n), end="")

night quarryBOT
#

@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | /home/main.py:2: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 |   * int('4nd integers'[:3 is 3]) + f'or' r'eal' + \
003 | /home/main.py:3: SyntaxWarning: "is not" with a literal. Did you mean "!="?
004 |   str('this' is not 'a' 'joke')
005 | Hello World!
sick hound
dusty zodiac
#
cipher = lambda t, s: ''.join(chr((ord(c) - 65 + s) % 26 + 65) if c.isupper() else chr((ord(c) - 97 + s) % 26 + 97) if c.isalpha() else c for c in t)

Wondering if this can be shortend further??

tough willow
#
cipher=lambda t,s:''.join(chr((ord(c)-65+s)%26+65)if c.isupper()else chr((ord(c)-97+s)%26+97)if c.isalpha()else c for c in t)```
gleaming linden
#

oh nvm

dusty zodiac
#

There is non alphabetic characters they just return it as is

#

else c for c in t

gleaming linden
#
cipher=lambda t,s:''.join([c,chr((ord(c)-65+s-c.islower()*32)%26+97-c.isupper()*32)][c.isalpha()]for c in t)
``` does this work?
it didn't work, it should be fixed now
#
cipher=lambda t,s:''.join([c,(d:=65+c.islower()*32),chr((ord(c)-d+s)%26+d)][-c.isalpha()]for c in t)
``` 100
gleaming linden
#

yeah, I just fixed it

#

I keep getting the 65+c.islower()*32 part wrong

dusty zodiac
#

Oh ey it works now

#

also smart using a walrus operator

gleaming linden
#

oh wait I'm stupid

#
cipher=lambda t,s:''.join([c,chr((ord(c)-(d:=65+c.islower()*32)+s)%26+d)][c.isalpha()]for c in t)
#

97

dusty zodiac
#

dang 97 length

sudden osprey
#

c.islower()*32 -> ord(c)&32 I think should work

gleaming linden
#
cipher=lambda t,s:''.join([c,chr((ord(c)-(d:=65+(ord(c)&32))+s)%26+d)][c.isalpha()]for c in t)
``` works but needs brackets, 94
sudden osprey
#
cipher=lambda t,s:''.join([c,chr(((n:=ord(c))+s-(d:=(n&96)+1))%26+d)][64<n&95<91]for c in t) 

92 if it works

#
cipher=lambda t,s:''.join([c,chr(((n:=ord(c))+s-(d:=-~(n&96)))%26+d)][64<n&95<91]for c in t)

Same length but looks cooler

#

oh wait

#
cipher=lambda t,s:''.join([c,chr(((n:=ord(c))+s+(d:=~(n&96)))%26-d)][64<n&95<91]for c in t)  

91

#
cipher=lambda t,s:''.join([c,chr(((n:=ord(c))+s+~(d:=n&96))%26-~d)][64<n&95<91]for c in t)

90

wheat river
#
cipher=lambda t,s:''.join([chr(((n:=ord(c))-s-~(d:=n&96))%26-~d),c][not n^32]for c in t)
#

86^

sick hound
#

What are we trying to golf now

fleet bridge
#
>>> cipher('abcdefgh',1)
'bcdefghi'
``` it is a caesar cipher i guess
sudden osprey
#

I'd ignored non-ASCII btw, given the original code only works properly for ascii. (could use [96<n|32<123] or [64<n&~32<91] to fix that, although it's +1 character)

wheat river
#
cipher=lambda t,s:''.join([c,chr(((n:=ord(c))+s+~(d:=n&96))%26-~d)][n>>5>1]for c in t)

86

gleaming linden
sick hound
#

@wheat river what are we trying to golf

gleaming linden
#

caesar cipher

sick hound
#

Uhh

#

What

gleaming linden
#

pretty much

gleaming linden
# sick hound What

when the key is 1, all the letters get shifted by 1 (so a -> b, b -> c, etc. and z -> a)

#

when the key is 2, all letters get shifted by 2 (a -> c, b -> d, ..., y -> a, z -> b)

#

etc.

sick hound
#

!e

exec(bytes('ๆฅฃๆกฐ็‰ฅใด ๆฐ ๆตกๆ‘ขโกโฑด็Œ โ€บโœงๆจฎๆฅฏโกฎๆกฃโกฒๆผจๆ‘ฒๆŒจโ€ฉโ€ญใ”ถโ€ ็Œซโ€ฉโ€ฅใ˜ฒโฌ ใ˜ โคตๆค โฆโนฃ็ฉ็ตๆ•ฐโกฒโ€ฉๆฑฅๆ•ณๆŒ ็‰จโ จ็‰ฏโกคโฅฃโด ใค โ€ทโ€ซโฅณโ” ใˆ โ€ถโ€ซใœนโ€ฉๆ™ฉๆŒ ๆคฎๆ…ณ็ฌๆ…จโคจๆ” ็ฌโฅโฃๆฝฆโฒโฃๆนฉ็ โ€ฉ','u16')[2:])
night quarryBOT
#

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

[No output]
sick hound
#

hehe bytes

sick hound
#

oh

gleaming linden
#

also, we usually count in bytes and not characters

sick hound
#

not sure what that means

gleaming linden
#

ASCII characters take up only 1 byte, but other characters (usually in degen solutions) take up more than 1 byte

#

eg ๆฅฃ is 1 character, but it might take up 2 or 3 bytes instead

sick hound
#

I see

#
def c(m,k):return"".join(chr((ord(i)-65+k)%26+65)for i in m)
gleaming linden
#
  1. the function is called cipher, you can't change that
  2. it has to preserve case (uppercase should remain uppercase and lowercase should remain lowercase)
  3. it should leave non-alphabetic characters alone
sick hound
#

172 bytes :(

#

hmm

gleaming linden
#
>>> cipher("abcABCuvw@{", 5)
'fghFGHzab@{'
``` here's a testcase if you need one
wheat river
sick hound
languid night
#

? ๐Ÿ˜ญ

flint hollow
#

low-level type. guessing unsigned 16-bit int

quartz wave
fleet bridge
#

wow, docs are now in dark theme! awesome!

#

since when?

last locust
glass drumBOT
last locust
#

It's been in progress for... 3 years apparently. Was finally merged last week

fleet bridge
#

i love it

last locust
#

Looks like it only applies to the dev docs (i.e. py3.12) atm though

sick hound
#

I kind of like how the dark theme uses the Monokai theme for syntax highlighting despite the fact I think it's kind of overrated

radiant anchor
#

!e

unused=b'\x50K\3\4'+b'\0'*26+b'+(\xca\xcc+\xd1P\xcfHL\xceNMQ\xc8\xc9\xcfQ\xd7\4\0PK\1\2'+b'\0'*6+b'\1'+b'\0'*9+b'\x15'+b'\0'*7+b'\13'+b'\0'*17+b'__\x6da\x69n__.\x70y\x50K\5\6'+b'\0'*8+b'9\0\0\0003\0\0\0'
i=__import__
i("runpy").run_path(i("py_compile").compile(__file__))
night quarryBOT
#

@radiant anchor :white_check_mark: Your 3.11 eval job has completed with return code 0.

hacked lol

failed_file Files with disallowed extensions can't be uploaded: .pyc

radiant anchor
golden finch
lunar marsh
spring rose
#

I have sever, root and intermediate certs. Where should these be uploaded so that i don't get SSL error when I establish a connection to the url endpoint using python get and post methods?

spring rose
#

Basically i have a python script to access a url endpoint
That fails as we have a self signed certificate
But i have all the self signed certificate with me
The root intermediate server and chain
Now which among these should I add to make the secure post request to the url?
And where should these be added?

restive void
finite blaze
#

Hey

#

I'm trying to golf something

#

Basically i need to find all numbers in a file that are a power of 3

#

What I'm doing rn is

print(len(*"".join(["","1"][math.log(int(i.strip()),3)] for i in open("file.txt")))
#

And i get some weird results from it

low lynx
#

that shouldn't work should it?

#

you can't index with a float

finite blaze
#

I forgot that i do .is_integet() after that log()

#

It gives me a generator object genexpr

spring rose
#

What is this queue parameter in airflow??

golden finch
#

this isn't a help channel

sly ibex
#

Depends

vast wave
#

!e ```py
class Whatever:
def init(self, msg, amount):
self.msg = msg
self.amount = amount
def print(self):
print(f"#{self.amount}: {self.msg*self.amount}")

fake_inst = type("", (), {})()
Whatever.init(fake_inst, "message ", 10)
Whatever.print(fake_inst)

night quarryBOT
#

@vast wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

#10: message message message message message message message message message message 
vast wave
#

instances are for losers

quartz wave
vast wave
#

no one needs to know

restive void
rain sluice
#

How can we append a item to a list inside a list?

#

??????

quartz wave
rain sluice
#

?

quartz wave
#

!e ```py
l=l[0]=[0]
l[0]+=l,
print(l)

night quarryBOT
#

@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.

[[...], [...]]
quartz wave
rain sluice
#

thx lemme try it

#

is l supposed to be the value

#

or the list

#

beginner python programmer so pretty new

quartz wave
rain sluice
#

then where

versed eagle
rain sluice
#

that'll take ages

quartz wave
vague cairn
dusty zodiac
#

Is it possible to shorten this into one line?

class Solution(object):
    def searchInsert(self, nums, target):
        x = nums
        if target in nums:
            return x.index(target)
        else:
            x.append(target)
            return x.index(target)

I tried doing this but it turns out x.appen(target) returns a None.

return nums.index(target) if target in nums else nums.index(nums.append(target))
cloud fossil
#

This should work

return nums.index(target) if target in nums else (len(nums), nums.append(target))[0]
dusty zodiac
#

it works thank you

fleet bridge
#
return (nums.append(target), nums.index(target))[1]
cloud fossil
fleet bridge
#

Ok

#

It returns the same result, but has different side effect

dusty zodiac
#

I just realized I forgot to add .sort() to the thing rip

dreamy pier
versed eagle
fleet bridge
#

Nice

gleaming linden
#
Solution=type("Solution",(),{"searchInsert":lambda s,n,t:(t in n or n.append(t),n.index(t))[1]})
``` does this work?
dreamy pier
#

Solution=type("Solution",(),{"searchInsert":lambda s,n,t:[n.append(t)]*(t in n)and n.index(t)})

gleaming linden
dreamy pier
#

oops

#

yeah

ivory lichen
#
def perfect(n):
  divs = [1]
  i = 2
  while i != n and n != 1:
    if n % i == 0:
      divs.append(i)
      i +=1
    else:
      i +=1
  dsum = sum(divs)
  if dsum == n and n != 1:
    return True
  else:
    return False 
#

is this a "good" answer to the perfect number question?

finite blaze
#

but yes, this is a good answer

#

!e

def perfect(n):
  divs = [1]
  i = 2
  while i != n and n != 1:
    if n % i == 0:
      divs.append(i)
      i +=1
    else:
      i +=1
  dsum = sum(divs)
  if dsum == n and n != 1:
    return True
  else:
    return False 

print(perfect(6))
night quarryBOT
#

@finite blaze :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
quartz wave
#

just using the class is shorter (82) ```py
class Solution:
def searchInsert(s,n,t):
if(t in n)<1:n+=t,
return n.index(t)

low lynx
#

and for your current solution first loop can be replaced by a for loop

#

and

if cond:
    return True
else:
    return False

is just return cond

dreamy pier
quartz wave
#

what if list.appendindex existed

versed eagle
#

what would its behaviour be?

quartz wave
#

actually what about list.indexdefault

versed eagle
#

what would its behaviour be?

quartz wave
versed eagle
#

yeah ik that. im asking which part of that you're trying to do

versed eagle
#

i already knew that it would be for what you were doing above
what im asking is which part of that it would be used for
i.e., what would it do (hence the question, "what would its behaviour be")

quartz wave
#

like append if the value isn't in the list and return its index?

versed eagle
#

ah

quartz wave
#

it would be so simple
we could just do staticmethod(list.indexdefault)

finite blaze
#

hmm, is there a way to add other functions to lists etc?

versed eagle
quartz wave
#

ok

versed eagle
#

that'd be interesting, but not very practical i think

quartz wave
#

yay ```pycon

a = []
a.indexdefault(2)
0
a
[2]

quartz wave