#esoteric-python
1 messages ยท Page 2 of 1
Source code: Lib/abc.py
This module provides the infrastructure for defining abstract base classes (ABCs) in Python, as outlined in PEP 3119; see the PEP for why this was added to Python. (See also PEP 3141 and the numbers module regarding a type hierarchy for numbers based on ABCs.)
The collections module has some concrete classes that derive from ABCs; these can, of course, be further derived. In addition, the collections.abc submodule has some ABCs that can be used to test whether a class or instance provides a particular interface, for example, if it is hashable or if it is a mapping.
This module provides the metaclass ABCMeta for defining ABCs and a helper class ABC to alternatively define ABCs through inheritance:
!e
from abc import Sequence, ABC
class Empty(ABC):
def __subclasshook__(cls, C):
return (isinstance(C, Sequence) and len(C) == 0)
print(isinstance([], Empty))
print(isinstance((), Empty))
print(isinstance("", Empty))
print(isinstance([1, 2, 3], Empty))
@royal whale :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ImportError: cannot import name 'Sequence' from 'abc' (/usr/local/lib/python3.11/abc.py)
Oh
it's from collections.abc
!e
from abc import ABC
from collections.abc import Sequence
class Empty(ABC):
def __subclasshook__(cls, C):
return (isinstance(C, Sequence) and len(C) == 0)
print(isinstance([], Empty()))
print(isinstance((), Empty()))
print(isinstance("", Empty()))
print(isinstance([1, 2, 3], Empty()))
@royal whale :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 8, in <module>
003 | TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union
dont call Empty
Empty().__class__
!e
from abc import ABC
from fishhook import hook
@hook(type)
def __invert__(self):
return type(f"Not{self.__name__}", (ABC, ), {"__subclasshook__": lambda s: not issubclass(s, self)})
print(list)
print(~list)
print(isinstance(1, list))
print(isinstance(1, ~list))
print(isinstance([1,2,3], list))
print(isinstance([1,2,3], ~list))
@languid hare :white_check_mark: Your 3.10 eval job has completed with return code 0.
001 | <class 'list'>
002 | <class 'abc.Notlist'>
003 | False
004 | True
005 | True
006 | False
@quartz wave request for your CPython fork (I think that was you):
from fishhook, abc import hook, ABC

