#esoteric-python

1 messages ยท Page 52 of 1

quartz wave
#

i just have to add evaluators for other nodes

wild remnant
frosty crow
#

me when fractional indices:

subtle viper
#

anyways hiatus until i get it back

#

esolang has prefix operators and weird token behavior

#

standalone digit is label, digit in a perceived operand context is a number

#
183 # labels/numbers 1, 8, 3
'183 # number 183
_183 # label 183, only valid outside of a perceived operand context
abc # names a, b, c
_abc # name abc

ye

shut zealot
#

So you can't pass a label as an operand and have it look up the thing it points to?

subtle viper
#

i originally intended it to be a stack based language where unpack and goto would be able to manipulate operations but the parsing part became harder as a result

#

i'll rework it when i get my pc back ;`;

shut zealot
#

Are you on iOS or Android (or hypothetically other) in the meantime?

subtle viper
shut zealot
#

Which? Both? I was gonna suggest a coding environment

subtle viper
#

my working code is on the pc, so..

shut zealot
#

Maybe Pydroid 3 is the coolest one for Android? Not sure. (Or QPython it looks like)

midnight isle
#

So I was poking at this new programming languageโ€™s closed sourced compiler and managed to get Cython function bugs out of it trying to run Pythonโ€™s pandas library on it. How does that work blobhuh

grave grail
subtle viper
grave grail
#

Well, I have no idea what that talking about or mean so I skipped it
But I only know that this is unrelated to here

subtle viper
#

i mean it's not completely unrelated

vocal elk
#

some help me with this

#

pls

#

ASAP

#

and pls pin me if you answer

worn jay
#

!rule 8

night quarryBOT
#

8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.

worn jay
#

And also this one I think?

#

!rule 7

night quarryBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

red mantle
# vocal elk

Sorry to the mods, cause itโ€™s off topic. But I see youโ€™re using obsidian and have python code inside it. What plugin are you using to do that?

gleaming linden
#

I was a section leader last year

#

Have you tried asking in the discussion forums?

vocal elk
# vocal elk

okkkkkkkkkkkkkkkkkkkkkkkkkkkkkk yeyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

#

i completed that codeeeeeeeeeeeeeeeeeeeeeeeeee

#

by myselffffffffffffffffffffffffffffff

#

๐Ÿ˜ญ

vocal elk
#

thank you , you all for not helping me so i can use my brain

vocal elk
vast wave
#

you probably do not want our help

arctic skiff
austere mauve
# vocal elk

Aghh, it's taking me too much time. They use some sort of code sanitization before passing the code to pyoide. Maybe it's possible to do stuff with it, but it's going to be an interesting challenge. If anyone up to the challenge, the main logic seems to be in static/js/ide/utils/karelCompiler/karel/KarelVM.js (after decoding with source maps - browses do that automatically). Oh and the link to the website is ofc https://codeinplace.stanford.edu/public/ide/a/housekarel (registration required?!)

zealous narwhal
#

hii

vocal elk
arctic skiff
noble belfry
#

!e

import sys
import traceback
def trace(exc_type, exc_val, exc_trace):
    if issubclass(exc_type, NameError):
        exc_trace.tb_frame.f_globals[str(exc_val).split("'")[1]] = str(exc_val).split("'")[1]
        while True:
            try:
                exec(exc_trace.tb_frame.f_code)
                break
            except NameError as e:
                exc_trace.tb_frame.f_globals[str(e).split("'")[1]] = str(e).split("'")[1]
                continue
sys.excepthook = trace

print(Hello, World)
night quarryBOT
noble belfry
#

How can i make this not exit with 1?

shut zealot
#

Hmm. It seems to me that.. When you call exec(exc_trace.tb_frame.f_code), you're re-running things from the frame where the exception occurred... but f_code is the whole function, not just the line the caused the error, right? Maybe that's fine but even then I guess the CPython interpreter state still thinks there's an unresolved exception, and is heading toward exiting?

noble belfry
#

!e

import sys
import traceback
def trace(exc_type, exc_val, exc_trace):
    if issubclass(exc_type, NameError):
        exc_trace.tb_frame.f_globals[str(exc_val).split("'")[1]] = str(exc_val).split("'")[1]
        while True:
            try:
                exec(exc_trace.tb_frame.f_code)
                break
            except NameError as e:
                exc_trace.tb_frame.f_globals[str(e).split("'")[1]] = str(e).split("'")[1]
                continue
sys.excepthook = trace

print(Hello, World)
# but this still runs:
print(Hello, Again)
night quarryBOT
shut zealot
#

I take it eval(your_var_name, frame.f_globals, frame.f_locals) isn't enough for what you want?

#

Hmm yeah that's interesting that it is proceeding, I guess that part of my model of it is wrong.

#

Maybe you just need to return False after breaking to let the default handler take over? Hmm.

#

Sorry, I'm not sure. Interesting code though!

noble belfry
shut zealot
#

I've never thought to implement a DSL based on NameError. Clever.

fleet lintel
# noble belfry No, doesn't work

I think you should just sys.exit(0) at the end of trace inside the if, since because the script runs the entire code again, once the code runs sucessfully to completion it should normally exit with code 0, you just have to do it yourself to interrupt python's default behavior after the excepthook.
Another thought, I think I remember seeing the person that made the goto in python use trace to resume execution at a specific point, so you might be able to do something like that to prevent code from running twice. It wouldn't be foolproof since you could have very nested statements, but it would at least work in the simple case of one set of errors per line.

noble belfry
#

I'm not familiar enough with traces and that, so I changed it to read the file, and rewrite it using ast.NodeTransformers instead. It even works with pypy

# fix.py
from ast import *
import sys
import inspect

if sys.implementation.name == "pypy":
    pypy = True
else:
    pypy = False


class NodeVisitor(NodeTransformer):
    def visit_Name(self, node):
        return Call(
            func=Name(id="__best_var", ctx=Load()),
            args=[
                Constant(value=node.id),
                Call(func=Name(id="locals", ctx=Load()), keywords=[], args=[]),
                Call(func=Name(id="globals", ctx=Load()), keywords=[], args=[]),
                (
                    (
                        Attribute(
                            value=Name(id="__builtins__", ctx=Load()),
                            attr="__dict__",
                            ctx=Load(),
                        )
                    )
                    if pypy
                    else (Name(id="__builtins__", ctx=Load()))
                ),
            ],
            keywords=[],
        )

    def visit_Import(self, node):
        if len(node.names) == 1 and node.names[0].name == "fix":
            return parse(
                r"""
if 1:
    def ___best_var(var, *scopes):
        for scope in scopes:
            if var in scope:
                return scope[var]
        return var
    globals()['__best_var'] = ___best_var
                """
            ).body[0]
        return node


frame = inspect.currentframe()
while frame:
    last_working = frame
    frame = frame.f_back
frame = last_working

source_file = frame.f_globals["__file__"]
with open(source_file, "r") as f:
    source = f.read()

new_tree = fix_missing_locations(NodeVisitor().visit(parse(source)))
# print(dump(new_tree, indent=2))
# print("==========")
# print(unparse(new_tree))
compiled = compile(new_tree, "", "exec")
exec(compiled)
sys.exit(0)
# main.py
import fix
print(Hello, World)
#

Tomorrow i'll add it so that spelled out english numbers become integers

subtle viper
noble belfry
subtle viper
noble belfry
# subtle viper well as long as there's another way other than using `__file__`..

Its actually very easy using code library

import code
import sys
from fixlib import fixed_parser


class CustomREPL(code.InteractiveConsole):
    def __init__(self, *args, **kwargs):
        super().__init__()
        import numbers as __number_converter

        def ___best_var(var, *scopes):
            for scope in scopes:
                if var in scope:
                    return scope[var]
            try:
                return __number_converter.english_to_int(var)
            except:
                return var

        self.locals["__best_var"] = ___best_var

    def runsource(self, source, filename="<input>", symbol="single"):
        """Override the runsource method to use the custom execute function."""
        try:
            code = self.compile(source, filename, symbol)
        except (OverflowError, SyntaxError, ValueError):
            # Case 1
            self.showsyntaxerror(filename, source=source)
            return False

        if code is None:
            # Case 2
            return True

        code = compile(
            fixed_parser(source, parsemode=symbol, import_rewrite=False),
            filename,
            symbol,
        )
        # Case 3
        self.runcode(code)
        return False


CustomREPL().interact(
    f'Python {sys.version.split()[0]} [Fixed]\nType "help", "copyright", "credits" or "license" for more information.'
)
#
Python 3.13.2 [Fixed]
Type "help", "copyright", "credits" or "license" for more information.
>>> print(Hello, python, discord, one, two, three, four_hundred_million_seventy_nine_thousand)
Hello python discord 1 2 3 400079000
>>> 
subtle viper
#

so just secretly open a new REPL when the module is imported, i see..

midnight isle
subtle viper
#

very quickly changed stances :p

midnight isle
#

we need a cobra-accelerated version of Python for this ecosystem

#

that would be awesome. A framework for Python with a cobra holy smokes deadge

rugged sparrow
#

Never did get around to part 2 tho lol

#

The secret to getting it to work everywhere was to hot swap the globals dict type to a custom subclass with that missing dunder implemented

proper vault
noble belfry
#

I think i figured it out. You can just replace the globals using c_void_p

#

!e

from ctypes import c_void_p
import random


class BuiltinDict(dict):
    # We need to save all builtin and global variables used as default parameters
    # otherwise this function will get called again trying to access that name
    def __getitem__(
        self,
        key,
        globals=globals(),
        builtins=__builtins__,
        hasattr=hasattr,
        getattr=getattr,
        random=random,
    ):
        if key in globals:
            return globals[key]
        elif hasattr(builtins, key):
            return getattr(builtins, key)
        if key == "pie":
            return "๐ŸŽ‚"
        elif key == "pi":
            return 3 + random.random()
        return key


c_void_p.from_address(id(globals()) + 8).value = id(BuiltinDict)


print(Hello, World, pie, pi)
night quarryBOT
versed eagle
unreal echo
#

For the highest reolution i got (75kร—150k) it was probably around like 32 gb for rgb

arctic skiff
#

optimize it to take half of it

fleet bridge
unreal echo
#

