#esoteric-python

1 messages Β· Page 40 of 1

magic wraith
#

huh

#

Try it out now using the Black Playground.

torn cypress
#

also like... as if formatting this would make it any better, lmao

magic wraith
#

idk since highlighting gave up on that code

serene coral
#

Python bot doesn't evaluate due to user inputs

arctic skiff
#

ok but what does this thing do?

serene coral
#

It's a question I had to do for school, where we take user input and form a matrix and perform operations on them

#

You can run it and try it out

sick hound
#

what language does linux/ubuntu use

serene coral
#

Enter the numbers of the matrix seperated by a space, its a 2x2 matrix

arctic skiff
#
while 1:(s:=str,r:=range,_:=s.join,print((lambda c,d:((d.update({'m1':[],'m2':[],'+':[[],[]],'-':[[],[]]})),[(d['m1'].append([int(i)for i in list(input(f"m1 line {i}:").replace(" ",''))]))for i in r(2)],[(d['m2'].append([int(i)for i in list(input(f"m2 line {i}:").replace(" ",''))]))for i in r(2)],([d['+'][i].extend([j+d['m2'][i][0],k+d['m2'][i][1]])for i,(j,k)in enumerate(d['m1'])]),([d['-'][i].extend([abs(j-d['m2'][i][0]),abs(k-d['m2'][i][1])])for i,(j,k)in enumerate(d['m1'])]),(_(_(_(_("Sum:\n"+" ",[s(i) for i in d['+'][0]])+'\n'+" ",[s(i) for i in d['+'][1]])+'\n' + 'Difference:\n'+" ",[s(i) for i in d['-'][0]])+"\n"+" ",[s(i)for i in d['-'][1]])))if c=='a'else(((d.update({'tm':[]})),[(d['tm'].append([int(i)for i in list(input(f"line {i}:").replace(" ",''))]))for i in r(2)],(d.update({'tf':[[d['tm'][j][i]for j in r(2)] for i in r(2)]})),(_(_(_(_("Original:\n"+" ",[s(i) for i in d['tm'][0]])+'\n'+" ",[s(i)for i in d['tm'][1]])+'\n'+'Transpose:\n'+" ",[s(i)for i in d['tf'][0]])+"\n"+" ",[s(i)for i in d['tf'][1]])))if c=='b'else(quit()if c=='q'else(None,'Invalid Input'))))(c=input("Enter Choice:\n(A)For Sum and Difference\n(B)For Transpose\n(Q)To Quit\n>>>").lower()[0],d={})[-1]))[:]
fleet bridge
arctic skiff
sick hound
#

I mean the Ubuntu Operating System and I mean like which computer language was it originally programmed by

sick hound
fleet bridge
#

most of the kernel is written in C
but there are a lot of other languages used in different parts of OS

sick hound
#

oh

#

k thanks bye

grave grail
#

Without execute the code, get the answer of the following code

class Base:
    def __repr__(self):
        return ''


class qmure(Base):
    def __repr__(self):
        return 'M' + super().__repr__()


class ko0r3(Base):
    def __repr__(self):
        return 'S' + super().__repr__()


class cumv6(Base):
    def __repr__(self):
        return 'E' + super().__repr__()


class stumv(cumv6):
    def __repr__(self):
        return 'A' + super().__repr__()


class rstuo(ko0r3):
    def __repr__(self):
        return 'I' + super().__repr__()


class umvs1(cumv6):
    def __repr__(self):
        return 'K' + super().__repr__()


class simpt(stumv, umvs1):
    def __repr__(self):
        return 'T' + super().__repr__()


class result(qmure, rstuo, simpt):
    pass


print(result())

(Basic level MRO, Question 1: Beginner level)

#

Please use spoiler to say the answer

#

lol

fleet bridge
#

||MISTAEK||

grave grail
#

nope

#

the concept, if the 2 parent of the class have the same parent, it should execute after both parent execute

fleet bridge
#

ah, im dumb
i confused the order at the end

grave grail
#

oh lol

fleet bridge
#

here is an inheritance tree: || ```py
Base
M
result
S
I
result
E
A
T
result
K
T
result

grave grail
#

mhh, make you should make result on top

#

this look more confusing lol

#

||```
result
M
Base
I
S
Base
T
A
E
Base
K
E
Base

grave grail
#

thx lol

fleet bridge
#
    object
        BaseException
            BaseExceptionGroup
                ExceptionGroup(BaseExceptionGroup, Exception)
            Exception
                ArithmeticError
                    FloatingPointError
                    OverflowError
                    ZeroDivisionError
                AssertionError
                AttributeError
                BufferError
                EOFError
                ImportError
                    ModuleNotFoundError
                LookupError
                    IndexError
                    KeyError
                MemoryError
                NameError
                    UnboundLocalError
                OSError
                    *snip* (there was too many to fit in one message)
                ReferenceError
                RuntimeError
                    NotImplementedError
                    RecursionError
                StopAsyncIteration
                StopIteration
                SyntaxError
                    IndentationError
                        TabError
                SystemError
                TypeError
                ValueError
                    UnicodeError
                        UnicodeDecodeError
                        UnicodeEncodeError
                        UnicodeTranslateError
                Warning
                    BytesWarning
                    DeprecationWarning
                    EncodingWarning
                    FutureWarning
                    ImportWarning
                    PendingDeprecationWarning
                    ResourceWarning
                    RuntimeWarning
                    SyntaxWarning
                    UnicodeWarning
                    UserWarning
            GeneratorExit
            KeyboardInterrupt
            SystemExit
grave grail
#

lmao lol

fleet bridge
#

this is the output from help(__builtins__)
it places base classes near the root, and subclasses are leafs

grave grail
#

ok lol

grave grail
#

Can you spoiler itπŸ’€

grave grail
# fleet lintel

It is like literally telling the answer if you spend 3 more second reading the code

#

πŸ’€

grave grail
#

It suppose to test you, not the machine

grave grail
#

I just realize probably my phone being weird on not spoiler it

fleet lintel
#

Yeh. I mean I made it manually, so I don't understand "test you, not the machine"

grave grail
#

oh ok, thought it was some IDE feature

#

lol

fleet lintel
#

Nope, I used app.diagrams.net

grave grail
#

nice lol

#

then ignore both of the thing I say

#

my bad

grave grail
#

MRO level 2

night quarryBOT
#

:incoming_envelope: :ok_hand: applied timeout to @grave grail until <t:1708552339:f> (10 minutes) (reason: newlines spam - sent 104 newlines).

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

vivid rock
#

!untimeout 692957118592057386

night quarryBOT
#

:incoming_envelope: :ok_hand: pardoned infraction timeout for @grave grail.

grave grail
#

I should have make a paste

#

thx πŸ™‚

#

Also remember to add spoiler to any form of answer

#

lol

grave grail
#

you can also validate your answer by adding /answer/ then the answer to the url even tho you can just run it anyway

#

like this

fleet lintel
grave grail
#

Lmao, you actually took to effort the make the graph

#

lol

#

And also correct

fleet lintel
#

It wasn't took bad, there is almost a 1-1 mapping between the mermaid syntax and a python class statement, so it was just find and replace.

grave grail
#

Well lol

#

Also impressive on how you use graph to solve the question

fleet lintel
#

It makes the MRO rules really clear, at least to me

grave grail
#

Yeah

#

||It might be better if I have more stuff point to n, Base instead of just Base||

serene coral
#

Guys is there a way to make entire classes within one line?

night quarryBOT
#

class type(object)``````py

class type(name, bases, dict, **kwds)```
With one argument, return the type of an *object*. The return value is a type object and generally the same object as returned by [`object.__class__`](https://docs.python.org/3/library/stdtypes.html#instance.__class__).

The [`isinstance()`](https://docs.python.org/3/library/functions.html#isinstance) built-in function is recommended for testing the type of an object, because it takes subclasses into account.
serene coral
#

Oh nvm type exists

#

Oh nvm type exists

arctic skiff
fleet bridge
night quarryBOT
#
I don't think so.

No documentation found for the requested symbol.

fleet bridge
#

where is it

#

!d types.new_class

night quarryBOT
#

types.new_class(name, bases=(), kwds=None, exec_body=None)```
Creates a class object dynamically using the appropriate metaclass.

The first three arguments are the components that make up a class definition header: the class name, the base classes (in order), the keyword arguments (such as `metaclass`).

The *exec\_body* argument is a callback that is used to populate the freshly created class namespace. It should accept the class namespace as its sole argument and update the namespace directly with the class contents. If no callback is provided, it has the same effect as passing in `lambda ns: None`.

New in version 3.3.
serene coral
#

Would you guys like to see me make a procedural terrain generator in one line?

grave grail
fleet lintel
grave grail
#

lmao lol

#

How long does it took you

#

This took me 16mins to make it but I don't know the answer without running it + some trial and error to make it work

#

lol

fleet lintel
#

VSCode highlighting all of the same letter when my cursor was on it made sure I didn't make any mistakes.

grave grail
#

nice lol

radiant anchor
#

What's the shortest expression you can come up with that evaluate to a recursive object? (of any type)

Best I have so far is (n:=[],n.append(n))

radiant anchor
#

that evaluates to None

torn cypress
radiant anchor
#

right, but it's still a recursive object

#

as a whole

torn cypress
#

mmm, I disagree, if you did sth like (n:=[],n.append(n))[0], then that'd be a recursive object

radiant anchor
#

well, my definition of the problem statement doesn't require the outer layer(s) to be part of the recursion

torn cypress
#

alright

fleet bridge
#

