#esoteric-python
1 messages ยท Page 114 of 1
K I just simplified it
I'm just getting into this decorator thing so yeah
!e ```py
@print
@lambda f: f.name
class Hello: ...
@terse mortar :white_check_mark: Your eval job has completed with return code 0.
Hello
lul
It mentioned someone lol
@terse mortar :white_check_mark: Your eval job has completed with return code 0.
Hello world!
!e
@lambda f:__import__(f.__name__)
class __hello__:...
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
Hello world!
!e ```py
from operator import attrgetter
@import
@attrgetter('name')
class hello: pass
@proper vault :white_check_mark: Your eval job has completed with return code 0.
Hello world!
!e
@print
class __hello__(metaclass=type('',(),{'__str__':'Hello, World!'})):...
wait no
!e
@print
class __hello__(metaclass=type('',(type,),{'__str__':lambda*a:'Hello, World!'})):...
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
Hello, World!
!e print("thats something!")
cool!
if 1==1:
print("some weird stuff")
else:
print("interesting")
e! ```py
if 1==1:
print("some weird stuff")
else:
print("interesting")
oh
e! ```
print("something")
It's "!e" but it has to be at the beginning of your message on its own line. The #bot-commands channel is a good place to practice various commands before "doing it live" in one of the other discussion channels.
!e
print("hello")
@deft rock :white_check_mark: Your eval job has completed with return code 0.
hello
!e
if 1==1:
print("thank you!")
else:
print("oh i cant code")
@spice tapir :white_check_mark: Your eval job has completed with return code 0.
thank you!
XD
The best importation around the world ๐ :
import pygame as pygameisincredibleformakevideogamesorsomeotherthingswecanuseitformakefunnyimportation
Just wait till you see mee6 source code
I'd like to see it
actually they really cleaned it up, it used to be so much worse
how tf lol
Why this no work?
def check_if_table_exists(table):
cursor.execute('''SELECT to_regclass('public.{}'))'''.format(table))
r = cursor.fetchall()
if r[0][0] is None:
print('Table doesn\'t exist!')
else:
print(r)
check_if_table_exists(shtousoh)
I'm getting an error that says shtousoh isn't defined
But why would it have to be defined if it's the argument to a function
oh
put quotes around it
merp
This isn't the best channel to get help with your code. #โ๏ฝhow-to-get-help is a better bet.
Whenever we 'help', the code looks worse than before.
I solved it
I needed to have the argument in quotes, and I had an extra parentheses in there
parenthesi?
parenthesus?
parenthesis
is correct
Do other topical channels get people wanting help with their code?
tbf I think chilaxan helped me gain the respect of my current python teacher cuz he hates python so when I used pointers to remove functionality from lists I think it made him like me
I badgered him several times to take data structures early and he was like "you use python, lists are a crutch, arrays are FIXED SIZE and ONE DATA TYPE"
turns out I need discrete math anyway to take classes after data structures at the uni I'll be attending but I'm hoping I can just do independent study or something for discrete and still wish he let me into fuckin data structures
but yeah can we hurry this thing up and make python more like haskell faster
how can we make recursion less expensive?
A decorator that optimises self-recursive tail calls into loops would be interesting, if a little brittle to redefining the variable holding the function.
ooh
Sorry guys I'll try to be more esoteric in the future
We'll be glad to have you.
Esoteric is kind of subjective btw
That's part of its draw.
Well what I mean is, I'm worried that I won't be esoteric enough even if I think I am
I don't want to get yelled at again
We weren't trying to forbid you from partaking in this channel, we just thought you might have misunderstood its purpose.
I think I did
It seems that this channel is more for exposition than for instruction
I think I understand that now, unless I'm mistaken
We don't currently have good resources for beginners to understand all of the bedlam that goes on in this channel, because it's just easier to learn to code Python well before you starting coding it mischievously. It's easier to break the rules once you know what will break.
True
However, like learning to speak a language through immersion, you might discover how to code regular Python better through reading here. At least, that's what I did.
This server is the best resource I've found for getting help when googling and documentation fails me
ya I learned python more completely once I knew what was possible
I'll make more when I have time.
@snow beacon very interesting guide, though so far its still quite basic. what other topics are you planning on covering?
any plans on adding types and ctypes stuff? what about class/object based fuckery?
How can I emulate a module? I want to make a multi-file module into a single file
I don't have expertise with ctypes. I hoped Chilaxan could help with that part. I'm not sure what in particular you mean by types, unless it's things like code objects. If you have ideas for it I invite anyone to contribute. (That way it might get good this decade.)
I think there's a module type in types. That could help.
Iirc it doesn't
You should write about generators too
(No i wont help lol sorry)
So far I've been writing about esoteric aspects of things. When I get enough ideas for generators I expect I will.
Parsing strings in general has a lot of fuff to it
nested f-strings, escaped newlines, the 2 different DSLs, comments in strings in comments [...], implicit concat,
well, more specifically i meant things like using they types module to create functions, classes etc on the fly
I was envisioning that being a section of the builtins section.
A string page might be a good idea.
I am working on some a section about ctypes, but I'm a bit swamped with finals atm
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hello world!
@abstract oracle :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | ModuleNotFoundError: No module named '__hmm__'
!e
@import
@lambda _: _.name
class hello: ...
@violet rune :white_check_mark: Your eval job has completed with return code 0.
Hello world!
@violet rune :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'python' is not defined
!e
import platform
print(platform.python_version())
@violet rune :white_check_mark: Your eval job has completed with return code 0.
3.9.4
!e
import sys
if sys.hexversion >= 0x3000000:
print('Python 3.x hexversion %s is in use.' % hex(sys.hexversion))
@violet rune :white_check_mark: Your eval job has completed with return code 0.
Python 3.x hexversion 0x30904f0 is in use.
!e
@__import__
@__import__('operator').attrgetter('__name__')
class __phello__:0
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
Hello world!
can you explain how that works lol
The class itself is pretty simple. Then it's decorated with the name lambda, which return the class's name instead of the class, "__hello__". The other decorator is __import__ which is a function that takes a string and imports the module with that name. It imports __hello__, which automatically prints Hello world!
!e ```py
import(import('operator').attrgetter('name')(type('phello', (), {})))
@naive roost :white_check_mark: Your eval job has completed with return code 0.
Hello world!
so, I'm going to write the equivalent code
!e ```py
from operator import attrgetter
class phello:
pass
name = phello.name
print(name)
import(name) # which is basically import name
@naive roost :white_check_mark: Your eval job has completed with return code 0.
001 | __phello__
002 | Hello world!
__phello__ looks like the package version of the __hello__ module.
That sounds plausible
!e why do you need operator for?
@__import__
@lambda c:getattr(c,'__name__')
class __phello__:...
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello world!
no reason just decided to use it lol
!e so much unoptimised code just
print("Hello World!")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
!e but i just cant help but
class _(metaclass=lambda*a:type(*a)()):__lt__=print
_<"Greetings, planet"
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Greetings, planet
!e ```py
class _(metaclass=lambda*a:type(*a[:2],a[2]|{'lt':print})()<a[2]['victim']):victim='Hello World!'
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
you got a | instead of a ,
!e ```py
class phello(metaclass=lambda*a:import(a[0])):...
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello world!
how about that one?
so you know how metaclass works?
yeah i just didn't see how you got the name and the bases using a[:2]
!e print((a:=[0,1,2,3])[:2])
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[0, 1]
!e ```py
class _(metaclass=lambda*a:a[2]['victim']|type(*a[:2],a[2]|{a[2]['a'][2]:getattr(globals()['builtins'],a[2]['a2'])})()):
victim,a,a2='Hello World!',[...,...,'ror'],'print'
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
ok.. i will look into this
there that's my final edit
i might ping you later if i don't figure this out, are you ok with that?
!e ```py
class _(metaclass=lambda*a:(*a[2],)[2]|type(*a[:2],a[2]|{a[2]['a'][2]:getattr(globals()['builtins'],a[2]['a2'])})()):
phello,a,a2=...,[...,...,'ror'],'import'
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello world!
I obfuscated it harder
any way to make this smaller?
matrixReshape=lambda s,m,r,c:m if len(m)*len(m[0])!=r*c else __import__("numpy").reshape(m,(r,c))```
matrixReshape=lambda s,m,r,c:m if r*c!=len(m)*len(m[0])else __import__("numpy").reshape(m,(r,c))
```For a start.
matrixReshape=lambda s,m,r,c:__import__("numpy").reshape(m,(r,c))if r*c==len(m)*len(m[0])else m
from numpy import*
matrixReshape=lambda s,m,r,c:reshape(m,(r,c))if r*c==len(m)*len(m[0])else m
```This also works.
if you want to ditch the short circuiting you can also use (a,b)[c]
from numpy import*
matrixReshape=lambda s,m,r,c:(m,reshape(m,(r,c)))[r*c==len(m)*len(m[0])]
```I'm unsure this can get any shorter.
Nice one lol
thanks
Wasn't aware of the boolean-index trick
I had forgotten about it until Olivia mentioned it, but I might not have thought that numpy.reshape has no side effects.
import numpy
matrixReshape=lambda s,m,r,c:(m,numpy.reshape(m,(r,c)))[r*c==len(m)*len(m[0])]
```I'm pretty sure this is the same length.
for longer module names (6+) it's worth it even if you use something just once
for 5 chars, it's the same thing
s also isn't used
but removing that is a breaking change to the api and requires a new major version :>
Only requiring an extra character if the incremented version needs a new version.
!e
import timeit
print(timeit.timeit("x == y", "x=tuple(range(100)); y=tuple(range(101))"))
print(timeit.timeit("x == y", "x=list(range(100)); y=list(range(101))"))
@forest harbor :white_check_mark: Your eval job has completed with return code 0.
001 | 0.4361311779357493
002 | 0.042158572003245354
^ funfact
Comparison between lists are optimized in a way like this:
class list:
def __eq__(self, other):
for x, y in zip(self, other):
if x is y:
continue
if x != y:
return False
return True
because is is faster than ==
nope, that's not the reason
what's the reason then
Lists shortcuts comparisions if the lists have different lengths. Tuples do not.
Ah that seems like another reason
The reason is "cause ain't nobody comparing tuples of different lengths", but this actually says a lot about the semantics of lists vs tuples.
I'm still right about lists comparison being faster though.
!e
import timeit
print(timeit.timeit("x == y", "x=tuple(range(100)); y=tuple(range(100))"))
print(timeit.timeit("x == y", "x=list(range(100)); y=list(range(100))"))
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
001 | 0.39714665664359927
002 | 0.1722207530401647
now try it with range(1000, 1100)
!e
import timeit
print(timeit.timeit("x == y", "x=tuple(range(1000, 1100)); y=tuple(range(1000, 1100))"))
print(timeit.timeit("x == y", "x=list(range(1000, 1100)); y=list(range(1000, 1100))"))
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
001 | 1.5638931365683675
002 | 1.862255543936044
!e
print(1000 is 1000)
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | True
๐ค
!e
a = 999
print(a + 1 is 1000)
@proper vault :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:2: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | False
ah right
Python only internalises ints 0 to 255 iirc
!e
print(sum(x is y for x, y in zip(range(1000, 1100), range(1000, 1100))))
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
0
makes sense
Now the question is why is that comparing tuples is faster?
(it's not just because it skips the is comparision)
Why is that so?
is there a way to order a list (ascending) without using sorted() or .sort()?
you can write your own sorting function
And how would i do so
well, pick a sorting algorithm is step 1
selection sort is probably the simplest, quick sort is probably the best that you can reasonably handwrite
ill go for quick sort :)
radix sort or pigeon hole sort if you have just numbers
n00b question, but Google was a bit unclear.. Using gevent, do I have to import gevent.monkey and monkey patch_all before other imports? Or can I do all my imports then monkey patch?
oh. its just numbers so radix then..?
sure
bogosort would be my pick. you can implement it in 2 or 3 lines.
lol. but its not efficient
oh ok
s = set()
while True:
x = eval('1000')
if (y:=id(x)) in s:
break
s.add(y)
print(len(s))
(not very) random number generator with a sense of russian roulette, it might just run forever, it might always run forever, it might give some random number.
Doesn't really seem to work on snekbox on the bot
does this work because eval forces Python to assign a new space in memory for the int generated?
I'm guessing it's because a looped eval(literal) can't be optimized like a looped int(literal), but that's just my take
also... are there any uses of := that can't be done by regular Python or is it purely syntactic sugar?
one liners
I should have seen that coming
so I guess it's just to improve readability in certain cases?
I would say so
pretty much, yeah. If you do
for _ in range(5):
print(id(1000))
When this is compiled to bytecode, 1000 will be stored as a single constant, if you use dis.dis then you can see it uses LOAD_CONST to load it each time, so it's loading the same thing each time. Because of this you'll get the same number 5 times. You can even work out what this number will be without actually executing the function
def f():
for _ in range(5):
print(id(1000))
print(id(f.__code__.co_consts[2]))
f() # will print the same id printed above 5 times
when you use eval, it doesn't know to store it as a constant, so creates a new 1000 each time. I think that's right anyway
it is storing it as a constant, but it's making a new constant in a new code object
the reason that py for _ in range(5): print(id(1000)) prints the same number 5 times is that it's the same LOAD_CONST loading the same constant
...uhhhh
hmm
that wasn't supposed to happen
oh
!e py exec(''' def f(): print(id(1000)) ''') exec(''' def g(): print(id(1000)) ''') f() g()
@stark fable :white_check_mark: Your eval job has completed with return code 0.
001 | 139899852728688
002 | 139899852730192
python is smarter than i expected, so even if you access the same constant from two different places it might optimise that and make them the same constant
but if you force them to be compiled separately, they're two different constants
!e py import dis exec(''' def f(): print(id(1000)) ''') exec(''' def g(): print(id(1000)) ''') dis.dis(f) dis.dis(g)
@stark fable :white_check_mark: Your eval job has completed with return code 0.
001 | 3 0 LOAD_GLOBAL 0 (print)
002 | 2 LOAD_GLOBAL 1 (id)
003 | 4 LOAD_CONST 1 (1000)
004 | 6 CALL_FUNCTION 1
005 | 8 CALL_FUNCTION 1
006 | 10 POP_TOP
007 | 12 LOAD_CONST 0 (None)
008 | 14 RETURN_VALUE
009 | 3 0 LOAD_GLOBAL 0 (print)
010 | 2 LOAD_GLOBAL 1 (id)
011 | 4 LOAD_CONST 1 (1000)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/lomucarupo.txt?noredirect
they're still constants
but they're different constants
because beyond a certain point it becomes impractical to keep track of every 1000 in existence and make sure they're all the same
the reason that in other cases they end up being the same 1000 is that the instructions loading the 1000s all end up pointing at the same 1000 to load
because when the code is "compiled" into bytecode it does optimisations like that
So it seems any 1000s that end up in the bytecode will be the same, wonder if there are any exceptions to that
not sure if that question makes much sense though lol
if they're in different pieces of bytecode then they'll be different
i think within one piece of bytecode they'll always end up the same
!e # start parameter: 10
result = text.endswith('geeks.', 10)
print(result)
@fading inlet :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | NameError: name 'text' is not defined
start parameter starts with 0 or 1
!e
____=type('_', (type,),{'__matmul__':__import__})("_",(),{})
__=_=type('_', (type,),{'__matmul__':lambda*_:_[1].__name__})("_",(),{})
@lambda ___:____@___
@lambda*_:__@_[0]
class __phello__:...
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
Hello world!
!e ```py
class phello(False,True,metaclass=lambda*:type('',(),{[2][''][0]:getattr(builtins,_[2][''][1])})()@(type('',(),{[2][''][0]:lambda*:__[[1][1]]})()@[[1][0]])):__='matmul','import'
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello world!
how do i acess a element in a python class by a string variable
The getattr function might be what you're looking for.
x.__dict__.__getitem__(attr), probably
except for slotted attrs
but that's beside the spec
ok switched my implementation but now i am getting powershell yelling at me
+ .
+ ~
Missing expression after '.' in pipeline element.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingExpression```
why powershell be angry
yes.
are you in the right channel?
!e ```py
class phello('matmul',import,metaclass=lambda*:type('',(),{[1][0]:[1][1]})()@(type('',(),{[1][0]:lambda*:[1]})()@_[0])):...
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello world!
>>> def test_reassign():
... abc = 'Old Value'
... print(abc) # 'Old Value'
... locals()['abc'] = 'New Value'
... print(abc) # 'New Value'
...
>>> test_reassign()
Old Value
New Value
>>>
``` i made the `locals()` mapping mutate the actual locals
my rough guess: locals is overwritten and does some inspect stuff
well i did some code that modifies the behavior of frame.f_locals (which is a getter)
__builtins__.locals = lambda:sys._getframe(1).f_locals
so this is what makes locals work
hah, almost correct. locals is overwriten but its just getframe not inspect
but frame.f_locals now returns a custom object that handles the modification of the fastlocals array
Hey @rugged sparrow!
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/ejiyoremuv.py @broken mesa @floral meteor
that is all the code that lets the frame.f_locals trickery work
i use the nb_invert slot function because the C function takes one py_object argument, calls __invert__ and returns the result directly
and frame didnt have __invert__ already
ya now you can replace
@lambda c:c()
class yay:
def __some_dunder__(self, *a):
return do_stuff(*a)
with
class yay(metaclass=lambda*a:type(*a)()):__some_dunder__=lambda*a:do_stuff(*a)
i can yea but i dont feel the need to in this case lol
i just needed some singletons with custom reprs
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Ellipsis
oh well that has a different repr to its str
!e ```py
from ctypes import *
from collections.abc import MutableMapping
import sys
base_size = sizeof(c_void_p)
FrameType = type(sys._getframe())
@lambda c:c()
class Null:
def repr(self):
return '<NULL>'
@lambda c:c()
class rec:
def repr(self):
return '...'
class f_locals(MutableMapping):
invert = None
def init(self, frameobj):
self.frameobj = frameobj
def __repr__(self):
return f'locals({repr({key: rec if value is self else value for key, value in self.items()})})'
def _getlocp(self):
addr = id(self.frameobj) + FrameType.__basicsize__ - base_size
buffer = addr.to_bytes(base_size, sys.byteorder)
loc_p = POINTER(py_object).from_buffer_copy(buffer)
return loc_p
def __getitem__(self, key):
names = self.frameobj.f_code.co_varnames
if key not in names:
raise KeyError(key)
loc_p = self._getlocp()
try:
return loc_p[names.index(key)]
except ValueError:
return Null
def __setitem__(self, key, value):
names = self.frameobj.f_code.co_varnames
if key not in names:
raise KeyError(key)
loc_p = self._getlocp()
if value is not Null:
loc_p[names.index(key)] = value
else:
cast(loc_p, POINTER(c_void_p))[names.index(key)] = None
def __delitem__(self, key):
names = self.frameobj.f_code.co_varnames
if key not in names:
raise KeyError(key)
loc_p = self._getlocp()
cast(loc_p, POINTER(c_void_p))[names.index(key)] = None
def __iter__(self):
return iter(self.frameobj.f_code.co_varnames)
def __len__(self):
return len(self.frameobj.f_code.co_varnames)
def foo():
f_locals(sys._getframe())['abc'] = 'value'
print(abc)
abc = None
foo()
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
value
you can use f_locals class outside of the other weirdness to get a mapping that represents a frames locals
yea thats why i just did a one off
whats wrong with
rec=type('rec',(),dict(__repr__=lambda s:'...'))()?
oof
figured out where it is
POINTER(py_object) doesnt handle python refcounts
https://paste.pythondiscord.com/utaresumuw.py fixed version
does the attr module have much use?
i havent really ever used it
!e ```py
import attr
class Test(metaclass=lambda*a:attr.s(type(*a))):
a=attr.ib(4)
t = Test(4)
print(t)
print(dir(t))
print(t.a)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | Test(a=4)
002 | ['__attrs_attrs__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a']
003 | 4
so you coulda turned your init function into
@attr.s
class f_locals(MutableMapping):
__invert__=None
frameobj=attr.ob()
I broke my brain
I'm running on my stomach rn, and it says get food, so brb nerds.
ok i broke my usb check this out
You can still contribute to discussion here if you want, using online Python and so on.
"A device attached to the system is not functioning"
The same for you: even if Python was on your USB, you can still use it.
i deliberately sacrificed that usb i was gonna burn a pop!_os image to it.
me nether, im trying to install it
burn the disk image! sacrifice the usb! please the os!
maybe i should just wipe the usb and start again
diskpart says it's unusable OH NO
idk but i cant even format it
16gb
ive attacked this disk from almost every angle
maybe i should try booting from it XD it should have pop os on it
aight ill git push all my C: drive code
Can itpy if True: pass elif True: pass elif True: pass else: pass #if just one lineinstead ofpy if True: pass elif True: pass elif True: pass else: passif all code line just one line?
yes but that is just the equivalent of pass
ok
@maiden blaze @terse mortar Alright, there's a way you can help the code golf challenges be a thing. The main thing that I don't have time for is to dedicate time to come up with good prompts that are well suited to esoteric-ness/code-golfness. If y'all can help contribute to that I can probably get the challenges going on the staff side
interesting
I mean im down, where do you want us to put the suggestions?
You can DM them to me for the time being until I get some better organizing stuff set up
aight
we can setup of a simple django site for this, ks for working on something similar
with the help of snekbox
@boreal slate I have an idea of what I want it to look like. I just need to properly scope it out and run it past a few admins who had worked on a similar system previously.
ok cool!
I think I have a fairly good idea, will DM you soon||โข๏ธ||
Ban all newlines unless the indent is increased by one
by banning those things do you mean banning them from occurring at all or just banning them from occurring in the conventional way in the program's code
i.e. are you allowed to use the value True if you obtain it as 1>0, or grab modules with __import__
hey, was just messing around in code golf when I found this weird thing
I've got no idea why lambdaa:chr(1) doesn't throw an error or return any value
if it's parsed as a lambda, it should return a function, but it isn't? no clue what python is interpreting this as
!e
lambdaa:chr(1)
@ebon ingot :warning: Your eval job has completed with return code 0.
[No output]
that is annotating a variable named lambdaa with the annotation chr(1)
!e
lambdaa: chr(1)
print(__annotations__)
@proper vault :white_check_mark: Your eval job has completed with return code 0.
{'lambdaa': '\x01'}
TIL about annotations in python
I'll be off to do some research, thanks @proper vault!
does annotation serve any pythonic purpose? i.e. is there any purpose other than type hinting for people reading the code?
pydantic uses it for models
it is not a pure type hint feature, but that is the most popular usage
ah... is it right to say that the idea behind it is to allow extensibility for 3rd party (and also in-house) type validation packages?
and for IDEs and stuff
or are there bigger plans coming up for type enforcing in pure python?
no, python will remain duck typed forever
there are far too many things where type enforcement just doesn't work soundly for it to be viable
I don't yet fully understand it, but here's an explanation: https://stackoverflow.com/questions/1325673/how-to-add-property-to-a-class-dynamically
Basically, setattr needs to add the attribute to the class not the instance.
Right. This should work.
class Packet:
def __init__(self):
for field_name in self.fields.keys():
def accessor(self):
return self.fields[field_name]
def setter(self, value):
self.fields[field_name] = value
setattr(Packet, field_name, property(accessor, setter))
class HandshakePacket(Packet):
fields = {
'protocol_version': 0,
}
Also not sure why you wanted to eval. I changed those lines as well.
I would actually do setattr(self.__class__, field_name, property(accessor, setter))
It's not equal. I think your version is more correct. The equal way would be __class__
Yep, that's why I mentioned it
It should be set in __init_subclass__
woops
This may not be the right place to ask this (sorry in advance if its not), but its for something at least somewhat esoteric.
Does anyone know why this works in normal cpython, but in snekbox/!eval gives an error (TypeError: <module '__main__' (built-in)> is a built-in module), and how to make it work in snekbox?
import inspect
import sys
print(inspect.getsource(sys.modules[__name__]))
Duck typing goes a long way towards obfuscation
I.e. hide a whole bunch of functions in what looks like numeric operations
I'd say it's because it's not safe code
and therefore blocked by the sandbox?
@drifting grove it is due to how snekbox works. all code in snek box is ran as such -> python3 -c "{code}"
!e ```py
from ctypes import *
_argv = POINTER(c_wchar_p)()
_argc = c_int()
pythonapi.Py_GetArgcArgv(byref(_argc), byref(_argv))
orig_argv = _argv[:_argc.value]
print(orig_argv)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
['/usr/local/bin/python', '-Squ', '-c', 'from ctypes import *\n\n_argv = POINTER(c_wchar_p)()\n_argc = c_int()\npythonapi.Py_GetArgcArgv(byref(_argc), byref(_argv))\norig_argv = _argv[:_argc.value]\nprint(orig_argv)']
^ the above gets the original input to the python binary so its easy to see how python is started in snekbox
you can actually use the __main__ module to fingerprint in what state python code is ran
no problem, i had the same question a while back
Ok
I'm going to abuse this as much as I can (in a good way)
!e
import sys
print(sys.argv)
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
['-c']
Interesting
@sick hound :white_check_mark: Your eval job has completed with return code 0.
-2
3.10 adds sys.orig_argv
Ooh
that gives the same as the above
Hackery
87% thru extracting files
Two usbs committed to being sacrificed
Battery percentage is moving faster than the install percentage
@sick hound :white_check_mark: Your eval job has completed with return code 0.
False
@sick hound :white_check_mark: Your eval job has completed with return code 0.
False
!e ```py
c = True
from sys import*
globals().setitem(argv[0][1],not eval(argv[0]))
print(c)
@snow beacon :white_check_mark: Your eval job has completed with return code 0.
False
@sick hound :white_check_mark: Your eval job has completed with return code 0.
0
nice i dont understand anything
sys.argv is a list of all of the command line arguments, in this case ["-c", ...]. globals() is a dictionary of all of the variables in the global scope. If you do globals()["a"] = 1 then a is now 1. globals().__setitem__ is a method that does that. You give it a name and something to set that name to, and it does the setting. sys.argv[0][1] is "c", so it sets the c variable. It sets it to ~eval(argv[0]), which is ~eval("-c"), ~(-c), ~-True, which is basically True - 1. Since Booleans are a subclass of int, True - 1 is 1 - 1 which is 0. So c gets set to 0.
ok
isnt there the argparse module
that can handle arguments
I believe it's a wrapper over sys.argv.
And I think it would ignore the first argument anyway.
@sick hound :white_check_mark: Your eval job has completed with return code 0.
False
!e
import sys
print(sys.argv)
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
['-c']
hella
I wonder if there's a way to do something along the lines of
from * import *
But like dynamicly
!d pkgutil.iter_modules
pkgutil.iter_modules(path=None, prefix='')```
Yields [`ModuleInfo`](https://docs.python.org/3/library/pkgutil.html#pkgutil.ModuleInfo "pkgutil.ModuleInfo") for all submodules on *path*, or, if *path* is `None`, all top-level modules on `sys.path`.
*path* should be either `None` or a list of paths to look for modules in.
*prefix* is a string to output on the front of every module name on output.
Note
Only works for a [finder](https://docs.python.org/3/glossary.html#term-finder) which defines an `iter_modules()` method. This interface is non-standard, so the module also provides implementations for [`importlib.machinery.FileFinder`](https://docs.python.org/3/library/importlib.html#importlib.machinery.FileFinder "importlib.machinery.FileFinder") and [`zipimport.zipimporter`](https://docs.python.org/3/library/zipimport.html#zipimport.zipimporter "zipimport.zipimporter").
Changed in version 3.3: Updated to be based directly on [`importlib`](https://docs.python.org/3/library/importlib.html#module-importlib "importlib: The implementation of the import machinery.") rather than relying on the package internal [**PEP 302**](https://www.python.org/dev/peps/pep-0302) import emulation.
just run through this and import
So instead of just straight up importing every possible module, if you make a statement like this
math.sqrt(5)
Without importing math, then ittle catch the error and then attempt to import it
Hmm
ah, I think chillaxan made something very similar
but it just suggested the module, rather than importing it straight up
Ah right
the general idea is replace globals() with a dict that will import
I'm in class rn but I might give it a shot when I get home
if you're working inside a class context you can emulate this with a metaclass
Even if its kinda already been mostly done
class _(AutoImport):
print(math.sqrt(5))
where AutoImport's metaclass overrides __prepare__
heck, you could even do something like
class Blah(type):
@classmethod
def __prepare__(mc, n, bs): # custom namespace here
def __new__(mc, n, bs, ns): return bs[0]
class _(metaclass=Blah): ...
=>
class _(_):
# your code with auto-imports here
so the actual class creation is just a wrapper
all within the confines of "safe" python code :>
you could probably use fishhook for this actually
dict.__getitem__?
Can you hook ModuleType.prepare?
A quick little thing I came up with to detect if the code is being run in Snekbox in case anyone else needs it for some reason.
snekbox is True if it is run in Snekbox, False otherwise.
There are probably cases when it would give a false positive, but its probably good enough for most things
snekbox=("built-in"in str(__import__("sys").modules[__name__]))
It works because sys.modules[__name__] is a builtin in snekbox
It's not just snekbox that works like that
>>> import __main__
>>> __main__
<module '__main__' (built-in)>
yeah
Or just doing this
> python -c "import __main__; print(__main__)"
<module '__main__' (built-in)>
I think that might be what snekbox does
Not sure though
I just assumed it would mainly be used for things that can be run in both snekbox and python, but uses something not in snekbox
like
if snekbox:
# version without internet access or whatever. maybe has example response for reb request or something
else:
# version for regular python with internet
that just tests if you are running interactively or from a file as far as I can tell
I think that might be what it does
But it also detects when its run with python -c "code"
which I think is what snekbox does
yeah, I considered that also interactive
you could use ```py
import sys
sys.argv[0] == '-c'
Oh and sys.modules[key] is kinda like __import__(key) except that if it isn't in sys.modules then it will import it
really?
And it doesn't even have the word import in it ๐
so its less obvious what it does
!e ```py
import os
print('/snekbox/' in os.environ.get('PYTHONPATH', ''))
@proper vault :white_check_mark: Your eval job has completed with return code 0.
True
dang I guess I should have done my research on how snekbox works
It won't import modules if they aren't found. Sys.modules is just the module cache
!e Basic versions of #define and #include ```py
import sys
def process(lines):
imports = []
for line in lines:
if line.strip().startswith('#include'):
imports.append('import '+line.split()[1])
for i in imports:
lines.insert(0,i)
defs = {}
for line in lines:
if line.strip().startswith('#define'):
defs[line.strip().split()[1]] = line.strip().split()[2]
for d in defs:
for i in range(len(lines)):
lines[i] = lines[i].replace(d,defs[d])
return lines
snekbox=("built-in"in str(sys.modules[name]))
if snekbox:
#from chilaxan on discord .gg/python (message link: #esoteric-python message)
from ctypes import POINTER,c_wchar_p,c_int,pythonapi,byref
_argv = POINTER(c_wchar_p)()
_argc = c_int()
pythonapi.Py_GetArgcArgv(byref(_argc), byref(_argv))
code = _argv[:_argc.value][-1]
else:code = import("inspect").getsource(sys.modules[name])
lines = code.split('\n')
for line in lines:
x = globals().get('x',0) + 1
if line == 'sys.exit()':break
exec('\n'.join(process(lines[x:])))
sys.exit()
#######################################
#include math
#define cake "lie"
print(math.sin(42))
print(cake)
@drifting grove :white_check_mark: Your eval job has completed with return code 0.
001 | -0.9165215479156338
002 | lie
Yeah...if it's not found in the cache then it will import it
>>> import sys
>>> sys.modules['discord']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'discord'
>>> __import__('discord')
<module 'discord' from '...\\discord\\__init__.py'>
>>> sys.modules['discord']
<module 'discord' from '...\\discord\\__init__.py'>
Oh I thought you were saying that sys.modules[key] would import key
Automatically
Oh, no
!e I'm guessing this is the only way to print hello world with no brackets and no whitespace
__package__='__hello__';from.import*
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
Hello world!
. is __package__
import sys
import io
__print = print
class Fake(io.StringIO):
def write(self, *args, **kwargs):
pass
def _print(*args, sep=" ", end="\n", file=sys.stdout, flush=False):
__print(*args, sep=sep, end=end, file=Fake, flush=flush)
def autoimport():
if __name__ == "__main__":
with open(__file__, mode="r", encoding="utf-8") as f:
file = f.read()
mods = [m.__name__ for m in sys.modules.values() if m]
a = globals().copy()
a["__name__"] = "__exec__"
__builtins__.print = _print
while True:
try:
exec(file, a, locals())
except NameError as e:
module = str(e).split("'")[1]
if module in mods:
globals()[module] = __import__(module)
a = globals().copy()
a["__name__"] = "__exec__"
else:
break
__builtins__.print = __print
so i made this
its terrible
it doesnt work on snekbox cos it works by reading the file
and im pretty sure that if you try and doing something tricky ittle break
but it execs the code, catches any errors, and then automatically imports into the globals the required modules
It's the module's package
Perhaps this might help?
It works on snekbox but not regular python
from ctypes import *
_argv = POINTER(c_wchar_p)()
_argc = c_int()
pythonapi.Py_GetArgcArgv(byref(_argc), byref(_argv))
orig_argv = _argv[:_argc.value]
code = _argv[-1]
print(code)
From:
#esoteric-python message
Ooooh
And then with that "detect if ur in snekbox" code snippet, then it can work "universally"
I would edit it but I'm in bed rn
yeah
just realised that everything isinstance(..., object)
It's all objects
I think that's Python's tagline.
All classes are also issubclass(..., type). Including type.
~ python3 -i name_hooks.py
>>> implicit_imports()
>>> __hello__
<stdin>:1: RuntimeWarning: implicitly importing module '__hello__'
Hello world!
<module '__hello__' (frozen)>
>>> ```
wrote a version that works by hooking globals at runtime
!e ```py
from ctypes import py_object, c_char
import atexit, builtins, sys, dis
def init_missing_hook(dct, func):
ob_base_p = py_object.from_address(id(dct) + 8)
class missing_hook(dict):
slots = ()
def missing(self, key, ob_base_p=ob_base_p, builtins=builtins):
try:
ob_base_p.value = builtins.dict
return (builtins.dict | self)[key]
except KeyError:
return func(self, key)
finally:
ob_base_p.value = class
ob_base_p.value = missing_hook
@atexit.register
def unhook():
ob_base_p.value = dict
return unhook
def builtinexc(exc, depth=1):
frame = sys._getframe(1 + depth)
addr = id(frame.f_code.co_code) + bytes.basicsize - 1
mem = (c_char * len(frame.f_code.co_code)).from_address(addr)
mem[frame.f_lasti + 2:frame.f_lasti + 4] = bytes([dis.opmap['RAISE_VARARGS'], 1])
return exc
import warnings, importlib.util
def auto_import(dct, name):
if importlib.util.find_spec(name):
warnings.warn(f'implicitly importing module {name!r}', RuntimeWarning, 3)
mod = import(name)
dct[name] = mod
return mod
else:
return builtinexc(NameError(f'name {name!r} is not defined'), 2)
def implicit_imports():
init_missing_hook(sys._getframe(1).f_globals, auto_import)
implicit_imports()
print(os)
print(math.sin(42))```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:46: RuntimeWarning: implicitly importing module 'os'
002 | <module 'os' from '/usr/local/lib/python3.9/os.py'>
003 | <string>:47: RuntimeWarning: implicitly importing module 'math'
004 | -0.9165215479156338
https://github.com/chilaxan/pysnippets/blob/main/name_hooks.py uses code from here
General messing around with the internals of python - chilaxan/pysnippets
!e
print(issubclass(int, type), issubclass(int, object))
print(isinstance(int, type), isinstance(int, object))
All classes are instances of type, and all classes are subclasses of object. Classes, by default, are not subclasses of type, and type is an object subclass, not a type one.
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
001 | False True
002 | True True
Right, my mistake, instances of type since it's the metatype.
Hmm, can you use fishhook / something or other to un-implement some of the dunders from object, like eq?
technically yes
I guess the question is whether you can do that, but for specific classes
I know they're slotted, or something ยฏ_(ใ)_/ยฏ
if you set the slot function pointers to null then that would effectively disable that dunder
from ctypes import py_object, c_char
import atexit, builtins, sys, dis
def init_missing_hook(dct, func):
ob_base_p = py_object.from_address(id(dct) + 8)
class missing_hook(dict):
__slots__ = ()
def __missing__(self, key, ob_base_p=ob_base_p, builtins=builtins):
try:
ob_base_p.value = builtins.dict
return (builtins.__dict__ | self)[key]
except KeyError:
return func(self, key)
finally:
ob_base_p.value = __class__
ob_base_p.value = missing_hook
@atexit.register
def unhook():
ob_base_p.value = dict
return unhook
def builtinexc(exc, depth=1):
frame = sys._getframe(1 + depth)
addr = id(frame.f_code.co_code) + bytes.__basicsize__ - 1
mem = (c_char * len(frame.f_code.co_code)).from_address(addr)
mem[frame.f_lasti + 2:frame.f_lasti + 4] = bytes([dis.opmap['RAISE_VARARGS'], 1])
return exc
import warnings, importlib.util
def auto_import(dct, name):
if importlib.util.find_spec(name):
warnings.warn(f'implicitly importing module {name!r}', RuntimeWarning, 3)
mod = __import__(name)
dct[name] = mod
return mod
else:
return builtinexc(NameError(f'name {name!r} is not defined'), 2)
def implicit_imports():
init_missing_hook(sys._getframe(1).f_globals, auto_import)
implicit_imports()
print(os)
print(math.sin(42))
Windows can run python in safe mode
Yaaass I can make runtime error now I just need to mix it with some ordinals
How?
OK that is both infinitely more cursed and wayyy more elegant. Well done!
Hello, why this not works?
>>> (([()for()in()if()==()])for([()for()in()if()==()])in([()for()in()if()==()])if([()for()in()if()==()])==([()for()in()if()==()]))
SyntaxError: cannot assign to list comprehension
If this works:
>>> ([()for()in()if()==()])
[]
because you have a for loop where the assignment target (for x <-- in []) is a list comprehension which is invalid
!e ```py
def gen(depth: int) -> str:
x = "{0}for()in{0}if{0}"
for _ in range(depth):
x = x.format("(" + x + ")")
return "(" + x.format(())+ ")"
print(gen(0))
print(gen(1))
print(gen(2))
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
001 | (()for()in()if())
002 | ((()for()in()if())for()in(()for()in()if())if(()for()in()if()))
003 | ((((()for()in()if())for()in(()for()in()if())if(()for()in()if()))for()in((()for()in()if())for()in(()for()in()if())if(()for()in()if()))if((()for()in()if())for()in(()for()in()if())if(()for()in()if())))for()in(((()for()in()if())for()in(()for()in()if())if(()for()in()if()))for()in((()for()in()if())for()in(()for()in()if())if(()for()in()if()))if((()for()in()if())for()in(()for()in()if())if(()for()in()if())))if(((()for()in()if())for()in(()for()in()if())if(()for()in()if()))for()in((()for()in()if())for()in(()for()in()if())if(()for()in()if()))if((()for()in()if())for()in(()for()in()if())if(()for()in()if()))))
these all evaluate to [], too
obviously the size grows at 3^n, but :>
in fact, [*eval(gen(4))] is enough to freeze for a solid few minutes
!e ```py
[print(69)for()in((),)]
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[15]
!e [print(...)for()in((),(),())]
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | Ellipsis
002 | Ellipsis
003 | Ellipsis
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
<generator object <genexpr> at 0x7f7dd85276d0>
!e
print([()for()in[1]])
@simple crystal :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 1, in <listcomp>
004 | TypeError: cannot unpack non-iterable int object
It doesn't. Stuff like that only works when I do it
!e
print([1 for()in[1]])
XD
@simple crystal :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 1, in <listcomp>
004 | TypeError: cannot unpack non-iterable int object
!e print([()for()in((),(),())])
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
[(), (), ()]
!e print([0x00for()in((1),(2),(3))])
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
[15]
whoops
Lol
!e print([()for()in((1),2(),(3))])
@simple crystal :x: Your eval job has completed with return code 1.
001 | <string>:1: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | TypeError: 'int' object is not callable
What advanced mathematical operation is this?
lol my gf is talking
!e print(*['K'for()in[(),(),()]],sep='')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
KKK
hard to focus
Tell her I said hi
!e print([()for()in((1),(2),(3))])
@simple crystal :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 1, in <listcomp>
004 | TypeError: cannot unpack non-iterable int object
You need commas next to the numbers
@simple crystal :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 1, in <listcomp>
004 | ValueError: too many values to unpack (expected 0)
Lol, okay just make the tuples empty
thought so
maybe not usefulf or golf cuz you need the extra 2 parens
hmm maybe it's minus 1 byte
Empty unpacking works only with empty sequence
!e print([()for()in((),)*3])
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
[(), (), ()]
You can use it to repeat an arbitrary command n times instead of using range(n)
yeah
Which generates a variable each iteration
I'm wondering if it saves any bytes
But this creates an empty namespace
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
[(), (), ()]
But that needs spaces
!e print([()for()in[()]*3])
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
[(), (), ()]
!e ```py
print(len("print([()for()in[()]*3])"))
print(len("print([()for _ in[1]*3])"))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 24
002 | 24
Bruh
Well I'd say mines memory optimised as it doesn't make an integer literal each run, just an empty array
although they're probably the same size
anything can be done by instantiating classes
cmm
!e ```py
import attr
class call:
def new(self,*a,**k):
class wrapper:new=lambda s,f:f(*a,**k)
return wrapper
@call()
class cout:lt,lshift,le,echo=print,lambda s,o:print(end=str(o))or s,lambda s,i:print(*i)or s,print
@call(end=10)
@attr.s
class forloop:
start, end, step = attr.ib(0), attr.ib(1), attr.ib(1)
def func(self):
cout<self.start
return type(self)(self.start+self.step,self.end,self.step)
def del(self):
@call(self.end>=self.start+self.step)
class runif:
def init(s,cond):
if cond:self.func()
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
yas!
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
damn it
wat?
Apparently I have python 3.9.2150.1013
!e ```
L ,=[(([0x0for(sum([((+0xCor{0j},)[~0b0]&3)&0xDfor[0j]in((-0b1|0b0,),)](0xEor(1,))),)in((0o0,),)][0b0]<<2)+([9for[i]in[[0x0]]][0x0]),)[0o0]]
print(L)```
@tribal moon :white_check_mark: Your eval job has completed with return code 0.
[69]
How can I add a view port in tkinter for playing YouTube videos?
I am shocked that's a possible thing, but apparently people are doing things like that, for instance here: https://stackoverflow.com/questions/55197752/playing-video-with-audio-on-a-tkinter-frame
Empty tuple and integer[-5..256] are all the same space complexity - O(1)
actually in my code () wasn't nested in list
you have [()]
but only () is enough
!e py print([()for()in()if()==()])
@sly root :white_check_mark: Your eval job has completed with return code 0.
[]
im using it in my obfuscator for list creation
yeah, I needed to nest so I could multiply
since it's the same no of bytes I'll use it for swag purposes in golf
ofc usually if you want to loop a number of times you multiply a string in an exec in golf
!e print([()for()in()*3])
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
[]
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
[(), (), ()]
I want the 3 iterations not the zero haha
islist=lambda x:[]==x*0
that's the shortest way to check ya
the \ themselves should be escaped. Also, this should go in a general help channel
A
:incoming_envelope: :ok_hand: applied mute to @quick edge until 2021-05-01 18:15 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
Make it a raw string (add r before the quotes, ie r"C:\Users\User\Etc"
been doing some tomfoolery as of late:```py
Get any URL
response = ractf.co.uk
print(response.status_code) # => 200
Paths work too!
response = google.com/memery/nested
print(response.status_code) # => 404
Subdomains also work, of course
response = sha256.badssl.com
print(response.status_code) # => 200
Any attribute from requests.Response is supported
This is also valid syntax
print(google.com.text) # => <!DOCTYPE html><html lang=...
how did you pull that off?
using this mess
import requests
from ctypes import py_object
import atexit, builtins
class DotAggregator:
def __init__(self, base):
self.url = base
def __getattr__(self, name):
sentinel = object()
if getattr(requests.Response(), name, sentinel) is not sentinel:
return getattr(requests.get(str(self)), name)
self.url += "." + name
return self
def __truediv__(self, ext):
self.url += "/" + str(ext)
return self
def __str__(self):
return "https://" + self.url
def dict_sub(ob_base_p, func):
class sub(dict):
__slots__=()
def __missing__(self,key,ob_base_p=ob_base_p,builtins=builtins):
try:
ob_base_p.value=builtins.dict
return{**builtins.__dict__,**self}[key]
except:return func(self,key)
finally:ob_base_p.value=__class__
return sub
ob_base_p=py_object.from_address(id(globals())+8)
ob_base_p.value=dict_sub(ob_base_p,lambda s,k:DotAggregator(k))```
come to think of it URLRoot is kinda useless
oh well
ahh you're using globals hooking, clever
updated it to remove URLRoot
yeah, I do have an older version that doesn't use global hooking, but it unfortunately doesn't support /whatever
>>> (google.com/a).url
'google.com/https://a'
``` i think there may be an issue
aw shucks i forgot that's why i kept urlroot
use this older version
import requests
from ctypes import py_object
import atexit, builtins
class DotAggregator:
def __init__(self, base):
self.url = "https://" + base
def __getattr__(self, name):
sentinel = object()
if getattr(requests.Response(), name, sentinel) is not sentinel:
return getattr(requests.get(str(self)), name)
self.url += "." + name
return self
def __truediv__(self, ext):
self.url += "/" + str(ext)
return self
def __str__(self):
return self.url
class URLRoot:
def __init__(self, root):
self.root = root
def __str__(self):
return self.root
def __getattr__(self, name):
return DotAggregator(self.root + "." + name)
def dict_sub(ob_base_p, func):
class sub(dict):
__slots__=()
def __missing__(self,key,ob_base_p=ob_base_p,builtins=builtins):
try:
ob_base_p.value=builtins.dict
return{**builtins.__dict__,**self}[key]
except:return func(self,key)
finally:ob_base_p.value=__class__
return sub
ob_base_p=py_object.from_address(id(globals())+8)
ob_base_p.value=dict_sub(ob_base_p,lambda s,k:URLRoot(k))```
can you import the function class from somewhere?
I can do type(lambda:...) to get it but I was wondering where it is normally
it says its module is builtins but I don't see it
!e print(type(lambda:...).__module__)
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
builtins
!e print('function' in __builtins__.__dict__)
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
False
!e print(type(lambda:...).__qualname__)
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
function
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
<class 'function'>
types, IIRC.
how does the argdefs argument of function class work?
it wants a tuple but I'm not sure what format
yeah using exec() is way better than this lol
Tuple of strings?
I don't think you can return though
I think it's just a tuple of defaults for args that have to already exist for the code object
so when I compile the code object I need to compile a function definition anyway then find the const that is that function and pass that to the function class
so might as well just exec()
Or...use def
I was trying to figure out how to do what turtle.py does without using exec()
i.e. makes all of its public class methods global functions
but it seems to be far better to just use exec() like it already does
because figuring out which const in the compiled code object is the desired function is a pain
and building a code object from scratch is a lot of overhead avoided with exec()
ah how would you use closures?
## The following mechanism makes all methods of RawTurtle and Turtle available
## as functions. So we can enhance, change, add, delete methods to these
## classes and do not need to change anything here.
__func_body = """\
def {name}{paramslist}:
if {obj} is None:
if not TurtleScreen._RUNNING:
TurtleScreen._RUNNING = True
raise Terminator
{obj} = {init}
try:
return {obj}.{name}{argslist}
except TK.TclError:
if not TurtleScreen._RUNNING:
TurtleScreen._RUNNING = True
raise Terminator
raise
"""
def _make_global_funcs(functions, cls, obj, init, docrevise):
for methodname in functions:
method = getattr(cls, methodname)
pl1, pl2 = getmethparlist(method)
if pl1 == "":
print(">>>>>>", pl1, pl2)
continue
defstr = __func_body.format(obj=obj, init=init, name=methodname,
paramslist=pl1, argslist=pl2)
exec(defstr, globals())
globals()[methodname].__doc__ = docrevise(method.__doc__)
_make_global_funcs(_tg_screen_functions, _Screen,
'Turtle._screen', 'Screen()', _screen_docrevise)
_make_global_funcs(_tg_turtle_functions, Turtle,
'Turtle._pen', 'Turtle()', _turtle_docrevise)
this is what it does
you just define a function inside the for loop
that does what __func_body does
and then set globals()[methodname] = new_func
oh makes sense
I might try to do that later and see if I can get it to work
would that be a closure or would the only surviving reference be in globals?
o its a closure
what's the weirdest thing you can make __new__ do and still return an instance of the class containing it
like is there a way without weird monkeypatching to avoid an explicit super().__new__(cls) call in __new__ and still instantiate the class?
I'm writing a module that defines a list base class which makes subclasses function like lists i.e. return type self instead of type list when multiplied, concatenated, sliced
... there's a UserList in collections >_>
object.__new__(cls)?
!e
class test(list):
def __new__(cls):
return object.__new__(cls)
print(test())
@simple crystal :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | File "<string>", line 3, in __new__
004 | TypeError: object.__new__(test) is not safe, use list.__new__()
but yeah that works when inheriting from object directly
I should have specified I mean weird stuff to do when constructing subclasses of built in mutable sequences
list.__new__(cls)?
yeah that also works, doesn't do anything weird though
class ListBaseClass(list):
"""Like list if it was meant to be subclassed."""
def __init(self, n):
"""Set own value and return self."""
super().__init__(n)
return self
def __add__(self, n):
"""Concatenate and return same type as self."""
return self.__new__(self.__class__).__init(super().__add__(n))
def __mul__(self, n):
"""Multiply and return same type as self."""
return self.__new__(self.__class__).__init(super().__mul__(n))
def __rmul__(self, n):
"""Multiply and return same type as self if left operand doesn't have defined behavior."""
return self.__mul__(n)
def __getitem__(self, n):
"""If slicing, return same type as self."""
if isinstance(n, slice):
return self.__new__(self.__class__).__init(super().__getitem__(n))
else:
return super().__getitem__(n)
better UserList
at least, I don't think there's anything UserList does better
UserList is picky about __init__ and __new__ of subclasses and this isn't is the main advantage
strangely, deque already has all this functionality except obviously slicing
subclasses of deque return their own type from add and mul, unlike list, and it's also not picky about __new__ and __init__
I don't get the point of the UserX stuff in collections
well, UserList subclasses return their own type if multiplied, added, sliced
list subclasses do not
but I think they were originally made before you could actually subclass built-ins
the docs say, for example:
The need for this class has been partially supplanted by the ability to subclass directly from list
The need for this class has been partially supplanted by the ability to subclass directly from dict
etc
which implies they were originally for before it was possible
Oh right
!e
class test(list):
...
print(type(test()[:]))
from collections import UserList
class test(UserList):
...
print(type(test()[:]))
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
001 | <class 'list'>
002 | <class '__main__.test'>
So it's just backwards compatibility
that and the subclassing stuff are all I can tell as far as usefulness
the docs say it's useful to be able to access their value as an attribute... but imo that's not useful haha
UserString is basically a mutable string though
well, not rly, but you can replace the string itself inside the object
and probably the easiest thing to turn into a fake "mutable string"
is there a way to use contextlib.suppress to suppress StopIteration to make infinite loops?
not really, the iterator will have already exited by then
supress is essentially just except E: pass
If you could, the next question would be what is being yielded
Can't you just use itertools.cycle?
What's this channel for, I meann what does esoteric mean?
Wait can u @ me when if someone answers ,lol
So I could get a notification
Cursed code
is there a better way to get the built-in a sub class inherits from higher in the inheritance chain than self.__class__.__mro__[-2]?
with arbitrary number of superclasses in chain
@austere linden IT IS CURSED!
parsed = set(
sum(
[list(x.keys()) for x in
[urllib.parse.parse_qs(x) for x in
[urllib.parse.urlparse(x).query for x in example_urls]]],
[]
)
)
๐ณ
ah, the deque implementation is sorta hacky i.e. calls the definitions of its extend and __copy__ for concat and multiply and actually calls __new__ and __init__ on self in __copy__ def instead of directly creating a new one and that's why its subclasses return themselves if concatted or multiplied...
I was all excited thinking it'd be possible to make subclasses of built-ins behave by looking at deque but it's rly not worth it to copy this behavior
..in C, will continue making a Python module to fix this
unless one exists, I searched for a few things on pypi and nothing came up
the hardest part: thinking of a name
auto_operatio is the best name I can think of cuz operators return Type[self]
my dynamic version worked first try (minus testing for mutables which employ slicing which require additional logic) and I must say I have to thank this channel for that
๐๐๐
Hey @simple crystal!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
https://paste.pythondiscord.com/bunohojayo.py mixin to make built-in mutables behave when subclassed
need tests for sets and dicts still
A weird code I made today generates large lists infinitely.
#This code generates large lists of n-tuples of from v0 to v_(n) (v0>=v1>=v2>=...>=v_(n-1)>=v_(n)>=1)
j=2
while True:
a=eval(str("[("+"{},"*(j-1)+"{}) for {} in range({})"+" for {} in range(1,{}+1)"*(j-1)+"]").format(*["v"+str(i) for i in range(j)],"v0",str(j+1),*["v"+str(i//2*3-i+1) for i in range(j*2-2)]))
print(j)
print(a)
j=len(a)
Works on Python IDLE 3.9.5
!e
#This code generates large lists of n-tuples of from v0 to v_(n) (v0>=v1>=v2>=...>=v_(n-1)>=v_(n)>=1)
j=2
while True:
a=eval(str("[("+"{},"*(j-1)+"{}) for {} in range({})"+" for {} in range(1,{}+1)"*(j-1)+"]").format(*["v"+str(i) for i in range(j)],"v0",str(j+1),*["v"+str(i//2*3-i+1) for i in range(j*2-2)]))
print(j)
print(a)
j=len(a)
@gaunt vessel :x: Your eval job has completed with return code 143 (SIGTERM).
001 | 2
002 | [(1, 1), (2, 1), (2, 2)]
003 | 3
004 | [(1, 1, 1), (2, 1, 1), (2, 2, 1), (2, 2, 2), (3, 1, 1), (3, 2, 1), (3, 2, 2), (3, 3, 1), (3, 3, 2), (3, 3, 3)]
005 | 10
006 | [(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), (2, 1, 1, 1, 1, 1, 1, 1, 1, 1), (2, 2, 1, 1, 1, 1, 1, 1, 1, 1), (2, 2, 2, 1, 1, 1, 1, 1, 1, 1), (2, 2, 2, 2, 1, 1, 1, 1, 1, 1), (2, 2, 2, 2, 2, 1, 1, 1, 1, 1), (2, 2, 2, 2, 2, 2, 1, 1, 1, 1), (2, 2, 2, 2, 2, 2, 2, 1, 1, 1), (2, 2, 2, 2, 2, 2, 2, 2, 1, 1), (2, 2, 2, 2, 2, 2, 2, 2, 2, 1), (2, 2, 2, 2, 2, 2, 2, 2, 2, 2), (3, 1, 1, 1, 1, 1, 1, 1, 1, 1), (3, 2, 1, 1, 1, 1, 1, 1, 1, 1), (3, 2, 2, 1, 1, 1, 1, 1, 1, 1), (3, 2, 2, 2, 1, 1, 1, 1, 1, 1), (3, 2, 2, 2, 2, 1, 1, 1, 1, 1), (3, 2, 2, 2, 2, 2, 1, 1, 1, 1), (3, 2, 2, 2, 2, 2, 2, 1, 1, 1), (3, 2, 2, 2, 2, 2, 2, 2, 1, 1), (3, 2, 2, 2, 2, 2, 2, 2, 2, 1), (3, 2, 2, 2, 2, 2, 2, 2, 2, 2), (3, 3, 1, 1, 1, 1, 1, 1, 1, 1), (3, 3, 2, 1, 1, 1, 1, 1, 1, 1), (3, 3, 2, 2, 1, 1, 1, 1, 1, 1), (3, 3, 2, 2, 2, 1, 1, 1, 1, 1), (3, 3, 2, 2, 2, 2, 1
... (truncated - too long)
Full output: too long to upload
successful.
def kill_python(*_):
import sys,os;os.system("")or sys.stderr.write('\x1b[31mFatal Python error: _Py_MorsObitusDecessus: Python has died.\nPython runtime state: deceased\x1b[0m\r\n')
import ctypes,random
while...:ctypes.py_object.from_address(random.randint(111111,id(type("",(),{})())+9)).value=type('DEATH',(type,),{'__del__':lambda*a:a})('death',(),{})
@rugged sparrow is there a way to optimise this crasher algorithm?
alright i'll try to make a dot notation globals hack
You can just segfault with ctypes.string_at(0)
Probably
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
-0x3ffffffb
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
0x1c0000005
negative a billion and a bit
!e ```py
a,b,c=1,2,3
if a-3:print(a!=3)
if b-3:print(b!=3)
if c-3:print(c!=3)
inequality golfing for integers
a,b,c=1,2,3
if a-3:print(1>0)
if b-3:print(1>0)
if c-3:print(1>0)
```Shorter.
It does the same thing.
it's the LHS that's being golfed
print(f"{a!=3=}") might be more demonstrative.
!e in that case
a,b,c=1,2,3
if a-3:print(a,'=/=',3)
if b-3:print(b,'=/=',3)
if c-3:3
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 1 =/= 3
002 | 2 =/= 3
the point is i'm using - instead of !=
i.e. ```py
class int:
...
def ne(self,other):
return bool(self-other)
def eq(self,other):
return not self!=other
ok, it seems i gotta remove existing dot notation syntax sugar to replace it :/
okay, full implementation is proving to be insane.
completely separating (getattr, setattr, delattr) and dot notation
i think i might have to make it not a struct array, in order to simplify it
!e ```py
exit=import("_sitebuiltins").Quitter('ab')
class cursed(metaclass=lambdaa:type(*a)()):
def getattr(self, s):
if s=='exit':exit()
else:return object.getattribute(self,s)
def setattr(self,n,v):
if n=='exit':exit(v)
else:object.setattr(self,n,v)
cursed.exit = 69
@floral meteor :warning: Your eval job has completed with return code 69.
[No output]
!e
[globals().setdefault('x', []).append(e) or e for e in range(5)]
print(x)
@edgy spire :white_check_mark: Your eval job has completed with return code 0.
[0, 1, 2, 3, 4]
@solid basalt a sneaky, self-actualizing listcomp
assignment operators are so yesteryear
That makes me physically ill to look at
It sets the default and returns the value, but if it already exists, it just returns the value. Hence that initializes at [], appends 0, then appends 1 thru 4 to the already existing value at x
yeah I think we got that
!e
class While:
___ = lambda self: ((exec(self.code), globals().update(locals()),
type(self)(self.condition, self.code)) if eval(self.condition) else ...)
def __init__(self, condition, code):
self.condition = condition
self.code = code
((x := getattr(self.__class__,
(setattr(self.__class__, (t := "__del__"), lambda ________: (...,...)),
t)[1]), setattr(x, "__code__", While.___.__code__)))
x = 3
While("x < 50", "x += 3")
print(x)
@gritty mesa :white_check_mark: Your eval job has completed with return code 0.
51
The new and improved while loop
I like for _ in iter(lambda: cond, False)
Or maybe to handle falsy values for _ in iter(lamdba: not cond, True)
If I'm doing a while True would that crash my computer
hmmmm
what about this
cond = 5 == 5
while cond:
print("True")
or this:
# Checking for 5 = 5
num1 = 5
num2 = 5
try:
num = (num1 - num2) / (num1 - num2)
except Exception:
print("They're equal")
!e
# Checking for 5 = 5
num1 = 5
num2 = 5
try:
num = (num1 - num2) / (num1 - num2)
except Exception:
print("They're equal")
@polar talon :white_check_mark: Your eval job has completed with return code 0.
They're equal
Condition checking through exceptions is too underrated, am I right?
!e
Checking for 6 = 5
num1 = 6
num2 = 5
try:
num = (num1 - num2) / (num1 - num2)
except Exception:
print("They're equal")
else:
print("Nopity nope, not the same!")
@polar talon :white_check_mark: Your eval job has completed with return code 0.
Nopity nope, not the same!
damn
You can use that to make loops too
you could do assert num1-num2
Most people come here for their daily dosage of insanity, I come here for my daily dosage of sanity.
I use functions that conditionally raise exceptions to pass to input validating functions so they can validate based on the exception raising func
way less hassle than passing to a function that returns a bool and dealing with the bool
and if I just want an int I can use int as the exception raising function
for example
Does anyone know how to do threading
don't fix it if it ain't broke
Hey guys can we assign custom value to True or False in python 3?
!e
from ctypes import py_object
py_object.from_address(id(True)+8).value = object
print(True)
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
<object object at 0x7fbf4c4b21a0>
thx
@sick hound @viscid nymph That is not changing the value of true, it is changing the type of True
oh
I do know that
If you want I could just do
!e
from ctypes import py_object
py_object.from_address(id(True)+8).value = object
py_object.from_address(id(True)).value = object()
print(True)
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
<object object at 0x7f443d9fd1a0>
It's the same output though :P
That also doesn't change True to object()
I guess so
import inspect, base64
plain_txt = inspect.getsource(caesar_quine)
encrypted_msg = []
length = len(plain_txt)
for i in range(length): encrypted_msg.append(plain_txt[i])
for e in range(length):
encrypted_msg[e] = (ord(encrypted_msg[e]))
encrypted_msg[e] = (encrypted_msg[e] + 3) % 256
encrypted_msg[e] = bin(encrypted_msg[e])
print(' '.join(encrypted_msg))```
This is a quine that encrypts itself in a caesar cipher
It prints its results in binary since 0-30 caused issues, and it gave me a few \r characters when I did
Im proud of that
I put it on github https://github.com/markl12s/Caesar_Quine/tree/main
That's neat. It things me of a program I wrote for the code obfuscation challenge on the server's esoteric challenges repo.
It also had a quine and encipherment.
how often does a obsufication challenge occur?
Not any more. I'm pretty sure the repo is archived.
By code obfuscation I mean code that obfuscates code, not just obfuscated code.
There might be some more coming soonโข๏ธ
You should make the file on GitHub a .py file lol
I've been having some issues with the PIL fork of pillow, specifically converting from a .eps file to .png or any other commonly used image format. Is that in anyone's area of expertise? I would greatly appreciate any help.
This doesn't really have to do with esoteric programming
you could try opening an help channel
Are any of those channels still open?
Judging by the timestamp, never mind.
I only had the first Google result to send anyway.
Why is it that None is so much smaller than other objects?
Are the struct fields special cased?
is it as big as a pointer?
@earnest wing None is only 2 fields, ref count and object type
!e print(None.sizeof())
ah still gotta refcount
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
16
!E
print(object().__sizeof__())
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
16
!e print(type.__sizeof__(type))
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
408
chunky boi
https://www.pyimagesearch.com/2016/03/28/measuring-size-of-objects-in-an-image-with-opencv/
I used this code to make a image measuring program. But the thing is, it only measures the image only once(and the same point multiple times when I repeat the code). How can I make this code measure an image at different parts at the same time like what they showed in the website? Am I doing something wrong?
I haven't used very much OpenCV. You could try asking in one of the help channels #โ๏ฝhow-to-get-help.
I figured out why turtle.py doesn't use a closure to make the methods global functions, it's so the call signature of the new function is the method call signature without self
there's no handy way to give an existing function a new call signature so exec is a good way to do it
You can zero the refcnt with ctypes
The field is still gonna be there tho
!e print(str.sizeof('yo mamma'))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
57
!e print(str.sizeof('a truck'))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
56
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[0]
!e (a:=[*range(10)])[0]=10;a.append(a.pop(0));
print(a)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
@floral meteor did you see my code a while ago that abused iterators and gc to make a tuple that contains itself?
Hang on I'm on phone
!e ```py
a=()
a+=(a,)
print(a)
Oh
Oof that copies it
Ok @rugged sparrow how'd you do it?
Y'know I keep thinking while I code why isn't there a getattribute augmented assignment? Other than it being a trinop rather than binop method
Oh wait
It's binop
So I don't have to do
flippity.floppity.funny.looking = flippity.floppity.funny.looking.thing
I would instead do
flippity.floppity.funny.looking .= 'thing'
Or is .= a thing already?
How do i hack python to make it a thing?
It'd dunder as something like __igetattr__
And also add an __icall__ while im there
!e print(import('sys').version)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 3.9.4 (default, Apr 5 2021, 18:26:27)
002 | [GCC 8.3.0]
I should update python
You can use the gc module to get a reference to the tuple while it's still being constructed from your iterator
!e ```py
import gc
class magic:
def length_hint(self):
return 1
def __iter__(self):
for obj in gc.get_objects():
if isinstance(obj, tuple):
try:0 in obj
except SystemError:
yield obj
break
tup = tuple(magic())
print(tup)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
((...),)
Noice
tuple(list(tuple(magic()))) # (((...),),)
XD
!e ```py
import gc
@print
@tuple
@list
@tuple
@list
@tuple
@lambda c:c()
class magic:
def length_hint(self):
return 1
def __iter__(self):
for obj in gc.get_objects():
if isinstance(obj, tuple):
try:0 in obj
except SystemError:
yield obj
break
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
(((...),),)
that's what it does for nested containers I think
I've run into it in normal usage anyway forgot exactly why ellipses shows up
ah
!e
some_list = []
some_list.append(some_list)
exec(f'print(some_list{"[0]"*1000})')
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
[[...]]
seven thousand line module, one decorator, all it does is add ">" before each print. just an idea
nO
class For:
def __init__(self, items, iterable, code):
self.items = items
self.iterable = iterable
self.code = code
def __del__(self):
try:
item = next(self.iterable)
exec(f"{self.items} = {item}")
exec(self.code)
globals().update(locals())
type(self)(self.items, self.iterable, self.code)
except StopIteration:
pass
For("x, y", enumerate(["hello", "world"]), "print(f'{x}: {y}')")
```Got a nice for loop alternative
Cool. You can also assign it to a value and then trigger it when needed
loop = For("x, y", enumerate(["hello", "world"]), "print(f'{x}: {y}')")
...
loop = "go!"
!e
y = lambda x:(exec('''
if x > 2:
globals()["g"]=4
else:
globals()["g"]=6''', f:={'x':x}) or f["g"])
print(y(2))
print(y(3))
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
001 | 6
002 | 4
ppl whining about lack of multiline lambdas have no ground to stand on
!e (a:=[1])[0]=0; print(a)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
[0]
!e print("1")
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1
what if i run discord bot on this?
discord.py isn't installed and you can't access the internet
oh
yeee
Plus it times out after a while.
Affirmative.
If you want multiline, use def. That's what def is for, to waste half your screen and mouse wheel life for a multiline function XD
Awww so I can't run urlopen either daaaaaamn
use the eval to mine for crypto ๐ง
alright it's insanity time
how would I optimise this?
def generate(k:int):
a = []; from threading import Thread
f = lambda n:a.append(int('9'*n)**99999)
for i in str(k):Thread(target=f,args=[int(i)]).start()
while len(a)<len(k.__str__()):...
return sum(a)
def main(SEED:int, KEY:list[int]):
mess = str(generate(SEED))
extract = lambda*a:[mess[i%len(mess)]for i in a]
result = int(''.join(extract(*KEY)))
print(result)
it thonks for ages then spits this out
>>> main(334467, [25,3856,936784,-65, -67, -5,2244])
6916073
>>>
ooh, and then i can esolangise the result to turn it into a message
I am so using this for ENCRYPTION
alright this is integerfuck, enjoy
from collections import defaultdict as d
def decode(n):
l,a,o=len(s:=str(n)),d(int),str();i=p=a[int()];b=[i]*2;c=8;t=0
while len(s)>=p:
def _0():a[i]+=1;a[i] %=1<<+ c;return i,c,o,t
def _1():a[i]-=1;a[i] %=1<<+ c;return i,c,o,t # i made "coerce encoding" operater XDDD
_2,_3=lambda: +i+ 1,c,o,t,lambda: +i- 1,c,o,t
_4=lambda:i,c,print(end=chr(a[i])or o+chr(a[i]),t
def _5():a[i]=ord(__import__('sys').stdin.read(1));return i,c,o,t
_6,_7=lambda:i,c,o,t+not bool(a[i]),lambda:i,c,o,t-bool(a[i])
_8,_9=lambda:i,c+1%32,o,t,lambda:i,c-1%32,o,t
i,c,o,t=[_0,_1,_2,_3,_4,_5,_6,_7,_8,_9][int(s[p])]()if not t else i,c,o,t -(t >+ 0 and int(s[p])==7)- -(t <+ 0 and int(s[p])==6)
p+=1-2 *+ (t <- 0) # i run out of fancy augmented operators :/ gimme more!
if p <- 0 or p>len(s):raise SyntaxError('mismatched 6 or 7')
return o
from collections import defaultdict as d
def generate(k:int,sec=99999):
a = []; from threading import Thread
f = lambda n:a.append(int('9'*n)**sec)
for i in str(k):Thread(target=f,args=[int(i)]).start()
while len(a)<len(k.__str__()):...
return sum(a)
def decrypt(SEED:int, KEY:list[int],sec=99999):
mess = str(generate(SEED,sec))
extract = lambda*a:[mess[i%len(mess)]for i in a]
return int(str().join(extract(*KEY)))
def decode(n):
l,a,o=len(s:=str(n)),d(int),str();i=p=a[int()];c=8;t=0
while len(s)>=p:
def _0():a[i]+=1;a[i] %=1<<+ c;return i,c,o,t
def _1():a[i]-=1;a[i] %=1<<+ c;return i,c,o,t # i made "coerce encoding" operater XDDD
_2,_3=lambda: +i+ 1,c,o,t,lambda: +i- 1,c,o,t
_4=lambda:i,c,print(end=chr(a[i])or o+chr(a[i]),t
def _5():a[i]=ord(__import__('sys').stdin.read(1));return i,c,o,t
_6,_7=lambda:i,c,o,t+not bool(a[i]),lambda:i,c,o,t-bool(a[i])
_8,_9=lambda:i,c+1%32,o,t,lambda:i,c-1%32,o,t
i,c,o,t=[_0,_1,_2,_3,_4,_5,_6,_7,_8,_9][int(s[p])]()if not t else i,c,o,t -(t >+ int()and int(s[p])==7)- -(t <+ int()and int(s[p])==6)
p+=1-2 *+ (t <- int()) # i run out of fancy augmented operators :/ gimme more!
if p <- int() or p>len(s):raise SyntaxError('mismatched 6 or 7')
return o
def main():
o = decode(decrypt(334467, [8153,6,-3,273576346,9929, -55, 4, 7, 888,25,3856,936784,-65, -67, -5,2244,24,-24]))
return o
BEHOLD YE MIGHTY AND DESPAIR, FOR EVEN WHEN YOU HAVE THE KEY IT STILL TAKES AGES TO DECRYPT
y'know what'll be cool?
>>> a + 1 = 4
>>> print(a)
3
>>>
>>> 2(a + 1) = 8
>>> print(a)
3
>>> 25 - b**2 = a**2
>>> print(b)
4
ALGEBRUH ASSIGNMENT
i should make a pep8 for algebruh assignment
That is some of the most horrific looking Python I've ever seen
Where do you get these ideas?
I know, but it's so mesmerizing and enchanting at the same time. I freaking love it. LOL 
Yeah, I'm still trying to make some sense of it lol
Still easier to read then Regex tho right? LOL
That is true
Yes, this is something that I would have to take half a day to just sit down with and have a little whiteboard to really get a good understanding. Definitely worthy of the eso channel for sure! ๐ฏ
Its kind of like that M.C Escher painting of the stairs
That is a perfect analogy. It's like a cerebral journey through, on, around, and in a Mรถbius strip.
!e
print(False == False in [False])
@strange basin :white_check_mark: Your eval job has completed with return code 0.
True
damn, this channel is only for python's god
That's comparison operator chaining. It lets you do 4 < x <=28, which means 4 < x and x <= 28.
It happens to also work with all the comparison operators, even if it's rather weird to read.
Exactly, python parses it aspy (False == False) and (False in [False])
It is. 1 in [1, 2, 3] is True.
binary operators that "should" return booleans according to the object model
!e print(True | False)
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
True
!e print(True | 0)
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
1
hmm
bools implement bitwise ops
!e
class p(int):
def __ror__(self, other):
print('test')
return super().__ror__(other)
print(True|p(1))
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
1
checks for int eh
yephttps://github.com/python/cpython/blob/2a031723eefcf6f1d678bbb4f6018610d43623c4/Objects/boolobject.c#L93
Objects/boolobject.c line 93
bool_or(PyObject *a, PyObject *b)```
or rather checks for non-bool and goes to number if it is
Objects/boolobject.c lines 92 to 98
static PyObject *
bool_or(PyObject *a, PyObject *b)
{
if (!PyBool_Check(a) || !PyBool_Check(b))
return PyLong_Type.tp_as_number->nb_or(a, b);
return PyBool_FromLong((a == Py_True) | (b == Py_True));
}```
@simple crystal I didn't know the bot did that
#changelog message ๐
nice me neither
It's new according to the server changelog.
Alright sorry everyone, I made a mistake, tuple packing takes precedence over lambda expressions
Ouch wrong reply
3 or 4 posts above
observe and weep
there's a lot of metaclass & stack frame screwing around
froze the program
๐ can't even solve such a simple equation smh
not yet
;-;
that's probably the most abstracted simultaneous equation solver in existence XD
wait how does _(Solver) do metaclass?
this looks straight up hacky
it is
I'd almost say you made your own syntax sugar
what if there are multiple solutions, what does it do?
pick whatever z3 picks
so just pick the first set of coordinates that work?