150k length

mild turtle
#

What in God's good name is this code from the IntelliJ repo?

def temp(filepath):
    a = 1
    with open(filepath) as f:
        l = <caret>f.readlines()
        for line in l:
            a = 1
shut zealot
#

Is that <caret> literal, or is that trying to say the line is: l = ^f.readlines()?

#

My guess is that's how their test harness decides where to put the editor's cursor during setup, and it's stripped out?

#

Looking at the testSrc directory, that does seem to be the case

mild turtle
#

Aaaaaah makes sense

#

Thanks!

daring panther
#

I'm using pyinstaller to bundle my core app into an exe. The app is modular and I'm bundling my modules as .pyd files.

The core doesn't know anything about the modules at compile time, but sometimes the modules have dependencies that the core doesn't... these need to be installed at runtime (app restart allowed).

Can someone suggest a way to do this? I'm currently trying to do pip and pip._internal etc as hidden imports for the pyinstaller to I might be able to call pip at runtime, but that seems like a dead end right now.

I hope that's esoteric/code gore enough for this channel :>

shut zealot
#

Sadly uv doesn't offer a Python API yet, or else that would be my preferred trick.

daring panther
shut zealot
#

Yeah, maybe pyenv offers that?
Edit: I guess not at first glance... hmm.

daring panther
#

I probably could include pip, or uv for that matter, with the project (e.g. through the installer). But I'm not sure how I would include the installed libraries with my project.

subtle viper
#

i miss my pc rn and i can't finish my wip esolang

#

so here's a fizzbuzz program in said esolang ```py
1a:100>?f01@:3%!?(!"Fizz"$<)1@:5%!?(1|"Buzz"$<)?(:$<)1+af

fleet lintel
#

I've recently been in the mood of writing python like rust, so could I get an opinion on this "procedural macro"? https://paste.pythondiscord.com/AJ4Q it's for automatically adding the default list constructors to a dataclass

fleet lintel
#

https://paste.pythondiscord.com/ONLA alternative version that doesn't compare asts by == since that stopped working, and makes the type checker happy by being less magic (using field: list[x] = [] instead of just field: list[x])

fleet bridge
#

I think pattern matching can be used to do what you are doing with three ifs

fleet lintel
subtle viper
#

there's a full tutorial in PEP 636 but that's the gist of what you'd need here

fleet lintel
#

Iโ€™ve read the pep for match, but since Iโ€™ve never actually played around with them Iโ€™m still not certain exactly how to write them.

night quarryBOT
subtle viper
#

iirc the other attributes not mentioned in the pattern will be ignored, so you won't need to check for them

#

!e ```py
from ast import *

x = parse('abc')
match x.body[0]:
case Expr(value=Name(id="abc")):
print("matched!")

night quarryBOT
subtle viper
#

!e ```py
from ast import *

x = parse('x: list[Any] = []')
match x.body[0]:
case AnnAssign(
annotation=Subscript(
value=Name(id="list"),
),
value=List(),
):
print("matched!")

night quarryBOT
twin roost
#

Is there a postfix way to convert generator to list?

#

e.g. something like range(5) -> list

#

if that makes sense

#

it's just would be easier to type when debugging sometimes

#

instead of going back and wrapping the generator with list

#

The best I've found for now is this

from pipe import Pipe

print(range(5) | Pipe(list))
subtle viper
#

a few move-across-word keybinds and you can easily wrap it in a call or that other syntax

subtle viper
#

for example, > _(list) where ```py
class _:
def init(self, f):
self.f = f
def lt(self, o):
return self.f(o)

twin roost
#

versus 1. type range(5) and 2. type | Pipe(list)

twin roost
subtle viper
#

there's always the option of overriding the names too

#

but i'm not sure if that'd fare well with linters or whatever they're called

twin roost
subtle viper
twin roost
#

oh, that would be too esoteric ๐Ÿ˜„

versed eagle
subtle viper
#

i still haven't told you to overwrite the built-in class slot ^_^

versed eagle
#

doing that would be annoying probaby because there are lots of different options

#

list, tuple, secret third option, set, dictionary, etc.

overriding them all is annoying

#

its sad that you cant override the abc to make stuff work tbh

subtle viper
#

!e ```py
from fishhook import hook

@hook(type)
def lt(self, other):
return self(other)

print(range(5) > list)
print(range(5) > set)

night quarryBOT
subtle viper
#

well.

versed eagle
#

ooh hooking it on type is nice actually

#

i was envisioning a 'catenation scheme

subtle viper
#

it's the only way, actually...

#

list etc. are instances, so

versed eagle
#

which is cute syntax, i think

#

although

#

type hooking allows for silliness

subtle viper
#

| can be overridden but it must be checked for type/generic unions

versed eagle
#

(1 > float) > str

#

the parens might get annoying

versed eagle
#

using | as ยฐ

#

1 > (float | str)

subtle viper
#

ooh-

versed eagle
#

may as well do functions too at that point

subtle viper
#

!e ```py
from fishhook import hook

@hook(type)
def lt(self, other):
return self(other)

@hook(type(int | str))
def lt(self, other):
for typ in self.args:
other = typ(other)
return other

print(range(5) > list)
print(1 > complex | str)

night quarryBOT
versed eagle
#

we might have to override piping anyway

#

__args__ doesnt actually return the args but rather the unique args

#

(int | str | int).args โ†ฆ (int, str)

#

kinda messed up if you ask me

fleet bridge
#

just hook truediv on object

#

rtruediv*

subtle viper
#

oh well

#

^

#

bitwise XOR is the second lowest operand-preserving non-chaining binary operator precedence after bitwise OR

trail zephyr
#
{{
    print('{}โ”‚{}โ”‚{}\nโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”ผโ”€โ”€โ”€\n{}โ”‚{}โ”‚{}\nโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”ผโ”€โ”€โ”€\n{}โ”‚{}โ”‚{}'
        .format(*['   ' if i == '1' else ' X ' if i == '5' else ' O ' for i in str(B)])
    ) for _ in range(5)
        if (B := B + 4 * 10 ** abs(9-int(input())))
            and (t := [2.71828 ** (
                sum(w[i][j] * list(map(int,str(B)))[j] for j in range(9)) + b[i]
            ) for i in range(9)])
            and (B := B + 8 * 10 ** t.index(max(t, key = lambda x: x / sum(t))))
} for B, w, b in [(
    111111111,
    [
        [0.5324228, 0.76355624, 1.0098922, 1.0587181, 0.47961304, 0.8581823, 0.045538172, 1.0410924, -1.579585],
        [0.4228034, 0.9537834, 0.9404552, 1.0115612, 0.5452481, 0.8414384, 0.0972775, -1.0017858, 0.40512067],
        [0.7085032, 0.955647, 1.0234874, 1.03152, 0.36106178, 0.82706773, -1.0083874, 0.76845086, 0.19899876],
        [0.46637133, 0.65566856, 1.0476296, 1.3649647, 0.5284521, -1.0649983, 0.18261205, 0.78231066, 0.3543514],
        [0.6555538, 0.993636, 1.0712171, 1.2289686, -1.1268336, 0.7060021, 0.121178925, 0.5562301, 0.011001009],
        [0.6181679, 0.48797947, 1.063911, -0.8666658, 0.55554706, 0.98548925, 0.23587868, 0.90056294, 0.30139807],
        [0.7447117, 0.6618681, -0.7941452, 1.040301, 0.39376765, 0.8027111, 0.14813231, 0.800058, 0.38237593],
        [0.6764701, -1.1199214, 1.1118764, 0.79409623, 0.48408085, 0.83786356, 0.18026906, 1.0840094, 0.28564036],
        [-0.9352118, 0.70592344, 1.1290987, 1.057092, 0.47734314, 0.8022352, 0.11734288, 0.7755984, 0.34827393],
    ],
    [-0.27312347, -0.35538667, -0.7696111, -0.9394737, 0.61957735, -0.09319963, 0.28401002, 0.48452064, 0.626548],
)]}

hihi
this seems like the right channel for this ive been working on-
the above code doesnt run because the walrus operator cant be used with B and i wanna know if theres an easy workaround without stepping out of the comprehension
dont expect too much from it tho since ive only been able to get the cost down to 0.8~

austere mauve
trail zephyr
#

oo- yep, i didnt know you could set a variable in a tuple like that. thought the operator was exclusive to conditionals. tyvm

silver ore
#

:= explain me this

shut zealot
#

It's the I mean it, officer operator

silver ore
#

Officer ๐Ÿ‘ฎ operator

shut zealot
#

Lets you do x = y in a place where by default the language wants to protect you

silver ore
#

๐Ÿ˜‚ n yeah n further more

shut zealot
silver ore
#

Oki

#

Hope it has good realworld application?

shut zealot
#

I mean, it sorta closes a loophole that might have been irritating, but I can't say I've seen it much in action yet either

#
while chunk := file.read(8192):
   process(chunk)
#

is sorta the most legit example on that page to my eye

#

I don't 100% get why we didn't just make chunk = ... into an expression vs. a statement and move on, but oh well

restive void
#

Among other reasons, because of this footgun.

shut zealot
#

Yeah. That works in Ruby, which is fun.. I appreciate the guardrail in Python I suppose.

#

But yeah that's why I called it the I mean it operator

silver ore
#

I do get it's just surface level but not deep understanding

#

How I can implement in my day to day code

#

Is it really necessary

shut zealot
#

There are some funny edges to it, to my eye.. for example:

class Example:
    [(j := i) for i in range(5)]  # INVALID
silver ore
#

Ya

#

Feels like I understand

#

I see more examples

#

I get more confused

#

Like that if else block with walrus operator

#

It's ez to read what the code does

shut zealot
#

My biggest complaint is that it doesn't support inline type annotations.

silver ore
#

I found it handy

shut zealot
#

So I guess I prefer to avoid using this where I can

silver ore
#

Ya bro

#

We should complain about it n ask from it dev team to add type annotations

#

It will provide safety

shut zealot
#

but I guess it's nice to be able to say this:

if env_base := os.environ.get("PYTHONUSERBASE", None):
    return env_base
``` but the type thing, yeah, that irks me.
subtle viper
shut zealot
subtle viper
silver ore
#