!e this is classic ```py
a=a[0]=[0]
print(a)

night quarryBOT
#

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

[[...]]
torn cypress
#

yeah, but that's no fun

#

why can't walrus just be more like =

fleet bridge
#

i dont think you can make it any shorter

#

0 is recursive, because it contains reference to int, which contains reference to type, which contains reference to itself

torn cypress
#

lmao

radiant anchor
#

HMMMMM I guess lol

torn cypress
#

fits the definition

radiant anchor
radiant anchor
fleet bridge
#

if we dont allow objects that are not a part of reference cycle, then i guess the shortest one is type

#

x:=globals() fits all requirements

  • it has ... in the repr
  • it references itself directly
#
>>> (x:=globals())
{   '__name__': '__main__',
    '__doc__': None,
    '__package__': None,
    '__loader__': _frozen_importlib.BuiltinImporter,
    '__spec__': None,
    '__annotations__': {},
    '__builtins__': builtins,
    'x': {...}}
#

it is 12 or 14 chars (depending on if you count parens)

torn cypress
#

x:=locals() also fits and is shorter

fleet bridge
#

i am a locals() hater

torn cypress
#

lol

fleet bridge
#

what is the shortest code that makes an object that is an instance of itself?

#

statements are allowed

fleet bridge
#

bruh

#

not counting this one

#

the goal is to make the same loop in pure python

torn cypress
#

that looks like pure Python to me

fleet bridge
#

||object|| technically also is an instance of itself

fleet bridge
torn cypress
#

Python is implemented in C

#

but oh well, I get your point, lol

fleet lintel
torn cypress
#

just

assert isinstance(obj, obj)
assert isinstance(obj(), obj)

?

#

do we also check this

assert obj() is not obj()
fleet lintel
#

So far, my "solution" still checks all of these boxes.

#

Slight optimization ||py class X(type):__instancecheck__=slice class x(metaclass=X):1||

torn cypress
#

alr, here's mine
||

class M(type):
 __instancecheck__=lambda*a:1
class T(metaclass=M):0

||

obj = T

assert isinstance(obj, obj)
assert isinstance(obj(), obj)
assert obj() is not obj()
torn cypress
fleet lintel
torn cypress
#

me neither

fleet lintel
# torn cypress me neither

I think this might be CPython specific. If it was implemented in just python, I don't think it would work. I also dont understand why cpython does it how it does, but it do. ||c PyObject *checker = _PyObject_LookupSpecial(cls, &_Py_ID(__instancecheck__)); ... PyObject *res = PyObject_CallOneArg(checker, inst);
It does a 1 arg call, so a 1 arg function works 🀷. I guess it's whatever is magic about _PyObject_LookupSpecial.||

proper vault
#

builtin functions aren't descriptors, so they don't bind self, if that's the point of confusion

grave grail
#

Bruh, why are we going through C now lol

torn cypress
proper vault
#

yes, all python defined functions are descriptors

#

they have __get__

torn cypress
#

oh

proper vault
#

!e

def foo(one): print(one)
foo.__get__(1)()
night quarryBOT
#

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

1
fleet bridge
torn cypress
night quarryBOT
#

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

False
fleet bridge
#

!e my way of doing it```py
class M(type):0
class X(M,metaclass=M):0
X.class=X

assert isinstance(X, X)
assert type(X) is X

night quarryBOT
#

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

[No output]
torn cypress
#

mmm

#

well, was a fun challenge, I don't think it's getting any shorter than this

fleet bridge
#

for style points, you can also make X.__new__ return X, so X() is X is type(X) will be true

fleet lintel
#

I suppose that means that you don't need functools.partial to partial almost any function, as long as it isn't builtin/constructed weirdly.

fleet bridge
fleet bridge
fleet lintel
#

:). Sadly only for one though, since after one __get__ it becomes a method, not a function.

torn cypress
#

this is hilarious

#

this obscure stuff is what I learn from here, pretty cool

fleet bridge
#
>>> m = f.__get__(1)
>>> m.__get__ # attribute access is forwarded to underlying function
f.__get__

>>> f.__get__?
Help on method-wrapper:

__get__(instance, owner=None, /)
    Return an attribute of instance, which is of type owner.

