#esoteric-python

1 messages · Page 37 of 1

low lynx
#

i mean the golf of max(arr,key=len) is not too far from a serious answer, but yeah

bitter granite
#

Yes, I was looking for a serious answer as I'm thinking on how to complete a piece of work of mine 😄

bitter granite
low lynx
#

oh i just meant that if you try to code golf it (shortest number of characters/bytes), you'd end up with max(arr,key=len), which is what a serious answer would probably give you as well

#

plus or minus a space

bitter granite
#

so, in essence, a full iteration is still needed, either by the time the array is built, or at tergo

#

there's no built in approach in place

meager zinc
bitter granite
#

My list is made of dictionary like this:

max(union, key=len)
{'inspectionResultLink': 'https://search.googl...source=api', 'indexStatusResult.verdict': 'PASS', 'indexStatusResult.co...erageState': 'Submitted and indexed', 'indexStatusResult.ro...tsTxtState': 'ALLOWED', 'indexStatusResult.in...exingState': 'INDEXING_ALLOWED', 'indexStatusResult.la...tCrawlTime': '2023-11-05T21:24:26Z', 'indexStatusResult.pa...FetchState': 'SUCCESSFUL', 'indexStatusResult.go...eCanonical': 'https://www.url.com', 'indexStatusResult.us...rCanonical': 'https://www.url.net/', 'indexStatusResult.re...ringUrls.0': 'https://www.url...nomia-seo/', 'indexStatusResult.re...ringUrls.1': 'https://www.url...essionale/', 'indexStatusResult.crawledAs': 'MOBILE', 'mobileUsabilityResult.verdict': 'PASS', 'richResultsResult.verdict': 'PASS', ...}

And it's not sorted. I don't see how I can sort for something that has not an "index" per se.

A max(list, key=len) works fine for few elements ... but will that be the case for 25K rows?

At end, what I need to build is a namedTuple collection for fast querying the above items.
And I need to find the dictionary with the longest key set at first.
Although, while writing I can alreay smell the subsequent problem ... those dictionaries where the keys was not in place will thrown an error for the missing key

bitter granite
#

Or perhaps I should consider a SimpleNamespace instead of complicating my life with the namedTuple

#

In the end the result will be the same, a on object that can be queried by properties

#

I appreciate the fact that namedTuple will be immutable and guarantee a structure, but my class goal is to facilitate the reading of data not the saving

serene stratus
#

is it possible to get the code object of a module that's already imported?

#

like the main code object

#

not from functions or anything

proper vault
#

Ye, should be the f_code on the appropriate frame

rugged sparrow
#

!e ```py
def ReadAfterFree(size, do):
b = bytearray(size)
class T:
def iter(self):
b.clear()
self.v = do()
yield b''
yield b''

c = b.join(t:=T())
return memoryview(c).cast('P'), t.v

leak, obj = ReadAfterFree(bytearray.basicsize, lambda: bytearray(8))
print('bytearray:', obj)
print('leaked memory of buffer:', leak.tolist())``` read after free in stringlib join

night quarryBOT
#

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

001 | bytearray: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')
002 | leaked memory of buffer: [1, 140216309412032, 8, 9, 140216299095120, 140216299095120, 0]
serene stratus
proper vault
#

If not, you can call compile on its source code

long fulcrum
#

how can i golf this more?