Is there any python library just for one liner.? Pre written snipets

shut zealot
#

Some of these examples I'm just not down with:

while total != (total := total + term):
    term *= mx2 / (i*(i+1))
    i += 2
return total

Like.. please spend another line to make this less nested? I dunno, maybe just me.

silver ore
#

As I hurt my wrist flicking in pc game ๐ŸŽฎ I can't type properly

#

I am using voice to text ๐Ÿคง

silver ore
flint hollow
#

tbf, that code is technically a syntaxerror

shut zealot
shut zealot
flint hollow
#

doesn't the pep indent the return

shut zealot
silver ore
#

I guess I need to be so high to understand this

flint hollow
#

it should also be noted, however, the context of the example:

The while test there is too subtle, crucially relying on strict left-to-right evaluation in a non-short-circuiting or method-chaining context. My brain isnโ€™t wired that way.

But cases like that were rare.

silver ore
#

Maybe time to go docs or get back to reading pep8 guidelines again

#

As I didn't touched it for long I feel so backlog

silver ore
#

We so use to simplicity that we getting stuck

shut zealot
#

in which case it's kinda missing a 'precision' param

#

lol yeah I just pasted it into Claude and asked it to reconstruct the full function, and it agrees

#

The PEP implementation would run into you hit floating-point precision limits, which might be more ocean boiling than you wanted

#

Hmm I just tried writing this the way I'd prefer and I have to admit it's quite a bit longer.

subtle viper
shut zealot
#

This is my best take so far.. way open to suggestions though

def cos_approximation(x, precision=1e-10):
    neg_x_squared = -x**2
    total = term = 1.0
    term_index = 2
    
    while True:
        old_total = total
        term *= neg_x_squared / (term_index * (term_index + 1))
        total += term
        term_index += 2
        
        if abs(term) < precision or old_total == total:
            return total

(sorry, kinda the opposite of esoteric)

#

but this is what I'd do instead of walrus-ing it like that example.. and yeah good point that the author calls it out as too-terse.

#

There's probably some nardog way to do that as a single comprehension but I guess I'm not there yet

twin roost
#

TIL augmented assignment + unpacking don't work together

a, b = 0, 0

def test() -> tuple[int, int]:
    return 5, 5


# Pyright:
# Expression with type "tuple[Unknown, Unknown, int, int]" cannot be assigned to target tuple
#   Type "tuple[Unknown, Unknown, int, int]" is incompatible with target tuple
#     Tuple size mismatch; expected 2 but received 4
# SyntaxError: 'tuple' is an illegal expression for augmented assignment
a, b += test()
subtle viper
#

ok more esolang rambling. ```py
def maxsumb(xs):
it = iter(xs)
r = a = next(it, 0)
b = -1e3082
for v in it:
r += v
a = min(a, r)
b = max(b, r - a)
return 0 if b == -1e308
2 else b

print(maxsumb([-4, 1, 3, 5, 1, -10, -100, 7, 1]))

esolang equiv:

($@x21'308*-$a$b0'x$=(-+:'a>?$a:-'a+:'b>?$b?)?;'b:22@,=??0)$`maxsumb
?; #"non-obligatory stack pop"

`maxsumb@((4-1351'10-'100-71))$<

subtle viper
mental radish
#
import discord.ext.commands as c,discord as d,tokens as t
b=c.Bot((),intents=d.Intents.all())
@b.tree.command()
async def s(i,a:int):
 async for(m)in(i.channel.history(limit=a)):
  await(m.delete())
@b.event
async def on_ready():await(b.tree.sync())
b.run(t.tokens["testbotpy"])
``` how shorten?
rigid trench
#

!e

night quarryBOT
#
Missing required argument

code

rigid trench
#

!e ```py
def foo(): {
print("Hello world")
}

foo()```

night quarryBOT
rigid trench
#

bruh

#

wtf

mild turtle
#

!e

def my_func():print(1);print(2);print(3);

my_func()
night quarryBOT
hybrid trail
#

Super tricky puzzle:

i=1000;exec(__________________*_)

In the code, each underscore can be replaced with any byte. Can you fill it in such that the code prints only the even numbers between 999 and 1? (998, 996, ..., 6, 4, 2)

grave grail
hybrid trail
#

oops, edited

shut zealot
#

Just to be sure, we only get one byte after the *?

grave grail
#

How many underscore there for the long one

shut zealot
#

18 it looks like

grave grail
#

"print(i);i-=1;" *i
Being silly rn because it didn't specify to only print every even number between 999 and 1
So technically this did print every even number between 999 and 1, just also all the odd number as well

#

And also 1000

subtle viper
grave grail
#

Yes unless I'm blind

grave grail
#

What is the seperator between the number, or just ""

hybrid trail
#

newline

noble belfry
#

Does anyone know if it's possible to raise objects that do not derive from 'BaseException', without using a wrapper? (cpython)

subtle viper
#

!e ```py
import ctypes as ct
class A: ...
ct.c_ulong.from_address(id(A)+16+8*19).value |= 2**30
print(A.flags)
raise A

night quarryBOT
noble belfry
#

!e

import ctypes as ct
ct.c_ulong.from_address(id(str)+168).value |= 1<<30
try:
    raise "test"
except:
    print("caught")
night quarryBOT
subtle viper
noble belfry
#

ok, thank you anyways. Guess i will have to do ast rewriting after all.

craggy hamlet
#

not sure if that's allowed here

mental radish
#

if it was a nuking bot, it wouldnt ask for the amount of messages, it would trigger automatically, and would destroy all channels

mental radish
craggy hamlet
#

that's all

mental radish
midnight isle
#

Obfuscate a Discord bot blobhuh yeah if the CIA wanted to deadge

#

We could probably build one in the Python community to match or best any government tech I reckon. If we really wanted to tbh blobgrimacing

craggy hamlet
#

what

versed eagle
subtle viper
midnight isle
# craggy hamlet what

Stealth tech. Is kind of what I meant. Sorry. I wouldnโ€™t be surprised if some from the community work in government or building cutting edge tech that isnโ€™t known in the mainstream or open source

earnest wing
midnight isle
#

You are getting sleepy Olivia. Veryy sleepy - bro it is 3am here smh

earnest wing
#

what are you

midnight isle
#

Donโ€™t poke about the obfuscated discord bot Olivia, Tristian will jump out from the shadows

midnight isle
mental radish
mental radish
grave grail
#

!d discord.TextChannel.purge

night quarryBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have [`manage_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_messages) to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history) is also needed to retrieve message history...
versed eagle
midnight isle
# versed eagle this is nonsense

Proprietary technology really has brainwashed programmers. Any real builder of proprietary software working at any company knows what real โ€˜nonsenseโ€™ looks like.

earnest wing
#

markov chain check?

subtle viper
#

can we replace chatgpt with this guy

earnest wing
midnight isle
#

Iโ€™m not sure if that is a compliment or Iโ€™m getting fried ๐Ÿ˜‚

arctic skiff
#

where the heck is esoteric stuff in this convo

subtle viper
midnight isle
#

esoteric like asking if the Python standard library has a library for ABI programming blobhuh

arctic skiff
subtle viper
arctic skiff
subtle viper
#

it's unimplemented bcause they took my pc away โ€“โ€ฆโ€“

arctic skiff
arctic skiff
subtle viper
#

but that's old so i'll change it when i get my pc back in 2 months

earnest wing
midnight isle
#

Hmm we can get more esoteric. ABI vs API blobhuh

subtle viper
earnest wing
#

that's fun

midnight isle
#

Thatโ€™s looks more like on the api side of python ๐Ÿ‘€

arctic skiff
subtle viper
#

currently planning how to go about that

#

```_A`` var?

arctic skiff
subtle viper
#

okay-

#

^_^

fluid pumice
mental radish
grave grail
subtle viper
hybrid trail
#

!e

# simple python operator tutorial
# created by bulmenisaurus. part of the timed programming session. time spent coding: 437 seconds (~7 minutes). 

a=b=1
a=โ€=b # -> true
a!=b # -> false

# integer division (repeating operator means integer result)
print(a // b) # -> 1

# ** means integer multiplication
a, b = 10, 5
print(a *โ€* b) # -> 50

# same with modulo (python uses %)
print(a %โ€% b) # -> 0

# like other c like lanaguages, python has -- and ++
print(+โ€+a) # -> 11
a--โ€
print(a) # -> 10
night quarryBOT
versed eagle
#

its actually a really neat idea

#

lkfdjdsklf

#

i kind of wanna steal it

versed eagle
arctic skiff
twin roost
#

is there any case when python would optimize the local name away during compilation?

#

!e

import dis
def test():
    x = 2
    y = x + 2
    return y
dis.dis(test)
night quarryBOT
twin roost
#

E.g. optimize out x in a case like this

#

I was just watching talk and got an impression that compiler does it, but I've never the case when it actually would work.
Maybe this part of the talk was just a way to introduce constants folding, when a = 25 + 19 would actually be optimized to a = 44, idk

austere mauve
#

A bit dangerous optimising bytecode - it changes the side-effects (but with this measure any bytecode optimisation would be dangerous). Maybe it could...

twin roost
#

I just don't see why it wouldn't be possible to optimize those variables that juse use literals

versed eagle
#

it might jit to be more optimised at runtime but it wont ever elide x entirely, i think

#

because its hard to know whether x will be used later in some mysterious way

oblique drift
#

!e py def checkNumber(digit=15): even = True number = 0 while number < digit: number += 1 even = not even print(f"Number: {number}, Even: {even}") checkNumber()

night quarryBOT
# oblique drift !e ```py def checkNumber(digit=15): even = True number = 0 while num...

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

001 | Number: 1, Even: False
002 | Number: 2, Even: True
003 | Number: 3, Even: False
004 | Number: 4, Even: True
005 | Number: 5, Even: False
006 | Number: 6, Even: True
007 | Number: 7, Even: False
008 | Number: 8, Even: True
009 | Number: 9, Even: False
010 | Number: 10, Even: True
... (truncated - too many lines)

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

oblique drift
#

๐Ÿ’€

#

most sane code

versed eagle
#

you cant optimise x out here, because its still needed later

grave grail
#

Hmm

#

!d inspect.getframeinfo

