#esoteric-python

1 messages ยท Page 2 of 1

unreal echo
#

!d abc

night quarryBOT
#
abc

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:

royal whale
#

!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))
night quarryBOT
#

@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)
royal whale
#

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()))
night quarryBOT
#

@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
wheat river
#

dont call Empty

versed eagle
languid hare
#

!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))
night quarryBOT
#

@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
restive void
#

@quartz wave request for your CPython fork (I think that was you):

from fishhook, abc import hook, ABC
languid hare
unreal echo
#

what is this fish hook thing yall are doing

#

!pypi fishhook

night quarryBOT
unreal echo
#

i feel like this esoteric stuff has purposes that im gonna need in the near future

#

which would suck

versed eagle
#

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

royal whale
#

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

royal whale
#

bc normally __annotations__ is a dict

versed eagle
#

well ig you could hook dict.__setitem__ but that would be all dicts, not just annotations

#

which would be not good

royal whale
#

yeah that's what I was thinking
hmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm...

versed eagle
#

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_

restive void
#

!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
night quarryBOT
#

@restive void :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).

do thing with x <class 'int'>
restive void
#

Basically: change __class__ of __annotations__, except you're not allowed to do that for dicts.

royal whale
#

!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))
night quarryBOT
#

@royal whale :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).

<class 'str'>
royal whale
#

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())
night quarryBOT
#

@royal whale :x: Your 3.11 eval job has completed with return code 139 (SIGSEGV).

001 | whoopty doo
002 | <class '__main__.Foo'>
003 | 27
royal whale
#

Anyone mind if I copyright this and sell it

versed eagle
royal whale
earnest wing
#

!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))
night quarryBOT
#

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

001 | 42
002 | <class '__main__.C'>
earnest wing
earnest wing
#

convenient, since it's not cpython-specific anymore!

royal whale
#

Yeah

#

Much, much better

fleet bridge
#

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}

night quarryBOT
#

@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
finite blaze
unreal echo
#

someone explain fishhook

finite blaze
fleet bridge
night quarryBOT
#

dis.dis(x=None, *, file=None, depth=None)```
restive void
versed eagle
# unreal echo someone explain fishhook

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

unreal echo
#

can't you just do py class int(int): def __add__(self, other): return self.__subtract__(other)

quartz wave
unreal echo
#

!d abc.ABC

night quarryBOT
#

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...
earnest wing
unreal echo
quartz wave
unreal echo
#

makes sense

#

written esoterically for esoteric purposes

astral rover
#

anyone know how you can check if a string is interned through python using ctypes?

quartz wave
#

that's what i can tell you

brazen geyser
#

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

astral rover
#

i cant get that macro :(

#

or PyASCIIObject

brazen geyser
#

you can mimic it using ctypes.Structure

quartz wave
#

but try if you want to

astral rover
#

the heck is this unsigned int interned:1;

quartz wave
#

i'm gonna test hold on

quartz wave
astral rover
#

why :1?

quartz wave
#

ctypes supports those btw

brazen geyser
#

how would this affect it? you could check that exact bit no?

quartz wave
#

the tuples in _fields_ have to be ('name', type, bit_field_size)

#

bit_field_size is optional

brazen geyser
#

can you clarify what the issue with place size/struct size means? not sure i understand

quartz wave
#

when you actually look at it from its outside container (PyASCIIObject), its size is only 8 bits

quartz wave
brazen geyser
#

how does that prevent accessing that one particular bit?

quartz wave
brazen geyser
#
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

astral rover
#

Thanks, I'll give it a go

wanton flame
#

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)

teef ๐Ÿคข

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)}")
granite tangle
#

๐Ÿ’€

wanton flame
#

serious answer: I like to play code golf to smash and smoosh my (non-production) code as small as I can

pastel sparrow
granite tangle
#

sounds cool

#

good luck with it

fleet bridge
#

!e

from dis import dis
dis('a.b: c')
night quarryBOT
#

@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
quartz wave
floral meteor
quartz wave
#

i think i've been working on it for 3 hours

floral meteor
#

Perhaps objects could have parameter annotations just like global variables have annotations

quartz wave
quartz wave
#

but i've already regenerated them

restive void
#

I could also try it on the lastest main of cpython, I guess

quartz wave
quartz wave
#

the module caches were causing problems ๐Ÿค”

floral meteor
#

wat have I done?

wheat river
#

s=()

floral meteor
#

!e print(len(())) # wrong

night quarryBOT
#

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

0
earnest wing
#

overridden __iter__ incompatibly with __len__?

floral meteor
#

I didn't even use __len__

#

but the __iter__ is a mess, and memory in position offset 16 is modified

wheat river
earnest wing
#

[*s] is not [s]

wheat river
#

no, i thought [*s] = 0 and [s] = 1, thats why said ()

floral meteor
#

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

quartz wave
#

@restive void this works now ```py

