#esoteric-python

1 messages · Page 99 of 1

slim echo
#

Ah so I need to find out how to clear those then :P

rugged sparrow
#

you cant

#

without using ctypes

slim echo
#

Fair enough then

rugged sparrow
#

every class stores a reference to its subclasses

slim echo
#

Which is kinda weird

rugged sparrow
#

!e py print(object.__subclasses__())

night quarryBOT
#

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

[<class 'type'>, <class 'weakref'>, <class 'weakcallableproxy'>, <class 'weakproxy'>, <class 'int'>, <class 'bytearray'>, <class 'bytes'>, <class 'list'>, <class 'NoneType'>, <class 'NotImplementedType'>, <class 'traceback'>, <class 'super'>, <class 'range'>, <class 'dict'>, <class 'dict_keys'>, <class 'dict_values'>, <class 'dict_items'>, <class 'dict_reversekeyiterator'>, <class 'dict_reversevalueiterator'>, <class 'dict_reverseitemiterator'>, <class 'odict_iterator'>, <class 'set'>, <class 'str'>, <class 'slice'>, <class 'staticmethod'>, <class 'complex'>, <class 'float'>, <class 'frozenset'>, <class 'property'>, <class 'managedbuffer'>, <class 'memoryview'>, <class 'tuple'>, <class 'enumerate'>, <class 'reversed'>, <class 'stderrprinter'>, <class 'code'>, <class 'frame'>, <class 'builtin_function_or_method'>, <class 'method'>, <class 'function'>, <class 'mappingproxy'>, <class 'generator'>, <class 'getset_descriptor'>, <class 'wrapper_descriptor'>, <class 'method-wrapper'>, <class 
... (truncated - too long)

Full output: https://paste.pythondiscord.com/ifarejemad.txt

rugged sparrow
#

it means we can do that ^

slim echo
#

Yeah I looked at that in my working shell lol

rugged sparrow
#

get_cls('_sitebuiltins._Printer').__init__.__globals__['sys'].modules this gets sys.modules

#

now we need to import builtins and restore it

slim echo
#

WOAH what

#

I cleared sys.modules though

rugged sparrow
#

so?

#

its still referenced

#

so we need to re-add builtins to recover

slim echo
#

Weird that sys.modules manages to restore itself

elfin onyx
#

@rugged sparrow how long has it been since you started python?

rugged sparrow
#

a couple years

#

@slim echo it doesnt

#

we just need to add builtins to that same dict

elfin onyx
slim echo
#

I'm literally clearing then immediately inspecting it in a shell and it's adding a bunch of stuff to it

rugged sparrow
#

2 years since i really started @elfin onyx

elfin onyx
#

thx

rugged sparrow
#

yea some modules will repair themselves

slim echo
#

Also somehow clearing sys.modules deletes all my variables; I guess that's because I'm deleting __main__

rugged sparrow
#

we need builtins to fully recover

slim echo
#

Yeah

rugged sparrow
#

@slim echo we'll have to bootstrap it a bit

#

lemme write up a clean proof of concept

slim echo
#

'clean'

rugged sparrow
#

@slim echo ^

slim echo
#

Good lord lmao

rugged sparrow
#

depending on the version __builtins__ may be a dict, or a module at this point

slim echo
#

Lol

rugged sparrow
#

so sometimes the code will be __builtins__.__dict__.update or __builtins__.update

slim echo
#

In 3.8.5 __builtins__ appears to be a dictionary

#

Did that say __builtins__ is undefined lol

#

That's an interesting way of implementing getattr btw

rugged sparrow
#

yea it works enough for importlib to do its job

#

!e ```py
_del = delattr
_imp = import
for i in dir(builtins):
_del(builtins, i)

sys = _imp('sys')
sys.meta_path.clear()
sys.modules.clear()

object = ().class.base
singleton = object()
type = object.class
def get_cls(name, base=object):
if f'{base}'.split("'")[1] == name:
return base
for cls in type(base).subclasses(base):
if ret := get_cls(name, cls):
return ret

builtins.dict.update({
'KeyError': get_cls('KeyError'),
'ImportWarning': get_cls('ImportWarning'),
'len': lambda o: type(o).len(o),
'hasattr': lambda o, a: a in o.dict,
'getattr': lambda o, n, d=singleton: o.dict.get(n, d),
'isinstance': lambda o, t: t in o.class.mro
})

builtins.dict.update(get_cls("_frozen_importlib.BuiltinImporter").load_module('builtins').dict)

print(1)```

night quarryBOT
#

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

1
slim echo
#

So from that point have you essentially repaired the shell then

#

I'll have to test this

#

Also interestingly destroying the environment as I demonstrated also breaks the autocomplete

rugged sparrow
#

makes sense

grizzled cloak
#

so really we should create a pep for storing modules as weak references to avoid them sticking around!

slim echo
#
>>> import sys
>>> Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 899, in _find_spec
NameError: name 'ImportWarning' is not defined

You nearly fixed the shell in one go lmao

rugged sparrow
#

since autocomplete is done by readline module

slim echo
#

Although really the issue is subclasses

#

type.__subclasses__ is the reason this works

#

Wait where is Exception even defined lol

#

We have no exceptions lol

rugged sparrow
#

one sec

rugged sparrow
#

@slim echo i was able to restore exceptions

#

but importing still fails

#
_del = delattr
_imp = __import__
for i in dir(__builtins__):
    _del(__builtins__, i)

sys = _imp('sys')
sys.meta_path.clear()
sys.modules.clear()

object = ().__class__.__base__
singleton = object()
type = object.__class__
def get_cls(name, base=object):
  if f'{base}'.split("'")[1] == name:
    return base
  for cls in type(base).__subclasses__(base):
    if ret := get_cls(name, cls):
      return ret

def all_excs(c=get_cls('BaseException')):
    yield c
    for s in c.__subclasses__():
        yield from all_excs(s)

__builtins__.update({
    **{exc.__name__: exc for exc in all_excs()},
    'len': lambda o: type(o).__len__(o),
    'hasattr': lambda o, a: a in o.__dict__,
    'getattr': lambda o, n, d=singleton: o.__dict__.get(n, d),
    'isinstance': lambda o, t: t in o.__class__.__mro__
})

__builtins__.update(get_cls("_frozen_importlib.BuiltinImporter").load_module('builtins').__dict__)

print(1)
slim echo
#

Is ImportWarning not a subclass of exception or smth

rugged sparrow
#

no now it just cant find any modules

slim echo
#

Ah

#

Probably because of meta_path being cleared

rugged sparrow
#
>>> import os
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'os'
>>> ``` yea
slim echo
#

There probably isn't a good way of fixing that

#

Wait we (probably) don't even have access to sys there probably isn't any way of fixing that

rugged sparrow
#
_del = delattr
_imp = __import__
for i in dir(__builtins__):
    _del(__builtins__, i)

sys = _imp('sys')
sys.meta_path.clear()
sys.modules.clear()

object = ().__class__.__base__
singleton = object()
type = object.__class__
def get_cls(name, base=object):
  if f'{base}'.split("'")[1] == name:
    return base
  for cls in type(base).__subclasses__(base):
    if ret := get_cls(name, cls):
      return ret

def all_excs(c=get_cls('BaseException')):
    yield c
    for s in c.__subclasses__():
        yield from all_excs(s)

__builtins__.update({
    **{exc.__name__: exc for exc in all_excs()},
    'len': lambda o: type(o).__len__(o),
    'hasattr': lambda o, a: a in o.__dict__,
    'getattr': lambda o, n, d=singleton: o.__dict__.get(n, d),
    'isinstance': lambda o, t: t in o.__class__.__mro__
})

__builtins__.update(get_cls("_frozen_importlib.BuiltinImporter").load_module('builtins').__dict__)
get_cls("_sitebuiltins._Printer").__init__.__globals__['sys'].meta_path.extend(
    map(
        get_cls,
        [
            '_frozen_importlib.BuiltinImporter',
            '_frozen_importlib.FrozenImporter',
            '_frozen_importlib_external.PathFinder'
        ]
    )
)

print(1)``` @slim echo fixed it
slim echo
#

Wait what

#

How does that work

#

Does metapath not do what I expect lol

rugged sparrow
#

_sitebuiltins is imported by the interpreter to define help and quit

#

but its written in python

slim echo
#

Also I forgot we have sys lol

rugged sparrow
#

that module also has a reference to a live sys module

#

which we can use to get sys.meta_path to repair it

slim echo
#

Nice

#

Is metapath not a list of paths though lol I thought it was

rugged sparrow
#

nah its a list of importers

stark fable
#

sys.path is a list of paths beecloseloaf

astral rover
#

as strings

rugged sparrow
#

The first 8 lines break the interpreter by clearing builtins

#

The rest fixes the interpreter

sudden willow
#

messing around with lambda

#

!e

_=lambda _:_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_)))))))))
print(_(1))
night quarryBOT
#

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

10
sick hound
#
x=type("",(dict,),{"__getattr__":lambda s,a:s[a]})

how to golf

thin trout
#

Can you pass a list as the second argument?

sick hound
#

not sure

#

the documentation for type says tuple

#

i will try though

#
TypeError: type.__new__() argument 2 must be tuple, not list
thin trout
#

Sad

#

I don't think you can do shorter

sick hound
#

what about like

#

that chinese thing

thin trout
#

Chinese thing?

sick hound
#

yeah like encoding the code in chinese characters

#

not sure

thin trout
#

Wow, I never heard about this one

sick hound
#

i think you have

#

i think i can link it one sec

#

u16

thin trout
#

That's stupid, I love it

sick hound
#

lol

#

its kinda cheating

next flame
#

this is why codegolf counts bytes not chars 🙂

thin trout
#

That is a good point

sudden willow
#

!e
_=lambda _:_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_))))))))) print(_(True))

night quarryBOT
#

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

10
sudden willow
#

True == 1

sick hound
#

yes @sudden willow and False == 0

proper vault
#

@sick hound do you know the type of s in that snippet?

#

guessing dict

#

you could

x=type("",(dict,),{"__getattr__":dict.get})
#

difference in behaviour since it now returns None instead of an error

sick hound
#

just made merge sort inline lol