>>> f.__get__(1,int)
<bound method f of 1>
>>> f.__get__(1,str) # no checks
<bound method f of 1>
>>> f.__get__(None,...) # literally no checks
f
>>> f.__get__(1,2) # second arg is discarded completely
<bound method f of 1>
>>> f.__get__(1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError:  expected at most 2 arguments, got 3
#
>>> f.__get__(None,...)
f
>>> f.__get__(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __get__(None, None) is invalid
``` i just noticed that you cant bind `None` using that approach
#

does it mean that NoneType cant have working pure-python methods? πŸ€”

#
import fishhook

@fishhook.hook(str)
@fishhook.hook(type(None))
def foo(self, *a):
    print(f'{self!r}.foo(*{a}) was called')
``` ```py
# works fine for strings:
>>> ''.foo
<bound method foo of ''>
>>> ''.foo()
''.foo(*()) was called

# this is weird:
>>> None.foo
foo
# this is ok:
>>> None.foo()
None.foo(*()) was called
# but if we call it in other way, then it breaks:
>>> x = None.foo; x()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() missing 1 required positional argument: 'self'
#
>>> dis('None.foo()')
  0           0 RESUME                   0

  1           2 LOAD_CONST               0 (None)
              4 LOAD_ATTR                1 (NULL|self + foo)
             24 CALL                     0
             32 RETURN_VALUE
``` this must be happening because of optimizations on bytecode level
unique heath
#

whats up

fleet bridge
#

LOAD_ATTR(namei)
If the low bit of namei is not set, this replaces STACK[-1] with getattr(STACK[-1], co_names[namei>>1]).

If the low bit of namei is set, this will attempt to load a method named co_names[namei>>1] from the STACK[-1] object. STACK[-1] is popped. This bytecode distinguishes two cases: if STACK[-1] has a method with the correct name, the bytecode pushes the unbound method and STACK[-1]. STACK[-1] will be used as the first argument (self) by CALL when calling the unbound method. Otherwise, NULL and the object returned by the attribute lookup are pushed.

Changed in version 3.12: If the low bit of namei is set, then a NULL or self is pushed to the stack before the attribute or unbound method respectively.

fleet bridge
#

i believe in None.foo case descriptor protocol failed to execute, so normal lookup was peroformed, so foo was returned

unique heath
#

!e

print(dis.dis("x = None.foo; x()"))```
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     print(dis.dis("x = None.foo; x()"))
004 |           ^^^
005 | NameError: name 'dis' is not defined. Did you mean: 'dir'? Or did you forget to import 'dis'?
unique heath
#

!e

import dis
print(dis.dis("x = None.foo; x()"))```
night quarryBOT
#

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

001 |   0           0 RESUME                   0
002 | 
003 |   1           2 LOAD_CONST               0 (None)
004 |               4 LOAD_ATTR                0 (foo)
005 |              24 STORE_NAME               1 (x)
006 |              26 PUSH_NULL
007 |              28 LOAD_NAME                1 (x)
008 |              30 CALL                     0
009 |              38 POP_TOP
010 |              40 RETURN_CONST             0 (None)
011 | None
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/5HNCCGESB3NEQJHAETNL6PY27Q

unique heath
#

ah yeah probably

earnest wing
#

that's how my custom-literals library works

quartz wave
# fleet bridge > LOAD_ATTR(namei) > If the low bit of namei is not set, this replaces STACK[-1]...

STACK[-1] has a method with the correct name...
if object STACK[-1] has an attribute with a name that matches that method, that is

>>> dis("a.foo()") # different LOAD_ATTR argument opcode because `a` and `foo` are both part of `.co_names`, but they're relatively the same
  0           0 RESUME                   0

  1           2 LOAD_NAME                0 (a)
              4 LOAD_ATTR                3 (NULL|self + foo)
             24 CALL                     0
             32 RETURN_VALUE
>>> dis("None.foo()")
  0           0 RESUME                   0

  1           2 LOAD_CONST               0 (None)
              4 LOAD_ATTR                1 (NULL|self + foo)
             24 CALL                     0
             32 RETURN_VALUE
arctic skiff
#

.topic I wonder what topics it will have for here

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

Suggest more topics here!

arctic skiff
#

this one is actually nice

arctic skiff
gleaming timber
#
is_odd=lambda _:bool(_&1)
earnest wing
#

is_odd=1 .__and__

arctic skiff
quartz wave
quartz wave
#

.topic

glass drumBOT
#
**What's the weirdest language feature that Python doesn't have, and how can we change that?**

Suggest more topics here!

arctic skiff
fleet bridge
#

imagine @return decorator: ```py
def deco(f):
@return
def wrapper(*args, **kwargs):
...
res = f(*args, **kwargs)
...
return res

torn cypress
# glass drum

Ruby's unless
well, we could just raise a PEP and hope it gets accepted...

torn cypress
#

no no

#
    raise Exception 
unless everything_is_fine:

or

    print("hello world")
    print("the quick brown fox jumps over the fence")
unless not True:
quartz wave
#

is that a reverse statement

torn cypress
#

maybe, idk, apparently Ruby has this

#

well, not exactly this syntax ig, but close enough

quartz wave
torn cypress
#

yeah

sturdy rune
# glass drum

Being able to treat strings as variables or executable code blocks without having to resort to eval or ast.literal. I find this really handy. But, I don't think there could be changes in Python to do that.

quartz wave
#

eval() is already the most compact way to do that

sturdy rune
#

Yeah, but I mean it in built-in matter. No eval needed. I'll show example in a few.

quartz wave
#

what could be the worst thing that could happen

arctic skiff
# glass drum

JSFuck, not sort of a feature but can be considered

sturdy rune
#

In Python, you have to use eval or ast.literal to do that. There's also being able to execute a command there and the string is treated as a call to a command.

fleet bridge
#

i dont understand your example

#

just do a,b,c,d,e=1,2,3,4,5

quartz wave
sturdy rune
fleet bridge
#

objects dont have any idea about variables they are stored in

quartz wave
quartz wave
sturdy rune
#

but back to Python anyway

open pulsar
#

czy ktos z tad jest w stanie wyslac kod do jakiejs gry w pythonie? mega potrzebuje z gory dzieki

sturdy rune
#

i don't know what language is this

open pulsar
#

polish

fleet bridge
open pulsar
#

whats the channel i can ask for it?

sturdy rune
#

you can search for github to find existing Python game code

open pulsar
#

thanks

fleet bridge
#

@open pulsar ```py
from pygame import*
init()
d=display
c=draw.rect
x=t=l=j=0
while not event.get(256):
s=d.set_mode((500,300));k=key.get_pressed()
if l:
if t%66<1:o+=[m:=Rect(550,p.y%9*-25,50,200),m.move(0,300)]
j=[j+1,-8][k[32]];p.y+=min(j,9);c(s,-1,p);t+=1;l=p.collidelist(o+[(0,0,70,300)])==len(o);x=t
for a in o:a.x-=3;c(s,-1,a)
else:s.blit(Font().render(str(x),0,"red"),p:=Rect(40,90,10,10));o=[];t=l=k[13]
d.flip();time.wait(33)

#

(not my code)

torn cypress
#

I have seen this somehwere

#

(speaking of recent events on reddit, there's an exe file pg_rofl)

versed eagle
torn cypress
#

how would you use break and continue as expressions? like in list comps or sth?

#

speaking of break, if we could have named loops and break out of one by that assigned name (I think Rust has sth like this), that'd be great as well

versed eagle
torn cypress
#

interesting idea

versed eagle
torn cypress
#

funny thing, this is how you could do it using the C API return RAISE(PyExc_TypeError, "foobar is unable to be frobnicated");

sick hound
#

Hello
Idont have the mic permissions

torn cypress
#

!voice

night quarryBOT
#
Voice verification

Can’t talk in voice chat? Check out #voice-verification to get access. The criteria for verifying are specified there.

versed eagle
#
class a:
    def __add__ (self, other):
        raise TypeError()
a() + a()
# Traceback (most recent call last):
#  File "somefile", line lineno, in <somemodule>
#  File "somefile", line lineno, in __add__
# TypeError

as opposed to

1 + ""
# Traceback (most recent call last):
#  File "somefile", line lineno, in <somemodule>
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
#

the error message for the first one includes the function in the traceback, and for complicated code it can be several layers deep before the error checking happens

#

it would be nice if the callsite could be the top of the traceback

torn cypress
#

you can do that now using other stuffs

versed eagle
torn cypress
#

perhaps perhaps

versed eagle
quartz wave
#

PyErr_Format() returns NULL which means it can be used with return, but PyErr_SetString() (most likely to be used here) does not return anything

#

and i don't know how returning a void would make sense

torn cypress
quartz wave
#

very convenient

#

any macro from the C API starts with Py*

torn cypress
#

right, makes sense, welp

quartz wave
#

or follows the general format of PySpecifier_SCREAMING_SNAKE_CASE_NAME

torn cypress
#

in fairness, it will most certainly exit the loop
by means of a NameError, but if it works, it works πŸ€·β€β™‚οΈ /s

fleet bridge
torn cypress
#

that's... obscure

#

but actually, going back a frame would be pretty neat so that it doesn't show the raise line (is there like a super simple solution to that rn? ik you can do sth, sth around excepthooks and such, but like, I have to configure that and such)

fleet bridge
#

you can manually construct the exception object with proper traceback and stuff, and then raise it
(and hope that its traceback remains untouched)

#

i believe it can be boiled down to raise f(MyException(blah, blah), 1)
f takes an exception you wanna raise, mutates its traceback removing specified amount of frames from it, and returns it

torn cypress
#

ooh, neat

versed eagle
#

but it wouldnt mesh with the modern raise exc from otherexc thing (which imo really shouldnt have become a thing in the first place but whatever)

quartz wave
torn cypress
#

time for a PEP 😁

digital mesa
#

ok wait...

grave grail
#

Hi, I had a a esoteric number generator

digital mesa
#
(1).__lshift__(1).__lshift__(1).__add__(1).__pow__(((1).__lshift__(1).__mul__((1).__lshift__(1).__add__(1))).__mul__((1).__add__((1).__lshift__(1).__add__(1).__pow__((1).__lshift__(1))).__pow__((1).__lshift__(1))).__sub__((1).__lshift__(1).__lshift__(1).__add__(1).__pow__((1).__lshift__(1)).__add__((1).__lshift__(1).__lshift__(1).__lshift__(1).__sub__(1).__pow__((1).__lshift__(1).__add__(1))))
#

I think I was dumb-dumb-stupid-head when I made that comment in pydiscussion

#

you can only do what I said for literally the first (1)

#

oh wait πŸ€”

grave grail
#

lol

digital mesa
#

I see now that you have some nesting

grave grail
#

*my code done some nesting

#

anyway, give me another number

digital mesa
#

is there a parenthesis mismatch?

#

yeah there is

grave grail
#

I doubt

#

wait what?

digital mesa
grave grail
#

oh yeah

#

found it

#

on preset on number 6

#

I forgot to remove the bracket at the front when copying

digital mesa
#

please send updated expression

grave grail
#
(1).__lshift__(1).__lshift__(1).__add__(1).__pow__((1).__lshift__(1).__mul__((1).__lshift__(1).__add__(1))).__mul__((1).__add__((1).__lshift__(1).__add__(1).__pow__((1).__lshift__(1))).__pow__((1).__lshift__(1))).__sub__((1).__lshift__(1).__lshift__(1).__add__(1).__pow__((1).__lshift__(1)).__add__((1).__lshift__(1).__lshift__(1).__lshift__(1).__sub__(1).__pow__((1).__lshift__(1).__add__(1))))
#

Was re-generating

#

lol

digital mesa
#
(1
.__lshift__(1)
.__lshift__(1)
.__add__(1)
.__pow__(1
    .__lshift__(1)
    .__mul__(1
        .__lshift__(1)
        .__add__(1)))
.__mul__(1
    .__add__(1
        .__lshift__(1)
        .__add__(1)
        .__pow__(1
            .__lshift__(1)))
    .__pow__(1
        .__lshift__(1)))
.__sub__(1
    .__lshift__(1)
    .__lshift__(1)
    .__add__(1)
    .__pow__(1
        .__lshift__(1))
    .__add__(1
        .__lshift__(1)
        .__lshift__(1)
        .__lshift__(1)
        .__sub__(1)
        .__pow__(1
            .__lshift__(1)
            .__add__(1)))))
grave grail
#
1.__add__(1)
  Cell In[11], line 1
    1.__add__(1)
     ^
SyntaxError: invalid decimal literal
#

umm, I doubt that would work

digital mesa
#

you need to put a space, as I said earlier in pydiscussion

#

well I didn't say it, but I wrote code like that ig

#

fairnuff

grave grail
#

oh ok, it is simple then

digital mesa
grave grail
#
1 .__lshift__(1).__lshift__(1).__add__(1).__pow__(1 .__lshift__(1).__mul__(1 .__lshift__(1).__add__(1))).__mul__(1 .__add__((1).__lshift__(1).__add__(1).__pow__(1 .__lshift__(1))).__pow__(1 .__lshift__(1))).__sub__(1 .__lshift__(1).__lshift__(1).__add__(1).__pow__(1 .__lshift__(1)).__add__(1 .__lshift__(1).__lshift__(1).__lshift__(1).__sub__(1).__pow__(1 .__lshift__(1).__add__(1))))
digital mesa
#

!e

print(                  (1
.__lshift__             (1)
.__lshift__             (1)
.__add__                (1)
.__pow__                (1
    .__lshift__         (1)
    .__mul__            (1
        .__lshift__     (1)
        .__add__        (1)))
.__mul__                (1
    .__add__            (1
        .__lshift__     (1)
        .__add__        (1)
        .__pow__        (1
            .__lshift__ (1)))
    .__pow__            (1
        .__lshift__     (1)))
.__sub__                (1
    .__lshift__         (1)
    .__lshift__         (1)
    .__add__            (1)
    .__pow__            (1
        .__lshift__     (1))
    .__add__            (1
        .__lshift__     (1)
        .__lshift__     (1)
        .__lshift__     (1)
        .__sub__        (1)
        .__pow__        (1
            .__lshift__ (1)
            .__add__    (1))))))
night quarryBOT
#

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

1562132
grave grail
#

lmao lol

digital mesa
#

time to make it even better

grave grail
#

Ok lol

#

Let me upload my code to gist first

digital mesa
#
(     print(    (1
.   __lshift__  (1)
.   __lshift__  (1)
.   __add__     (1)
.   __pow__     (1
.   __lshift__  (1)
.   __mul__     (1
.   __lshift__  (1)
.   __add__     (1) )   )
.   __mul__     (1
.   __add__     (1
.   __lshift__  (1)
.   __add__     (1)
.   __pow__     (1
.   __lshift__  (1) )   )
.   __pow__     (1
.   __lshift__  (1) )   )
.   __sub__     (1
.   __lshift__  (1)
.   __lshift__  (1)
.   __add__     (1)
.   __pow__     (1
.   __lshift__  (1) )
.   __add__     (1
.   __lshift__  (1)
.   __lshift__  (1)
.   __lshift__  (1)
.   __sub__     (1)
.   __pow__     (1
.   __lshift__  (1)
.   __add__     (1) )   )   )   )   )   )
grave grail
#

🀣

digital mesa
#

t a b u l a r

grave grail
digital mesa
#

ok now I'm bored bye

grave grail
#

Ok lol

digital mesa
#

wait for a nested while loop break

#

put it in a function and use return

grave grail
#

gonna to

#

Done

fleet bridge
#
def f(a,b):
    # this code is executed when the function is running:
    print(a, b, a + b)
    return a + b
else:
    # this code is executed when the function is not running:
    print('f() is not running :-(')
#
print(f(1,2))
``` expected output: ```py
f() is not running :-(
f() is not running :-(
f() is not running :-(
f() is not running :-(
*snip*
f() is not running :-(
f() is not running :-(
f() is not running :-(
1 2 3
3
f() is not running :-(
f() is not running :-(
f() is not running :-(
...
versed eagle
#
def f ():
    ...
else:
    f()
#

while True: loop

#

:3

fleet bridge
#

asynchronous while True loop!

#
def f():
    print('foo')
else:
    f()

def g():
    print('bar')
else:
    g()
``` this will print a lot of foos and bars
#

simultaneously

versed eagle
#

that would be an error of some sort

#

unless the functions are declared with async def

#

hm

#

what are the semantics of this?

def f ():
    def g ():
        ...
    else:
        ...
else:
    ...
f()
#

and what about this

def f ():
    def g ():
        ...
    else:
        ...
    return g
else:
    ...
a = f()
#

do the else blocks live for the objects whole lifetime, or just until the definition goes out of scope?

#

&& is there a specified order for when else blocks execute (maybe from innermost scope outwards, in order or definition in case of a tie?)

solid lichenBOT
#
Command not found

Command "&" is not found

versed eagle
#

an interesting thing to do would be to have functions which dont execute a return just continue execution at the point after the definition, a la old C

e.g.,

_ = 0
def a ():
    global _
    _ = 1
    print("a")
print("here")
if 1-_: # so it doesnt loop forever
    a()

prints

here
a
here
grave grail
#

I gone insane on my esoteric number generator and type a random large number

#

and then I got this

((((1<<1<<1<<1)-1)*((((1+(1+((1+(1<<1))**(1<<1))))*(((1<<1<<1)+1)+(1+((1+(1<<1))**(1<<1)))))<<1)+((((1+(1<<1))**(1<<1))+(1+((1+(1<<1))**(1<<1))))**(1<<1))))+(((((1<<1)*(((1+(1<<1))+(1+((1+(1<<1))**(1<<1))))**(1<<1)))+((((1+(1<<1))**(1<<1))+(1+((1+(1<<1))**(1<<1))))*((1+((1+(1<<1))**(1<<1)))+(1+((1+(1<<1))**(1<<1))))))**(1<<1))*((((1+(1<<1))+(1+((1+(1<<1))**(1<<1))))*((1<<1<<1<<1)+(1+((1+(1<<1))**(1<<1)))))+((1+(1+((1+(1<<1))**(1<<1))))*(((1<<1)*((1<<1)+1))**(1<<1))))))
fleet bridge
#

using numbers to make numbers feels like cheating

#

consider replacing 1 with (()==())

torn cypress
#

what about using True

fleet bridge
#

True is an integer

grave grail
#

0==0 -> 1

#

1 -> 1

#

n//n -> 1

#

amd it is up to you on how you replacing it

#

lol

arctic skiff
grave grail
#

and, I make a way to make you customize how you represent 1

#

just, it have no validation

arctic skiff
grave grail
#

give me a relatively large number

arctic skiff
grave grail
#

too large πŸ’€

arctic skiff
#

798788454649646354563

#

forgot it

#

use 5 tetration 5

grave grail
#

you know it use bruteforce right lol

arctic skiff
#

basically 5**5**5**5**5**5

grave grail
#

my computer is having fun calculating that

arctic skiff
grave grail
#

yeah nah no way

#

I have to type the numeric value for it

arctic skiff
grave grail
#

jk it won't be what you want to be

arctic skiff
grave grail
#

I only allow it do do to the power of 10

earnest wing
arctic skiff
#

oh wait

#

yeah

#

I didn't realize

grave grail
#

Oh lol

#

I was like why it's so different

earnest wing
#

🀯

grave grail
#

so (5**5)**5?

grave grail
#

By change some settings

#

Jk I just crashed PyCharm so relaunching

grave grail
#

Even my system monitor with trustinstaller perm get terminated

#

anyway

(((~~(([])>([]))^(()==()))>>(~~(([])>([]))^(()==())))+(((((~~(([])>([]))^(()==()))<<(~~(([])>([]))^(()==()))<<(~~(([])>([]))^(()==())))+(~~(([])>([]))^(()==())))**(((~~(([])>([]))^(()==()))+(((~~(([])>([]))^(()==()))+((~~(([])>([]))^(()==()))<<(~~(([])>([]))^(()==()))))**((~~(([])>([]))^(()==()))<<(~~(([])>([]))^(()==())))))+((~~(([])>([]))^(()==()))+(((~~(([])>([]))^(()==()))+((~~(([])>([]))^(()==()))<<(~~(([])>([]))^(()==()))))**((~~(([])>([]))^(()==()))<<(~~(([])>([]))^(()==())))))))*((((~~(([])>([]))^(()==()))<<(~~(([])>([]))^(()==()))<<(~~(([])>([]))^(()==())))+(~~(([])>([]))^(()==())))**(((~~(([])>([]))^(()==()))<<(~~(([])>([]))^(()==()))<<(~~(([])>([]))^(()==())))+(~~(([])>([]))^(()==()))))))

for (5**5)**5

#

and you 2 disappear

#

lol

grave grail
#

400=

((((~~(([])>([]))^(()>=()))+(((~~(([])>([]))^(()>=()))+((~~(([])>([]))^(()>=()))<<(~~(([])>([]))^(()>=()))))**((~~(([])>([]))^(()>=()))<<(~~(([])>([]))^(()>=())))))+((~~(([])>([]))^(()>=()))+(((~~(([])>([]))^(()>=()))+((~~(([])>([]))^(()>=()))<<(~~(([])>([]))^(()>=()))))**((~~(([])>([]))^(()>=()))<<(~~(([])>([]))^(()>=()))))))**((~~(([])>([]))^(()>=()))<<(~~(([])>([]))^(()>=()))))
torn cypress
fleet bridge
#
  • () is not an integer, it is a tuple
  • == is not an integer, it is an operator
  • () is a tuple too
#

you are mistaken

torn cypress
#

True is a boolean value

#

I said "as much an integer as" because in this context, evalutation both True and ()==() would yield an integer, well, ig, the latter is gonna yield a boolean first, but like... why does it have to be 2 layers of abstraction and why is 1 not enough sobbing

grave grail
#

also ability to represent an integer with only syntax is funny

#

-~(()<())

#

better

#

look at this amazing thing

#

lol

#

just don't work on chaining

grave grail
#

How to get globals (globals dict) with just 0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_{|}~ `

digital mesa
#

can other non-letter characters be used?

grave grail
#

yeah

digital mesa
#

although you did say syntax and numbers

grave grail
#

I just pick printable and remove the \t, \r...

digital mesa
#

ok

grave grail
#

since it would be annoying to find else

#

but any non-letter is allowed

digital mesa
#

let's discuss all the possible values you could get out of say two characters of that set (or more, if you can describe it well)

grave grail
#

_0

digital mesa
#

of course you can have any integer or float

grave grail
#

yes

digital mesa
#

also any string containing those characters

grave grail
#

yeah

#

'0.0' count

digital mesa
#

list, tuple, set, dict, containing any valid value

grave grail
#

yes

digital mesa
#

I think that's gotta be all

grave grail
#

yeah, and you cannot use dunder since it is character

#

I thought of that and realize it don't work

digital mesa
#

any operator used on numbers or string is gonna give you bool, number or string

grave grail
#

I mean, we could also try to get exec or eval

#

but the diffculty is probably the same

digital mesa
#

we don't have a way to make arbitrary characters in a string, do we?

grave grail
#

oh wait yeah, we would need chr

#

oops, I realize to do what I want, we also need chr

#

since to get anything from globals we need the name

#

constructing a string with number would require chr

digital mesa
grave grail
#

what idea

digital mesa
#

!e

print([*globals()][0])
night quarryBOT
#

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

__name__
digital mesa
#

if you can get globals, then you can extract names positionally

#

because you can convert to list like that

grave grail
#

oh ok, then we can extract chr from there

digital mesa
#

because you can access everything by position

grave grail
#

ye fair

digital mesa
#

so yeah the aim is still to get globals

#

nothing with int dunder methods will help

grave grail
#

Yeah, dunder won't work

digital mesa
#

operators call dunders

#

is what I mean

#

there is no operation on int that will help get globals directly

grave grail
#

I don't know you can call dunder with operator

digital mesa
grave grail
digital mesa
#
1 + 2 == (1).__add__(2)
grave grail
#

Yeah, ik that

digital mesa
#

ok so what's the issue smh

#

OK

#

I had a really good idea

#

using % with strings

#

because that lets us use format codes

grave grail
#

But that won't be executable tho

digital mesa
#

?

grave grail
#

Like you cannot execute to get globals dict

digital mesa
#

the short-term idea here is to make an arbitrary string

#

because at least it's a fun mini-project

grave grail
#

Ok

digital mesa
#

!e print("%c" % 68)

night quarryBOT
#

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

D
digital mesa
#

if we can get the letter c then we can get any letter

grave grail
#

Mhh

digital mesa
#

ok I got bored

grave grail
#

Ok

fleet bridge
grave grail
#

???what python was that

torn cypress
#

since when is a question mark doing stuff in the repl?

grave grail
#

Or he just trolling

torn cypress
#

no, I saw it used the other day

grave grail
#

When did it even exist

grave grail
fleet bridge
#

you can read this message (and a little bit above about weird emojis)

torn cypress
#

scam

grave grail
#

Scamming

#

I cannot write a letter so I cannot define a function until I have access to globals()

#

And I probably still couldn't after I have

#

Haven't investiate that part

fleet bridge
#

i dont think this is possible

#

is there a way to get some alphabet characters as string values?
if so, and if only one exception to the rules is allowed: _=str.format, then i can perform attribute lookups and get results formatted to strings

#
>>> _=str.format
>>> _('{0.__class__.__base__}',())
'object'
>>> _('{0.__class__.__class__}',())
'type'
>>> _('{0.__class__.__dict__}',())
("{'__new__': tuple.__new__, '__repr__': tuple.__repr__, '__hash__': tuple.__hash__, '__getattribute__': "
 "tuple.__getattribute__, '__lt__': tuple.__lt__, '__le__': tuple.__le__, '__eq__': tuple.__eq__, '__ne__': "
 "tuple.__ne__, '__gt__': tuple.__gt__, '__ge__': tuple.__ge__, '__iter__': tuple.__iter__, '__len__': "
 "tuple.__len__, '__getitem__': tuple.__getitem__, '__add__': tuple.__add__, '__mul__': tuple.__mul__, '__rmul__': "
 "tuple.__rmul__, '__contains__': tuple.__contains__, '__getnewargs__': tuple.__getnewargs__, 'index': tuple.index, "
 '\'count\': tuple.count, \'__class_getitem__\': tuple.__class_getitem__, \'__doc__\': "Built-in immutable '
 'sequence.\\n\\nIf no argument is given, the constructor returns an empty tuple.\\nIf iterable is specified the '
 "tuple is initialized from iterable's items.\\n\\nIf the argument is a tuple, the return value is the same "
 'object.", \'__invert__\': <function sc._@__invert__ UnpackedArgs=<class \'sc._.<locals>.UnpackedArgs\'>>}')
grave grail
fleet bridge
#

you can get rid of c

#

just use ||oct escaped strings||

#
>>> code = 'print(123)'
>>> eval(eval('"'+''.join(f'\\{oct(ord(c))[2:]}' for c in code)+'"'))
123
>>> print('"'+''.join(f'\\{oct(ord(c))[2:]}' for c in code)+'"')
"\160\162\151\156\164\50\61\62\63\51"
# ^^^ this is code generation
# vvv this is what actually will be executed
>>> eval("\160\162\151\156\164\50\61\62\63\51")
123
grave grail
#

Ok

#

(but issue is I have to use syntax to represent the number

#

which still either require f-string or modula format

torn cypress
#

!e

a = 1 == 1.0 == True == bool(...) == type("", (), {"__eq__": bool})() == (not None) == all([]) == (() == ())
print(a)
night quarryBOT
#

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

True
torn cypress
#

not particularly esoteric, but...

#

missing (not any([]))

grave grail
#

I mean pretty more all of them are having 0-9a-zA-Z character

#

except last one

#

I mean using this btw

#

!e

print(-~(()<()))
night quarryBOT
#

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

001 | /home/main.py:1: DeprecationWarning: Bitwise inversion '~' on bool is deprecated. This returns the bitwise inversion of the underlying int object and is usually not what you expect from negating a bool. Use the 'not' operator for boolean negation or ~int(x) if you really want the bitwise inversion of the underlying int.
002 |   print(-~(()<()))
003 | 1
torn cypress
#

what I sent is completely unrelated

grave grail
#

oh lol

#

sorry

quartz wave
grave grail
#

why tho

#

you want to bypass depercation?

#

that I completely ignore

#

lol

quartz wave
#

(unlikely chance of removal)

grave grail
#

lol

#

The fact that they just deprecated on 3.12, I would believe it would only be removed like 3.14+, and it is just a small fun project that probably only last a few day

#

Would be funny decades later someone complain it doesn't work lol

bright valve
#

can someone make this shitcode even more shitcode

def floor(n: float) -> int:
    return int(str(n).split(".")[0])
#

has to be in 1 line no ;

bright valve
#

gore

quartz wave
bright valve
#

*_ huh?

quartz wave
bright valve
#

!e

a=lambda*_:print(_)
a()```
night quarryBOT
#

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

()
bright valve
#

!e

a=lambda *_:print(_)
a()```
#

tf

night quarryBOT
#

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

()
quartz wave
#

fun fact: removing n*0 will do the same thing

bright valve
#

nah ffs

#

how do you even learn to write that

quartz wave
#

let's say abouttt...

#

3 years of experience

bright valve
#

gotta learn how to code those

fluid juniper
#

it looks kind of dark magic to me

unreal echo
#

Same way how converting (int)double just discards the decimal component

#

-5.5 gets int-ed into -5 rather than -6

unreal echo
#

Bro wha6

#

Blud autogenerated that

grave grail
#

Yes

molten timber
#

Using strange Python to remove the nth element of a list with the .remove function.

my_list = [1, 2]*10
class RemoveObj():
    def __init__(self, x):
        self.x = x
    def __eq__(self, x):
        self.x -= 1
        return self.x < 0
my_list.remove(RemoveObj(15))

kinda cursed if you ask me

fluid juniper
#

no need to ask you, it is

quartz wave
#

why's the string split up

bright valve
#

eval("exev")(...) bruh

quartz wave
grave grail
#

It was used to prevent recurrsion error

#

When I throw a 7kb file to obfuscate

#

And when it run, it say recursion error on compilation

#

Which was fixed by bracket them reasonably so they ain't doing a single chain of process

#

In this size, it is not necessary but way too lazy to code it to handle differently

grave grail
#

So it make more sense to use eval instead of exec

grave grail
#

Nah

gleaming timber
#

upcoming french python```
dΓ©f fizzbuzz(n):
pour i en sΓ©rie(1, n+1):
si i % 15 == 0:
imprimer(Β«fizzbuzzΒ»)
sinonsi i % 5 == 0:
imprimer(Β«buzzΒ»)
sinonsi i % 3 == 0:
imprimer(Β«fizzΒ»)
sinon:
imprimer(i)

fizzbuzz(100)

grave stag
#

looks hilarious

night quarryBOT
#

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

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

grave grail
#

An incomplete version of the same tool is on my GitHub gist

#

Gl finding it

quartz wave
grave grail
#

lol

quartz wave
#

these parentheses are grouped in a particular order

grave grail
#

Because it's continuously group by 2

quartz wave
grave grail
#

Well, do anything without uploading it on my gist lol

quartz wave
grave grail
#

Yes

#

It should have been 128 from the code, but guess you accidentally ignored it

#

1: 1
2: 1+1
3: (1+1)+1
4: (1+1)+(1+1)
5: ((1+1)+(1+1))+1
6: ((1+1)+(1+1))+(1+1)
...

quartz wave
grave grail
#

is it?

quartz wave
#

yeah

grave grail
#

it shouldn't be checking from my code

unique heath
#

py.french

#

french subsystem for python

torn cypress
#

FSP? so like the opposite of PSF

unique heath
#

FSP FTW

#

well maybe not i wouldnt want to subject anyone except my worst enemy to that

quartz wave
# grave grail is it?

i managed to remake the logic but in a sloppy way that only equals when totally evaluated

#

do you have test inputs anywhere

grave grail
#

No

#

But you can pm me the code

fleet bridge
floral meteor
#

!e who still covers their numbers in brackets?

print(0 .__class__ is int)
print(0..__class__ is float)
night quarryBOT
#

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

001 | True
002 | True
floral meteor
#

!e or even worse, a dot with no purpose

print(
  69..__int__() is 69 .__int__()
)
night quarryBOT
#

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

True
floral meteor
#

!e is this... getting the right answer by threatening a list comprehension into submission?

fifteen ,= [0x00for hello in world]
print(fifteen)
night quarryBOT
#

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

001 | /home/main.py:1: SyntaxWarning: invalid hexadecimal literal
002 |   fifteen ,= [0x00for hello in world]
003 | 15
floral meteor
#

oh come on is this warning a new thing?

#

3.10 onwards is starting to look like a killjoy

fleet bridge
#
C:\Users\denba>py -3.10 -c "fifteen ,= [0x00for hello in world]"

C:\Users\denba>py -3.11 -c "fifteen ,= [0x00for hello in world]"
<string>:1: SyntaxWarning: invalid hexadecimal literal

C:\Users\denba>py -3.12 -c "fifteen ,= [0x00for hello in world]"
<string>:1: SyntaxWarning: invalid hexadecimal literal
unique heath
#

cursed

#

!e

fifteen ,= [0x00for hello in world]
print(fifteen)```
night quarryBOT
#

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

001 | /home/main.py:1: SyntaxWarning: invalid hexadecimal literal
002 |   fifteen ,= [0x00for hello in world]
003 | 15
unique heath
#

very cursed

#

!e

print("bananas"or hello)```
night quarryBOT
#

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

bananas
unique heath
#

oh

versed eagle
thorny falcon
#

!e ```py

fifteen ,= [0x00for hello in world]
print(hello world!)```

night quarryBOT
#

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

001 | /home/main.py:1: SyntaxWarning: invalid hexadecimal literal
002 |   fifteen ,= [0x00for hello in world]
003 |   File "/home/main.py", line 2
004 |     print(hello world!)
005 |           ^^^^^^^^^^^
006 | SyntaxError: invalid syntax. Perhaps you forgot a comma?
thorny falcon
#

!e ```py

fifteen = [0x00for hello in world]
print(hello_world!)```

night quarryBOT
#

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

001 | /home/main.py:1: SyntaxWarning: invalid hexadecimal literal
002 |   fifteen = [0x00for hello in world]
003 |   File "/home/main.py", line 2
004 |     print(hello_world!)
005 |                      ^
006 | SyntaxError: invalid syntax
thorny falcon
#

!e ```py

fifteen = [0x00for hello in world]
print(hello_python)```

#

!e ```py

fifteen = [0x00for hello in world]
print(hellopython)```

night quarryBOT
#

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

001 | /home/main.py:1: SyntaxWarning: invalid hexadecimal literal
002 |   fifteen = [0x00for hello in world]
003 | Traceback (most recent call last):
004 |   File "/home/main.py", line 2, in <module>
005 |     print(hellopython)
006 |           ^^^^^^^^^^^
007 | NameError: name 'hellopython' is not defined
thorny falcon
#

!e ```py

fifteen = [0x00for hello in world]
print(helloworld)```

night quarryBOT
#

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

001 | /home/main.py:1: SyntaxWarning: invalid hexadecimal literal
002 |   fifteen = [0x00for hello in world]
003 | Traceback (most recent call last):
004 |   File "/home/main.py", line 2, in <module>
005 |     print(helloworld)
006 |           ^^^^^^^^^^
007 | NameError: name 'helloworld' is not defined
thorny falcon
#

!e ```py

fifteen = [0x00for hello in world]
print(hello_world)```

#

!e ```py
print("X.Y")(z. B. 3.8, 3.9)

night quarryBOT
#

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

001 |   File "/home/main.py", line 1
002 |     print("X.Y")(z. B. 3.8, 3.9)
003 |                        ^^^
004 | SyntaxError: invalid syntax
unique heath
#

what are you even

#

doing

restive void
#

Please use #bot-commands for trying things out

solemn quartz
#

guys can someone hop on a call w/ me so they can help me with why my pygame images are not blitting to the screen

#

just dm me so we can call, would really appreciate it.

south totem
solemn quartz
#

ok

night quarryBOT
#

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

001 | /home/main.py:1: SyntaxWarning: invalid hexadecimal literal
002 |   print(0x0for truly_cursed)
003 | 15
fluid pumice
#

!e

__0xff__=lambda:__builtins__.__import__("sys").stdout.write(__builtins__.__dir__()[0x01c-(1-~~-1)][1>>1]+__builtins__.__dir__()[--1^++1**1][0x08-0x03]+__build_class__.__dir__()[(0x0f-0x08>>++1*1)-1][(0x0a>>1)-1]*(0x0ff-0x0fd)+chr(int("++-++++".replace(*"-0").replace(*"+1"),2))+chr(int("{}".format(int("08",16)-0x02*0x02<<0x06-0x03)))+__annotations__.__dir__()[0x02*0x04-0x06>>2][(0x0b>>2)*2]+str(dir().__dir__()[(0x3d>>1)-1][0x03-0x02]+dir().__dir__().__dir__()[(0x62>>0x02)+0x0a][0x06//0x03])+__build_class__.__dir__()[(0x0f-0x08>>++1*1)-1][(0x0a>>1)-1]+dir().__dir__().__dir__()[0x0b6-0x088][0x0a>>2])
if ((__name__:=__name__) == '__main__'):__0xff__()```
night quarryBOT
#

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

hello world
sick hound
#

!e ```python
(lambda _, , , ____, , , ______, ________:
getattr(
import(True.class.name[
] + [].class.name[
]),
().class.eq.class.name[:
] +
().iter().class.name[
:][
:
__]
)(
_, (lambda _, __, ___: (, __, ___))(
lambda _, __, :
bytes([
% __]) + (, __, ___ // __) if ___ else
(lambda: _).code.co_lnotab,
_ << ___,
(((
<< __) + ) << (( << ____) - )) + ((((( << )
- ) << ) + ) << (( << ) + ( << ))) + (((
<<
_) - ) << ((((( << ) + )) << ) + ( << ))) + (((
<< ) + ) << (( << ) + )) + ((( << ) - ) <<
((
<< ))) + ((( << ) - ) << (((( << ) + ) <<
) - )) - (
<< ((((
<< ) - ) << ) + )) + (

<< (((((
<< ___) + _)) << _))) - (((((( << ) + )) << ) +
) << ((((
<< ) + ) << ))) + (((
<< ) - ) <<
(((((
<< ) + )) << ))) + ((( << ) + ) << (( <<
))) + (
<< _____) + ( << ___)
)
)
)(
*(lambda _, __, ___: (, __, ___))(
(lambda _, , :
[
(
[(lambda: _).code.co_nlocals])] +
(, __, ___[(lambda _: _).code.co_nlocals:]) if ___ else []
),
lambda _: _.code.co_argcount,
(
lambda _: _,
lambda _, __: _,
lambda _, __, ___: _,
lambda _, __, ___, ____: _,
lambda _, __, ___, ____, _____: _,
lambda _, __, ___, ____, _____, ______: _,
lambda _, __, ___, ____, _____, ______, _______: _,
lambda _, __, ___, ____, _____, ______, _______, ________: _
)
)
)

night quarryBOT
#

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

001 | /home/main.py:10: DeprecationWarning: co_lnotab is deprecated, use co_lines instead.
002 |   (lambda: _).__code__.co_lnotab,
003 | Hello world!
sick hound
#

!e

print(~0o0or truly @ cursed)
night quarryBOT
#

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

001 | /home/main.py:1: SyntaxWarning: invalid octal literal
002 |   print(~0o0or truly @ cursed)
003 | -1
unique heath
#

cursed

arctic skiff
#

cursed

finite blaze
#

truly

versed eagle
#

its just <truthy expr> or <expr> returning <truthy expr>

cerulean rivet
#

is there a simple way to reassembly the parser/ast in runtime to do some preprocessing in tokens/ast?

gleaming linden
#

custom encodings might be able to do something

#

or fork cpython, but that's not very simple

hard spoke
#

would a parsinghook do?

gleaming linden
#

I haven't heard of that before, TIL

unreal echo
gleaming timber
#

!e ```py
print(+())

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     print(+())
004 |           ^^^
005 | TypeError: bad operand type for unary +: 'tuple'
fleet bridge
#
>>> ''+()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "tuple") to str
>>> 1+[]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
#

weird

#

error messages are different

#

does it mean that str.__add__ raises TypeError instead of returning NotImplemented?

#
>>> ''.__add__(())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "tuple") to str
>>> 1 .__add__([])
NotImplemented
``` yeah
#

i consider this a bug

arctic skiff
#
Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 .__add__([])
NotImplemented
>>> 1+[]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> 
```its been like that for long time
#

I don't have older versions to test on

fleet bridge
arctic skiff
#

and why?

fleet bridge
#

why would it be a bug?

#

.__op__ should not raise an exception, they should return NotImplemented
this is a documented behaviour

arctic skiff
#

then why ```py

''.add([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'list' object to str implicitly
[].add('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list

arctic skiff
#

__op__ only exist on numericals datatypes?

#

wait let me read more about it

fleet bridge
fleet bridge
#

any binary dunder method

#

a dunder method that implements some binary operator

#
>>> ''.__add__(b'')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "bytes") to str
>>> b'' + ''
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't concat str to bytes
``` this is also weird, i would expect these errors to be the same

i also have a suspicion that all these inconsistencies are caused by some common code that is shared across all sequence-like types (list/tuple/str/...)
it might be related to the fact that there are two slots that implement `+`, and the one that is related to sequences is not implemented properly
arctic skiff
#

ok

red timber
#

what does a for look for to stop when a StopIteration is thrown, besides the exception? e.g. you can't simply do a raise StopIteration within the for's body itself or use .throw taken from a generator:

throw = (lambda: (yield))().throw

class Iterator:
    def __init__(self):
        self.i = 0
        self.limit = 4

    def __next__(self):
        if self.i < self.limit:
          self.i += 1
          return self.i

        # works with `raise`, not with `throw(...)`
        raise StopIteration
        # throw(StopIteration)

Iterable = type(
    '',
    (),
    {
        '__iter__': lambda self: Iterator()
    })

for n in Iterable():
    print(n)```I assume it has something to do with the way the tracing works
fleet bridge
#
  1. it only looks for exceptions when calling .__next__(). This is why exceptions in the loop body are not caught
  2. not sure why throw(...) is ignored
proper vault
# red timber what does a `for` look for to stop when a `StopIteration` is thrown, besides the...

In [17]: throw = (lambda: (yield))().throw

In [18]: throw(StopIteration)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
Cell In[17], line 1, in <lambda>()
----> 1 throw = (lambda: (yield))().throw

StopIteration:

The above exception was the direct cause of the following exception:

RuntimeError                              Traceback (most recent call last)
Cell In[18], line 1
----> 1 throw(StopIteration)

RuntimeError: generator raised StopIteration
```generators aren't allowed to raise StopIteration other than by being exhausted - `next((lambda:1 or (yield))())` for example.
red timber
#

ah, that explains the message... explaining it

#

lololol

#

thanks, is there any other way to raise an exception with an expression? without using exec

proper vault
red timber
#

interesting

#

thanks

proper vault
#

that's what I'm here for

buoyant slate
#

Hi

fleet bridge
#
n2s=lambda n,b:[s:='',[(s:=s+'0123456789ABCDEF'[n%b],n:=n//b)for _ in iter(lambda:n>0,False)],s[::-1]][-1]
#

number n -> string in base b

#

assert b in range(1, 16+1)
assert b in range(2, 16+1)

torn cypress
#

doesn't work with b = 1

versed eagle
torn cypress
#

int converts from base to int not the other way around like n2s above and also denball specified that b in range(1, 16 + 1) which includes 1, so, uhhh

left hinge
#

i always await seeing new wizard spells to gaze upon in esoteric python channel

unique heath
#

same

fleet bridge
#

yeah, it was a typo
also this function produces empty string for 0, and will produce some nonsense for negative numbers

torn cypress
#

(I mean... kinda obvious that you are golfing)

grave grail
#

Nvm

gleaming linden
#
n2s=lambda n,b:[s:='',[(s:='0123456789ABCDEF'[n%b]+s,n:=n//b)for _ in iter(lambda:n>0,0)]]and s
fleet bridge
#

i can swap the order in s:=... and get rid of [::-1] at the end

quartz wave
#

much shorter when recursive but that doesn't work for lengths greater than 999

#

also shorter when using a normal function

dense nova
#

i made wordle in 1 line but it can probably be shorter

#

idk

#
a:[((g:=(gf:=lambda:(((i,print(a[0]-c-1,a[4](i,a[1])))[0] if(i!=a[1])else(print(1),__import__('sys').exit()))if len((i:=input().strip().upper()))==5 and i not in a[3]and i in a[2]else gf()))()),a[3].append(g))for c in range(a[0])]+[print(0,a[1])]=[9-2*(df:=lambda:int(r)if(r:=input().strip()).isdigit()and 0<int(r)<=3 else df())(),__import__('random').choice(open('answers.txt','r').readlines()[0].strip().split()),open('valid_guesses.txt','r').readlines()[0].strip().split(),[],(lambda g,r:(c:=__import__('colorama'),u:=[],m:=[f"{c.Back.GREEN}{c.Fore.BLACK}",f"{c.Back.YELLOW}{c.Fore.BLACK}"],''.join((f"{m[0]}{l}{c.Style.RESET_ALL}"if l==r[i]else(f'{m[1]}{l}{c.Style.RESET_ALL}'if l in r and u.count(l)+1<=r.count(l)else l),u.append(l))[0]for i,l in enumerate(g)))[3])]
arctic skiff
#

also you don't need to pass 'r'

#

by default it opens in r mode

#

!d open

night quarryBOT
#

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

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

you were supposed to send format for them

dense nova
#

oh mb

#

its just WORD WORD WORD WORD

left hinge
#
r = lambda a,b: str(random.randint(a,b))
c = lambda s: random.choice(s)
comp = c([f"Lenovo ","Windows "])+r(10,50)+" "

calling upon the grand wizards
how do i make this more

left hinge
#

silly

#

shorter

#

more... "pleasing" to look at

turbid dragon
#

You can import randint and choice (maybe with aliases) to remove random., you can make a an iterable argument so you dont need the brackets around Lenovo or Windows, remove the broken f

#

Could do maths on 10, 50 i guess

#

Hash lenovo and windows

#

Could not make a variable for comp and just concatenate where its used

#

This isnt really the right channel though

#

Not sure what you're after - shorter and messier are two completely separate things - It looks like you want messier code? Which can be done in a million ways with like str.__call__ or calling __add__ instead of +, using ridiculous ternaries, adding redundancy, to just name a few

left hinge
#
import random

r = lambda a,b: str(random.randint(a,b))
c = lambda s: random.choice(s)
while True:
    hubris = "Why yes, I quite enjoy playing DOOM on my "+c(["Lenovo ","Windows ","Atari ","Dell ","Raspberry Pi ","HP ","Alienware ","Acer ","Toshiba ","IBM ","Panasonic "])+r(10,9001)+c([" Deluxe "," Extreme ",("-"+r(1,99)+" "),"-X ","-I4 "," 99 "," "])+c(["AMD Ryzen ", "Intel ", "Cortex-A7 ","AMD Phenom ","AMD K6-III+ ","GTIA ","Motorola 68k ","Zilog Z80 ","MOS 6502 "])+r(3,124)+"ghz "+c(["DRAM ",("DDR"+r(2,19)+" "),"SRAM "])+r(1,140)+c(["GB ","MB ","KB "])
    print(hubris)
#

this is what i ended up with

dense nova
#

i play doom on my neighbours 12th microwave

left hinge
#

adding microwave to the list

arctic skiff
left hinge
#

texas instruments calculator

dense nova
#

when there are 0 ti calculators where i am 😭

arctic skiff
dense nova
#

yeahhh i saw that

#

crazy low fps but still

left hinge
#

what

#

that's almost lower than my toshiba laptop

arctic skiff
dense nova
#

omg

left hinge
#

i think my framerate would be higher than gut bacteria

#

i just need to bust out hella calculators

dense nova
#

Potatoes().play_doom()

arctic skiff
left hinge
#

imagine a competition where competitors need to play doom with a piece of paper and calculators

#

Potatoes(doom)

dense nova
arctic skiff
#

you dopy @Potatoes().doom def play(): return self.status.playing play()

left hinge
#

what is @

dense nova
#

decorator

arctic skiff
#

it decorates the function so you can invite your little pet ant to it

left hinge
#

what

dense nova
#

when you add a decorator to a function it sneakily adds a πŸŽ€ to the byte code

left hinge
#

i'm in the wrong channel to ask questions, i'm gonna get some enchantment table moon rune type stuff

arctic skiff
#

I didn't expect this

dense nova
#

nah cuz it cant be that hard to modify the c code for python to change the notation for decorators from @ to πŸŽ€ right

left hinge
#

"am i pregnant?"
"hold on let me finish this level"

dense nova
arctic skiff
dense nova
#

mad

#

"Ok, you look very qualified for the job! Just one last thing, what version of python are you most comfortable with?"
"Oh, mostly Python 4"
"bro what"

stone topaz
#

4

arctic skiff
dense nova
#

no way

arctic skiff
#

.topic

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

Suggest more topics here!

arctic skiff
left hinge
#

make a print function without using the print function

arctic skiff
#

here you go

#

print function without using print

#

with all functionality

left hinge
#

wh

arctic skiff
arctic skiff
#

oh wait shit

arctic skiff
#

forgot I can't just change name of kwargs

#

!e```py
print=lambda*a,sep=' ',end='\n',file=import('sys').stdout,flush=0:(file.write(sep.join([*map(str,[*a,end])])),file.flush()if flush else...)[0]

print('hello world')
print('1,2,', 1,4, sep=',', end='5')
print('f.f', file=open('file.txt','w'))
print('flush', flush=True)```

night quarryBOT
#

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

001 | hello world 
002 | 1,2,,1,4,5flush 

file.txt

f.f 
arctic skiff
#

@left hinge

left hinge
#

i didn't know you could print to files

#

what does the flush do?

arctic skiff
#

it flush the buffer

#

I just found a bug

left hinge
#

it's not supposed to spit out a 7

#

it is insane to me that you can just. redefine a built in function

arctic skiff
#
print=lambda*a,sep=' ',end='\n',file=__import__('sys').stdout,flush=0:(file.write(sep.join([*map(str,a)])+end),file.flush()if flush else...,None)[2]```fixed
arctic skiff
left hinge
#

!e

print=lambda*a,sep=' ',end='\n',file=__import__('sys').stdout,flush=0:(file.write(sep.join([*map(str,a)])+end),file.flush()if flush else...,None)[2]

print('hello')
night quarryBOT
#

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

hello
left hinge
#

does it just function the exact same as the built in one, or is it better

arctic skiff
arctic skiff
arctic skiff
#

I don't see anyway to make it shorter

dense nova
versed eagle
versed eagle
versed eagle
#
from sys import*
def print(*a,sep=' ',end='\n',file=stdout,flush=0):file.write(sep.join(map(str,a))+end);flush and file.flush()
arctic skiff
#

!e```py
print(len("""
from sys import*
def print(*a,sep=' ',end='\n',file=stdout,flush=0):file.write(sep.join(map(str,a))+end);flush and file.flush()"""))

night quarryBOT
#

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

127
arctic skiff
#
import sys
def print(*a,sep=' ',end='\n',file=sys.stdout,flush=0):file.write(sep.join(map(str,a))+end);flush and file.flush()
#

!e```py
print(len("""
import sys
def print(*a,sep=' ',end='\n',file=sys.stdout,flush=0):file.write(sep.join(map(str,a))+end);flush and file.flush()"""))

night quarryBOT
#

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

125
fleet bridge
bright valve
#

idk why I felt it looked like gradle at first glance

quartz wave
#

i don't think so

rugged sparrow
#

I have a challenge for y'all. Given only control over the inputs to this function: ```py
def challenge(data, stacksize=0, variables=0):
func = lambda:None
func.code = func.code.replace(
co_stacksize=stacksize,
co_nlocals=variables,
co_varnames= ('',) * variables,
co_code=data
)
return func()

#

@quartz wave you might like this ^

magic raptor
#

Probably not that esoteric, but is there a way to programmatically update the locals of a function while within the function?

#

For context, I'm trying to iterate through the locals and update them based on some conditions.

def test(
    a: int = 2,
    b: float = 1.0,
    /,
    ex: str = "hello",
    *,
    c: list[object] = defer(lambda *_: ["Preceding args", *_]),
    d: bool = False,
    e: int = defer(lambda _, __, ___, c, ____: len(c))
) -> tuple[object, ...]:
    for arg_name, arg_val in locals().copy().items():
        if isinstance(arg_val, defer):
            result = arg_val(*itertools.takewhile(lambda arg: not isinstance(arg, defer), locals().values()))
            exec(f"{arg_name} = result")  # Doesn't seem to work.
            sys._getframe(0).f_locals.update({arg_name: result})  # Doesn't seem to work.
rugged sparrow
#

you will need use the pythonapi to tell python the locals are updated

rugged sparrow
rugged sparrow
magic raptor
rugged sparrow
magic raptor
#

Gotcha. I’ll look into that then.

#

Thanks.

left hinge
#

opinion from the wizards:
is it better to use lambdas or defs

rugged sparrow
#

defs are always going to be more readable and clear

#

so if thats your goal, go with that ig

rugged sparrow
#

^ this makes an empty list, then treats it as a cell and stores an object at its addr + (3 * 8), then uses GET_LEN to dump the address

#

the inverse to load an object from an address is trickier, requires floats

left hinge
torn cypress
versed eagle
# left hinge opinion from the wizards: is it better to use lambdas or defs

in code thats actually meant to be used for anything ever:
for very (very!) trivial functions that are only used once, and are passed as arguments to other functions (e.g. map), lambdas are better because they're more concise, but for anything else, normal function definitions are more readable, maintainable, and a bunch of other positive adjectives that i cant be bothered to type out

for doing esoteric nonsense:
lambda is so silly, you should use it 100% of the time :3:3

quartz wave
#

applies to both esoteric and readable purposes

lunar marsh
rugged sparrow
gleaming timber
#

private variables using closures```py
class ObjWithPrivate:
def init(self):
int_only = 0
def get_int_only(self):
return int_only
def set_int_only(self, v):
if not isinstance(v, int):
raise ValueError
int_only = v
self.x = property(get_int_only, set_int_only)

o = ObjWithPrivate()
o.x = 42
print(o.x) # 42
o.x = 'hello' # error```

restive void
#

!e

class ObjWithPrivate:
    def __init__(self):
        int_only = 0
        def get_int_only(self):
            return int_only
        def set_int_only(self, v):
            if not isinstance(v, int):
                raise ValueError
            int_only = v
        self.x = property(get_int_only, set_int_only)


o = ObjWithPrivate()
o.x = 42
print(o.x) # 42
o.x = 'hello' # error
print(o.x)
night quarryBOT
#

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

001 | 42
002 | hello
restive void
#

Nope, doesn't error.

#

Descriptors don't work on the instance.

#
class ObjWithPrivate:
    def setup():
        int_only = 0
        def get_int_only(self):
            return int_only
        def set_int_only(self, v):
            if not isinstance(v, int):
                raise ValueError
            nonlocal int_only
            int_only = v
        return get_int_only, set_int_only
    x = property(*setup())


o = ObjWithPrivate()
o.x = 42
o.x = 'hi' # error

this works ^

#

(Although you can still do type(o).x.fset.__closure__[0].cell_contents = 'hi')

gleaming timber
rugged sparrow
versed eagle
versed eagle
#

like all problems, this can be fixed by using more indirection

class with_int_only:
    def _setup (self):
        int_only = 0
        def get ():
            return int_only
        def set (v):
            if not isinstance(v, int):
                raise ValueError
            nonlocal int_only
            int_only = v
        self._get, self._set = get, set
    def _get_wrapper (s):
        return s._get()
    def _set_wrapper (s, v):
        return s._set(v) 
    x = property(_get_wrapper, _set_wrapper)
    def __init__ (self):
        self._setup()

o = with_int_only()
o.x = 43
O = with_int_only()
print(O.x == o.x) # False
O.x = "hello" # errors
quartz wave
quartz wave
#

rewrite it as a C extension

lunar marsh
rugged sparrow
versed eagle
sick hound
# rugged sparrow yea thats my goal now that I have the primitives laid out. It will still only wo...
import dis
import opcode

def generate_extended_args(argval):
    if argval < 0:
        argval += 0xffffffff + 1
    args = []
    while argval > 0:
        args = [argval & 0xff] + args
        argval >>= 8
    return args

def op(opname, arg=0):
    arg &= 0xffffffff

    if (arg > 255) or (arg < 0):
        args = generate_extended_args(arg)
    else:
        args = [arg]
    for i, arg in enumerate(args):
        if i == len(args) - 1:
            yield (opn := dis.opmap[opname])
            yield arg
            yield from [0] * 2 * opcode._inline_cache_entries[opn]
            return
        yield dis.opmap['EXTENDED_ARG']
        yield arg

def push_number(n):
    return bytes([
        *op('LOAD_CONST', 0),  # None
        *op('UNARY_NOT'),      # True
        *op('UNARY_POSITIVE'), # 1
        *op('COPY', 1),
        *op('COPY', 1),
        *op('BINARY_OP', 10),  # 1-1=0
    ]) + b''.join(
        bytes([
            *([
                *op('COPY', 2),
                *op('BINARY_OP', 0), # +
            ] if n & (1 << i) else []),
            *op('SWAP', 2),
            *op('COPY', 1),
            *op('BINARY_OP', 0), # +
            *op('SWAP', 2)
        ])
        for i in range(n.bit_length())
    ) + bytes([
        *op('SWAP', 2),
        *op('POP_TOP'),
    ])

def position_independent_code(payload):
    # Here, you can implement logic to generate position-independent code
    # that adapts to different memory layouts and offsets
    # For simplicity, let's assume the payload doesn't rely on fixed addresses
    return payload

def generate_payload():
    # Example payload generation
    payload = b''  # Replace this with your actual payload bytecode
    return position_independent_code(payload)

# Generate and print the payload
print(generate_payload())```
#

this is an example of a more offset-agnostic payload generator using Python bytecode manipulation. This payload dynamically calculates memory addresses and utilizes position-independent code to adapt to different memory layouts.

rugged sparrow
sick hound
#

actually chatGPT 4

#

and they made some errors

#

in which I fixed so it isnt all chat gpt

rugged sparrow
sick hound
#

I guess this can be considered esoteric

#

maybe

#

korn shell wrapper that outputs python code: you write shell > out comes the snake

rugged sparrow
#

so you can grab the __builtins__ dictionary

#

and you can grab the code object (and use the letter c from it for format spec to generate strings)

lunar marsh
rugged sparrow
#

yea

#

for all of 3.11

lunar marsh
#

dope

rugged sparrow
#

its -7 for __builtins__ and -5 for code

serene stratus
#

Why is it always at -7?

#

What's the idea behind storing builtins behind every frame

fleet bridge
#

because reference to builtins can be different

lunar marsh
#

f_builtins is 8*7 bytes behind localsplus

#

so not really outside the frame, just another place inside it

sick hound
rugged sparrow
ornate geyser
#

yo uhm guys I need help with a little script

elfin ether
#

is it possible to monkeypatch __getitem__ on the globals dict?

rugged sparrow
#

yea, there are a few ways to do that

#

you can change the globals instance for a frame, or you can swap out the base type using ctypes/memory corruption

#

!e ```py
def example():
print(non_existent)

class MyDict(dict):
def getitem(self, key):
print('Looking up:', key)
return super().getitem(key)

example = type(example)(example.code, MyDict())
example()```

night quarryBOT
#

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

001 | Looking up: print
002 | Looking up: non_existent
003 | Traceback (most recent call last):
004 |   File "/home/main.py", line 10, in <module>
005 |     example()
006 |   File "/home/main.py", line 2, in example
007 |     print(non_existent)
008 |           ^^^^^^^^^^^^
009 | NameError: name 'non_existent' is not defined
rugged sparrow
#

@elfin ether ^

elfin ether
#

Let me try it

#

Thanks

#

any way to do it for the global frame?

rugged sparrow
#

this is much less stable however

elfin ether
#

Thanks, and lol that you have this bookmarked

#

I'm looking at this thread and wondering if there's a somewhat less brittle solution: https://discuss.python.org/t/when-might-f-globals-and-f-builtins-not-be-a-dict/22071

rugged sparrow
#

i am still working on the second part (which will accomplish global name lookup hooks)

elfin ether
#

Will do, thanks.

#

I'm trying to modify the code you shared, adding __getitem__ to the missing_hook class, but everything i've tried results in endless recursion

#

I'm not actually trying to resolve names that don't exist in scope. I'm trying to "decorate" everything

rugged sparrow
#

those use LOAD_FAST at the bytecode level, and just indexing a C level array of pointers

elfin ether
#

that's unfortunate

#

Weren't you saying there's a way to replace the globals dict in a frame; does the same approach not work for the locals dict?

rugged sparrow
#

The locals dict is not used for lookups

#

That representation is more read only

sick hound
#

I think u might need to do your homework first

#

πŸ˜‚

rugged sparrow
#

@elfin ether you could use a tracing function that runs on every bytecode access, but that would likely be really slow

elfin ether
rugged sparrow
#

the issue isn't where the bytecode runs, its the actual instructions used

#

!e py import dis x = lambda a:a dis.dis(x)

night quarryBOT
#

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

001 |   2           0 RESUME                   0
002 |               2 LOAD_FAST                0 (a)
003 |               4 RETURN_VALUE
rugged sparrow
#

^ inside the function, LOAD_FAST is used to load local variables

#

even if the bytecode is moved outside the frame, it will still be a load fast

#

you could in theory use a tracing function, watch for LOAD_FAST ops and replace them with LOAD_GLOBAL of some custom name that your global hook sees and uses to resolve the value

elfin ether
#

Understood, I guess what I meant was possibly creating new frame from the code of the function, except replacing the function declaration with a set of dummy initializations (or real initializations in the case of optional args), then compiling this to bytecode and executing it. Obviously there are tons of potential issues

rugged sparrow
#

ah yea patching bytecode and recompiling is going to be very tricky

#

I did that a while back when I implemented Tail Call Optimization into python

#

there are a lot of edge cases

elfin ether
#

Do you have a blog post on that? I've read a few blog posts on tail call optimization in python awhile back.

rugged sparrow
#

also with bytecode specialization, it may not be consistent

#

i never wrote a post on it (although I really should)

#

let me find the implementation

elfin ether
#

Is it possible to force the load_fast to look at a different memory location?

rugged sparrow
#

LOAD_FAST indexes just after the frame object

#

since there isnt any indirection, you would need to swap out the entire frame i think

#

thats from 3.10, it does not optimize on 3.12

#

it looks for CALL_FUNCTION which was replaced with PRECALL and CALL in 3.11

elfin ether
#

been awhile since i looked into the details of python bytecode, so I can't really digest this quickly

rugged sparrow
versed eagle
night quarryBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

elfin ether
#

Unrelated to everything we've been talking about, but may be of interest to some: here's a fragile way to create "custom operators" possibly with modifiers:

def reshape(mat, r, c, fill=np.nan):
    newmat = np.empty((r, c))
    newmat.fill(np.nan)
    rr, cc = mat.shape
    rr = min(r, rr)
    cc = min(c, cc)
    newmat[:rr, :cc] = mat[:rr, :cc]
    return newmat
    
class Block:
    def __init__(self, mat: np.array):
        self.mat = mat
        self.mod = None
    def __invert__(self):
        self.mod = 1
        return self
    def a(self, other):
        r1, c1 = self.mat.shape
        r2, c2 = other.mat.shape
        
        if other.mod == 1:
            mat = np.hstack([reshape(self.mat, r2, c1), other.mat])
        else:
            mat = np.hstack([self.mat, reshape(other.mat, r1, c2)])
        return Block(mat)

class A:
    def __init__(self):
        self.args = []
    def __gt__(self, other):
        if not self.args:
            self.args.append(other)
            return True
        else:
            return self.args.pop().a(other)

a = A()
block1 = Block(np.arange(4).reshape((2,2)))
block2 = Block(5 + np.arange(9).reshape((3,3)))

(block1 <a> block2).mat, (block1 <a>~ block2).mat
rugged sparrow
#

oh thats sick

#

reminds of my weird typing code i wrote to emulate generics from java.

#

it would let this Type<int>(1) work

#

but it involved some weird bytecode reordering shenanigans

#

basically would rearrange the bytecode once the first < executed to be shaped like Type(int, (1))

versed eagle
#

interesting

rugged sparrow
#
class Tmeta(type):
    def __lt__(cls, ocls):
        frame = sys._getframe(1)
        mem = getmem(id(frame.f_code.co_code) + bytes.__basicsize__ - 1, len(frame.f_code.co_code))
        instructions = [*dis.get_instructions(frame.f_code)]
        for idx, instruction in enumerate(instructions):
            if idx * 2 < frame.f_lasti:
                continue
            if instruction.opname == 'COMPARE_OP' and instruction.argval == '>':
                if instructions[idx+1].opname == 'JUMP_FORWARD':
                    if instructions[idx+2].opname == 'ROT_TWO':
                        if instructions[idx+3].opname == 'POP_TOP':
                            inj_code = bytes([
                                dis.opmap['ROT_TWO'], 0,
                                dis.opmap['ROT_THREE'], 0,
                                dis.opmap['CALL_FUNCTION'], 2,
                                dis.opmap['NOP'], 0,
                            ])
                            mem[frame.f_lasti] = dis.opmap['POP_TOP']
                            mem[frame.f_lasti + 2] = dis.opmap['NOP']
                            mem[idx * 2:idx * 2 + len(inj_code)] = inj_code
                            return cls

class Array(metaclass=Tmeta):
    def __init__(self, T, args):
        self.T = T
        self.args = args

    def __repr__(self):
        return f'{type(self).__name__}<{self.T.__name__}>{self.args}'

class HashMap(metaclass=Tmeta):
    def __init__(self, T, args):
        self.T = T
        self.args = args

    def __repr__(self):
        return f'{type(self).__name__}<({", ".join(t.__name__ for t in self.T)})>{self.args}'

a = Array<int>(1,2,3)
b = HashMap<(str, int)>{
    'a': 0,
    'b': 1
}

def f():
    v = Array<int>(1,2,3)
    print(v)```
#

it def does not work on anything above 3.9

versed eagle
#

i would have treated it like a metaclass
stuff<thing>(123) -> stuff(thing)(123)

rugged sparrow
#

ah that would have been good too

#

and in hindsite, actually easier lol

#

by a decent amount

#

actually because of the shortcircuting it would still be difficult

#

just for different reasons

#

A<B>C turns into A<B and B>C, (and B is copied)

versed eagle
#

right

rugged sparrow
#

so in theory could replace B on the stack with the a wrapped return value that calls its input when > against another argument

#

tricky part is grabbing the address to the stack of a currently evaluating frame

versed eagle
rugged sparrow
versed eagle
#

ah

rugged sparrow
#

(in refence to fishhook but i extended it to most of my weird hacks)

versed eagle
#

the second example (stuff<thing<thing2>>(123)) probably actually could be done with bytecode hacking

#

because it is valid syntax

#

and with barry as flufl the first one could also be done..

rugged sparrow
#

i was about to say that lol

#

in a perfect world tho, if its being treated as a meta class i would want X = thing<thing2> to work, but thats not valid

versed eagle
#

true

#

though, such things aren't allowed with Java generics afaik
since they're based on C++ templates

rugged sparrow
#

hmm fair

elfin ether
versed eagle
#

!e ```py
from future import barry_as_FLUFL
print(1 <> 2) # same as 1 != 2

night quarryBOT
#

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

001 |   File "/home/main.py", line 2
002 |     print(1 <> 2) # same as 1 != 2
003 |             ^^
004 | SyntaxError: invalid syntax
versed eagle
#

oh did they remove it

#

it works in my repl :c

elfin ether
#

first i'm hearing of barry_as_FLUFL

rugged sparrow
#

!e py from __future__ import barry_as_FLUFL print(1 <> 2)

night quarryBOT
#

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

001 |   File "/home/main.py", line 2
002 |     print(1 <> 2)
003 |             ^^
004 | SyntaxError: invalid syntax
rugged sparrow
#

might not work with the bot