night quarryBOT
#

inspect.getframeinfo(frame, context=1)```
Get information about a frame or traceback object. A [`Traceback`](https://docs.python.org/3/library/inspect.html#inspect.Traceback) object is returned.

Changed in version 3.11: A [`Traceback`](https://docs.python.org/3/library/inspect.html#inspect.Traceback) object is returned instead of a named tuple.
versed eagle
#

and at that point its not really worth the time taken while implementing and the maintenance burden and what not

grave grail
#

!e

import inspect
frame_log =[]
def f():
    x = 2
    y = x*2
    frame_log.append(inspect.currentframe())

f()
print(frame_log[0].f_locals["x"])

You never know when it's still needed :)

night quarryBOT
grave grail
#

!e

import inspect
frame_log =[]

def not_suspicious_func():
    frame_log.append(inspect.currentframe().f_back)

def f():
    x = 2
    y = x*2
    not_suspicious_func() # Nothing would went wrong right?

f()
print(frame_log[0].f_locals["x"])

Even better

night quarryBOT
stable hornet
versed eagle
versed eagle
#

in more complicated cases you can run into things like closures or some such

stable hornet
#

I suppose it wouldn't make a difference in most cases since the compiler doesn't have much to reason with

versed eagle
#

yeah

earnest wing
#

also it leads to like 0 actual performance boost when profiling

subtle viper
#

!e ```py
import dis
def test():
x = 2
y = x + 2
return y

dis.dis(test)

night quarryBOT
subtle viper
#

aw

#

they don't have STORE_FAST__LOAD_FAST in 3.13

versed eagle
#

which i think is cute

#

!e ```py
import dis
def f():
x = 1
x + x
dis.dis(f)

night quarryBOT
flint hollow
#

!e [i for i in [(x:=3)]] what cruelty thine inflict upon me, python!

night quarryBOT
flint hollow
#

@shut zealot that's why ucd has the dunder import, but not sys, btw

#

also import unicodedata as ucd is a federal law

shut zealot
#

Huh I'm a little surprised that doesn't work, interesting

fleet lintel
night quarryBOT
versed eagle
#

but yes, it is possible to alter things in such a way that the program would no longer have the expected result were the optimisation applied

#

a more agnostic (but still implementation detail dependent) way to do this would be with tracing functions

fleet lintel
#

I wonder if it would be possible to do something like using inspect/traceback to schedule code to run at a specific line number.

#

Since there was that goto implementation posted here a while back

versed eagle
#

one would either have to alter the running code object or use a tracing function for that

twin roost
fleet lintel
twin roost
#

Those are even harder to imagine being actually used

versed eagle
#

pretty much, if you allow any expression or statement that isnt setting x or y in these specific ways then your optimisation is invalid

twin roost
#

I thought f-strings are using vars too but they seem to access consts directly

#

!e

def test(): x = 25; print(f'x = {x}')

import dis
dis.dis(test)
night quarryBOT
fleet lintel
#

(The corruption of spending too much time in eso-py)

versed eagle
twin roost
versed eagle
#

oh i see

#

you want to optimise a subset of python, rather than python itself

#

i would recommend checking out RPython

fleet lintel
#

I'm not familiar with them, but I'd think the compile-to-c flavors of python like Cython or Nukita have some sort of restriction like that

versed eagle
#

i dont know about Nukita, but Cython also changes the syntax and adds extra sorts of things

#

RPython is a strict subset of python

twin roost
#

are those 3 cython nuitka and rpython are basically separate languages with their own compilers?

#

I was thinking more of something like what numba does, some kind of @optimize decorator that would recompile the byte code

stable hornet
night quarryBOT
subtle viper
grave grail
night quarryBOT
subtle viper
#

i'm seeing less sys._getframe() and more inspect.currentframe()

red barn
#

is = equivalent to .__set__() ?
I want to use in pytorch as it is not allowing me to use two = operaters in one line.

subtle viper
#

but it doesn't mean the attribute gets assigned when calling .__set__(), so it's not necessarily equivalent

night quarryBOT
#

:incoming_envelope: :ok_hand: applied timeout to @gilded fiber until <t:1745331387:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).

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

twin roost
#

have you seen this?

#

!e

def test():
    try:
        return 42
    finally:
        return "Unexpected"

print(test())
night quarryBOT
twin roost
#

I didn't know that there is a such esoteric feature in python

night quarryBOT
twin roost
#

It's not even discarding the full return statement, it just not returning the value

#

!e

def x():
    print('hey')
    return 32

def test():
    try:
        return x()
    finally:
        return 23

print(test())
night quarryBOT
grave grail
#

Yep
Because it got the value
And
Hey time to return ->
Oh wait I need to do finally first, I cannot just leave that
Done finally
Oh such a shame I already returned, guess I cannot return again now

austere mauve
#

Imagine that it's something like:

On return:
  set $return_value to return value!
  raise ItsTimeToReturnIGuessException (cached by default on function call)

Therefore:
try:
  return stuff
finally:  # Runs after any interrupts leaving the try cause, so exceptions, ItsTimeToReturnIGuessException and just_leaving_the_scope_dont_mind_me_exception
  return sneaky  # we'll catch "the exception" and set the SPECIAL VARIABLE OF RETURN to ``sneaky``
sharp delta
#

!e py import os for i in range(10000000): os.mkdir(str(i))

grave grail
#

You click the try again, not run in ...

#

And also #bot-commands

sharp delta
#

!e py import os for i in range(10000000): os.mkdir(str(i))

night quarryBOT
twin roost
blissful rock
#

i'm going down the pympler rabbit hole, measuring the size of all my Python objects. something i haven't figured out yet is measuring the memory overhead of loading a module.. pympler's output is strange when pointed at a module

twin roost
#

!e

a = {"a": 25, "b": 42}
lst = [a]
b = {"b": 42, "a": 25}
print(b in lst)

a = [1, 2, 3]
lst = [a]
b = [1, 2, 3]
print(b in lst)
night quarryBOT
twin roost
#

omg, I didn't know contains is using == to figure the matching object, I thought it would be using is

civic crypt
#

!e

night quarryBOT
#
Missing required argument

code

magic wraith
night quarryBOT
magic wraith
#

ok this was unexpected to me, my python 3.12.7 returns none for the third one

twin roost
#

Now I can only hope I haven't introduced some weird bug anywhere because of this assumption

proper vault
#

!e ```py
def find_using_is(arr, el):
for idx, i in enumerate(arr):
if i is el:
return idx

arr = [-4, 77, 8394]
print(find_using_is(arr, -4))
print(find_using_is(arr, 77))
exec('print(find_using_is(arr, 8394))')

night quarryBOT
proper vault
#

if you use the same int literal in a compilation unit multiple time, it'll only get created once

twin roost
#

!e

a = (1,2,3)
b = (1,2,3)
print(a is b)
night quarryBOT
twin roost
magic wraith
#

yeah in idle you execute it line by line instead of all at once

#

!e ```py
def find_using_is(arr, el):
for idx, i in enumerate(arr):
if i is el:
return idx

arr = [-4, 77, 8398]
print(find_using_is(arr, -4))
print(find_using_is(arr, 77))
print(find_using_is(arr, eval('8398')))
print(find_using_is(arr, arr[2]))```

twin roost
night quarryBOT
magic wraith
twin roost
subtle viper
#

!e ```py
class x:
eq = lambda a, b: print("done") or a is b

l = [x(), x()]
m = l.copy()
n = [x(), x()]
print("m:")
l == m
print("n:")
l == n

night quarryBOT
subtle viper
#

list.__eq__() does both is and ==, btw

twin roost
magic wraith
#

probably a shortcut to avoid checking elements of itself

subtle viper
proper vault
#

it first checks a is b, and if that is False, it does a == b

#

this causes it to be wrong with NaN

magic wraith
#

it would make sense if it checked len too (after ensuring the other is a list too)

twin roost
#

oh, I see, makes sense

subtle viper
night quarryBOT
subtle viper
#

yup

#

checks length mismatch before anything. ^^

magic wraith
magic wraith
#

gotcha

twin roost
#

!e

class x:
    __eq__ = lambda a, b: print("done") or a is b

l = [x(), x()]
n = [x()]
print(l == n)
night quarryBOT
magic wraith
#

!e py from math import nan a = eval('[nan]') b = [eval('nan')] print(a == a, a == b, a[0] == b[0], a[0] is b[0])

night quarryBOT
magic wraith
#

how is the second one True tho?

twin roost
#

sometimes I feel like this channel is some kind of Python related jazz club

subtle viper
#

so, you know.. is equality

magic wraith
#

oh right it's the same nan ๐Ÿคฆโ€โ™‚๏ธ

subtle viper
#

weird activity going on and concealed from the public.. sorta :3c

hybrid trail
#

!e ```py
t=b"5966235733 12250270781 225129188 1169776007 7209451424 12849676943"
from hashlib import md5
exec(b'print('+b'\n'.join(md5(c).digest() for c in t.split())+b'\n)')

night quarryBOT
hybrid trail
#

This is a stupid way to store data

blissful rock
#

Hello, backdoor!

glass stone
#

is there a sneaky way to print something without calling print or builtins? like print(x) but in 5 characters?

shut zealot
#

open(1,'w').write(...) I guess but that's not a lot shorter

glass stone
shut zealot
#

It's certainly got me curious; languages like Ruby and Perl have super-terse ways to access STDOUT but I can't really think of one in Python?

restive void
glass stone
#

ya... i think so or trick into dumping contents of the variable

proper vault
#

It's probably going to be ||{}[x]||

restive void
glass stone
#

hmm that doesn't seem to get executed

#

tricky challenge thanks for your help! im thinking there is a way to crash the program and spit out the contents in an error message but their error handling is good so i dunno. will post the challenge here after the CTF and see what ya'll think

grave grail
night quarryBOT
# errant crescent !e ```py import this ```

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

001 | The Zen of Python, by Tim Peters
002 | 
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/3FJ23ANHL2E67OQUB734IG4BYU

errant crescent
#

import __hello__ doesn't want to work ;-;

hybrid trail
#

a related puzzle with a silly solution: what is the shortest python code that prints a pangram, i.e. the output has every letter a-z at least once (case insensitive)