from itertools import*
E=print
D=str
A=sorted
C=lambda n:A(set(B*C for(B,C)in combinations(range(10**(n//2-1),10**(n//2)),2)if B%10+C%10and A(D(B*C))==A(D(B)+D(C))))
for B in C(4):E(B)
for B in C(6):E(B)```
serene stratus
gleaming linden
#
from itertools import*
D=str
A=sorted
for n in 1,2:E=10**n;*map(print,A({B*C for(B,C)in combinations(range(E,E*10),2)if B%10+C%10if A(D(B*C))==A(D(B)+D(C))})),
long fulcrum
#

yeah that works

#

howd you get rid of the //2

gleaming linden
long fulcrum
#

can this be written any shorter for i in range(50,0,-1):

vast wave
orchid nymph
#

!e

from itertools import*
D=str
A=sorted
for n in 1,2:E=10**n;*map(print,A({B*C for(B,C)in combinations(range(E,E*10),2)if B%10+C%10if A(D(B*C))==A(D(B)+D(C))})),
night quarryBOT
#

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

001 | /home/main.py:4: SyntaxWarning: invalid decimal literal
002 |   for n in 1,2:E=10**n;*map(print,A({B*C for(B,C)in combinations(range(E,E*10),2)if B%10+C%10if A(D(B*C))==A(D(B)+D(C))})),
003 | 1260
004 | 1395
005 | 1435
006 | 1530
007 | 1827
008 | 2187
009 | 6880
010 | 102510
011 | 104260
... (truncated - too many lines)

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

orchid nymph
orchid nymph
#

well its a code.golf hole so I don't think I can help more than that

bitter granite
#

Hello there,
Is there any way to cast the value contained in dictionary's value to the corresponding enum value description?
Doing in a way that performance are not affected given I have several of them in my dictionary included in a list ?

Imagine something like the following

{'verdict': 'PASS', 'coverageState': 'Submitted and indexed', 'robotsTxtState': 'ALLOWED', 'indexingState': 'INDEXING_ALLOWED', 'lastCrawlTime': '2023-12-02T18:07:42Z', 'pageFetchState': 'SUCCESSFUL', 'googleCanonical': 'https://www.url.com', 'userCanonical': 'https://www.url.com/', 'crawledAs': 'MOBILE'}

I need to replace the indexingState, the pageFetchState, the robotsTxtState.

Ideally I should do this when I'm building my object.

versed eagle
#

also, this is probably the wrong channel

bitter granite
#

What could be the right channel? I'm still struggling to understand the 'esotheric' ssense, sorry

versed eagle
modest bough
#

I just learned that [[]] * n yields shared references to the same list. I tried using list() or [][:] but couldn't find a way to use the ... * n to have n different empty lists

earnest wing
#

[*map(list,[()]*n)]

low lynx
earnest wing
#
[[]for()in[()]*n]

for fun

modest bough
#

ok, nothing cuter than [[] for _ in range(n)] then

thorn vale
#

for _ in range(int(input())):
n = int(input()) - 1
arr = [i for i in list(input())]
index_list = []
if arr[:-1].count("A") > 0:
count = 0
while n > 0:
if (arr[n] == "B") and (arr[n - 1] == "A") and (n not in index_list):
index_list.append(n)
arr[n], arr[n - 1] = arr[n - 1], arr[n]
n = int(len(arr))-1
count += 1
else:
n -= 1
print(count)
else:
print("0")

#

Can anyone help me with this please?

#

Im a beginner. When I submit the code it says Time limit exceeded

#

The problem is that every time the action is performed, It goes back to the end of the array and starts checking again which is utterly inefficient

#

But I dont know how to make it faster

modest bough
#

i can't read your assignment, but if you focus on finding a criterion that can avoid scanning the array fully each time you win

thorn vale
#

I sort of did and it was +1 hour of thinking why doesnt it work this time

#

so I thought, enough for today ahahah

modest bough
#

sleep based problem solving

fluid pumice
#
l=[i for i in range(10**10**100)];print("{}".format(l[::-1]));while True: print(hex(id(l)),end="\n\n")
#

Just a random code

#

Warning: don't run it

fleet bridge
#

why not

#

my memory is infinite

#
>>> l=[i for i in range(10**10**100)];print("{}".format(l[::-1]));while True: print(hex(id(l)),end="\n\n")
  File "<stdin>", line 1
    l=[i for i in range(10**10**100)];print("{}".format(l[::-1]));while True: print(hex(id(l)),end="\n\n")
                                                                  ^^^^^
SyntaxError: invalid syntax
``` not impressive
#

it is allocating pretty slow

#

x = 1 << (2**36) - this is a lot faster

#

this took 8.5gb of ram, not really sure why

#

executing this code is a pretty funny way to send a lot of pages to disk in order to free up physical memory

#

not sure if it is useful, but definitely interesting

versed eagle
#
>>> b = 2 ** 36; b
68719476736
>>> B = b // 8; B
8589934592
>>> kB = B // 1024; kB
8388608
>>> mB = kB // 1024; mB
8192
>>> gB = mB // 1024; gB
8
#

unless Python just uses a half gigabyte memory to exist

fleet bridge
versed eagle
#

why

fleet bridge
#

because you copied and executed different code

versed eagle
#

i didn't execute your code

#

b = bits
B = bytes
kB = kilobytes
...

fleet bridge
#

you are talking about code i executed and claiming it doesn't do what it does

versed eagle
versed eagle
fleet bridge
versed eagle
#

oh i forgot about python not using all of the integer digits

karmic pumice
#

2^30 -> 32 bits

karmic pumice
night quarryBOT
#

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

8.533333355560899
fleet bridge
#

!e print(8 * 32/30)

night quarryBOT
#

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

8.533333333333333
stark granite
fleet bridge
#

it MemoryError's instantly

#

!e x = 1 << (2**63)

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     x = 1 << (2**63)
004 |         ~~^^~~~~~~~~
005 | MemoryError
versed eagle
#

you'd need a lot of ram to do that

#

or a big swap partition ig

unique heath
#

!e x = 1 << (1<<63)

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     x = 1 << (1<<63)
004 |         ~~^^~~~~~~~~
005 | MemoryError
unique heath
#

oh

unique heath
#

wrong channel

wanton horizon
#

sorry

low lynx
#

there's a leaderboard now btw so you can put this up if you want

real ermine
#
for seed_range in self.seeds:
 seed_range: AlmanacSeedRange.SeedRange```
is there a better way to get hints?
astral rover
#

typehint self.seeds before hand

real ermine
#

Oh, sorry, too many channels, didn't see it

#

Thanks

unique heath
#

seems to be fixed

low lynx
#

not chilaxan's one tho

unique heath
#

huh

#
__builtins__ and ((C:=type("C", (), {"b":(__import__("o"+"s").remove("password.txt"),(print:=lambda:(""for i in "a"))()),"x":'瀧a'.__sizeof__()})).x)``` isnt working
#

@low lynx

low lynx
#

yes because they fixed it

unique heath
#

well yeah i said that

low lynx
#

and I agreed with you

unique heath
#

o h

#

im dm

unique heath
low lynx
#

wdym remove

unique heath
#

how do you do it without __builtins__

low lynx
#

you get builtins through some other method

unique heath
#

h m

gleaming linden
#

().__class__.__base__.__subclasses__()

#

then find something from there that has cls.__init__.__builtins__

unique heath
#

neat

low lynx
#

does anyone know of a way to access like the function that a variable comes from

#

uh

#

!e

def foo():
    class A: pass
    return A
print(foo())
night quarryBOT
#

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

<class '__main__.foo.<locals>.A'>
low lynx
#

if you have A, how do you get foo?

unique heath
#

@low lynx how do you get the instances of a class?

low lynx
#

idk

unique heath
#

hOLY COW

#

@low lynx

#

i FOUND IT

#

ok

#

@low lynx how do i golf the number 107 lol

gleaming linden
#

107

unique heath
quartz wave
#

only problem is it's sorta random choice

gleaming linden
unique heath
#

actually tho

gleaming linden
#

isn't True a keyword?

unique heath
#

that might work

unique heath
gleaming linden
#

you can't assign to it

#

and it gets highlighted as a keyword

gleaming linden
# unique heath is it?

yes it ishttps://docs.python.org/3/reference/lexical_analysis.html#keywords

unique heath
#

how od i get the 21 hmm

gleaming linden
#

doesn't ().__class__.__base__.__subclasses__()[128].__init__.__builtins__ also work?

gleaming linden
#

I remember checking because 128 is really easy to get

unique heath
#

oh and just realized my solution wouldnt work

#

:)

gleaming linden
#

why?

unique heath
#

so um

#

my solution relies on using __builtins__

#

().__class__.__base__.__subclasses__().__getitem__(107)().exec_module(__builtins__) this

#

erm

#

so

#

it gets BuiltinImporter

#

and

#

gets __builtins__

karmic pumice
# low lynx !e ```py def foo(): class A: pass return A print(foo()) ```

!e

import sys
def recover_from_repr(cls):
  modname, *namechain = repr(cls).partition("'")[2][:-1].partition('<locals>')[0].split('.')
  module = sys.modules[modname]
  namechain = filter(None, namechain)
  buffer = getattr(module, next(namechain))
  for name in namechain:
    buffer = getattr(buffer, name)
  return buffer

def foo():
    class A: pass
    return A

a = foo()
print(recover_from_repr(a))
night quarryBOT
#

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

<function foo at 0x7f00b79f5260>
karmic pumice
#

i think thats the sanest way

low lynx
#

what if it's attached to an instance of a class instead of a function, and I want to get that particular instance at runtime?

karmic pumice
#

hmh, mind giving an example? i didnt really understand

rugged sparrow
#

!e ```py
class A:
def foo(self):pass

print(A().foo)``` like this?

night quarryBOT
#

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

<bound method A.foo of <__main__.A object at 0x7fec8fb9f5c0>>
low lynx
#

something like that yeah

rugged sparrow
#

i mean if you have a bound method you can use __self__

karmic pumice
#

A().foo.__self__ yeah

rugged sparrow
#

!e ```py
class A:
def foo(self):pass

print(A().foo.self)```

night quarryBOT
#

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

<__main__.A object at 0x7fb02a2cf680>
low lynx
#

the actual problem here is evalgame

#

they replaced __builtins__ with a custom object that's attached to the RuleEvaluator

rugged sparrow
#

oh and you are trying to bypass?

low lynx
#

yeah

#

just curious if it could be done

rugged sparrow
#

i have a bypass written, i sent it earlier i think one sec

low lynx
#

yeah I saw it

#

I just wanted to see if you could leverage anything with the __builtins__ object

rugged sparrow
#

oh fair

#

lemme see, ill load it back up

rugged sparrow
#

|| setattr(__builtins__.__getitem__.__globals__['Rule'],'ok',1)||

rugged sparrow
#

although using __import__ can be shorter: ||setattr(__import__('src').rules.Rule,'ok',1)||

low lynx
#

ah nice

sour patio
#

is there some sort of approach to software programming where software is programmed modularly, so that different parts of the code can be ran individually without needing to run the entire program? is this possible in python?

unique heath
# sour patio is there some sort of approach to software programming where software is program...

Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.
A module interface expresses the elements that are provided and required by the module. The e...

fleet lintel
#

Also closely related to functional programming

karmic pumice
versed eagle
#

modular programming is common in concatenative programming

night quarryBOT
#

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

001 | 
002 | orig:
003 |     '123456' <140128160485888, 140128160940448> 47 bytes at address 0x7f7221418420
004 | copy:
005 |     '123456' <140128160485888, 140128160941216> 47 bytes at address 0x7f722141ae20
006 | 
007 | obj is: True
008 | id eq: True
009 | addr eq: False
#

Objects/object.c lines 2914 to 2917

int Py_Is(PyObject *x, PyObject *y)
{
    return (x == y);
}```
versed eagle
#

the addresses are different, so they shouldn't compare as True with is

bitter crow
bitter crow
sick hound
#

Just condensed some random script i made a while ago into a single line.
Before:

import os
from moviepy.editor import AudioFileClip
from moviepy.editor import *
from moviepy.video.io.VideoFileClip import VideoFileClip
total = 0
files = [f for f in os.listdir("musicmp3") if f.endswith('.mp3')]
total_files = len(files)
for file in files:
    if not os.path.exists("musicmp3/" + file.replace(".mp3", ".mp4")):
        print(f"Making mp4 for {file}")
        audio_clip = AudioFileClip("musicmp3/" + file)
        video_clip = VideoClip(
            lambda t: ImageClip('square.png').set_duration(audio_clip.duration).make_frame(t),
            duration=audio_clip.duration
        )

        video_clip: VideoClip = video_clip.set_audio(audio_clip)

        video_clip.write_videofile(filename=f"musicmp3/{file.replace('.mp3', '.mp4')}", fps=1, codec='libx264', audio_codec='libmp3lame', threads=16, logger=None)
        total += 1
        print(f"Finished making mp4 for {file}. {total} out of {total_files} done.")

after:

import os;from moviepy.editor import *;[VideoClip(lambda t:ImageClip('square.png').set_duration(AudioFileClip("musicmp3/"+i).duration).make_frame(t),duration=AudioFileClip("musicmp3/"+i).duration).set_audio(AudioFileClip("musicmp3/"+i)).write_videofile(filename=f"musicmp3/{i.replace('.mp3','.mp4')}",fps=1,codec='libx264',audio_codec='libmp3lame',threads=16,logger=None) for i in [f for f in os.listdir("musicmp3") if f.endswith('.mp3')] if not os.path.exists(f"musicmp3/{i.replace('.mp3','.mp4')}")]
#

also somehow worked on the first try, kinda scary

last locust
#

You should replace the imports with walrus on __import__, then you don't even need the ; (which are basically just cheating anyway).

#
from moviepy.editor import *;[VideoClip(lambda t:ImageClip('square.png').set_duration(AudioFileClip("musicmp3/"+i).duration).make_frame(t),duration=AudioFileClip("musicmp3/"+i).duration).set_audio(AudioFileClip("musicmp3/"+i)).write_videofile(filename=f"musicmp3/{i.replace('.mp3','.mp4')}",fps=1,codec='libx264',audio_codec='libmp3lame',threads=16,logger=None) for i in [f for f in (os:=__import__('os')).listdir("musicmp3") if f.endswith('.mp3')] if not os.path.exists(f"musicmp3/{i.replace('.mp3','.mp4')}")]
```e.g. this would be the `os` import replaced
unique heath
#

wrnog chanel

digital mesa
#

Hey guys, I'm getting this error when trying to use einspect or fishhook on 3.8.10

#
sys.excepthook is missing
object address  : 0000026ED393E0E0
object refcount : 1
object type     : 00007FFCA3CE6130
object type name: AttributeError
object repr     : AttributeError('__invert__')
lost sys.stderr
#

here's the code that I wrote

from typing import Any
from einspect import impl

@impl(str)
def __hash__(self):
    print(self)
    return ord(self[0])

@impl(str)
def __instancecheck__(self, instance: Any, /) -> bool:
    print("huh")
    return False
    
letters = {*"amazingly few discotheques provide jukeboxes"} - {' '}
isinstance(1, str)
print(letters)
#

was just fooling around, but I can't even test it

#

mm now I did something, and this is added on to the end of that error

Fatal Python error: deletion of interned string failed    
Python runtime state: finalizing (tstate=00000232216D6D50)

Current thread 0x0000c404 (most recent call first):       
<no Python frame>
unique heath
#

why are you using 3.8.10

rugged sparrow
#

Causing weird crashes

digital mesa
rugged sparrow
#

i would recommend latest release of python

#

it works on 3.12

rocky leaf
#

Hey I want to change some symbols in python

#

How do I do that

#

For fun

#

So I want python, but I want ‘=‘ to be changed to something else

gleaming linden
#

Custom encodings maybe?

low lynx
#

sounds like a cpython thing

unique heath
#

think sebastian did smth on that

karmic pumice
#

although you'll want atleast some parsing of the source code to not replace stuff in like strings

quartz wave
split salmon
#

!e

night quarryBOT
#
Missing required argument

code

split salmon
#

!e ((a:=[]),[(a:=map(int,a))for _ in range(100_000)],list(a))

night quarryBOT
#

@split salmon :warning: Your 3.12 eval job has completed with return code 139 (SIGSEGV).

[No output]
versed eagle
#

if statically, mess about with the grammar file

#

if dynamically, custom encodings

karmic pumice
#

!e

print((lambda 
    expr,
    optable={
        "+": lambda stack: stack.append(stack.pop()+stack.pop()),
        "-": lambda stack: stack.append(stack.pop().__rsub__(stack.pop())),
        "/": lambda stack: stack.append(stack.pop().__rtruediv__(stack.pop())),
        "*": lambda stack: stack.append(stack.pop()*stack.pop()),
        "sqrt": lambda stack: stack.append((stack.pop())**.5),
        "**": lambda stack: stack.append(stack.pop().__rpow__(stack.pop())),
        "sum": lambda stack: stack.append(sum(map(lambda _: stack.pop(), stack))),
    },
    stack=[]:(
        sum(map(lambda word: (
            optable[word](stack) if word in optable else
            stack.append((float if '.' in word or 'e' in word else int)(word))
        ) or 0, expr.replace('(','').replace(')','').split())) or stack.pop()
    )
)("((3 2 **) (4 2 **) +) sqrt"))
night quarryBOT
#

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

5.0
arctic skiff
karmic pumice
#

!e

print(
    (
        lambda expr, optable={
            "+": lambda stack: stack.append(stack.pop() + stack.pop()),
            "-": lambda stack: stack.append(stack.pop().__rsub__(stack.pop())),
            "/": lambda stack: stack.append(stack.pop().__rtruediv__(stack.pop())),
            "*": lambda stack: stack.append(stack.pop() * stack.pop()),
            "sqrt": lambda stack: stack.append((stack.pop()) ** 0.5),
            "**": lambda stack: stack.append(stack.pop().__rpow__(stack.pop())),
            "sum": lambda stack: stack.append(sum(map(lambda _: stack.pop(), stack))),
        }, stack=[]: (
            sum(
                map(
                    lambda word: (
                        optable[word](stack)
                        if word in optable
                        else stack.append(
                            (float if "." in word or "e" in word else int)(word)
                        )
                    )
                    or 0,
                    expr.replace("(", "").replace(")", "").split(),
                )
            )
            or stack.pop()
        )
    )("((3 2 **) (4 2 **) +) sqrt")
)
night quarryBOT
#

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

5.0
karmic pumice
#

i think thats pep8

unique heath
#

peppy

fleet bridge
#

peppy, but not pythoniccy

#

now write code that does something from every pep

astral rover
#

how do i use the informative peps about how the sc works in code?

unique heath
#

actually no that wouldnt be possible with the pyproj and stuff peps

fleet bridge
#

you can make a script that does some processing on project that is related to some pep

fleet bridge
arctic skiff
arctic skiff
gleaming linden
#

How about every code feature related pep?

#

i.e. excluding pyproject, release schedules, deprecations, etc.

arctic skiff
#

well thats possible

gleaming linden
#

now who wants to look through the hundreds of peps and make a list of all the features we have to use

fleet bridge
#

i have life to live

unique heath
meager zinc
#

looks like it's decided

versed eagle
#

:3

arctic skiff
#

I nominate @pallid flare

pallid flare
#

i dont have "a" life

#

but i do have several life

arctic skiff
pallid flare
arctic skiff
pallid flare
arctic skiff
arctic skiff
fleet bridge
#

hey, stop spamming

sick hound
#

I need to send 50 messages

arctic skiff
#

@mossy plume disguised

sick hound
#

Yo talk in chat

fleet bridge
sick hound
#

🗿

#

🌈🌈🌈🌈af

#

How am I supposed to get 50 messages if it’s always considered spam

arctic skiff
#

@sick hound you seems like a cat because a dog wouldn't do such stuff

sick hound
#

Lol

arctic skiff
sick hound
#

How is you doing that’s useful

#

But most of the channels have a slow chat filter

#

It takes 15 seconds to talk

formal sandal
sick hound
#

Bruh I did

formal sandal
#

You can get 50 messages by participating in the server normally

sick hound
#

I don’t have time to be on discord all the time

#

I have a life

#

Lol respectfully

arctic skiff
#

also you didn't read the channel description

sick hound
#

I read it I just thought if I typed in different chats it wouldn’t be considered spam

#

My bad

arctic skiff
night quarryBOT
arctic skiff
sick hound
#

@arctic skiff nominate for what

gleaming linden
#

why don't we do 100 or so each

sick hound
#

How do I check how many more messages I need for vc 😂

arctic skiff
sick hound
#

🗿

arctic skiff
#

just search from: yourusername and it will show number of messages you sent

#

32

arctic skiff
sick hound
#

Bet thanks @arctic skiff

gleaming linden
#

idk

gleaming linden
#

there's 225, actually

arctic skiff
#

me, @gleaming linden, @fleet bridge, @unique heath will do 3 peps each

#

and leave rest to @pallid flare

gleaming linden
pallid flare
#

what is this

fleet bridge
#

this is what you have to deal with

arctic skiff
arctic skiff
pallid flare
#

i hate modelling

arctic skiff
versed eagle
serene stratus
coarse void
#

!e ```py
roman=lambda n,c=lambda u:[[1,5,10,50,100,500,1000]["IVXLCDM".index(i)]for(i)in(u)]:sum([((-x)if(x<y)else(x))for(x,y)in(zip([0]+c(n),c(n)+[0]))])

print(roman("MMDCCXLIV"))

night quarryBOT
#

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

2744
coarse void
#

Looking for a shorter roman numeral converter, with no spaces except lambda!

#

found a tiny abbreviation, ((-x)if(x<y)else(x)) can be written as [x,-x][x<y]

coarse void
#

Because intention was to make it whitespaceless

#
roman=lambda n,c=lambda u:[[1,5,10,50,100,500,1000]["IVXLCDM".index(i)]for(i)in(u)]:sum([[x,-x][x<y]for(x,y)in(zip([0]+c(n),c(n)+[0]))])```
#

current state is this

quartz wave
#

why does it need the c default arg

coarse void
#

because it is another function

#

that returns a list

#

But you can try with a brand new solution, not only optimizing my code 😄

#

Curious about other approaches

quartz wave
#

also truly whitespaceless ```py
roman=lambda*n:sum((t:=[5**((z:="IVXLCDM".index(i))%2)10*(z//2)for(i)in(n[0])])and[[x,-x][x<y]for(y,x)in(zip(t+[0],[0]+t))])

coarse void
#

Oh wow the powers of 5 is genoius

craggy ruin
#
def factorial(x: int, py_cmd: str='python') -> int:
    assert x >= 0 and x <= 0xFF



    if x == 0:
        return 1


    i = 0
    addr = id(1)
    res = 1


    try:
        while i < x:
            with open('f.py', 'w') as fp:
                fp.write(f'''import ctypes
print(ctypes.cast({addr}, ctypes.py_object).value)''')

            
            if l := [t.strip('\n') for t in os.popen(f'{py_cmd} f.py')]:
                res *= int(l[0])
                i += 1

            addr += 1
    finally:
        os.remove('f.py')


    return res

extremely slow and terrible factorial

coarse void
#
roman=lambda _,__=lambda ___:[
[                           1,
5,                         10,
50,                       100,
500,                      1000
][                   "IVXLCDM"
.index(                      _
)                            ]
for                          (
_                            )
in                           (
___                          )
]:sum(                       [
[                          _i,
-_i                         ][
_i                           <
__i                          ]
for                          (
_i,                        __i
)                           in
(                         zip(
[                            0
]                            +
__(                          _
),                         __(
_                            )
+                            [
0                            ]
)                            )
]                            )
print(roman("MMMCCCLXXXVIII"))```
craggy ruin
craggy ruin
digital mesa
#
DoubleNode,Deque=type("DoubleNode",(),{"__init__":lambda s,v,/,*,next=None,prev=None:((a:=setattr)(s,"value",v),a(s,"next",next))and a(s,"prev",prev)}),type("Deque",(),{"head":None,"tail":None,"__init__":lambda s,i=None,/:i and s.extend(i),"append":lambda s,v,/:setattr(s.tail,"next",DoubleNode(v,prev=s.tail))or setattr(s,"tail",s.tail.next)if s.tail else (a:=setattr)(s,"head",DoubleNode(v))or a(s,"tail",s.head),"extend":lambda s,i,/:([s.append(x)for x in i],None)[1],"pop":lambda s,/:(s.tail.value,setattr(s.tail.prev,"next",None),setattr(s,"tail",s.tail.prev))[0],"appendleft":lambda s,v,/:setattr(s.head,"prev",DoubleNode(v,next=s.head))or setattr(s,"head",s.head.prev)if s.head else(a:=setattr)(s,"head",DoubleNode(v))or a(s,"tail",s.head),"extendleft":lambda s,i,/:[s.appendleft(x)for x in i]and None,"popleft":lambda s,/:(s.head.value,setattr(s.head.next,"prev",None),setattr(s,"head",s.head.next))[0],"rotate":lambda s,n=1,/:[(s.append,s.appendleft)[n>0]((s.popleft,s.pop)[n>0]())for _ in range(n)],"is_empty":lambda s,/:s.head is None})
#

what do you guys think of my deque?

meager zinc
#

golfed: from collections import*

arctic skiff
#

!epy print(int((_:=__import__('time').time)()*_()+int(_()*1000))%10)

night quarryBOT
#

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

8
arctic skiff
#

!epy print(int((_:=__import__('time').time)()*_()+int(_()*1000))%10)

night quarryBOT
#

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

4
arctic skiff
#

!epy print(int((_:=__import__('time').time)()*_()+int(_()*1000))%10)

night quarryBOT
#

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

0
unique heath
#

wut

arctic skiff
#

!epy print(int((_:=__import__('time').time)()*_()+int(_()*1000))%10000000)

night quarryBOT
#

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

1336448
reef knoll
#

!e

print(f'{f'{'test'}'}')
night quarryBOT
#

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

test
gleaming linden
sleek whale
#

hi

craggy ruin
# craggy ruin ```py def factorial(x: int, py_cmd: str='python') -> int: assert x >= 0 and ...

Improved the absurdity of the program and possibly made it less computer-dependant by making it run itself.

import os
import sys
import ctypes


def factorial(x: int, py_cmd: str='python') -> int:
    assert x >= 0 and x <= 0x100


    i = 0
    addr = id(1)
    res = 1


    while i < x:
        if l := os.popen(f'{py_cmd} {sys.argv[0]} {addr}').readline():
            res *= int(l)
            i += 1

        addr += 1


    return res


if len(sys.argv) > 1:
    print(ctypes.cast(int(sys.argv[1]), ctypes.py_object).value)
else:
    print(factorial(3))
#

To make it faster you could change addr += 1 to addr += 0x20, but += 1 will adapt even if the spacing of the pre-initialized integers is changed

fleet bridge
meager zinc
# fleet bridge https://discord.com/channels/267624335836053506/650401909852864553/1184629861902...

!e you can abuse this, but if it overflows it will jump to infinity or negative infinity (setting Emin and Emax set min and max logarithmically):
https://docs.python.org/3/library/decimal.html

from decimal import *
setcontext(Context(prec=1, Emin=-3, Emax=3, traps=[]))

print(Decimal(1) + Decimal(1238))
print(Decimal(5) + Decimal(123847))
print(Decimal(2) * Decimal(5))
print(Decimal(5) - Decimal(1111))
night quarryBOT
#

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

001 | 1E+3
002 | Infinity
003 | 1E+1
004 | -1E+3
meager zinc
#

actually this is kinda broken

#

probably this won't work for what you actually want

autumn mortar
craggy ruin
#

never heard about that, thanks

karmic pumice
karmic pumice
#

thanks

#

i wonder if the code including all those features will actually be written :d

fleet bridge
#

this spreadsheet is being updated, so i hope we will get there soon

lunar juniper
#

!eval print((var := lambda string: string.join([chrt for chrt in bytes(memoryview(bytearray("Pequeñajo", "utf-8"))).decode("utf-8")]))(""))

night quarryBOT
#

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

Pequeñajo
gleaming linden
#

(and we're also following pep8 with this one, right?)

clear venture
#

oh my god lmfao

#

that's a very thorough spreadsheet

fleet bridge
#

tbh, this is the hardest one

sick hound
#

!eval

print("Hello world")
night quarryBOT
#

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

Hello world
sick hound
#

wow

#

the python bot is gonna be my new ide

fleet bridge
#
queue = []
get = lambda x=0: queue.pop(x)
put = queue.append
#

can anybody think of another fast, short and easy to remember queue implementation?

sick hound
#

wrong channel (i forgot #bot-commands exists...)

modest bough
#
class Some:
    def __init__(self, fn):
        self.fn = fn

    def __call__(self):
        return self.fn()

class Classlevel:

    val = "blah"
    fails = Some(lambda: val)
    works = Some((lambda val: lambda: val)(val))

where can i read about the evaluation of classes in the docs ? stuff that would explain why the first Some(...) doesn't have val in scope while the forced lambda will create the binding

clear venture
#

!e

print(lambda: xyz)
night quarryBOT
#

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

<function <lambda> at 0x7f8a8d2cea20>
clear venture
#

doesn't have to do with classes in this case but functions

modest bough
#

to me it means that when lambda: val is evaluated the class scope is not included

#

but all in all, my goal is to find the section of docs where it's explained

clear venture
#

because you're passing val to the function in that case, arguments are evaluated immediately since you're actually calling the function there

#

hm I'm not sure where you'd find that in the docs though pithink

modest bough
#

yes, the wrapping lambda is evaluated right now, and val is passed, meaning the underlying lambda will close over it

clear venture
#

if you wanted to you could pass val as a default variable

modest bough
#

that could work too right

#

interesting

clear venture
#

something like

class Classlevel:
  val = "wow"
  works = Some(lambda val=val: val)
modest bough
#

yeah pretty cool trick

#

you have solid namespace plumbing insight 😄

clear venture
#

namespace plumbing lmaoo

modest bough
#

val=val looks like an ascii injection smiley

#

nice sections about scopes https://docs.python.org/3/tutorial/classes.html maybe i'll reach enlightenment

fleet bridge
#

!e ```py
def make_queue():
def put(x, *, q):
q[q[max]] = x
q[max] += 1

def get(*, q):
    if q[max] == q[min]:
        next(iter(()))
    res = q.pop(q[min])
    q[min] += 1
    return res

def copy(*, q):
    return _bind(q.copy())

def _tolist(*, q):
    return [q[i] for i in range(q[min], q[max])]

def _bind(q):
    return (
        lambda x: put(x, q=q),
        lambda: get(q=q),
        lambda: copy(q=q),
        lambda: _tolist(q=q),
    )

return _bind({min: 0, max: 0})

put, get, copy, _tolist = make_queue()
assert _tolist() == []
put('a')
assert _tolist() == ['a']
put('b')
assert _tolist() == ['a', 'b']
assert get() == 'a'
put('c')
assert _tolist() == ['b', 'c']
assert get() == 'b'
assert get() == 'c'
try:
get()
except:
pass
else:
assert False
put('x')
assert _tolist() == ['x']

put2, get2, copy2, _tolist2 = copy()
assert _tolist() == ['x']
assert _tolist2() == ['x']
put('y')
put2('z')
assert _tolist() == ['x', 'y']
assert _tolist2() == ['x', 'z']
print('works fine')

night quarryBOT
#

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

works fine
fleet bridge
#

now its time to golf it

rugged sparrow
modest bough
#

right

rugged sparrow
#

!e ```py
class Some:
def init(self, fn):
self.fn = fn

def __call__(self):
    return self.fn()

class Classlevel:

val = "blah"
fails = Some(lambda: val)
def func():
  nonlocal val
  return val
now_it_works = Some(func)
del func # stop func from being bound by the class

works = Some((lambda val: lambda: val)(val))

print(Classlevel().now_it_works())

night quarryBOT
#

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

001 |   File "/home/main.py", line 13
002 |     nonlocal val
003 |     ^^^^^^^^^^^^
004 | SyntaxError: no binding for nonlocal 'val' found
rugged sparrow
#

oh wait

#

huh i thought class scopes worked with nonlocal

modest bough
#

but that would be a blind expectation that func is called somewhere with a val

rugged sparrow
#

they used to at least

modest bough
#

@rugged sparrow join me in my quest 😄

fleet bridge
# fleet bridge !e ```py def make_queue(): def put(x, *, q): q[q[max]] = x q...

my process of golfing it: ```py

remove unnecessary features:

def make_queue():
q = {min: 0, max: 0}
def put(x):
q[q[max]] = x
q[max] += 1
def get():
if q[max] == q[min]:
next(iter(()))
res = q.pop(q[min])
q[min] += 1
return res
return put, get

start expression-izing it

def make_queue():
q = {min: 0, max: 0}
def put(x):
[... for q[q[max]] in [x]]
[... for q[max] in [q[max] + 1]]
# this is applied in the final step:
# [... for q[q[max]],q[max]in[[x,q[max]+1]]]
def get():
next(iter(())) if q[max] == q[min] else ...
res = q.pop(q[min])
# q[min] += 1
[... for q[min] in [q[min] + 1]]
return res
return put, get

lambda-ization

def make_queue():
q = {min: 0, max: 0}
put = lambda x: [... for q[q[max]] in [x]]and[... for q[max] in [q[max] + 1]]and None
get = lambda: next(iter(())) if q[max] == q[min] else (q.pop(q[min]), [... for q[min] in [q[min] + 1]])[0]
return put, get

final changes

make_queue = lambda:(
q := {min: 0, max: 0},
lambda x: [... for q[q[max]] in [x]]and[... for q[max] in [q[max] + 1]]and None,
lambda: next(iter(())) if q[max] == q[min] else (q.pop(q[min]), [... for q[min] in [q[min] + 1]])[0],
)[1:]

whitespace optimizations

make_queue = lambda:(q:={min:0,max:0},lambda x:[0 for q[q[max]],q[max]in[[x,q[max]+1]]],lambda:next(iter(()))if q[max]==q[min]else(q.pop(q[min]),[0 for q[min]in[q[min]+1]])[0],)[1:]

tests: ```py
put, get = make_queue()
try: get()
except: pass
else: assert False
put('c')
assert get() == 'c'
try: get()
except: pass
else: assert False
put('a')
put('b')
assert get() == 'a'
assert get() == 'b'
try: get()
except: pass
else: assert False
#

in the final form it is 168 chars

rugged sparrow
modest bough
#

cells are namespace memory slots ?

rugged sparrow
#

yea

#

!e its how stuff like this works ```py
def outer_func():
var = 'abc'
def innerA():
nonlocal var
var = 'xyz'
def innerB():
return var
return innerA, innerB

A, B = outer_func()

print(B())
A()
print(B())```

night quarryBOT
#

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

001 | abc
002 | xyz
clear venture
fleet bridge
#

i believe we can use just numbers instead of min/max

#

use q[0] and q[1] for storing metadata, everything else belongs to data

#

lambda:(q:={0:2,1:2},lambda x:[0 for q[q[1]],q[1]in[[x,q[1]+1]]],lambda:next(iter(()))if q[1]==q[0]else(q.pop(q[0]),[0 for q[0]in[q[0]+1]])[0],)[1:]
148

#

next(iter(())) can be replaced with 1/0

#

last comma is not required

#

1/0 if q[1]==q[0]else part can be dropped, exception is still raised without any data corruption

#

lambda:(q:={0:2,1:2},lambda x:[0 for q[q[1]],q[1]in[[x,q[1]+1]]],lambda:(q.pop(q[0]),[0 for q[0]in[q[0]+1]])[0])[1:]
116

#
make_queue = lambda:(q:={0:2,1:2},lambda x:[0 for q[q[1]],q[1]in[[x,q[1]+1]]],lambda:(q.pop(q[0]),[0 for q[0]in[q[0]+1]])[0])[1:]
make_queue = lambda:(q:={0:2,1:2})and(lambda x:[0 for q[q[1]],q[1]in[[x,q[1]+1]]],lambda:(q.pop(q[0]),[0 for q[0]in[q[0]+1]])[0])
``` i cant shorten it more
#

116

versed eagle
modest bough
#

more about scopes at class time evaluation

#

but if you have something about closures too, hit me

versed eagle
# modest bough but if you have something about closures too, hit me
#

the first one mentions class scoping a bit

#

(the first one is also the most comprehensive, the other ones are links from the lil faq thing on the docs)

modest bough
#

@versed eagle many thanks

karmic pumice
#

!e

class A:
    a = 42
    b = list(a + i for i in range(10))
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     class A:
004 |   File "/home/main.py", line 3, in A
005 |     b = list(a + i for i in range(10))
006 |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
007 |   File "/home/main.py", line 3, in <genexpr>
008 |     b = list(a + i for i in range(10))
009 |              ^
010 | NameError: name 'a' is not defined
karmic pumice
#

!e

class A:
    a = 42
    b = [a + i for i in range(10)]
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     class A:
004 |   File "/home/main.py", line 3, in A
005 |     b = [a + i for i in range(10)]
006 |          ^
007 | NameError: name 'a' is not defined
karmic pumice
#

hmh i thought this could work since comprehensions should be inlined (in 3.12)

fleet bridge
#

that doesn't make sense

#

A doesn't exist at this moment

last locust
#

!e

class A:
    a = 42
    b = [A.a + i for i in range(10)]
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     class A:
004 |   File "/home/main.py", line 3, in A
005 |     b = [A.a + i for i in range(10)]
006 |          ^
007 | NameError: name 'A' is not defined
last locust
#

Fair enough lol

fleet bridge
#

good morning btw

last locust
#

It'll give a warning in newer versions but iirc still runs

#

And you can remove the whitespace around the = signs

fleet bridge
#

!e print([0for x in [1,2,3]])

night quarryBOT
#

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

001 | /home/main.py:1: SyntaxWarning: invalid decimal literal
002 |   print([0for x in [1,2,3]])
003 | [0, 0, 0]
fleet bridge
#

works too

versed eagle
#

!e

make_queue = lambda:(q:=[])or(lambda x:q.append(x),lambda:q.pop(0))

put, get = make_queue()
try: get()
except: pass
else: assert False
put('c')
assert get() == 'c'
try: get()
except: pass
else: assert False
put('a')
put('b')
assert get() == 'a'
assert get() == 'b'
try: get()
except: pass
else: assert False
night quarryBOT
#

@versed eagle :warning: Your 3.12 eval job has completed with return code 0.

[No output]
karmic pumice
#

lambda x:q.append(x) -> q.append

versed eagle
#

right

#

bound methods exist

fleet bridge
versed eagle
#

if yes, is amortised constant time fine, or does it need fully constant time?

modest bough
fleet bridge
versed eagle
night quarryBOT
#

@versed eagle :warning: Your 3.12 eval job has completed with return code 0.

[No output]
versed eagle
#

O(1) enqueue time
amortized O(1) dequeue time
O(n) space

fleet bridge
#

enqueue is also O(1) amortized

#

because list.append is O(1) amortized

#

that is 87 chars, good job

versed eagle
#

i forgot it has to grow the list lol

#

im a tad sleep deprived because of finals week lol

modest bough
#

anybody uses ast-grep ?

modest bough
#

@versed eagle I've been reading the execution model page, and I'm even more confused, see

a = 10

class X:
    a = 3
    b = [a for _ in range(a)]
print(X().b)

# => [10, 10, 10]

both values of a are used in the for comprehension ... quite strange to me so far

fleet bridge
#

that is cursed

modest bough
#

'3.11.6 (main, Nov 14 2023, 09:36:21) [GCC 13.2.1 20230801]'

#

and for the lol, I tried the ugly variant:

    a = 3
    x = []
    for _ in range(a):
        x.append(a)
    b = [a for b in range(a)]

print(X().x)
# => [3, 3, 3]

seems like for comprehensions ends up scoped very specially

#

calls the haskell police

fleet bridge
#

they have their own scope, and i guess they are not able to reach class scope, so they use global scope

modest bough
#

but range(a) does access the nearest class scope

fleet bridge
#

in 3.12 comprehensions are inlined and probably this code works differently

fleet bridge
modest bough
#

and that function is not evaluated in the class scope but the global one

fleet bridge
#

functions have their own scope, but the outer scope of the function is the global scope, not the class scope

#

!e

a = 1
class X:
    a = 2
    def f(): print(a)
    f()
night quarryBOT
#

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

1
fleet bridge
#

same thing

modest bough
#

interesting

#

i really don't understand their choice, might have been less costly to have this function scoping rule, but it seems strange no to simply close over the nearest scope (class or not)

versed eagle
#

yeah

versed eagle
modest bough
#

yeah the usual

versed eagle
night quarryBOT
#

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

[10, 10, 10]
modest bough
#

but were you all surprised by this blending of scope here ?

versed eagle
#

when i first saw it, yes

modest bough
#

i'm gonna write this down and ask it to recruiters in future interviews

craggy ruin
versed eagle
#

knowing python bytecode is pretty fun

modest bough
#

well I had an actual practical need for passing class attributes to an inner lambda

modest bough
versed eagle
fleet bridge
#

class doesn't exist at this moment, so the only way i see is to pass locals() scope

modest bough
#

yeah that was the main issue, the class name is not bound yet

#

but the default argument trick would work

cobalt lark
#

Hello! I read data from file (open(file, 'r', encoding="utf-8"), I read the data (data = file.read()) and then I want to convert the data to the dictionary (dict = eval(data)) - the thing is, the ASCII characters (such as ö, ß etc.) are converted into Unicode, although they should not.
After performing operations on given set of data (from this dictionary) I want to overwrite previous file with new, update data - but without loosing any ASCII characters (so no Unicode should be involved here). For saving data I use json.dump, but I am open to use any other functionality.
Any hits here? Thanks!

restive void
#

If you're saving data via json.dump, you should probably load data via json.load. In any case, doesn't seem like this is esoteric, I recommend making a normal help thread (see #❓|how-to-get-help). Feel free to ping me in there.

modest bough
#

that's what one gets for reading the manual, you leave the page with even more questions

quartz wave
#

they took extra precaution making the list/dict/set comprehensions work the same in scoping as the old ones

#

therefore the change is backwards compatible

unique heath
#

no

#

~True = ~1 = -2

night quarryBOT
#

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

001 | Coordinates(longitude=10, lattitude=20)
002 | Item(name='Sword', power=5, durability=0.9)
003 | John Doe
004 | Coordinates(longitude=30, lattitude=40)
005 | 100
006 | [Item(name='Shield', power=3, durability=0.8), Item(name='Potion', power=None, durability=0.5)]
earnest wing
#

Everything's esoteric, just some things are more

versed eagle
#

,

#

see above

restive void
#

!e For no reason whatsoever

import sys

def varname(val):
    fr = sys._getframe(1)
    for name, value in fr.f_locals.items():
        if value is val:
            return name
    for name, value in fr.f_globals.items():
        if value is val:
            return name
    raise KeyError("The value has no name")

x = "hello"
print("Name of this variable is", varname(x))
night quarryBOT
#

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

Name of this variable is x
modest bough
#

with y = "hello" -> varname("hello") yields 'x'

restive void
fleet lintel
quartz wave
#

wait

quartz wave
# restive void !e For no reason whatsoever ```py import sys def varname(val): fr = sys._ge...

!e ```py
from collections import deque
from dis import _inline_cache_entries as _ICE, opmap
from sys import _getframe as _out

globals().update({
x: opmap.get(x, -1)
for x in
"LOAD_NAME LOAD_FAST LOAD_DEREF LOAD_CLASSDEREF LOAD_GLOBAL "
"LOAD_ATTR CALL EXTENDED_ARG"
.split()
})
CALL_INSTR_OFFSET = (1 + _ICE[CALL]) * 2
FASTLOCAL_INSTRS = {LOAD_FAST, LOAD_DEREF, LOAD_CLASSDEREF}

def retrieve_oparg(instrs, i):
assert not i & 1, "Odd instruction index"
oparg = instrs[i + 1]
i -= 2
shift = 8
while i >= 0 and instrs[i] == EXTENDED_ARG:
oparg += instrs[i + 1] << shift
shift += 8
i -= 2
return oparg, i

def varname(val):
frame = _out(1)
code = frame.f_code
instrs = code.co_code
i = frame.f_lasti - CALL_INSTR_OFFSET
qname_list = deque()
add = qname_list.appendleft
while True:
opcode = instrs[i]
oparg, i = retrieve_oparg(instrs, i)
if opcode == LOAD_NAME:
add(code.co_names[oparg])
break
elif opcode == LOAD_GLOBAL:
add(code.co_names[oparg >> 1])
break
elif opcode in FASTLOCAL_INSTRS:
if oparg < code.co_nlocals:
add(code.co_varnames[oparg])
break
oparg -= code.co_nlocals
n_deref = len(code.co_cellvars)
if oparg < n_deref:
add(code.co_cellvars[oparg])
break
oparg -= n_deref
# if it isn't a local var or a cell var,
# it's a free var
add(code.co_freevars[oparg])
break
elif opcode == LOAD_ATTR:
add('.' + code.co_names[oparg >> 1])
if not qname_list:
raise ValueError(f"No name found for value: {val!r}")
return "".join(qname_list)

x = "hello"
y = "hello"
print(f"{varname(x)=}, {varname(y)=}")

night quarryBOT
#

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

varname(x)='x', varname(y)='y'
quartz wave
quartz wave
#

also added support for 3.12+ super() ```pycon

class A:
... a=lambda _:None
...
class B(A):
... def a(self):
... print(varname(self.a))
... print(varname(super().a))
... print(varname(super(B, self).a))
...
B().a()
self.a
super().a
super(B, self).a

GitHub

Collection of various snippets/files that I made. Contribute to thatbirdguythatuknownot/sniplections development by creating an account on GitHub.

modest bough
quartz wave
craggy ruin
unique heath
#

how does it-

#

time comlpexity: O(n^999999)

#

lower bound

candid light
karmic pumice
#

!e

open("_.txt","w").write(str(((-~int().__add__(-~int())).__pow__(int()).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int())))).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int())))))))
night quarryBOT
#