from dis, sys import *
setrecursionlimit
<built-in function setrecursionlimit>
dis
<function dis at 0x00000230DFF23330>

restive void
#

I've been working on it, too, but Python/compile.c is.. a bit tough

quartz wave
quartz wave
floral meteor
#

at least they match now. Now I just need the contents to be the actual contents

earnest wing
floral meteor
#

yes

earnest wing
#

I mean it would have to traverse the python path

floral meteor
#

name clashes will be resolved with loss of information

quartz wave
floral meteor
#

import* would be a better idea

#

to get everything

earnest wing
#

well, help("modules") seems to find everything (minus cwd paths)

floral meteor
#

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_char
len(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

quartz wave
quartz wave
restive void
quartz wave
restive void
quartz wave
astral rover
#

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 lemon_angrysad

unreal echo
#

!d sys.setrecursionlimit

night quarryBOT
#

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.
junior mesa
#

from flask_mysqldb import MySQL
ModuleNotFoundError: No module named 'flask_mysqldb'

#

how clear this error

#

can't install flask mysql db

sick hound
#

!e import ctypes;ctypes.string_at(0)

#

๐Ÿ˜ญ

night quarryBOT
#

@sick hound :warning: Your 3.10 eval job has completed with return code 139 (SIGSEGV).

[No output]
rugged sparrow
vital dirge
#

hey how do I get code coloring again... ``py ?

royal whale
vital dirge
royal whale
vital dirge
#

ah, right

royal whale
vital dirge
#

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

night quarryBOT
#

@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
wheat river
#

def __eq__ instead of def__eq__

vital dirge
#

oh. Oh I see, thank you

#

hrm that also didn't execute?

vital dirge
night quarryBOT
#

@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
vital dirge
#

!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')
night quarryBOT
#

@vital dirge :white_check_mark: Your 3.11 eval job has completed with return code 0.

A mixed tale
vital dirge
#

ok, yes!

#

aaanyway I think this is a cool way to mix regexes into structural pattern matching

finite blaze
#

anyone here tried golfing snake before?

fleet bridge
#

is it possible to get access to real hardware where snekbox is running and execute arbitrary code on it?
if no, why?

finite blaze
#

well i guess if you can escape sandboxing

#

then it is possible

#

is it opensource btw?

quartz wave
finite blaze
#

What would be the shortest way to check if x == 0 or 9

versed eagle
#
if x in(0,9):... # your code here
finite blaze
#

wait, you cant do string[index]='char' to replace character in string at index?

burnt pasture
finite blaze
#

trying to golf snake

#

map is a string

#

and i wanted to replace chars at given index with '@'

burnt pasture
#

@finite blaze use a bytearray instead. They are mutable

finite blaze
#
t='#'*10+'\n';m=t+f"#{' '*8}#\n"*8+t;
#

so thats how i generate my map (okay i've removed not needed code)

quartz wave
#

one character difference

finite blaze
#

nope

#

i need space

#

to generate my map

#

cuz without it it will look like this

burnt pasture
finite blaze
#

oh i didnt notice the :

#

my bad

#

how does it work?

burnt pasture
#

:8 means, make this take 8 spaces

finite blaze
#

thanks

finite blaze
#

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

versed eagle
finite blaze
#

I guess i would have to change 'cls' right?

versed eagle
#

yeah

#

you'd have to do "cls"if platform.system()=="Windows"else"clear"

#

and import platform

finite blaze
#

Yeah, I'll focus on windows for now

#

I just want to finish it first

versed eagle
versed eagle
#

does it use the terminal width/height and make the map the size of the terminal, or is it fixed width/height?

finite blaze
#

Fixed

versed eagle
#

cool

finite blaze
#

Need to make the first line shorter

versed eagle
finite blaze
#

s array will contain snake body

#

5,5 is just it's head

versed eagle
#

oh, its a list of coordinate tuples?

finite blaze
#

Yup

versed eagle
#

instead of time.sleep(), you can use os.system("SLEEP 1")

#

so you dont have to import time

sick hound
#

Are you trying to reduce length

#

!e

from time import*
sleep(1)
night quarryBOT
#

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

[No output]
sick hound
#

Or same for OS and use the suggestion above mine

versed eagle
#

!e

print(len(
"""from time import*;import os
sleep(1);os.system("cls")"""))
print(len(
"""from os import system as _;_("cls");_("SLEEP 1")"""))
night quarryBOT
#

@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 53
002 | 48
versed eagle
#

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")"""))
night quarryBOT
#

