#esoteric-python
1 messages · Page 99 of 1
Fair enough then
every class stores a reference to its subclasses
Which is kinda weird
!e py print(object.__subclasses__())
@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
it means we can do that ^
Yeah I looked at that in my working shell lol
get_cls('_sitebuiltins._Printer').__init__.__globals__['sys'].modules this gets sys.modules
now we need to import builtins and restore it
Weird that sys.modules manages to restore itself
@rugged sparrow how long has it been since you started python?
a couple years
@slim echo it doesnt
we just need to add builtins to that same dict
may i please get numbers, sorry if i am being an hindrance
I'm literally clearing then immediately inspecting it in a shell and it's adding a bunch of stuff to it
2 years since i really started @elfin onyx
thx
yea some modules will repair themselves
Also somehow clearing sys.modules deletes all my variables; I guess that's because I'm deleting __main__
we need builtins to fully recover
Yeah
@slim echo we'll have to bootstrap it a bit
lemme write up a clean proof of concept
'clean'
@slim echo ^
Good lord lmao
depending on the version __builtins__ may be a dict, or a module at this point
Lol
so sometimes the code will be __builtins__.__dict__.update or __builtins__.update
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
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)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1
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
makes sense
so really we should create a pep for storing modules as weak references to avoid them sticking around!
>>> 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
since autocomplete is done by readline module
Absolutely
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
one sec
@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)
Is ImportWarning not a subclass of exception or smth
no now it just cant find any modules
>>> import os
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'os'
>>> ``` yea
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
_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
_sitebuiltins is imported by the interpreter to define help and quit
but its written in python
Also I forgot we have sys lol
that module also has a reference to a live sys module
which we can use to get sys.meta_path to repair it
nah its a list of importers
sys.path is a list of paths 
as strings
What does this achieve
The first 8 lines break the interpreter by clearing builtins
The rest fixes the interpreter
messing around with lambda
!e
_=lambda _:_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_)))))))))
print(_(1))
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
10
x=type("",(dict,),{"__getattr__":lambda s,a:s[a]})
how to golf
Can you pass a list as the second argument?
not sure
the documentation for type says tuple
i will try though
TypeError: type.__new__() argument 2 must be tuple, not list
Chinese thing?
Wow, I never heard about this one
That's stupid, I love it
this is why codegolf counts bytes not chars 🙂
That is a good point
!e
_=lambda _:_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_.__add__(_))))))))) print(_(True))
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
10
True == 1
yes @sudden willow and False == 0
@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
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?
An Aiohttp request
omg right
that's so smart
has anyone ever used the _peg_parser module for anything
I got a challange for you, try to find out which module the NoneType class is in
>>> None.__class__.__module__
'builtins'
oh i tried on the actual nonetype class
should still just be its module dunder
it raises namerror
huh
like u can't use nonetype class
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
i think what they mean is that using the name NoneType doesn't work
Do not use this module, it was only for testing peg parser code on the 3.9, it will be removed in 3.10 (it already is btw, just not released).
this is #esoteric-python tho
How do I obfuscate numbers without using dunders? So like getting 100 without just stacking .__add__()
And the type does need to be integer
I mean, instead of stacking __add__ together, you can use __mul__. Dunno if that's what you want tho
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
Ohh yeah, ~- decreases the value by 1, and -~ increases it by one.
it's because ~ inverts the bits of a number
so 0 -> 1, and 1 -> 0
which pretty much. ~x == x - 1
Is there an esoteric way to square a number without dunders?
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
~-~-int() is -2, so actually, that should be 4 ** 2 - 2 ** (-2)
Right, I got the signs the wrong way round
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())))]))))
@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
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
globals().__setitem__('_', )
How would I do that in-line here? @astral rover
that is one line friendly
I meant incorporating it with my current code so the entire thing is still one line
globals().__setitem__('_', ~-~-(-~-~-~-~int()).__pow__(-~-~int()).__sub__((-~-~int()).__pow__(-~-~int())))
No like implementing it inside this print somehow #esoteric-python message
you could use walrus
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
You broke the random.choice lol
there's no if though?
you dont need an if to use a walrus
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]
)
@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
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
this is a quirky channel
!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()])
@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
It is indeed lol
!e
eval(eval(__import__("base64").b64decode("cHJpbnQoJ0hlbGxvLCB3b3JsZCEnKQ==")))
@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 :white_check_mark: Your eval job has completed with return code 0.
Hello, world!
ao eval waits for the process in between the quotes to take place before evaluating?
quirky
thats how all python works
hey guys
i made hangman in one line >:)
Hello.
hi lol
wow thats impressive
Why thank you @frozen holly
i would ask how it works but i have a headache rn so it prolly wouldnt be the best idea
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
((use __import__))
done `__import__`
So u can use libraries inline with that
@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
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
Flag is any value
Okay
So like [*iter(int,1)] would loop infinitely
Yes
Okay okay i get it
This could come in very handy for any future inline algorithm i work on
Thanks man
I thought you were just gonna use contextlib lol
It sorta does @astral rover
If theres a lib for it then you could use the inline import right
Yeah
But I added some stuff to make it more modular
@sick hound that code uses context lib
Right right
It creates a decorator that works like with
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
When I get home I'll ping you with my newer version of inline try except
Yes please 🙏
If you can do stuff like this inline
In theory you could pretty much make any program inline
What do you think i should try make inline next
Considering ive made a couple sort algorithms and hangman already
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
Gotta research it then lol
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
Just try it
Will do
If it ends up being easy, make it smaller
Good idea actually
Ive just been thinking of one liners working
But making them as short as possible would be an interesting challenge
Thats a good one
Ive always struggled with finding when someone has won programatically without a bunch of ifs
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
i made a one line discord bots with one command and an event once
not nearly as impressive as what u guys do but
@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)
https://repl.it/@chilaxan/MineSweeper-One-Line#main.py here is the minesweeper
there now it follows pep8 perfectly
👍
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.
[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
!e
import math
i = -math.inf
while i < 0:
continue
still running
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)]
@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
Hmm
wtf is this function
esoteric python
!e
_=lambda _: (print(1)if(_)is(1)else(print(2))) _(int(True))
@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
pog
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?
You could probably using sys._getframe
@sick hound #esoteric-python message this one works for 3.9
Woah, that’s amazing. Could you give a summary of what it does?
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
@sick hound it modifies the byte code to insert jumps to specified labels
@flint briar it's #esoteric-python
@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
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
wdym
you would die if you scrolled up some
There is. To implement other loops 🙂
!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]")
@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
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])
you also can't inline elif like that
just noticed that
I have a challenge. Make a program in which await (yield) is used to accomplish something useful.
Is the default use case not good enough?
!e ```py
class A: ...
class B: ...
classes = [A, B]
class C(*classes):
...
@distant wave :warning: Your eval job has completed with return code 0.
[No output]
@distant wave :white_check_mark: Your eval job has completed with return code 0.
Foo () {'__module__': '__main__', '__qualname__': 'Foo'}
why does that print Foo.__class__.__new__'s args?
any function can be a metaclass
when that calls print.__new__ does that do print?
it doesnt do __new__, it does __call__
right
that makes slightly more sense
so what the metaclass kwarg does is just call the objects __call__ with name bases attrs and kwargs
!e
and all other kwargs
class A(metaclass=print, end=' is the thing', sep=','):
pass
@proper vault :white_check_mark: Your eval job has completed with return code 0.
A,(),{'__module__': '__main__', '__qualname__': 'A'} is the thing
is there a way to do that but onelined using type
not really
it would just be
print('A',(),{'__module__': '__main__', '__qualname__': 'A'}, end=' is the thing', sep=',')
oh
!e
print(True.__int__())
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
1
quirky
I mean, int(True) is 1
yea i just now learned how to use __int__
why does this return none
im pretty sure your're returning print's return
not an error, it is a singleton, to those who don't know
NotImplemented / NotImplementedError trips up a lot of folks
what does ... do?
it means pass
It's like putting class A: 0, except it's an ellipsis.
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
I personally also use it instead of pass when the function body hasn't been written yet, but will be filled with something
Anything that is supposed to exist but is being omitted.
Being an expression, it's easy to fulfill this.
oh ok.
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
__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])
print(__all__)
Ty ty
That's two lines, but you could probably make the printing a side effect of the assignment.
print(__all__:=...)
This is the wrong channel for that. You should claim a free help channel (see #❓|how-to-get-help)
!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]))
@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__']
Cool
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.
hey does anyone know anything about artificial intelligence?
thank you
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?
@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
Amicable Numbers , yeah
@boreal slate Hmm maybe try changing the last line to print(y == a(a(y)) != a(y))
!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)```
@boreal slate :white_check_mark: Your eval job has completed with return code 0.
True
!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))```
@boreal slate :white_check_mark: Your eval job has completed with return code 0.
False
You can do sum(x * (not y%x)
That saves a few chars I think
@boreal slate
and remove the if y%x == 0
!e
y=496
a=lambda y:sum(x*(not y%x)for x in range(1,y))
print(y==a(a(y))!=a(y))```
@boreal slate :white_check_mark: Your eval job has completed with return code 0.
False
!e
!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!*
@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
Yea it does make it slower. It’s not a good idea just one tht makes it shorter lol
like code golf
probably walrus can do the trick
replace not x%y with x%y<1 to save 2 bytes
total byte saved count = 3
haha if this keeps going it wont be readable soon
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))
@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
!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))
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
False
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))
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
True
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))
@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
yeeeeah
it happens
this is #esoteric-python we don't mind a few hiccups
it works for sufficiently high N
That implementation is genius how did you do/find it. @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)
It's effectively wrapping the sum in N layers of recursion
That’s so creative, and it can be applied to any function of ints to reduce a conditional list of ints
Pretty much, yeah - also works to reduce sequences using other functions as well (*, etc)
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
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
What if you put getattr(locals(), 'cache', cache := {}) instead of the first evaluated cache?
@sick hound ^
or use __setattr__
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]}') )
Cool!
thanks!
(
(
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!`
I know how that works
can you explain some?
That works like a python code
Yeah....
uh huh
Let some dude explain
ok
There is a good chance that he indeed did write it
but the dude that dmmed me wrote it
Or you can paste the code in an ide, and use the inspect feature
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
Really?
Can anyone write a python code that prints a sentence in inverse position
@fossil estuary wrote that code
Guys this isn't the channel for this. Please go to #❓|how-to-get-help or #python-discussion
for example ; I'm from England answer: dnalgne morf m'I
You most definitely do not want help from this channel.
we was in #python-discussion and got told to go here from a helper
sooooooo
yes...for the esoteric code
You got told to come here for that specific code. This has gotten way off topic now
not for help
esoteric code goes in #esoteric-python
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,
)
)
@short crag :white_check_mark: Your eval job has completed with return code 0.
Hello World!
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
ohhh
>>> hex.__class__.__name__
'builtin_function_or_method'``` we're slicing strings like these
we're slicing them and adding them to other sliced strings
that makes more sense
which then forms the Hello, World!
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
here is the original message
ok
Amazing.
#esoteric-python message here's another one too lol
#esoteric-python message this is my favourite
he is a impostor!!!!!!
#esoteric-python message horrible
sorry for not believing you
@tribal moon you have too much time.
lol it's all cool I love esoteric Python
so the thing is
what else has he lied about
thats my thing
did anyone here make this?
Yeah someone else made that, I think it was a moderator?
check the pinned messages here
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)
@short crag :white_check_mark: Your eval job has completed with return code 0.
Perl 6
Brainfuck in python
See this is what happens, I trust someone then I find out they lied to me.
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
It doesn't inherit from it, in instantiates it
Ahhh
!e
def foo():
pass
print(type(foo))
@twilit grotto :white_check_mark: Your eval job has completed with return code 0.
<class 'function'>
@sharp canyon I guess this is the place https://github.com/python/cpython/blob/master/Objects/funcobject.c?..
Yeah I think that's what I need
Was wondering what awful things you could do with it by inheriting it
@sharp canyon I'm pretty sure you can't inherit from it
no you cant
Damn
You can do horrible things with inheritance anyway 🙂
True
And I suppose messing with meta methods and classes gives enough awfulness anyway
||Ellipse inheriting from Circle in manim is more unsettling to me than most hacks in here||
although im pretty sure using fish hook you can add your own methods to it
This thing https://pypi.org/project/fishhook/?
yeah
how is it different from forbiddenfruit?
cause it can patch c code
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)
hmm
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
ive tried that too, ValueError: f() requires a code object with 0 free vars, not 2
ah, variable numbers have to match up. That does make it quite a bit more complex.
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
!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)
@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
@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
yeah it must be, but as you can see in the example both __code__objects have a arg count of 0
!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
@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
how??
because its defined local to decorated, but youre trying to access outside of that scope
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)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
argcount 0 0 2
now decorated doesn't accept a closure
OHHHHHH
oh, wait, I have an idea
I found this trick in Python 2 docs, from the times when you could create inner functions, but when closures didn't exist.
try calling overwrite_this, both those kwargs are required
?
also i noticed, ideally there wouldnt need to be a return original
since yknow, im trying to overwrite the code object of overwrite_this
anyway, it doesn't really work here, because the decorated function could have a different number of closured variables
which is fixable by doing the same thing for it
like, decorate both in this way
if it worked
You could try overwriting the __code__.co_consts with your own objects.
decorated() missing 2 required keyword-only arguments: '____func' and '____original'
hmmm
right, but my block doesn't transfer the default values to the new function 🙂
afaict
!e
def foo():
print("hello", "world")
foo.__code__ = foo.__code__.replace(co_consts=(None, "fizz", "buzz"))
foo()
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
fizz buzz
this instead of the default kwargs should work
like, refer to (1,2,3,4,5) or whatever
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
@broken mesa :white_check_mark: Your eval job has completed with return code 0.
1 2 3
!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)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
1 2
this is so incredibly awfull its putting a big dumb grin on my face
it must be done
you can if you want
I would be interested how the assembly would look like. Seems pretty hard to reverse 😄
The bytecode would look... pretty normal?
Time to spend 3 hours making a cursed one liner!
yeah you are right.
Assembler gives a shit about decorators and stuff. Correct me if I am wrong @formal sandal
wdym?
arent decorators just syntactic sugar? wouldnt matter to the assembly in that case..
yeah, a decorator is just a function call
If the decorator returns a new function, then yes, it might be a bit puzzling
yes, of course
but a decorator often creates a new function that captures the old one in a closure
Or at least make a call
!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
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
1 2
Whats happening? 😄
the second version gave correct output, but also made a segfault
oof
@broken mesa ^^^
ooooof
anyways, one step closer to being able to convert a function object into a class
@broken mesa have you seen this? https://repl.it/@int6h/Namespace#main.py
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"]())
ideally i would like to have it work with stdlib
crap
Well, it outputs
{'apple': 42, 'orange': <function orange at 0x7f28748f95e0>, 'banana': 47}
42
@broken mesa
yeah i looked at the repl
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 🤔
you didnt print anything
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
[1, 4, 9]
wait, I think I got the wrong example
ah, yes
!e
class Foo:
a = 1
b = [a**2 for _ in range(3)]
@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
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
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:
yeah sorry
Idk if it is going to work for everyone else
hey why hasn't the bot reacted with trash can
here's the raw https://paste.pythondiscord.com/raw/uzezukotop
it's a rickroll thing
Is it a rickroll link?
it opens one
That's sick
It's automatic
it generates the thing automatically
maybe I should post it on my github
oh wow it does
What an absolute chad
@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)
!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)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
namespace({'outer_scope': 'InnerScope', 'a': 1, 'b': 2}) OuterScope
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
!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)
@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
@sick hound this also lets stuff like that work
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))
Like this system #esoteric-python message
!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)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
d
AAAAAAAAAAAAAAA
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.
I would do x = float("inf"), @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
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
@stark fable That makes a lot of sense.
Still learning and python has surprised me with the likes of the walrus operator before.
i like scrolling through this channel when i wake up
!e
_=["_"]
_=[_.append(__*2) for __ in _]
@sudden willow :warning: Your eval job timed out or ran out of memory.
[No output]
pog
Is there any way to create a custom keyword?
!e
def Notnt(condition):
return not (not (bool(condition)))
print(Notnt (1 == 1) )
@verbal totem :white_check_mark: Your eval job has completed with return code 0.
True
other than modifying the interpreter, no
Darn
heres a challenge implementation of a maybe boolean operator, if you care:
https://github.com/python-discord/esoteric-python-challenges/blob/master/challenges/06-maybe-keyword/solutions/juanita.py
@verbal totem You can set a custom coding for a Python file, have it parse the file, transform the AST and then output different code.
It's been done a few times for various purposes in this channel.
Maybe that 'various' should say 'nefarious'.
!e
a: (a := lambda: print("hello"))() = 1
@sick hound :white_check_mark: Your eval job has completed with return code 0.
hello
I wonder how difficult it'd be to implement an APL interpreter in python using Numpy
*Google APL interpreter* Yeah, that should be faaaiiirly straightfoward, at least not more complicated than using some lists
Numpy more or less cannot do the same things apl vectors can
Since apl nests can be jagged
Maybe with the object dtype
Wtf
You can execute functions by using them as annotations?
an annotation can be any valid python expression
its more of a "why not allow it"
decorators with reduced syntax didn't bring much of anything
!e
@lambda a: a()
def f():
return 4
print(f)
@proper vault :white_check_mark: Your eval job has completed with return code 0.
4
fixed in 3.9
Bruh, is there a pep where I can read more about this?
!pep 614
@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)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1
yea it uses EXTENDED_ARG opcodes
!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))
@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
What's the purpose of using type.sizeof over sys.getsizeof?
!d endswith
This appears to be a generic page not tied to a specific symbol.
@astral rover sys.getsizeof adds garbage collector overhead
Why do type(obj).sizeof(obj) rather than, obj.sizeof()?
That avoids calling overridden dunders on classes
Oh, I see
!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,
)
)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello World!
was lazy to import math just for floor
`def alternative_floor(myfloat):
if myfloat < 0:
myfloat -= 1
x = int(myfloat)
return(x)`
x // 1?
return function
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
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
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?
that is considered real random
though you generally use atmospheric pressure or lava lamps
since they vary faster and are easier to measure
if you really want true* randomness you can rely on radioactive decay :v)
*commonly accepted to be
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`
is that python2?
how do i use function.__code__?
i typed dir(function.__code__) but it has a lot of attributes and im confused
@terse mortar :white_check_mark: Your eval job has completed with return code 0.
<code object test at 0x7f4a2648c660, file "<string>", line 1>
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
>>> (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>'
is co_code settable?
help((lambda: None).__code__) can probably help you
ooh
I don't know how to play with it, though
that's actually python 3
yeah it doesnt say anything about co_code @naive roost
what is co_nlocals? i see people using it here a lot
you might want to look into this: https://docs.python.org/3/library/inspect.html?highlight=__code__, because I am completely underqualified to talk about that, sorry 😅
@sick hound func.__code__ contains the information that python uses to run the function. By modifying it you can manipulate how the function works
i realize that
can you go into detail? @rugged sparrow
like how can i edit the function code
!e
print("".join((chr(ord("`")+9), chr(ord("`")+12), chr(ord("`")+25))))
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
ily
just learnt how to do that
@sick hound you can use func.__code__ = func.__code__.replace(*any co_ attr*=new_val) to modify individual attributes to test things
__getslice__ in python 3, uh, weird?
o
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
__getslice__ was killed in 3.9
a[i:j] now translates to a.__getitem__(slice(i, j))
that would be a.__getitem__(i)
hum... I'm pretty sure you don't have to
@pulsar adder inside __getitem__ use isinstance to see if the first arg is a slice
you don't have to do that, the interpreter will do that for you
@naive roost wdym by that
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
Yea that's fair
@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))```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 140568672393520
002 | 1
so the only way that it will fail now is if the bytes and tuple are further than (0xffffffff // 2) * 8 bytes apart
huh nice, so there's basically a signed integer overflow?
interesting, I remember trying to do that and I thought it wouldn't work, but I guess I was wrong
its cause oparg in ceval.c is just a regular signed int
this is some real esoteric python
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
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))
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
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
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
There's also a different way, although not that esoteric <#esoteric-python message>
!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
@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>
!e ```py
import dis
def a():
for i in range(5):
...
dis.dis(a)
@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
!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
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
@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
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)
@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
I'm screwing some instruction thing up but that's fine, for now. And it doesn't support 255+ opcode jumps but meh
Is the bot filter down or something?
How can I put an image inside a function in a tkinter tab????
@distant wave you can use EXTENDED_ARG opcode to do 255+ jumps
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
I did something that overwrote instructions in my goto implementation, so I just made labels reset the overwrote instructions
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 :white_check_mark: Your eval job has completed with return code 0.
hello world
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
what code golf site counts chars instead of bytes
oh wow
thanks
how would be best to go about encoding the code like that?
https://code.golf
there's an option of both
I thought this was the main site?
ah
But that doesn't do anything except eat memory
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
you can make a language that defines an empty program as a solution to the problem
yielding consistent 0byte solution
You can still bypass that using a custom code page
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
thats why its a banned loophole 🙂 https://codegolf.meta.stackexchange.com/a/5076/70761
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
for _ in iter(lambda: x < 5, False):?
list comprehend that?
🤔 🤔
Why didn't I think of that
[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
You can do very limited exception handling with generator expressions.
From memory they catch StopIteration.
Nice. Example?
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.
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:])
@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 :white_check_mark: Your eval job has completed with return code 0.
�fddS�
!e exec('fddS'.encode('U16')[2:])
@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
this thing hates me
!e exec(print("Hello, World!"))
@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
I get ValueError: source code string cannot contain null bytes
@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)
@distant wave :white_check_mark: Your eval job has completed with return code 0.
1
The code object is bytecode plus various constants. This bytecode won't work unless you give it, by my count, two constants and a value from the containing closure.
and you need to create a code object and wrap it in a function obj
three constants, one just isn't used
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
Can't you just eval or exec them?
yeah that works too
so how would I do that?
eval(code_object)
how would I do that from the bytes?