grave grail
hybrid trail
#

not that I know of

grave grail
#

vars() in repl

grave grail
#

Because you didn't require me a specific environment

hybrid trail
#

ah, I see what you mean now. I meant running the file directly as opposed to the repl, and output to stdout

grave grail
#

!e
print(vars())

night quarryBOT
# grave grail !e `print(vars())`

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

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fef7d488dd0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/main.py', '__cached__': None}
grave grail
hybrid trail
#

it should work regardless of filename

grave grail
#

Ok

stable hornet
#

no stderr? ๐Ÿ˜ข

grave grail
#

!e
print(globals())

night quarryBOT
# grave grail !e `print(globals())`

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

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fb58cdd8dd0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/main.py', '__cached__': None}
grave grail
#

Not helpful

#

print(vars(),"qvwy")

hybrid trail
#

I'm pretty sure the stdout solution beats any stderr abusing one, but you can try ๐Ÿ˜‰

grave grail
#

!e print(dir())

night quarryBOT
# grave grail !e `print(dir())`

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

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
grave grail
#

...too few

#

jqvwxy=z=print;z(dir())

stable hornet
#

I can do 10 with stderr but I get the feeling that yours is going to be shorter ```
esmecat@papaya:~$ python3 -c "[]['zvqj']"
<string>:1: SyntaxWarning: list indices must be integers or slices, not str; perhaps you missed a comma?
Traceback (most recent call last):
File "<string>", line 1, in <module>
[]['zvqj']
~~^^^^^^^^
TypeError: list indices must be integers or slices, not str

glass stone
night quarryBOT
grave grail
#

If you are not sure about the channel topic, read it

glass stone
#

i know its not support i just thought this qualified as esoteric thought i'd share sorry to break your rules ๐Ÿ˜ฆ

grave grail
#

Only take 2 input where first is that and second whatever

#

Assuming I remember exec at the right scope

stable hornet
#

try: exec(guess) is a very strange way to do target == guess. You also introduce such false positives as "print", "input", "super", "bytes", "float", "round", and "slice" not to mention the one mentioned above

grave grail
#

I think it meant for eval code execution

glass stone
#

ya your code gets executed and if you get all green it ran without error if not then all red.

#

so you need to somehow compare individual indexes of the f string maybe hell i dunno

stable hornet
#

if you're looking to do something nasty then perhaps you could try golfing the guess result rules. As your code is I don't think it quite has the same behaviour has wordle (which I assume is what you're trying to emulate)

glass stone
grave grail
#

So what is the challenge?

glass stone
#

well you connect to the server, and somehow need to get the contents of f which is flag.txt on the server's system.

#

flag for mat usualy like pwnctf{l337FLAGTIMEWOOT}

#

you should try some its a lot of fun. much fun. such challenge

grave grail
#

I searched subset of function that is <= 3 char

#

But only thing I find helpful is combining int and min

#

Where you can take a min of the string, and integer it

#

Which gives you less constraints

#

If you can replace it to len

#

But only if you can combine it

hybrid trail
#

so basically you need to leak the flag, but you can only output information via erroring/not erroring?

grave grail
#

Well, you have multiple round of exec

#

So you might able to inject stuff

#

I figured out how to create arbitrary length string now

#

But storing eval/exec require 6

#

a=exec

#

For example

stable hornet
#

I think someone already mentioned a way to do this

grave grail
#

Who

#

If I can have exec where the function name is <2character, I can run arbitrary code

hybrid trail
#

if you have multiple runs, you can maybe binary search it one character at a time

#

like

k='a'
j=k>f
1/j
``` could tell you if codepoint of the first character is greater or less than `'a'`
#

and then once you get the first character just make k longer

grave grail
#

What the binary search for

#

Oh f is already the string?

#

I thought it was the file handle the whole time lmao

glass stone
magic wraith
#

idk if it was mentioned alreafy

#

eval takes expressions, not statements
but things such as [a:=3] and setattr(a,1,2) are expressions

magic wraith
grave grail
#

Unless you can modify len to something usable first, you only get 5 char each time

#

Best bet is convert len to eval
a=eval
len=a
But require min 6 currently

grave grail
#

!e

f="secret" # outside eval

k=int
k(f)#
night quarryBOT
grave grail
#

Would this work?

#

Or have to not error

#

Oh wait nvm I forgot the except

#

Thinking how to cause a warning

versed eagle
#

syntaxwarning

#

is probably the easiest

#

or deprecation warning but those are unlikely to print anything useful i think

grave grail
#

Syntax cannot print something useful

earnest wing
#

i mean unless there's some other 1-char function in the environment you can hook len into your best bet is getting 1 bit at a time

grave grail
#

You can use 3 char
k=abc
len=k
But I checked but nothing seems work

twin roost
#

Top 10 bugs I don't wanna meet in production code

#

!e

def run(gen):
    next(gen)

def main():
    x = 42
    gen = (i for i in range(20) if i >=15 and (x:=i))
    run(gen)
    print(x)

if __name__ == "__main__":
    main()
night quarryBOT
subtle viper
twin roost
#

yeah, it's not very welcomed both as a feature and as a bug it might become ๐Ÿ˜„

#

It's probably working in similar way to closures from nonlocal

vast wave
#

closure captures x as an assignment target, you invoke the generator which invokes the closure to get a value, the first one being 15 since i >= 15 is true and x := 15 -> 15 is also true

#

side effect is assignment to x

versed eagle
subtle viper
twin roost
#

I mean it is explainable, it's just very weird when some function very far away can change local variable in another function.

#

I meant not that this particular code has a bug, but that it could easily introduce one

subtle viper
#

!e ```py
def a(it):
x = 36
print('a', x)
print(next(it))
print('a', x)

def b():
x = 42
print('b', x)
a((x := i for i in range(5)))
print('b', x)

b()

night quarryBOT
subtle viper
#

it can't change anything "very far away" no more than a normal closure function

twin roost
#

That's understandable that it cannot change a scope, I was more worried that it may unexpectedly change x in b.
But yes, it's the same thing as with nonlocal closures.

flint karma
#

!e ```py
import math as math;
class console:
def init(self):
pass;
def log(x):
print(x);

text = list("i am not sorry");
if True: console.log(str("".join(text)));

night quarryBOT
flint karma
#

this is the worst piece of code i have ever written in my life

sharp delta
summer venture
#

hi

earnest wing
flint karma
subtle viper
night quarryBOT
grave grail
earnest wing
#

it is, because it's important that every class has a pass;

worthy nova
#

Hi there! I don't know if this is the perfect place to ask this question (I'm new here).

In my python programming class we noticed that the first 128 integers seem to be preloaded by the python interpreter. That is, despite the fact that integers are immutable, new variable declarations seem to point to the same place in memory. If I declare two large integer variables x,y to the same number, the statement 'x ==y' is true but the statement 'x is y' is false. This isn't true for these special lower integers. 'x is y' evaluates to true!

Does anyone know why this is happens? Is it an intentional optimization, because low integer numbers are used frequently?

subtle viper
#

basically, every integer in range(-5, 257) (-5 to 256 inclusive) is preloaded

#

if it's <= -6 or >= 257, the integer is not preloaded

versed eagle
placid jetty
#

Idk what channel to ask this in so: is these 2 things equal in what they do, cuz someone on a dif server told me to use match/case instead of the severe If spam

restive void
#

Equal in that there's a SyntaxError in both.

#

But generally speaking, you can replace simple if-elif-elif-... chains with match-case, but match-case is more than just that, it matches patterns.

#

