#esoteric-python

1 messages ยท Page 135 of 1

halcyon bay
#

the bitmaps don't give me the associated curves though

#

so let's say I wanted to construct the letter 'a'

The bitmap would say "here's how to construct an 'a' out of exactly 37 points. If you have less points than that, you're out of luck"

#

Whereas getting a curve or list of curves that describe how to draw the 'a' would say, "if you have more than the minimum number of points to describe the curve (usually 3-4 points) than we're in business"

#

So it would allow the number of points used to draw the glyph to be variable. The package I linked can do this for the outlines of the letters, but not the letter itself.

#

Actually, this example almost does what I want: it reduces the letter to series of curves. Thank you, I missed that

vague cairn
vague cairn
#

based on one of the comments I modified it to

def tail_call_optimized2(g):
    """
    This function decorates a function with tail call
    optimization. It does this by throwing an exception
    if it is it's own grandparent, and catching such
    exceptions to fake the tail call optimization.

    This function fails if the decorated
    function recurses in a non-tail context.
    """
    state = []
    def func(*args, **kwargs):
        if not state:#@ start of stack, we want to catch from the top of the stack.
            state.append(1)
            try:
                while 1:
                    try:
                        return g(*args, **kwargs)
                    except TailRecurseException as e:
                        args = e.args
                        kwargs = e.kwargs
            finally:
                state.clear()
        else:
            try:
                return g(*args, **kwargs)
            except RecursionError as E:
                raise TailRecurseException(args, kwargs)#we're at the top of the stack, throw all the way to the bottom of the stack.
                
    func.__doc__ = g.__doc__
    return func

Which appears to be ever so slightly faster to shaves an entire 1/7 off the time, apparently based on the whims of the GC.

#

Which makes sense, this version lets the entire stack fill up before restarting, instead of letting the GC keep everything incrementally trimmed back.

#