#
print( ( mergesort := lambda arr : arr if len(arr) <= 1 else ( merge := lambda result,left,right,lp=0,rp=0 : ( merge([*result,left[lp]],left,right,lp+1,rp) if left[lp] < right[rp] else merge([*result,right[rp]],left,right,lp,rp+1) ) if (lp < len(left) and rp < len(right)) else [*result,*right[rp:],*left[lp:]] )( [],mergesort(arr[:len(arr)//2]),mergesort(arr[len(arr)//2:]) ) )( arr=[int(num) for num in input('Enter a list of numbers seperated by commas:\n>>> ').split(',')]), '\n\nMerge sort one liner made by @rafrafraf' )
#

any suggestions for something harder to do inline?

proper vault
#

An Aiohttp request

sick hound
#

woah

#

imma google what that is

#

lmao

sick hound
#

that's so smart

astral rover
#

has anyone ever used the _peg_parser module for anything

elfin onyx
#

I got a challange for you, try to find out which module the NoneType class is in

astral rover
#
>>> None.__class__.__module__
'builtins'
elfin onyx
#

oh i tried on the actual nonetype class

astral rover
#

should still just be its module dunder

elfin onyx
#

it raises namerror

astral rover
#

huh

elfin onyx
#

like u can't use nonetype class

astral rover
#

yeah you dont have to get its class

#

cause you have NoneType already

#
None.__class__.__class__
<class 'type'>```but that also works fine for me
stark fable
#

i think what they mean is that using the name NoneType doesn't work

bitter iris
twilit grotto
bitter iris
#

right

#

then feel free to create ASTs with it ;-)

astral rover
#

ah

#

i was just curious cause it just had the two ast functions

last locust
#

How do I obfuscate numbers without using dunders? So like getting 100 without just stacking .__add__()

#

And the type does need to be integer

terse mortar
#

I mean, instead of stacking __add__ together, you can use __mul__. Dunno if that's what you want tho

last locust
#

I want to avoid all dunders if possible

#

I think I've seen some stuff using ~ to manipulate numbers but no clue how it works

terse mortar
twilit grotto
#

it's because ~ inverts the bits of a number

#

so 0 -> 1, and 1 -> 0

#

which pretty much. ~x == x - 1

last locust
#

Is there an esoteric way to square a number without dunders?

last locust
#

Wait

#
>>> (-~-~-~-~int()).__pow__(-~-~int()).__sub__((-~-~int()).__pow__(~-~-int()))
NotImplemented```why does this give NotImplemented?
#

It should bepy (4).__pow__(2).__sub__((2).__pow__(2))akapy 4 ** 2 - 2 ** 2akapy 12but clearly not

naive roost
#

~-~-int() is -2, so actually, that should be 4 ** 2 - 2 ** (-2)

last locust
#

Right, I got the signs the wrong way round

naive roost
#

However, (16).__sub__(.25) is not implemented

#

(.25).__rsub__(16) is though

last locust
#

I wanted ** 2 instead of ** -2 aka -~-~int() not ~-~-int()

#

Thanks

#
print('\n'.join(map(str, map(__import__('random').choice, [[x for x in map(str, range(-~int(), -~(~-~-(-~-~-~-~int()).__pow__(-~-~int()).__sub__((-~-~int()).__pow__(-~-~int()))).__pow__(-~-~int())))] for _ in range(~-~-(-~-~-~-~int()).__pow__(-~-~int()).__sub__((-~-~int()).__pow__(-~-~int())))]))))```beautiful
#

!e py print('\n'.join(map(str, map(__import__('random').choice, [[x for x in map(str, range(-~int(), -~(~-~-(-~-~-~-~int()).__pow__(-~-~int()).__sub__((-~-~int()).__pow__(-~-~int()))).__pow__(-~-~int())))] for _ in range(~-~-(-~-~-~-~int()).__pow__(-~-~int()).__sub__((-~-~int()).__pow__(-~-~int())))]))))

night quarryBOT
#

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

001 | 23
002 | 84
003 | 88
004 | 72
005 | 55
006 | 94
007 | 75
008 | 100
009 | 71
010 | 85
last locust
#

By any chance is there a way I could assignpy ~-~-(-~-~-~-~int()).__pow__(-~-~int()).__sub__((-~-~int()).__pow__(-~-~int()))to _ or something? Since I use it twice

astral rover
#

globals().__setitem__('_', )

last locust
#

How would I do that in-line here? @astral rover

astral rover
#

that is one line friendly

last locust
#

I meant incorporating it with my current code so the entire thing is still one line

astral rover
#

globals().__setitem__('_', ~-~-(-~-~-~-~int()).__pow__(-~-~int()).__sub__((-~-~int()).__pow__(-~-~int())))

last locust
twilit grotto
#

you could use walrus

astral rover
#

i think i broke something

#
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/random.py", line 346, in choice
    return seq[self._randbelow(len(seq))]
IndexError: list index out of range```
#
print([globals().__setitem__("_", ~-~-(-~-~-~-~int()).__pow__(-~-~int()).__sub__((-~-~int()).__pow__(-~-~int()))), "\n".join(map(str,map(__import__("random").choice,[[x for x in map(str, range(-~int(), -~(_).__pow__(-~-~int())))] for _ in range(_)])))][-1])
```in my head something like this works
last locust
#

You broke the random.choice lol

last locust
astral rover
#

you dont need an if to use a walrus

last locust
#

So you don't lol

astral rover
#

oh i think its shadowing something

#

yeah it was

#

!e ```py
print(
(
lambda: [
globals().setitem("", ~-~-(-~-~-~-~int()).pow(-~-~int()).sub((-~-~int()).pow(-~-~int()))),
"\n".join(
map(
str,
map(
import("random").choice,
[[x for x in map(str, range(-~int(), -~
.pow(-~-~int())))] for __ in range(_)],
),
)
),
]
)()[-1]
)

night quarryBOT
#

@astral rover :white_check_mark: Your eval job has completed with return code 0.

001 | 7
002 | 91
003 | 83
004 | 74
005 | 60
006 | 61
007 | 8
008 | 55
009 | 58
010 | 75
astral rover
#

there we go

#

just pretend i didnt format that

last locust
#
print([globals().__setitem__('_', 10), '\n'.join(map(str, map(__import__('\x72\x61\x6e\x64\x6f\x6d').choice, [[x for x in map(str, range(-~int(), -~(_).__pow__(2)))] for __ in range(_)])))][~-int()])
```this is what I've got from your `globals().__setitem__(...)`
#

Just need to replace 10 with the esoteric thing

sudden willow
#

this is a quirky channel

last locust
#

!e py print([globals().__setitem__('_', ~-~-(-~-~-~-~int()).__pow__(-~-~int()).__sub__((-~-~int()).__pow__(-~-~int()))), '\n'.join(map(str, map(__import__('\x72\x61\x6e\x64\x6f\x6d').choice, [[x for x in map(str, range(-~int(), -~(_).__pow__(-~-~int())))] for __ in range(_)])))][~-int()])

night quarryBOT
#

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

001 | 32
002 | 76
003 | 11
004 | 100
005 | 13
006 | 96
007 | 40
008 | 57
009 | 38
010 | 86
last locust
#

Nice

#

Pretty happy with that

last locust
sudden willow
#

!e
eval(eval(__import__("base64").b64decode("cHJpbnQoJ0hlbGxvLCB3b3JsZCEnKQ==")))

night quarryBOT
#

@sudden willow :x: Your eval job has completed with return code 1.

001 | Hello, world!
002 | Traceback (most recent call last):
003 |   File "<string>", line 1, in <module>
004 | TypeError: eval() arg 1 must be a string, bytes or code object
sudden willow
#

sad

#

!e
(eval(__import__("base64").b64decode("cHJpbnQoJ0hlbGxvLCB3b3JsZCEnKQ==")))

night quarryBOT
#

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

Hello, world!
sudden willow
#

ao eval waits for the process in between the quotes to take place before evaluating?

#

quirky

astral rover
#

thats how all python works

sick hound
#

hey guys

#

i made hangman in one line >:)

bold jolt
#

Hello.

sick hound
#

hi lol

sick hound
#

Why thank you @frozen holly

frozen holly
#

i would ask how it works but i have a headache rn so it prolly wouldnt be the best idea

sick hound
#

I could explain a few parts to how i managed to fit it in one line

#

The main thing is nested lambdas that i declare with the := walrus operator which let me do recursion

#

This is because you cant have while loops inline

#

Simple one for using imports inline is the import(‘whatever’)

#

Meant to be __ import __

#

Bruh discord is underlining it

#

2 underscores before and after import

#

Theres a lot more to it ofcourse but yeah those are some parts to how i did it

frozen holly
#

((use __import__))

sick hound
#

Yes

#

That

frozen holly
#

done `__import__`

sick hound
#

So u can use libraries inline with that

rugged sparrow
#

@sick hound you can use [*iter(func, flag)] to do infinite loops inline. It calls func (and yields its result) until the result equals the flag

#

That won't use recursion so it's actually infinite

sick hound
#

Oh my god

#

Thats amazing but wait

#

Can you stop loop on condition??

#

@rugged sparrow

#

Wait i may be stupid could you explain how the flag works

rugged sparrow
#

Flag is any value

sick hound
#

Okay

rugged sparrow
#

So like [*iter(int,1)] would loop infinitely

sick hound
#

Okay

#

So is whatever the func returns compared to flag and if it matches it breaks?

rugged sparrow
#

Yes

sick hound
#

Okay okay i get it

#

This could come in very handy for any future inline algorithm i work on

#

Thanks man

rugged sparrow
#

No prob

#

I also have ways to do exceptions inline too

sick hound
#

Wdym

#

Show me the way

rugged sparrow
#

Like try/except

#

You use contextdecorators

sick hound
#

I mean like how

#

I must see

#

Lmaoo

#

Mention me if possible so i see thanks man

rugged sparrow
#

@sick hound ^

#

That's an old implementation but it should still work

sick hound
#

Woah

#

This may be beyond me

astral rover
#

I thought you were just gonna use contextlib lol

rugged sparrow
#

It sorta does @astral rover

sick hound
#

If theres a lib for it then you could use the inline import right

astral rover
#

Yeah

rugged sparrow
#

But I added some stuff to make it more modular

#

@sick hound that code uses context lib

sick hound
#

Right right

rugged sparrow
#

It creates a decorator that works like with

sick hound
#

You see with me im pretty decent at using the syntax of inline coding but this kind of stuff is next level

#

If that makes sense

rugged sparrow
#

When I get home I'll ping you with my newer version of inline try except

sick hound
#

Yes please 🙏

#

If you can do stuff like this inline

#

In theory you could pretty much make any program inline

rugged sparrow
#

You definitely can

#

Some are more difficult but all are possible

sick hound
#

What do you think i should try make inline next

#

Considering ive made a couple sort algorithms and hangman already

rugged sparrow
#

Well I made minesweeper in one line once

#

Try for that

sick hound
#

Now you see i would try that except ive never played mine sweeper so i dont even know how it works lmaoo

#

And after making hangman inline

rugged sparrow
#

Gotta research it then lol

sick hound
#

Ive realised how much it hurts to put together a game inline

#

Do you think quicksort would be a good challenge to implement inline or is it easier than merge sort

rugged sparrow
#

Just try it

sick hound
#

Will do

rugged sparrow
#

If it ends up being easy, make it smaller

sick hound
#

Good idea actually

#

Ive just been thinking of one liners working

#

But making them as short as possible would be an interesting challenge

rugged sparrow
#

Ooh write tic tac toe

#

As small as possible

sick hound
#

Thats a good one

#

Ive always struggled with finding when someone has won programatically without a bunch of ifs

rugged sparrow
#

I'll send my implantation when I get home

#

It uses a map of indexes and all()

sick hound
#

Great thanks man

#

Ill definitely get into this and really try understand your code tomorrow, its past midnight for me now though so ill let my mind rest for now

sick hound
#

i made a one line discord bots with one command and an event once

#

not nearly as impressive as what u guys do but

rugged sparrow
#

@sick hound py try_ = lambda t, *a, f=lambda a:a, e=Exception, **k,:(r:={}).pop( 'r', type( '', (__import__('contextlib').ContextDecorator,), { '__enter__':int, '__exit__':lambda s,*a:isinstance( a[1], e ) and [r.update( r=f(a) )] } )()(t)(*a, **k) ) my newest try/except (t is try func, *a is args to try func, f is except func (passed tuple of exc_type, exc, traceback), e is what exceptions are caught (can be one or tuple of exc_types), and k is kwargs to try func)

formal sandal
#

maybe name it try_, to comply with PEP 8

#

@rugged sparrow

rugged sparrow
#

there now it follows pep8 perfectly

formal sandal
#

👍

#

Mapping while unpacking. Now you can unpack and change the value at the same time. However, only works then the assignment target is a local variable.

rugged sparrow
#
[b:={}.fromkeys('012345678',' '),*iter(lambda:[[*iter(lambda:b.update({i:a})if(i:=input(a+':'))in(b)and b.get(i)==' 'else 1,[print(*['|'.join(l[i:i+3])for(i)in[0,3,6]],sep='\n')for(l)in zip(*b.items())][0])]for(a)in'xo']and((c:=([r.pop()for(r)in[{*[*b.values()][slice(*[*map(int,str(ord(c)))][::-1])]}for(c)in'\x1e?`ƆƇƈǪĚ']if len(r)==1and{' '}^r]or[None])[0])and bool(print(c,'wins'))),False)]
``` @sick hound heres a tictactoe too
verbal totem
#

!e

import math
i = -math.inf
while i < 0:
    continue
thorny fern
#

still running

sick hound
#

Oh my @rugged sparrow

#

Thats crazy

rugged sparrow
#

thanks

#

lmk if you want me to explain anything

sick hound
#

Wait, what happends if there's input with the bot

#

!e

[b:={}.fromkeys('012345678',' '),*iter(lambda:[[*iter(lambda:b.update({i:a})if(i:=input(a+':'))in(b)and b.get(i)==' 'else 1,[print(*['|'.join(l[i:i+3])for(i)in[0,3,6]],sep='\n')for(l)in zip(*b.items())][0])]for(a)in'xo']and((c:=([r.pop()for(r)in[{*[*b.values()][slice(*[*map(int,str(ord(c)))][::-1])]}for(c)in'\x1e?`ƆƇƈǪĚ']if len(r)==1and{' '}^r]or[None])[0])and bool(print(c,'wins'))),False)] 
night quarryBOT
#

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

001 | 0|1|2
002 | 3|4|5
003 | 6|7|8
004 |  | | 
005 |  | | 
006 |  | | 
007 | x:Traceback (most recent call last):
008 |   File "<string>", line 1, in <module>
009 |   File "<string>", line 1, in <lambda>
010 |   File "<string>", line 1, in <listcomp>
011 |   File "<string>", line 1, in <lambda>
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/gulonugeli.txt

sick hound
#

Hmm

elfin onyx
#

esoteric python

sudden willow
#

!e
_=lambda _: (print(1)if(_)is(1)else(print(2))) _(int(True))

night quarryBOT
#

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

001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | 1
sudden willow
#

pog

sick hound
#

Is there a way to change what line is being executed using sys or something?

#

For example,

#
1. print(...)
2. ...
3. ...
4. redirect_to(1)
#

Here, when line 4 is executed, the program will go back to line 1

#

Is that somehow possible?

astral rover
#

You could probably using sys._getframe

next flame
rugged sparrow
sick hound
#

Woah, that’s amazing. Could you give a summary of what it does?

flint briar
#

That kind of GOSUB coding is called "Spaghetti Code" because it makes code into unrecognisable pasta

#

You are a wee bit new to programming aye? What you are actually after I think is called a 'Loop'.

#

There is no situation in the world where GOTO/GOSUB is ever ever ever... Ever... Ever a good idea.

#

🍝

#

Here's a cool wee thing that might help a bit. It's called a 'while' loop.

#

while True : print(...)

#

It will print infinitely.

#

@sick hound

rugged sparrow
#

@sick hound it modifies the byte code to insert jumps to specified labels

twilit grotto
earnest wing
#

@flint briar lol, "unrecognizable pasta" is warmly welcome here. Especially if it's "never ever a good idea"

#

now, back to my one-line hangman command-line game

verbal totem
#

Has anybody worked on a int to word form string converter?

#

I'm curious on how to put it all on one line, seeing that is a common theme here in #esoteric-python

sudden willow
formal sandal
sudden willow
#

!e
_=lambda _: (print(1)if(_)==(1)else(print(2))) _(int(True)if(__import__("sys").argv[1])==(1)elif(__import__("sys").argv[1])==(2)int(False)elif(__import__("sys.argv[1]!=(1 or 2)print(__import__("sys.argv[1]")

night quarryBOT
#

@sudden willow :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 2
002 |     _(int(True)if(__import__("sys").argv[1])==(1)elif(__import__("sys").argv[1])==(2)int(False)elif(__import__("sys.argv[1]!=(1 or 2)print(__import__("sys.argv[1]")
003 |                                                  ^
004 | SyntaxError: invalid syntax
sudden willow
#

line 3??

#

oh wait im dumb

#

_=lambda _: (print(1)if(_)==(1)else(print(2))) _(int(True)if(__import__("sys").argv[1])==(1)elif(__import__("sys").argv[1])==(2)int(False)elif(__import__("sys")gv[1]!=(1 or 2)print(__import__("sys").argv[1])

next flame
#

missing a bunch of parens

#

__import__("sys")gv[1] uhhh

twilit grotto
#

you also can't inline elif like that

sudden willow
proper vault
#

I have a challenge. Make a program in which await (yield) is used to accomplish something useful.

astral rover
#

Is the default use case not good enough?

distant wave
#

!e ```py
class A: ...
class B: ...
classes = [A, B]
class C(*classes):
...

night quarryBOT
#

@distant wave :warning: Your eval job has completed with return code 0.

[No output]
distant wave
#

And stealing from @formal sandal

#

!e ```py
class Foo(metaclass=print):
...

night quarryBOT
#

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

Foo () {'__module__': '__main__', '__qualname__': 'Foo'}
astral rover
#

why does that print Foo.__class__.__new__'s args?

formal sandal
#

@distant wave well, I stole it from someone else

#

not my idea

proper vault
#

any function can be a metaclass

astral rover
#

when that calls print.__new__ does that do print?

proper vault
#

it doesnt do __new__, it does __call__

astral rover
#

right

#

that makes slightly more sense

#

so what the metaclass kwarg does is just call the objects __call__ with name bases attrs and kwargs

proper vault
#

!e
and all other kwargs

class A(metaclass=print, end=' is the thing', sep=','):
    pass
night quarryBOT
#

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

A,(),{'__module__': '__main__', '__qualname__': 'A'} is the thing
tribal moon
#

is there a way to do that but onelined using type

proper vault
#

not really

#

it would just be

print('A',(),{'__module__': '__main__', '__qualname__': 'A'}, end=' is the thing', sep=',')
tribal moon
#

oh

sudden willow
#

!e
print(True.__int__())

night quarryBOT
#

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

1
sudden willow
#

quirky

proper vault
#

I mean, int(True) is 1

sudden willow
#

yea i just now learned how to use __int__

thin trout
#

I didn’t know that was a dunder

#

It makes sense when you think about it

charred hill
astral rover
#

im pretty sure your're returning print's return

charred hill
#

oh wait im dumb

marsh void
#

not an error, it is a singleton, to those who don't know

earnest wing
#

NotImplemented / NotImplementedError trips up a lot of folks

elfin onyx
#

it means pass

earnest wing
#

Means the same thing Ellipsis does

#

In the context it does nothing

snow beacon
#

It's like putting class A: 0, except it's an ellipsis.

distant wave
#

It's an ellipsis. Useful as a placeholder as well as for interesting syntax when applicable, such as
a[1:, ...] for numpy, or something like Tuple[int, ...] for typing

thin trout
#

I personally also use it instead of pass when the function body hasn't been written yet, but will be filled with something

earnest wing
#

Anything that is supposed to exist but is being omitted.

#

Being an expression, it's easy to fulfill this.

boreal slate
#

oh ok.

terse mortar
#

How should I make this a one liner? ```py
all = [i for i in str.dict if i.startswith("") and i.endswith("")]

all = all + [i1 for i1 in builtins.dict if i1.startswith("") and i1.endswith("")]

all = all + [i2 for i2 in globals() if i2.startswith("") and i2.endswith("")]

all = all + [i3 for i3 in type.dict if i3.startswith("") and i3.endswith("")]

for c in all:
if int(all.count(c)) >= 2:
all.remove(c)

all.sort(key=lambda letter: letter.split(" ")[-1])

print(all)


Also yeah ik this might not be the best code, and I'm still probably missing a few dunders, but it's fine. I just need some help making this a one liner
cinder cradle
snow beacon
#

That's two lines, but you could probably make the printing a side effect of the assignment.

slim echo
#

print(__all__:=...)

sick hound
#

Can someone please help me

#

Selenium doesnt work

last locust
terse mortar
#

!e ```py
print(all:= sorted({i for data in [str.dict, builtins.dict, globals(), type.dict] for i in data if i.startswith("") and i.endswith("")}, key=lambda letter: letter.split(" ")[-1]))

night quarryBOT
#

@terse mortar :white_check_mark: Your eval job has completed with return code 0.

['__abstractmethods__', '__add__', '__annotations__', '__base__', '__bases__', '__basicsize__', '__build_class__', '__builtins__', '__call__', '__contains__', '__debug__', '__delattr__', '__dict__', '__dictoffset__', '__dir__', '__doc__', '__eq__', '__flags__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__import__', '__init__', '__instancecheck__', '__itemsize__', '__iter__', '__le__', '__len__', '__loader__', '__lt__', '__mod__', '__module__', '__mro__', '__mul__', '__name__', '__ne__', '__new__', '__package__', '__prepare__', '__qualname__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__spec__', '__str__', '__subclasscheck__', '__subclasses__', '__text_signature__', '__weakrefoffset__']
terse mortar
#

Cool

snow beacon
#

I was thinking assigning it normally, but passing the result through some lambdas that also send it to print. This way is probably easier.

#
also_print = lambda x: print(x) or x
```This sort of thing.
harsh mesa
#

hey does anyone know anything about artificial intelligence?

next flame
#

wrong channel?

harsh mesa
#

thank you

boreal slate
#
a=lambda y:sum(x for x in range(1,y)if y%x==0)
print(y==a(a(y))and a(y)!=y)
``` any way to shorten this?
tiny hazel
#

@boreal slate This code checks go see if a number is the sum of the divisors of the sum of its divisors and also not the sum of its divisors? Including 1 as a divisor

boreal slate
#

Amicable Numbers , yeah

tiny hazel
#

@boreal slate Hmm maybe try changing the last line to print(y == a(a(y)) != a(y))

boreal slate
#

!e

y=5020
a=lambda y:sum(x for x in range(1,y)if y%x==0)
print(y==a(a(y))and a(y)!=y)```
night quarryBOT
#

@boreal slate :white_check_mark: Your eval job has completed with return code 0.

True
boreal slate
#

!e

y=496
a=lambda y:sum(x for x in range(1,y)if y%x==0)
print(y == a(a(y)) != a(y))```
night quarryBOT
#

@boreal slate :white_check_mark: Your eval job has completed with return code 0.

False
boreal slate
#

hmm

#

works

proper vault
#

there is a direct formula for this

#

or maybe not, slightly misread it

tiny hazel
#

You can do sum(x * (not y%x)

#

That saves a few chars I think

#

@boreal slate

#

and remove the if y%x == 0

boreal slate
#

!e

y=496
a=lambda y:sum(x*(not y%x)for x in range(1,y))
print(y==a(a(y))!=a(y))```
night quarryBOT
#

@boreal slate :white_check_mark: Your eval job has completed with return code 0.

False
tiny hazel
#

!e

night quarryBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

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

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

tiny hazel
#

@boreal slate I feel like to make it smaller than that you need a drastically different implementation or formula

#

Or some fancy tricks I don’t know

boreal slate
#

i dunno of any formula, also yours makes it too slow

#

the x*(not x%y) one

tiny hazel
#

Yea it does make it slower. It’s not a good idea just one tht makes it shorter lol

#

like code golf

boreal slate
#

probably walrus can do the trick

earnest wing
#

replace not x%y with x%y<1 to save 2 bytes

elfin onyx
#

total byte saved count = 3

tiny hazel
#

haha if this keeps going it wont be readable soon

earnest wing
#

steal answer from elsewhere to save a few more bytes:

a=lambda y,i=1:i<y and(y%i<1)*i+f(y,i+1)
#

(requires sys.setrecursionlimit for higher N)

#

!e ```py
y=202
a=lambda y,i=1:i<y and(y%i<1)*i+f(y,i+1)
print(y==a(a(y))!=a(y))

night quarryBOT
#

@earnest wing :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 |   File "<string>", line 2, in <lambda>
004 | NameError: name 'f' is not defined
earnest wing
#

!e ```py
y=202
a=lambda y,i=1:i<y and(y%i<1)*i+a(y,i+1)
print(y==a(a(y))!=a(y))

night quarryBOT
#

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

False
earnest wing
#

or not

#

oh, oops

#

!e ```py
y=220
a=lambda y,i=1:i<y and(y%i<1)*i+a(y,i+1)
print(y==a(a(y))!=a(y))

night quarryBOT
#

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

True
earnest wing
#

there, that's at least 3 more bytes down

#

this will fail, though:

#

!e ```py
y=5020
a=lambda y,i=1:i<y and(y%i<1)*i+a(y,i+1)
print(y==a(a(y))!=a(y))

night quarryBOT
#

@earnest wing :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 |   File "<string>", line 2, in <lambda>
004 |   File "<string>", line 2, in <lambda>
005 |   File "<string>", line 2, in <lambda>
006 |   [Previous line repeated 996 more times]
007 | RecursionError: maximum recursion depth exceeded in comparison
earnest wing
#

yeeeeah

#

it happens

#

it works for sufficiently high N

tiny hazel
#

That implementation is genius how did you do/find it. @earnest wing

earnest wing
#

by searching for "code golf sum of divisors", clicking the relevant stackexchange link and ctrl-f "python" to find a solution (that I tweaked because it didn't actually work)

tiny hazel
#

Wait I just understood the code

#

Now it seems even more genius

earnest wing
#

It's effectively wrapping the sum in N layers of recursion

tiny hazel
#

That’s so creative, and it can be applied to any function of ints to reduce a conditional list of ints

earnest wing
#

Pretty much, yeah - also works to reduce sequences using other functions as well (*, etc)

tiny hazel
#

yea exactly so clever

#

wait lemme try to rewrite

#

a = lambda y, i=1: i<y and (condition)*f(i, a(y, i+1))

#

Exploiting the fact that and short circuits is such a nice touch

earnest wing
#

Yes, that's the general form

#

A very neat way to reduce+filter :)

sick hound
#

hey can anyone help me with a one liner problem i have

#

im making a fibonacci function using memoization and recursion and need to set a dict called cache as global

#

ive got it down to 2 lines so far

#
cache = {}
print( (fib_memo_inline := lambda n, store=lambda value, n : cache.update({n:value}) or value : cache[n] if n in cache else ((value := 1) if n <= 2 else store(value = fib_memo_inline(n-1) + fib_memo_inline(n-2), n=n) ))(10) )
#

it works fine but i need to get it into one line

thin trout
#

What if you put getattr(locals(), 'cache', cache := {}) instead of the first evaluated cache?

#

@sick hound ^

terse mortar
#

or use __setattr__

sick hound
#

hmm lemme try that

#

ive been trying to use globals().setitem

#

done!

#

thanks for the help

#
( getattr(locals(), 'cache', cache := {}), (fib_memo_inline := lambda n, store=lambda value, n : cache.update({n:value}) or value : cache[n] if n in cache else ((value := 1) if n <= 2 else store(value = fib_memo_inline(n-1) + fib_memo_inline(n-2), n=n) ))((n := int(input('Enter term number: ')))), __import__("sys").stdout.write(f'{cache[n]}') )
terse mortar
#

Cool!

sick hound
#

thanks!

short crag
#
(
    (
        lambda __, ___, ____, _____: getattr(
    __builtins__,
    ().__class__.__name__[__ << __]
    + ().__iter__().__class__.__name__[(__).__rmul__(-1)]
    + [].__class__.__name__[____ % ___]
    + chr(_____)
    + ().__class__.__name__[__ >> __],
        )
    )(
        (lambda _: _).__code__.co_nlocals,
        (lambda _, __: _ | __).__code__.co_nlocals,
        (lambda _, __, ___: _ | __ | ___).__code__.co_nlocals,
        (
    (lambda _, __, ___: _ & __ & ___).__code__.co_nlocals.__rmul__(
        (lambda _, __, ___: _ | __ | ___).__code__.co_nlocals
    )
    + (True.__rmul__((lambda _, __: _ | __).__code__.co_nlocals))
        ).__rmul__(
    (
        lambda _, __, ___, ____, _____, ______, _______, ________, _________, __________:
    _
    ).__code__.co_nlocals
        ),
    )
)(
    (
        lambda __, ___, ____, _____, ______: hex.__class__.__name__[
    ___.__rmul__(____ * _____) - ______
        ].upper()
        + hex.__class__.__name__[___.__rmul__(____ * _____) - _____ - ______]
        + hex.__class__.__name__[___] * 2
        + hex.__class__.__name__[___.__rmul__(____ * _____)]
        + chr(__.__rmul__(___) + _____)
        + Warning.__qualname__[______ - True]
        + hex.__class__.__name__[___.__rmul__(____ * _____)]
        + Warning.__qualname__[_____]
        + ().__class__.__name__[___]
        + {}.__class__.__name__[______ - True]
        + chr(__.__rmul__(___) + ___)
    )(
        (
    lambda _, __, ___, ____, _____, ______, _______, ________, _________, __________: (
        _
    )
        ).__code__.co_nlocals,
        (lambda _, __, ___: _).__code__.co_nlocals,
        (lambda _, __, ___, ____: _).__code__.co_nlocals,
        (lambda _, __: _).__code__.co_nlocals,
        (lambda _: _).__code__.co_nlocals,
    )
)
```can some explain how this works? Someoe gave it to me and it prints `Hello World!`
cyan valley
short crag
#

can you explain some?

cyan valley
short crag
#

Yeah....

tribal moon
#

I wrote that code

#

I know how it works

#

I'll explain in a sec

short crag
#

uh huh

terse mortar
#

Let some dude explain

short crag
#

ok

terse mortar
#

There is a good chance that he indeed did write it

short crag
#

but the dude that dmmed me wrote it

terse mortar
#

Or you can paste the code in an ide, and use the inspect feature

tribal moon
#

well the code shows up here and there once in a while

#

But I'm the one who wrote it

#

I think it was like 5 months ago or more

cyan valley
#

Can anyone write a python code that prints a sentence in inverse position

short crag
#

@fossil estuary wrote that code

terse mortar
cyan valley
#

for example ; I'm from England answer: dnalgne morf m'I

terse mortar
#

You most definitely do not want help from this channel.

short crag
#

sooooooo

twilit grotto
#

yes...for the esoteric code

terse mortar
#

You got told to come here for that specific code. This has gotten way off topic now

twilit grotto
#

not for help

short crag
#

I just wanted to know

#

how it works

twilit grotto
short crag
#

or something

#

!e

(
    (
        lambda __, ___, ____, _____: getattr(
    __builtins__,
    ().__class__.__name__[__ << __]
    + ().__iter__().__class__.__name__[(__).__rmul__(-1)]
    + [].__class__.__name__[____ % ___]
    + chr(_____)
    + ().__class__.__name__[__ >> __],
        )
    )(
        (lambda _: _).__code__.co_nlocals,
        (lambda _, __: _ | __).__code__.co_nlocals,
        (lambda _, __, ___: _ | __ | ___).__code__.co_nlocals,
        (
    (lambda _, __, ___: _ & __ & ___).__code__.co_nlocals.__rmul__(
        (lambda _, __, ___: _ | __ | ___).__code__.co_nlocals
    )
    + (True.__rmul__((lambda _, __: _ | __).__code__.co_nlocals))
        ).__rmul__(
    (
        lambda _, __, ___, ____, _____, ______, _______, ________, _________, __________:
    _
    ).__code__.co_nlocals
        ),
    )
)(
    (
        lambda __, ___, ____, _____, ______: hex.__class__.__name__[
    ___.__rmul__(____ * _____) - ______
        ].upper()
        + hex.__class__.__name__[___.__rmul__(____ * _____) - _____ - ______]
        + hex.__class__.__name__[___] * 2
        + hex.__class__.__name__[___.__rmul__(____ * _____)]
        + chr(__.__rmul__(___) + _____)
        + Warning.__qualname__[______ - True]
        + hex.__class__.__name__[___.__rmul__(____ * _____)]
        + Warning.__qualname__[_____]
        + ().__class__.__name__[___]
        + {}.__class__.__name__[______ - True]
        + chr(__.__rmul__(___) + ___)
    )(
        (
    lambda _, __, ___, ____, _____, ______, _______, ________, _________, __________: (
        _
    )
        ).__code__.co_nlocals,
        (lambda _, __, ___: _).__code__.co_nlocals,
        (lambda _, __, ___, ____: _).__code__.co_nlocals,
        (lambda _, __: _).__code__.co_nlocals,
        (lambda _: _).__code__.co_nlocals,
    )
)
night quarryBOT
#

@short crag :white_check_mark: Your eval job has completed with return code 0.

Hello World!
tribal moon
#

when we have a function for example a lambda, we can give them arguments, for example ```py

(lambda _, __, ___: None).code.co_nlocalsgives us 3 because the function has 3 parameters Let's look at this linepy
lambda __, ___, ____, _____, ______: hex.class.name[```
This function takes in 5 parameters, they're just underscores to give the more esoteric feeling, the underscores, _, __, ___, ____, _____, are supposed to be integers, which we will use to slice strings of class names of builtins, for example, the most common one used here seems to be hex because it has the __self__ attribute.

Let's examine one of the lines inside that function: py hex.__class__.__name__[___.__rmul__(____ * _____) - _____ - ______], now let's substitute the underscores with numbers

hex.__class__.__name__[(3).__rmul__(4 * 2) - 2 - 1]```, this gives us the string `e`, which then adds it to the next one, `l`
#

and then you can do the rest

#

it's easier to understand when you substitute the underscore parameters with numbers

short crag
#

ohhh

tribal moon
#
>>> hex.__class__.__name__
'builtin_function_or_method'``` we're slicing strings like these
#

we're slicing them and adding them to other sliced strings

short crag
#

that makes more sense

tribal moon
#

which then forms the Hello, World!

short crag
#

hmm, intriging

#

you made that code?

tribal moon
#

yeah

#

I made another one too

short crag
#

got any proof or anything, because a friend said they made that a little while ago and i just remmbered it and wanted to ask about it

tribal moon
#

here is the original message

short crag
#

ok

terse mortar
#

Amazing.

short crag
#

OK

#

WHOLY

tribal moon
short crag
#

he is a impostor!!!!!!

tribal moon
short crag
terse mortar
#

@tribal moon you have too much time.

tribal moon
#

lol it's all cool I love esoteric Python

short crag
#

so the thing is

#

what else has he lied about

#

thats my thing

tribal moon
#

Yeah someone else made that, I think it was a moderator?

#

check the pinned messages here

short crag
#

Not seeing anything

#

!e

p="+++++++++++++++[>++>+++>++++>+++++>++++++>+++++++>++++++++<<<<<<<-]+++++++++++++++>>>>+++++.>>----.>------.------.<<<<<<++.>>------.<<<-----."
s,a='',[0]*32;j=t=0
for i in p:s+=' '*t+'j-=1 a[j]+=1 j+=1 a[j]-=1 print(end=chr(a[j])) while+a[j]: # # # #'.split()[ord(i)%18-6]+'\n';t+=(i>'Z')-2*(i>'[')
exec(s)
night quarryBOT
#

@short crag :white_check_mark: Your eval job has completed with return code 0.

Perl 6
short crag
#

hmm

#

welp

#

@tribal moon your a excellenet coder, sorry for doubting you.

tribal moon
#

nah it's fine lol

#

that code is a monstrosity

terse mortar
#

Brainfuck in python

short crag
#

See this is what happens, I trust someone then I find out they lied to me.

sharp canyon
#

Okay, so when you define a function, it inherits from the Function class, right? Anyone have the docs for that particular class? Or am I incorrect in my thinking

formal sandal
sharp canyon
#

Ahhh

twilit grotto
#

!e

def foo():
  pass
print(type(foo))
night quarryBOT
#

@twilit grotto :white_check_mark: Your eval job has completed with return code 0.

<class 'function'>
formal sandal
sharp canyon
#

Yeah I think that's what I need

#

Was wondering what awful things you could do with it by inheriting it

formal sandal
#

@sharp canyon I'm pretty sure you can't inherit from it

astral rover
#

no you cant

sharp canyon
#

Damn

formal sandal
#

You can do horrible things with inheritance anyway 🙂

sharp canyon
#

True

#

And I suppose messing with meta methods and classes gives enough awfulness anyway

formal sandal
#

||Ellipse inheriting from Circle in manim is more unsettling to me than most hacks in here||

astral rover
#

although im pretty sure using fish hook you can add your own methods to it

formal sandal
astral rover
#

yeah

formal sandal
#

how is it different from forbiddenfruit?

astral rover
#

cause it can patch c code

formal sandal
#

can't forbiddenfruit do that?

#
>>> from forbiddenfruit import curse
>>> def words_of_wisdom(self):
...     return self * "blah "
>>> curse(int, "words_of_wisdom", words_of_wisdom)
>>> assert (2).words_of_wisdom() == "blah blah "
#

(example from the docs)

astral rover
#

hmm

broken mesa
#

probably the most likely channel to know: any idea how, given a function object, i can overwrite the code it runs with another function, without overwriting the main function object?
i tried overwriting func.__call__ and func.__init__ but neither change the outcome of calling the func

proper vault
#

@broken mesa change func.__code__

#

for a code object of a different function

broken mesa
#

ive tried that too, ValueError: f() requires a code object with 0 free vars, not 2

proper vault
#

ah, variable numbers have to match up. That does make it quite a bit more complex.

broken mesa
#

ouch, wierd tho cuz both the original and the new just have *args, **kwargs

#

even worse if the new function is a method-wrapper, dammnit

broken mesa
#

!e ```py
def overwrite_this(*args, **kwargs):
pass

def overwrite_func(original):
def decorator(func):
def decorated(*args, **kwargs):
func(original, *args, **kwargs)
print("argcount", original.code.co_argcount, original.code.co_posonlyargcount, original.code.co_kwonlyargcount)
print("argcount", decorated.code.co_argcount, decorated.code.co_posonlyargcount, decorated.code.co_kwonlyargcount)
original.code = decorated.code
return original
return decorator

@overwrite_func(overwrite_this)
def new(a, b):
print(a, b)

night quarryBOT
#

@broken mesa :x: Your eval job has completed with return code 1.

001 | argcount 0 0 0
002 | argcount 0 0 0
003 | Traceback (most recent call last):
004 |   File "<string>", line 15, in <module>
005 |   File "<string>", line 10, in decorator
006 | ValueError: overwrite_this() requires a code object with 0 free vars, not 2
formal sandal
#

@broken mesa I guess you could use ctypes to transfer all the bytes from the new function object to the old one?..

#

except the garbage collection stuff, not quite sure what it is

#

Or actually, just the free vars count. Although if it's restricted, it must be important, right

broken mesa
#

yeah it must be, but as you can see in the example both __code__objects have a arg count of 0

formal sandal
#

!e

def overwrite_this(*args, **kwargs):
    pass

def overwrite_func(original):
    def decorator(func):
        def decorated(*args, ____func=func, ____original=original, **kwargs):
            ____func(____original, *args, **kwargs)
            print("argcount", ____original.__code__.co_argcount, ____original.__code__.co_posonlyargcount, ____original.__code__.co_kwonlyargcount)
            print("argcount", decorated.__code__.co_argcount, decorated.__code__.co_posonlyargcount, decorated.__code__.co_kwonlyargcount)
            ____original.__code__ = decorated.__code__
        return ____original
    return decorator

@overwrite_func(overwrite_this)
def new(a, b):
    print(a, b)
#

hmm

night quarryBOT
#

@formal sandal :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 15, in <module>
003 |   File "<string>", line 8, in decorator
004 | NameError: name '____original' is not defined
formal sandal
#

how??

broken mesa
#

because its defined local to decorated, but youre trying to access outside of that scope

formal sandal
#

oh, c

#

!e

def overwrite_this(*args, **kwargs):
    pass

def overwrite_func(original):
    def decorator(func):
        def decorated(*args, ____func=func, ____original=original, **kwargs):
            ____func(____original, *args, **kwargs)
            print("argcount", ____original.__code__.co_argcount, ____original.__code__.co_posonlyargcount, ____original.__code__.co_kwonlyargcount)
        print("argcount", decorated.__code__.co_argcount, decorated.__code__.co_posonlyargcount, decorated.__code__.co_kwonlyargcount)
        original.__code__ = decorated.__code__
        return original
    return decorator

@overwrite_func(overwrite_this)
def new(a, b):
    print(a, b)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

argcount 0 0 2
formal sandal
#

now decorated doesn't accept a closure

broken mesa
#

OHHHHHH

formal sandal
#

oh, wait, I have an idea

broken mesa
#

thats, kinda genius

#

wait no

formal sandal
# broken mesa OHHHHHH

I found this trick in Python 2 docs, from the times when you could create inner functions, but when closures didn't exist.

broken mesa
#

try calling overwrite_this, both those kwargs are required

formal sandal
#

?

broken mesa
#

also i noticed, ideally there wouldnt need to be a return original

#

since yknow, im trying to overwrite the code object of overwrite_this

formal sandal
#

anyway, it doesn't really work here, because the decorated function could have a different number of closured variables

broken mesa
#

which is fixable by doing the same thing for it

#

like, decorate both in this way

#

if it worked

formal sandal
#

You could try overwriting the __code__.co_consts with your own objects.

broken mesa
#

decorated() missing 2 required keyword-only arguments: '____func' and '____original'

#

hmmm

formal sandal
#

🤔

#

ah. you didn't transfer the default values, I guess

broken mesa
#

i did

#

copied your block exactly

formal sandal
#

right, but my block doesn't transfer the default values to the new function 🙂

#

afaict

broken mesa
#

ahh

#

wait no

formal sandal
#

!e

def foo():
    print("hello", "world")

foo.__code__ = foo.__code__.replace(co_consts=(None, "fizz", "buzz"))
foo()
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

fizz buzz
formal sandal
#

this instead of the default kwargs should work

#

like, refer to (1,2,3,4,5) or whatever

broken mesa
#

hah got it

#

i think

#

!e ```py
def overwrite_this(a, b):
pass

def overwrite_func(original):
def decorator(func):
def decorated(*args, ____func=func, ____original=original, **kwargs):
____func(*args, **kwargs)
original.code = decorated.code
original.kwdefaults = decorated.kwdefaults
return original
return decorator

@overwrite_func(overwrite_this)
def new(a, b, c):
print(a, b, c)

overwrite_this(1, 2, 3)

#

HECC YEA

night quarryBOT
#

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

1 2 3
broken mesa
#

thanks for your help, fix error

#

same goes for lakmatiol

formal sandal
#

!e

def overwrite_this(*args, **kwargs):
    pass

def overwrite_func(original):
    def decorator(func):
        def decorated(*args, **kwargs):
            a = 'argcount'
            f = 'fizz'
            f(*args, **kwargs)
        original.__code__ = decorated.__code__.replace(co_consts=(None, 'argcount', func))
        return original
    return decorator

@overwrite_func(overwrite_this)
def new(a, b):
    print(a, b)

overwrite_this(1, 2)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

1 2
broken mesa
#

this is so incredibly awfull its putting a big dumb grin on my face

formal sandal
#

just to demonstrate what I meant

#

now oneline it

broken mesa
#

😢

#

no

twilit grotto
#

it must be done

broken mesa
#

you can if you want

craggy sundial
formal sandal
#

The bytecode would look... pretty normal?

terse mortar
#

Time to spend 3 hours making a cursed one liner!

formal sandal
#

@craggy sundial

craggy sundial
broken mesa
craggy sundial
#

Assembler gives a shit about decorators and stuff. Correct me if I am wrong @formal sandal

formal sandal
#

wdym?

broken mesa
#

arent decorators just syntactic sugar? wouldnt matter to the assembly in that case..

formal sandal
#

yeah, a decorator is just a function call

#

If the decorator returns a new function, then yes, it might be a bit puzzling

broken mesa
#

well no

#

it would be the same assembly as f = decorator(f)

formal sandal
#

yes, of course

#

but a decorator often creates a new function that captures the old one in a closure

craggy sundial
#

Or at least make a call

formal sandal
#

!e

overwrite_func=lambda o:lambda f:(d:=lambda *a,**k:(u:='fizz',u(*a,**k))[1],setattr(o,'__code__',d.__code__.replace(co_consts=(None,f,1))),o)[2]

def overwrite_this(*args, **kwargs):
    pass

@overwrite_func(overwrite_this)
def new(a, b):
    print(a, b)

overwrite_this(1, 2)
#

done

#

well...

#

eh

#

the warning

#

lmao

night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

1 2
craggy sundial
#

Whats happening? 😄

formal sandal
#

the second version gave correct output, but also made a segfault

craggy sundial
#

oof

broken mesa
#

ooooof

#

anyways, one step closer to being able to convert a function object into a class

formal sandal
#

wait, I think it fits here

#

!e

import ast
import inspect
from textwrap import dedent
def namespace(*, fn=lambda x: x):
    frame = inspect.currentframe().f_back
    def _namespace(function_to_hack_open):
        nonlocal _namespace
        _namespace.__name__ = f"namespace({function_to_hack_open.__name__}"
        source = dedent(inspect.getsource(function_to_hack_open))
        tree = ast.parse(source)
        glob = frame.f_globals
        names_before = set(glob.keys())
        tree.body = tree.body[0].body
        exec(
            compile(
                tree,
                f"<namespace{function_to_hack_open.__name__}>",
                "exec"),
            glob
        )
        names_after = set(glob.keys())
        new_keys = names_after - names_before - {"local_names_before"}
        return {key: fn(glob[key]) for key in new_keys}
    return _namespace


ANSWER = 42


@namespace()
def fruits():
    apple = ANSWER

    banana = apple + 5

    def orange():
        return ANSWER


print(fruits)

print(fruits["orange"]())
broken mesa
#

ideally i would like to have it work with stdlib

formal sandal
#

crap

#

Well, it outputs

{'apple': 42, 'orange': <function orange at 0x7f28748f95e0>, 'banana': 47}
42

@broken mesa

broken mesa
#

yeah i looked at the repl

formal sandal
#

It works like a class, with one caveat:

#

!e

class Foo:
    a = [1, 2, 3]
    b = [x**2 for x in a]
print(Foo().b)
#

huh 🤔

broken mesa
#

you didnt print anything

night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

[1, 4, 9]
formal sandal
#

wait, I think I got the wrong example

#

ah, yes

#

!e

class Foo:
    a = 1
    b = [a**2 for _ in range(3)]
night quarryBOT
#

@formal sandal :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 3, in Foo
004 |   File "<string>", line 3, in <listcomp>
005 | NameError: name 'a' is not defined
formal sandal
#

this^

#

but in my namespace, it would work

sick hound
#

Interesting way to implement namespace

#

Some weeks ago, I was doing the same, but I didn’t think about using a decorator

#

I was using a context manager instead, and trying to use sys._getframe to get the objects and put them in a class

#

The only problem is, I didn’t know how to delete the objects so they don’t go into global scope

#

Chilaxan talked about using ctypes to modify objects in frames IIRC, but haven’t gotten the time to look into that

tribal moon
night quarryBOT
#

Hey @tribal moon!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

tribal moon
#

yeah sorry

#

Idk if it is going to work for everyone else

#

hey why hasn't the bot reacted with trash can

#

it's a rickroll thing

terse mortar
tribal moon
#

it opens one

terse mortar
#

That's sick

tribal moon
#

It's automatic

#

it generates the thing automatically

#

maybe I should post it on my github

sick hound
#

oh wow it does

terse mortar
#

What an absolute chad

rugged sparrow
#

@sick hound another idea for namespaces with context managers is to grab a copy of the current local space, then compare to the space after the context (in exit)

rugged sparrow
#

!e ```py
import sys

class namespace:
def enter(self):
self.actual = sys._getframe(1).f_locals
self.vars = self.actual.copy()
return self

def __exit__(self, *exc):
    self.env = {}
    for key, value in self.actual.items():
        if value is self:
            self.vars[key] = value
        elif key not in self.vars or value is not self.vars[key]:
            self.env[key] = value
    self.actual.clear()
    self.actual.update(self.vars)

def __getitem__(self, key):
    return self.env[key]

def __repr__(self):
    return f'{type(self).__name__}({self.env})'

outer_scope = 'OuterScope'

with namespace() as values:
a = 1
b = 2
outer_scope = 'InnerScope'

print(values, outer_scope)```

night quarryBOT
#

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

namespace({'outer_scope': 'InnerScope', 'a': 1, 'b': 2}) OuterScope
sick hound
#

Ah, that’s interesting, I totally forgot about .clear

#

This is actually much easier than what I did, need to take a good look at the frame objects’ attributes

rugged sparrow
#

!e ```py
import sys

class namespace:
def init(self, env=None):
self.env = env or {}

def __enter__(self):
    self.actual = sys._getframe(1).f_locals
    self.vars = self.actual.copy()
    self.actual.update(self.env)
    return self

def __exit__(self, *exc):
    for key, value in self.actual.items():
        if value is self:
            self.vars[key] = value
        elif key not in self.vars or value is not self.vars[key]:
            self.env[key] = value
    self.actual.clear()
    self.actual.update(self.vars)

def __getitem__(self, key):
    return self.env[key]

def __repr__(self):
    return f'{type(self).__name__}({self.env})'

e = namespace()
e.enter()
inside_namespace = 1
e.exit()
print(e)
print(inside_namespace)

night quarryBOT
#

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

001 | namespace({'inside_namespace': 1})
002 | Traceback (most recent call last):
003 |   File "<string>", line 33, in <module>
004 | NameError: name 'inside_namespace' is not defined
rugged sparrow
#

@sick hound this also lets stuff like that work

sudden willow
#

not really esoteric but program to write equations like print(True.__add__(True.__add__(...)))

#
import sys

with open("writeoff.txt", "w") as f:
  temp = int(sys.argv[1])-2
  f.write("print(True.__add__(")

  for i in range(temp):
    f.write("True.__add__(")
  f.write(f"True" + ")" * int(temp+2))
snow beacon
floral meteor
#

!e ```py

this should print d

p="++++++++++[>++++++++++<-]>."
s,a='',[0]*32;j=t=0
for i in p:s+=' 't+'j-=1 a[j]+=1 j+=1 a[j]-=1 print(end=chr(a[j])) while+a[j]: # # # #'.split()[ord(i)%18-6]+'\n';t+=(i>'Z')-2(i>'[')
exec(s)

night quarryBOT
#

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

d
floral meteor
#

AAAAAAAAAAAAAAA

serene nacelle
#
if x <= y:
  pass

What could one set x to, to have the expression always evaluate to be false?
y is an int and has a range from 0 and up.

I found that:

False > y

is always false, but that does not work in my use-case.

If one could put an expression into a variable, which I dont believe is possible one could do:

if not False <= y:

which is also always false.

#

I could put x to the an insanely large number, and it would probably work for my code, but that feels like a bad solution.

clever rivet
#

I would do x = float("inf"), @serene nacelle .

serene nacelle
#

it works!

#

I was leaning towards setting x to None and have:

if x and x <= y:
    pass
#

would there be any difference in performance?

#

it might be called quite a few times per second

#

like 1200 times per second ish

stark fable
#

If one could put an expression into a variable, which I dont believe is possible one could do:

if not False <= y:

which is also always false.
that's not just "putting an expression into a variable", that's performing a substitution and then forcing the code to be reparsed to re-evaluate operator precedence

#

not False <= y is not (False <= y)

#

"putting an expression in a variable" like that isn't just impossible, it's necessarily meaningless because any sensible value can be passed to a C function which cannot be forcibly recompiled by a bizarre value to re-evaluate operator precedence in a weird mix of C and Python

#

and even if you write a C decompiler it cannot possibly make any sense to pass an expression and have it behave like that into a function that was originally written in assembly

#

@serene nacelle

#

tl;dr: it wouldn't mean anything to put an expression in a variable, it only means anything with a flawed model of how code works and what code is

serene nacelle
#

@stark fable That makes a lot of sense.
Still learning and python has surprised me with the likes of the walrus operator before.

sudden willow
#

i like scrolling through this channel when i wake up

sudden willow
#

!e

_=["_"]
_=[_.append(__*2) for __ in _]
night quarryBOT
#

@sudden willow :warning: Your eval job timed out or ran out of memory.

[No output]
sudden willow
#

pog

verbal totem
#

Is there any way to create a custom keyword?

#

!e

def Notnt(condition):
    return not (not (bool(condition)))

print(Notnt (1 == 1) )
night quarryBOT
#

@verbal totem :white_check_mark: Your eval job has completed with return code 0.

True
verbal totem
#

No reason

#

Just wondering

next flame
#

other than modifying the interpreter, no

verbal totem
#

Darn

broken mesa
snow beacon
#

It's been done a few times for various purposes in this channel.

#

Maybe that 'various' should say 'nefarious'.

sick hound
#

!e

a: (a := lambda: print("hello"))() = 1
night quarryBOT
#

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

hello
grave rover
#

I wonder how difficult it'd be to implement an APL interpreter in python using Numpy

thin trout
#

*Google APL interpreter* Yeah, that should be faaaiiirly straightfoward, at least not more complicated than using some lists

proper vault
#

Numpy more or less cannot do the same things apl vectors can

#

Since apl nests can be jagged

#

Maybe with the object dtype

sick hound
#

You can execute functions by using them as annotations?

proper vault
#

an annotation can be any valid python expression

sick hound
#

Woah

#

Is there a reason to why that’s allowed?

proper vault
#

its more of a "why not allow it"

#

decorators with reduced syntax didn't bring much of anything

zealous widget
#

^

#

i've been annoyed more than once at decorators for this

proper vault
#

!e

@lambda a: a()
def f():
    return 4
print(f)
night quarryBOT
#

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

4
proper vault
#

fixed in 3.9

sick hound
proper vault
#

!pep 614

night quarryBOT
#
**PEP 614 - Relaxing Grammar Restrictions On Decorators**
Status

Final

Python-Version

3.9

Created

10-Feb-2020

Type

Standards Track

rugged sparrow
#

@radiant anchor i figured out a way to not need the heapgroom for the LOAD_CONST bug

#

!e ```py
def sizeof(obj):
return type(obj).sizeof(obj)

TUPLE_HEADER = sizeof(())
BYTES_HEADER = sizeof(b'') - 1
PTR_SIZE = sizeof((0,)) - TUPLE_HEADER
def load_addr(addr):
magic = lambda:None
b_addr = addr.to_bytes(PTR_SIZE, 'little')
offset = id(b_addr) + BYTES_HEADER
offset -= id(magic.code.co_consts) + TUPLE_HEADER
offset //= PTR_SIZE
co_code = bytes([0x64, offset & 0xff])
offset >>= 8
while offset > 0:
co_code = bytes([0x90, offset & 0xff]) + co_code
offset >>= 8
co_code += bytes([0x53, 0])
magic.code = magic.code.replace(
co_code=co_code
)
return magic()

obj = load_addr(id(1))
print(obj)

night quarryBOT
#

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

1
radiant anchor
#

👀

#

hm, that's using custom bytecode generation right?

rugged sparrow
#

yea it uses EXTENDED_ARG opcodes

verbal totem
#

!e

is_even = lambda n: [True for i in range(0,n) if str(i).endswith("0") or str(i).endswith("2") or str(i).endswith("4") or str(i).endswith("6") or str(i).endswith("8") else False][-1]
print(is_even(2))
night quarryBOT
#

@verbal totem :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     is_even = lambda n: [True for i in range(0,n) if str(i).endswith("0") or str(i).endswith("2") or str(i).endswith("4") or str(i).endswith("6") or str(i).endswith("8") else False][-1]
003 |                                                                                                                                                                           ^
004 | SyntaxError: invalid syntax
astral rover
#

What's the purpose of using type.sizeof over sys.getsizeof?

verbal totem
#

!d endswith

night quarryBOT
#

This appears to be a generic page not tied to a specific symbol.

rugged sparrow
#

@astral rover sys.getsizeof adds garbage collector overhead

sick hound
#

Why do type(obj).sizeof(obj) rather than, obj.sizeof()?

rugged sparrow
#

That avoids calling overridden dunders on classes

sick hound
#

Oh, I see

sick hound
#

!e

(
    (
        lambda __, ___, ____, _____: getattr(
    __builtins__,
    ().__class__.__name__[__ << __]
    + ().__iter__().__class__.__name__[(__).__rmul__(-1)]
    + [].__class__.__name__[____ % ___]
    + chr(_____)
    + ().__class__.__name__[__ >> __],
        )
    )(
        (lambda _: _).__code__.co_nlocals,
        (lambda _, __: _ | __).__code__.co_nlocals,
        (lambda _, __, ___: _ | __ | ___).__code__.co_nlocals,
        (
    (lambda _, __, ___: _ & __ & ___).__code__.co_nlocals.__rmul__(
        (lambda _, __, ___: _ | __ | ___).__code__.co_nlocals
    )
    + (True.__rmul__((lambda _, __: _ | __).__code__.co_nlocals))
        ).__rmul__(
    (
        lambda _, __, ___, ____, _____, ______, _______, ________, _________, __________:
    _
    ).__code__.co_nlocals
        ),
    )
)(
    (
        lambda __, ___, ____, _____, ______: hex.__class__.__name__[
    ___.__rmul__(____ * _____) - ______
        ].upper()
        + hex.__class__.__name__[___.__rmul__(____ * _____) - _____ - ______]
        + hex.__class__.__name__[___] * 2
        + hex.__class__.__name__[___.__rmul__(____ * _____)]
        + chr(__.__rmul__(___) + _____)
        + Warning.__qualname__[______ - True]
        + hex.__class__.__name__[___.__rmul__(____ * _____)]
        + Warning.__qualname__[_____]
        + ().__class__.__name__[___]
        + {}.__class__.__name__[______ - True]
        + chr(__.__rmul__(___) + ___)
    )(
        (
    lambda _, __, ___, ____, _____, ______, _______, ________, _________, __________: (
        _
    )
        ).__code__.co_nlocals,
        (lambda _, __, ___: _).__code__.co_nlocals,
        (lambda _, __, ___, ____: _).__code__.co_nlocals,
        (lambda _, __: _).__code__.co_nlocals,
        (lambda _: _).__code__.co_nlocals,
    )
) 
night quarryBOT
#

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

Hello World!
fast current
#

was lazy to import math just for floor

`def alternative_floor(myfloat):
if myfloat < 0:
myfloat -= 1
x = int(myfloat)

return(x)`
earnest wing
#

x // 1?

fast current
#

oh, thats even better

#

thank

earnest wing
#

return(x) 🤔

#

I mean it's not wrong

marsh void
#

return function

earnest wing
#

from future import return_function

#

await, yield, while, if also work

#

though the latter two are more clearly sugared thanks to the block

#

await as a function is believable

bitter iris
#

you can not propagate the effects of return/await/yield etc. The only thing that would work (with a little hack to fix traceback) is raise. AFAIK there were some debates around whether make it an expression (just like await/yield) or not, but I prefer this version as a statement

thin trout
#

Return... function ?

#

That can create a lot of semantic problems

cunning summit
#

If a random number is generated based off a natural event like the changing luminosity of a star is that considered real random or still pseudo?

proper vault
#

that is considered real random

#

though you generally use atmospheric pressure or lava lamps

#

since they vary faster and are easier to measure

cunning summit
#

ohhh nice

#

thank you so much

earnest wing
#

if you really want true* randomness you can rely on radioactive decay :v)
*commonly accepted to be

pulsar adder
#
class int(list):

    def __init__(self, number: int):
        self.number = number
        self.bits = [round(float(i)) for i in [*(str(bin(number))[2:])]]
        list.__init__(self, self.bits)  
    
    def __getslice__(self, i, j):
        return int(list.__getslice__(self, i, j))

    def __str__(self):
        return f"{self.number}"
#

so doing

x = int(2)
print(x[0])
``` will return `1`
bitter iris
#

is that python2?

sick hound
#

how do i use function.__code__?

#

i typed dir(function.__code__) but it has a lot of attributes and im confused

night quarryBOT
#

@terse mortar :white_check_mark: Your eval job has completed with return code 0.

<code object test at 0x7f4a2648c660, file "<string>", line 1>
sick hound
#

yes

#

what do i do now

#
>>> dir((lambda: None).__code__)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_kwonlyargcount', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']

which one of these are useful

naive roost
#
>>> (lambda: None).__code__.co_varnames
()
>>> (lambda: None).__code__.co_code
b'd\x00S\x00'
>>> (lambda: None).__code__.co_consts
(None,)
>>> (lambda: None).__code__.co_argcount
0
>>> (lambda: None).__code__.co_names
()
>>> (lambda: None).__code__.co_flags
67
>>> (lambda: None).__code__.co_firstlineno
1
>>> (lambda: None).__code__.co_filename
'<stdin>'
sick hound
#

is co_code settable?

naive roost
#

help((lambda: None).__code__) can probably help you

sick hound
#

ooh

naive roost
#

I don't know how to play with it, though

pulsar adder
sick hound
#

yeah it doesnt say anything about co_code @naive roost

#

what is co_nlocals? i see people using it here a lot

naive roost
rugged sparrow
#

@sick hound func.__code__ contains the information that python uses to run the function. By modifying it you can manipulate how the function works

sick hound
#

i realize that

#

can you go into detail? @rugged sparrow

#

like how can i edit the function code

sudden willow
#

!e

print("".join((chr(ord("`")+9), chr(ord("`")+12), chr(ord("`")+25))))
night quarryBOT
#

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

ily
sudden willow
#

just learnt how to do that

rugged sparrow
#

@sick hound you can use func.__code__ = func.__code__.replace(*any co_ attr*=new_val) to modify individual attributes to test things

sick hound
#

huh

#

that's interesting

bitter iris
pulsar adder
#

apparently it works

#

i think it's a deprecated method

#

(im on 3.7 btw)

sick hound
#

o

pulsar adder
#

btw i improved the code subclassing int and not list

class int(int):

    def __init__(self, number: int):
        self.number = number
        self.bits = [int(i) for i in [*(str(bin(number)).replace("0b", "").replace("-", ""))]]
        super().__init__() 

    # Types
    def __str__(self): return str(self.number)
    # def __list__(self): return self.bits
    def __iter__(self): return iter(self.bits)

    # Iterable
    def __setitem__(self, index, bit):
        if bit in (0, 1):
            self.bits[index] = bit
        elif bit == False:
            self.bits[index] = 0
        elif bit == True:
            self.bits[index] = 1
        self.number = int(''.join(map(str, self.bits)), 2)
        return self.bits

    def __delitem__(self, index):
        del self.bits[index] 
        self.number = int(''.join(map(str, self.bits)), 2)
        
    def __getitem__(self, index):
        return self.bits[index]

    # ???
    def __getslice__(self, i, j):
        return int(list.__getslice__(self, i, j))

    def __delslice__(self, i, j):
        return int(list.__delslice__(self, i, j))
#

this is stupid

naive roost
#

__getslice__ was killed in 3.9

pulsar adder
#

yea

#

im still running this on 3.7.4

#

how would you do it in 3.9+?

naive roost
#

a[i:j] now translates to a.__getitem__(slice(i, j))

pulsar adder
#

yea makes sense

#

but if i were to do a[i] would it still work?

naive roost
#

that would be a.__getitem__(i)

pulsar adder
#

yea

#

so would i have to define getitem twice for both cases or what

naive roost
#

hum... I'm pretty sure you don't have to

rugged sparrow
#

@pulsar adder inside __getitem__ use isinstance to see if the first arg is a slice

naive roost
#

you don't have to do that, the interpreter will do that for you

rugged sparrow
#

@naive roost wdym by that

naive roost
#

the thing you'll probably do with __getitem__ is something like that:

def __getitem__(self, index_or_slice):
  if isintance(index_or_slice, int):
    return self.bits[index_or_slice]
  else:
    return self.bits[index_or_slice]
```so it's not really useful to specialise on ints
rugged sparrow
#

Yea that's fair

rugged sparrow
#

@radiant anchor i also figured out how it can work with negative offsets where the bytes obj is before the tuple. you can add 0xffffffff + 1 to the negative offset, then generate the EXTENDED_ARG opcodes and when the interpreter combines the args internally it'll index the co_conts with a negative c_int

#

!e ```py
def sizeof(obj):
return type(obj).sizeof(obj)

TUPLE_HEADER = sizeof(())
BYTES_HEADER = sizeof(b'') - 1
PTR_SIZE = sizeof((0,)) - TUPLE_HEADER
MAX_INT = (1 << PTR_SIZE * 8 - 1) - 1

def load_addr(addr):
magic = lambda:None
b_addr = addr.to_bytes(PTR_SIZE, 'little')
offset = id(b_addr) + BYTES_HEADER
offset -= id(magic.code.co_consts) + TUPLE_HEADER
offset //= PTR_SIZE
if offset < 0: # overflow offset to convert to unsigned
offset += 0xffffffff + 1
co_code = bytes((0x64, offset & 0xff))
offset >>= 8
while offset > 0:
co_code = bytes((0x90, offset & 0xff)) + co_code
offset >>= 8
co_code += bytes((0x53, 0))
magic.code = magic.code.replace(
co_code=co_code
)
return magic()

addr_1 = id(1)
print(addr_1)
print(load_addr(addr_1))```

night quarryBOT
#

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

001 | 140568672393520
002 | 1
rugged sparrow
#

so the only way that it will fail now is if the bytes and tuple are further than (0xffffffff // 2) * 8 bytes apart

radiant anchor
#

huh nice, so there's basically a signed integer overflow?

rugged sparrow
#

yea

#

EXTENDED_ARG doesnt check for overflow

radiant anchor
#

interesting, I remember trying to do that and I thought it wouldn't work, but I guess I was wrong

rugged sparrow
#

its cause oparg in ceval.c is just a regular signed int

bitter iris
rugged sparrow
#

it abuses the fact that cpython LOAD_CONST opcode doesnt do bounds checking to load any address as a py_object. essentially the reverse of id

sick hound
#

Can't execute the code here but here's a simple implementation of a context-aware self

#
from inspect import getsourcelines

va_in = lambda objs, iterable: all(obj in iterable for obj in objs)
va_nin = lambda objs, iterable: all(obj not in iterable for obj in objs)

def allow_aware(func):
    def wrapper(*args, **kwargs):
        s_code = getsourcelines(func)[0][1 :]
        
        for c, line in enumerate(s_code):
            if va_in(('self', '='), line) \
                and va_nin((':=', '=='), line):
                
                var_name = line.split('=')[0].strip()
                s_code[c] = s_code[c].replace('self', var_name)

        exec('\n'.join(s_code))
        return locals()[func.__name__](*args, **kwargs)
    return wrapper

@allow_aware
def mod_increment(self):
    a = 1
    a = self + 1
    return self + a

@allow_aware
def increment(obj):
    obj = self + 1
    return obj

@allow_aware
def type_stuff(type_):
    type_ = type(self)
    return type_

print(increment(10), mod_increment(10), type_stuff(int))
night quarryBOT
#

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

[No output]
formal sandal
#

Why even have while, if you can do this? 😛

#

!e

class While:
    def __init__(self, condition):
        self.condition = condition

    def __iter__(self):
        return self

    def __next__(self):
        if self.condition():
            return None
        else:
            raise StopIteration

x = 0

for _ in While(lambda: x < 5):
    print(x)
    x += 1
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
formal sandal
distant wave
#

!e ```py
import ctypes
import dis
import inspect

class Manager:
def enter(self):
f = inspect.currentframe().f_back

    last_instr = f.f_lasti
    BYTES_HEADER_SIZE = 32
    offset = (last_instr + 2)  # two bytes forwards is the next instruction
    ctypes.c_char.from_address(id(f.f_code.co_code)+BYTES_HEADER_SIZE+offset).value = 126

def __exit__(self, exc_type, exc_value, exc_tb):
    print(exc_type, exc_value, exc_tb)
    return True

with Manager() as start:
start

night quarryBOT
#

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

<class 'NameError'> name 'start' is not defined <traceback object at 0x7f02f5a0d600>
distant wave
#

!e ```py
import dis

def a():
for i in range(5):
...

dis.dis(a)

night quarryBOT
#

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

001 |   5           0 LOAD_GLOBAL              0 (range)
002 |               2 LOAD_CONST               1 (5)
003 |               4 CALL_FUNCTION            1
004 |               6 GET_ITER
005 |         >>    8 FOR_ITER                 4 (to 14)
006 |              10 STORE_FAST               0 (i)
007 | 
008 |   6          12 JUMP_ABSOLUTE            8
009 |         >>   14 LOAD_CONST               0 (None)
010 |              16 RETURN_VALUE
distant wave
#

!e ```py
import ctypes
import dis
import inspect

class Manager:
def enter(self):
f = inspect.currentframe().f_back

    last_instr = f.f_lasti
    BYTES_HEADER_SIZE = 32
    offset = (last_instr + 2)  # two bytes forwards is the next instruction
    # last instruction, minus the load for None, hopefully?
    last_instr = len(f.f_code.co_code) // 2
    ctypes.c_char.from_address(id(f.f_code.co_code)+BYTES_HEADER_SIZE+offset).value = 110
    ctypes.c_char.from_address(id(f.f_code.co_code)+BYTES_HEADER_SIZE+offset+1).value = last_instr

def __exit__(self, exc_type, exc_value, exc_tb):
    print(exc_type, exc_value, exc_tb)
    return True

with Manager() as start:
print(1)
print(2)
print(3)
print(4)

#

Whooops

#

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

night quarryBOT
#

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

001 | <class 'TypeError'> 'NoneType' object is not callable <traceback object at 0x7f2769b396c0>
002 | 4
distant wave
#

I wonder why it threw that

#

!e ```py
import ctypes
import dis
import inspect

class Manager:
def enter(self):
f = inspect.currentframe().f_back

    last_instr = f.f_lasti
    BYTES_HEADER_SIZE = 32
    offset = (last_instr + 2)  # two bytes forwards is the next instruction
    # last instruction, minus the load for None, hopefully?
    last_instr = len(f.f_code.co_code) // 2
    ctypes.c_char.from_address(id(f.f_code.co_code)+BYTES_HEADER_SIZE+offset).value = 110
    ctypes.c_char.from_address(id(f.f_code.co_code)+BYTES_HEADER_SIZE+offset+1).value = last_instr
    # dis.dis(f.f_code)

def __exit__(self, exc_type, exc_value, exc_tb):
    print(exc_type, exc_value, exc_tb)
    return True

with Manager() as start:
print(1)
print(2)
print(3)
print(4)

night quarryBOT
#

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

001 | <class 'TypeError'> 'NoneType' object is not callable <traceback object at 0x7f5b019d1600>
002 | 4
distant wave
#

I'm screwing some instruction thing up but that's fine, for now. And it doesn't support 255+ opcode jumps but meh

terse mortar
#

Is the bot filter down or something?

mossy cloud
#

How can I put an image inside a function in a tkinter tab????

rugged sparrow
#

@distant wave you can use EXTENDED_ARG opcode to do 255+ jumps

distant wave
#

Yeah but then I'd need to overwrite other instructions

#

Plus I'm calculating the jump completely wrong at the moment

#

but yeah, realistically, someone ought to make a fully featured edition of this that edits all the code properties to simply replace a code block in place in the interpreter

#

Completely doable at this point, I think

rugged sparrow
#

I did something that overwrote instructions in my goto implementation, so I just made labels reset the overwrote instructions

analog rock
#

I often see some of the top "golfers" having their solutions use significantly more bytes than chars. why might this be? can you do some weird optimizations with unicode chars or something?

stark fable
#

yep

#

!e py exec('牰湩⡴栧汥潬眠牯摬⤧'.encode('U16')[2:])

night quarryBOT
#

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

hello world
stark fable
#

in this example the code has actually been made longer but if there's a lot of code doing something like that does make it shorter

#

i think

next flame
#

what code golf site counts chars instead of bytes

analog rock
#

thanks

#

how would be best to go about encoding the code like that?

analog rock
next flame
#

anarchy golf uses bytes

analog rock
#

ah

sick hound
#
__import__("discord").Client().run("")

how 2 golf

#

with bytes not chars

astral rover
#

But that doesn't do anything except eat memory

next flame
#

though i assume the reason why codegolf.se and anarchy use bytes is because of golfing languages

#

so you cant just make a language that abuses unicode to store multiple instructions in 1 char

proper vault
#

you can make a language that defines an empty program as a solution to the problem

#

yielding consistent 0byte solution

earnest wing
next flame
#

but at least you can only have up to 256 instructions if you're doing single byte

#

instead of 1,114,112 for all of unicode

floral meteor
#

install, then erase self if _SINGLE_INSTALL

install()or _SINGLE_INSTALL and os.remove(__file__)

Is there a shorter way to do this, not including shortening predefined names?

#

based on:

os.system("echo __import__('os').remove(__file__)>disappear.py")
#

I've been reducing one-liners to one-expressioners in this style:

os.chdir(LOCATION)or os.system(f'subst {_DRIVE_LETTER}: {LOCATION}')and[print(f"\x1b[31mERROR: \\\\??\\\\{_DRIVE_LETTER}:\\ already exists. Please back up and remove or reallocate a drive letter before retrying.\x1b[0m"),1][1]and exit(-2)

I just need to eliminate while loops and exception catching

#

If there's exception handling in a code suite, I have to expand the entire if suite.
Observe how a try-except suite forces this into at least 4 lines:

  if (ver:=float(''.join(sys.version.split('.')[:1])))>=float(_SUPPORTED_VERSION)or ver<3.1:
    print(f"\x1b[33mPython version {'.'.join(sys.version.split('.')[:2])} not supported.\x1b[0m")
    try:assert not os.system(f"START /b /d {LOCATION} py -{_SUPPORTED_VERSION} {os.path.realpath(__file__)}")
    except AssertionError:print("\x1b[31mERROR: Unable to automatically launch correct version. Exiting...\x1b[0m")or os.system("timeout /t 5")
    exit(-2)
#

when it could be...

((ver:=float(''.join(sys.version.split('.')[:1])))>=float(_SUPPORTED_VERSION)or ver<3.1)and (print(f"\x1b[33mPython version {'.'.join(sys.version.split('.')[:2])} not supported.\x1b[0m")or(os.system(f"START /b /d {LOCATION} py -{_SUPPORTED_VERSION} {os.path.realpath(__file__)}")and print("\x1b[31mERROR: Unable to automatically launch correct version. Exiting...\x1b[0m")or os.system("timeout /t 5"))or exit(-2)
#

expressions can be concatenated based on whether they return truthy values in this manner:

  # LOCATION & VERSION CONTROL
(os.chdir(LOCATION)or os.system(f'subst {_DRIVE_LETTER}: {LOCATION}')and[print(f"\x1b[31mERROR: \\\\??\\\\{_DRIVE_LETTER}:\\ already exists. Please back up and remove or reallocate a drive letter before retrying.\x1b[0m"),1][1]and exit(-2))or((ver:=float(''.join(sys.version.split('.')[:1])))>=float(_SUPPORTED_VERSION)or ver<3.1)and (print(f"\x1b[33mPython version {'.'.join(sys.version.split('.')[:2])} not supported.\x1b[0m")or(os.system(f"START /b /d {LOCATION} py -{_SUPPORTED_VERSION} {os.path.realpath(__file__)}")and print("\x1b[31mERROR: Unable to automatically launch correct version. Exiting...\x1b[0m")or os.system("timeout /t 5"))or exit(-2))or os.system("echo \x1b[32mVersion check passed.\x1b[0m")or os.system("echo Initialising...")

pesudo:

set directory to LOCATION;
try subst _DRIVE_LETTER %cd%;
but error, make error go brrr and leave;
if version not supported, print not supported, try fixing it, but error print can't fix, wait 5 and leave;
else print positive feedback

But the above could be additionally assigned to a variable, or even set inside an array of execution, which would store values based on successful execution

#

the feature being exploited:

and:
  a and b
  returns a if not a else returns b
or:
  a or b
  returns a if a else b
snow beacon
floral meteor
#

list comprehend that?

formal sandal
floral meteor
#
[print("pls gib a number")for _ in iter(lambda: (x:=input("gib number>")).isdigit(), False)]+[None]and print(x)
#

advanced number-only cat program

#

so it's just the try except suites left

#

I use them a lot

snow beacon
#

You can do very limited exception handling with generator expressions.

#

From memory they catch StopIteration.

floral meteor
#

Nice. Example?

snow beacon
#

Alas, I think they may have patched (_ for _ in ()).throw(StopIteration) to raise a RuntimeError.

#

next(iter(())) doesn't look as scary.

#

It seems like the strategy may no longer work very usefully.

floral meteor
#

alright, how do I execute this?
b'\x87\x00f\x01d\x01d\x02\x84\x08S\x00'

#

I got it from a lambda .code.co_code

#

it looks nice and small

#

!e

exec('\x87\x00f\x01d\x01d\x02\x84\x08S\x00'.encode("U16")[2:])
night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ValueError: source code string cannot contain null bytes
floral meteor
#

bruh

#

!e print('\x87\x00f\x01d\x01d\x02\x84\x08S\x00')

night quarryBOT
#

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

‡�fdd„S�
floral meteor
#

!e exec('‡fdd„S'.encode('U16')[2:])

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ValueError: source code string cannot contain null bytes
floral meteor
#

this thing hates me

cunning hollow
#

!e exec(print("Hello, World!"))

night quarryBOT
#

@cunning hollow :x: Your eval job has completed with return code 1.

001 | Hello, World!
002 | Traceback (most recent call last):
003 |   File "<string>", line 1, in <module>
004 | TypeError: exec() arg 1 must be a string, bytes or code object
floral meteor
#

I get ValueError: source code string cannot contain null bytes

distant wave
#

@floral meteor I don't think you can. I believe you need a list of variables (co_consts) for example, which are present on the __code__ object as well. You should, I think, be able to execute __code__ objects by themselves

#

!e ```py
def a():
print(1)

exec(a.code)

night quarryBOT
#

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

1
snow beacon
next flame
#

and you need to create a code object and wrap it in a function obj

stark fable
#

it needs a tuple of three constants and it will ignore the first constant in that tuple

#

it looks like the second constant should be a code object and the third constant should be a string

sick hound
#

Just a hello world of 6000 lines.

snow beacon
next flame
#

yeah that works too

floral meteor
#

so how would I do that?

astral rover
#

eval(code_object)

floral meteor
#

how would I do that from the bytes?