(and regular if is better for complex conditions, I'd say)

shut zealot
#

(Also at the risk of stating the obvious, your if code checks every case top to bottom, and the match code stops when it finds the first match.)

austere mauve
#

(using elif would prevent it)

placid jetty
shut zealot
#

The argument you see here a lot is that it's for 'pattern matching' not 'multi-if'.. but I don't personally find it so objectionable.

placid jetty
#

So it can be used for both but If/Elif can be used for more complicated conditions, so for an equality check its fine to just do match/case?

shut zealot
#

e.g.

match command.split():
    case ["go", ("north" | "south" | "east" | "west") as direction]:
        current_room = current_room.neighbor(direction)
``` is kind of the motivating story
#

But they show an example of HTTP status codes, and I personally think it's fine to use there too

#

Other people feel differently and like to use if/elif whenever they aren't using the 'full' features of match/case.

placid jetty
#

Im using it I guess, it looks neater

stray grove
fleet lintel
blissful rock
#

!e

class Thing:
    order = 0

    @classmethod
    def __lt__(cls, other: type) -> bool:
        if not issubclass(other, Thing):
            return NotImplemented
        return cls.order < other.order

class BigThing(Thing):
    order = 1

class LittleThing(Thing):
    order = -1

print(BigThing < LittleThing)
night quarryBOT
blissful rock
#

is there a way around this?

astral rover
#

you need a metaclass

#

!e

class Thing(type):
    order = 0

    @classmethod
    def __lt__(cls, other: type) -> bool:
        if not issubclass(type(other), Thing):
            return NotImplemented
        return cls.order < other.order

class BigThing(metaclass=Thing):
    order = 1

class LittleThing(metaclass=Thing):
    order = -1

print(BigThing < LittleThing)```
night quarryBOT
astral rover
#

@blissful rock ^

#

!d metaclass

night quarryBOT
#

The class of a class. Class definitions create a class name, a class dictionary, and a list of base classes. The metaclass is responsible for taking those three arguments and creating the class. Most object oriented programming languages provide a default implementation. What makes Python special is that it is possible to create custom metaclasses. Most users never need this tool, but when the need arises, metaclasses can provide powerful, elegant solutions. They have been used for logging attribute access, adding thread-safety, tracking object creation, implementing singletons, and many other tasks.

More information can be found in Metaclasses.

blissful rock
#

oh nice

restive void
subtle viper
#

!e

class Thing(type):
    order = 0

    def __lt__(cls, other: type) -> bool:
        if not issubclass(type(other), Thing):
            return NotImplemented
        return cls.order < other.order

class BigThing(metaclass=Thing):
    order = 1

class LittleThing(metaclass=Thing):
    order = -1

print(BigThing < LittleThing)
night quarryBOT
subtle viper
#

it seems to not matter in this situation?

#

i am perplexed.

#

!e

class Thing(type):
    order = 0
    def __lt__(cls, other):
        if not isinstance(other, Thing): return NotImplemented
        print(cls.order)
        return cls.order < other.order

class BigThing(metaclass=Thing): order = 1

class LittleThing(metaclass=Thing): order = -1

print(BigThing < LittleThing)
night quarryBOT
subtle viper
#

!e ```py
class Thing(type):
order = 0
@classmethod
def lt(cls, other):
if not isinstance(other, Thing): return NotImplemented
print(cls.order)
return cls.order < other.order

class BigThing(metaclass=Thing): order = 1

class LittleThing(metaclass=Thing): order = -1

print(BigThing < LittleThing)

night quarryBOT
subtle viper
#

the use of @classmethod uses Thing.order, which is 0
the not-use would utilize BigThing.order, which is 1

#

coincidentally, both values are not less than the value of LittleThing.order

#

(1 < -1 => False, 0 < -1 => False)

subtle viper
#

python assignments are truly confounding-

#

instead of following the unwritten(?) rule of closest first, it executes in first-written first order

#
@spam
@ham
def eggs(): ...
# eggs => ham => spam

-~x
# x => ~ => -

a = b = 42
# 42 -> a -> b
earnest wing
#

binary operators would be a better analogue, in particular comparison chains

#

but it's goofy yea

#

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

#

evaluation jumping from right to left to middle, you can't even conceptualize the assignments as parallel

magic wraith
north zinc
#

NE1 IN?

blissful rock
tame furnace
fleet bridge
night quarryBOT
#

main.py line 42

if memory_pointer < 30000:```
fleet bridge
night quarryBOT
#

main.py line 46

get_in = input()```
noble belfry
#

!e

import sys
import ctypes as ct
import string

Py_TPFLAG_HAVE_GC = 1 << 14
NULL = 0
__used_list__ = set()

if sys.platform.startswith("linux"):
    libc = ct.CDLL("libc.so.6")  # Linux
elif sys.platform.startswith("win"):
    libc = ct.CDLL("msvcrt.dll")  # Windows
else:
    raise OSError("Could not find clib!")


class AllocationError(MemoryError): ...
class FreeError(MemoryError): ...
class DoubleFreeError(FreeError): ...


malloc = libc.malloc
malloc.argtypes = [ct.c_size_t]
malloc.restype = ct.c_void_p

free = libc.free
free.argtypes = [ct.c_void_p]

memcpy = libc.memcpy
#                   dest            src         n
memcpy.argtypes = [ct.c_void_p, ct.c_void_p, ct.c_size_t]


def malloc_obj(obj) -> ct.c_size_t:
    addr = malloc(size := sys.getsizeof(obj))
    if addr == NULL:
        raise AllocationError(f"Failed to allocate object of size {size}!")
    memcpy(addr, id(obj), size)
    new_obj = ct.cast(addr, ct.py_object).value
    # We should un-set Py_TPFLAG_HAVE_GC to prevent the object from being
    # garbage collected but there does not seem to be a consistent,
    # cross-platform way to find the offset of the tp_flags member on a
    # PyTypeObject, so we 'manually' increment the refcount by adding
    # the new object to a global set to prevent Python from trying to
    # free it
    global __used_list__
    __used_list__.add(new_obj)
    return new_obj


def free_obj(obj):
    # We let Python free the object lazily as explicitly freeing it would cause
    # a double free at the end of the program when Python tries to free
    # all leftover objects.
    # This should also prevent use-after-free since Python will keep the object
    # until it is sure that there are NO references to it anymore
    try:
        global __used_list__
        __used_list__.remove(obj)
    except:
        raise DoubleFreeError("tried to free object that was never allocated")


my_string = malloc_obj("Hello")
print(my_string)
free_obj(my_string)
night quarryBOT
subtle viper
#

huh..?

#

oh..

#

oh..

#

umu.

#

!e ```py
import sys
import ctypes as ct
import string

NULL = 0
used_list = set()

if sys.platform.startswith("linux"): libc = ct.CDLL("libc.so.6")
elif sys.platform.startswith("win"): libc = ct.CDLL("msvcrt.dll")
else: raise OSError("Could not find clib!")

class AllocationError(MemoryError): ...
class FreeError(MemoryError): ...
class DoubleFreeError(FreeError): ...

malloc = libc.malloc
malloc.argtypes = [ct.c_size_t]
malloc.restype = ct.c_void_p

free = libc.free
free.argtypes = [ct.c_void_p]

memcpy = libc.memcpy

dest src n

memcpy.argtypes = [ct.c_void_p, ct.c_void_p, ct.c_size_t]

def copy_obj[T](obj: T) -> T:
addr = malloc(size := sys.getsizeof(obj))
if addr == NULL:
raise AllocationError(f"Failed to allocate object of size {size}!")
memcpy(addr, id(obj), size)
ct.c_ssize_t.from_address(addr).value = 1
new_obj = ct.cast(addr, ct.py_object).value
global used_list
used_list.add(new_obj)
return new_obj

def free_obj(obj):
try:
global used_list
used_list.remove(obj)
except KeyError:
raise DoubleFreeError("tried to free object that was never allocated")

one = 1
other = 1
obj = copy_obj(one)
print(one, obj)
print(one is other, one is obj)
free_obj(obj)

night quarryBOT
subtle viper
#

hehe. non-cached 1

tame furnace
tame furnace
errant crescent
#

wut?!

grave grail
#

Also I don't think adding/remove from list require global

subtle viper
grave grail
#

Oh well

fleet lintel
#

I recently came across something really baffling, I guess python normalizes line endings before running?

shut zealot
#

I would imagine the lexer replaces the platform-specific line endings with a universal representation?

#

Oh, in a string like that though? Weird.

fleet lintel
#

!e ```py
print(f"\n={ord("\n")} \r={ord("\r")}")
exec("print(ord('''\r'''))")

night quarryBOT
fleet lintel
#

I wonder if you ran this on an old Mac with native \r lien ends it would give 13, or if itโ€™s always 10

#

I guess Iโ€™d hope it would always be 10, since otherwise it could/should fail on a system with \r\n as the native

#

!e exec("print(ord('''\r\n'''))")

night quarryBOT
fleet lintel
#

Thatโ€™s also slightly cursed, what looks like a multi char ord ends up working

versed eagle
#

yeah it is a bit silly but overall a good design choice probably

grave grail
arctic skiff
#

!e```py
import ast
from linecache import*
import sys as s
from traceback import*
s.excepthook=lambda t,v,tb:getattr(builtins,(c:=ast.parse(getline((e:=extract_tb(tb)[-1]).filename,e.lineno)).body[0].value).args[0].value)(c.func.id)if issubclass(t,NameError)else s.excepthook(t,v,tb)

Hello_world("print")

night quarryBOT
arctic skiff
#

black formatting my spaghetti

brisk zenith
#

i love that

#

i wonder what it would do with some of my one-liners

arctic skiff
#

I wonder what it will do to my 16k char hello world

#

let me try

subtle viper
#

fun fact, python has a built-in formatter

#

!e ```py
from ast import unparse, parse
print(unparse(parse(r'''
console = type("console",(),{"log":print});
text = [...,"okay"],;
if [] == []: console.log("%s"*~-len(text)%text[()==():]);
''')))

night quarryBOT
subtle viper
#

not that it does a good job, but it expands code, at least

brisk zenith
#

that's fun!

brisk zenith
brisk zenith
arctic skiff
#

(I got 16GB of ram)

brisk zenith
#

hehe i'll work on it tonight then!

#

i remember how i made it, just gotta do it again

errant crescent
# brisk zenith i wonder what it would do with some of my one-liners

so true plus1

print(bytes((sum(range((-~True + True) * ~True * ~True)) + sum(range(~True * ~True)), sum(range(-~True * (~True * ~True -~True + True))) - (-~True + True) * ~True, sum(range((~True) ** (-~True) ** (-~True))) - (-~True + True) * -~True, sum(range(True - True, sum(range(-~True * -~True + True + -~True * -~True)) - sum(range(True - ~True)) - True, -~True * -~True + True)) + sum(range(-~True * -~True + True)) + sum(range(True - ~True)) - True, sum(range(-~True * -~True + True + -~True * -~True)) - sum(range(True - ~True)) - True, (sum(range(-~True * -~True + True + -~True * -~True)) - sum(range(True - ~True)) - True) * -~ True + ~True * ~True, sum(range((-~True * -~True + True + -~True * -~True) * -~True - True)) - sum(range(-~True * -~True + True + -~True * -~True)) + True, sum(range((-~True - ~True) * -~True, sum(range(True - ~True, sum(range(~True * ~True)) + True)))) - sum(range((-~True - ~True) * -~True + True, (-~True - ~True) * -~True - ~True)) - True, sum(range(sum(range(~True * ~True)) + True, sum(range(~True * ~True - ~True)) - ~True)) - ~True, sum(range(-~True * -~True + True + -~True * -~True)) - sum(range(True - ~True)) - True, sum(range((~True) ** (-~True) ** -~True + ~True)) + ~True, sum(range(~True * ~True + True, (~True) ** (-~True) ** -~True)) + True)).decode('utf' + str((-~True) ** (True - ~True))))
night quarryBOT
brisk zenith
#

gotta make sure it's pep8-compliant then you'll be good to go

brisk zenith
night quarryBOT
brisk zenith
#

i'm not entirely sure the paste bin would appreciate it

#

but thank you

night quarryBOT
stray grove
brisk zenith
#

what do you mean? this way is perfect

austere mauve
#

Do chess next.

errant crescent
brisk zenith
#

because i realised that was a bit unnecessary

brisk zenith
stable hornet
# brisk zenith for anybody curious of how i generated it: https://gist.github.com/skrungly/0c33...
brisk zenith
#

oh yeah! that's a fun one

#

i feel like that one is simpler.. but 330GB is insane

#

the tic-tac-toe script is only a mere 180MB

brisk zenith
#

oh boy

#

what was the task?

fleet lintel
#

This was only for part 1, basically finding numbers around asterisks in 2D and multiplying them, made 33k chars long by fixed width look back

river mica
earnest wing
#

word soup

fleet lintel
#

Time cube moment

shut zealot
#

sub-Planck is funny

arctic skiff
brisk zenith
#

yep! mine was the same.

#

it's not as bad as the original one i made a few years back, but i don't even know if that one worked properly

#

so at least this one worksโ„ข๏ธ

night quarryBOT
#

:incoming_envelope: :ok_hand: applied timeout to @brisk zenith until <t:1746881262:f> (10 minutes) (reason: newlines spam - sent 106 newlines).

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

brisk zenith
#

oops

#

been a while

#

anyways, let me try that again

#

(actually, i will do it in a bit)

brisk zenith
brisk zenith
#

easily done, i'm just a bit stupid

blissful rock
#

so it's generating 936 unused code paths? disappointingly inefficient, literally unusable

#

also: ship it

brisk zenith
#

haha exactly

#

this is the script i used to count it (without generating the actual code)

arctic skiff
#

search it up

errant crescent
#

or an immediate loss, if p2 didn't counter correctly in the 2nd turn.

#

there aren't that many moves since the board could be rotated in any way...

fleet bridge
#

outcome of ttt is decided at 0 turn (= before the game), assuming each player plays perfectly

fleet bridge
#

@errant crescent here, your turn: ```
O | . | .
. | . | .
. | . | X

errant crescent
errant crescent
fleet bridge
#

making the "perfect" move in these games is relatively controversial
not at all
hard to compute? yes, for now

fleet bridge
errant crescent
fleet bridge
#
O | . | X
. | X | O
O | . | X

O | . | X
X | X | O
O | . | X

no way to win => draw
azure pike
#

Mega Man and other NES games without PRNG are also "deterministically winnable" state machines

errant crescent
#

ofc you can rotate & flip however much u need; however the strat remains.

#

now imma delete that comment, since there are 400k members in this server.

errant crescent
versed eagle
#

if you vary the first N moves and then assume optimal play from there, it will also be deterministic based on the starting varied state

#

this is because ttt is a fully solved game

errant crescent
fleet bridge
versed eagle
#

its useful to distinguish between ply and turns here probably

versed eagle
#

the only way that you will need moves to determine the outcome is if you assume unoptimal play

errant crescent
errant crescent
fleet lintel
#

This entire discussion reminds me of this video https://youtu.be/QNFQvX-MQgI?si=6GQne9wVRB1inrhL

When it comes right down to it, there just aren't that many ways a game of Tic-Tac-Toe can go down. Join me as we investigate what it means for things to be different, with digressions into music, coding and math.

If you enjoyed this video and want some behind the scenes content, I hope you'll consider supporting me on Patreon: https://www.pat...

โ–ถ Play video
subtle viper
#

tic tac toe is so simple

#

like it's either a win or a gazillion draws

magic wraith
#

and then people like to do bizarre analysis of such simple game

#

i remember seeing somewhere "if one player plays optimally and the other plays random moves, what's the expected win-draw ratio"

versed eagle
versed eagle
azure pike
# versed eagle its not possible to do this with chess, for example

It is possible, just not with our compute- but there's no reason it couldn't be done. Chess is enumerable- just a very large search space (as an aside; checkers is solved). The DL techniques for chess attempt to estimate the win prob for every move- so you could use that as a reasonable heuristic; assuming DL has reached a level pretty close to perfect play

versed eagle
#

chess is solvable

#

but chess isnt solved

azure pike
#

My fav thing solved is Pokemon Platinum: https://youtu.be/jNMWkD5VsZ8

Scripted in Lua not python- but still fun

After getting only a 99.8% chance of success in FireRed, I'm back in Platinum, with several billions of simulations to reclaim those pesky fractions of a percent.

โš ๏ธWARNING: There are several points in the video where sped-up footage creates a strobe effect that may affect viewers sensitive to flashing lights. This occurs most prominently...

โ–ถ Play video
versed eagle
versed eagle
azure pike
#

I was responding to "it's not possible"

versed eagle
#

chess isnt solved โ†’ it is not possible for us to determine the outcome of a game given an arbitrary starting state and assuming optimal play

versed eagle
azure pike
#

it's not possible *now

versed eagle
#

it seems like you agree with me, so im not really sure why you tried to start an argument

#

so i think i will just stop engaging with this conversation now

fleet lintel
# azure pike My fav thing solved is Pokemon Platinum: https://youtu.be/jNMWkD5VsZ8 Scripted ...

That was a fun video, though the method they used looked very over complicated to me. Since battles last a different amount of time, that means they make a different number of RNG calls, so I didnโ€™t see why they couldnโ€™t just keep repeating battles until all the seeds converge to the same seed. There might be some cycles, but going full armchair mode I donโ€™t see why there wouldnโ€™t be some consistent short sequence of inputs you could repeat until all the seeds converge, then just tas the game normally

azure pike
azure pike
brisk zenith
# errant crescent so true <:plus1:768543607492706314> ```py print(bytes((sum(range((-~True + True...

also this reminds me of one of the first programs i posted in here about 7 years ago, which obfuscated strings using True and bit shifts: ```py

bytes([(True ^ True << True ^ True << (True << True) ^ True << (True << (True << True)) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << (True ^ True << True) ^ True << (True << (True << True)) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True ^ True << (True << True))), (True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << (True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << True ^ True << (True << True) ^ True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True ^ True << (True << True))), (True << (True << True) ^ True << (True << (True << True)) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << (True ^ True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << (True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True << True ^ True << (True << (True << True)) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True))), (True ^ True << (True << True) ^ True << (True ^ True << (True << True)) ^ True << (True << True ^ True << (True << True)))]).decode()
'why hello there'

versed eagle
#

this is the problem

#

every seed will be in some cycle, and not all of them will be the same cycle

earnest wing
#

it is indeed harder than the armchair would make you think

#

to converge every single seed together you need a method that is able to distinguish between arbitrary seeds without direct feedback!

#

and your only observable change is the outcome of certain random events

upper mulch
#

Hey everyone, I was doing some code golfing challenges earlier today and came across the following challenge:

Given some user input of integers separated by spaces, check if the list of integers is a valid Fibonacci sequence
IF the sequence is correct: print out "fib"
IF the sequence is incorrect: print out the first instance of an erroneous value

Example inputs and outputs:

"0 1 1 2 3 5 8"      # fib
"2 4 6 10 16"        # fib
"1 2 3 4 5"          # 4
"0 1 1 2 3 21 24 45" # 21

Here is some sample code that provides a solution:

# User inputs a list of numbers as a string, e.g. "1 2 8 3 19 101"
num_list = input().split()                            
num_list = [int(x) for x in num_list]    

# Take out the two starting integers to start the sequence with
a, b, *num_list = num_list

for i in num_list:
    # If the next integer i is correct
    if a + b == i:
        a = b
        b = i
    else:
        # If it is ever not correct, print the erroneous value and exit
        print(i)
        exit()

# If the loop succeeded in it's entirety, print "fib"
print("fib")

And here is my current shortest amount of characters I've gotten (the site I was on interpreted input() instead of print() as valid solutions)

I=input;a,b,*z=[*map(int,I().split())]
for x in z:
    if a+b!=x:I(x);exit
    a,b=b,x
I("fib")

I was wondering if anyone could beat my record of 93 bytes here, since I've gotten a bit obsessed with this specific challenge

upper mulch
subtle viper
#

basically a shrunk down version, so..

upper mulch
#

yup that'll do it

subtle viper
#

i need to get back to codingame when i get my pc back =^^=

upper mulch
#

How exactly does that a+b!=p>l(p) work? I've never seen > like that before

subtle viper
upper mulch
#

I've not seen it anytime recently so if I did I forgot ๐Ÿ˜…

subtle viper
#

it's like a < b and b < c

#

so by extension, a+b != p > l(p) becomes a+b != p and p > l(p)

upper mulch
#

ohhh that's so good ๐Ÿ˜ญ , and to check it runs the code

subtle viper
upper mulch
#

Oh and since it waits when you use input you don't need exit either ofc

#

genius stuff

#

I wonder if that would've worked on codingame ๐Ÿค”

#

Or if it would complain about timeouts

#

It probably would work

subtle viper
#

(it should work for isolated test cases in theory)

upper mulch
#

codingame is fun, especially when you get a golf challenge

twin roost
#

Is there a way to check if loop iterated at least once without early continue but without setting some variable on every iteration (or checking it)?

did_iterate = False

for i in range(100):
    if i < 50:
        continue
    did_iterate = True    

print(did_iterate)
subtle viper
#

in the others, just set a variable

twin roost
#

I understand, I thought maybe there is some hack to avoid doing it more than once

subtle viper
austere mauve
# twin roost I understand, I thought maybe there is some hack to avoid doing it more than onc...
for i in [1, 2]:
    if i == 2: break
else:
    if "i" in locals():
        print("ited")

I've managed to create something that prints to console if iterated at least once without breaking out of the loop even once (not only in first iteration, but also second, third, etc), but I don't think that's what you asked for exactly, right?

Also continue skips only one iteration, you meant break?
Also, I'm guessing that you are asking this because you want to optimise your code. If so, it's not worth it.

proper vault
#

Good thinking ```py
foo = bar = object()
for foo in some_iterable:
...
did_iterate = foo is not bar

upper mulch
#

Alternatively if you are going to use i in a range:

i=0
for i in range(1):
    ...
print(i!=0)
``` seems to work for me as well
austere mauve
#

Ye, but it doesn't catch aborting with break (for whatever that's needed).

austere mauve
earnest wing
upper mulch
subtle viper
#

without evaluating, what is the output? ```py
*a, = a[:3] = "kl", *"mn" "x".join("abc"),
print(len(a))

earnest wing
#

21?

#

or no, the kl is one element

#

so 19?

#

not so, sad

arctic skiff
magic wraith
#

it's two separate unrelated assignments, the first one unpacks an iterable into a list (UNPACK opcode but it's all packed back into a single assignment target)