@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.

52
versed eagle
versed eagle
sick hound
#

Considering my next comment, I meant doing the same for os

#

!e

print(len("""from os import*;system("cls");system("sleep 1")"""))
night quarryBOT
#

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

47
sick hound
#

This is one character shorter

old socket
#

!e ```py
print(len("(:=import('os'))('cls');('sleep 1)"))

night quarryBOT
#

@old socket :white_check_mark: Your 3.11 eval job has completed with return code 0.

40
gaunt gate
#

hey everyone. super random question- are the metaprogramming facilities faster in pypy? general question, all answers welcome

burnt pasture
gaunt gate
#

just curious why they would be slower in pypy? if thats not an enourmous question

#

if it is dont worry about it

burnt pasture
#

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.

gaunt gate
#

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

earnest wing
#

!e

print(len("""import os;s=os.system;s("cls");s("sleep 1")"""))
night quarryBOT
#

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

43
earnest wing
old socket
#

Brain fart

quartz wave
night quarryBOT
#

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

34
quartz wave
#

-9

fleet bridge
#

import os;os.system('')
__import__('os').system('')

quartz wave
fleet bridge
#

i know, im just comparing __import__ expr and import statement

#

statement is 4 char shorter

finite blaze
#

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

lyric fern
#

!e - imagine

print('hi'): str
night quarryBOT
#

@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
floral meteor
finite blaze
#

yep!

floral meteor
#
import os;os.system('cls')
print('\x1bc')
floral meteor
finite blaze
#

i need to find a good way to read input

floral meteor
#

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)
floral meteor
#

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()

finite blaze
#

s is a list of coordinate tuples

#

and (5,5) i just snake's head

floral meteor
#

ah you want snek

finite blaze
#

yepp

floral meteor
#

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

finite blaze
#

true

floral meteor
#

although my idea of production code would be traumatising for some here's my progress so far

floral delta
#

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 meteor
#

because this channel is absolute last resort

#

where you go if you need to make 2 + 2 == 5

floral delta
#

works

floral meteor
quartz wave
floral meteor
#

Very few people understand the meaning of "esoteric"

vital dirge
#

hidden knowledge?

floral meteor
vital dirge
#

yeah

#

that's right, small circle of folks who understand it

#

you're correcter than me

floral meteor
#

not exactly hidden knowledge. Just difficult or uncommon to grasp

vital dirge
#

like for when you want a decorator that can turn a class definition into a function definition or vice versa

floral meteor
#

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

vital dirge
#

LOL the ninja-fu

floral meteor
#

remote variable mutation

vital dirge
#

has there been a security audit conducted on the standard library yet?

#

comprehensive, I mean, including stuff like fuzzing

#

and taint tracing

floral meteor
vital dirge
#

sure

#

ok

floral meteor
#

at least better than here

#

Here we just poke holes in python

vital dirge
#

of particular note: merging structural pattern matching with regexes

#

by overriding str.eq

quartz wave
vital dirge
#

str.__eq__

quartz wave
#

@vital dirge extreme example of esoteric

floral meteor
#

I have a mild irrational phobia of match-case, or its aliases in other languages, I prefer to use inline dictionary-getitem-call

vital dirge
quartz wave
floral meteor
#

here's how we switched in the good ol' days of python 3.9

vital dirge
floral meteor
#

This is an example of remote variable mutation, and also an simulation of a Turing Machine.

floral meteor
quartz wave
floral meteor
#

!e useless knowledge for the day: ```py
[[[[a]]]] = [[[[69]]]]
print(a)