Wow
i feel like this esoteric stuff has purposes that im gonna need in the near future
which would suck
is there a way to make annotations instantiate a class?
such that:
class cl:...
var: cl = 5
``` will make var equal to `cl(5)`?
I remember some similar shenanigans with calling the annotation with the val, which is why I ask
#hook __annotations__ so that __setitem__ = this
def __annotations___setitem__(name, cls):
self[name] = cls(globals(name))
Idk how you can hook __annotations__ but it should be possible
Remember flogbals? The same idea here
I don't know ctypes wizardry though, so I can't do that part
I think it would be a class
well ig you could hook dict.__setitem__ but that would be all dicts, not just annotations
which would be not good
yeah that's what I was thinking
hmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm...
the problem is getting the value to init the class with
cause I can assign through annotations relatively easily, but I can't init the class with the correct value as its not passed to _setitem_
!e
from ctypes import py_object as p
class MyDict(dict):
def __setitem__(self, k, v):
print("do thing with", k, v)
p.from_address(id(__annotations__) + 8).value = MyDict
x: int = 23
@restive void :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
do thing with x <class 'int'>
Basically: change __class__ of __annotations__, except you're not allowed to do that for dicts.
!e
from ctypes import py_object as p
class Annototatotions(dict):
def __setitem__(self, k, v):
globals()[k] = v(globals()[k])
p.from_address(id(__annotations__) + 8).value = Annototatotions
x: int = 23
print(type(x))
wait
!e
from ctypes import py_object as p
class Annototatotions(dict):
def __setitem__(self, k, v):
globals()[k] = v(globals()[k])
p.from_address(id(__annotations__) + 8).value = Annototatotions
x: str = 23
print(type(x))
@royal whale :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
<class 'str'>
hahahaha yes
There you go @versed eagle
!e
from ctypes import py_object as p
class Annototatotions(dict):
def __setitem__(self, k, v):
globals()[k] = v(globals()[k])
p.from_address(id(__annotations__) + 8).value = Annototatotions
class Foo:
def __init__(self, value):
print("whoopty doo")
self.value = value
def thing(self):
return self.value + 4
x: Foo = 23
print(type(x))
print(x.thing())
@royal whale :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).
001 | whoopty doo
002 | <class '__main__.Foo'>
003 | 27
Anyone mind if I copyright this and sell it
ty <3
Happy to help
It was @restive void that did half of it ๐
!e Can't you just do
@type.__call__
class __annotations__:
def __setitem__(self, k, v):
globals()[k]=v(globals()[k])
class C:
def __init__(self, x):
print(x)
c: C = 42
print(type(c))
@earnest wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 42
002 | <class '__main__.C'>
No need to use ctypes, you can just assign any object to __annotations__
smart
convenient, since it's not cpython-specific anymore!
why not just __annotations__ = MyClass() ?
there is no special opcodes for updating __annotations__, so it will work with any object
>>> dis('x: a')
1 0 SETUP_ANNOTATIONS
2 LOAD_NAME 0 (a)
4 LOAD_NAME 1 (__annotations__)
6 LOAD_CONST 0 ('x')
8 STORE_SUBSCR
10 LOAD_CONST 1 (None)
12 RETURN_VALUE
!e
print(__annotations__)
del __annotations__
try:
print(__annotations__)
except:
print('no __annotations__')
else:
1/0
x: 1
print(__annotations__)
in repl```py
print(annotations)
{}
del annotations
try:
... print(annotations)
... except:
... print('no annotations')
... else:
... 1/0
...
no annotations
x: 1
print(annotations)
{'x': 1}
@fleet bridge :x: Your 3.10 eval job has completed with return code 1.
001 | {}
002 | no __annotations__
003 | Traceback (most recent call last):
004 | File "<string>", line 10, in <module>
005 | NameError: name '__annotations__' is not defined
whats the dis() doing?
someone explain fishhook
ah i see, its a disassembler
!d dis.dis
didn't know that worked
fishhook basically lets you replace methods of a class with a function of your choosing
for example, you can hook int._add_ so that it always returns 1 more than it would otherwise
can't you just do py class int(int): def __add__(self, other): return self.__subtract__(other)
yeah i've been thinking of adding that
!d abc.ABC
class abc.ABC```
A helper class that has [`ABCMeta`](https://docs.python.org/3/library/abc.html#abc.ABCMeta "abc.ABCMeta") as its metaclass. With this class, an abstract base class can be created by simply deriving from [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC "abc.ABC") avoiding sometimes confusing metaclass usage, for example:
```py
from abc import ABC
class MyABC(ABC):
pass
``` Note that the type of [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC "abc.ABC") is still [`ABCMeta`](https://docs.python.org/3/library/abc.html#abc.ABCMeta "abc.ABCMeta"), therefore inheriting from [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC "abc.ABC") requires the usual precautions regarding metaclass usage, as multiple inheritance may lead to metaclass conflicts. One may also define an abstract base class by passing the metaclass keyword and using [`ABCMeta`](https://docs.python.org/3/library/abc.html#abc.ABCMeta "abc.ABCMeta") directly, for example...
existing int objects won't magically become a new type
fishhook is in C, right?
pure python using ctypes
anyone know how you can check if a string is interned through python using ctypes?
it's very hard to do
that's what i can tell you
there might not be a totally portable way to do it, but there does seem to be a macro for it: https://github.com/python/cpython/issues/90165
does this
/* Use only if you know it's a string */
#define PyUnicode_CHECK_INTERNED(op) \
(((PyASCIIObject *)(op))->state.interned)
so i guess recreate the casting via ctypes
you can mimic it using ctypes.Structure
state is a struct of unsigned int with a size of 32 bits and a place size of ONLY 8 bits
but try if you want to
the heck is this unsigned int interned:1;
i'm gonna test hold on
bit field
why :1?
how would this affect it? you could check that exact bit no?
the tuples in _fields_ have to be ('name', type, bit_field_size)
bit_field_size is optional
can you clarify what the issue with place size/struct size means? not sure i understand
when you view it in the source code, it seems like a struct of 32 bits with 25-bit padding
when you actually look at it from its outside container (PyASCIIObject), its size is only 8 bits
might change with pointer size probably
how does that prevent accessing that one particular bit?
it messes up stuff when i tried to get them
import ctypes
import sys
class PyObject_HEAD(ctypes.Structure):
_fields_ = [
("ob_refcnt", ctypes.c_ssize_t),
("ob_type", ctypes.c_void_p),
]
class PyASCIIObject(ctypes.Structure):
_fields_ = [
('ob_base', PyObject_HEAD),
('length', ctypes.c_ssize_t),
('hash', ctypes.c_ssize_t),
('interned', ctypes.c_ubyte, 1),
]
string = 'this is a test string'
ascii_object = PyASCIIObject.from_address(id(string))
print(ascii_object.interned)
sys.intern(string)
print(ascii_object.interned)
this seems to work, at least in 3.9 didnt test anywhere else
@astral rover
Thanks, I'll give it a go
Just wanted to share my golfed solution to the daily programming puzzle I received today
(Monty Hall problem, given a contestant's starting door and strategy for switching or not, what is their success rate over 1000 attempts)
๐คข
from random import shuffle as S, choice as C
T,F,E=lambda _:1,lambda _:0,lambda:C((0,1,2))
def p():
def r(c,a=0):
d=[0,0,1]
S(d)
while a==c[0]or d[a]:a=E()
d.pop(a)
i=c[0]==2
if c[1](a):
d.pop(-1)if i else d.pop(c[0])
return d[0]
return d[-1]if i else d[c[0]]
def m(n,c=[0,T],w=0,i=1000):
l=[[0,F],[0,T]]
for _ in range(i):
if r(c):w+=1
elif n=='Gina':
l=l[::-1]
c=l[0]
print(f"{n:<6} {float(w/i):.1%}")
for _ in[('Alice',[0,F]),('Bob',[0,T]),('Carol',[E(),lambda _:C((0, 1))]),('Dave',[E(),F]),('Erin',[E(),T]),('Frank',[0,lambda _:1if _!=1else 0]),('Gina',)]:m(*_)
p()
Output:
Alice 34.0%
Bob 68.3%
Carol 53.3%
Dave 35.2%
Erin 64.8%
Frank 52.0%
Gina 55.5%
and the more readable equivalent prior to golfing:
from random import shuffle, choice
def p389(contestant: list) -> float:
"""
The Monty Hall Problem [Easy]
:param n:
:return:
"""
doors = [True, False, False]
shuffle(doors)
monty = 0
while monty == contestant[0] or doors[monty]:
monty = choice((0, 1, 2))
doors.pop(monty)
if contestant[1](monty):
# print("switching doors!")
(doors.pop(-1) if contestant[0] == 2 else doors.pop(contestant[0]))
return doors[0]
# print("staying with my door!")
return doors[-1] if contestant[0] == 2 else doors[contestant[0]]
def test():
alice = [0, lambda _: False]
bob = [0, lambda _: True]
carol = [choice((0, 1, 2)), lambda _: choice((True, False))]
dave = [choice((0, 1, 2)), lambda _: False]
erin = [choice((0, 1, 2)), lambda _: True]
frank = [0, lambda x: True if x != 1 else False]
gina = None
def monty(contestant=None) -> str:
gina = False
if contestant is None:
gina = True
contestant = [0, lambda _: True]
wins = 0
gina_last = [alice, bob]
for _ in range(1000):
if gina:
contestant = gina_last[0]
if p389(contestant):
wins += 1
else:
gina_last = gina_last[::-1]
return f"{float(wins / 1000):.2%}"
print(f"Alice: {monty(alice)}")
print(f"Bob: {monty(bob)}")
print(f"Carol: {monty(carol)}")
print(f"Dave: {monty(dave)}")
print(f"Erin: {monty(erin)}")
print(f"Frank: {monty(frank)}")
print(f"Gina: {monty(gina)}")
bro what the hell am i looking at
๐
PEP negative 20
serious answer: I like to play code golf to smash and smoosh my (non-production) code as small as I can
could you post the exact problem description, might try my hands on golfing a solution
182 votes and 67 comments so far on Reddit
good god man
sounds cool
good luck with it
!e
from dis import dis
dis('a.b: c')
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0 0 RESUME 0
002 |
003 | 1 2 SETUP_ANNOTATIONS
004 | 4 LOAD_NAME 0 (a)
005 | 6 POP_TOP
006 | 8 LOAD_NAME 1 (c)
007 | 10 POP_TOP
008 | 12 LOAD_CONST 0 (None)
009 | 14 RETURN_VALUE
@restive void it keeps segfaulting
Ideally, that would write to a.__annotations__['b']
i think i've been working on it for 3 hours
Perhaps objects could have parameter annotations just like global variables have annotations
@rugged sparrow can you help with this
and also the side-by-side (interned?) strings 2 weeks earlier
i feel like the problem is the frozen modules
but i've already regenerated them
is your fork somewhere public?
I could also try it on the lastest main of cpython, I guess
well no it's not
wait wtf it's the caches
the module caches were causing problems ๐ค
wat have I done?
s=()
!e print(len(())) # wrong
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
0
overridden __iter__ incompatibly with __len__?
I didn't even use __len__
but the __iter__ is a mess, and memory in position offset 16 is modified
oh, i thought len([s]) was 1
[*s] is not [s]
no, i thought [*s] = 0 and [s] = 1, thats why said ()
there's no square brackets on the second input
I have no clue how carriage return got involved either.
Expected behaviour is
>>> s
['fluffy','floofy']
>>> [*s]
['fluffy','floofy']
>>> len(s)
2
>>> len([*s])
2
>>> |
for the input I gave it, anyway
@restive void this works now ```py
from dis, sys import *
setrecursionlimit
<built-in function setrecursionlimit>
dis
<function dis at 0x00000230DFF23330>
only with star-imports, or also zipped?
I've been working on it, too, but Python/compile.c is.. a bit tough
i'll have to make a few more changes for the normal ones to work in random order
yeah i also got confused when i first looked at it
at least they match now. Now I just need the contents to be the actual contents
how unstable would from * import * be?
yes
I mean it would have to traverse the python path
name clashes will be resolved with loss of information
can that even be done
well, help("modules") seems to find everything (minus cwd paths)
I'm a little tired so I'm not even try to gonna figure out why this doesn't work. ```py
from ctypes import*
class StringArray(str): # but actually a list
def new(cls, a, *_):
s = str.new(cls, '\0'.join(a)+'\0')
return s
def init(self, a):
super().init()
l=c_longlong.from_address(id(self)+16).value=len(a:=(a or((),))[0])
self[:]=a
def iter(self):
i,k=0,len(self)
def ():
nonlocal k,i
while k:
s = b''
for c in iter(lambda:c_char.from_address(id(self)+48+i).value,b'\0'):
i+=1;s+=c
yield s.decode(); k-=1
return iter(())
def repr(self): return str([*self])
str=repr
def getitem(self,key): return[*self][key]
def setitem(self,key,value):
(a:=[self])[key]=value
s = '\0'.join(a).encode()+b'\0'
l = len(a)
(c_charlen(s)).from_address(id(self)+48)[:]=s
c_longlong.from_address(id(self)+16).value=l
a = StringArray(["this", "that", "foo", "bar"])
print(a, len(a), len([*a]))
print(*a, a[:2], a[2])
a[0],*a[1:3] = "foo","this","that"
print(a)
It almost does, but then it doesn't
made it work now ```py
from dis, sys import setrecursionlimit, dis
setrecursionlimit
<built-in function setrecursionlimit>
dis
<function dis at 0x000002B53AE83330>
hey that's what i said with the code i wrote trying to implement zipped from-imports
nice. I'd be interested to see the diff, to see what I still had to do (minus autogenerated files)
mine probably varies a lot from the current main branch files
Right, but just the diff of this one change would help me. You don't have to, of course.
i'll send some .diff files generated by winmerge
is there a semi reliable way to check if something is being matched against, bytecode doesnt seem all that useful
In [5]: def foo():
...: import sys, dis
...: dis.dis(sys._getframe(1).f_code)
...:
In [6]: match foo():
...: case _:
...: print()
...:
1 0 LOAD_NAME 0 (foo)
2 CALL_FUNCTION 0
2 4 POP_TOP
3 6 LOAD_NAME 1 (print)
8 CALL_FUNCTION 0
10 POP_TOP
12 LOAD_CONST 0 (None)
14 RETURN_VALUE```
I was kinda hoping there'd be a special op code for thing 
!d sys.setrecursionlimit
sys.setrecursionlimit(limit)```
Set the maximum depth of the Python interpreter stack to *limit*. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.
The highest possible limit is platform-dependent. A user may need to set the limit higher when they have a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.
If the new limit is too low at the current recursion depth, a [`RecursionError`](https://docs.python.org/3/library/exceptions.html#RecursionError "RecursionError") exception is raised.
Changed in version 3.5.1: A [`RecursionError`](https://docs.python.org/3/library/exceptions.html#RecursionError "RecursionError") exception is now raised if the new limit is too low at the current recursion depth.
from flask_mysqldb import MySQL
ModuleNotFoundError: No module named 'flask_mysqldb'
how clear this error
can't install flask mysql db
@sick hound :warning: Your 3.10 eval job has completed with return code 139 (SIGSEGV).
[No output]
The interned strings thing is definitely some quirk of memory allocation so it's not something you can rely on. Changing the python interpreter to allow that kind of import statement you would need to import all of the modules it's asking for and then search through their namespaces to find the names that you're looking for and you would need to handle different name collisions
hey how do I get code coloring again... ``py ?
```py
[your code here]
```
Got it, thanks! I had been trying `` before.
`...` results in this kind of text, which is also useful
ah, right
No problem, happy to help!
so hwy didn't this execute:
!e
class RegexEqual(str):
"Override str.__eq__ to match a regex pattern."
def __eq__(self, pattern):
return bool(re.search(pattern,self))
match RegexEqual('the tale of two cities'):
case 's...y': print('A sad story')
case 't..e': print('A mixed tale')
case 's..a': print('A long read')
oh
eh? what was the invalid syntax <- @royal whale
@vital dirge :x: Your 3.10 eval job has completed with return code 1.
001 | File "<string>", line 3
002 | def__eq__(self, pattern):
003 | ^
004 | SyntaxError: invalid syntax
def __eq__ instead of def__eq__
!e
class RegexEqual(str):
"Override str.__eq__ to match a regex pattern."
def __eq__(self, pattern):
return bool(re.search(pattern,self))
match RegexEqual('the tale of two cities'):
case 's...y': print('A sad story')
case 't..e': print('A mixed tale')
case 's..a': print('A long read')
@vital dirge :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 7, in <module>
003 | File "<string>", line 4, in __eq__
004 | NameError: name 're' is not defined
!e
import re
class RegexEqual(str):
"Override str.__eq__ to match a regex pattern."
def __eq__(self, pattern):
return bool(re.search(pattern,self))
match RegexEqual('the tale of two cities'):
case 's...y': print('A sad story')
case 't..e': print('A mixed tale')
case 's..a': print('A long read')
@vital dirge :white_check_mark: Your 3.11 eval job has completed with return code 0.
A mixed tale
ok, yes!
aaanyway I think this is a cool way to mix regexes into structural pattern matching
courtesy of Raymond Hettinger's structural pattern matching toolkit: https://www.dropbox.com/s/w1bs8ckekki9ype/PyITPatternMatchingTalk.pdf?dl=0
anyone here tried golfing snake before?
is it possible to get access to real hardware where snekbox is running and execute arbitrary code on it?
if no, why?
well i guess if you can escape sandboxing
then it is possible
is it opensource btw?
i decided on first namespace with the name will have its value imported
What would be the shortest way to check if x == 0 or 9
if x in(0,9):... # your code here
wait, you cant do string[index]='char' to replace character in string at index?
strings are immutable. What are you working on?
trying to golf snake
map is a string
and i wanted to replace chars at given index with '@'
@finite blaze use a bytearray instead. They are mutable
t='#'*10+'\n';m=t+f"#{' '*8}#\n"*8+t;
so thats how i generate my map (okay i've removed not needed code)
you can do {'':8} instead of {' '*8}
one character difference
did you try it? f"{'':8}" is the same as f"{' '*8}"
:8 means, make this take 8 spaces
thanks
i think that a bytearray would make it longer
or actually, let me try one thing
import time,os;m=x=y=[35]*10+[10]+([35]+[32]*8+[35,10])*8+[35]*10;s=[(5,5)]
while 1:
os.system('cls');t=m
for p in s:t[p[0]*11+p[1]]=64;print(bytes(t).decode('utf-8'));time.sleep(1)
okay, quick test
it works but i need to make it shorter
do you plan on having your code run on *nix systems, or just windows? (just curious)
For now only windows
I guess i would have to change 'cls' right?
yeah
you'd have to do "cls"if platform.system()=="Windows"else"clear"
and import platform
theres also a way using os but its a lot longer lol
makes sense
does it use the terminal width/height and make the map the size of the terminal, or is it fixed width/height?
Fixed
cool
Need to make the first line shorter
in this, since s is fixed as (5,5), you can do this
import time,os;m=x=y=[35]*10+[10]+([35]+[32]*8+[35,10])*8+[35]*10
while 1:
os.system('cls');t=m
t[60]=64;print(bytes(t).decode('utf-8'));time.sleep(1)
oh, its a list of coordinate tuples?
Yup
instead of time.sleep(), you can use os.system("SLEEP 1")
so you dont have to import time
@sick hound :warning: Your 3.11 eval job has completed with return code 0.
[No output]
Or same for OS and use the suggestion above mine
!e
print(len(
"""from time import*;import os
sleep(1);os.system("cls")"""))
print(len(
"""from os import system as _;_("cls");_("SLEEP 1")"""))
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 53
002 | 48
a combination of both is better since you're using os twice
one for cls and one for sleep
so you import system from os as _, then call _ with whatever args you want
!e
print(len("""import time;import os;time.sleep(1);os.system("cls")"""))
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
52
thats whats currently being done
that one is 1 char longer than whats currently being done, if you account for os.system("cls")
Considering my next comment, I meant doing the same for os
!e
print(len("""from os import*;system("cls");system("sleep 1")"""))
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
47
This is one character shorter
!e ```py
print(len("(:=import('os'))('cls');('sleep 1)"))
@old socket :white_check_mark: Your 3.11 eval job has completed with return code 0.
40
hey everyone. super random question- are the metaprogramming facilities faster in pypy? general question, all answers welcome
i don't know why they would be faster. if anything, they sound like the kind of thing that could be slower. What's going on?
just researching python metaprogramming tools. i like the idea of them but the perfromance penalty is making it seem very risky.
just curious why they would be slower in pypy? if thats not an enourmous question
if it is dont worry about it
maybe we should clarify: what do you mean by metaprogramming?
it could be slower in pypy only because it's a kind of off-the-beaten-path thing that doesn't need to be made faster.
Things like the inspect module. Meta classes, agressive abuse of properties. And that sounds reasonable that it wouldnt be high priority for the team. Guess ill put some time into testing it. Thanks @burnt pasture
!e
print(len("""import os;s=os.system;s("cls");s("sleep 1")"""))
@earnest wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
43
-4
that's 47 including .system
Ohhh lmaoo I forgot the whole system part
Brain fart
!e ```py
print(len("""import os;os.system("cls&sleep 1")"""))
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
34
-9
import os;os.system('')
__import__('os').system('')
doesn't clear the console or sleep 1 second
i know, im just comparing __import__ expr and import statement
statement is 4 char shorter
can I somehow make an n long array of the same number?
is there any shorter way that [number]*n
I want to make this thingy shorter [35]*10+[10]+([35]+[32]*8+[35,10])*8+[35]*10
m=x=y=[35]*10+[10]+([35]+[32]*8+[35,10])*8+[35]*10;s=[(5,5)]
m=x=y=[[35]*10,10,([35],[32]*8,35,10)*8,[35]*10];s=[(5,5)]
almost
!e - imagine
print('hi'): str
@lyric fern :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print('hi'): str
003 | ^^^^^^^^^^^
004 | SyntaxError: illegal target for annotation
do you mean, ```py
m=x=y=[35]*10+[10]+([35]+[32]8+[35,10])8+[35]10;s=[(5,5)]
_=10[35];m=x=y=_+[10]+8[35,[32]*8,35,10]+_;s=[(5,5)]
yep!
also depending on the terminal, you don't need os to cls
import os;os.system('cls')
print('\x1bc')
import time;print('\x1bc');time.sleep(1)
i need to find a good way to read input
if you're on windows, msvcrt
should come with
i cant remember if it does
import time;_=10*[35];m=x=y=_+[10]+8*[35,*[32]*8,35,10]+_;p=print
while 1:p('\x1bc');m[60]=64;p(''.join(map(chr,m)));time.sleep(1)
the laziest sorting algorithm: sleepsort ```py
from threading import Thread
import time
a = [1, 7, 8, 8, 4, 3, 8, 4, 5]
def f(i,n):
time.sleep(n)
print(end=f'{n}, ',flush=1)
Thread.join([*map(lambda t:Thread.start(t)or t,[Thread(target=f,args=n)for n in enumerate(a)])][a.index(max(a))]);time.sleep(.1);print()
i cant do m[60]
s is a list of coordinate tuples
and (5,5) i just snake's head
ah you want snek
yepp
The throttle in my brain is stuck on minimum right now otherwise I'd write snake in the terminal using msvcrt and with an adaptive framerate
using a memory efficient cell object, a matrix infused engine and an ascii/ANSI interface manager.
like I do with literally every terminal game i write
It's generally a good idea to start with production style code and golf down from there
true
although my idea of production code would be traumatising for some here's my progress so far
i have two drop down boxes lets say A and B and both drop down boxes have options based on SQL database, how do i make the options in drop down box B such that its options are relavant to what is selected in box A.
here box A is service engineer and box B is serial number
@floral delta is this an #esoteric-python subject, or do you need help with something? #โ๏ฝhow-to-get-help
because this channel is absolute last resort
where you go if you need to make 2 + 2 == 5
oh my bad i didnt know how this words
works
#esoteric-python so esoteric even its meaning is esoteric ๐
Very few people understand the meaning of "esoteric"
hidden knowledge?
yeah
that's right, small circle of folks who understand it
you're correcter than me
not exactly hidden knowledge. Just difficult or uncommon to grasp
like for when you want a decorator that can turn a class definition into a function definition or vice versa
or when you have a str and you want to turn it into an int, but you're in the wrong scope, so you use ctypes to overwrite the memory
LOL the ninja-fu
remote variable mutation
has there been a security audit conducted on the standard library yet?
comprehensive, I mean, including stuff like fuzzing
and taint tracing
#cybersecurity at a glance seems like the best place to discuss that
hmm how about this: Raymond Hettinger put out this amazing and useful little library to make python 3.10's structurla pattern matching even better: https://www.dropbox.com/s/w1bs8ckekki9ype/PyITPatternMatchingTalk.pdf?dl=0
of particular note: merging structural pattern matching with regexes
by overriding str.eq
i guess
str.__eq__
@vital dirge extreme example of esoteric
I have a mild irrational phobia of match-case, or its aliases in other languages, I prefer to use inline dictionary-getitem-call
ah, sure. And what, it prints "hello wold" or something, lol. This is my favorite channel to browse on this Discord server ๐
no it prints 0, 1, 2, etc. all the way to infinity (until the program stops)
ah ok ๐
here's how we switched in the good ol' days of python 3.9
Oh wow, LOL, dictionaries weren't good enough were they ๐
This is an example of remote variable mutation, and also an simulation of a Turing Machine.
dictionaries kinda do it backwards
mentioning 3.9 in 2022 ๐
!e useless knowledge for the day: ```py
[[[[a]]]] = [[[[69]]]]
print(a)
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
69
spider variables: they have 8 legs
also they have 8 eyes
i[0 : 7]
Spider bite:
Flail_about
Cry_ouch
Stick_to(walls)
Shoot(webs)
Fight(crime)
untested unit: command line snake game.
class Engine:
class Cell:
def __init__(self, x, y, init_value='blank'):
self.value=init_value
self.n, *self.xy = -1, x, y
self.head=0
# Engine() meta-methods
def _fw(self):
if self.n>0:self.n-=1
if not self.n:self.value,self.n='blank',-1
return self
def __iter__(self):
return iter(self.xy)
def snake(self, n):
self.value,self.n='snek',n
# Interface() meta-methods
BLINK=[0]
@classmethod
def blink(cls):cls.BLINK[0]^=1
def __str__(self):return{'blank':'\x1b[100m \x1b[m','snek':f'\x1b[{42+60*self.head}m \x1b[m','food':f'\x1b[{41+60*__class__.BLINK[0]}m \x1b[m'}[self.value]
class exceptions:
class GameOver(Exception):
def __init__(self, obj):
self.engine = obj
super().__init__(f"Game Over")
class GameQuit(GameOver):0
class FatalError(RuntimeError):
def __init__(self, e):
super().__init__(f"{e.__class__.__name__}: {e}")
def __init__(self, x, y):
self.direction, *self.head, self.max, self.size = 2, x//3,x//2, (x,y), 1
self.matrix = [[*map(self.Cell,range(x),[row]*x)]for row in range(y)]
self[self.head].snake(1)
def step(self):
(X, Y), (x, y), s, d = self.max, self.head, self.size, self.direction
target = [x+(d==2)-(d==3),y+(d==0)-(d==1)]
if target[0]not in range(X) or target[1]not in range(Y)or self[target].value='snek':raise GameOver(self)
self.size+=(food:=self[target].value=='food')
self[target].snake(self.size)
if not food:*map(self.Cell._fw,self),
else:
m = [*filter(lambda x:x.value=='blank',self)]
m[__import__('random').randint(len(m))].value = 'food'
return self
def turn(self, d):
if self.direction//2!=d//2:self.direction=d
return self
def __getitem__(self, key):
x, y = key
return self.matrix[y][x]
def __iter__(self):
X, Y = self.max
return iter(self[x,y]for x in range(X)for y in range(Y))
def __str__(self):
X, Y = self.max
return'[\n '+',\n '.join([', '.join(map(lambda x:str(self[x,y]),range(X)))for y in range(Y)])+'\n]'
__repr__=__str__
!e Ah, the smell of a freshly-baked RecursionError
a = []
a.append(a)
print(a)
c = a
while isinstance(c, list):
print(c)
c = c[0]
@royal whale :x: Your 3.11 eval job has completed with return code 143 (SIGTERM).
001 | [[...]]
002 | [[...]]
003 | [[...]]
004 | [[...]]
005 | [[...]]
006 | [[...]]
007 | [[...]]
008 | [[...]]
009 | [[...]]
010 | [[...]]
011 | [[...]]
... (truncated - too many lines)
Full output: too long to upload
it's infinite.
yea, I didn't realize that
and you don't need c as an intermediate variable
lists don't copy on variable assignment.
neither do strings actually
!e ```py
from ctypes import*
a = "Hello"
n = id(a)
b = a
(c_char*5).from_address(n+48)[:]=*map(ord,"G'day"),
print(b)
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
G'day
you see b not only equals a, it is a
!e remote variable mutation! ```py
def f(a = "Hello"):
return a
def g(s):
from ctypes import c_char
(c_char*5).from_address(id(s)+48)[:] = *map(ord,'World'),
s = f()
print(s)
g(f())
print(s)
@floral meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Hello
002 | World
but in his code has stuff in between the cls and the sleep, so they need to be seperate function calls
!e
class console(object):
def log(a: str):
return a
console.log('e');
@lyric fern :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!e
class console(object):
def log(a: str):
return a
print(console.log('e'));
@lyric fern :white_check_mark: Your 3.11 eval job has completed with return code 0.
e
@vital dirge :warning: Your 3.11 eval job has completed with return code 0.
[No output]
@vital dirge :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'isclose' is not defined
@vital dirge :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!e
import math
math.isclose(3, 3.000000000000000000000000003)
@vital dirge :warning: Your 3.11 eval job has completed with return code 0.
[No output]
would you mind running these in #bot-commands?
ok
Is there a way of shortening
data = "whatever data"
for some in bunch:
data = transform_data(data, some)
```?
!d map
map(function, iterable, ...)```
Return an iterator that applies *function* to every item of *iterable*, yielding the results. If additional *iterable* arguments are passed, *function* must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see [`itertools.starmap()`](https://docs.python.org/3/library/itertools.html#itertools.starmap "itertools.starmap").
You can probably use map
data = [*map(lambda s:transform_data(data,s),bunch)] at a guess
is it possible to overload the globals object without using ctypes (or similar modules/extensions)?
by overload I mean such as you can do with __annotations__, e.g.
class __annotations__(dict):
def __setitem__(self, key, val):
...
def shortened_way_of_doing_thing(transform_data, bunch, data):
@__import__("dataclasses").dataclass
class fn:
f:type(lambda:0)
__mul__=lambda s,o: fn(lambda x: s.f(o.f(x)))
__xor__=lambda s,n: fn(lambda _:_)if not n else s*(s^(n-1))
__call__=lambda s,x: s.f(x)
goobus = list(bunch)
doobus = iter(goobus)
return (fn(lambda x: transform_data(x,next(doobus))^len(goobus))(data)
this should be fairly short and to the point
:O
๐คฃ
Maybe, but since you can't access it except through globals, I'm not sure
!e
@type.__call__
class __annotations__(dict):
def __setitem__(self, key, val):
print(f'__annotations__[{key!r}] = {val!r}')
return super().__setitem__(key, val)
x: 1
y: 2
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | __annotations__['x'] = 1
002 | __annotations__['y'] = 2
lol
you effectively re-invented the assignment operator? ๐
I mean you can put the values in the globals dictionary too for that matter
Now each variable can store two times more data!
that's not what i asked though
I know about overloading annotations, I've been doing that
I said overloading the globals dictionary
I want to change __getitem__ and __setitem__ for globals
Why does Python call in's corresponding dunder method __contains__ and not __in__
Can this be done with fishhook?
What's the decorator do
None of the skills I learnt in this channel have been used in production
Why do I keep coming back
Good
Nothing posted in this channel is meant to be used in production
it makes annotations be an instance of annotations
it's the end as
class __annotations__(dict):
...
__annotations__=__annotations__()
Huh
Don't get it but okay
Why does it inherit from dict
Doesn't annotations already have setitem
because annotations is normally a dict
so it has to have all the same attributes that dict has
Kk
otherwise stuff can break
What
Any way of using try/catch and context managers inside a lambda?
Oh because otherwise it's the class
yeah
Super cool
decorators are really cool in general
Should have written
class __annotations__(dict):
...
__annotations__ = type.__call__(__annotations__)
To be precise
But honestly it's the same
Does it work if you use object
Ah, no, type's __call__ makes an instance
And all
Wait, couldn't you then do object.__new__
Or is its cls argument automatically assigned object
!e
@object.__new__
class cl:
def __init__(self):
print("hi")
@versed eagle :warning: Your 3.11 eval job has completed with return code 0.
[No output]
search for one line try catch or something, in this channel, it's been done before
!e
@object.__new__
class cl:
def __init__(self):
print("hi")
print(cl)
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
<__main__.cl object at 0x7f99298374d0>
I guess not?
yep
Wait oh never mind it is an instance
This is honestly like a funky object
A single purposefully made object
In code
I like @type.__call__ because you can then alternate between those and @type annotations to create a funny decorator chain
Because object.__new__ doesn't call the object's __init__ method, I guess
!e
@object.__new__
class cl:
def __init__(self):
print("hi")
self.thing = 4
print(cl)
cl.__init__()
print(cl.thing)
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <__main__.cl object at 0x7f118e1a3610>
002 | hi
003 | 4
yeah
Tbh you can just override the class's __new__ method to not initialize
Unless it happens during type.__call__
Yeah
Because it's called on the container, not the (potentially) contained item.
__in__(self, other) would imply the question "Is self in other?"
Behold
The dumbest piece of code ever written
https://paste.pythondiscord.com/goremuguwo
does using .pythonrc to do weird stuff in Python interpreter count as esoteric?
like
having neofetch inside Python's interpreter
we are getting there
import time,msvcrt;_=10*[35];m=x=y=_+[10]+8*[35,*[32]*8,35,10]+_;s,p,d=[[5,5]],print,100
while 1:
t=m
for l in s:t[l[0]*11+l[1]]=64
p(''.join(map(chr,t)));time.sleep(.5);p('\x1bc')
if msvcrt.kbhit():
d = msvcrt.getch()
while msvcrt.kbhit():
d = msvcrt.getch()
d = ord(d)
if d == 119: s[0][0]-=1
elif d == 115: s[0][0]+=1
elif d == 97: s[0][1]-=1
elif d == 100: s[0][1]+=1
(not golfed)
so for some reason my map isn't clear at the start of each loop cycle
t=m this should clear it but yeah
it grows even tho i didn't eat any apple
but anyway, need to just add apples i am almost there
why Lmao
but when you operate on it afterwards, it does change
yes
!e
a=5
b=a
b+=1
print(a,b)
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
5 6
why not the same with lists
it's the same with lists
!e
a=[5]
b=a
b+=[1]
print(a,b)
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
[5, 1] [5, 1]
a is also changed
x += y isn't the same as x = x + y with lists
it implements __iadd__
ints don't
so the default behaviour is __add__
why not
cause that's useless for ints
any immutable type doesn't implement __i*__ like mutable types do
why isn't the end result the same though
how can i avoid it?
like, why would they design the language specification in such a way that lists are like this
is there a use case?
cuz it seems like m also changes
memory efficiency
the same as t
thing = listvar[:]
then also we don't want number types and strings to change randomly
!e
class X:
inst = None
def __new__(cls):
if cls.inst is None:
cls.inst = super().__new__(cls)
return cls.inst
def __init__(self):
print('__init__ called')
x = X()
y = X()
print(x is y)
@fleet bridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | __init__ called
002 | __init__ called
003 | True
im not calling __init__ directly
it copies the list
it's a slice
so what array1=array2 does?
that copies the list
yes
that creates a new reference to array2 and puts it in array1
but it does not copy the list
I was typing an explanation to go further in more detail but mobile typing is hard :(
I thought references are a c++ thing
in c, they use pointers instead, right?
well that's what they call it
pointers are still references but they're explicit
oh, since you're here, can you answer a question for me?
I asked a while ago and got no answer
.
got no answer a while ago when I asked
ik I could just have everything be a function, exec it's _code_ and pass a class as globals and locals, but exec feels like cheating
i have so far not known a way without using ctypes or such
also sorry for my atrocious grammar in this question, I was tired as hell when I wrote it
from ctypes import py_object
class __globals__(dict):
__slots__ = ()
...
py_object.from_address(id(globals()) + tuple.__itemsize__).value = __globals__
seems fine to me
"i mean such as you can do"
that's fine
ty
i could've wrote "i mean like how it's done with" but i feel like what you said is much better
well I'm gonna go do some stupid stuff with globals and annotations
goodbye
thank you for your help
have a nice day cereal
well now i just have to figure out how to not recurse on _getitem_ for globals
use dict.__getitem__ for any builtin/global you're using
i am
and it recurses
user@host:~/Desktop$ python3 c.py
Traceback (most recent call last):
File "c.py", line 12, in <module>
@type.__call__
File "c.py", line 6, in __getitem__
return dict.__getitem__(key)
File "c.py", line 6, in __getitem__
return dict.__getitem__(key)
File "c.py", line 6, in __getitem__
return dict.__getitem__(key)
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
currently __getitem__ is
def __getitem__(self, key):
return dict.__getitem__(key)
use {}.__class__.__getitem__(self, key)
?
when i was typing this:
py_object.from_address(id(globals()) + 8).value = __globals__
i accidently typed
py_object.from_address(id(globals()) + 8).value = __globals__()
which caused a segfault when i ran it
๐
exec("".join(map(chr, __import__('zlib').decompress(b'x\x9cM\x8e\xc1\x0e\xc2 \x10D\xef|\xc5\xa6\'H\x9a\x06\xdaj\xab\xa7\xfe\x871\x1b,4\xd6Pl\x00\xff_\xa8Z\xd9\xc3df\xden\xb2dX\xddl\x03\x19\x8c\\nJ\x02\x9e\xa1(\xaa\xc7s\xb6t\x91+\x1d\xef\xae\x04d,\xe7X!*md\x08\x0e\x91rFF#\xbd\x8f\x84@\x1c\xa5\'\xc8\xb9\xd7fb\x1f\x94\xc6\xe9\xf0r\x16.]_\x82\xe0"\x8a\xf8\xbb\xb6\x84\xa6N\xa9Ii\xab\xf8WN]\xce\xf8!?\xdc\xfaZ\xec7\xbf\xd5d\x84\x88\xae=^\xf7\x07\xde\xfe\x0b9V'))))```
๐ฆ
i walked 4 miles from my home to my grandparents' home and still don't know who said that
if god was incarnated as a human, with infinite knowledge of all that exists, even god doesn't know who said that
that's an over-exaggeration but ok
Why does he need to be reincarnated to have the knowledge?
Wouldn't the mortal form make it harder to remember everything?
While you discuss that...
I made a programming language
literally the most pythonic programming language you can have
!e
import sys;from random import*;seed(1337);q=sys.stdout;n=lambda *x:None;sys.stdout=type("",(object,),{"write":n,"flush":n})();from this import*;sys.stdout=q;l="".join([d.get(c, c)for c in s]).splitlines()[2:];g=4**5;G=[chr(g+_)for _ in range(len(l))];t=0;u=globals().update;f=lambda p:[u(t=p),"".join(map(lambda x:str(u(t=t.replace(x[0][:-1],x[1]))),zip(l,G))),u(t="".join(filter((lambda Y:Y in G),t))),list(map(lambda _:(ord(_)-g-randrange(len(l)))%len(l),t))][-1];L=[0];P=0;I=0;T=0;B=0;F=0;S=0;O=0;U=0;run=lambda p:[u(U=f(p),T=[0]*5**5,P=0,I=0,O="",B={},S=[],F=[0]),[([B.update({Q:i,i:Q})for Q in[S.pop()for _ in L if c==5]],[S.append(i)for _ in L if c==4])for i,c in enumerate(U)],[[[u(P=P+1) for _ in L if U[I]==0],[u(P=P-1) for _ in L if U[I]==1],[T.__setitem__(P,(T[P]+1)%256)for _ in L if U[I]==2],[T.__setitem__(P,(T[P]-1)%256)for _ in L if U[I]==3],[u(I=B[I])for _ in L if(U[I]==4and T[P]==0 or U[I]==5and T[P]!=0)],[u(O=O+chr(T[P]))for _ in L if U[I]==6],[F.append(u(I=I+1))for _ in L if I+1<len(U)]]for W in F],O][-1]
print(run("""
Explicit is better than implicit.
Although never is often better than *right* now.
Simple is better than complex.
Simple is better than complex.
Although practicality beats purity.
Although that way may not be obvious at first unless you're Dutch.
Although never is often better than *right* now.
In the face of ambiguity, refuse the temptation to guess.
In the face of ambiguity, refuse the temptation to guess.
Although that way may not be obvious at first unless you're Dutch.
In the face of ambiguity, refuse the temptation to guess.
In the face of ambiguity, refuse the temptation to guess.
Sparse is better than dense.
Beautiful is better than ugly.
Although never is often better than *right* now.
Sparse is better than dense.
Complex is better than complicated.
"""))
@twin reef :white_check_mark: Your 3.10 eval job has completed with return code 0.
42
isnt it a brainfuck, where all characters are replaced with strings from zen?
tsss... don't tell anybody
You calculated the meaning of life, the universe and everything in zenfuck!
How to hide a distress call in your source code
fix again ```py
from sys import _getframe
from dis import opmap, _inline_cache_entries
from ctypes import c_char
def builtinexc(exc, depth=1):
frame = _getframe(1 + depth)
addr = id(co := frame.f_code) + type(co).basicsize
mem = (c_char * len(co._co_code_adaptive)).from_address(addr)
base = frame.f_lasti + _inline_cache_entries[mem[frame.f_lasti][0]] * 2
mem[base + 2:base + 4] = bytes([opmap['RAISE_VARARGS'], 1])
return exc
It'd be great if
1: the python bot supported stdin input, perhaps in a seperate code block to the code
2: the bot generated images by keyword to show terminal output with the effect of escape sequences.
although these are edge cases and anyone can just screenshot their terminal
and even an image cannot capture the glory of a loading bar
the bot could edit the output message at the correct time to animate the result :D
but then it would take so much more resources to run the bot
Would it? There's anyways a timeout, so it'd be at most a handful of edits..
then discord might complain to many requests or slow the bot down by ratelimiting
yeah. you'd anyways want to debounce that, I guess..
It's also gotta generate these images in realtime
Oh, I'm not talking about the images, just real-time output so loading bars etc. work
loading bars wouldn't work unless the escape sequences were intercepted and interpreted
Yes, sounds doable
bruh
i'm trying to do runtime constants but locals() only loads properly when it wants to
>>> f() = ...
File "<stdin>", line 1
f() = ...
^^^
SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
can we use assignment to function in this channel somehow?
f().__setcall__(...)
that's a syntax error
no can do unless you're modifying cpython
idea: build modified cpython in snekbox using build script and run modified cpython inside snekbox
i know you can do that
what
there's a cpython folder in snekbox?
If this doesn't work in your terminal, you're using the wrong terminal
def loadbar(size):
def map(f,*a):
[] = result = ()
try:assert(l:=len(a:=[*zip(*a)]))
except:return f()
print(f"\x1b[42m[\x1b[m{' '*size}\x1b[44m]\x1b[m {l} iterations remaining. ",end='\x1b[G',flush=1)
for i,e in enumerate(a):
n = i*size//l; g = 255 - (b:=i*255//l) # unit conversion is a real skill
result += f(*e),
print(f"\x1b[42m[\x1b[{n+1}G\x1b[48;2;12;{g+g*b//255};{b+g*b//255}m \x1b[44m\x1b[{size+1}G]\x1b[m {l-i} iterations remaining. ",end='\x1b[G',flush=1)
print(f'\x1b[42m[\x1b[{size+1}G\x1b[44m]\x1b[m 0 iterations remaining. ')
return map
loadbar(40)(time.sleep,[.1]*200)
there's cpython source code and gcc in snekbox?
decompile python executable, patch it and compile (using your own compiler of course)
what
how is that done with snekbox
also it isn't as easy as it seems
decompiling stuff into folders
new proposed source code for windows troubleshooter: ```py
def loadbar(size):
def map(f,*a):
[] = result = ()
try:assert(l:=len(a:=[zip(a)]))
except:return f()
print(f"\x1b[42m[\x1b[m{' 'size}\x1b[44m]\x1b[m {l} iterations remaining. ",end='\x1b[G',flush=1)
for i,e in enumerate(a):
n = isize//l; g = 255 - (b:=i255//l) # unit conversion is a real skill
result += f(e),
print(f"\x1b[42m[\x1b[{n+1}G\x1b[48;2;12;{g+gb//255};{b+gb//255}m \x1b[44m\x1b[{size+1}G]\x1b[m {l-i} iterations remaining. ",end='\x1b[G',flush=1)
print(f'\x1b[42m[\x1b[{size+1}G\x1b[44m]\x1b[m 0 iterations remaining. ')
return map
print("Windows is looking for problems...")
loadbar(40)(time.sleep,[1]*600)
print("We found no problems.")
runs twice as fast as the current source code for windows troubleshooter: ```c
#include <windows.h>
#include <stdio.h>
int main() {
printf("Windows is searching for problems...\n");
Sleep(1200);
printf("We didn't find any problems.\n");
}
oh i did something similar back in July
# creates std class and adds modules to import path
from cpp_stdlib import *
# now i can import iostream
import iostream
std.cout << "hi"; # wont print because its buffered
std.cout " there, hello" << std.endl; # prints "hi there, hello\n"
std.cout "hi" << std.flush; # prints "hi" with no nl
std.cout "no"; # wont print until the program ends and the destructor is called
cpp_stdlib.py
# add the cpp_stdlib folder to the module search path
# only works for me since im too lazy to figure out
# a way to do this without adding a "/cpp_stdlib" to
# every path in sys.path, which is a bad way to do stuff
__import__("sys").path.insert(0, __import__("sys").path[1]+"/cpp_stdlib")
# std class to represent the std namespace found in the c++ stdlib
class std:
pass
class flush:
pass
class endl:
pass
class cout:
def __init__(self):
self.write = __import__("sys").stdout.write;
self.buffer = "e";
def __lshift__(self, other):
if other == std.endl:
self.write(self.buffer[1:] + "\n");
self.buffer = "e";
elif other == std.flush:
self.write(self.buffer[1:]);
self.buffer = "f";
else:
self.buffer += str(other);
return self;
def __repr__(self):
return ["", __import__("os").system("echo -ne '\033[2A'") if self.buffer[0] != "f" else __import__("os").system("echo -n")][0]
def __del__(self):
self.write(self.buffer[1:]);
self.buffer = "";
std = __import__("__main__").std
std.cout = cout();
std.flush = flush;
std.endl = endl;
you could've implemented __getitem__ with slices for std
couldve, but imo . is closer to :: than [::]
maybe i couldve done some funky stuff with __annotations__ to do std:cout, but that just feels wrong
Hello People
I may have possibly made the world's most simplest and restricted language
it's called NumberScript (https://github.com/Sas2k/NumberScript)
Here is an example code from it.
0 %This %starts %it
2Hello
2World
3a=1
^a+4
2a
1 %Ends
you can also format this to 1 line as well
0 2Hello 3 World 3a=1 ^a+4 2a 1
It's still in Dev
snek
indeed
how can i get all the function in a call stack at the given point of time
def dfs(i):
if i >= len(nums):
res.append(sub.copy())
return
sub.append(nums[i])
#point 1
dfs(i+1)
sub.pop()
dfs(i+1)
#point 2
dfs(0)
I want to get the functions available at point 1 and point 2 in call stack
idk, but here's some more command line snek
sometimes the tail is too long by one cell tho
I still need to test gameover, but i also kinda wanna see how far i can go
You can't write new files in snekbox
So you would need to patch the executable in memory, and then use ctypes to recall the main function (properly with all the arguments passed correctly)
I'm working on an update to fishhook that will include some assembly hooking capabilities and that would make the patching easier at least
The code for assembly hooking is already written if anyone wants to mess with it it's on my pysnippets github under the name asm_hook.py
Currently my assembly hooking strategy involves using ctypes to call into python code so it would be interesting to see what happens if PyMain is called again after those CFUNCTYPE functions are created
I'm nailing this snake game
stays in one spot, and i'm using the input part of the interface with a thrown together event loop
now it looks better
that looks sick
I'm keeping gameover as an exception until I'm using Interface.run
damn
There is a gamewon, if you occupy the entire board
looks like a good golfing exercise ๐
it originally was, but I'm making the production code before it gets golfed
ah nice!
that display took some ANSI gymnastics
mhmm
only runs on windows, but here it is so far: ```py
from msvcrt import getch,kbhit
class Engine:
class Cell:
def init(self,x,y,init='blank'):self.value=init;self.n,self.xy=-1,x,y;self.head=0
def iter(self):return iter(self.xy)
def snake(self,n):self.value,self.n,self.head='snek',n,1;return self
def body(self):self.head=0;return self
def _fw(self):
if self.n>0:self.n-=1
if not self.n:self.value,(self.n,self.head)='blank',range(-1,1)
return self
BLINK=[0] # meta-methods
@classmethod
def blink(cls):cls.BLINK[0]^=1
def str(self):return{'blank':'\x1b[100m \x1b[m','snek':f'\x1b[{42+60self.head}m \x1b[m','food':f'\x1b[{41+60*class.BLINK[0]}m \x1b[m'}[self.value]
repr=str
class exceptions:
class GameOver(Exception):
def init(self,obj):self.engine=obj;super().init(f"Game Over")
class GameQuit(GameOver):0
class GameWon(GameOver):0
class FatalError(RuntimeError):
def init(self,e):super().init(f"{e.class.name}: {e}")
def init(self,x,y):
self.direction,*head,self.max,self.size=2,x//3,x//2,(x,y),3;self.matrix=[[*map(self.Cell,range(x),[row]*x)]for row in range(y)]
self.head=self[head].snake(3);self[x-head[0],head[1]].value='food'
def step(self):
(X,Y),(x,y),s,d=self.max,self.head,self.size,self.direction;target=[x+(d==2)-(d==3),y+(d==1)-(d==0)]
if target[0]not in range(X) or target[1]not in range(Y)or self[target].n>1:raise class.exceptions.GameOver(self)
assert target!=self.head,"self.direction must be in range(4) you idiot"
self.size+=(food:=self[target].value=='food');self.move_head(*target)
if not food:*map(self.Cell._fw,self),
else:(m:=[*filter(lambda x:x.value=='blank',self)])[import('random').randint(0,len(m)-1)].value='food'
if not[*filter(lambda s:s.value!='snek',self)]:raise class.exceptions.GameWon(self)
class.Cell.blink();return self
def move_head(self,x,y):
self[self.head].body();self.head=self[x,y].snake(self.size)
assert self.head.head;return self
def turn(self,d):
if self.direction//2!=d//2:self.direction=d
return self
def getitem(self,key):x,y=key;return self.matrix[y][x]
def iter(self):X,Y=self.max;return iter(self[x,y]for x in range(X)for y in range(Y))
def str(self):X,Y=self.max;return'[\n '+',\n '.join([', '.join(map(lambda x:str(self[x,y]),range(X)))for y in range(Y)])+'\n]'
repr=str
class Interface:
def init(self, args):
try:x,y=args
except:self.engine,=args
else:self.engine = Engine(x,y)
@property
def score(self):return self.engine.size
def iter(self):return self
def next(self):
if kbhit():
c=getch().decode('ANSI')
if c=='\xe0':c+=getch().decode('ANSI')
if c=='\x1b':raise StopIteration
return c
else:return'\0'
def display(self):
for cell in self.engine:x,y=cell;print(end=f"\x1b[{y+2}H\x1b[{x2+1}G{cell}{cell}")
print(f'\x1b[H{self.engine.size}\x1b[{engine.max[1]+1}H')
def run(self):
import time
t=time.time();print('\x1bc')
for char in self:
try:
... # the rubble of unfinished construction appears ahead of you
except Engine.exceptions.GameOver as e:print(f'\x1b[HGame {e.name[4:]}\x1b[{self.engine.xy[1]+3}H');return self
print(f'\x1b[HGAME QUIT\x1b[{self.engine.xy[1]+3}H');return self
if name=='main':
interface=Interface(10,10)
engine=interface.engine;import sys;print(end='\x1bc')
while 1:
d=next(interface)
if d=='w':engine.turn(0)
if d=='s':engine.turn(1)
if d=='d':engine.turn(2)
if d=='a':engine.turn(3)
if d=='q':raise Engine.exceptions.GameQuit(engine)
if ord(d):engine.step()
interface.display()
#score=Interface(30,20).run().score
about 3800 characters at a glance
mhmm
how to get code object of a python object?
<function subsets at 0x7f3d39761440>
I have a function object, I want to get code object of that object
!e ```py
def foo() -> None:
print("bar")
print(foo.code)
@old socket :white_check_mark: Your 3.11 eval job has completed with return code 0.
<code object foo at 0x7fc121ab16f0, file "<string>", line 1>
Thanks, silly me
how can i access the values of these objects
p=inspect.currentframe().f_globals['subsets'].code.co_cellvars
output: ('nums', 'dfs', 'res', 'sub')
got it
what should i esoteric (verb- make something unnecessarily complex [not real verb])?
(What's a real verb? Verbing weirds language.)
My coding is so evil I literally broke python. I try to run anything with the broken python it just says exit code 120 lmao
and the script was just printing pretty green letters to terminal.
weirding verbs language?
i think that happened with morbius
ooh
Calvin and Hobbes
one of the best comic strips of all time
I used to own a book of them, actually
I have several :)
it got destroyed though :(
ooh nice
!e ```py
import fishhook
@quartz wave :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'fishhook'
i dont understand because english is not my native language
neither do i
some adjectives and nouns can be used in sentences where you would typically put a verb
"i will weird this sentence" uses "weird" as the verb even though it's not a verb
sometimes when people do this enough the original word gets accepted as a verb, such as "access"
"sus"?
how would you get the actual code as a string from this?
read the source file?
but I get the feeling that's not what you mean
what you would probably do is read attributes of ._code_
!e ```py
def foo() -> None:
print("bar")
print(foo.code.co_code)
@old socket :white_check_mark: Your 3.11 eval job has completed with return code 0.
b'\x97\x00t\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00d\x01\xa6\x01\x00\x00\xab\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00d\x00S\x00'
I think
bytecode
I assume you would use the co_* attributes to figure it out
you could also exec a code object in namespace that's a class with getitem and setitem overloaded
to print var names+values
You can also prob just use inspect module
Actually that seems to be the best option
!e ```py
import inspect
def foo(): print("bar")
print(inspect.getsource(foo))
@old socket :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | File "/usr/local/lib/python3.11/inspect.py", line 1270, in getsource
004 | lines, lnum = getsourcelines(object)
005 | ^^^^^^^^^^^^^^^^^^^^^^
006 | File "/usr/local/lib/python3.11/inspect.py", line 1252, in getsourcelines
007 | lines, lnum = findsource(object)
008 | ^^^^^^^^^^^^^^^^^^
009 | File "/usr/local/lib/python3.11/inspect.py", line 1081, in findsource
010 | raise OSError('could not get source code')
011 | OSError: could not get source code
huh
does it get comments too?
Yes
hmm
probably a 3.11 thing then
I assumed he meant without a module though
@old socket probably because it's executed in a container or something?
!e ```py
raise SystemExit(10248129471289542174982141)
@quartz wave :warning: Your 3.11 eval job has failed.
A fatal NsJail error occurred
it's enclosed in nsjail
Ok
.bm how to raise nsjail error
random minesweeper game
508 fps
don't ask why
but it runs at 500 fps
Imma boutta make snake running at twice that
0 3ismorning:true ?ismorning=true:2goodMorning:2GoodDay 1
!d lambda
An anonymous inline function consisting of a single expression which is evaluated when the function is called. The syntax to create a lambda function is lambda [parameters]: expression
more fps
double the fps
How cranked can I get this?
the cpu fan is now running
so i guess when he stopped sending stuff that meant his pc blew up
just checked on my esoteric language and guess what the download count is
115 downloads
I just uploaded it yesterday
nice ๐
So, Should I create a support server or something like that?
for it?
thanks!
its up to you, if you feel like it then go for it
i think it's true it's been 3 hours ๐
Link?
sure
pypi -> https://pypi.org/project/NumberScript/
Github -> https://github.com/Sas2k/NumberScript
sure
rip
Bsod XD
I had over 330000 but the screenshot button slowed it down
I edited so it won't frame if it doesn't need to.
It was fun while it lasted tho
Hey guys I made the support server for the NumberScript
World's most simplest and restricting language built with Python
I see you have not met my child OIL
https://github.com/L3viathan/OIL
@soft vapor Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
you missed the Possibly part in the sentence
Possibly the world's most simplest and restricting language built with python
also your language is awesome. (That syntax of yours is What my goal was.) and it's in Esolang wikie so it's double awesome
framerate is now 5, unless you spam press spacebar to make the snake go faster
here's 3800 char snake, have fun golfing ```py
from msvcrt import getch,kbhit
class Engine:
class Cell:
def init(self,x,y,init='blank'):self.value=init;self.n,self.xy=-1,x,y;self.head=0
def iter(self):return iter(self.xy)
def snake(self,n):self.value,self.n,self.head='snek',n,1;return self
def body(self):self.head=0;return self
def _fw(self):
if self.n>0:self.n-=1
if not self.n:self.value,(self.n,self.head)='blank',range(-1,1)
return self
BLINK=[0] # meta-methods
@classmethod
def blink(cls):cls.BLINK[0]^=1
def str(self):return{'blank':'\x1b[100m \x1b[m','snek':f'\x1b[{42+60self.head}m \x1b[m','food':f'\x1b[{41+60*class.BLINK[0]}m \x1b[m'}[self.value]
repr=str
class exceptions:
class GameOver(Exception):
name=='GameOver'
def init(self,obj):self.engine=obj;super().init(class.name)
class GameQuit(GameOver):name=='GameQuit'
class GameWon(GameOver):name=='GameOver'
class FatalError(RuntimeError):
def init(self,e):super().init(f"{e.class.name}: {e}")
def init(self,x,y):
self.direction,*head,self.max,self.size=2,x//3,y//2,(x,y),3;self.matrix=[[*map(self.Cell,range(x),[row]*x)]for row in range(y)]
self.head=self[head].snake(3);self[x-head[0],head[1]].value='food'
def step(self):
(X,Y),(x,y),s,d=self.max,self.head,self.size,self.direction;target=[x+(d==2)-(d==3),y+(d==1)-(d==0)]
if target[0]not in range(X) or target[1]not in range(Y)or self[target].n>1:raise class.exceptions.GameOver(self)
assert target!=self.head,"self.direction must be in range(4) you idiot"
self.size+=(food:=self[target].value=='food');self.move_head(*target)
if not food:*map(self.Cell._fw,self),
else:
try:(m:=[*filter(lambda x:x.value=='blank',self)])[import('random').randint(0,len(m)-1)].value='food'
except ValueError:0
if not[*filter(lambda s:s.value!='snek',self)]:raise class.exceptions.GameWon(self)
class.Cell.blink();return self
def move_head(self,x,y):self[self.head].body();self.head=self[x,y].snake(self.size);assert self.head.head;return self
def turn(self,d):
if self.direction//2!=d//2:self.direction=d
return self
def getitem(self,key):x,y=key;return self.matrix[y][x]
def iter(self):X,Y=self.max;return iter(self[x,y]for x in range(X)for y in range(Y))
def str(self):X,Y=self.max;return'[\n '+',\n '.join([', '.join(map(lambda x:str(self[x,y]),range(X)))for y in range(Y)])+'\n]'
repr=str
class Interface:
def init(self, args):
try:x,y=args
except:self.engine,=args
else:self.engine = Engine(x,y)
@property
def score(self):return self.engine.size
def iter(self):return self
def next(self):
if kbhit():
c=getch().decode('ANSI')
if c=='\xe0':c+=getch().decode('ANSI')
if c=='\x1b':raise StopIteration
return c
else:return'\0'
def display(self):
for cell in self.engine:x,y=cell;print(end=f"\x1b[{y+2}H\x1b[{x2+1}G{cell}{cell}")
print(f'\x1b[H\x1b[91m{self.engine.size}\x1b[m\x1b[{self.engine.max[1]+1}H')
def run(self):
import time;t=time.time()+.2;print('\x1bc');q=[]
for char in self:
if char in'wasd':q+='wsda'.find(char),
if char=='q':break
if len(q)>4:q=q[-4:]
try:
if not(s:=(time.time()>t and(t:=time.time()+.2))or char==' '):continue
q and self.engine.turn(q.pop(0));self.engine.step();x=self.engine.max[0];self.display()
except Engine.exceptions.GameOver as e:print(f'\x1b[H{e}\x1b[{self.engine.max[1]+3}H');return self
print(f'\x1b[HGAME QUIT\x1b[{self.engine.max[1]+3}H');return self
if name=='main':score=Interface(20,20).run().score;print(score)
wasd to move, q or esc to quit, spacebar to go faster
hey what are the core parts of a language
things I already implemented:
print,
variables,
if-else,
for-loops,
arithemetic (+, -, /, *)
compare (=, !=, <, >)
What else are there?
(I'm going to implement User Input now)
I'd say functions and potentially OOP
ok
ok The new version of NumberScript (https://github.com/Sas2k/NumberScript) Is Finished and on pypi
the multiprocessing module is harmful to the computer.
can cause instability
ok
Also I finished a FizzBuzz program in my Language
Code:
%FizzBuzz-Program
0
3num:~Enter-Num>
6n\num\3nm:^n+1;?^nm#15=0:2FizzBuzz:5;?^nm#3=0:2Fizz:5;?^nm#5=0:2Buzz:2nm
1
Output:
Enter-Num>10
1
2
Fizz
3
4
Buzz
Fizz
6
7
8
Fizz
9
Buzz
@soft vapor how about 20?
wait let me try it
wow the syntax is... uhm
interesting let's just say
1
2
Fizz
3
4
Buzz
Fizz
6
7
8
Fizz
9
Buzz
11
Fizz
12
13
14
FizzBuzz
Fizz
Buzz
16
17
Fizz
18
19
Buzz
I wanted it to be like the Intcode syntax
pretty cool how you parse it tho
well I split the words by space
or newlines
i don't see spaces?
ayy i know that!
that's a bug i think
shouldn't it print the words, "fizz", "buzz" or "fizzbuzz" in place of the number?
so 3 shouldn't be there
Oh waiy
I thinkk it prints the sentence and the numer
**number, wait
I will fix it
You guys can try to fix it if you want
for i in range (1, 101):
out = ""
if i % 3 == 0:
out += "Fizz "
if i % 5 == 0:
out+= "Buzz"
if not out:
out += str (i)
print (out)```
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizz Buzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
Fizz Buzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
Fizz Buzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
Fizz Buzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
Fizz Buzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
Fizz Buzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz
!e
for n in range(17):
b, i = [str(n), ''], 0
if n % 3 == 0:
b[i] = 'Fizz'
i += 1
if n % 5 == 0:
b[i] = 'Buzz'
i += 1
print(''.join(b))
@proper vault :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | FizzBuzz
002 | 1
003 | 2
004 | Fizz
005 | 4
006 | Buzz
007 | Fizz
008 | 7
009 | 8
010 | Fizz
011 | Buzz
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/batoseriso.txt?noredirect
I meant to fix the problem in my language
(you can install the interpreter with pip install NumberScript==1.9.0)
I think the error lies in my interpreter
Can anyone see the code and see if there are any errors
hell yeah time to get to work
uh-
instead of for loops or while loops, you can use labels with goto
its platform specific
that's a good idea
ty <3
that would simulate functions as well, since you could goto a function label whenever it needs to be called
reinventing assembly i see
i havent yet, sorry
:p
more like ciml (or whatever its called)
George Ciprian Necula is a Romanian computer scientist, engineer at Google, and former professor at the University of California, Berkeley who does research in the area of programming languages and software engineering, with a particular focus on software verification and formal methods. He is best known for his Ph.D. thesis work first describin...
that thing
c intermediate language
so does anyone know if there is any errors or mis-haps in the interpreter
If anyone finds something
just put it here
oh Wait @versed eagle No need
I fixed the problem
dang
I just needed to make the max split to 2
ig windows isn't supported
@sick hound Sorry I can't accept your friend request since I only accept requests whom I know in real life
Np
why you compare __name__ with some strings?
technically all my code is esoteric because i write stuff horribly
i just reviewed my ansi console snake game code, itsucks
!e
def format1(func):
def dec(*args, **kwargs):print("-"*40);func(*args, **kwargs);print("-"*40)
return dec;[1];
def format2(func):
def dec(*args, **kwargs):print("+"*40);func(*args, **kwargs);print("+"*40)
return dec;[0];
@format1
def a(b):print(b)
@format2
def c(j):print(j)
a('Wohoo!');c('Yay!')
@lyric fern :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ----------------------------------------
002 | Wohoo!
003 | ----------------------------------------
004 | ++++++++++++++++++++++++++++++++++++++++
005 | Yay!
006 | ++++++++++++++++++++++++++++++++++++++++
childs play ```py
from inspect import signature
def fuckup(func):
@import('functools').wraps(func)
def _(a,**k):
return func(**dict((k,v2 if import('random').random()>.5 else v)if not(isinstance(v, bool))else(k,0 if v else 1) for k, v in signature(func).bind(*a,**k).arguments.items()))
return _
def f(func):
@import('functools').wraps(func)
def i(*a,**k):
c={}
for i, v in signature(func).parameters.items():
if v.kind is v.POSITIONAL_OR_KEYWORD:
if v.annotation!=v.empty:
if not(isinstance(signature(func).bind(*a,**k).arguments[v.name], v.annotation)):c[v.name]=v.annotation(signature(func).bind(*a,**k).arguments[v.name])
else:c[v.name]=signature(func).bind(*a,**k).arguments[v.name]
else:c[v.name]=signature(func).bind(*a,**k).arguments[v.name]
else:c[v.name]=signature(func).bind(*a,**k).arguments[v.name]
return func(**c)
return i
class b(str):
@f
@fuckup
def format(s, b,f:int):
return b.str()*f
@print
@lambda a: b().format(*a)
@lambda x: (x.doc[0], x.doc[1])
class _:
doc=("101101010101", import('random').randint(0, 100)^7)
>>> class X:
... 'a'
... __doc__ = 'b'
...
>>> X.__doc__
'b'
does anyone know if there is a way to embed information into a python function dynamically? what i want to do is have it so every python function has access to meta data like its name, a line number, the module, etc. the issue is to do that you have to use very performance heavy functions from the inspect module.
so im wondering if its possible to dynamically add a variable to a function that just gives it access to the information in advance, by either editing locals() or generating a default argument. or something that gives the function access to the meta data without having to call the expensive inspect funcitons?
decorators could maybe do it
could they. interesting.
ya im not super familiar with decorators yet. but ill look into it
you could exec the function. _code_ and provide a class for the namespace argument
you're welcome <3
What features would you like to see in python?
Good question...
Hmmmm...
@gaunt gate how often will the functions be using the metadata? Are you sure inspect is too expensive? You could put a cache around it.
so im trying to make a system that litterally logs the entire program so i can make my own little custom debugger. so if a function gets called in loop it could get really slow.
cache it.
sure. im drawing a blank as to how to do that though. any suggestions?
im still fairly new to python in general
a dict makes a fine cache.
you can also just set the info as an attribute on the function, and fall back to the slow path (inspect) when the attribute doesn't exist. Still a cache, but local on the function.
sure. i should clarify im trying to minimise the amount of boiler plate, so is there any way access the attribute generically? without having to explicitly type the functions name out?
you might want to start with an easier project than a dynamic debugger.
Can you describe again, ideally with a piece of code, how you'd use this ideally? Inside the function? Outside, before/after you call it?
oh definitly. i just didnt know it would requite this level of intricacy. cuz most of the meta data use cases are very simple so far until this issue
so inside the function i want to be able to access the functions metadata so i can log all the state of the function and associate it with the functions name with minimal performance cost and without having to type out lots of boiler plate.
wait hold on. are dictionaries static? meaning data entered into it persists across any call of the function?
you really might want to learn more about the basics of the language. data can be passed between functions, and persist beyond any one call.
i see. but then im glad i asked cuz now i know where to look
cuz if i can have static vars then this is free. so thank you
i'd recommend reading/watching https://bit.ly/pynames1
!e Since we're in esoteric Python, what you could do is:
import dis
def patch(fn):
code = fn.__code__
try:
global_idx = code.co_names.index("INFO")
except ValueError:
return fn
infodict = {"name": fn.__name__} # add other inspecty things here
consts = (*code.co_consts, infodict)
local_idx = len(consts) - 1
bytecode = []
it = iter(code.co_code)
for op, arg in zip(it, it):
if op == dis.opmap["LOAD_GLOBAL"] and arg == global_idx:
bytecode.append(dis.opmap["LOAD_CONST"])
bytecode.append(local_idx)
else:
bytecode.append(op)
bytecode.append(arg)
fn.__code__ = code.replace(co_consts=consts, co_code=bytes(bytecode))
return fn
@patch
def foo():
print(INFO["name"])
foo()
@restive void :white_check_mark: Your 3.10 eval job has completed with return code 0.
foo
in 3.11, arg >> 1 == global_idx
!e ```py
import dis
def patch(fn):
code = fn.code
try:
global_idx = code.co_names.index("INFO")
except ValueError:
return fn
infodict = {"name": fn.name} # add other inspecty things here
consts = (*code.co_consts, infodict)
local_idx = len(consts) - 1
bytecode = []
it = iter(code.co_code)
for op, arg in zip(it, it):
if op == dis.opmap["LOAD_GLOBAL"] and arg >> 1 == global_idx:
bytecode.append(dis.opmap["LOAD_CONST"])
bytecode.append(local_idx)
for _ in range(dis._inline_cache_entries[dis.opmap["LOAD_GLOBAL"]]):
next(it)
next(it)
else:
bytecode.append(op)
bytecode.append(arg)
fn.code = code.replace(co_consts=consts, co_code=bytes(bytecode))
return fn
@patch
def foo():
print(INFO["name"])
foo()
@quartz wave :white_check_mark: Your 3.11 eval job has completed with return code 0.
foo
!e ```py
from inspect import signature
def fuckup(func):
@import('functools').wraps(func)
def _(a,**k):
return func(**dict((k,v2 if import('random').random()>.5 else v)if not(isinstance(v, bool))else(k,0 if v else 1) for k, v in signature(func).bind(*a,**k).arguments.items()))
return _
def f(func):
@import('functools').wraps(func)
def i(*a,**k):
c={}
for i, v in signature(func).parameters.items():
if v.kind is v.POSITIONAL_OR_KEYWORD:
if v.annotation!=v.empty:
if not(isinstance(signature(func).bind(*a,**k).arguments[v.name], v.annotation)):c[v.name]=v.annotation(signature(func).bind(*a,**k).arguments[v.name])
else:c[v.name]=signature(func).bind(*a,**k).arguments[v.name]
else:c[v.name]=signature(func).bind(*a,**k).arguments[v.name]
else:c[v.name]=signature(func).bind(*a,**k).arguments[v.name]
return func(**c)
return i
class b(str):
@f
@fuckup
def format(s, b,f:int):
return b.str()*f
@print
@lambda a: b().format(*a)
@lambda x: (x.doc[0], x.doc[1])
class _:
doc=("101101010101", import('random').randint(0, 100)^7)
@unreal echo :white_check_mark: Your 3.11 eval job has completed with return code 0.
101101010101101101010101101101010101101101010101101101010101101101010101
now make it change the code depending on the version
woah i wrote the same thing
!paste
it requires keyboard and aioconsole to work btw
that wouldn't be too difficult tbh, just need to use platform.system() and use exec statements with globals
True lol
exec("".join(map(chr, __import__('zlib').decompress(b'x\x9cmQ\xc1n\x830\x0c\xbd\xf3\x15V/q$\x84`\xc7\x9c\xf6\x1f\xd5\x14\x05\x08kP U\x92J\xa0\xaa\xff>\x07F\x01mV\x0e\xb6\xdf\xb3\xfd\x1cg\x9fV\ru\xab\xa0\x17 \xa5\x19\xee\xceG)\x91\xb9\xc0x\x11\xe6\x10\xf5\x80\x1d\xd3\xcd\xcd\xc1\xb3\x7f1\x9em\xfcI\x00cE\xef\xcc\x88\xcd\xcd\xa3\xe1\xd09\x0f\x06\xcc\x08\xd3\xce\x92\x02\x06u\xc7\xbd\xc6\x8c\x11\xa7\x1c>x\x0e\xf2D\x93\x85\x94\xad\xb6*FO\xf3K\x9e5V\x85@H\x06d\xad\xee\xe0\x88\x07m;\xbeB\xc9\xbc\x8e\x0f?\xc2a\xcea\xaa\x11\xd0\xb1\xa7\xf3-\x89\x14\xf5\x8b\xe5$\x90\xe3\x86\xb6\xba1\x83\xb2A@=G\x1dp\x8byA\x9ek5\x1e\xb8\xb5\x19\x95\x9f\x05\\\xd3\x16\x89\x9e\x16Y\xf6NAZ\xdd\x9a@\xc8B\xe3_{a\xd4S\x14\x80WBp\x15\xc2\x0b\xaf\xefV5\x1aYM\x8a\x18;\xfc_\x88\x1eS\x05u\xe0x\xb9\xac\x9f|^\xc8\xe4\x80f\xaf\xd8\x10\xaa4\xe3w\x12x\xee\xb6\xe6\x93\xa2\xedf\xe7\xabl\xae\x15\x90\x8eii\xee\xfbPt)dUY\xd2+\x93\xd2j\xf1\xab_7E\xff\xb9\xd5J(\xcbw\xd5\x92=\xe3\xd9\x92\xa6n\x7f;\xa4q\x8c\xef\xf6\x03\xdcb\xc4k'))))
tbh i should've put a rickroll there
Hey how do you get a language into the esoteric language wiki
No need of this
Anyways this got 226 downloads
lmao
!e hides 'exec' in a series of and and or evaluations
import random
hide = lambda hidden: (lambda special: (lambda words: (lambda instructions: '"'+'"'.join((''.join([''.join([special.pop() if len(special) and not instructions[0] else words.pop(random.randint(0, len(words)-1)), '" '+('and' if instructions.pop(0) else 'or')+' "']) for _ in range(len(words))])).split('"')[:-2])+'"')([1]*7+[random.choice((0, 1)) for _ in range(len(words))]))(dir(__builtins__)))([hidden])
o = hide('exec')
print(eval(o))
print(o)
@steady lily :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | exec
002 | "eval" and "round" and "OverflowError" and "abs" and "hex" and "ModuleNotFoundError" and "setattr" and "PendingDeprecationWarning" and "Exception" and "exec" or "UnicodeDecodeError" or "map" or "dict" and "divmod" or "str" or "NotImplemented" or "list" and "AttributeError" or "ResourceWarning" and "tuple" or "TypeError" or "print" or "slice" and "__debug__" and "bin" and "bool" or "frozenset" and "UnicodeEncodeError" or "bytearray" and "DeprecationWarning" or "__spec__" or "ZeroDivisionError" or "StopIteration" or "delattr" or "TimeoutError" or "IOError" and "ArithmeticError" and "format" or "__import__" and "KeyError" or "oct" or "chr" and "memoryview" and "FutureWarning" and "filter" and "anext" and "StopAsyncIteration" or "UserWarning" and "ConnectionAbortedError" or "id" or "ExceptionGroup" or "BaseException" and "hash" and "ReferenceError" or "input" and "True" and "BytesWarning" and "range" or "__package__" or "all" or "exec" and "IndexError" or "min" and "pow" o
... (truncated - too long)
Full output: https://paste.pythondiscord.com/xajadupaqe.txt?noredirect
Hey how do you create an inmport and library system in python
python has its whole import system written in python
try inserting at line 0 import os;os.system('');
my terminal automatically parses escape sequences
yeah that worked
What I mean is that. I want to implemented a import and library system in my language.
How do I do this
oh wow you added moves that can be buffered huh
yeah, but there's a cap to buffered moves
up to 4 moves can be buffered
if you spam press wdwdwdwdwdwdsd, then on the next frame it will parse wdsd
I'm working on tetris next
idk
i forget what the names all mean, but the top left corner of the shape is what falls, the rest of the shape rotates so that its highest point is level with the corner, and its leftest point is below the corner
bagged?
I'm writing this entirely off memory
and that memory does not include any terminology
so just a literal matrix rotation?
ok
you should check out the leaked 2009 official Tetris guidelines if you want something fancy btw
entirely off memory
and I just realised 7 is an upside down L and nearly made two Ls
not quite, it's more like each cell in a shape has an id within that shape in range(4), a shape rotation in range(4) and the shape's id in range(-1,7)
a cell's position relative to its shape's top left corner is fetched from hard coded offset values like dx,dy = self.displacements[self.shape_id][self.rot][self.id]
a pair of dx, dy are spat out by each cell, and the engine deactivates all four active cells, and activates new cells at the locations provided by the respective x+dx, y+dy values
if there's interference to this process from static cells, I've yet to decide whether to cancel the action or offset y in the negative (up) direction
perhaps I should allow a single offset only if the offset is unobstructed
here's the raw rotation data
in a nutshell, Cell contains conversion data, cell objects contain data, Engine() contains cells and executes conversions, Interface() makes it look like tetris.
doesnt it have import system written in C? i thought this pure-python import system just duplicates C-code
actually i think it's only the file finding that's implemented in python
Guys help
what
nvm :)
Ahem
Windows 11???
So you don't code in Linux?
lmao
The most esoteric operating system
Linux is for nerds.
@floral meteor can i have your snekgame ๐ ๐
@unreal echo not mine
?
i replied to the source code
.bm esoteric snake game
are you calling me a nerd
gasp
how dare you
Lmao
Caesar cipher (where s is some string, and n is an int of how much to shift).
Wondering how it can be done shorter?
from string import ascii_lowercase as A
def p1(s,n):
i=lambda _:((n+A.index(_.lower()))%26)
return"".join([(A[i(c)].upper(),A[i(c)])[c in A]if c.lower()in A else c for c in s])
from string import ascii_lowercase as A
A="abcdefghijklmnopqrstuvwxyz"
even better:
A=list(map(chr,range(65,91)))```
(then flip .upper and .lower)
A=[*map(...)]
range(*b"AZ") is more characters but funnier
aw wait that skips Z
kinda wish there were ranges for other types too
as much as I hate regex, [A-z] or [0-9] is really handy
The problem with regex is mostly about how unreadable it is literally the next day you go and take a look at it
the irony of complaining about being unreadable in #esoteric-python
true lmao
but regex is bad universally really, not specifically in python
Pretty sure most languages have the same rules for regex
A=[*map(chr,range(*b"A["))]
gets the Z
oh you have never been more wrong 
hmm
hey, is there any list of things that we can do with array index?
stuff like [:], [2:] etc
a:b:c desugars to slice(a,b,c) when inside an index operation, which means you can do lots of fun things like x[:,...,::,...,:]
It depends on the implementation of the object's __getitem__ and __setitem__ methods
Huh, I never realized slice is type-agnostic; never seen it used with anything but numbers. But foo["bar":"bat":()] is legal.
i thiiink pandas allows string slices for selecting a range of columns
Yes.
!e print(slice("foo",1,0.123))
@earnest wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
slice('foo', 1, 0.123)
neat