#

and since they go from left to right, it makes a

#

the next one a[:3] = modifies the first three elements of the newly created list a

#

remark: ```py
a = b.c = d[e] = f = g

equivalent to

tmp = g
a = tmp
b.c = tmp
d[e] = tmp
f = tmp``` (not entirely sure on this one so please correct me)

twin roost
# austere mauve ```py for i in [1, 2]: if i == 2: break else: if "i" in locals(): ...

Was asking completely out of curiosity (it seems there could be a way to do something once when you actually need it just once, instead of repeating it again and again, though maybe it's not possible in Python), I know that those kind of micro optimizations are never worth it.
I really meant continue, but checking locals to see if iterator ever had an output is a cool idea, I like it

fleet bridge
#

or 17...

#

1(kl) + 9(a mnx b mnx c) = 10 items get assigned to a
then first 3 are replaced with 10 = +7 more items
10+7=17
that's how I understand it

#

btw I didn't know "a" "b".join was syntactically valid

subtle viper
versed eagle
#

oh people already posted the answer

#

i just had to scroll down lol

#

yay i was right though

#

||```py
*a, = a[:3] = "kl", *"mn" "x".join("abc"),

*a, = a[:3] = ("kl", "a", "m", "n", "x", "b", "m", "n", "x", "c")

a = ["kl", "a", "m", "n", "x", "b", "m", "n", "x", "c"]; a[:3] = ["kl", "a", "m", "n", "x", "b", "m", "n", "x", "c"]

a = ["kl", "a", "m", "n", "x", "b", "m", "n", "x", "c", "n", "x", "b", "m", "n", "x", "c"]

print(len(a))

#

is it cheating that i evaluated it by hand

#

if taken literally, the "without evaluating" would say yes and then murder me 1000 times

subtle viper
versed eagle
#

yay

#

i didnt want to be murdered 1000 times

#

1 is probably plenty

marble river
#

aaaaaaaaaaaaaaaaaaaaaaaaand my adhd came again:

import pyautogui as p
from bs4 import BeautifulSoup, Tag

def element_to_dict(element):
    if not isinstance(element, Tag):
        return str(element).strip()

    children = [element_to_dict(child) for child in element.children if str(child).strip()]

    return {"tag": element.name, "attributes": dict(element.attrs), "children": children}

response = requests.get(url)

asdf = BeautifulSoup(str(BeautifulSoup(response.text, "html.parser").find("div", id="products-found")), "html.parser").find_all("div", class_="product")

p.write(element_to_dict(asdf[0])["children"][0]["children"][1]["children"][1]["children"][0]["attributes"]["data-micro-price"].split(".")[0])
#

i usually write worse code than this

subtle viper
marble river
#

can you direcrly replace the element to dict in p.write()?

#

i only use it once so idfc about how golfed it is

subtle viper
fleet lintel
shut zealot
#

Yeah xpath/selector-query seems like a way better approach for this example

marble river
#

Well, imma take it

fleet lintel
# marble river The Frick is this

xpath is a way of querying for elements in xml-like datastructures. // means "any child of", and when it is first implicitly means any child of the root. div means a <div> element. [] lets you specify more specific criteria of an element. @<thing> gets the value of the property of <thing> on the element, and = is comparison,. Putting this all together, //div[@class='product'] means "a div that is a child of the root element with the class product". I then chain this one more time, except the second // means any elements that are children of the first element. The ending //@data-micro-price gets the value of the data-micro-price tag from any elements that are children of the matching divs of the matching divs.

Depending on how the website looks/what data you want, it might even be golfable to just .xpath("//@data-micro-price").

I am more comfortable with xpaths, which is why I used lxml, but Defiler also mentioned selector-query, which is built into bs4 and lets you use css selector queries, which act similar to xpath expressions.

subtle viper
#

xpaths are also cooler

marble river
fleet lintel
#

The main reason I like them more than css selectors is that they are much easier to test, since almost all browsers support the $x("xpath") syntax for quickly running an xpath expression on the website

fleet lintel
shut zealot
#

XPath looks more metal to me so I guess I prefer it ๐Ÿ™‚

#

//@lets-frikkin-go

pseudo helm
#

what is estoeric python?

lunar perch
#

I think the answer will be along the lines of: "If you need to ask, then you are in the wrong place."

austere mauve
#

It's python taken to the extreme.

arctic skiff
# pseudo helm what is estoeric python?
import ast
from linecache import*
import sys as s
from traceback import*
s.excepthook=lambda t,v,tb:getattr(__builtins__,(c:=ast.parse(getline((e:=extract_tb(tb)[-1]).filename,e.lineno)).body[0].value).args[0].value)(c.func.id)if issubclass(t,NameError)else s.__excepthook__(t,v,tb)



Hello_world("print") # print('Hello_world')
```guess this snippet will be enough to answer that
subtle viper
ionic flicker
#

Yeah I'm kinda new to python so this is to be expected

subtle viper
#

so don't expect to encounter something like the above in functional projects

ionic flicker
#

Someone get the SCP foundation lmao

sick hound
#

_ โ–„โ–‚
[โ–ˆ|||โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ]โ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–„โ–„
__โ–‚โ–„โ–…โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–…โ–„โ–ƒโ–‚
Iโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ]
โ—ฅโŠ™โ–ฒโŠ™โ–ฒโŠ™โ–ฒโŠ™โ–ฒโŠ™โ–ฒโŠ™โ–ฒโŠ™โ–ฒโŠ™โ—ค