night quarryBOT
#

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

69
floral meteor
#

spider variables: they have 8 legs

vital dirge
#

also they have 8 eyes

#

i[0 : 7]

#
Spider bite:
  Flail_about
  Cry_ouch
  Stick_to(walls)
  Shoot(webs)
  Fight(crime)
floral meteor
#

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__
royal whale
#

!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]
night quarryBOT
#

@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

royal whale
#

wait

#

that didn't error

#

Dangg

floral meteor
#

it's infinite.

royal whale
#

yea, I didn't realize that

floral meteor
#

and you don't need c as an intermediate variable

#

lists don't copy on variable assignment.

#

neither do strings actually

royal whale
#

ah

#

I am but a young padawan compared to you, a veritable Jedi Knight of esotericsm

floral meteor
#

!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)

night quarryBOT
#

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

G'day
floral meteor
#

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)

night quarryBOT
#

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

001 | Hello
002 | World
versed eagle
lyric fern
#

!e
class console(object):
def log(a: str):
return a

console.log('e');

night quarryBOT
#

@lyric fern :warning: Your 3.11 eval job has completed with return code 0.

[No output]
lyric fern
#

!e
class console(object):
def log(a: str):
return a

print(console.log('e'));

night quarryBOT
#

@lyric fern :white_check_mark: Your 3.11 eval job has completed with return code 0.

e
vital dirge
#

!e
isclose(3, 3.0000000003)

#

!e
1

night quarryBOT
#

@vital dirge :warning: Your 3.11 eval job has completed with return code 0.

[No output]
vital dirge
#

ok so:

#

!e
isclose(3, 3.00000003)

night quarryBOT
#

@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
#

hrm.

#

!e
import math
math.isclose(3, 3.000000003)

night quarryBOT
#

@vital dirge :warning: Your 3.11 eval job has completed with return code 0.

[No output]
vital dirge
#

!e
import math
math.isclose(3, 3.000000000000000000000000003)

night quarryBOT
#

@vital dirge :warning: Your 3.11 eval job has completed with return code 0.

[No output]
astral rover
#

would you mind running these in #bot-commands?

vital dirge
#

ok

shrewd seal
#

Is there a way of shortening

data = "whatever data"
for some in bunch:
  data = transform_data(data, some)