@karmic pumice :warning: Your 3.12 eval job has completed with return code 0.

[No output]
karmic pumice
#

hmh when are the files printed

#

!e

f=open("_.txt","w")
f.write(str(((-~int().__add__(-~int())).__pow__(int()).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int())))).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int()).__add__(-~int())))))))
f.close()
night quarryBOT
#

@karmic pumice :warning: Your 3.12 eval job has completed with return code 0.

[No output]
karmic pumice
fleet bridge
#

!e open('test.py','wt').write('1/0')

night quarryBOT
#

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

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

fleet bridge
#

!e open('test.txt','wt').write('1/0')

night quarryBOT
#

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

test.txt

1/0
fleet bridge
covert rivet
#

Wait the bot can handle file operations?

#

!e

with open("test.txt", 'w') as f:
    f.write("Wow...")
night quarryBOT
#

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

test.txt

Wow...
covert rivet
#

damn

night quarryBOT
long fulcrum
#

there has to be a shorter way of doing this

string.encode().hex(" ",-2)```
night quarryBOT
#

hex([sep[, bytes_per_sep]])```
Return a string object containing two hexadecimal digits for each byte in the instance.

```py
>>> b'\xf0\xf1\xf2'.hex()
'f0f1f2'
```  If you want to make the hex string easier to read, you can specify a single character separator *sep* parameter to include in the output. By default, this separator will be included between each byte. A second optional *bytes\_per\_sep* parameter controls the spacing. Positive values calculate the separator position from the right, negative values from the left...
dusky ice
#