marble river
arctic skiff
#

its full of nightmares

arctic skiff
ionic flicker
hybrid trail
#

Elitism in esoteric python :(

blissful rock
#

let them ast cake

arctic skiff
sick bridge
# pseudo helm what is estoeric python?

(P:=print,R:=range,G:="\033[32m",RE:="\033[31m",B:="\033[34m",W:="\033[0m",BW:="\033[1;37m",DG:="\033[90m",M:=["#########","#.......#","#.Z.....#","#.......#","#########"],w:=[[1,1],1,[[2,2]]],PC:=['^','>','v','<'],D:={0:[-1,0],1:[0,1],2:[1,0],3:[0,-1]},r:=lambda:[P(f"\n\n{G}=== ZOMBIE HUNTER ==={W}\n"),[P("".join(f"{B}{PC[w[1]]}{W}"if[y,x]==w[0]else f"{RE}Z{W}"if[y,x]in w[2]else f"{BW}#{W}"if M[y][x]=='#'else f"{DG}.{W}"for x in R(len(M[0]))))for y in R(len(M))]],[(r(),P("\nControls: WASD to move, F for melee attack, G for ranged attack"),c:=input("\nEnter command: ").lower(),w.__setitem__(0,[w[0][0]+D[w[1]][0],w[0][1]+D[w[1]][1]])if c=='w'and M[w[0][0]+D[w[1]][0]][w[0][1]+D[w[1]][1]]!='#'else w.__setitem__(0,[w[0][0]+D[(w[1]+2)%4][0],w[0][1]+D[(w[1]+2)%4][1]])if c=='s'and M[w[0][0]+D[(w[1]+2)%4][0]][w[0][1]+D[(w[1]+2)%4][1]]!='#'else w.__setitem__(1,(w[1]-1)%4)if c=='a'else w.__setitem__(1,(w[1]+1)%4)if c=='d'else(h:=[w[0][0]+D[w[1]][0],w[0][1]+D[w[1]][1]]in w[2],P("\nMelee "+f"{G}hit!{W}"if h else f"{RE}miss...{W}"),w[2].remove([w[0][0]+D[w[1]][0],w[0][1]+D[w[1]][1]])if h else None,(P(f"\n{G}You win! Killed the zombie with melee attack!{W}"),exit())if not w[2]else None)if c=='f'else(h:=next((t for i in R(1,6)for t in[[w[0][0]+D[w[1]][0]*i,w[0][1]+D[w[1]][1]*i]]if t in w[2]),None),P("\nRanged "+f"{G}hit!{W}"if h else f"{RE}miss...{W}"),w[2].remove(h)if h else None,(P(f"\n{G}You win! Killed the zombie with ranged attack!{W}"),exit())if not w[2]else None)if c=='g'else None)for _ in iter(int,1)])
sick bridge
azure pike
#

Love this script so much. The fact it runs too is amazing

grave grail
#

Wtf

sick bridge
arctic skiff
#

and vice versa

sick bridge
#

I think it's a good challenge if you are learning

subtle viper
#

ugh i had to do this on mobile for 2 hours... whatever.

sick bridge
subtle viper
#

it's changed a bit from that form but same thing anyways.

fleet lintel
#

I recently got hooked by a Truttle1 video on the slashes (///) esolang, so I tried to golf an interpreter (279 chars with \n line ends): ```py
def slashes(s):
m=r="";t=0
while(s:=list(s)):
if(c:=s.pop(0))=="/":
if(t:=t+1)==3:
while(s:="".join(s))and m in s:s=s.replace(m,r,1)
r=m="";t=0
continue
if c=="\":
if s:(c:=s.pop(0))
else:break
(m:=m+c)if t==1 else(r:=r+c)if t==2 else print(c,end="")

subtle viper
subtle viper
#

shortened a bit more ```py
def slashes(s):
m=r="";t=0;g=1
while s:
c,*s=s;t+="/"g==c
if t>2:
while m in(s:="".join(s))>"":s=s.replace(m,r,1)
r=m="";t=0
elif g:="\"g!=c:m+=t%2c;r+=t//2
c;t<1==print(end=c)

fleet lintel
subtle viper
fleet lintel
#

Your memorization of operator precedence is crazy, I think I see how you turned the ternaries into </== but wow

subtle viper
#

i spent most of my 4 years of python experience in esopy/golfing so..

subtle viper
fleet lintel
#

I think the golf/my original implementation/the implementation I referenced on the wiki has a bug, since if I'm reading the rules right I think /\a/b/a should also output b, not a

#

no wait they do work, I'm just stupid/tired and forgot the r-string

subtle viper
#

fixed 2? ```py
def slashes(s):
m=r="";t=0;g=1
while s:
c,s=s;z="/"==gc;t+=z;g="\"!=gc
if t>2:
while m in(s:="".join(s))>"":s=s.replace(m,r,1)
r=m="";t=0
elif z<g:m+=t%2
c;r+=t//2*c;t<1==print(end=c)

#

ya i think it's fixed now

fleet lintel
#

I think I get it, the \ is handled by the z<g being false, right?

subtle viper
#

yup