```?
night quarryBOT
#
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").
last locust
#

data = [*map(lambda s:transform_data(data,s),bunch)] at a guess

versed eagle
#

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):
        ...
earnest wing
#

this should be fairly short and to the point

shrewd seal
#

:O

royal whale
fleet bridge
night quarryBOT
#

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

001 | __annotations__['x'] = 1
002 | __annotations__['y'] = 2
vital dirge
#

lol

#

you effectively re-invented the assignment operator? ๐Ÿ™‚

#

I mean you can put the values in the globals dictionary too for that matter

twin reef
#

Now each variable can store two times more data!

versed eagle
#

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

cloud fossil
#

Why does Python call in's corresponding dunder method __contains__ and not __in__

unreal echo
unreal echo
#

None of the skills I learnt in this channel have been used in production

#

Why do I keep coming back

cloud fossil
#

Nothing posted in this channel is meant to be used in production

versed eagle
unreal echo
#

Huh

#

Don't get it but okay

#

Why does it inherit from dict

#

Doesn't annotations already have setitem

versed eagle
#

because annotations is normally a dict

#

so it has to have all the same attributes that dict has

unreal echo
#

Kk

versed eagle
#

otherwise stuff can break

shrewd seal
#

Any way of using try/catch and context managers inside a lambda?

cloud fossil
#

Oh because otherwise it's the class

versed eagle
cloud fossil
versed eagle
#

decorators are really cool in general

cloud fossil
#

To be precise

versed eagle
#

yeah I should have

#

but I'm on mobile

cloud fossil
#

But honestly it's the same

versed eagle
#

and I'm lazy

#

cause typing on mobile is hard

cloud fossil
#

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

versed eagle
#

!e

@object.__new__
class cl:
    def __init__(self):
        print("hi")
night quarryBOT
#

@versed eagle :warning: Your 3.11 eval job has completed with return code 0.

[No output]
earnest wing
versed eagle
#

!e

@object.__new__
class cl:
    def __init__(self):
        print("hi")
print(cl)
night quarryBOT
#

@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.

<__main__.cl object at 0x7f99298374d0>
cloud fossil
#

I guess not?

cloud fossil
#

Wait oh never mind it is an instance

versed eagle
#

you can also use metaclasses

#

but that's more verbose

#

to get the same result

cloud fossil
#

A single purposefully made object

#

In code

versed eagle
#

it never has init called

#

which is interesting

earnest wing
#

I like @type.__call__ because you can then alternate between those and @type annotations to create a funny decorator chain

cloud fossil
versed eagle
#

yeah

#

so you can have uninitialized objects

#

if you want

cloud fossil
#

Oh my god

#

That's actually not a bad thing

#

If only it was not for a single object

versed eagle
#

!e

@object.__new__
class cl:
    def __init__(self):
        print("hi")
        self.thing = 4
print(cl)
cl.__init__()
print(cl.thing)
night quarryBOT
#

@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
versed eagle
#

yeah

cloud fossil
#

Tbh you can just override the class's __new__ method to not initialize

#

Unless it happens during type.__call__

versed eagle
#

you could use metaclasses

#

to do that

cloud fossil
#

Yeah

restive void
cloud fossil
#

Right

#

Imagine having in then

#

It's like __rcontains__ or something

shrewd seal
sick hound
#

does using .pythonrc to do weird stuff in Python interpreter count as esoteric?

#

having neofetch inside Python's interpreter

finite blaze
#
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

versed eagle
quartz wave
#

no assignment ever copies

versed eagle
#

but when you operate on it afterwards, it does change

versed eagle
#

!e

a=5
b=a
b+=1
print(a,b)
night quarryBOT
#

@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.

5 6
versed eagle
#

why not the same with lists

quartz wave
versed eagle
#

!e

a=[5]
b=a
b+=[1]
print(a,b)
night quarryBOT
#

@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.

[5, 1] [5, 1]
versed eagle
#

a is also changed

quartz wave
versed eagle
#

wait what

#

why not

quartz wave
#

ints don't

#

so the default behaviour is __add__

versed eagle
quartz wave
#

any immutable type doesn't implement __i*__ like mutable types do

finite blaze
#

i think we are facing the same problem

#

almost

versed eagle
#

why isn't the end result the same though

finite blaze
#

how can i avoid it?

versed eagle
#

like, why would they design the language specification in such a way that lists are like this
is there a use case?

finite blaze
#

cuz it seems like m also changes

finite blaze
#

the same as t

versed eagle
finite blaze
#

explain please?

#

(it works, thanks)

quartz wave
fleet bridge
#

!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)
night quarryBOT
#

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

001 | __init__ called
002 | __init__ called
003 | True
fleet bridge
#

im not calling __init__ directly

quartz wave
versed eagle
#

it's a slice

finite blaze
#

so what array1=array2 does?

quartz wave
versed eagle
#

yes

quartz wave
versed eagle
#

I was typing an explanation to go further in more detail but mobile typing is hard :(

versed eagle
#

in c, they use pointers instead, right?

quartz wave
versed eagle
#

oh, since you're here, can you answer a question for me?

#

I asked a while ago and got no answer

versed eagle
#

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

quartz wave
versed eagle
#

hmm
ok

#

what about with ctypes?

versed eagle
quartz wave
versed eagle
#

"i mean such as you can do"

quartz wave
versed eagle
#

my English teachers have lied to me

quartz wave
versed eagle
#

well I'm gonna go do some stupid stuff with globals and annotations

#

goodbye

#

thank you for your help

#

have a nice day cereal

versed eagle
#

well now i just have to figure out how to not recurse on _getitem_ for globals

quartz wave
versed eagle
#

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)
quartz wave
versed eagle
#

alr

#

oh, i also got it to segfault somehow

quartz wave
versed eagle
#

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

unreal echo
#

๐Ÿ’€

#
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'))))```
gusty quartz
#

they said it couldnt SHOULDNT be done

there - yall happy now

quartz wave
unreal echo
quartz wave
floral meteor
#

Why does he need to be reincarnated to have the knowledge?

#

Wouldn't the mortal form make it harder to remember everything?