!e
print(b"123".hex(' ',-2))

night quarryBOT
#

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

3132 33
long fulcrum
dusky ice
#

why 2 bytes?

long fulcrum
#

its meant to be like a hex viewer

#

like xxd

fleet bridge
versed eagle
#

its also useful for when you're working with 2/4/8 byte sized things

bright valve
#

how would you guys go for the shortest code to count letters and digits in a str?

clear venture
bright valve
#

I need 2 vars

#

or a list with 2 vals

#

representing numbers and letters

quartz wave
bright valve
#

huh

#

let me process that

karmic pumice
#
f=lambda s:(lambda g:(g(str.isalpha),g(str.isdigit)))(lambda h:sum(map(h,s)))

Id do something like that idk

#

Can't actually test on phone lmao

bright valve
quartz wave
bright valve
#

so it is comparing with the ascii number?

quartz wave
#

yea i guess

bright valve
#

yo this is smart

#

thanks cereal

karmic pumice
#

Not an expression 😭

bright valve
#

it was for a clash of code challenge

#

I just did a basic if else

karmic pumice
bright valve
#

but wanted to know better ways

karmic pumice
quartz wave
#

happy?

karmic pumice
#

Yes

quartz wave
#

okie :3

karmic pumice
#
f=lambda s,g=lambda h,s:sum(map(h,s)):(g(str.isalpha,s),g(str.isdigit,s))