(and doesn't need to import sys)

vague cairn
#

Ok, I both versions are only correct for functions with a single nesting call:

@tail_call_optimized
def weird_nest_test(i=5, j='-'):#don't do this.
    if i<0: return j[0]
    if i==0: return j
    assert weird_nest_test(-1,j) == j[0] #this call instruction should never match frame instruction.
    return weird_nest_test(i-1, j * i)

This always gives a wrong answer on the first and third versions, and randomly fails on second (depending on whether the stack was reached.
I can fix the original by changing it to:

def tail_call_optimized(g):
    """
    This function decorates a function with tail call
    optimization. It does this by throwing an exception
    if it is it's own grandparent, and catching such
    exceptions to fake the tail call optimization.
    
    This function fails if the decorated
    function recurses in a non-tail context.
    """
    def func(*args, **kwargs):
        f = sys._getframe(1)#changed this to 1
        if f.f_back and (fbb := f.f_back.f_back) \
              and fbb.f_code == f.f_code \
              and f.f_lasti == fbb.f_lasti:#added this comparison
                  raise TailRecurseException(args, kwargs)
        #removed this else:
        while 1:
            try:
                return g(*args, **kwargs)
            except TailRecurseException as e:
                args = e.args
                kwargs = e.kwargs
    func.__doc__ = g.__doc__
    return func
#

but ... this makes me want to write a dis-assembler re-assembler version. and I don't have time for that.

rapid sparrow
#

yeah, but you shouldn't let a little thing like time get in your way

#

To make tail-optimized functions, i think?

sick hound
#

@rapid sparrow me and truth made most complex hello world

vague cairn
#

a decorator that takes appart the code of the given function catches all locations where it says return self(*args, **kargs)
and change that to a continue, and wrap the whole thing in a while True:
effectively, except...

sick hound
#

!e ```py
builtins.import('sys')._getframe(0).f_globals.setitem(
"method",
object.class.class("method", (), {
"take_argument": print
})
)
builtins.import('sys')._getframe(0).f_globals.setitem(
"setobj",
object.class.class("class", (), {
"varobj": method.take_argument
})
)
builtins.import('sys')._getframe(0).f_globals.setitem(
"setvariablename",
setobj.varobj
)
builtins.import('sys')._getframe(0).f_globals.setitem(
"varname",
setvariablename("hello")
)

builtins.import('sys')._getframe(0).f_globals.setitem(
"varname2",
setvariablename("world")
)

builtins.import('sys')._getframe(0).f_globals.setitem(
"method",
object.class.class("method", (), {
"take_argument": print
})
)
builtins.import('sys')._getframe(0).f_globals.setitem(
"setobj",
object.class.class("class", (), {
"varobj": method.take_argument
})
)
builtins.import('sys')._getframe(0).f_globals.setitem(
"setvariablevalue",
setobj.varobj
)```

night quarryBOT
#

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

001 | hello
002 | world
rapid sparrow
#

of the above code.

vague cairn
#

yep, verify that the call being made is to itself.

#

I'm not clear if I need to replace the stack frame with a blank one but with new args, or what.

rapid sparrow
sick hound
#

shut up this should never be simplied

rapid sparrow
#

yeah, who does that

#

if you make it long enough to exceed a screen, people will forget what they are looking at and lose context

sick hound
#

you know you guys can just code in C++

rapid sparrow
#

in other words, Java

#

give the classes unique names while you'te at it, then you can simplify away the delete

#

well I'm shocked, shocked

#

__import__ hello
simplified v3

#

indeed

sick hound
#

hey guys

#

what do yall think the most esoteric way to make classes is

proper vault
#

writing the PyObject struct by hand using ctypes

sick hound
#

whats ctyoes

#

idk

#

ctypes

prisma coral
#

Oh boy

#

!e ```py
import ctypes
ctypes.c_int.from_address(id(7)+24).value = 0
print(1 < 7)

night quarryBOT
#

@prisma coral :white_check_mark: Your eval job has completed with return code 0.

False
unique rose
#

i'm suprised .value dereferences

#

iirc, in most versions of fortran you can just write 7 = 0

#

likewise, True = 0 in python-2

fleet bridge
#

!e



def is_compiled(cls: type) -> bool:
    return not any(
        getattr(cls, attr, None).__class__.__name__ == 'function' for attr in dir(cls)
    )


def compiled_str(cls: type) -> str:
    return ('Py', 'C')[is_compiled(cls)]


def print_class(cls: type, index: int = 0, indent: str = '') -> None:
    name = cls.__name__
    module = cls.__module__
    if module == 'builtins':
        module = ''

    print(f"{f'{indent}{index:3} {name}':<55} {compiled_str(cls):2}  {module} ")


def print_subclasses(cls: type, index: int = 0, indent: str = '') -> None:
    print_class(cls, index, indent)
    subclasses = type.__subclasses__(cls)
    for i, c in enumerate(subclasses):
        print_subclasses(c, i, '  . ' + indent)


class X: # this will be recognised as compiled, because there are no methods
    pass

class Y:
    def __init__(self) -> None:
        pass


print_subclasses(object)
night quarryBOT
#

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

001 |   0 object                                              C    
002 |   .   0 type                                            C    
003 |   .   .   0 ABCMeta                                     Py  abc 
004 |   .   1 async_generator                                 C    
005 |   .   2 int                                             C    
006 |   .   .   0 bool                                        C    
007 |   .   3 bytearray_iterator                              C    
008 |   .   4 bytearray                                       C    
009 |   .   5 bytes_iterator                                  C    
010 |   .   6 bytes                                           C    
011 |   .   7 builtin_function_or_method                      C    
... (truncated - too many lines)

Full output: too long to upload

fleet bridge
#

it prints beautiful hierarchy of all defined classes

unique rose
#

is .mro() not relevant here?

fleet bridge
#

thanks!

unique rose
#

oh you're doing the inverse of .mro, ie., finding all children

fleet bridge
#

hmm it has duplicates

#

๐Ÿ˜„

#

def is_compiled(cls: type) -> bool:
    return not any(getattr(cls, attr, None).__class__.__name__ == 'function' for attr in dir(cls))


def compiled_str(cls: type) -> str:
    return ('Py', 'C')[is_compiled(cls)]


def print_class(cls: type, index: int = 0, indent: str = '') -> None:
    name = cls.__name__
    module = cls.__module__
    if module == 'builtins':
        module = ''

    print(f"{f'{indent}{index:3} {name}':<55} {compiled_str(cls):2}  {module} ")


def print_subclasses(cls: type, index: int = 0, indent: str = '', memo: set[type] = None) -> None:
    indent_add = '  . '
    if memo is None:
        memo = set[type]()

    print_class(cls, index, indent)
    subclasses = type.__subclasses__(cls)
    if cls in memo:
        print(f'{indent + indent_add}...')
    else:
        memo.add(cls)
        for i, c in enumerate(subclasses):
            print_subclasses(c, i, indent_add + indent, memo)


class X:  # this will be recognised as compiled, because there are no methods
    pass


class Y:
    def __init__(self) -> None:
        pass


print_subclasses(object)
```updated
#

recently ive learned its possible to instantiate generic builtins in this way: set[int]() or dict[str, str]()

unique rose
#

or, to tidy, ```py

def print_class(cls: type, index: int = 0, indent: str = '') -> None:
def is_compiled(cls: type) -> bool:
return not any(getattr(cls, attr, None).class.name == 'function' for attr in dir(cls))

print(f"{indent}{index:3} {cls.__name__:<55} {('Py', 'C')[is_compiled(cls)]}  {cls.__module__} ")

def print_subclasses(cls: type, index: int = 0, indent: str = '', seen: list = []) -> None:
if cls in seen:
return

print_class(cls, index, indent)
seen.append(cls)

for i, c in enumerate(type.__subclasses__(cls)):
    print_subclasses(c, i, '  . ' + indent, seen)
#

seen should be a set, but wouldnt run as a set on mine, not sure why

fleet bridge
fleet bridge
fleet bridge
sick hound
#

has any1 here made their own language

#

or something similar

#

just curious

unique rose
#

ah, its just my version of python

#

i wasnt running 3.9+, now it works

fleet bridge
#

how to know if the class is compiled or written in python?

unique rose
#
def print_subclasses(cls: type, index: int = 0, indent: str = '', seen: set[type] = set()) -> None:
    def _print(cls: type, index: int = 0, indent: str = '') -> None:
        def _ispy(cls: type) -> bool:
            return not any(getattr(cls, attr, None).__class__.__name__ == 'function' for attr in dir(cls))

        print(f"{indent}{index:3} {cls.__name__:<55} {('Py', 'C')[_ispy(cls)]}  {cls.__module__} ")

    if cls not in seen:
        _print(cls, index, indent)
        for i, c in enumerate(set(type.__subclasses__(cls)) - seen):
            print_subclasses(c, i, '  . ' + indent, seen)
#

i'm trying to think of a simpler test

#

yeah, i was thinking of a module reference

fleet bridge
#

no, it works only with methods

#

i want to recognise classes such as class X: pass as pure python

fleet bridge
#

oh...

#

sry

unique rose
#

arent python classes either X.__module__ == '__main__' or otherwise haev .py in them?

fleet bridge
#

no

#

.py isnt appended

#

!e
print(__import__('typing').Iterator.__module__)

night quarryBOT
#

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

typing
fleet bridge
#
>>> import typing
>>> sys.modules['typing']
<module 'typing' from 'D:\\Programs\\Python\\310\\lib\\typing.py'>
>>> import math
>>> sys.modules['math']
<module 'math' (built-in)>
```we can check file where class's module is
unique rose
#

you can maybe just check __new__

#

ie., type(X.__new__) will be a builtin if its compiled, otherwise it'll be an object derivative

#

my guess is, 'builtin' in str.__new__.__class__.__name__

#

will be true for compiled classes, ie., sub str for a given class

fleet bridge
#

!e

class X: pass
class Y:
  def __new__(cls):
    pass

print('builtin' in str.__new__.__class__.__name__)
print('builtin' in X.__new__.__class__.__name__)
print('builtin' in Y.__new__.__class__.__name__)



night quarryBOT
#

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

001 | True
002 | True
003 | False
unique rose
#

i didnt get a True on X

fleet bridge
#

what is your version?

unique rose
#

not sure, maybe i had an X around from some other run

#

the test doesnt work anyway, so no good

fleet bridge
#

!e

import sys
import typing

def is_compiled(cls: type) -> bool:
    if (module := sys.modules.get(cls.__module__, None)) is None:
        pure_module = False
    elif (spec := module.__spec__) is None:
        pure_module = False
    else:
        pure_module = spec.origin != 'built-in'

    return not (
        pure_module
        or any(getattr(cls, attr, None).__class__.__name__ == 'function' for attr in dir(cls))
    )

class X: pass
class Y:
    def __init__(self): pass

print(f'{is_compiled(int) = }')
print(f'{is_compiled(X) = }')
print(f'{is_compiled(Y) = }')
print(f'{is_compiled(typing.TypeVar) = }')
print(f'{is_compiled(type("", (), {})) = }')
# print(f'{is_compiled(some_module.X) = }') # but if X is empty class defined in other module, it will be recognised as pure python, i hope
night quarryBOT
#

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

001 | is_compiled(int) = True
002 | is_compiled(X) = True
003 | is_compiled(Y) = False
004 | is_compiled(typing.TypeVar) = False
005 | is_compiled(type("", (), {})) = True
night quarryBOT
#

Lib/typing.py line 764

class TypeVar( _Final, _Immutable, _TypeVarLike, _root=True):```
rapid sparrow
#

!e
e.g.,

__import__("pprint").pprint(dict(sorted([(k, getattr(getattr(v, "__loader__", None), "__name__", None) or getattr(v, "__loader__", None).__class__.__name__) for k,v in list(__import__("sys").modules.items())])))
night quarryBOT
#

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

001 | {'__main__': 'BuiltinImporter',
002 |  '_abc': 'BuiltinImporter',
003 |  '_ast': 'BuiltinImporter',
004 |  '_codecs': 'BuiltinImporter',
005 |  '_collections': 'BuiltinImporter',
006 |  '_collections_abc': 'SourceFileLoader',
007 |  '_frozen_importlib': 'FrozenImporter',
008 |  '_frozen_importlib_external': 'FrozenImporter',
009 |  '_functools': 'BuiltinImporter',
010 |  '_imp': 'BuiltinImporter',
011 |  '_io': 'BuiltinImporter',
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/sumemuvelu.txt?noredirect

rapid sparrow
#

BuiltinImporter and ExtensionFileLoader will be the modules implemented in C. SourceFileLoader and FrozenImporter will be the ones written in python, if I'm not mistaken

#

in C I'm including stuff that uses the C API like rust, fortran, etc

#

some modules will be python source , but still have "built-in" functions because they simply import functions from a C extension module, I believe

#

!e
for example

import io, _io
print(f"{io.open is _io.open=}")
night quarryBOT
#

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

io.open is _io.open=True
golden finch
#

beautiful

rapid sparrow
#

and many details will be found

#

but not necessarily in comments

fleet bridge
#
import sys
def is_compiled(cls: type) -> int:
    if any(getattr(cls, attr, None).__class__.__name__ == 'function' for attr in dir(cls)):
        return 0
    if cls.__module__ == '__main__':
        return 0
    if cls.__module__ == 'builtins':
        return 1

    module = sys.modules.get(cls.__module__, None)
    if module is None:
        return -1

    loader = module.__loader__
    if loader is not None:
        if loader.__class__.__name__ in {'ExtensionFileLoader'}:
            return 1
        if loader.__class__.__name__ in {'SourceFileLoader'}:
            return 0
        if loader.__name__ in {'FrozenImporter', 'BuiltinImporter'}:
            return 1

    spec = module.__spec__
    if spec is not None:
        if spec.origin.endswith('built-in'):
            return 1
        if spec.origin.endswith('.pyd'):
            return 1
        if spec.origin.endswith('.py'):
            return 0

    return -1


def compiled_str(cls: type) -> str:
    return {
        -1: '??',
        0: 'Py',
        1: 'C',
    }[is_compiled(cls)]
```the most complete version
#

cannot be broken

rapid sparrow
#

let's see

fleet bridge
#

maybe it can crash here if there is some custom loader

sick hound
#

hey, hope this is the right channel to ask this.. i'm trying to debug some implementation details of random.Random(seed), specifically the difference between how it handles bytes and ints. for example,

>>> import random
>>> 
>>> random.Random(bytes.fromhex("cafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00d")).random()
0.5658661137631236
>>> random.Random(0xcafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00d).random()
0.5514871491681438
#

looking at the c implementation, it seems like it hashes the bytes but not the ints, which would explain the different output: https://github.com/python/cpython/blob/f4c03484da59049eb62a9bf7777b963e2267d187/Modules/_randommodule.c#L303-L306

but if that's the case, then i would expect the hash of the bytes to generate the same output (0.5658661137631236). so it seems like it's doing something more than just hashing the input? any ideas?

>>> random.Random(hash(bytes.fromhex("cafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00d"))).random()
0.5557356028492896
night quarryBOT
#

Modules/_randommodule.c lines 303 to 306

Py_hash_t hash = PyObject_Hash(arg);
if (hash == -1)
    goto Done;
n = PyLong_FromSize_t((size_t)hash);```
rapid sparrow
#

It returned true for all methods I could find in:
_asyncio, _bz2, _codecs_cn, _codecs_hk, _codecs_iso2022, _codecs_jp, _codecs_kr, _codecs_tw, _contextvars, _crypt, _ctypes, _ctypes_test, _curses, _curses_panel, _dbm, _decimal, _hashlib, _json, _lsprof, _lzma, _multibytecodec, _multiprocessing, _opcode, _posixshmem, _queue, _sqlite3, _ssl, _testbuffer, _testcapi, _testimportmultiple, _testinternalcapi, _testmultiphase, _uuid, _xxsubinterpreters, _xxtestfuzz, _zoneinfo, audioop, mmap, nis, ossaudiodev, parser, readline, resource, termios, xxlimited

#

which are all extension modules

#

These I couldn't fund any usable callables in to check, though I didn't look super hard:
_codecs_cn, _codecs_hk, _codecs_iso2022, _codecs_jp, _codecs_kr, _codecs_tw, _crypt, _ctypes_test, _opcode, _posixshmem, _testimportmultiple, _testinternalcapi, _uuid, _xxtestfuzz, readline

#

I was only looking at members of classes

fleet bridge
# sick hound looking at the c implementation, it seems like it hashes the bytes but not the i...
>>> import random
>>> random.Random(bytes.fromhex("cafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00c")).random()
0.7704815135035927
>>> random.Random(0xcafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00c).random()
0.10138861086464579
>>> random.Random(hash(bytes.fromhex("cafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00c"))).random()
0.85474433430598
```it gives three different numbers in all cases
rapid sparrow
sick hound
#

aren't they the same binary representation?

fleet bridge
#

!e

print(hash(b'\0'))
print(hash(0))
night quarryBOT
#

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

001 | -2763233213550341773
002 | 0
fleet bridge
#

hash(bytes) is randomly salted, but random.Random(bytes).random() doesnt salt the value

sick hound
#

that would explain it.. but where do you see it is randomly salted? I get the same output every time

night quarryBOT
#

Lib/random.py line 128

def seed(self, a=None, version=2):```
sick hound
#

ohh wow i completely missed this file

#

looks like bytes gets sha512

#
elif version == 2 and isinstance(a, (str, bytes, bytearray)):
            if isinstance(a, str):
                a = a.encode()
            a = int.from_bytes(a + _sha512(a).digest(), 'big')
sick hound
#

hmm, i'm still getting different values even with sha512

>>> random.Random(int.from_bytes(hashlib.sha512(bytes.fromhex("cafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00d")).digest(), 'big')).random()
0.9705493706075311
>>> random.Random(bytes.fromhex("cafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00d")).random()
0.5658661137631236
>>> 
vague cairn
sick hound
#
>>> import random
>>> 
>>> random.Random(bytes.fromhex("cafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00d")).random()
0.5658661137631236
>>> random.Random(0xcafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00d).random()
0.5514871491681438
>>> random.Random(int.from_bytes(bytes.fromhex("cafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00d") + hashlib.sha512(bytes.fromhex("cafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00dcafef00d")).digest(), 'big')).random()
0.5658661137631236
#

thank you so much @fleet bridge !

dim geyser
#

i have a task where i have a set of data for papers written by Charles Severance. I need to make a program where i print out the co-authors

this is what the data looks like

This is what i got so far. I managed to print out name and how many articles Charles Severance have written.
but i dont know how to find information about the co-authors

#

this is what the data looks like:

#

okey, thanku

rapid sparrow
#

so we should run some real workloads on it and see if theres a noticable benefit from tail optimizing

#

it seems like, if it weren't beneficial, why would compilers and other languages be doing it

proper vault
#

a lot of languages use it as a feature, alternative to loops

#

since it gives a nice O(1) space loop without mutability

#

other than that, it is a minor optimalization

rapid sparrow
#

and it would put some tail recuraive algorithms within reach that need deep stacks? though the functions in question would need to be written to take advantage of it, I guess

proper vault
#

every tail recursive algorithm can be trivially rewritten into a while loop

rapid sparrow
#

then it becomes just iteration whether t's done by the programmer, or the compiler?

proper vault
#

yup

#

C compilers can remove recursion even from non-tail calls

#

and some other more powerful compilers

#

which can be helpful

rapid sparrow
#

what about actually just using the same stack frame and jumping back to the entry point, with the new arguments on the stack

proper vault
#

that's what TCO more or less is

#

the issue is that you lose the stack trace

rapid sparrow
#

does that count as iteration?

proper vault
#

yes

rapid sparrow
#

amazing

#

crankykong what won't they think of next

night quarryBOT
#

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

[No output]
#

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

False
unique rose
#

(_),(__)=(([]==[])|([]!=[])),([]!=[])+_)==([])

sick hound
#

hmm quines

rapid sparrow
#

that's a truism for sure

#
([] == []) or ([] != [])

should hope that wouls be true ;p

#

!e

print(f"{() is ()=}")
night quarryBOT
#

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

001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | () is ()=True
rapid sparrow
#

odd SyntaxWarning

#

what's happening here

#

!e

print(
    set([(int(i) is int(i)) for i in range(35000)])
)
night quarryBOT
#

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

{True}
rapid sparrow
#

do we cache way more integers than i thought

rugged sparrow
rugged sparrow
turbid dragon
#

!e py _:__import__('typing').Callable[[str],str] = lambda m=None: True if m is False else False; print((__:=(_,))[0](True if (___:=lambda e=None: _())() else 'E'))

night quarryBOT
#

@turbid dragon :white_check_mark: Your eval job has completed with return code 0.

False
turbid dragon
#

is this esoteric enough

turbid dragon
#

i need a reassurance that that is 100% esoteric

rapid sparrow
#

Is It Esoteric or Just Correct Type Hinting?

turbid dragon
#

okay fine ill go back and work on it more

rapid sparrow
#

there's no limit afaik

#

lots of _, :, = are always good

sick hound
#

( []==[]) is always cool unless overused

turbid dragon
#

what does that do

rapid sparrow
#

wtf ??

#

!e

{__:__, (__:=__):_} = _:__:=8
night quarryBOT
#

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

001 |   File "<string>", line 1
002 |     {__:__, (__:=__):_} = _:__:=8
003 |     ^^^^^^^^^^^^^^^^^^^
004 | SyntaxError: cannot assign to dict literal here. Maybe you meant '==' instead of '='?
sick hound
#

huh

rapid sparrow
#

i got a different error

sick hound
rapid sparrow
#

>>> {__:__, (__:=__):_} = _:__:=8 File "<stdin>", line 1 {__:__, (__:=__):_} = _:__:=8 ^ SyntaxError: cannot assign to dict display

turbid dragon
#

!e py print([]==[])

night quarryBOT
#

@turbid dragon :white_check_mark: Your eval job has completed with return code 0.

True
maiden river
#

ok so i wanna ask

turbid dragon
#

yeah

maiden river
#

is there a ceil function like excel

#

eg

ceil(num, upperBound)
ceil(5222, 1000)
>>> 6000```
turbid dragon
#

how can i make a fake print

rapid sparrow
#

bollux

turbid dragon
#

what

#

fake print?

rapid sparrow
#

i think its only doing what it does for me because I'm in the repl

sick hound
rapid sparrow
turbid dragon
#

!e py print(()==() if True is not True else True is not True);_:__import__('typing').Callable[[str],str] = lambda m=None: True if m is False else False; print(list(map(lambda __m__: __m__.lower(), str((__:=(_,))[0](True if (___:=lambda e=None: _())() else (_)==(_)==[_])))))

night quarryBOT
#

@turbid dragon :white_check_mark: Your eval job has completed with return code 0.

001 | False
002 | ['t', 'r', 'u', 'e']
turbid dragon
#

how can I make it not print that first false

#

so it looks like it should

#

but it doesnt

rapid sparrow
#

now I'm annoyed I can't seem to reproduce this here

rapid sparrow
#

then it won't show anything, if that's what you're asking

turbid dragon
#

eh it makes a newline

sick hound
#

hmm

rapid sparrow
#

take out the first print call?

#

!e

_:__import__('typing').Callable[[str],str] = lambda m=None: True if m is False else False; print(list(map(lambda __m__: __m__.lower(), str((__:=(_,))[0](True if (___:=lambda e=None: _())() else (_)==(_)==[_])))))โ€Š
night quarryBOT
#

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

['t', 'r', 'u', 'e']
rapid sparrow
#

oh you wanted it to look like you were printing

rapid sparrow
# turbid dragon eh it makes a newline

!e
what about this ?

print(()==() if True is not True else True is not True or '', end='');_:__import__('typing').Callable[[str],str] = lambda m=None: True if m is False else False; print(list(map(lambda __m__: __m__.lower(), str((__:=(_,))[0](True if (___:=lambda e=None: _())() else (_)==(_)==[_])))))
night quarryBOT
#

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

['t', 'r', 'u', 'e']
turbid dragon
#

is there something like ()==() which returns None

#

actually nvm ill make it

#

why is this

#

!e py print((___():=lambda: None)==___() if True is True else True is not True);_:__import__('typing').Callable[[str],str] = lambda m=None: True if m is False else False; print(list(map(lambda __m__: __m__.lower(), str((__:=(_,))[0](True if (___:=lambda e=None: _())() else (_)==(_)==[_])))))

#

ohh

#

same name

#

im dmnb

#

fuck

#

its all gone to shit now

#

!e py print((__0__:=lambda: None)==__0__ if True is True else True is not True);_:__import__('typing').Callable[[str],str] = lambda m=None: True if m is False else False; print(list(map(lambda __m__: __m__.lower(), str((__:=(_,))[0](True if (___:=lambda e=None: _())() else (_)==(_)==[_])))))

night quarryBOT
#

@turbid dragon :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | ['t', 'r', 'u', 'e']
turbid dragon
#

o

rapid sparrow
#

().__init__(())

#

().__init__()

turbid dragon
#

hmm

sick hound
#

print(repr(print()))

rapid sparrow
#

here's another

#

!e

print(f'{exec("_:().__class__.__dict__[dir(())[7]]((), ())")=}')
night quarryBOT
#

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

exec("_:().__class__.__dict__[dir(())[7]]((), ())")=None
sick hound
#

hmmmm i has idea

sick hound
turbid dragon
#

!e py print(str((__0__:=lambda: None)==((_0:=1),)).replace('False', '') if True is True else True is True, end='');_:__import__('typing').Callable[[str],str] = lambda m=None: True if m is False else False; print.__call__(bool(''.join(list(map(lambda __m__: __m__.lower(), str((__:=(_,))[0](True if (___:=lambda e=None: _())() else (_)==(_)==[_])))))))

night quarryBOT
#

@turbid dragon :white_check_mark: Your eval job has completed with return code 0.

True
sick hound
#

create a program that outputs a program which also outputs a program which is slightly different to the first program but functionally the same. how many times it outputs a program before the first repetition or it breaks is your score. 100 characters only.

#

!e ```py
print(()==())

night quarryBOT
#

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

True
sick hound
#

!e ```py
print(()==())

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name '_' is not defined
rapid sparrow
#

more arbitrary restrictions:
>>> print(f"{((o):=(0), (0),(o))=}") File "<stdin>", line 1 (((o):=(0), (0),(o))) ^ SyntaxError: f-string: cannot use assignment expressions with name

rapid sparrow
#

a meta-meta-meta-programming exercise

#

the output has to change?

rapid sparrow
#

!e

s=""; eval(s:='print("s=eval(%r)"%s)',{"s":s})
night quarryBOT
#

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

s=eval('print("s=eval(%r)"%s)')
rapid sparrow
#

!e

s=eval('print("s=eval(%r)"%s)')
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 |   File "<string>", line 1, in <module>
004 | NameError: name 's' is not defined
rapid sparrow
#

ff

fleet bridge
# sick hound create a program that outputs a program which also outputs a program which is sl...

i=0;_='i=%r;_=%r;print(_%%(i+1,_));i=...;_=...';print(_%(i+1,_));i=...;_=...
it prints this:
i=1;_='i=%r;_=%r;print(_%%(i+1,_));i=...;_=...';print(_%(i+1,_));i=...;_=...
which prints this:
i=2;_='i=%r;_=%r;print(_%%(i+1,_));i=...;_=...';print(_%(i+1,_));i=...;_=...
and so on...

it never repeats, functionality is same (it prints some program and sets all used vars to ... at the end)
it reaches 100 characters after ~10^23 iterations (program is 77 characters long)

maiden river
turbid dragon
#

().__init__()

fleet bridge
#

().__class__.__base__.__subclasses__()[76]()

#

!e
print(().__class__.__base__.__subclasses__()[76]())

night quarryBOT
#

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

None
maiden river
#

but isnt there anything without alphabets

#

i remember [] empty lists or something returned None

fleet bridge
#

[].__hash__ - also returns None

maiden river
fleet bridge
#

because it doesnt make sense

#

!e

a = "hello bro"
s = a.split
print(s())
night quarryBOT
#

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

['hello', 'bro']
maiden river
#

!e this too does not

str.s = str.split
a = "helo helo"
print(s(a))
print(a.s())
night quarryBOT
#

@maiden river :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: cannot set 's' attribute of immutable type 'str'
fleet bridge
#

when you do a.b b isnt variable, it is just name, which is look-uped in object dictionary

fleet bridge
#

!e

from fishhook import hook
@hook(str)
def s(self) -> str:
    return self.split()

print("a b c".s())
night quarryBOT
#

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

['a', 'b', 'c']
maiden river
#

!e perhaps

s = lambda n:n.split()
a = 'helo helo helo'
print(s(a))
maiden river
#

oh, this aint in std lib

fleet bridge
sick hound
#

however, won't I eventually reach an overflow?

sick hound
fleet bridge
#

!e
2**1000

night quarryBOT
#

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

[No output]
sick hound
#

it might take thousands of years

fleet bridge
sick hound
#

ok

fleet bridge
#

but it will reach 100 characters in far future

sick hound
#

yeah it will

#

eventually it will break

#

after an unknowable amount of time

maiden river
#

!e

O=(()==())+(()==())+(()==());o=O*O;o=o*(o-(()==()));O=O+(()==())+(()==());Q=O*((()==())+(()==()));Q=((Q))*((Q));print(chr(o)+chr(O+Q))
night quarryBOT
#

@maiden river :white_check_mark: Your eval job has completed with return code 0.

Hi
maiden river
#

!e

_=(()==())+(()==())+(()==());__=_*_;__=__*(__-(()==()));_=_+(()==())+(()==());___=_*((()==())+(()==()));___=((___))*((___));print(chr(__)+chr(_+___))
night quarryBOT
#

@maiden river :white_check_mark: Your eval job has completed with return code 0.

Hi
maiden river
#

Golf Challenge:
write Hi using least number of ()+-*/_=; Oo and maybe print() and chr() at the end
No 0123... etc allowed

long fulcrum
sick hound
#

this channel has now reached a point where (()==()) is so overused where people would be more confused if you just wrote 1 lol

fleet bridge
#

!e
print(end='Hi')

night quarryBOT
#

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

Hi
fleet bridge
#

done

sick hound
#

I can do it better

dark wharf
#

forbidden technology

#

get it away from me

sick hound
#

I'm sorry

dark wharf
#

my eyes are saved

unique rose
#

!e

print(**{ list(vars(str).values())[24](str(), map(chr, [10**2 + i for i in [10**0, 10**1, 0]])) : 'hi' })
sick hound
#
print([eval("(chr(ord(___)))") for ___ in "hi"][(ord(รˆ)//100)-all(().__init__.())][(ord(รˆ)//200)])

this doesn't work

unique rose
#

!e print(**{ list(vars(str).values())[24](str(), map(chr, [10**2 + i for i in [10**0, 10**1, 0]])) : 'hi' })

night quarryBOT
#

@unique rose :white_check_mark: Your eval job has completed with return code 0.

hi
sick hound
#

if someone could fix it that'd be welcome

#

night chat

#

night chat on your time zone

#

oh lol

#

but yeah goodvye

unique rose
#

!e print(**{ list(vars(str).values())[ord('0')//2]( str(), map(list(vars(__builtins__).values())[ord('*')//3], [int(10**2 + 10**i) for i in [0, 1, -1]]) ) : 'hi' })

night quarryBOT
#

@unique rose :white_check_mark: Your eval job has completed with return code 0.

hi
unique rose
#

i'll probably stop here,

#

!e print(**{ list(vars(str).values())[10**2 * ord('10**2'[2**1])//(10**2 + 75)]( str(), map( list(vars(__builtins__).values())[ord('10**2'[2**1])//3], map(type(10**2), [10**2 + 10**i for i in [False, True, True/-1]]) ) ) : 'hi' })

night quarryBOT
#

@unique rose :white_check_mark: Your eval job has completed with return code 0.

hi
turbid dragon
#

!e py print(str((__0__:=lambda: None)==((_0:=1),)).replace('False', '') if True is True else True is True, end='');_:__import__('typing').Callable[[str],str] = lambda m=None: True if m is False else False; print.__call__(bool(''.join(list(map(lambda __m__: __m__.lower(), str((__:=(_,))[0](True if (___:=lambda e=None: _())() else (_)==(_)==[_])))))))

night quarryBOT
#

@turbid dragon :white_check_mark: Your eval job has completed with return code 0.

True
boreal slate
#

!e

a = "ABCDEFGHI"
b = "ABCDEFGH"
dimension = 0
per_dimension = 0

for word in (a, b):
  l = len(word)
  for d in 1,2,3:
    (x := round(l**(1/d)))** d-l or (dimension:=d, per_dimension:=x)

  print(word, dimension, per_dimension)
night quarryBOT
#

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

001 | ABCDEFGHI 2 3
002 | ABCDEFGH 3 2
boreal slate
#

interesting way to use or :D

night quarryBOT
#

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

3
coral kernel
#

hello crazy people

#

i need a crazy solution for a seemingly simple question

#
def f():
   def g():
       print("foo")

>>> f.g
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
AttributeError: 'function' object has no attribute 'g'
#

what's the best approach to programmatically decorate g?

#

in #advanced-discussion eh.. #internals-and-peps we only could come up with broad-stroke solutions like "manipulate source code", "manipulate ast" or "manipulate bytecode"

#

maybe you know a working solution to this problem?

rugged sparrow
#

@coral kernel you could replace the code object in the consts of f

#

Ie from outside you construct g, wrap it, then reinject the resulting code obj

bleak ermine
coral kernel
rugged sparrow
#

@coral kernel ill write poc in a bit

sick hound
#

yo bro

#

what is esoteric python hahah

coral kernel
#

code that purposefully ignores the zen of python and often is as convoluted as possible to make it as unreadable as possible

#

code that pushes the boundaries of what people thought possible in python

rugged sparrow
#

@coral kernel this is a bit tricky because of variable scoping actually

unique rose
#

!e

print(**{ 
    list(vars(str).values())[10**2 * ord('10**2'[2**1])//(10**2 + 75)](
        str(), 
        map(
            list(vars(__builtins__).values())[ord('10**2'[2**1])//3],
                map(type(10**2), [10**2 + 10**i for i in [False, True, True/-1]])
        )
    ) : 'esoteric' 
})
night quarryBOT
#

@unique rose :white_check_mark: Your eval job has completed with return code 0.

esoteric
turbid dragon
#

!e py print(str((__0__:=lambda: None)==((_0:=1),)).replace('False', '') if True is True else True is True, end='');_:__import__('typing').Callable[[str],str] = lambda m=None: True if m is False else False; print.__call__(bool(''.join(list(map(lambda __m__: __m__.lower(), str((__:=(_,))[0](True if (___:=lambda e=None: _())() else (_)==(_)==[_])))))))

night quarryBOT
#

@turbid dragon :white_check_mark: Your eval job has completed with return code 0.

True
sharp spruce
#

every time I pop in this channel I lose a bit of sanity trying to read the code

#

great job

rapid sparrow
#

serenity now ... insanity later

restive void
rapid sparrow
#

is there a reason it wouldn't be possible to add a dunder to ModuleType

restive void
#

show

#

awesome

#

But you had to change the bytecode, I was hoping it was possible without that

golden finch
#

!e

@lambda f:type('',(),{'':f.__code__.co_consts,'__getattribute__':lambda self,name:type(lambda:0)([i for i in object.__getattribute__(self,'')if hasattr(i,'co_name') and i.co_name==name][0],globals())})()
def f():
   def g():
       print("foo")

print(f.g)
night quarryBOT
#

@golden finch :white_check_mark: Your eval job has completed with return code 0.

<function g at 0x7f390c757d90>
golden finch
#

@coral kernel hail satan, I guess

#

I must have misunderstood then

#

Does it mean you can access the function's internal namespace via attribute access?

#

What do you mean by "programattically decorate"?

#

so you go like

def f(x):
  @dec
  def g(x):
    print('foo')
```?
#

so what would that look like?

coral kernel
golden finch
#

oh that's hard

coral kernel
#

f.g = dec(f.g) more like

coral kernel
rapid sparrow
#

it would be much nicer if the functions themselves were in the code object

#

is it basically loading the nested function as a piece of code and saying "jump here"?

#

MAKE_FUNCTION ? too bad the opcodes aren't implemented in python

#

boost::python has a function for it -- make_function .. could use boost.python and pass the nested function as a callback using ctypes

#

it would make the code less portable, though, and who knows where the arguments would go

#

we just want the opposite of PyGunction_GetCode

#

the way it is done in C is using:

PyFunctionObject *func = _PyFunction_FromConstructor(&constr);
``` where constr has some values like `fc_code = _co, fc_defaults = defaults` etc. in ceval.c
#

that's MAKE_FUNCTION

coral kernel
#

@sick hound i just tried your code snippet you linked - it looks like a demonic invocation ๐Ÿ˜„

#

but it kind of works, really nice!

#

guess we have a POC we can build on

quick basalt
#

Can anyone explain this?

print(1_1_1 + 2_2_2)

333

#

Of course, now I remember:

200_000

coral kernel
#

yeah, but it's not limited to a fixed number of digits

quick basalt
#

I doubt this is used, much

coral kernel
#

it definitely is

#

i use it all the time if i have any big enough number, which is.. all the time

quick basalt
#

OK, ๐Ÿ™‚ I'm not questioning your aesthetics. @coral kernel (I definitely am ๐Ÿ™‚ )

coral kernel
#

it's not a question of aesthetics, it's safer

#

it's easy to miscount if you have numbers in the billions

quick basalt
#

I see that's true.
I've rarely had a reason to work with hard-coded magic values - the need has never occurred to me.

coral kernel
#

try slicing into GB of numpy arrays or work with neural networks, where numbers quickly add up

quick basalt
#

Yes, I can see that it can be useful.
Just... 1_11111_111_1_0 is valid too.

coral kernel
quick basalt
#

Well, other locales use different thousands separators (I recall Indian currency being really odd) so hardcoding would have been very odd.

coral kernel
#

true

rapid sparrow
#

so nested functions can be type hinted... but nobody outside the function would have access to see the hints

#

i mean in source code, sure

#

but from an API perspective, no

coral kernel
#

inner beauty bla blah

rapid sparrow
#

haha

#

challenge accepted

sick hound
#

I did a stupid thing but thought it looked cool

#
__main__ = {
  1 : lambda x : x+1, # your function code here
  2 : lambda x : x+2, # other function code stuff
}
exec(f"{__name__}[1]({x})"); # call the first function```
#

I thought it might make defining functions more fun and maybe will help so you don't have to call different ones every time

#

I do think it's stupid but it looks cool to me

fleet bridge
#

what is __text_signature__?

#

it isnt documented

#

!e
print(sorted.__text_signature__)

night quarryBOT
#

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

($module, iterable, /, *, key=None, reverse=False)
night quarryBOT
#

@maiden river :white_check_mark: Your eval job has completed with return code 0.

[1, 1]
fleet bridge
#

!e

from typing import Protocol

class P(Protocol):
    pass

class X(P):
    pass

Y = type('Y', (P,), {})

print(X)
print(Y)
night quarryBOT
#

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

001 | <class '__main__.X'>
002 | <class 'abc.Y'>
fleet bridge
#

why modules are different?

maiden river
#

!e

a = [[1,2,3],[4,5,6]]
indx = [1,1]

print(a[indx[0]][indx[1]])
night quarryBOT
#

@maiden river :white_check_mark: Your eval job has completed with return code 0.

5
maiden river
#

can we somehow do
a[indx]
instead of
a[indx[0]][indx[1]]

maiden river
#

!e So I built coords finder for 2D and 3D matrices using list comps, Next Step - generalize for nD matrices

g2 = [[7,8,9],
      [4,5,6],
      [1,2,3]]

pos = lambda n,grid:[[grid.index(y),y.index(n)] for y in grid if n in y][0]
print(pos(5,g2))

g3 =[
    [ 
    [1, 2, 3], 
    [4, 5, 6], 
    [7, 8, 9]],
    [
    [11, 22, 33], 
    [44, 55, 66], 
    [77, 88, 99]],
    [
    [111, 222, 333], 
    [444, 555, 666], 
    [777, 888, 999]]]

pos3d = lambda n,grid:[[[[grid.index(z),z.index(y),y.index(x)] for x in y if x==n] for y in z] for z in g3]
print(pos3d(5,g3))
night quarryBOT
#

@maiden river :white_check_mark: Your eval job has completed with return code 0.

001 | [1, 1]
002 | [0, 1, 1]
maiden river
#

turns out it wasn't so simple

#

!e The Ultimate 3D Matrix Indexer - feat. @warm void

g = [
    [ 
    [1, 2, 3], 
    [4, 5, 6], 
    [7, 8, 9]],
    [
    [11, 22, 33], 
    [44, 55, 66], 
    [77, 88, 99]],
    [
    [111, 222, 333], 
    [444, 555, 666], 
    [777, 888, 999]]]

pos = lambda n,grid:[[[[grid.index(z),z.index(y),y.index(x)] for x in y if x==n and [grid.index(z),z.index(y),y.index(x)] != []] for y in z if [[grid.index(z),z.index(y),y.index(x)] for x in y if x==n and [grid.index(z),z.index(y),y.index(x)] != []] != []] for z in g if [[[grid.index(z),z.index(y),y.index(x)] for x in y if x==n and [grid.index(z),z.index(y),y.index(x)] != []] for y in z if [[grid.index(z),z.index(y),y.index(x)] for x in y if x==n and [grid.index(z),z.index(y),y.index(x)] != []] != []] != []][0][0][0]

print(pos(55,g))
night quarryBOT
#

@maiden river :white_check_mark: Your eval job has completed with return code 0.

[1, 1, 1]
warm void
#

:)

vague cairn
#

I am impressed! Nicely done!

carmine sun
sick hound
#

uh

#

@sick hound ๐Ÿ™‚

#

il show you some stuff here

#

ohhhhhhh

night quarryBOT
#

failmail :ok_hand: applied mute to @sick hound until <t:1638377530:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

sick hound
#

@sick hound```py
(
builtins
.import('sys')
._getframe(0)
.f_globals
.setitem(
"define_variable",
builtins
.import('sys')
._getframe(0)
.f_globals
.setitem
)
)
(
builtins
.import('sys')
._getframe(0)
.f_globals
.setitem(
"operations",
import('operator')
)
)
define_variable('x', 1)
define_variable('y', 2)
print(operations.add(x, y))

#

yeah thats our thing xd

#

that was fun

#

xD

sick hound
#

it returns false keyword

#

!e py ___=((([]==[]))+(([]==[])));__=(___)*((([]==[]))+(([]==[])))**___//___ ____=(__)**___;((____+___)**__)//___;_______________________=(((__))+(__))**((([]==[]))+(([]==[])))+(([]==[]))\ +(([]==[]))+(([]==[]))+(([]==[]));_____________=((___)) ((_______))=(([]==[]))+(___);((_______))=((_______))+_____________ ((______)) = chr((((___)))*((((__))))**(__)+(__)//((___))) for ___ in range(__): if ((_______)) !=[(([]==[]))-(___)]: print((__)+(((___)))//(____)-((___))+((___)**(___)**((_______)))) (_________________)=(__)+(((___)))//(____)-((___))+((___)**(___)**((_______))) (_________________) = ((((((((((((((_________________))))))))))))))+_______ print((_________________),~_______________________)

night quarryBOT
#

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

001 | 5
002 | 10 -69
003 | 4
004 | 9 -69
005 | 4294967298
006 | 4294967303 -69
007 | 87189642485960958202911070585860771696964072404731750085525219437990967093723439943475549906831683116791055225665628
008 | 87189642485960958202911070585860771696964072404731750085525219437990967093723439943475549906831683116791055225665633 -69
sick hound
#

fun

#

this is a really nice one cheeki made based off my code

#

!e ```py
print((lambda self=[:=((([]==[]))+(([]==[]))) ,
:=(
)*((([]==[]))+(([]==[])))**
//__ , :=()** ,
_____:=((())+())**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
________:=(()) , :=(()) , :=(([]==[]))+() , :=(())+ ,
______ := chr((((
)))*((((
))))**(
)+(
)//((
))) , [[((
)+(((
)))//(
)-(())+(()**()**(()))) ,
____________:=()+((()))//(
)-((
))+(()**()**(())) ,
_________________ := ((((((((((((((_________________))))))))))))))+
__ , ((),~____)]
for ___ in range(
) if ((_)) !=[(([]==[]))-()]]][]: eval(type(None).bool.doc))())

import fishhook
@fishhook.hook(int)
def repr(self):
stuff = {v: k for k,v in globals().items() if isinstance(v,int)} | {1:'false_()'}

x = self
nums = []
for elem in sorted(stuff.keys(),reverse=True):
    while x>=elem:
        nums.append(stuff[elem])
        x-=elem

return float(self).__str__() +' = '+ '+'.join(nums)

print(fr'{69}')```

night quarryBOT
#

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

001 | True
002 | 69.0 = _______________________+false_()
sick hound
#

it turns any number into my special underscore morse code

#

you could with strings aswell but we dont have it implemented

fleet bridge
#

what happens if i press Ctrl+S in python REPL?

sick hound
#

i need to open a file without using the letter e

#

how?

sick hound
next flame
sick hound
#

wdym

snow beacon
# sick hound wdym

globals()[...] converts a string to a value that has its name, like "open" to open. chr(...) converts a number to a string with that codepoint, like "e".

sick hound
#

ah

snow beacon
#

You could also import and use pathlib.Path.

#

There might be other options in the sys module.

next flame
#

you might need to use __builtins__ instead of globals, idr which and can't check rn

sick hound
#
#for count, v in enumerate(__builtins__):
#    print(f"{count} | {v}")

builtins = [n for n in __builtins__] 
input=__builtins__[builtins[146]]("input.txt") #This is slightly illicit, but still works

this is what i got

#

bit complicated honestly

#

but i like how its still pythonic

next flame
sick hound
#

exactly

prisma coral
sick hound
#

i could've indeed done that

snow beacon
next flame
viscid nymph
#
#encoding:unicode-escape
with op\u0065n("input.txt") as f:
   ...
earnest wing
#

I see three [necessary]ย e-s there

viscid nymph
#

oh yeah, my bad

turbid dragon
#

!e ```py
import datetime as dt

class datetime(dt):
def init(self):
self.datetime = self
print(datetime().datetime().datetime())```

night quarryBOT
#

@turbid dragon :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | TypeError: module() takes at most 2 arguments (3 given)
turbid dragon
#

how do i make this infinitely loop

#

as in

#

i can keep .datetime()ing

unique rose
#

just return self from __getattribute__

#

aprox, ```py
class me: getattribute = lambda s: s

me().me.me.me.me.me.me

turbid dragon
#

i tried dt.datetime but it kept asking me for arguments even though i was subclassing datetime

vague cairn
night quarryBOT
#

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

<class '__main__.datetime'>
turbid dragon
#

hm

unique rose
#

!e ```py
class t: init = print
class inheritValue(t()): ...

night quarryBOT
#

@unique rose :white_check_mark: Your eval job has completed with return code 0.

001 | 
002 | inheritValue (<__main__.t object at 0x7fe12ada7b50>,) {'__module__': '__main__', '__qualname__': 'inheritValue'}
unique rose
#

you can inherit from values if the initializer of their type handles ^ properly

#

this "feels useful", possibly if there was a function to make it work, ie., class inheritValue(makeitwork(5))

vague cairn
sick hound
#

huh

unique rose
#

!e

def lift(v):
    class LiftValue(type(v)):
        def __init__(self, *args):
            self = v
        

    return LiftValue

class MyInt(lift(5)): ...

print(MyInt())
vague cairn
#
builtins = [n for n in __builtins__.__dict__]
input=__builtins__.__dict__[builtins[146]]("input.txt")
``` This does however.
#

and through the outcome is hilarious, I'm not sure that the index is the same one that was intended.

sick hound
#

huh

vague cairn
#
builtins = [n for n in __builtins__.__dict__]
input=__builtins__.__dict__[builtins[145]]("input.txt")
#I'm annoyed that this transformation only saves one character:
input=getattr(__builtins__,builtins[145])("input.txt")
sick hound
#

have you got inputs.txt

vague cairn
#

I haven't that wasn't the problem, the problem is that 146 refers to quit() on my python (3.8), 145 gives the Error #2 that one expects for missing files.

sick hound
#

oh

#

run the top part of the code I sent

#

and find the part that has open on the output

#

modify it so it's the same as your additions

#

and use the index for open() as the number

#

might work idk

vague cairn
#

I did, after doctoring it to refer to __builtins__.__dict__ that's how I got 145 to replace 146.

#

etc

sick hound
#

ah ok

vague cairn
#

Nothing wrong with your code, just, you know, wrong python, but I got the gist and explained to my python what you had meant.

#

๐Ÿ™‚

#

Yes, well.

#

What? Line 2 worked on the previous go round?

snow beacon
vague cairn
#

!e

b = list(__builtins__.__dict__)
print(b[145:])
input=getattr(__builtins__, b[149])("input.txt")
print(input.read())
#

wow

#

!e

b = list(__builtins__.__dict__)
input=getattr(__builtins__, b[148])("input.txt")
print(input.read())
night quarryBOT
#

@vague cairn :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | FileNotFoundError: [Errno 2] No such file or directory: 'input.txt'
vague cairn
#

That's better.

drifting oar
#

!e

def _(*a, **kw):
  'takes args but does nothing and returns nothing'

multiline_lambda = lambda: (
  _(a := 5),
  _(b := 6),
  (a + b)
)[-1]

print(multiline_lambda())
night quarryBOT
#

@drifting oar :white_check_mark: Your eval job has completed with return code 0.

11
restive void
#

!e

multiline_lambda = lambda _=(lambda*a,**k:0): (
    _(a := 5),
    _(b := 6),
    a + b,
)[-1]

print(multiline_lambda())
night quarryBOT
#

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

11
drifting oar
#

better

restive void
#

Could even introduce some control flow:

#

!e

multiline_lambda = lambda _=(lambda*a,**k:0),If=(lambda x:(lambda y:(lambda z: y if x else z))): (
    _(a := 5),
    _(b := 6),
    If(a + b == 12)(
        "a + b is 12"
    )(
        "a + b isn't 12"
    )
)[-1]

print(multiline_lambda())
night quarryBOT
#

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

a + b isn't 12
restive void
#

Got While working as well, but you can't modify variables from before the while (because nonlocal doesn't work in lambdas)..

rugged sparrow
#

why the _=lambda *a, **k:0? you can just to (a := 5)

restive void
#

True

#

!e

# doesn't like being defined as a argument of the lambda:
While = lambda c: lambda b: (b(),While(c)(b))[-1] if c() else 0
multiline_lambda = lambda time=__import__("time"), If=(lambda x:(lambda y:(lambda z: y if x else z))): (
    t0 := time.time(),
    While(lambda: time.time() < t0 + 5)(lambda:(
        print("time is", time.time()),
        time.sleep(1),
    )),
)[-1]
multiline_lambda()
night quarryBOT
#

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

001 | time is 1638403270.4303958
002 | time is 1638403271.434814
003 | time is 1638403272.438414
004 | time is 1638403273.4424503
005 | time is 1638403274.4464326
cerulean rivet
#

how?

vague cairn
#

For = lambda s: lambda B: [B(i) for i in s]

#

seems like there should be a more lambda way to do that.

#

Ok, at that point could just be:
For = lambda s: lambda B: list(map(B, s))

#

which is a good point, map can be defined in terms of reduce, and I think I've seen reduce defined in terms of lambda... hmmm

#

But it was in a language with car, cons, and pEmpty so ...

#

!e

ReduceL = lambda k, s, i: ReduceL(k, s, k(i, s.pop(0))) if s else 0
Reduce = lambda k, s, i=0: ReduceL(k, list(s), i)

Map = lambda k, s: ReduceL(lambda init,item: (init.append(k(item)), init)[-1], list(s), list())

For = lambda s: lambda k: Map(k, s)
For(range(10))(lambda i: print(i))
night quarryBOT
#

@vague cairn :white_check_mark: Your eval job has completed with return code 0.

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
vague cairn
#

!e

import sys
class J(Exception):
    def __init__(self,*fak): self.fak=fak
def T(f, *a, **k):
    while 1:
        try:
            return f(*a, **k)
        except J as e:
            f,a,k = e.fak
def TCE(g):
    def ST(*a, **k):
        fb = sys._getframe(1)
        
        while fb:
            if fb.f_code == T.__code__: raise J(g,a,k)
            elif (fb.f_code.co_code[(ti := fb.f_lasti + 2) :ti+2]) != b'S\x00':
                return T(g, *a, *k)
            fb = fb.f_back
        return T(g, *a, *k)
    ST.__doc__ = g.__doc__
    return ST

ReduceL = lambda k, s, i: ReduceL(k, s, k(i, s.pop(0))) if s else 0
ReduceL = TCE(ReduceL)
Reduce = lambda k, s, i=0: ReduceL(k, list(s), i)

Map = lambda k, s: ReduceL(lambda init,item: (init.append(k(item)), init)[-1], list(s), list())

For = lambda s: lambda k: Map(k, s)
For(range(2000))(
    lambda i: print(i) if i % 500 == 0 else 0
)
night quarryBOT
#

@vague cairn :white_check_mark: Your eval job has completed with return code 0.

001 | 0
002 | 500
003 | 1000
004 | 1500
sick hound
#

@uncut folio (sry for ping)

(
    __builtins__
    .__import__('sys')
    ._getframe(0)
    .f_globals
    .__setitem__(
        "define_variable",
        __builtins__
        .__import__('sys')
        ._getframe(0)
        .f_globals
        .__setitem__
    )
)
(
    __builtins__
    .__import__('sys')
    ._getframe(0)
    .f_globals
    .__setitem__(
        "operations",
        __import__('operator')
    )
)
define_variable('x', 1)
define_variable('y', 2)
print(operations.add(x, y))

Since you hate functions, do this instead lol

sick hound
#

Python ๐Ÿ™‚

uncut folio
#

ima be honest, i dont even know what esoteric is AHHHHHHH

sick hound
rapid sparrow
#

it may as well be undefined

sick hound
#

i have alot more to show

#

: )

#

one of the things i really want to do is make a longass esoteric underscore language translator

#

based of cheekis code

#

!e ```py
print((lambda self=[:=((([]==[]))+(([]==[]))) ,
:=(
)*((([]==[]))+(([]==[])))**
//__ , :=()** ,
_____:=((())+())**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
________:=(()) , :=(()) , :=(([]==[]))+() , :=(())+ ,
______ := chr((((
)))*((((
))))**(
)+(
)//((
))) , [[((
)+(((
)))//(
)-(())+(()**()**(()))) ,
____________:=()+((()))//(
)-((
))+(()**()**(())) ,
_________________ := ((((((((((((((_________________))))))))))))))+
__ , ((),~____)]
for ___ in range(
) if (()) !=[(([]==[]))-()]]][]: eval(type(None).bool.doc))())
import fishhook
@fishhook.hook(int)
def repr(self):
stuff = {v: k for k,v in globals().items() if isinstance(v,int)} | {1:'
()()'}

x = self
nums = []
for elem in sorted(stuff.keys(),reverse=True):
    while x>=elem:
        nums.append(stuff[elem])
        x-=elem

return float(self).__str__() +' = '+ '+'.join(nums)

print(fr'{69}')```

night quarryBOT
#

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

001 | True
002 | 69.0 = _______________________+_()_()_
sick hound
#

this is the underscore variable that was made which is 68 and then _()_()_ which is assigned to 1 in the __repr__ function

#

!e ```py
print((lambda self=[:=((([]==[]))+(([]==[]))) ,
:=(
)*((([]==[]))+(([]==[])))**
//__ , :=()** ,
_____:=((())+())**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
________:=(()) , :=(()) , :=(([]==[]))+() , :=(())+ ,
______ := chr((((
)))*((((
))))**(
)+(
)//((
))) , [[((
)+(((
)))//(
)-(())+(()**()**(()))) ,
____________:=()+((()))//(
)-((
))+(()**()**(())) ,
_________________ := ((((((((((((((_________________))))))))))))))+
__ , ((),~____)]
for ___ in range(
) if ((_)) !=[(([]==[]))-()]]][]: eval(type(None).bool.doc))())

import fishhook
@fishhook.hook(int)
def repr(self):
stuff = {v: k for k,v in globals().items() if isinstance(v,int)} | {1:'false_()'}

x = self
nums = []
for elem in sorted(stuff.keys(),reverse=True):
    while x>=elem:
        nums.append(stuff[elem])
        x-=elem

return float(self).__str__() +' = '+ '+'.join(nums)

print(fr'{hi}')```

night quarryBOT
#

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

001 | True
002 | Traceback (most recent call last):
003 |   File "<string>", line 26, in <module>
004 | NameError: name 'hi' is not defined
sick hound
#

as you can see string doesnt work

#

sadly, id like to change that soon

uncut folio
sick hound
#

you learn alot here

uncut folio
#

lemme learn the basics first ๐Ÿคง

sick hound
#

if i wasnt doing other stuff id be working on the underscore translator and also be making an import module to make some even more fun things here

#

yeah once you learn slightly above intermediates then coming here to learn is something you wont regret

uncut folio
sick hound
#

i mean half the stuff you see here regardless of your skill level will be like "what the hell is this shit" and then you look at it properly and ur like oh i get this

earnest wing
#

here's a fun thing:

#

Input image

#

that converts to valid python

โฏ python3 -m unibitmap --width 20 tests/cup.jpeg tests/cup.py
โฏ cat tests/cup.py
# -*- coding: utf-8 -*-
from unibitmap import Bitmap

class MyBitmap(Bitmap):
    ้’Œใ†ณใ„’ใ„†ๅœฆๅนดๅผ…ใ„จๅพ‰ๅฏŠไปœๅ†ๅฏŠๆฐฐๆ†›ๆ‡ฏ่ฝˆ่†—ๆช‚็กฑ
    ็ดใ‚ฆใ„ๅ‡ตๅ…ฎๆ–ฅๅฒขใ„จๆ–ๅœฑใ‚ขใƒ•ใ„คๅฟฃๆฅธ่—ฅ้‡ƒๆฅฌๅžๆฆพ
    ใ„จใƒ’ๅ‡ขใƒฆใƒฆๅœฆไธใƒ…ๅผใ‚Šใ„ใƒšใƒ‹ๅ’”ๆญ ่ฒœๆ‡ฏใฃ”ๅ†ฌๅœธ
    ใ‚ฆใ†ณไบๅˆๅ†ฌไปˆใ„†ๅฎƒๆƒขใ‚ฉใƒ•ใƒถใ…ใ‚‡ใƒŸๅ…ƒๆ…†ๆดๆดๅด
    ๆžฏใƒ…ๅญฆๅงพๅฅŒๅฅทๆณดๆŠ›ๅทฟใƒšใ…ใ—ใ‚ˆใƒƒใ„ใƒ‰ใƒฑๅธ›ๅžถๅคผ
    ๆ ™ๅ†ทไ’‘ใ‚ธใ ชๅณƒๆณใฃ”ใ†บใ„ใ…ใ„šใคใ…ใ‚Žใ‚ˆใ‚คใ‚คไปŽไปœ
    ๅฃฎๅ†ทใƒƒใ†ขไธๅคšๆžˆใ“€ใ‚Žใคใ‚ˆใ“€ใ…ไธฟใ‚‡ใ‚Žใคใ€ณๅ†ซใ…
    ๆฆพๆฟๆ˜”ๆฃ–ๆŠฏๆณถใ„Œใƒ™ไน‰ใฃ”ใ‚ˆใ…ใƒผใƒŽใ†บใ…ใƒ‰ใ†ขๅฎƒใ€ก
    ๆ™„ๆณถๅžๅ†ฌๅคปๅคšใ„จใƒŸใƒใ„’ใ‚ไธฟใ†ณใ†ณใ†ณไ’‘ใ‡ทใƒƒๅคปๅบ’
    ใ‚ˆๅฐคๆฏฎๆ”ฃ็žถๆฏๅพใ„Œใ†ขใ‚ฆใƒ‰ใƒใ„’ใƒƒไ’‘ใƒƒใƒ…ๅˆๅฃ‡่ผ›
    ๆฆฝ็ฐ ็พˆ็พˆ่—ตๆฅฎๅคปๅพ‰ๅ†ฌไบใ„Œใ ชๅ‡ขใ†ขใ ชๅœฆๅบ’ๅผƒๆฅธ็พˆ
    ่ฅบ่ฅบๆปฝๆš”็žถๆ‡ฏใฃ”ๅ…ƒๅ†ฌไธๅพๅฃฎๅˆๅพไบๅ†ทใ„Œใฃ”ๆ˜ๆฅธ
    ็ฐ ๆ•ƒๆฆพ็ฐ ่น’่ ดๅ†ฌใ‚ธใ‚ฆใƒžใ†ขไน‰ใ„‰ใ†ขไน‰ใ„‰ใƒŸใ“€ๅผ—ๆฝ›
    ็€œๅฃ‡ๆ‡ฏ่ฅบ่ˆ่ ดๆญงใ‚ธใƒŸใƒ™ใƒใƒใƒ™ใƒใƒใ‚กใ„’ใฃ”ๅฏŠๆ ”
    ๆฟ็ฐ ่ฅบ่ˆ่ˆ่ ดๆง ใ„†ใƒ’ใƒ‰ใ†บใƒใ†บใ†บใƒ™ใƒใ‚กๅ†ฌๅดๆด
#

that evaluates to the image

#

@uncut folio are you feeling gross yet

#

(yes that is executable ascii* art python)

sick hound
#

ok thats fucking cool

#

@earnest wing question

#

do you know how to install fishhook

#

the import

#

is it just pip install

rapid sparrow
#

it's since been lost, and is now esoteric flotsam and jetsom waiting to be overwritten

rapid sparrow
earnest wing
#

overlapping windows with the terminal being iterm2 running zsh
(i just cropped the pic to look like one thing)

earnest wing
prisma coral
sick hound
#

im gonna make cheekis code also take in strings

#

and it will be a very annoying to crack coded message

#

without having the code

#

the enigma code will be a joke after ive finished

#

@prisma coral could u help me get it

#

ive done pip install fishhook

#

it says its installed

#

but still cant find fishhook as a module

#

any idea why

prisma coral
#

Hmm itโ€™s possible that pip installed it to a different interpreter than the one your IDE uses

#

I donโ€™t have time rn to help debug this, but itโ€™s a common question in the help channels so you should be able to find an answer if you ask there

sick hound
#

ok then thanks

rugged sparrow
#

@sick hound try pip3 install fishhook

#

or python3 -m pip install fishhook (or if on windows: py -3 -m pip install fishhook)

sick hound
#

dont worry it worked

#

i did python3.10 -m pip install fishhook

#

pretty nice import you made

#

how hard is it to make one and get it on pypi btw @rugged sparrow

rugged sparrow
#

not hard at all, just a bit of setup

sick hound
#

i want to make one for my esoteric purposes

#

do you a link to something that guides you through it?

#

like a website or video

rugged sparrow
#

if you google adding a packaged to pypi youll find a bunch of stuff

restive void
#

Nowadays the easiest way IMO is poetry

sick hound
#

whats that

restive void
sick hound
#

thank you

#

i will make some very confusing arithmatic bullshit with it

#

and import it for some fun

sick hound
#

here is mah code

#
print((lambda self=[___:=((([]==[]))+(([]==[]))) , 
__:=(___)*((([]==[]))+(([]==[])))**___//___ , ____:=(__)**___ , 
_______________________:=(((__))+(__))**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) , 
_____________:=((___)) , _____________:=((___)) , _______:=(([]==[]))+(___) , _______:=((_______))+_____________ , 
______ := chr((((___)))*((((__))))**(__)+(__)//((___))) , [[((__)+(((___)))//(____)-((___))+((___)**(___)**((_______)))) , 
_________________:=(__)+(((___)))//(____)-((___))+((___)**(___)**((_______))) , 
_________________ := ((((((((((((((_________________))))))))))))))+_______ , ((_________________),~_______________________)]\
for ___ in range(__) if ((_______)) !=[(([]==[]))-(___)]]][___]: eval(type(None).__bool__.__doc__))())
import fishhook
@fishhook.hook(int)
def __repr__(self):
    stuff = {v: k for k,v in globals().items() if isinstance(v,int)} | {1:'(()'} 
    x = self
    nums = []
    for elem in sorted(stuff.keys(),reverse=True):
        while x>=elem:
            nums.append(stuff[elem])
            x-=elem

    for _ in [1]:
        sstring = 'message'
        slist = []
        slist.append(sstring)
        x = 0
        for i in range(len(sstring)):
            print(ord(slist[0][x]))
            x += 1
    return float(self).__str__() +' = '+ '+'.join(nums) ```
#

im trying to make it print the ord() number for each char in 'message'

severe canyon
#

my eyes

#

xD

sick hound
#

then i will use the top part of __repr__ to make those ord numbers into underscore morse code thing

prisma coral
sick hound
#

strangly print worked

#

on its own

#
True
m
e
s
s
a
g
e```
#

is the result

#

i called it by putting it in the code yet it still doesnt print

prisma coral
#

What is the hook supposed to do? Where are you calling the hooked method?

sick hound
#

not sure i supposed .hook is inside the import fishhook @dark wharf made this part of the code

#

the hook part

prisma coral
#

The hook changes what happens when an integer is printed. You never print any integers after you apply the hook, so the function never gets called

dark wharf
#

i just made that for fun, you can easily change it

#

i just wanted to make all integer prints follow the enlightened format

sick hound
#

i was gonna make it work for strings

sick hound
#

the True keyword one

#

i want to put a string inside the list and then turn every character of the string into an ord number then turn those into underscore number

sick hound
#

in the func

#

but i dont call it

#

well now i know what to do

dark wharf
#

theyd have to be done with repr here, otherwies you need to tweak the implementation of fishhook

#

which is what i ended up doing

#

so that it would work for normal prints

sick hound
#
print((lambda self=[___:=((([]==[]))+(([]==[]))) , 
__:=(___)*((([]==[]))+(([]==[])))**___//___ , ____:=(__)**___ , 
_______________________:=(((__))+(__))**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) , 
_____________:=((___)) , _____________:=((___)) , _______:=(([]==[]))+(___) , _______:=((_______))+_____________ , 
______ := chr((((___)))*((((__))))**(__)+(__)//((___))) , [[((__)+(((___)))//(____)-((___))+((___)**(___)**((_______)))) , 
_________________:=(__)+(((___)))//(____)-((___))+((___)**(___)**((_______))) , 
_________________ := ((((((((((((((_________________))))))))))))))+_______ , ((_________________),~_______________________)]\
for ___ in range(__) if ((_______)) !=[(([]==[]))-(___)]]][___]: eval(type(None).__bool__.__doc__))())
import fishhook
@fishhook.hook(int)
def __repr__(self):
    stuff = {v: k for k,v in globals().items() if isinstance(v,int)} | {1:'(()'} 
    x = self
    nums = []
    for elem in sorted(stuff.keys(),reverse=True):
        while x>=elem:
            nums.append(stuff[elem])
            x-=elem
    return float(self).__str__() +' = '+ '+'.join(nums)  


for _ in [1]:
    sstring = 'message'
    slist = []
    slist.append(sstring)
    x = 0
for i in range(len(sstring)):
    print(ord(slist[0][x]))
    x += 1```
#

this doesnt work

#

hang on why do i have the first for loop

#

and now my vscode crashed lovely

dark wharf
#
print((lambda self=[___:=((([]==[]))+(([]==[]))) , 
__:=(___)*((([]==[]))+(([]==[])))**___//___ , ____:=(__)**___ , 
_______________________:=(((__))+(__))**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) , 
_____________:=((___)) , _____________:=((___)) , _______:=(([]==[]))+(___) , _______:=((_______))+_____________ , 
______ := chr((((___)))*((((__))))**(__)+(__)//((___))) , [[((__)+(((___)))//(____)-((___))+((___)**(___)**((_______)))) , 
_________________:=(__)+(((___)))//(____)-((___))+((___)**(___)**((_______))) , 
_________________ := ((((((((((((((_________________))))))))))))))+_______ , ((_________________),~_______________________)]\
for ___ in range(__) if ((_______)) !=[(([]==[]))-(___)]]][___]: eval(type(None).__bool__.__doc__))())
import fishhook
@fishhook.hook(int)
def __str__(self):
    stuff = {v: k for k,v in globals().items() if isinstance(v,int) and k.startswith('_')} | {1:'([]==[])'} 
    x = self
    nums = []
    for elem in sorted(stuff.keys(),reverse=True):
        while x>=elem:
            nums.append(stuff[elem])
            x-=elem
    return self.__repr__() +' = '+ '+'.join(nums)  

print(100)

sstring = 'message'
slist = []
slist.append(sstring)
x = 0
for i in range(len(sstring)):
    print(ord(slist[0][x]))
    x += 1
#

this only works with edited fishhook library tho

#
stuff = {v: k for k,v in globals().items() if isinstance(v,int) and k.startswith('_')} | {1:'([]==[])'}
``` this is the important change
#

because we used to get all the int variables from globals but when you set x=0 it adds a new variable to use with value 0 and thus we get infinite loops

#

so either restrict to the wack underscore variables or maybe change to only use vars that have v>0

sick hound
#

no underscore variables have a value under 0

#

!e ```py
print((lambda self=[:=((([]==[]))+(([]==[]))) ,
:=(
)*((([]==[]))+(([]==[])))**
//__ , :=()** ,
_____:=((())+())**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
________:=(()) , :=(()) , :=(([]==[]))+() , :=(())+ ,
______ := chr((((
)))*((((
))))**(
)+(
)//((
))) , [[((
)+(((
)))//(
)-(())+(()**()**(()))) ,
____________:=()+((()))//(
)-((
))+(()**()**(())) ,
_________________ := ((((((((((((((_________________))))))))))))))+
__ , ((),~____)]
for ___ in range(
) if (()) !=[(([]==[]))-()]]][]: eval(type(None).bool.doc))())
import fishhook
@fishhook.hook(int)
def str(self):
stuff = {v: k for k,v in globals().items() if isinstance(v,int) and k.startswith('
')} | {1:'([]==[])'}
x = self
nums = []
for elem in sorted(stuff.keys(),reverse=True):
while x>=elem:
nums.append(stuff[elem])
x-=elem
return self.repr() +' = '+ '+'.join(nums)

print(100)

sstring = 'message'
slist = []
slist.append(sstring)
x = 0
for i in range(len(sstring)):
print(ord(slist[0][x]))
x += 1```

night quarryBOT
#

@sick hound :x: Your eval job timed out or ran out of memory.

True
sick hound
#

nice

#

!e ```py
print((lambda self=[:=((([]==[]))+(([]==[]))) ,
:=(
)*((([]==[]))+(([]==[])))**
//__ , :=()** ,
_____:=((())+())**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
________:=(()) , :=(()) , :=(([]==[]))+() , :=(())+ ,
______ := chr((((
)))*((((
))))**(
)+(
)//((
))) , [[((
)+(((
)))//(
)-(())+(()**()**(()))) ,
____________:=()+((()))//(
)-((
))+(()**()**(())) ,
_________________ := ((((((((((((((_________________))))))))))))))+
__ , ((),~____)]
for ___ in range(
) if (()) !=[(([]==[]))-()]]][]: eval(type(None).bool.doc))())
import fishhook
@fishhook.hook(int)
def str(self):
stuff = {v: k for k,v in globals().items() if isinstance(v,int) and k.startswith('
')} | {1:'([]==[])'}
x = self
nums = []
for elem in sorted(stuff.keys(),reverse=True):
while x>=elem:
nums.append(stuff[elem])
x-=elem
return self.repr() +' = '+ '+'.join(nums)

print(f'{100}')

sstring = 'message'
slist = []
slist.append(sstring)
x = 0
for i in range(len(sstring)):
print(ord(slist[0][x]))
x += 1```

night quarryBOT
#

@sick hound :x: Your eval job timed out or ran out of memory.

True
sick hound
#

can this code fucking print the underscores

#

!e ```py
print((lambda self=[:=((([]==[]))+(([]==[]))) ,
:=(
)*((([]==[]))+(([]==[])))**
//__ , :=()** ,
_____:=((())+())**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
________:=(()) , :=(()) , :=(([]==[]))+() , :=(())+ ,
______ := chr((((
)))*((((
))))**(
)+(
)//((
))) , [[((
)+(((
)))//(
)-(())+(()**()**(()))) ,
____________:=()+((()))//(
)-((
))+(()**()**(())) ,
_________________ := ((((((((((((((_________________))))))))))))))+
__ , ((),~____)]
for ___ in range(
) if (()) !=[(([]==[]))-()]]][]: eval(type(None).bool.doc))())
import fishhook
@fishhook.hook(int)
def str(self):
stuff = {v: k for k,v in globals().items() if isinstance(v,int) and k.startswith('
')} | {1:'([]==[])'}
x = self
nums = []
for elem in sorted(stuff.keys(),reverse=True):
while x>=elem:
nums.append(stuff[elem])
x-=elem
return self.repr() +' = '+ '+'.join(nums)

print(f'{69}')

sstring = 'message'
slist = []
slist.append(sstring)
x = 0
for i in range(len(sstring)):
print(ord(slist[0][x]))
x += 1```

night quarryBOT
#

@sick hound :x: Your eval job timed out or ran out of memory.

True
sick hound
#

why wont it print the underscores cba

dark wharf
#

because ur using a default version of fishhook

#

where the str method hack doesnt work on ints

#
def itos(n):
    def _itos(n):
        while n:
            yield chr(n % 10 + 48)
            n //= 10
    return ''.join(reversed(list(_itos(n))))
#

and tweak these lines

prisma coral
#

Looks like chilaxan already put the itos in source

#

So you can run

pip install git+https://github.com/chilaxan/fishhook.git

To install the latest version, which should hopefully work

#

@sick hound

sick hound
#

ah so it wont work on bot so its harder to show people

#

well its fine

#

its very epic

#

thanks @prisma coral

#

helpful apple moment

#

i see why ur a helper

prisma coral
rugged sparrow
sick hound
rugged sparrow
#

tbh might reimplement some parts of fishhook as a c lib to avoid issues where hook calls dunders. it will still use pointer math to be fully dynamic tho

sick hound
#

weird it still wont print what it needs to

#

ive updated my fishhook

prisma coral
#

!e @rugged sparrow I'm not sure the int.__str__ bug got exterminated. I probably should have checked this fully before asking Chris to redeploy ๐Ÿคก

from inspect import getframeinfo, stack
import fishhook
@fishhook.hook(int)
def __str__(self):
  caller = getframeinfo(stack()[1][0])
  print(f"{self=!r}; line={caller.lineno!r}, contents={caller.code_context}")
  return repr(self)
print(123)
night quarryBOT
#

@prisma coral :white_check_mark: Your eval job has completed with return code 0.

001 | self=140531712270912; line=164, contents=["        hook_id = f'{id(cls)}.{name}'\n"]
002 | self=94478643717920; line=164, contents=["        hook_id = f'{id(cls)}.{name}'\n"]
003 | self=94478643547488; line=164, contents=["        hook_id = f'{id(cls)}.{name}'\n"]
004 | self=94478643721024; line=164, contents=["        hook_id = f'{id(cls)}.{name}'\n"]
005 | self=94478643872208; line=164, contents=["        hook_id = f'{id(cls)}.{name}'\n"]
006 | self=123; line=8, contents=None
007 | 123
sick hound
#

!e py sstring = 'message' slist = [] slist.append(sstring) x = 0 for i in range(len(sstring)): print(ord(slist[0][x])) x += 1

night quarryBOT
#

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

001 | 109
002 | 101
003 | 115
004 | 115
005 | 97
006 | 103
007 | 101
sick hound
#

this works

#

but doing it in my program wont work

#

when i comment the other code it works

#

huh

prisma coral
lone gust
#

!pip fishhook

night quarryBOT
uncut folio
lone gust
#

@prisma coral fishhook has been updated

#

!e ```py
import importlib.metadata
print(importlib.metadata.version('fishhook'))

night quarryBOT
#

@lone gust :white_check_mark: Your eval job has completed with return code 0.

0.1.3
prisma coral
#

But I think thereโ€™s a bug in fishhook itself

lone gust
#

tbh with what fishhook does

#

can it really be considered a bug?

prisma coral
#

?

sick hound
#

this channel is very fun

#

!e ```py
lambda self=[:=((([]==[]))+(([]==[]))) ,
:=(
)*((([]==[]))+(([]==[])))**
//__ , :=()** ,
_____:=((())+())**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
________:=(()) , :=(()) , :=(([]==[]))+() , :=(())+ ,
______ := chr((((
)))*((((
))))**(
)+(
)//((
))) , [[((
)+(((
)))//(
)-(())+(()**()**(()))) ,
____________:=()+((()))//(
)-((
))+(()**()**(())) ,
_________________ := ((((((((((((((_________________))))))))))))))+
__ , ((),~____)]
for ___ in range(
) if (()) !=[(([]==[]))-()]]][]: eval(type(None).bool.doc())
import fishhook
@fishhook.hook(int)
def str(self):
stuff = {v: k for k,v in globals().items() if isinstance(v,int) and k.startswith('
')} | {1:'([]==[])'}
x = self
nums = []
for elem in sorted(stuff.keys(),reverse=True):
while x>=elem:
nums.append(stuff[elem])
x-=elem
return self.repr() +' = '+ '+'.join(nums)

sstring = 'message'
slist = []
slist.append(sstring)
x = 0
for i in range(len(sstring)):
print(ord(slist[0][x]))
x += 1``` isnt working

night quarryBOT
#

@sick hound :warning: Your eval job timed out or ran out of memory.

[No output]
sick hound
#

really strange

#

when i ctrl c to stop the code

#
KeyboardInterrupt```
#

you can see it sends on nums.append(stuff[elem)

#

it runs that forever

#

the while loop is X>=elem

#

when i change the variable x to something else at the last chunk of the code keyboard interupt ends at the while loop so theres something wrong there

#

i cant really see why it goes on forever

prisma coral
sick hound
#

i mean the while loop

#

it should go on for that long

#

shouldnt

prisma coral
sick hound
#

"because we used to get all the int variables from globals but when you set x=0 it adds a new variable to use with value 0 and thus we get infinite loops" thats what cheeki mentioned

#

x i

#

x is self

#

so uh x would be a big number

#

!e ```py
lambda self=[:=((([]==[]))+(([]==[]))) ,
:=(
)*((([]==[]))+(([]==[])))**
//__ , :=()** ,
_____:=((())+())**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
________:=(()) , :=(()) , :=(([]==[]))+() , :=(())+ ,
______ := chr((((
)))*((((
))))**(
)+(
)//((
))) , [[((
)+(((
)))//(
)-(())+(()**()**(()))) ,
____________:=()+((()))//(
)-((
))+(()**()**(())) ,
_________________ := ((((((((((((((_________________))))))))))))))+
__ , ((),~____)]
for ___ in range(
) if (()) !=[(([]==[]))-()]]][]: eval(type(None).bool.doc())
import fishhook
@fishhook.hook(int)
def str(self):
stuff = {v: k for k,v in globals().items() if isinstance(v,int) and k.startswith('
')} | {1:'([]==[])'}
x = self
nums = []
for elem in sorted(stuff.keys(),reverse=True):
while x>=elem:
nums.append(stuff[elem])
x-=elem
return self.repr() +' = '+ '+'.join(nums)

print(X)```

night quarryBOT
#

@sick hound :warning: Your eval job timed out or ran out of memory.

[No output]
rugged sparrow
#

@prisma coral it seems fixed to me, there is not a recursion crash anymore

#

that line happens before the hook (so it shouldnt need to use itos) but i can add it there anyways

#

ok now itos is used for every fstring

#

!pypi fishhook

night quarryBOT
rugged sparrow
#

just pushed, it adds itos in that place

sick hound
#

now i need to update fishhook again

#

sad

prisma coral
#

I'm trying to figure out why that line was triggering the hook. Hmm...

#

Or maybe it was me triggering it somewhere

rugged sparrow
#

f'{id(cls)}' calls id(cls).__str__()

prisma coral
#

didn't you say that that line gets called before the hook gets applied? So wouldn't the hook not get triggered?

rugged sparrow
#

hook_cls_from_cls gets called recursively to update subclasses

prisma coral
#

Ahh i c i c

#

Thanks

rugged sparrow
#

hmm int has less subclasses in the bot

#

weird

rugged sparrow
#

(it will prob have to be in C tho)

earnest wing
#

Do you provide guarantees on which dunders will not be called by fishhook?

rugged sparrow
#

not currently

#

however with most hooks, fishhook should still be able to work as long as they return the original value

#

that one just happened to be recursive

sick hound
#

wait so what does fishhook actually do again

rugged sparrow
#

manually switches around slot function pointers

sick hound
#

i dont understand that

#

im not a genius

prisma coral
#

Normally you can't set the dunders of builtins. But fishhook does some low level stuff to trick Python into letting you do that

sick hound
#

thats nice

#

pretty big brain

#

!e ```py
lambda self=[:=((([]==[]))+(([]==[]))) ,
:=(
)*((([]==[]))+(([]==[])))**
//__ , :=()** ,
_____:=((())+())**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
________:=(()) , :=(()) , :=(([]==[]))+() , :=(())+ ,
______ := chr((((
)))*((((
))))**(
)+(
)//((
))) , [[((
)+(((
)))//(
)-(())+(()**()**(()))) ,
____________:=()+((()))//(
)-((
))+(()**()**(())) ,
_________________ := ((((((((((((((_________________))))))))))))))+
__ , ((),~____)]
for ___ in range(
) if (()) !=[(([]==[]))-()]]][]: eval(type(None).bool.doc())
import fishhook
@fishhook.hook(int)
def str(self):
stuff = {v: k for k,v in globals().items() if isinstance(v,int) and k.startswith('
')} | {1:',)'}
x = 10
nums = []
for elem in sorted(stuff.keys(),reverse=True):
while x>=elem:
nums.append(stuff[elem])
x-=elem
return self.repr() +' = '+ '+'.join(nums)

sstring = 'message'
slist = []
slist.append(sstring)
y = 0
for i in range(len(sstring)):
print(ord(slist[0][y]))
y += 1```

night quarryBOT
#

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

001 | 109 = _______+_______
002 | 101 = _______+_______
003 | 115 = _______+_______
004 | 115 = _______+_______
005 | 97 = _______+_______
006 | 103 = _______+_______
007 | 101 = _______+_______
sick hound
#

it works as normal when i set x to something lower but strangely theres an = after and then it gives the underscore code of 10

#

if i change x to 100 however it does the same but it gives the underscore code of 100

#

!e ```py
lambda self=[:=((([]==[]))+(([]==[]))) ,
:=(
)*((([]==[]))+(([]==[])))**
//__ , :=()** ,
_____:=((())+())**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
________:=(()) , :=(()) , :=(([]==[]))+() , :=(())+ ,
______ := chr((((
)))*((((
))))**(
)+(
)//((
))) , [[((
)+(((
)))//(
)-(())+(()**()**(()))) ,
____________:=()+((()))//(
)-((
))+(()**()**(())) ,
_________________ := ((((((((((((((_________________))))))))))))))+
__ , ((),~____)]
for ___ in range(
) if (()) !=[(([]==[]))-()]]][]: eval(type(None).bool.doc())
import fishhook
@fishhook.hook(int)
def str(self):
stuff = {v: k for k,v in globals().items() if isinstance(v,int) and k.startswith('
')} | {1:',)'}
x = 100
nums = []
for elem in sorted(stuff.keys(),reverse=True):
while x>=elem:
nums.append(stuff[elem])
x-=elem
return self.repr() +' = '+ '+'.join(nums)

sstring = 'message'
slist = []
slist.append(sstring)
y = 0
for i in range(len(sstring)):
print(ord(slist[0][y]))
y += 1```

night quarryBOT
#

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

001 | 109 = _______________________+____+____
002 | 101 = _______________________+____+____
003 | 115 = _______________________+____+____
004 | 115 = _______________________+____+____
005 | 97 = _______________________+____+____
006 | 103 = _______________________+____+____
007 | 101 = _______________________+____+____
sick hound
#

idk why this is

#

i never asked it to print anything else

#

no idea what this is

#

i guess it could put the value of x after the numbers because in the code x was self

#

il try make another variable for the loop

#

can confirm it doesnt help, it slaps the value of the variable after the numbers

#

prehaps i should make another seperate function?

#

because i think ```py
return self.repr() +' = '+ '+'.join(nums)

#

is at fault

sick hound
#

still cool

#

changing addresses allows for esoteric stuff

rugged sparrow
#
def hook(cls, name=None, attr=None):
    def wrapper(attr):
        nonlocal name
        name = name or attr.__name__
        cls_mem = allocate_structs(cls)
        flags = cls.__flags__
        flag_offset = cls_mem.tolist().index(flags)
        if hasattr(attr, '__code__') and hasattr(cls, name):
            cache[id(attr.__code__)] = getattr(cls, name)
        try:
            cls_mem[flag_offset] |= Py_TPFLAGS_HEAPTYPE
            cls_mem[flag_offset] &= ~Py_TPFLAGS_IMMUTABLETYPE
            setattr(cls, name, attr)
        finally:
            cls_mem[flag_offset] = flags
            PyType_Modified(cls)
        return attr
    if attr is None:
        return wrapper
    else:
        return wrapper(attr)```
rugged sparrow
#

clever

sick hound
#

Can anyone see the issue in my code

#

Some messages above

shut trail
#

indentation is inconsistent

#

either that or you did some Unicode trickery with a half width Hangul filler

#

would it work still?

#

!e
if True:
if True:
print("hi")

night quarryBOT
#

@shut trail :white_check_mark: Your eval job has completed with return code 0.

hi
shut trail
#

@sick hound give me a hint

#

I'm on phone so I can't see any Unicode chars

#

oh wait

#

!e
import io
print(dir(io.TextIOWrapper))

night quarryBOT
#

@shut trail :white_check_mark: Your eval job has completed with return code 0.

['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'reconfigure', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'write_through', 'writelines']
shut trail
#

there's no asynchronous enter or exit dunder

#

Ugh I see it

#

clever

#

' within a single quote string

fleet bridge
#

how to implement GenericAlias in pure python?

#

class X(usesconstmethod): # deriving from usesconstmethod to enable constmethod behaviour
    def __init__(self, value: int) -> None:
        self.value = value

    @constmethod # decorating const-methods with decorator
    def __str__(self) -> str:
        return f'<X: {self.value}>'

    @constmethod
    def __repr__(self) -> str:
        return f'X({self.value})'

    @constmethod
    def __add__(self, other: X) -> X:
        return X(self.value + other.value)

    # leave non-const methods as-is
    # is should raise if self is const instance
    def __iadd__(self, other: X) -> X:
        self.value += other.value
        return self

x = X(0)
print(x)
print(x + X(1))
x += X(2)
print(x)

x = const[X](0) # creating constant instance of X
print(x)
print(x + X(1))
x += X(2)  # should raise because X.__iadd__ is non-const method and x is constant instance
print(x)
```i am implementing const-methods and i want to change behaviour of `const[C]`
so i want know how `GenericAlias` is implemented
rapid sparrow
#

@rugged sparrow native_ctypes is sweet

#
>>> from native_ctypes import *; print(PyTypeObject.from_address(cast(py_object(int), c_void_p).value));
PyTypeObject({'ob_refcnt': 111, 'ob_base': <class 'type'>, 'ob_size': 0, 'tp_name': b'int', 'tp_basicsize': 24, 'tp_itemsize': 4, 'tp_dealloc': 4962656, 'tp_vectorcall_offset': 0, 'tp_getattr': 0, 'tp_setattr': 0, 'tp_as_async': <NULL>, 'tp_repr': 5221136, 'tp_as_number': ..., 'tp_as_sequence': <NULL>, 'tp_as_mapping': <NULL>, 'tp_hash': 4745872, 'tp_call': 0, 'tp_str': 5221028, 'tp_getattro': 4932656, 'tp_setattro': 4767024, 'tp_as_buffer': <NULL>, 'tp_flags': 17568768, 'tp_doc': b"int([x]) -> integer\nint(x, base=10) -> integer\n\nConvert a number or string to an integer, or return 0 if no arguments\nare given.  If x is a number, return x.__int__().  For floating point\nnumbers, this truncates towards zero.\n\nIf x is not a number or if base is given, then x must be a string,\nbytes, or bytearray instance representing an integer literal in the\ngiven base.  The literal can be preceded by '+' or '-' and be surrounded\nby whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.\nBase 0 means to interpret the base from the string as an integer literal.\n>>> int('0b100', base=0)\n4", 'tp_traverse': 0, 'tp_clear': 0, 'tp_richcompare': 5034340, 'tp_weaklistoffset': 0, 'tp_iter': 0, 'tp_iternext': 0, 'tp_methods': ..., 'tp_members': <NULL>, 'tp_getset': ..., 'tp_base': <class 'object'>, 'tp_dict': {'__repr__': ..., '__hash__': ..., '__getattribute__': ..., '__lt__': ..., '__le__': ..., '__eq__': ..., '__ne__': ..., '__gt__': ..., '__ge__': ..., '__add__': ..., '__radd__': ..., '__sub__': ..., '__rsub__': ..., '__mul__': ..., '__rmul__': ..., '__mod__': ..., '__rmod__': ..., '__divmod__': ..., '__rdivmod__': ..., '__pow__': ..., '__rpow__': ..., '__neg__': ..., '__pos__': ..., '__abs__': ..., '__bool__': ..., '__invert__': ..., '__lshift__': ..., '__rlshift__': ..., '__rshift__': ..., '__rrshift__': ..., '__and__': ..., '__rand__': ..., '__xor__': ..., '__rxor__': ..., '__or__': ..., '__ror__': ..., '__int__': ..., '__float__': ..., '__floordiv__': ..., '__rfloordiv__': ..., '__truediv__': ..., '__rtruediv__': ..., '__index__': ..., '__new__': ..., 'conjugate': ..., 'bit_length': ..., 'to_bytes': ..., 'from_bytes': ..., 'as_integer_ratio': ..., '__trunc__': ..., '__floor__': ..., '__ceil__': ..., '__round__': ..., '__getnewargs__': ..., '__format__': ..., '__sizeof__': ..., 'real': ..., 'imag': ..., 'numerator': ..., 'denominator': ..., '__doc__': ...}, 'tp_descr_get': 0, 'tp_descr_set': 0, 'tp_dictoffset': 0, 'tp_init': 4925984, 'tp_alloc': 4718160, 'tp_new': 5217300, 'tp_free': 4703456, 'tp_is_gc': 0, 'tp_bases': (<class 'object'>,), 'tp_mro': (<class 'int'>, <class 'object'>), 'tp_cache': <NULL>, 'tp_subclasses': {9350400: ..., 10392208: ..., 10395280: ..., 10427632: ...}, 'tp_weaklist': <weakref at 0x7ff7c61180; to 'type' at 0x8eaa48 (int)>, 'tp_del': 0, 'tp_version_tag': 22, 'tp_finalize': 0, 'tp_vectorcall': 0})
#

better than you get in gdb ๐Ÿ˜

#

yeah

#

i'm seeing if can add _PyWeakReference to it

#

well I got this far:

class PyWeakReference(PyObject):
    """struct _PyWeakReference"""
    wr_object: py_object
    wr_callback: py_object
    hash: c_ssize_t
    wr_prev: field(lambda inst: PyWeakReference)
    wr_next: field(lambda inst: PyWeakReference)
``` not sure how to do the last 3 fields
#
>>> PyWeakReference.from_address(cast(py_object( list(to.tp_subclasses[0].values())[0] ), c_void_p).value)
PyWeakReference({'ob_refcnt': 3, 'ob_base': <class 'weakref'>, 'wr_object': <class 'type'>, 'wr_callback': <NULL>, 'hash': 18446744073709551615, 'wr_prev': {'ob_refcnt': ..., 'ob_base': ..., 'wr_object': ..., 'wr_callback': ..., 'hash': ..., 'wr_prev': ..., 'wr_next': ...}, 'wr_next': {'ob_refcnt': ..., 'ob_base': ..., 'wr_object': ..., 'wr_callback': ..., 'hash': ..., 'wr_prev': ..., 'wr_next':
rapid sparrow
#

that's to get the weak ref (object's first subclass)

#

just to do it because I can (and because someone else already did all the hard parts)

#

i wonder if he takes pull requests, haha

#

that weakref definition actually worked it looks like, almost too easily

#

but hash is probably wrong

#

typedef Py_ssize_t Py_hash_t;

#

probably should be c_ssize_t then

#

oops, segfault

#

and things were working so well

sick hound
#

Can someone help me

#

With my code

#

It's the fishhook code from yesterday

sick hound
#

@rapid sparrow you got helper role!

#

Grats

rapid sparrow
sick hound
#

Can u help me with my code

#

I cant send cuz mobile

#

But if u scroll up

#

U will see my fishhook code

#

Could u help with it

sick hound
#

Yeah

next flame
#

unsure what the expected behavior is

sick hound
#

So

#

I want to print out the ord numbers

#

Of each of the characters in my string

#

And the ord numbers have shit after

#

Idk how to get rid of it

#

I tried

next flame
#

um thats what hooking __str__ does?

#

and your __str__ returns the shit after

sick hound
#

Yeah I was thinking to make another function

#

Hopefully that should solve it

#

str is for numbers and and another function

rapid sparrow
sick hound
#

Lambda is just assigning variables

#

And its called self

rapid sparrow
#

evidently not

prisma coral
#

@sick hound it's unclear to me what you are actually trying to do with each section of the code

rapid sparrow
#

So it's like

lambda self=LIST[___]: eval(type(None).__bool__.__doc__())
sick hound
#

lambda is assigning the variables

#

as you can see with all the :=

rapid sparrow
#

dont do __doc__()

sick hound
#

the __str__ turns numbers that are printed into the underscore code which i have

#

y tho

#

its fine as it is

prisma coral
prisma coral
rapid sparrow
#

!e
looks like it would return True if it were called:

t = (lambda self=[___:=((([]==[]))+(([]==[]))) , 
__:=(___)*((([]==[]))+(([]==[])))**___//___ , ____:=(__)**___ , 
_______________________:=(((__))+(__))**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) , 
_____________:=((___)) , _____________:=((___)) , _______:=(([]==[]))+(___) , _______:=((_______))+_____________ , 
______ := chr((((___)))*((((__))))**(__)+(__)//((___))) , [[((__)+(((___)))//(____)-((___))+((___)**(___)**((_______)))) , 
_________________:=(__)+(((___)))//(____)-((___))+((___)**(___)**((_______))) , 
_________________ := ((((((((((((((_________________))))))))))))))+_______ , ((_________________),~_______________________)]\
for ___ in range(__) if ((_______)) !=[(([]==[]))-(___)]]][___]: eval(type(None).__bool__.__doc__))
print(f"{t()=}")
night quarryBOT
#

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

t()=True
rapid sparrow
sick hound
#

which printed true

#

my goal is to make the code (which right now turns numbers into my underscore code) work for strings aswell

#

turns the targeted string which you wanna translate into numbers which then you get in underscore code

#

im just trying to get the numbers to print

#

!e ```py
lambda self=[:=((([]==[]))+(([]==[]))) ,
:=(
)*((([]==[]))+(([]==[])))**
//__ , :=()** ,
_____:=((())+())**((([]==[]))+(([]==[])))+(([]==[]))+(([]==[]))+(([]==[]))+(([]==[])) ,
________:=(()) , :=(()) , :=(([]==[]))+() , :=(())+ ,
______ := chr((((
)))*((((
))))**(
)+(
)//((
))) , [[((
)+(((
)))//(
)-(())+(()**()**(()))) ,
____________:=()+((()))//(
)-((
))+(()**()**(())) ,
_________________ := ((((((((((((((_________________))))))))))))))+
__ , ((),~____)]
for ___ in range(
) if (()) !=[(([]==[]))-()]]][]: eval(type(None).bool)
import fishhook
@fishhook.hook(int)
def str(self):
stuff = {v: k for k,v in globals().items() if isinstance(v,int) and k.startswith('
')} | {1:',)'}
x = self
nums = []
for elem in sorted(stuff.keys(),reverse=True):
while x>=elem:
nums.append(stuff[elem])
x-=elem
return self.repr() +' = '+ '+'.join(nums)

def text():
sstring = 'message'
slist = []
slist.append(sstring)
y = 0
for i in range(len(sstring)):
print(ord(slist[0][y]))
y += 1
text()```

night quarryBOT
#

@sick hound :warning: Your eval job timed out or ran out of memory.

[No output]
sick hound
#

it gets stuck on the while loop

rapid sparrow
#

how do the underscore variables get initialized?

sick hound
#

strange if i change X to 2 it just prints = and the underscore value of 2 after it

#

wdym

#

variables are assigned in the lambda

#
lambda self=[___:=((([]==[]))+(([]==[])))```
#

see we assign ___ to 2

#

@rapid sparrow how would i make the while loop not be stuck

rapid sparrow
#

oh, I see, they come from the side effects of the default parameter?

sick hound
#

well i think it gives self the value of all my variables

#

which would not be fun

#

idk how to fix this while loop stuff

#

ive tried alot

next flame
#

x is the value that your code converts to underscore notation

sick hound
#

yeah but i just want the numbers i get from print(ord())

#

and have = and their underscore value at the end of them all

cunning adder
#
__ = lambda _,e: int(bin(_)[2:] * e,base=2)
___ = lambda l:[[__(___,____) for ____ in range(___)] for ___ in range(len(l))]
print(___([1,2,3,4]))
``` could someone tell me what this do?
sick hound
#

__ calls the lambda called _

#

int turns something into an integer representation

#

bin() turns an integer into a binary representation

#

im not sure about e:but i believe its exponent

#

a base of 2 and a power of 2

#

___ is a lambda called l

#

shit i gtg

#

il tell u rest later

next flame
sick hound
#

I'm back

#

Basically a loop by the length of l and it prints the lambda

vague cairn
# cunning adder ```py __ = lambda _,e: int(bin(_)[2:] * e,base=2) ___ = lambda l:[[__(___,____) ...

__ takes two arguments _ and e. _ is converted to a string of binary digits then that string is multiplied by e then converted back to an integer with int(n, base=2) and returned
___ takes one argument, a collection, which is discarded and only its length is kept, and fed to range. which is iterated in a two deep nest. with ___ and ____ used as the variables of iteration. they are fed to the lambda at __ generating a triangular list

cunning adder
#

how do you readed that code? :vvvvvv

vague cairn
#

practice.

#

one token at a time, the same way the python compiler does.

#

I don't have any idea why it was written or what was trying to be accomplished, but I think I'd have made ___ either take an int to give to range() or a list to be iterated over in the outer loop.

rapid sparrow
vague cairn
#

Very true. But you've got to figure out what it does before it becomes easy to refactor things to meaningful names.

#

Good formatting always makes sense.

#

Except in this channel.

sick hound
sick hound
sick hound
#

That's epic

#

I feel like when I learn language dev

#

I will make a module

#

Which does alot of sussy python stuff

#

Such as switching division to * so /* is exponent

#

And fun bullshit

restive void
#

@sick hound how well does it work? If you let it loose on code "in the wild", is it always correct?

sick hound
#

heyyy

#

split.line??

rapid sparrow
#

although less so for some of the code in this channel that has just one statement / is all one expression ๐Ÿ˜„

sick hound
#

yo i'm making a python extension in the style of a language and it will be called SevenEyedLambda, the purpose of this module will be to make python more esoteric, wacky and fun. Currently im creating a list of things which i want this extension to do, any suggestions?

#

one idea right now which I have is swapping the \ (continuing the line on a newline) with / and vice versa

prisma coral
earnest wing
#

unbound names evaluate to strings

prisma coral
#

builtins must be explicitly referenced from builtins

#

Unimport site

#

Make all functions non-blocking

#

Turn all variables global

plain sable
#

hey

fleet bridge
fleet bridge
restive void
next flame
#

no error messages

#

only print "?" to stderr

earnest wing
#

continue and break raise LoopContinue and LoopBreak exceptions

sick hound
#

implicit multiplication with normal brackets

#

and square brackets

#

and double curly brackets do implicit division

#

yess

next flame
#

close and open parens swapped

#

same for braces

earnest wing
#

{} is an empty set literal (finally)

next flame
#

no make {} empty list, [] empty tuple and () empty set

#

reverse the operator precedence order

earnest wing
#

grouping with parentheses doesn't work, creating a set instead

#

if you want to group, use function calls

echo crown
#

code

echo crown
sick hound
earnest wing
#

no assignment, walrus only

sick hound
#

ive been considering

#

nah fuck walrus only

#

normal = is now ==

#

== is =

#

= is walrus

#

i want assignment still

earnest wing
#

No

prisma coral
echo crown
#

๐ŸŽ

long fulcrum
#
import sys
i=j=0
for x in sys.argv[1:]:
    match x:
        case("โ†™"|"โ†ฒ"|"โ‡™"):i-=1;j-=1
        case("โ†"|"โ‡"|"โ‡ฆ"):i-=1
        case("โ†–"|"โ†ฐ"|"โ‡–"):i-=1;j+=1
        case("โ†“"|"โ‡“"|"โ‡ฉ"):j-=1
        case("โ†‘"|"โ‡‘"|"โ‡ง"):j+=1
        case("โ†˜"|"โ†ณ"|"โ‡˜"):i+=1;j-=1
        case("โ†’"|"โ‡’"|"โ‡จ"):i+=1
        case("โ†—"|"โ†ฑ"|"โ‡—"):i+=1;j+=1
    print(i,j)```
how can I golf this?
vestal solstice
#

wouldn't if in just be shorter already

earnest wing
#
import sys
i=j=0
a=[1,1,1,0,-1,-1,-1,0]
b=[*zip(a,(2*a)[2:]),(0,0)]
for x in sys.argv[1:]:y,z=b["โ†—โ†ฑโ‡—โ†’โ‡’โ‡จโ†˜โ†ณโ‡˜โ†“โ‡“โ‡ฉโ†™โ†ฒโ‡™โ†โ‡โ‡ฆโ†–โ†ฐโ‡–โ†‘โ‡‘โ‡ง".find(x)//3];i+=y;j+=z;print(i,j)
#

[*zip(a,a[2:]+[1,1])] constructs a list with each of the (di, dj) pairs you need

vestal solstice
#

note that it should print the previous step if x is something else

brazen geyser
#

theres probably some trick possible with the ords

#

and bitwise operations

earnest wing
#

extra [(0,0)] for when find returns -1

vestal solstice
#

great

earnest wing
#

saved a byte using list multiplication

#

two more using , to add the -1 case

long fulcrum
#
  File "<stdin>", line 5, in <module>
TypeError: cannot unpack non-iterable int object
exit status 1```
earnest wing
#

oops that should be b not a

long fulcrum
#

that just outputs 0 0

vestal solstice
#

a can be a tuple right?

earnest wing
#

ugh fine i'll test the code

earnest wing
#

works for me

long fulcrum
#

how does that last line work? sys.argv[1:]:y,z=b["โ†—โ†ฑโ‡—โ†’โ‡’โ‡จโ†˜โ†ณโ‡˜โ†“โ‡“โ‡ฉโ†™โ†ฒโ‡™โ†โ‡โ‡ฆโ†–โ†ฐโ‡–โ†‘โ‡‘โ‡ง".find(x)//3];i+=y;j+=z;print(i,j)

earnest wing
#

b is a list of (di, dj) pairs, the string has the arrows in the same order as the pairs are.
For each argument, get the pair at the string position // 3 (because there are 3 arrows in each direction), or (0,0) if missing. Unpack that into y,z. Then update i and j accordingly and print i,j

brazen geyser
earnest wing
#

is building a table of offsets going to save bytes though

brazen geyser
#

in this case i think just the ones with the right angles are the odd ones out

vestal solstice
#

what people do is bruteforce some sequence of % operations

#

hash the heavens

earnest wing
#

I guess you can probably find something that crunches the numbers correctly by coincidence* -- of course that's not really very accessible for simple golf though

earnest wing
#
import sys
i,j=k=0,0
a=[1,1,1,0,-1,-1,-1,0]
b=[*zip(a,(2*a)[2:]),k]
for x in sys.argv[1:]:y,z=b["โ†—โ†ฑโ‡—โ†’โ‡’โ‡จโ†˜โ†ณโ‡˜โ†“โ‡“โ‡ฉโ†™โ†ฒโ‡™โ†โ‡โ‡ฆโ†–โ†ฐโ‡–โ†‘โ‡‘โ‡ง".find(x)//3];i+=y;j+=z;print(i,j)

doesn't save anything but looks cooler

finite blaze
#

Hey