twin reef
#

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.
"""))
night quarryBOT
#

@twin reef :white_check_mark: Your 3.10 eval job has completed with return code 0.

42
twin reef
#

hello world is too long/too pythonic ๐Ÿ˜ฆ

#

I call this language zenfuck

fleet bridge
floral meteor
#

You calculated the meaning of life, the universe and everything in zenfuck!

#

How to hide a distress call in your source code

quartz wave
#

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

floral meteor
#

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

restive void
#

the bot could edit the output message at the correct time to animate the result :D

floral meteor
#

but then it would take so much more resources to run the bot

restive void
#

Would it? There's anyways a timeout, so it'd be at most a handful of edits..

floral meteor
#

then discord might complain to many requests or slow the bot down by ratelimiting

restive void
#

yeah. you'd anyways want to debounce that, I guess..

floral meteor
#

It's also gotta generate these images in realtime

restive void
#

Oh, I'm not talking about the images, just real-time output so loading bars etc. work

floral meteor
#

loading bars wouldn't work unless the escape sequences were intercepted and interpreted

restive void
#

Yes, sounds doable

floral meteor
#

you'd get "beautiful mojibake"

#

cursor movement

quartz wave
#

bruh
i'm trying to do runtime constants but locals() only loads properly when it wants to

floral meteor
#

you gotta establish yourself as the boss

#

be the alpha programming language

fleet bridge
#
>>> 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__(...)

quartz wave
fleet bridge
#

idea: build modified cpython in snekbox using build script and run modified cpython inside snekbox

#

i know you can do that

quartz wave
#

there's a cpython folder in snekbox?

floral meteor
#

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)
earnest wing
#

there's cpython source code and gcc in snekbox?

fleet bridge
earnest wing
#

it would be easier to patch in-memory

#

decompilation output is famously garbage

floral meteor
quartz wave
#

also it isn't as easy as it seems

#

decompiling stuff into folders

floral meteor
#

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 = 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

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");
}

versed eagle
# gusty quartz

oh i did something similar back in July

main.py

# 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

iostream.py

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;
quartz wave
versed eagle
#

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

soft vapor
#

Hello People

#

I may have possibly made the world's most simplest and restricted language

#

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

floral meteor
finite blaze
#

indeed

marsh mica
#

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

floral meteor
#

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

rugged sparrow
#

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

floral meteor
#

I'm nailing this snake game

floral meteor
#

stays in one spot, and i'm using the input part of the interface with a thrown together event loop

#

now it looks better

pastel sparrow
#

that looks sick

floral meteor
#

I'm keeping gameover as an exception until I'm using Interface.run

pastel sparrow
#

damn

floral meteor
#

There is a gamewon, if you occupy the entire board

pastel sparrow
#

looks like a good golfing exercise ๐Ÿ‘€

floral meteor
#

it originally was, but I'm making the production code before it gets golfed

pastel sparrow
#

ah nice!

floral meteor
#

that display took some ANSI gymnastics

pastel sparrow
#

mhmm

floral meteor
#

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+60
self.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[{x
2+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

pastel sparrow
#

mhmm

floral meteor
#

I'll finish it tomorrow

#

a damn it is tomorrow

marsh mica
#

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

old socket
night quarryBOT
#

@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>
marsh mica
#

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

unreal echo
#

what should i esoteric (verb- make something unnecessarily complex [not real verb])?

restive void
floral meteor
#

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

floral meteor
#

and the script was just printing pretty green letters to terminal.

versed eagle
restive void
quartz wave
versed eagle
#

Calvin and Hobbes

#

one of the best comic strips of all time

#

I used to own a book of them, actually

restive void
#

I have several :)

versed eagle
#

it got destroyed though :(

versed eagle
quartz wave
#

!e ```py
import fishhook

night quarryBOT
#

@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'
fleet bridge
# restive void

i dont understand because english is not my native language

earnest wing
#

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"

shy remnant
versed eagle
#

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_

old socket
#

!e ```py
def foo() -> None:
print("bar")

print(foo.code.co_code)

night quarryBOT
#

@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'
old socket
#

I think

versed eagle
#

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

old socket
#

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))

night quarryBOT
#

@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
old socket
#

uhhh weird it works fine for me using my own python

versed eagle
#

huh

old socket
#

Python 3.11 error?

#

My ipython is on 3.10

versed eagle
old socket
versed eagle
#

hmm
probably a 3.11 thing then

versed eagle
quartz wave
#

!e ```py
raise SystemExit(10248129471289542174982141)

night quarryBOT
#

@quartz wave :warning: Your 3.11 eval job has failed.

A fatal NsJail error occurred
quartz wave
#

it's enclosed in nsjail

old socket
#

Ok

unreal echo
floral meteor
#

random minesweeper game

languid hare
#

508 fps

floral meteor
#

don't ask why

#

but it runs at 500 fps

#

Imma boutta make snake running at twice that

soft vapor
#

0 3ismorning:true ?ismorning=true:2goodMorning:2GoodDay 1

sick hound
#

!lambda

#

!lambdas

floral meteor
#

!d lambda

night quarryBOT
#

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

floral meteor
#

snake works now

#

and it goes at 6000 fps

floral meteor
#

double the fps

#

How cranked can I get this?

#

the cpu fan is now running

quartz wave
# floral meteor

so i guess when he stopped sending stuff that meant his pc blew up

soft vapor
#

just checked on my esoteric language and guess what the download count is

#

115 downloads

#

I just uploaded it yesterday

wheat river
#

nice ๐Ÿ‘

soft vapor
#

for it?

soft vapor
wheat river
quartz wave
soft vapor
sick hound
#

I'll check it out tomorrow, it's 3 am here

#

Thanks ๐Ÿ˜ƒ

soft vapor
floral meteor
#

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

soft vapor
#

Hey guys I made the support server for the NumberScript

restive void
night quarryBOT
#

@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

soft vapor
#

Possibly the world's most simplest and restricting language built with python

soft vapor
floral meteor
#

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+60
self.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[{x
2+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

soft vapor
#

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)

last locust
soft vapor
floral meteor
#

the multiprocessing module is harmful to the computer.

floral meteor
#

can cause instability

soft vapor
#

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
eager sphinx
#

@soft vapor how about 20?

soft vapor
sour grove
#

interesting let's just say

soft vapor
#
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
soft vapor
sour grove
#

pretty cool how you parse it tho

soft vapor
#

or newlines

sour grove
#

i don't see spaces?

sour grove
#

shouldn't it print the words, "fizz", "buzz" or "fizzbuzz" in place of the number?

#

so 3 shouldn't be there

soft vapor
#

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

tame onyx
#
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
proper vault
#

!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))
night quarryBOT
#

@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

soft vapor
#

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

pastel sparrow
versed eagle
versed eagle
versed eagle
#

ty <3

soft vapor
#

anyways

#

did any of you figure out why my interpreter isn't working?

versed eagle
#

that would simulate functions as well, since you could goto a function label whenever it needs to be called

languid hare
#

reinventing assembly i see

versed eagle
#

i havent yet, sorry

languid hare
#

:p

versed eagle
#

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

soft vapor
#

so does anyone know if there is any errors or mis-haps in the interpreter

versed eagle
#

i havent been able to look at it yet, sorry

#

i will later today though

soft vapor
#

If anyone finds something

#

just put it here

#

oh Wait @versed eagle No need

#

I fixed the problem

pastel sparrow
soft vapor
#

I just needed to make the max split to 2

pastel sparrow
#

ig windows isn't supported

soft vapor
#

@sick hound Sorry I can't accept your friend request since I only accept requests whom I know in real life

fleet bridge
unreal echo
#

technically all my code is esoteric because i write stuff horribly

#

i just reviewed my ansi console snake game code, itsucks

lyric fern
#

!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!')
night quarryBOT
#

@lyric fern :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | ----------------------------------------
002 | Wohoo!
003 | ----------------------------------------
004 | ++++++++++++++++++++++++++++++++++++++++
005 | Yay!
006 | ++++++++++++++++++++++++++++++++++++++++
unreal echo
# lyric fern !e ```py def format1(func): def dec(*args, **kwargs):print("-"*40);func(*arg...

childs play ```py
from inspect import signature
def fuckup(func):
@import('functools').wraps(func)
def _(a,**k):
return func(**dict((k,v
2 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)

fleet bridge
#
>>> class X:
...   'a'
...   __doc__ = 'b'
...
>>> X.__doc__
'b'
gaunt gate
#

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?

versed eagle
#

decorators could maybe do it

gaunt gate
#

ya im not super familiar with decorators yet. but ill look into it

versed eagle
#

you could exec the function. _code_ and provide a class for the namespace argument

gaunt gate
#

ok ill try that.

#

oh and thank you

versed eagle
#

you're welcome <3

finite blaze
#

What features would you like to see in python?

royal whale
burnt pasture
#

@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.

gaunt gate
gaunt gate
#

im still fairly new to python in general

burnt pasture
#

a dict makes a fine cache.

restive void
#

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.

gaunt gate
#

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?

burnt pasture
restive void
#

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?

gaunt gate
gaunt gate
#

wait hold on. are dictionaries static? meaning data entered into it persists across any call of the function?

burnt pasture
#

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.

gaunt gate
#

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

burnt pasture
restive void
#

!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()
night quarryBOT
#

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

foo
restive void
#

huh, strange, doesn't work in 3.11

#

probably because of all the bytecode changes

quartz wave
#

!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()

night quarryBOT
#

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

foo
quartz wave
#

@restive void

#

account for arg >> 1 and the number of CACHEs of LOAD_GLOBAL

unreal echo
# unreal echo childs play ```py from inspect import signature def fuckup(func): @__import_...

!e ```py
from inspect import signature
def fuckup(func):
@import('functools').wraps(func)
def _(a,**k):
return func(**dict((k,v
2 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)

night quarryBOT
#

@unreal echo :white_check_mark: Your 3.11 eval job has completed with return code 0.

101101010101101101010101101101010101101101010101101101010101101101010101
last locust
unreal echo
#

!paste

#

it requires keyboard and aioconsole to work btw

unreal echo
last locust
#

True lol

unreal echo
#
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

soft vapor
#

Hey how do you get a language into the esoteric language wiki

soft vapor
steady lily
#

!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)
night quarryBOT
#

@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

languid hare
#

err

#

why?

soft vapor
#

Hey how do you create an inmport and library system in python

quartz wave
floral meteor
#

my terminal automatically parses escape sequences

pastel sparrow
floral meteor
#

how's it look now?

#

I haven't tested it on anything other than Win11

pastel sparrow
#

it looks good

soft vapor
#

How do I do this

pastel sparrow
#

oh wow you added moves that can be buffered huh

floral meteor
#

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

quartz wave
earnest wing
#

any wall kicks?

floral meteor
#

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

languid hare
#

bagged?

floral meteor
#

I'm writing this entirely off memory

#

and that memory does not include any terminology

earnest wing
#

so just a literal matrix rotation?

#

ok

#

you should check out the leaked 2009 official Tetris guidelines if you want something fancy btw

floral meteor
#

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

floral meteor
floral meteor
#

in a nutshell, Cell contains conversion data, cell objects contain data, Engine() contains cells and executes conversions, Interface() makes it look like tetris.

fleet bridge
quartz wave
sick hound
#

Guys help

quartz wave
sick hound
#

nvm :)

royal whale
versed eagle
#

lmao

restive void
#

The most esoteric operating system

floral meteor
#

Linux is for nerds.

unreal echo
unreal echo
#

?

pastel sparrow
#

i replied to the source code

versed eagle
#

gasp

#

how dare you

#

Lmao

wanton flame
#

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])
maiden blaze
#
from string import ascii_lowercase as A
A="abcdefghijklmnopqrstuvwxyz"
wanton flame
dark wharf
#

A=[*map(...)]

maiden blaze
#

aw wait that skips Z

#

kinda wish there were ranges for other types too

wanton flame
#

as much as I hate regex, [A-z] or [0-9] is really handy

primal juniper
#

The problem with regex is mostly about how unreadable it is literally the next day you go and take a look at it

maiden blaze
primal juniper
#

true lmao

#

but regex is bad universally really, not specifically in python

#

Pretty sure most languages have the same rules for regex

wanton flame
earnest wing
primal juniper
#

hmm

finite blaze
#

hey, is there any list of things that we can do with array index?

#

stuff like [:], [2:] etc

earnest wing
#

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[:,...,::,...,:]

cloud fossil
restive void
#

Huh, I never realized slice is type-agnostic; never seen it used with anything but numbers. But foo["bar":"bat":()] is legal.

maiden blaze
#

i thiiink pandas allows string slices for selecting a range of columns

floral meteor
earnest wing
#

!e print(slice("foo",1,0.123))

night quarryBOT
#

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

slice('foo', 1, 0.123)
earnest wing
#

neat