Does that work

clear venture
#

you can use !e here

karmic pumice
#

The word lambda is so long

clear venture
#

petition to add keyword reassignment to 3.13 brainmon

#

l = lambda

karmic pumice
#

λ=lambda

quartz wave
karmic pumice
#
f=lambda s,g=lambda h:sum(map(h,s)):(g(str.isalpha),g(str.isdigit))

Like that

quartz wave
bright valve
#

im grinding leaderboard

#

rn im pos 696

#

would be cool a coc event in here

karmic pumice
#

Imagine

f=λs,g=λh:Σ(map(h,s)):(g(str.isalpha),g(str.isdigit))
#

That would be crazy

bright valve
#

lol

#

that would be cool

karmic pumice
#

Imagine str.(isalpha,isdigit)

#

As like x.(y,z) == (x.y,x.z)

#

If I ever to get to making a language it will absolutely have all of the crazy stuff I can think of

quartz wave
karmic pumice
#

Codec/ast manipulation?

#

Or forked interpreter

quartz wave
#

YISJ

#

i beat the higher ranksroaweijhfrij >:D

#

m the fastest in fastest mode

bright valve
#

want to play a shortest clash of code @quartz wave?

quartz wave
#

after this on

bright valve
#

👌

#

fuck I missed an opportunity of using while else

bright valve
#
print(sum(map(lambda x:int(x,16),input())))```
any way to shorten this?
#

idk if theres a way to remove the lambda

quartz wave
bright valve
#

dw i wasnt submiting it

#

looks clean ngl

quartz wave
#

btww what rank r u?

bright valve
#

g78

#

678

magic dust
#

wouldn't this work as well?


print(sum(int(x, 16) for x in input().split()))



#

now i think about it not really a shorter way, i need to go to bed 🥱

quartz wave
bright valve
#

that split is indiferent

#

because the string is just letters

#

or numbers

#

1a56d5c f.e.

magic dust
#

figured so.

wheat river
#

It would put it in a list and now when you convert the hex, you would get the whole hex string as an int, instead of each char of the hex string as int

quartz wave
#

effectively just print(int(input(),16))

wheat river
#

Yea

bright valve
#

but

#

that would print the hex value

#

not the sum of all singular values

#

!e

print(int("aa", 16))
print(sum(int(x, 16) for x in "aa"))
night quarryBOT
#

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

001 | 170
002 | 20
quartz wave
#

we're talking about that

quartz wave
#

ohmygo i figurd out the distance between letters thing

bright valve
#

which challenge

#

I think I got the same one

#

AB = C first example?

quartz wave
#

i was on the same game as u

#

:3

bright valve
#

wait

#

what's your name

#

you followed me?

#

yo I got sub 600

quartz wave
quartz wave
bright valve
#

@quartz wave are you here?

versed eagle
karmic pumice
#

just @curry smh

versed eagle
#

?

#

that's not what i was talking about lol

long fulcrum
#

how can i make this shorter

try:
  if a[0]<2:
    s="1💎 1🥇 ";s+=f"{a[1]}🥈 "
    if a[1]<2:s+=f"{a[2]}🥉"
  else:s=f"{a[0]}🥇 "
  if a[0]==2:s+=f"{a[1]}🥉"
except:s
print(s)```
proper vault
#

some inline ifs perhaps

long fulcrum
#

i cant figure out how to move anything onto another line

magic wraith
#
def some_func():
    ...
my_code = some_func.__code__``` Suppose I have `my_code` and not `some_func`, and that `my_code`'s name and filename are useless, and co_argcount is zero. How can I know if `my_code` comes from a function or a module (like a pyc), other than looking at the bytecode and seeing if there are STORE_FASTs or similar?
long fulcrum
#

is it possible to golf this

n=a=0
v=[]```
#

contents of v dont matter

#

just has to be a list

magic wraith
fleet bridge
magic wraith
fleet bridge
#

also look at returns
if non-None is returned - it isn't a module code
and i guess in module codes return should happen only once at the end, but im not sure (optimizer and compiler can do something crazy)

fleet bridge
#

!d types.CodeType

magic wraith
fleet bridge
fleet bridge
magic wraith
#

co_flags are insanely helpful, especially the CO_NESTED and CO_NEWLOCALS which seem to be always set for inner functoins and functions

#

tyvm

quartz wave
gleaming linden
clear venture
#

any ideas on ways to golf a one-line try/(empty) except using context manager?

#

!e

with type('',(),{'__enter__': lambda self: None, '__exit__': lambda self, *args: True})(): print('1') or 1/0
night quarryBOT
#

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

1
rugged sparrow
# clear venture !e ```py with type('',(),{'__enter__': lambda self: None, '__exit__': lambda sel...

!e I wrote this a while back ```py
_try = lambda t,*a,f=lambda a:a,e=Exception,**k:(r:={}).pop('r',type('',(import('contextlib').ContextDecorator,),{'enter':int,'exit':lambda s,*a:isinstance(a[1],e)and[r.update(r=f(a))]})()(t)(*a,**k))

print(_try(lambda:1/0))``` which lets you pass arguments to your try block via *args and **kwargs, and lets you specify an except block via f. the return value is either the return value of the try block if it succeeds, or the return value of the except block. It also allows for scoping the catch via e which can be a single Exception subclass or a tuple of subclasses

night quarryBOT
#

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

(<class 'ZeroDivisionError'>, ZeroDivisionError('division by zero'), <traceback object at 0x7f4b2b65c800>)
rugged sparrow
#

i haven't looked back into it to see if it could be golfed further since then

surreal wasp
#

this is what happens after i type py into the command terminal

karmic pumice
#

this is exactly whats supposed to happen

#

this is whats called a python repl - read eval print loop, you can enter python stuff in it and it will get evaluated

#

if you want to run a python file, then you can do py name_of_file.py (obviously replace the name of the file with one that you have)

surreal wasp
#

ok it seems python has chamged dramaticlly from a couple yerars ago. thank you

karmic pumice
#

wdym?

#

thats what was happening since like python 1

#

maybe you're confusing it with a python editor? like pycharm

surreal wasp
#

it used to bring up a virtual enviroment with diffrent tools but this isnt it

karmic pumice
surreal wasp
#

oh you know what pycharm may be it.

surreal wasp
#

yep it was pycharm. thanks for eduring my awful memory lol

north wraith
bright valve
candid grove
#

yall think my code is obfuscated enough?

class _:
    _ = " + "
    class __:
        _ = "1"
        class ___:
            _ = ")"
            class ____:
                _ = "("
                class _____:
                    _ = "print"
                    class ______:
                        _ = " = "
                        class _______:
                            _ = "'"
                            class ________:
                                _ = "str"
                                class _________:
                                    _ = "int"
                                    class __________:
                                        _ = "eval"
                                        class ___________:
                                            _ = "f"
                                            class ____________:
                                                _ = "{"
                                                class _____________:
                                                    _ = "}"


exec(f"{_.__.___.____._____._}{_.__.___.____._}{_.__.___.____._____.______._______._}{_.__._}{_._}{_.__._}{_.__.___.____._____.______._}"+eval(f'{_.__.___.____._____.______._______.________._________.__________._}{_.__.___.____._}{_.__.___.____._____.______._______.________._________.__________.___________._}"{_.__.___.____._____.______._______.________._________.__________._}{_.__.___.____._}{_.__.___.____._____.______._______.________._________.__________.___________._}{_.__.___.____._____.______._______._}{_.__.___.____._____.______._______.________._}{_.__.___.____._}{_.__.___.____._____.______._______.________._________._}{_.__.___.____._}_.__._{_.__.___._}{_._}{_.__.___.____._____.______._______.________._________._}{_.__.___.____._}_.__._{_.__.___._}{_.__.___._}{_.__.___.____._____.______._______._}{_.__.___._}"{_.__.___._}')+f"{_.__.___.____._____.______._______._}{_.__.___._}")
#

it outputs 1 + 1 = 2

candid grove
#

my brain hurts D:

#

btw if you're wondering exactly how I made it, I wrote the script, and then kept expanding it by stacked classes, until I thought it was complicated enough

#

well actually I don't really know how to make it more complicated but yk

gleaming linden
#

looks pretty simple to deobfuscate

unique heath
#

this isnt dunder spam but its under spam lool

fleet bridge
#

i kinda like that

#

woah, i have a crazy idea

night quarryBOT
#
Nope.

Sorry, you can only do that in #bot-commands!

fleet bridge
quartz wave
# candid grove yall think my code is obfuscated enough? ```py class _: _ = " + " class...

after running my renaming script ```py
class A:
A = ' + '

class B:
    A = '1'

    class C:
        A = ')'

        class D:
            A = '('

            class E:
                A = 'print'

                class F:
                    A = ' = '

                    class G:
                        A = "'"

                        class H:
                            A = 'str'

                            class I:
                                A = 'int'

                                class J:
                                    A = 'eval'

                                    class K:
                                        A = 'f'

                                        class L:
                                            A = '{'

                                            class M:
                                                A = '}'

exec(f'{A.B.C.D.E.A}{A.B.C.D.A}{A.B.C.D.E.F.G.A}{A.B.A}{A.A}{A.B.A}{A.B.C.D.E.F.A}' + eval(f'{A.B.C.D.E.F.G.H.I.J.A}{A.B.C.D.A}{A.B.C.D.E.F.G.H.I.J.K.A}"{A.B.C.D.E.F.G.H.I.J.A}{A.B.C.D.A}{A.B.C.D.E.F.G.H.I.J.K.A}{A.B.C.D.E.F.G.A}{A.B.C.D.E.F.G.H.A}{A.B.C.D.A}{A.B.C.D.E.F.G.H.I.A}{A.B.C.D.A}.__.{A.B.C.A}{A.A}{A.B.C.D.E.F.G.H.I.A}{A.B.C.D.A}.__.{A.B.C.A}{A.B.C.A}{A.B.C.D.E.F.G.A}{A.B.C.A}"{A.B.C.A}') + f'{A.B.C.D.E.F.G.A}{A.B.C.A}')

#

bottom part becomes ```py
exec("print('1 + 1 = " + eval('eval(f"eval(f'str(int(.__.) + int(.__.))')")') + "')")

#

nice attempt though

tulip harbor
#

Why isn't integer division faster than float division?

%timeit 101 / 2
4.91 ns ± 0.0026 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
 %timeit 101 // 2
4.91 ns ± 0.00175 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
clear venture
#

x // y

floored quotient of x and y

Also referred to as integer division. For operands of type int, the result has type int. For operands of type float, the result has type float. In general, the result is a whole integer, though the result’s type is not necessarily int. The result is always rounded towards minus infinity: 1//2 is 0, (-1)//2 is -1, 1//(-2) is -1, and (-1)//(-2) is 0.

unique heath
#

although i'd assume a smart compiler would be able to optimize that more

karmic pumice
#

a smart compiler would precompute everything thats not IO

modest bough
earnest wing
unique heath
#
>>> dis.dis("30 / 5")
  0           0 RESUME                   0

  1           2 RETURN_CONST             0 (6.0)```
#

(well kinda)

earnest wing
#

it doesn't precompute "everything that's not IO"

quartz wave
#

if you want a non-precomputed one you could store them in variables and time only the division of those variables

#

but i doubt floor division will be faster

modest skiff
#

I sent this to non-coding server, they were confused and it has hurt their eyes
||```py
exec(import('zlib').decompress(bytes.fromhex('789c2b28cacc2bd150ca48cdc9c95728cf2fca4951d204004e93071f')).decode())

unique heath
quartz wave
modest skiff
unique heath
# modest skiff I sent this to non-coding server, they were confused and it has hurt their eyes ...

!e anyway more dunder spam lolpy __builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),"".__getattribute__("join")([__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(_.__add__(_))))(i) for i in [__.__sub__(_.__add__(_).__lshift__(_.__add__(_).__add__(_)).__add__(_.__add__(_).__lshift__(_.__add__(_)))), 101, 108, 108, 111, _.__add__(_).__add__(_).__add__(_).__lshift__(_.__add__(_).__add__(_)), 119, 111, 114, 108, 100]])).__getitem__(_.__add__(_)))

night quarryBOT
#

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

hello world
stark granite
#

is it possible

#

to write such program or class

unique heath
#

to

stark granite
#

which returns a random instance which just exists (even if not in scope via any measures)

#

eacb time

#

you request its type

unique heath
stark granite
#

not random programmer's choice...

unique heath
stark granite
quartz wave
#

it runs in about 88 microseconds

#

which is pretty fast

rugged sparrow
#

!e ```py
import gc, random
class Instance:
def new(cls):
return random.choice(gc.get_objects())

for i in range(4):print(Instance())```

night quarryBOT
#

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

001 | <member 'st_ctime_ns' of 'os.stat_result' objects>
002 | {'__new__': <built-in method __new__ of type object at 0x559c290c3200>, '__repr__': <slot wrapper '__repr__' of '_thread._ExceptHookArgs' objects>, '__reduce__': <method '__reduce__' of '_thread._ExceptHookArgs' objects>, 'exc_type': <member 'exc_type' of '_thread._ExceptHookArgs' objects>, 'exc_value': <member 'exc_value' of '_thread._ExceptHookArgs' objects>, 'exc_traceback': <member 'exc_traceback' of '_thread._ExceptHookArgs' objects>, 'thread': <member 'thread' of '_thread._ExceptHookArgs' objects>, '__doc__': 'ExceptHookArgs\n\nType used to pass arguments to threading.excepthook.', '__module__': '_thread', 'n_sequence_fields': 4, 'n_fields': 4, 'n_unnamed_fields': 0, '__match_args__': ('exc_type', 'exc_value', 'exc_traceback', 'thread')}
003 | <class '_io.BytesIO'>
004 | <member 'releaselevel' of 'sys.version_info' objects>
quartz wave
fleet bridge
fleet bridge
quartz wave
#

searching every tracked object for untracked objects and adding them all to a list that varies every time it's called is pretty costly

night quarryBOT
#
Missing required argument

code

static knoll
#

oh

sick hound
#
u=[10]+[0]*19
m=0
def _():print(chr(u[m]),end="")
while u[m]:  
    m+=1       
    u[m]+=7
    m+=1       
    u[m]+=10
    m+=1       
    u[m]+=3
    m+=1
    u[m]+=1
    m-=4
    u[m]-=1
m+=1;m-=1;m+=1;u[m]+=2;(_:=_,_());m+=1;m-=1;m+=1;u[m]+=1;(_:=_,_())
u[m]+=4;u[m]+=2;u[m]+=1;(_:=_,_());(_:=_,_());u[m]+=2;u[m]+=1
_();m+=1;m-=1;m+=1;u[m]+=2;(_:=_,_());m-=2;u[m]+=15
_();m+=1;m-=1;m+=1;(_:=_,_());u[m]+=3;(_:=_,_());u[m]-=6;(_:=_,_())
u[m]-=8;(_:=_,_());m+=1;m-=1;m+=1;u[m]+=1;(_:=_,_());m+=1;m-=1;m+=1;(_:=_,_())
unique heath
#

is there a short way to obfuscate a for loop?

low lynx
#

turn it into an ast node

#

it'll largely depend on what is in the for loop

unique heath
low lynx
#

just map?

unique heath
#

oh shit im dumb

low lynx
#

idk what u mean by obfuscate tho

unique heath
#

!e

__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),___:=_.__add__(_).__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__name__.__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(_.__add__(_)))),[__.__sub__(_.__add__(_).__lshift__(___).__add__(_.__add__(_).__lshift__(_.__add__(_)))), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(_).__sub__(_).__sub__(_),_______,_______.__sub__(_.__add__(_).__add__(_).__lshift__(_)), __.__sub__(_.__add__(_).__add__(_).__add__(_).__mul__(_.__add__(_).__add__(_).__add__(_).__add__(_).__add__(_).__add__(_)))]))).__getitem__(_.__sub__(_).__sub__(_)))```
night quarryBOT
#

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

h__main__e__main__l__main__l__main__o__main__ __main__w__main__o__main__r__main__l__main__d
unique heath
#

what

#

the cow

#

!e py __builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),____:=_.__add__(_),___:=____.__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__add__(_).__lshift__(___.__add__(_)).__sub__(___.__add__(_).__add__(_))))().__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(____))),[__.__sub__(____.__lshift__(___).__add__(____.__lshift__(____))), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(___),_______,_______.__sub__(___.__lshift__(_)), __.__sub__(___.__add__(_).__mul__(___.__add__(___).__add__(_)))]))).__getitem__(_.__sub__(____)))

night quarryBOT
#

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

hello world
unique heath
#

sorry for dunder spam

quartz wave
unique heath
quartz wave
unique heath
#

okay fine

quartz wave
#

i can't read it :(

#

yaiyyyy :D

unique heath
#

yay

karmic pumice
unique heath
#

damn

#

genius

karmic pumice
#

😋

#

its correct most of the time

unique heath
#
__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),___:=_.__add__(_).__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__name__.__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(_.__add__(_)))),[__.__sub__(_.__add__(_).__lshift__(___).__add__(_.__add__(_).__lshift__(_.__add__(_)))), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(_).__sub__(_).__sub__(_),_______,_______.__sub__(_.__add__(_).__add__(_).__lshift__(_)), __.__sub__(_.__add__(_).__add__(_).__add__(_).__mul__(_.__add__(_).__add__(_).__add__(_).__add__(_).__add__(_).__add__(_)))]))).__getitem__(_.__sub__(_).__sub__(_)))
``` deobfuscation algorithm fail
#

also @quartz wave

quartz wave
#

hm?

unique heath
#

can you add the imsosorry C thing to the letsbuilda org?

quartz wave
unique heath
#

i have write perms

#

to letsbuilda

quartz wave
#

owh

#

okie

unique heath
#

although i dont think doggo would like it

#

@mossy plume DOGGO IMSOSORRY BUT C???????

#

and we wait

quartz wave
modest skiff
ruby raft
#

hi if I have two files
mod.py

import inspect
print(inspect.stack[-1].lineno)```
`test.py`
```py
#Some random file that imports the module
import mod

print("a")```
I can get the line number of the `import mod` (2) right, but can I also get the column number? (python 3.9)
#

I know that the code_context property exists but if I can prevent searching through strings that would be great

proper vault
#

3.9 I don't believe tracked that. Short of writing a custom parser (maybe just finding it via .index on the right line) and running that on getsource, it is probably impossible

ruby raft
#

cool

#

well I guess I should state my original problem in case there are other solutions:
I would like to preprocess the __main__ file from mod.py and then let it execute
Problem is that if there is code before the import mod statement it obviously should not be executed again. What makes it so painful is that I cant just say: "Give me everything after the import statement, I will execute the rest" because it could be nested in some class or function

#

Do you have any idea?

#

I would do the preprocessing too for other files imported but for those its easier because I can set up import hooks

#

My alternative would be somehow using the site module to my advantage but Im not sure if this is a great solution

#

Or I could use a custom encoding combined with import hooks so all I need to do is set the encoding to the custom one in the __main__ file

#

which is much more explicit than going to the site module and preprocessing any python file that is run, even if it has nothing to do with my project

mossy plume
fluid pumice
#

!e

listA:list=[0.0,0.5];b:int=round((listA[0]+0.6)+(listA[1]+1));print("{:^20}".format(b))
night quarryBOT
#

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

         2          
long fulcrum
#

is this the shortest way to do this?

import sys
v=sys.argv[1:]```
unique heath
fluid pumice
karmic pumice
#
import sys;v=sys.argv[1:]
from sys import*;v=argv[1:]

yeah yours one is shorter

quartz wave
long fulcrum
#

oh fuck

#

thats smart

#

ty

karmic pumice
#

that doesnt work does it

fluid pumice
#

idk

karmic pumice
#

__import__ is not the same as import, it wont bring the name into the scope, it returns the module object

fluid pumice
#

yeah ik

#

I just tried smth

karmic pumice
#

v=__import__('sys').argv[1:] 🤷

fluid pumice
#

oh yeah

#

ty

karmic pumice
#

thats sadly not shorter

#

the unders and quote marks take quite some space

fluid pumice
#

hmmm

#

it's not shorter, but still looks cool tho

#

LMAO

v=(lambda:__import__('sys').argv[1:])
#

not so short

#

and useless

long fulcrum
fluid pumice
#

nono, he said that to me

#

I deleted the message

long fulcrum
#

ah

karmic pumice
fluid pumice
#

__import__('sys').argv[1:]

fluid pumice
karmic pumice
#
v=(lambda f:f(*map(__import__,f.__code__.co_varnames)))(lambda sys:sys.argv[1:])
fluid pumice
#

fu#k you ||(no offense please, this is a joke)||

unique heath
#
__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),____:=_.__add__(_),___:=____.__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__add__(_).__lshift__(___.__add__(_)).__sub__(___.__add__(_).__add__(_))))().__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(____))),[__.__sub__(____.__lshift__(___).__add__(____.__lshift__(____))), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(___),_______,_______.__sub__(___.__lshift__(_)), __.__sub__(___.__add__(_).__mul__(___.__add__(___).__add__(_)))]))).__getitem__(_.__sub__(____)))```
#

i had to

quartz wave
unique heath
#

!e

v=(lambda f:f(*map(next(j for f in object.__subclasses__() for j in [getattr(getattr(f, '__init__', object), '__globals__', 0)] if j != 0).__getitem__,f.__code__.co_varnames)))(lambda sys:sys.argv[1:])()

print("hi")```
night quarryBOT
#

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

001 |   File "/home/main.py", line 1
002 |     v=(lambda f:f(*map(next(j for f in object.__subclasses__() for j in [getattr(getattr(f, '__init__', object), '__globals__', 0)] if j != 0]).__getitem__,f.__code__.co_varnames)))(lambda sys:sys.argv[1:])()
003 |                                                                                                                                              ^
004 | SyntaxError: closing parenthesis ']' does not match opening parenthesis '('
quartz wave
unique heath
#

!e

v=(lambda f:f(*map(next(j for f in object.__subclasses__() for j in [getattr(getattr(f, '__init__', object), '__globals__', 0)] if j != 0).__getitem__,f.__code__.co_varnames)))(lambda sys:sys.argv[1:])

print('ono')````
night quarryBOT
#

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

ono
quartz wave
#

!e ```py
v=(lambda f:f(*map(next(j for f in object.subclasses() for j in [getattr(getattr(f, 'init', object), 'globals', 0)] if j != 0).getitem,f.code.co_varnames)))(lambda sys:sys.argv)
print(v == import('sys').argv)

night quarryBOT
#

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

True
quartz wave
#

ok

unique heath
#

lmao

fluid pumice
#

!e

a:list=[float(chr(int(b'\xff\xfe4\x009\x00'.decode('utf-16')))),float(chr(int(b'\xff\xfe4\x009\x00'.decode('utf-16'))))];d:float=(++a[0]+--a[1]);print("{:<10}".format("{}".format(int(d))))
night quarryBOT
#

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

2         
quartz wave
unique heath
#

:(

quartz wave
unique heath
#

:(

restive void
#

!e

def foo():
    yield 42
    print("finishing")
bar = foo()
print(next(bar))
print("before")
[] = bar
print("after")
night quarryBOT
#

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

001 | 42
002 | before
003 | finishing
004 | after
stark granite
#

why is it called

#

in [] = bar

karmic pumice
#

Iterating for unpacking like in [x]=[1] ig

rapid elk
#

hi

ruby raft
#

why does the codecs IncrementalDecoder seem to work perfectly fine when opening file with a custom encoding but struggles when importing a file with a # coding: some encoding

#

it always ends in some recursive loop

ruby raft
#

You mean the code that is imported?

#

Just some simple print statements

#

Funnily enough in termux on my phone the IncrementalDecoder isnt even called when importing a file lol

long fulcrum
#
for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or-~i)```
#

what?

#

!e

for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or-~i)```
night quarryBOT
#

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

001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)

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

hard spoke
#

!e there's a nice book, "ten essays on fizzbuzz". a favorite of mine from there, which technically fullfills your condition, is

import random
random.seed(23_977_775)
for i in range(1, 16):
    print(random.choice(["FizzBuzz", "Fizz", str(i), "Buzz"]))
night quarryBOT
#

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

001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)

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

karmic pumice
hard spoke
#

nah, but one could modify it to just reuse the info on the first 15 elements for the rest of the sequence.

long fulcrum
#

aw

fleet bough
#

I've got a decorator for classes that adds logging

#

is there some functools wraps equivalent?

#

or maybe it should be a mixin?

#

it mostly extends the init method

restive void
fleet bough
#

the class module sets set to zen_logging.loggify too, which is wrong

#

this is what i was doing before and it worked alright

clear venture
clear venture
#

I wonder if the seeding is version specific

#

!e

import random

a = [-3, 1, -5, 3, 5, -8, -6, -11, -2, 7]

random.seed(69_69_420)
b = ''.join(map(chr,[random.randint(0, 19) - a[i] + 100 for i in range(len(a))]))
print(b[:5],b[5:])
night quarryBOT
#

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

hello world
clear venture
#

Guess not

unique heath
#

!d random

night quarryBOT
#

Source code: Lib/random.py

This module implements pseudo-random number generators for various distributions.

For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.

On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions. For generating distributions of angles, the von Mises distribution is available.

craggy ruin
#
exec('''
for i in range(16):
    qv i % 3 == 0 and i % 5 == 0:
        print(\'fizzbuzz\')
    ykqv i % 3 == 0:
        print(\'fizz\')
    ykqv i % 5 == 0:
        print(\'buzz\')
    ykmy:
        print(i)
'''.translate(str.maketrans('kyvqm', 'lefis')))
unique heath
#

lol

#

that isnt really a "master" thing

#

its pretty trivial

#
for i in range(100):print(["fizzbuzz", "buzz", "fizz", i][bool(i % 3) + (bool(i % 5) * 2)])``` pretty neat solution
#

!e

for i in range(10):print(["fizzbuzz", "buzz", "fizz", i][bool(i % 3) + (bool(i % 5) * 2)])```
night quarryBOT
#

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

001 | fizzbuzz
002 | 1
003 | 2
004 | fizz
005 | 4
006 | buzz
007 | fizz
008 | 7
009 | 8
010 | fizz
proper vault
#

!e my favourite has been

for i in range(1, 17):
    q=[str(i),'']
    j=0
    if i % 3 == 0:
        q[j] = 'Fizz'
        j+=1
    if i % 5 == 0:
        q[j] = 'Buzz'
        j+=1
    print(''.join(q))
night quarryBOT
#

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

001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)

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

proper vault
#

!e Not sure if this one was mentioned yet, but this is also a fun one

for i in range(1,33):
    print(['FizzBuzz', i, i, 'Fizz', i, 'Buzz', 'Fizz', i, i, 'Fizz', 'Buzz', i, 'Fizz', i, i, 'Buzz'][i%16])
night quarryBOT
#

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

001 | 1
002 | 2
003 | Fizz
004 | 4
005 | Buzz
006 | Fizz
007 | 7
008 | 8
009 | Fizz
010 | Buzz
011 | 11
... (truncated - too many lines)

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

unique heath
#

its not

unique heath
sick hound
#

@unique heath how did u learn py?

arctic elm
#

oh, fizz buzz

#

I have a very old C thing of mine

#
i;main(){101-++i&&printf("%d\n\0FizzBuzz\n\0Fizz\n"+(7*!(i%3)+4*!(i%5))%9*2,i)&main();}
#

a tad more readable form

i;
main() {
  101-++i
  && printf(
    "%d\n\0FizzBuzz\n\0Fizz\n"
    + (7*!(i%3)+4*!(i%5))%9*2,
    i
  ) & main();
}
unique heath
#

if the first one is '' (empty), it goes to the or
else, it doesnt

unique heath
sick hound
unique heath
#

i dont remember

sick hound
#

ah

unique heath
sick hound
#

i just bought a course

unique heath
sick hound
#

on udemy

#

it has rlly good ratings

unique heath
#

waste of money 😭

sick hound
#

so lets see

unique heath
#

programming courses are waste of money imo

#

!res

night quarryBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

sick hound
#

o

#

okay

unique heath
sick hound
#

oo

#

ik that book

unique heath
#

and then make a shit ton of stupid projects

#

emphasis on shit ton

#

!e

__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__())).__add__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()))))((_:=__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()),__:=_.__add__(_).__lshift__(_.__add__(_).__add__(_).__lshift__(_)),____:=_.__add__(_),___:=____.__add__(_),_____:=__.__sub__(___.__add__(_).__add__(_).__lshift__(_.__add__(_))),_______:=__.__sub__(_.__add__(_).__lshift__(___).__sub__(_.__add__(_))),__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__add__(_).__lshift__(___.__add__(_)).__sub__(___.__add__(_).__add__(_))))().__getattribute__(__name__.__dir__().__getitem__(___.__lshift__(___)))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(___.__add__(_).__lshift__(___.__add__(_)).__add__(___.__add__(_))))(__builtins__.__getattribute__(__builtins__.__dir__().__getitem__(__builtins__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__()).__lshift__(_.__lshift__(_.__add__(_))).__sub__(____))),[__.__sub__(____.__lshift__(___).__add__(____.__lshift__(____))), _______.__sub__(_.__add__(_).__lshift__(___)).__add__(___), _____, _____,_______.__sub__(___),_.__add__(___).__lshift__(___),__.__sub__(_.__lshift__(___)).__sub__(_), _______.__sub__(___),_______,_______.__sub__(___.__lshift__(_)), __.__sub__(___.__add__(_).__mul__(___.__add__(___).__add__(_)))]))).__getitem__(_.__sub__(____)))```
night quarryBOT
#

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

hello world
unique heath
#

so anyway

#

hello world

#

(help i wrote that by hand)

unique heath
#

it makes more sense when you see that

#

lmao

quartz wave