#esoteric-python

1 messages ยท Page 94 of 1

steep mural
#

(lambda: (yield))().throw(exc)

grave rover
#

ohno

#

I'm currently still working on for loops

formal sandal
#
(lambda:(yield))().throw(exc)
(0for()in()).throw(exc)

still shorter ๐Ÿ‘…

#

I didn't know you could even yield in a lambda

steep mural
#

You just have to wrap it in parenthesis

#

for some reason

grave rover
#
a = lambda b: 
for c in range(len(b)):
    d = c
    for e in range(c + 1, len(b)):
        if b[d] > b[e]:
            d = e
    (b[c], b[d]) = (b[d], b[c])

I feel like I should try to figure out assignments somehow, hmm...

rugged sparrow
#

if its 3.8+ you can prob use (var:=val)

#

in most cases

formal sandal
#

I'm not sure how to handle nonlocal stuff

#

You can always implement your own scopes, though.

rugged sparrow
#

nonlocal you may have to mod the bytecode of the lambda after compiling

formal sandal
#

Well, in that case you could've just written bytecode in the first place

#

Oh, I have an idea -- you could probably replace a nonlocal with a singleton list. This way, you can share a mutable cell.

#

!e

cell = [0]

inc = lambda c:c.__setitem__(0,c[0]+1)

inc(cell)
print(cell)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

[1]
sick hound
#
x = lambda number_1,op,number_2,: number_1+number_2 if op == '+' else number_1-number_2 if op == '-' else number_1 * number_2 if op == '*' else number_1 / number_2 if op == '/' else False
print(x(int(input("Enter number 1:")),input("Enter op -,+,*,/:"),int(input("Enter number 2:")),))
``` anyway i can make this code smaller?
twilit grotto
#

a dictionary is probably shorter

sick hound
#

I'll try that

proper vault
#
x=lambda a,o,b: {'+':a+b,'-':a-b,'*':a*b,'/'a/(b or 1)}[o]
#

the problem with a dict is division

sick hound
#

@proper vault cheers

sick hound
#
(0for()in()).throw(exc)

@formal sandal

#

Wait, how does that syntax work?

#

(0for()in())

#

Why does that even work

formal sandal
#

(0 for () in ())

#

it's a generator expression

sick hound
#

Oh

formal sandal
#

you can use tuples to desturcture things

#

!e

xs = []
() = xs
night quarryBOT
#

@formal sandal :warning: Your eval job has completed with return code 0.

[No output]
formal sandal
#

^ as well as empty tuples

sick hound
#

Wtf

formal sandal
#
(x, y, z) = [1, 2, 3]
(x, y) = [1, 2]
(x,) = [1]
() = []
sick hound
#

*l,=range(10) is also a thing

#

Just found out yesterday

grave rover
#

I wonder how I can turn a, b = c into a non-statement

#

I could use (a:=b) for single variables but for destructuring it'll be difficult

proper vault
#
[expr for a, b in [c]][0]
grave rover
#

good one

#

wait

#

I can't do things that require statements further on

#

or could I

#

wait

#

no nvm I can't do that

#

aaaa

proper vault
#

I mean yeah, if you are removing statements, you gotta remove all statements

grave rover
#

yeah

#

I have a solution for most cases, but this is hard

rugged sparrow
#

!e __import__('ctypes').string_at(0)

night quarryBOT
#

@rugged sparrow :warning: Your eval job has completed with return code 139 (SIGSEGV).

[No output]
rugged sparrow
#

@sick hound ^

grave rover
#

!e __import__('ctypes').memset(0,0,1)

night quarryBOT
#

@grave rover :warning: Your eval job has completed with return code 139 (SIGSEGV).

[No output]
grave rover
#

wait no that's 1 char more

steep mural
#

is that like a segfault? What's so special about string at 0 lol

formal sandal
#

yes, it's a segfault

#

it's trying to read memory from address 0

rugged sparrow
#

!e py c=lambda *a:__import__('ctypes').wstring_at(id(int)) b=[int]*30;print(c([int]*7)+c(*[int]*2)+(c(*[int]*5,[int])*2)+c(*[int]*7),c(*[int]*11)+c(*[int]*7)+c(*[int]*8,[int])+c(*[int]*5,[int])+c([int],int))

night quarryBOT
#

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

hello world
grave rover
#
def selection_sort(items):
    for i in range(len(items)):
        min_idx = i
        for j in range(i + 1, len(items)):
            if items[min_idx] > items[j]:
                min_idx = j
        items[i], items[min_idx] = items[min_idx], items[i]

# Generated by Mart Obfuscator
selection_sort = lambda items, MART_OBFUSCATOR_locals_a=[0]: [
    (
        MART_OBFUSCATOR_locals_a.__setitem__(0, i),
        [
            items[MART_OBFUSCATOR_locals_a[0]] > items[j] and 
                MART_OBFUSCATOR_locals_a.__setitem__(0, j) 
            for j in range(i + 1, len(items))
        ],
       (items.__setitem__(i, items[MART_OBFUSCATOR_locals_a[0]]),
        items.__setitem__(MART_OBFUSCATOR_locals_a[0], items[i]))
    )
    for i in range(len(items))
]
``` Does anyone know why the second one fails to work properly?
open ore
grave rover
#

oh wait I see what's wrong

#

my double assign isn't working as it should

#

a,b = b,a fails because it does a = b and then b = a

grave rover
#

any ideas for how to solve these?

grave rover
#
def selection_sort(items):
    for i in range(len(items)):
        min_idx = i
        for j in range(i + 1, len(items)):
            if items[min_idx] > items[j]:
                min_idx = j
        tmp = items[i]
        items[i] = items[min_idx]
        items[min_idx] = tmp

# Generated by Mart Obfuscator
a=lambda b,c=[0,0]:[(c.__setitem__(0,d),[b[c[0]]>b[e]and c.__setitem__(0,e)for e in range(d+1,len(b))],c.__setitem__(1,b[d]),b.__setitem__(d,b[c[0]]),b.__setitem__(c[0],c[1]))for d in range(len(b))]
``` pretty happy with this one
#

I'm sure there's a smaller selection sort but whatever

#

any other good suggestions for stuff to obfuscate? leaving classes for later rn

grave rover
#

oh god it doesn't handle scopes properly

rugged sparrow
#

@grave rover for double assigns you'll need a temp var to do the swap

grave rover
#

alright fuck generating that, I'll just let it fail silently lmao

#

good news: I think I got while loops to work, testing quicksort soon

rugged sparrow
#

I assume using [*iter()]?

grave rover
#

nope

#

f = lambda: (condition and (body, f()))
f()

rugged sparrow
#

That will fail eventually right? If you do [*iter(lambda:[condition,body][0],True)] it should work infinitely (until buildlist starts to hang)

restive void
#

b.__setitem__(c[0],c[1]) can be rewritten as getattr(b, "__setitem__")(c[0], c[1]). You can then assign "__setitem__" to a variable at the beginning and use that instead.

#

In general, re-assigning all used names to short variables could obfuscate the code further.

stark fable
#

you could assign lambda x:getattr(x,"__setitem__") to a variable if you wanted to

grave rover
#

even better, assign something to lambda x,y,z:x.__setitem__(y,z)

formal sandal
#
lambda x,*a:x.__setitem__(*a)

a bit shorter ๐Ÿ™‚

grave rover
#

good one

#
f=lambda g,h,i,j=[0]:h>=i and-1or(j.__setitem__(0,k(g,h,i)),f(g,h,j[0]-1),f(g,j[0]+1,i))
k=lambda g,h,i,l=[0]*6:(l.__setitem__(0,g[h]),l.__setitem__(1,h+1),l.__setitem__(2,i),l.__setitem__(5,lambda:l[1]<=l[2]and((l.__setitem__(3,lambda:(l[1]<=l[2]and g[l[2]]>=l[0])and(l.__setitem__(2,l[2]-1),l[3]())),l[3](),l.__setitem__(4,lambda:(l[1]<=l[2]and g[l[1]]<=l[0])and(l.__setitem__(1,l[1]+1),l[4]())),l[4](),l[1]<=l[2]and(l.__setitem__(1,g[l[1]]),g.__setitem__(l[1],g[l[2]]),g.__setitem__(l[2],l[1]))),m())),l[5](),l.__setitem__(1,g[h]),g.__setitem__(h,g[l[2]]),g.__setitem__(l[2],l[1]),l[2])
```honestly having quicksort compressed to this is already a big win
#

for blank return I sadly need to return -1 though :(

#

Wait

#

it fails on one of the while loops?

#

I know why it goes wrong but not... why

#
partition=lambda array,start,end,MART_OBFUSCATOR_locals_c=[0]*6:(MART_OBFUSCATOR_locals_c.__setitem__(0,array[start]),MART_OBFUSCATOR_locals_c.__setitem__(1,start+1),MART_OBFUSCATOR_locals_c.__setitem__(2,end),MART_OBFUSCATOR_locals_c.__setitem__(5,lambda:MART_OBFUSCATOR_locals_c[1]<=MART_OBFUSCATOR_locals_c[2]and((MART_OBFUSCATOR_locals_c.__setitem__(3,lambda:(MART_OBFUSCATOR_locals_c[1]<=MART_OBFUSCATOR_locals_c[2]and array[MART_OBFUSCATOR_locals_c[2]]>=MART_OBFUSCATOR_locals_c[0])and(MART_OBFUSCATOR_locals_c.__setitem__(2,MART_OBFUSCATOR_locals_c[2]-1),MART_OBFUSCATOR_locals_c[3]())),MART_OBFUSCATOR_locals_c[3](),MART_OBFUSCATOR_locals_c.__setitem__(4,lambda:(MART_OBFUSCATOR_locals_c[1]<=MART_OBFUSCATOR_locals_c[2]and array[MART_OBFUSCATOR_locals_c[1]]<=MART_OBFUSCATOR_locals_c[0])and(MART_OBFUSCATOR_locals_c.__setitem__(1,MART_OBFUSCATOR_locals_c[1]+1),MART_OBFUSCATOR_locals_c[4]())),MART_OBFUSCATOR_locals_c[4](),MART_OBFUSCATOR_locals_c[1]<=MART_OBFUSCATOR_locals_c[2]and(MART_OBFUSCATOR_locals_c.__setitem__(1,array[MART_OBFUSCATOR_locals_c[1]]),array.__setitem__(MART_OBFUSCATOR_locals_c[1],array[MART_OBFUSCATOR_locals_c[2]]),array.__setitem__(MART_OBFUSCATOR_locals_c[2],MART_OBFUSCATOR_locals_c[1]))),MART_OBFUSCATOR_while_d())),MART_OBFUSCATOR_locals_c[5](),MART_OBFUSCATOR_locals_c.__setitem__(1,array[start]),array.__setitem__(start,array[MART_OBFUSCATOR_locals_c[2]]),array.__setitem__(MART_OBFUSCATOR_locals_c[2],MART_OBFUSCATOR_locals_c[1]),MART_OBFUSCATOR_locals_c[2])```
the one `MART_OBFUSCATOR_while_d` does not get remapped to `MART_OBFUSCATOR_locals_c[5]`
odd canyon
#

your code is so obfusctaed

formal sandal
#

Is there a way to hack together a circular inheritance relation?

#

I was able to make it so that B.__bases__ == (B,), but in that case printing B causes a segmentation fault.

stark fable
#

one issue with doing something like that is that you would end up with an infinite MRO

thin trout
#

Yeah, the MRO will probably make the object unusable

formal sandal
#

๐Ÿ˜ฟ

twin reef
#

I was trying to make a circular inheritance some time ago. My idea was to create a class that merges all the classes in inheritance and makes them reference this class. For example, if A(B) and B(A) it will create a class C with all the fields of A and B merged together. Obviously, it's not a real inheritance (no MRO action involved). But A is a subclass of B and B is a subclass of A. It was kind of complicated to implement with just plain metaclasses with all of the edge cases considered (What if class A overrides the field of class B? Or the field of class A is collides with a slot of class B?) therefore I quickly gave up.

naive roost
#

I am not sure you can even do that. I don't see how it could work, actually. You need the address of one class to define the other, so you could have something like ```py
class A:
pass

class B(A):
pass

class A(B):
pass

formal sandal
#

This just creates a new class named A

#

!e

class A:
  pass

old_A = A

class B(A):
  pass

class A(B):
  pass

print(A is old_A)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

False
rugged sparrow
#
>>> from forbiddenfruit import curse
>>> curse(type, '__add__', lambda *classes:(c:=tuple(set(classes))) and type(','.join(map(getattr, c, ['__name__']*len(c))), c,{}))
>>> class a:
...     def foo(self):
...             print('foo')
...
>>> class b:
...     def bar(self):
...             print('bar')
...
>>> AB = (a + b)()
>>> AB.foo()
foo
>>> AB.bar()
bar
>>>```
naive roost
#

!e ```py
class A:
pass

old_A = A

class B(A):
pass

class A(B):
pass

print(issubclass(A, old_A))```

night quarryBOT
#

@naive roost :white_check_mark: Your eval job has completed with return code 0.

True
naive roost
#

!e ```py
class A:
pass

old_A = A

class B(A):
pass

class A(B):
pass

print(issubclass(A, old_A))
print(issubclass(B, A))

night quarryBOT
#

@naive roost :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | False
sick hound
#

@rugged sparrow Woah, never heard of that library. Do you know any other cool libraries that let you do stuff like that?

#

Damn, why didn't I hear about this before

formal sandal
#

@naive roost class A: ... works like assignment: it creates a new class object and binds it to the name A

#

just like creating a new function or a new list

rugged sparrow
sick hound
#

Thanks

distant wave
#

the magic of module finders:

#
import inspect
import sys
from importlib.machinery import PathFinder


class LogImporter(PathFinder):
    def __init__(self, print_file_path: bool = False):
        self.print_file_path = print_file_path

    def find_spec(self, name, path=None, target=None):
        print('Importing', name, end=" ", flush=True)
        cf = inspect.currentframe().f_back
        a = 0
        while cf:
            a += 1
            if "importlib" in cf.f_globals['__file__']:
                cf = cf.f_back
                continue
            if not self.print_file_path:
                print("from file", '/'.join(cf.f_globals['__file__'].rsplit("/")[-2:]))
            else:
                print("from file", cf.f_globals['__file__'])
            break
        del cf
        return super().find_spec(name, path, target)


sys.meta_path.insert(0, LogImporter())

import json
print(json)
#
Importing json from file scratches/scratch_9.py
Importing json.decoder from file json/__init__.py
Importing json.scanner from file json/decoder.py
Importing _json from file json/scanner.py
Importing json.encoder from file json/__init__.py
#

I'm sure there's some way to convert the path into another module, but I'm tired. If someone wants to, do it and ping me lol

night tiger
#

It annoys me that you put spaces around some =s and not all

twilit grotto
#

i think pep8 says that's what you should do

rugged sparrow
#

!e py from ctypes import c_ssize_t t = (0,) c_ssize_t.from_address(id(t) + 16).value = -1 print(t) print(t.__len__()) print(len(t))

night quarryBOT
#

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

001 | (,)
002 | -1
003 | Traceback (most recent call last):
004 |   File "<string>", line 6, in <module>
005 | SystemError: <built-in function len> returned NULL without setting an error
snow beacon
#

Let's say I wanted to make debugging difficult by raising a strange exception, but didn't want raise WeirdException() showing up in the traceback. Is there any way to edit a raised exception undetectably, so that it doesn't end up with any suspect lines like raise do_evil_things_to_traceback(WeirdException()) in the final context?

rugged sparrow
#

sys.excepthook

#

@snow beacon ^

#

It gets called when exceptions get raised and you can mod the traceback

snow beacon
#

Intriguing.

rugged sparrow
#

!e ```py
import sys
sys.excepthook = lambda *a:print(*a)
1/0

night quarryBOT
#

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

<class 'ZeroDivisionError'> division by zero <traceback object at 0x7fa938647480>
steep mural
#

Woah that's a thing?

rugged sparrow
#

!d sys.excepthook

night quarryBOT
#
sys.excepthook(type, value, traceback)```
This function prints out a given traceback and exception to `sys.stderr`.

When an exception is raised and uncaught, the interpreter calls `sys.excepthook` with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to `sys.excepthook`.

Raise an auditing event `sys.excepthook` with arguments `hook`, `type`, `value`, `traceback` when an uncaught exception occurs. If no hook has been set, `hook` may be `None`. If any hook raises an exception derived from [`RuntimeError`](exceptions.html#RuntimeError "RuntimeError") the call to the hook will be suppressed. Otherwise, the audit hook exception will be reported as unraisable and `sys.excepthook` will be called.

See also... [read more](https://docs.python.org/3/library/sys.html#sys.excepthook)
steep mural
#

!e

del __import__('sys').excepthook
raise RuntimeError('Lost sys.excepthook lol')
night quarryBOT
#

@steep mural :x: Your eval job has completed with return code 1.

001 | sys.excepthook is missing
002 | Traceback (most recent call last):
003 |   File "<string>", line 2, in <module>
004 | RuntimeError: Lost sys.excepthook lol
steep mural
#

O interesting

rugged sparrow
#

!e py import sys print(sys.getsizeof(()))

night quarryBOT
#

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

40
sick hound
#

b

rugged sparrow
#

!e py print(().__sizeof__())

night quarryBOT
#

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

24
edgy kelp
#

Do they grow with the same size for additional fields?

rugged sparrow
#

@edgy kelp the difference is because sys.getsizeof adds the objects garbage collector memory use

#

If you need to get the memory range of an object id(obj) -> id(obj) + offset you should always use obj.__sizeof__() as the offset

edgy kelp
#

huh that's a lot used by it then, what everything would fall into it?

rugged sparrow
#

well the tuple struct by itself has ref-count (8), base-type-ptr (8), size (8), py-object-ptr*len (8 * len) the gc holds 2 (8) refs to the tuple object (and any tracked objects afaik)

rugged edge
#

How to stop a "while" loop by adding a reaction, without the 'check' function @client.command() async def crash(ctx, arg:int): number = 1 r = round(random.uniform(1, 5), 2) print(r) masage = await ctx.send(content=None, embed = discord.Embed(title='ะšั€ะฐัˆ', description = f'{number}', colour = discord.Colour.green())) await masage.add_reaction('โœ…') while number < r: number = round(number + 0.01, 2) await masage.edit(content=None, embed = discord.Embed(title='ะšั€ะฐัˆ', description = f'{number}', colour = discord.Colour.green())) await asyncio.sleep(0.1) if number > 1.1: number = round(number + 0.05, 2) await masage.edit(content=None, embed = discord.Embed(title='ะšั€ะฐัˆ', description = f'{number}', colour = discord.Colour.green())) await asyncio.sleep(0.1)

astral rover
#

this isnt really fitting for the channel

sick hound
formal sandal
#

@shut venture This is off-topic for this channel. Besides, we don't allow recruitment on this server. If you're looking for collaborators for an open-source projects, say that explicitly, and post that in #python-discussion.

sick hound
#

i finished writing it. The ultimate data parser for lazy people

class ctx:
    def __init__(self, data):
        self.__dict__.update({k: ctx(v) if type(v) == dict else v for k, v in data.items()})


data  = {"test": "test",
         "test2": {"test3": "111"},
         "test4": [1, 2, 3],
         "test5": {"test6": {"test7": 69}}
         }

Val = ctx(data)

print(Val.test2.test3)

print(Val.test5.test6.test7)```

(output)

C:\Users\Tobi\AppData\Local\Microsoft\WindowsApps\python.exe C:/Users/Tobi/Documents/Scripting/Python/NewiFunny/test.py
111
69```

This is probably the most stupid thing ive written in a while.

formal sandal
#

@sick hound Maybe you'd like to see the attrdict third-party library? ๐Ÿ™‚

#

anyway, this is off-topic for this channel

wise valve
#

!e

print (test)
#

!e

print (input("test"))
#

!e

name = input ("test")
print (name)
#

!e

print (true-1)
night quarryBOT
#

@wise valve :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 'true' is not defined
wise valve
#

!e
print (True-1)

night quarryBOT
#

@wise valve :white_check_mark: Your eval job has completed with return code 0.

0
twilit grotto
#

take this to #bot-commands

hexed siren
#

i finished writing it. The ultimate data parser for lazy people
Add a __getattr__ method instead of adding attributes x)

steep mural
#

Val.test4.first would be nice tbh

vague cairn
#

Yeah I recently added

    if name in self.data:
        print("Warning: you said Record.{0} when you meant Record[{0}]".format(name))
        return self.data[name]```
To one of my classes. Then took much too long to figure out how to code the equivelent mirror code for `__setattr__()`
`super().__setattr__(name,value)` is much more friendly to property decorators than `self.__dict__[name]=value`
night quarryBOT
vague cairn
#

If I want to force everything to inherit from AttrObject, what should I do? I've tried just setting object = AttrObject
but that seems to only affect classes that explicitly derive from object, class whatever(object): pass
but not classes that implicitly derive from object:

    pass```
Is this one of those use cases of ctypes?
#

Or will mucking with ctypes create an infinite recursion when AttrObject accesses super()?

sick hound
#
class ArgCountException(Exception):
    pass

class AddX:
    def __getattr__(self, name: str) -> callable:
        if "add" in name:
            def wrapper(*args):
                if len(args) != int(name[3:]):
                    raise ArgCountException("Arguments don't match")
                return sum(args)

            setattr(self, name, wrapper)
            return wrapper

inst = AddX()

print(inst.add2(1, 2))
print(inst.add3(1, 2, 3))

Any better way of doing this? I know it's not good practice, I was just doing it for fun. It's supposed to create methods that add x amount of numbers. I just used __getattr__ to create the methdos

vague cairn
#

Yeah, that works.

#

If that's exactly what you want to do, I'm not clear wouldn't just use sum, but if you're asking how to use __getattr__() then yes.

#

But you may wish to add else: return super().__getattr__(name)

high garnet
#

is there a way for an imported module to log code entered interactively?

vague cairn
#

Oooh, I can imagine about six places to take that if you got it working.

high garnet
#

so I just wrote code to destructure mappings for fun:

a, c, d, b = D({'a': 1, 'b': 2, 'c': 3, 'd': 4})
print(a, b, c, d)

Output:

1 2 3 4

the thing is...it inspects source to find the order of assignments, so it won't work for REPL code

#

which is ๐Ÿ˜ฆ

vague cairn
#

Oh, I see.

#

That's cool, does it read the source or read the bytecodes?

high garnet
#

source

#

I felt that was faster (dev time wise)

#

it's p hacky since I just did it

vague cairn
#

It probably is a lot easier, and reading bytecodes has always struck me as pretty hacky too, but it might get you there in this case, let me go digging.

#

given that:
def test():
a, c, d, b = D({'a': 1, 'b': 2, 'c': 3, 'd': 4})
print(a, b, c, d)
disassembles into:
22 0 LOAD_GLOBAL 0 (D)
2 LOAD_CONST 1 (1)
4 LOAD_CONST 2 (2)
6 LOAD_CONST 3 (3)
8 LOAD_CONST 4 (4)
10 LOAD_CONST 5 (('a', 'b', 'c', 'd'))
12 BUILD_CONST_KEY_MAP 4
14 CALL_FUNCTION 1
16 UNPACK_SEQUENCE 4
18 STORE_FAST 0 (a)
20 STORE_FAST 1 (c)
22 STORE_FAST 2 (d)
24 STORE_FAST 3 (b)

23 26 LOAD_GLOBAL 1 (print)
28 LOAD_FAST 0 (a)
30 LOAD_FAST 3 (b)
32 LOAD_FAST 1 (c)
34 LOAD_FAST 2 (d)
36 CALL_FUNCTION 4
38 POP_TOP
40 LOAD_CONST 0 (None)
42 RETURN_VALUE

#

I think that it will be easy to find the 'load_const' two steps before the CALL_FUNCTION before currently on the stack. and grab it's parameter, but I've just got to remember how.

#

Nope it gets more complicated,

#

from the REPL: (g, x) = D(d) looks similar to the function, but `g, x = D(d) looks like:
1 0 LOAD_NAME 0 (D)
2 LOAD_NAME 1 (d)
4 CALL_FUNCTION 1
6 UNPACK_SEQUENCE 2
8 STORE_NAME 2 (g)
10 STORE_NAME 3 (x)
12 LOAD_CONST 0 (None)
14 RETURN_VALUE

high garnet
#

It probably is a lot easier, and reading bytecodes has always struck me as pretty hacky too, but it might get you there in this case, let me go digging.
@vague cairn yup, that's a great idea

#

after you mentioned it I went to poke around

#

I think bytecode analysis will be better

#

just need to figure out how to handle it...

vague cairn
#
from pprint import pprint
import dis
def ShowFrame(depth=0):
    f = sys._getframe(depth+1)
    pprint({k: getattr(f,k)
            for k in dir(f)
            if k not in {'f_builtins', 'f_globals', 'f_locals'}
            and k[0] != '_'
            })
    c = f.f_code
    pprint({k: getattr(c,k)
            for k in dir(c)
            if k[0] != '_'
            })
    dis.dis(c)
    
def D(amap):
    ShowFrame(1)
    f = sys._getframe(1)
    

def test():
    a, c, d, b = D({'c': 3, 'b': 2, 'd': 4, 'a': 1,})
    print(a, b, c, d)

test()
#

proves that we actually want to look after the function call to choose return order, not before.

high garnet
#

think the order of assignment can be deduced from the order of STORE_NAME calls

#

but it's important to also check for UNPACK_EX

vague cairn
#

I haven't seen that, when do you get it?

#

This is what I got:

    #ShowFrame(1)
    f = sys._getframe(1)
    C = [i for i in dis.get_instructions(f.f_code) if i.offset >f.f_lasti]
    ret = []
    size = 0
    for i in C:
        print(i)
        if i.opname == 'UNPACK_SEQUENCE':
            size = i.argval
            continue
        if i.opname in ('STORE_FAST', 'STORE_NAME'):
            try:
                ret.append( amap[i.argval])
            except KeyError:
                raise ValueError("Mapping does not include {}".format(amap[i.argval]))
            if len(ret)==size:
                return ret```
rugged sparrow
#

@vague cairn it is possible to make the inheritance object -> AttrObject -> everything else but itll be hacky

vague cairn
#

Or this: def D(amap): f = sys._getframe(1)#get frame C = [i for i in dis.get_instructions(f.f_code) if i.offset >f.f_lasti]#partition at current call size = C[0].argval#get size return [amap[i.argval] for i in C[1:size+1]] #get args (assume that all opnames are apropriate and that dis decoded argval's correctly.)

#

@rugged sparrow I mostly only want to do it for moduels that from FinalObject import *

rugged sparrow
#

Or if you made AttrObject inherit from type then you could make object inherit from AttrObject

vague cairn
#

Hmm, I've never used type. how different is it?

rugged sparrow
#

It's the the class that object inherits from

#

!e print(type(object))

night quarryBOT
#

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

<class 'type'>
vague cairn
#

So if I do that, I'll have to replicate other behavior of object as well?

#

No, because it's inheriting from it, it provides it itself, as long as I'm not using something it hasn't make yet.

rugged sparrow
#

Yea

#

Acc it would def be easier to just hook builtins.__build_class__

vague cairn
#

oooh

rugged sparrow
#
__builtins__.__build_class__ = lambda f,n,*s, b=__builtins__.__build_class__, **k:b(f,n,*set(s+(FinalObject,)),**k)
``` all classes made after this line is ran will subclass from FinalObject
#

@vague cairn ^

vague cairn
#

That doesn't look to hard, doesn't set risk randomizing the order, or does that even matter?

rugged sparrow
#

It'll only matter if you have a class subclassed from 2 classes that have the same layout

#

Cause it has a chance of messing with the mro

#

It's only there in case the class already subclasses FinalObject

#

If you can guarantee the only way FinalObject is added is via that hook then you can just do *(s+(FinalObject,))

vague cairn
#

Yeah, I had MRO errors immediatly, I fixed it with def NondupeTuple(seq): print(seq) ret = [] s=set() for i in seq: if not i in s: ret.append(i) s.add(i) print(ret) return tuple(ret) instead of set()

rugged sparrow
#

That works

high garnet
#

IIRC there is a way to specify a custom parser for a Python module

#

is there?

#

or am I remembering wrongly

formal sandal
#

!warn @haughty basin Spamming "okay" in several channels to pass the voice gate or for any other purpose is not okay.

night quarryBOT
#

:incoming_envelope: :ok_hand: applied warning to @haughty basin.

proper vault
#

@high garnet you might mean #coding or import hooks, those can afaik do that

high garnet
#

@high garnet you might mean #coding or import hooks, those can afaik do that
@proper vault yup, I know about import hooks, but there's something else

#

what do you mean #coding?

proper vault
#

not sure how exactly it works tbh

high garnet
#

that was it

#

thank you

#

I knew I remembered something like that but I couldn't find it

proper vault
#

braces from nekit uses it

#

if you need an example

high garnet
#

it's fine, I'll figure it out

#

thanks again!

next flame
#

wrong channel?

twilit grotto
#

most likely, yeah

wintry schooner
#

@winter geyser Hi, this video isn't related to this channel

ivory parcel
#

!e
def add_one(n):
return n+1

print(add_one(1))

night quarryBOT
#

@ivory parcel :white_check_mark: Your eval job has completed with return code 0.

2
ivory parcel
#

very useful function

rugged sparrow
#

!e ```py
import ctypes
known = {}
class Memory:
sentinel = object()
def init(self, obj):
self._size = type(obj).sizeof(obj)
self._memory = (ctypes.c_char * self._size).from_address(id(obj))
self._addr = id(obj)
self._obj = obj

@classmethod
def at_address(cls, addr, size):
    self = cls.__new__(cls)
    super(cls, self).__init__()
    self._memory = (ctypes.c_char * size).from_address(addr)
    self._addr = addr
    self._obj = Memory.sentinel
    self._size = size
    return self

def at_offset(self, offset, size=8):
    return Memory.at_address(self._addr + offset, size)

def __repr__(self):
    return f'Memory[of={self._obj}]' if self._obj is not Memory.sentinel else f'Memory[size={self._size}]'

@property
def raw(self):
    return self._memory

@property
def object(self):
    return self._obj

def _get_types(self):
    if t := known.get(type(self._obj)):
        return t(self._obj)
    raise Exception(NotImplemented)

def map(self, *types):
    if not types:
        types = self._get_types()

    offset = 0
    return tuple(typ.from_buffer(
                self.at_offset(
                    (offset:=offset + ctypes.sizeof(typ)) - ctypes.sizeof(typ), ctypes.sizeof(typ)
                ).raw
            ) for typ in types)

def free(self):
    self._obj = Memory.sentinel

x = 1000
Memory(x).at_offset(24).map(ctypes.c_ssize_t)[0].value = 5
print(x + x)

night quarryBOT
#

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

10
sick hound
#

!e

def convert_to_bin(st):
    return ' '.join(format(ord(x), 'b') for x in st)
print(convert_to_bin('testing'))
night quarryBOT
#

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

1110100 1100101 1110011 1110100 1101001 1101110 1100111
next flame
#

why format()?

sick hound
#

cuz

#

wait lemme see if theres a difference

#

i forget why i had that there

#

!e

def convert_to_bin(st):
    return ' '.join(ord(x), 'b') for x in st)
print(convert_to_bin('testing'))```
night quarryBOT
#

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

001 |   File "<string>", line 2
002 |     return ' '.join(ord(x), 'b') for x in st)
003 |                                  ^
004 | SyntaxError: invalid syntax
sick hound
#

oh wait

#

!e

def convert_to_bin(st):
    return ' '.join(ord(x), 'b' for x in st)
print(convert_to_bin('testing'))```
night quarryBOT
#

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

001 |   File "<string>", line 2
002 | SyntaxError: Generator expression must be parenthesized
sick hound
#

thats why

#

oh wait i could just remove the comma

#

!e

def convert_to_bin(st):
    return ' '.join(ord(x) 'b' for x in st)
print(convert_to_bin('testing'))```
night quarryBOT
#

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

001 |   File "<string>", line 2
002 |     return ' '.join(ord(x) 'b' for x in st)
003 |                            ^
004 | SyntaxError: invalid syntax
sick hound
#

nope nevermind

next flame
#

!e ```python
def convert_to_bin(s):
return ' '.join(bin(ord(c))[2:] for c in s)
print(convert_to_bin("testing"))

night quarryBOT
#

@next flame :white_check_mark: Your eval job has completed with return code 0.

1110100 1100101 1110011 1110100 1101001 1101110 1100111
sick hound
#
c=lambda _:' '.join(bin(ord(i))[2:]for i in _);c('testing')
#
print(lambda _:' '.join(bin(ord(i))[2:]for i in _))('testing')
#

Oh wait

#

!e

c=lambda _:' '.join(bin(ord(i))[2:]for i in _);c('testing')
print(c('hi'))```
night quarryBOT
#

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

1101000 1101001
sick hound
#

!e

print(lambda _:' '.join(bin(ord(i))[2:]for i in _))('testing'))
night quarryBOT
#

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

001 |   File "<string>", line 1
002 | SyntaxError: unmatched ')'
sick hound
#

Bruh

#

Ah

#
print((lambda _:' '.join(bin(ord(i))[2:]for i in _))('testing'))
#

!e

print((lambda _:' '.join(bin(ord(i))[2:]for i in _))('testing'))
night quarryBOT
#

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

1110100 1100101 1110011 1110100 1101001 1101110 1100111
lusty crown
#

!e?

#

!e

night quarryBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*

grave rover
#

!e ```py
print((lambda _:' '.join(f"{ord(c):b}"for c in _))('testing'))

night quarryBOT
#

@grave rover :white_check_mark: Your eval job has completed with return code 0.

1110100 1100101 1110011 1110100 1101001 1101110 1100111
grave rover
#

2 chars shorter Cool

#

Another one, though 4 chars longer than mine:```py
print((lambda _:' '.join(f"{c:b}"for c in _.encode()))('testing'))

proper vault
#

what is the point of the lambda?

grave rover
#

to make it a callable I guess?

#

everyone before me did it so I just copied

proper vault
#

print(*(f"{ord(c):b}"for c in'testing'))

sick hound
#

Thatโ€™s way better, but I used lambdas assuming that the OP is going to use the function somewhere else

#

Wait

#

You could skip the space after โ€˜inโ€™

#

Ah

grave rover
#

Hmm, let's say for some reason you have data of two or more types, but crammed into the same list, would you rather have ABCABCABCABC or AAAABBBBCCCC, assuming all are equal size of course

distant wave
#

Well, for what purpose?

#

Python's lists, IIRC are just pointers (usually) and as a result the datatype ordering doesn't matter much except when you might want to zip/unzip the contents

#

And ABCABCABC to (a,b,c), (a,b,c) is simple enough with zip(a[::3], a[1::3], a[2::3]), and AAAABBBBCCCC to (a, b, c) is also simple enough with zip(a[:len(a)/3)], a[len(a)/3:len(a)*2/3)], a[2*len(a)/3):]).

#

So I suppose the first would be preferable, but if they are related data, I'd actually prefer the list of tuples over both

proper vault
#

the latter is generally better for cache friendliness, but either is trivial to iterate over.

next flame
#

just use grouper from itertools recipies

#

and then it should have the same cache friendliness

proper vault
#
f'''{f"""{f'{f"{ {}=}"}'=}"""=}'''
frozen holly
#

what the

unreal compass
#

@proper vault what was that formatting?

distant wave
#

!f-strings

night quarryBOT
#

In Python, there are several ways to do string interpolation, including using %s's and by using the + operator to concatenate strings together. However, because some of these methods offer poor readability and require typecasting to prevent errors, you should for the most part be using a feature called format strings.

In Python 3.6 or later, we can use f-strings like this:

snake = "Pythons"
print(f"{snake} are some of the largest snakes in the world")

In earlier versions of Python or in projects where backwards compatibility is very important, use str.format() like this:

snake = "Pythons"

# With str.format() you can either use indexes
print("{0} are some of the largest snakes in the world".format(snake))

# Or keyword arguments
print("{family} are some of the largest snakes in the world".format(family=snake))
median lark
#

How do you enter the python editor in disc?

vague cairn
#

my favorite python editors are the built in IDLE and 'sublime text' but lots of multi-language code editors can detect the .py extention and highlight the syntax apropriately.

#

Is that what you are asking?

next flame
#

!code

night quarryBOT
#

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:

```python
print('Hello world!')
```

Note:
โ€ข These are backticks, not quotes. Backticks can usually be found on the tilde key.
โ€ข You can also use py as the language instead of python
โ€ข The language must be on the first line next to the backticks with no space between them

This will result in the following:

print('Hello world!')
next flame
#

@median lark is this what you were looking for?

median lark
#

Yes!

#
def ascii_arrow(line_symbol):
    if line_symbol == ")" or "(" or "*" or "&" or "^": 
        print("<" + line_symbol + line_symbol + line_symbol + line_symbol + line_symbol + ">")   
    else:
        print("  " + "^")
        print("  " + line_symbol)
        print("  " + line_symbol)
        print("  " + line_symbol)
        print("  " + line_symbol)
        print("  " + line_symbol)
        print('<--->')
#

Could someone tell me why these if/else statement isn't working correctly?

sick hound
#

!or

night quarryBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
sick hound
#

@median lark

next flame
#

also this is the wrong channel

#

please take a look at this channels description

median lark
#

Sorry, I couldn't figure it out

vague cairn
#

@median lark Also what you want might be if line_symbol in (")", "(", "*", "&", "^"):
Which constructs a tuple, then checks membership in it of line_symbol

vague cairn
#

@sick houndtechnically I have to ask after your sanity, because a binary file shouldn't be converted to strings wholesale, or it wouldn't be a binary file...
But if I had to do that and the file were small enough it would look something like

   with open(filename, 'rb') as file:
       data_bytes = file.read() #default size to read is until end of file
   return data_bytes.decode()# turn the bytes data in to string data.```
Except for a true binary file this always fails on the .decode() step, and for a file with a commonly used text encoding format, it's easier to treat it as a text file with:
```def read_text(filename, encoding = 'utf-8'):
   with open(filename, 'r', encoding=encoding) as file:
       string = file.read() #default size to read is until end of file
   return string```

1) For a larger file I'd look into using a loop and providing a size to file.read()
2) What is much more common for binary files that include strings in them, you're usually read()ing for objects whose length you already know(because it is specified in the file format specification), converting the bytes that ought to be strings to string and the bytes that ought to be int to int, etc.
next flame
#

you can just do line_symbol in ")(*&^"

sick hound
#

technically I have to ask after your sanity, because a binary file shouldn't be converted to strings wholesale, or it wouldn't be a binary file...
But if I had to do that and the file were small enough it would look something like

   with open(filename, 'rb') as file:
       data_bytes = file.read() #default size to read is until end of file
   return data_bytes.decode()# turn the bytes data in to string data.```
Except for a true binary file this always fails on the .decode() step, and for a file with a commonly used text encoding format, it's easier to treat it as a text file with:
```def read_text(filename, encoding = 'utf-8'):
   with open(filename, 'r', encoding=encoding) as file:
       string = file.read() #default size to read is until end of file
   return string```

1) For a larger file I'd look into using a loop and providing a size to file.read()
2) What is much more common for binary files that include strings in them, you're usually read()ing for objects whose length you already know(because it is specified in the file format specification), converting the bytes that ought to be strings to string and the bytes that ought to be int to int, etc.

@vague cairn Why I'm doing this is so I can translate any file to pixels on an image and then take the images and create a video which I can then upload to youtube.... free cloud storage

stark fable
#
f'''{1:{f"""{1:{f'{1:{f"{1:{1:1}}":1}}':1}}""":1}}'''```
formal sandal
#

@sick hound That won't work -- youtube only works with lossy compression.

#

A video file isn't literally a collection of 2d arrays of pixels.

sick hound
#

@sick hound That won't work -- youtube only works with lossy compression.
@formal sandal I have ways around youtube's compression

#

Just leave that part up to me

#

also could just store the data as qr codes or barcodes

formal sandal
#

yeah, or store videos of very quickly scrolling plaintext ๐Ÿ™‚

#

and then use OCR to retrieve the data

sick hound
#

that would be even more complicated

formal sandal
#

Oh, by the way, you can just store Base85 in subtitles!

sick hound
#

Yea but then I'd still need to store something for video

formal sandal
#

But I'm pretty sure that would be abuse of YouTube anyway, and it's not very nice.

sick hound
#

which would be a waste of data

#

the point of this is to reduce data size

gusty igloo
#

Hello, how can I create a file Browser of another pc (socket) with Python?

next flame
formal sandal
vague cairn
#

I bet you could make a 1x1 video of a black pixel (or 4k of them for that matter, as long as they stayed black, they'd compress really well) and put all the subtitles you wanted!

sick hound
#

Can someone help me

#

QUESTION 7
Write a for loop that prints the numbers 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100

formal sandal
high garnet
#

@formal sandal were you the one who wrote code for destructuring mappings

formal sandal
#

yep

#
def destructure(obj):
    if not isinstance(obj, dict):
        raise TypeError(f"{obj} is not a dict")
    parent_frame = inspect.currentframe().f_back
    line = inspect.getframeinfo(parent_frame).code_context[0]
    var_names = map(str.strip, line.split("=")[0].split(","))
    for var_name in var_names:
        yield obj[var_name]

a, c, b = destructure({"a": 1, "b": 2, "c": 3})
#

won't work in @night quarry, though

high garnet
#

oh, okay

#

yeah so I did that

#

then I realised it wouldn't work in the REPL

#
>>> a, b = D({'c': 1, 'a': 2, 'b': 3})
>>> a
2
>>> b
3
#

so like now I parse the bytecode of the calling line

#

which, unfortunately, still doesn't work in functions in the REPL

vague cairn
formal sandal
#

works in IPython

high garnet
#

works in IPython
@formal sandal yeah because it stores the source, right

#

but well I'm happy with where I am I guess

#

nontrivial to make it work in functions

#

now just not sure if I should use it in production code ๐Ÿค”

formal sandal
#

wdym? works fine in functions for me

high garnet
#

wdym? works fine in functions for me
@formal sandal in vanilla REPL?

formal sandal
#

why would you run production code in REPL ๐Ÿ˜›

high garnet
#

yeah I know it works in IPython because it stores whatever you type into it

#

why would you run production code in REPL ๐Ÿ˜›
@formal sandal ๐Ÿ˜ก BECAUSE!

#

but using IPython is cheating ๐Ÿฅด

vague cairn
#

But the error detection and messages are not up to par across all three logic branches.

formal sandal
#

That's very smart!

#

and it works if the line takes more than one... line

vague cairn
#

True!

formal sandal
#

What does it do with star-unpacking?

#

like a, b, (*c,), d = ...

vague cairn
#

for a, b, *c, d it works properly. for a, b, (*c,), d I couldn't interpret what that would even mean, so I couldn't make it pack up the values properly for that.

formal sandal
#

so a, b, *c, d = desrtucture(a_dict) unpacks a_dict["c"] into c?

vague cairn
#

No it unpacks, a, into a, b into b, d into d and a dict of all the remaining key/value pairs into c. Which is sort of what * means, except interpreted differently for being a dict we're unpacking instead of a tuple.

#

Whatever that var is, it ignores the var name and just packs up the unused part of the dict to plop into it.

formal sandal
#

oh, makes sense

vague cairn
#

a, b, (c, d, e, ), f = (1,2,(3,4,5),6) would mean what it ought to mean. (every var has the coresponding digit)
a, b, (*c), d = (1,2,(3,4,5),6) would mean that c has (3,4,5) in it, but so would
a, b, c, d = (1,2,(3,4,5),6)
Why use the extra parentheses to tell it to unpack the inner tuple for 1 to 1 corespondence, and then pack them all back into one var again anyway?
a, b, (*c, d), e = (1,2,(3,4,5),6) at least has a meaning.
c would == 3,4 and d would == 5
But ... comprehending the bytecodes, then manipulating them back in time to get that to handle properly was too much for my brain without adding another layer of abstraction to automate away some of the complexity, and it didn't seem like it would add any functionality.
If I did manage all that extra complexity in order to force a, b, (*c, d),e = destruct() to mean the same thing as a, b, *c, d, e = destruct()

rugged sparrow
#

@vague cairn btw, if you want to make this work without a apparent function call, you can patch dict.__iter__

vague cairn
#

@stark fable
Those are some impressive f-strings. Can you make a quine?

#

OOOOH, hmm, so it should check its code context and decide whether it's a for loop and ought to iterate over keys() like normal, or in a tuple context and destructure.

rugged sparrow
#

you could do that. then it would look like part of the lang. or you could just break dicts default iter

vague cairn
#

๐Ÿ™‚

#

Depends on which kind of troll one wishes to be.

#

"Why doesn't this work, I saw someone else doing this" to, "you write code that can't possibly work, but does, then when I try to fix it, it screams and dies instead."

#

๐Ÿ˜„

rugged sparrow
#

yeee

#

the best kind of troll

vague cairn
#

I wonder if I can analize a for loop sufficiently to let it decide whether to iterate over keys() over items() or to destructure()...

#

But at some point it would be less of 'I'm a troll' and cross the line into 'don't steal my code, you will be sorry'

twilit grotto
vague cairn
#

And I'm still here aren't I?

#

Since I found this place last week, I've barely left to sleep and go to work.

twilit grotto
#

well...that sounds quite unhealthy

rugged sparrow
#

!e ```py
from ctypes import *
def new_iter(self):
for i in self.items():
yield i

c_void_p.from_address(id(dict) + (8*27)).value = cast(CFUNCTYPE(py_object, py_object)(new_iter), c_void_p).value

x = {'a':1}
print(*x)```

night quarryBOT
#

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

('a', 1)
rugged sparrow
#

@vague cairn ^

#

for reference on replacing dict.__iter__ incase you decide to go full cursed

vague cairn
#
        """A better dict iter"""
        c = code_split(1)['after_call']
        if c[0].opname == 'GET_ITER' and c[1].opname == 'FOR_ITER':
            if c[2].opname == 'UNPACK_SEQUENCE':
                return amap.items()
            else:
                return amap.keys()
        elif c[0].opname == 'UNPACK_SEQUENCE':
            return destructure(amap, 1)
        return amap.keys()```
stoic whale
#

?

#

?

vague cairn
#

Humm, that breaks something, once I put it in a better order.

rugged sparrow
#

@vague cairn do yield from iter(whatever)

vague cairn
rugged sparrow
#

Not return iter(whatever)

vague cairn
#

No that makes it worse.

#

Now it's working.

rugged sparrow
#

Oh weird

#

Still if it works dope

vague cairn
#

I'm sure it could have been made to work with yield from, but it made getting the first version working difficult, perhaps now that I have the second version working, it would be simpler if I refactored for a generator instead.

sick hound
#

@rugged sparrow How does c_void_p.from_address(id(dict) + (8*27)).value = cast(CFUNCTYPE(py_object, py_object)(new_iter), c_void_p).value work?

zealous widget
#

the destructuring code can also be used to make a "none aware" assignment:


In [1]: from none_aware import maybe

In [2]: x = 2
   ...: y = None
   ...: x = maybe(y)

In [3]: x
Out[3]: 2

In [4]: x = maybe(32)

In [5]: x
Out[5]: 32
#

which is roughly x = y if y is not None else x

rugged sparrow
#

@sick hound at a basic level, 8*27 is the offset where the original duct.__iter__ is located. The code there allows for changing the function at that location to a new one

vague cairn
#

So the basic structure of a for loop is:
LOAD_GLOBAL(function name)
CALL_FUNCTION(number of args)
GET_ITER????
FOR_ITER(exit address)
(code to pack cell vars)
(loop code)
unconditional jump back to FOR_ITER
exit address: (whatever comes next)
if the function returns an iterable, the frame's instruction pointer will be pointing to CALL_FUNCTION
if the function is an .__iter__(self) method that returns an iterator, there will be no CALL_FUNCTION instruction and the frame instruction pointer will be pointing to GET_ITER
if the function is a generator that uses yield or yield from, the frame instruction pointer it will pointing to FOR_ITER.
So yes, with yield from I could refactor it half as big.

#

Is 8*27 imply 28th pointer in an array of 64bit pointers?

formal sandal
#

yes

rugged sparrow
#

In hindsight, it should be ctypes.sizeof(ctypes.c_ssize_t)*27

#

@vague cairn ^

vague cairn
#

Got it, change applied.

vague cairn
#

So ... my code seems to run on 3.8 and not 3.5.

#

@rugged sparrow is there a refcount we can increment or decrement to keep it from throwing a seg fault as it shuts down?

#

or should I try to register a shutdown hook to put it back?

rugged sparrow
#

You can save the original value to a variable and restore it at shutdown

vague cairn
#

I got it working with: ```def dict_iter_register():
"""installs new_iter() as dict.iter() enabling items() sensing and tuple <= dict unpacking."""
label = ctypes.sizeof(ctypes.c_ssize_t)*27
oldv = ctypes.c_void_p.from_address(id(dict) + label).value
ctypes.c_void_p.from_address(id(dict) + label).value = ctypes.cast(ctypes.CFUNCTYPE(ctypes.py_object, ctypes.py_object)(new_iter), ctypes.c_void_p).value

def deregister():
    ctypes.c_void_p.from_address(id(dict) + label).value = oldv
    atexit.unregister(deregister)
atexit.register(deregister)
return deregister```
#

And I'll leave figuring out how to handle python3.5 bytecode variations tomorrow.

thin trout
#

I was going to say "what the f*ck" but then I realized which channel I was in

formal sandal
#

I still say that every time

vague cairn
rugged sparrow
#

!e ```py
_id = lambda o:1 .class(().class.base.repr(o).strip('>').split(' ')[-1],16)
print(id(1))
print(_id(1))

night quarryBOT
#

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

001 | 140706928808192
002 | 140706928808192
rugged sparrow
#

^ id with no builtins

copper thunder
#

joli ^^

slim yarrow
#

the intent was merely to reduce it to 1 line, not to make it overly esoteric

proper vault
#

Consider something like

{70<=a<=79:'A', ...}.get(True, 'E')
slim yarrow
#

edited

formal sandal
#

rather .get(1,'E') ๐Ÿ™‚

#

shorter by 3 characters

slim yarrow
#

edited to do that

earnest wing
#

You can replace the <= with < if you adjust the bounds by 1, saving a handful of bytes

#

Your input is all integral anyways

formal sandal
#

Also, you can do 79 or -> 79or in every case

fervent hull
#

Given that these all evaluate to bool, can't we use & | instead of and or?

formal sandal
#

it will screw up precedence

#

a < b | c < d = a < (b | c) < d

fervent hull
#

You're right

formal sandal
#

also,

def something():...
something=lambda:...

counterintuitively, def is 1 character longer.

high garnet
#

nothing binds tighter than ., right?

#

it's not even in the operator precedence list

#

so that's my guess

formal sandal
#

I'm pretty sure covalent bonds are stronger lemon_unamused

#

Well, it's not an operator

#

because the right side of it is not an expression

twilit grotto
#

my love for you is stronger still

formal sandal
#

but it binds stronger, yes

#

"A" + "B".lower() == "Ab"

next flame
#

it would be pretty counterintuitive if it didn't

#

inb4 someone writes some ast hackery to break it

high garnet
#

๐Ÿ˜ฆ

#

oh well I guess my lens dream syntax is dead

formal sandal
#

I tried watching a video on lenses, but after the words "costate comonad" my mind went "Nope, goodbye, and have a nice day"

#

I get that it's an accessor function, like a getter+setter

#

but not more

next flame
#

all I remember is that it's some weird ass fp thing

#

just like a lot of fp things

snow beacon
#

At the surface, it's bringing object oriented properties to functional programming. However, there's a fair bit beneath the surface to make sure you can use basically anything as a lens.

high garnet
#

I get that it's an accessor function, like a getter+setter
@formal sandal basically this

>>> d = {'a': {'b': {'c': {'d': 1}}}}
>>> lens = ItemLens() >> 'a' >> 'b' >> 'c' >> 'd'
>>> lens(d).get()
1
>>> lens = ItemLens() >> 'a' >> 'b' >> 'e' >> 'd'
>>> print(lens(d).get_optional())
None
#

it's nice for accessing deeply nested values in immutable objects and creating copies with modified values

#

in Python it's kinda meh I guess

rugged sparrow
#

finally got this working for any dunder without having to explicitly make a map of them

@patch(int, '__iter__')
def int_iter(self):
    yield from range(self)
#
>>> @patch(str,'__getitem__')
... def str_getitem(self, arg):
...     print(self, arg)
...     return _orig(self, arg)
... 
size=10 base_addr=104 secondary_addr=3
got func_ptr=c_void_p(140298571840192) from struct_addr=140298576729376
size=3 base_addr=112 secondary_addr=1
got func_ptr=c_void_p(140298571022384) from struct_addr=140298576726176
patching func_ptr=c_void_p(140298571840192)
patching func_ptr=c_void_p(140298571022384)
>>> 'a'[0]
a 0
'a'
>>> 'a'[0:1]
a slice(0, 1, None)
'a'
``` it also supports _orig for calling the original without recursion issues
narrow ridge
#

WHAT IS HAPPENING?

south bone
#

yeah

rugged sparrow
#

that code allows for hotswapping base class dunders

#

like list.__getitem__ or str.__add__

narrow ridge
#

im confused

rugged sparrow
#

it lets you replace the original methods

south bone
#

im confused
@narrow ridge I mean, this is esoteric stuff

narrow ridge
#

pretty interesting that people understand that

south bone
#

Yeah

#

Itโ€™s something you kind of have to actively seek out

restive void
#

@rugged sparrow Planning to publish to PyPI?

rugged sparrow
#

needs some polishing but probably

next flame
#

whats the difference between this and forbidden fruit?

rugged sparrow
#

patchy is fully dynamic and thus can patch just about any dunder

#

!e ```py
from forbiddenfruit import curse
def int_iter(self):
yield from range(self)

curse(int, 'iter', int_iter)
[*10]

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 |   File "/usr/local/lib/python3.8/site-packages/forbiddenfruit/__init__.py", line 412, in curse
004 |     _curse_special(klass, attr, value)
005 |   File "/usr/local/lib/python3.8/site-packages/forbiddenfruit/__init__.py", line 329, in _curse_special
006 |     tp_as_name, impl_method = override_dict[attr]
007 | KeyError: '__iter__'
rugged sparrow
#

vs with patchy ```py

@patch(int, 'iter')
... def int_iter(self):
... yield from range(self)
...
[*10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]``` @next flame

next flame
#

oh nice

sick hound
#

@rugged sparrow Where do you learn this stuff?

#

Do you just figure it out by experimenting by yourself?

#

I tried reading your code, and although itโ€™s very readable, I literally understand nothing there conceptually

#

All I can see is that youโ€™re using ctypes and some pointers. But how are you able to manipulate methods of primitive types using pointers?

#

Whatโ€™s the theory behind this? Any resources I can go to, to learn more about this?

rugged sparrow
#

It's mostly looking through the cpython source code and understanding what the memory structures look like conceptually

#

@sick hound and lots of experimentation

sick hound
#

I see, thanks

marsh void
#

@rugged sparrow seems really CPython-magical, I wonder what happens on other implementations

rugged sparrow
#

it def is cpython magic, prob wouldnt work on other implementations

slate wasp
#

I'm trying to delete a function using a decorator. Basically, this is what I'm looking for: ```py
@delete_function
def foo():
pass

#

This would mean that foo isn't a part of globals. Is this even possible?

potent cliff
#

I was about to ask you what in the world you were thinking, then I realized what channel I was in

slate wasp
#

Hahah yeah

rugged sparrow
#

@slate wasp your goal is something like ```py
foo() #works

@delete_function
def foo():pass

foo() # no longer works

slate wasp
#

Basically. But that it doesn't exist at all. I know how to set it to None, but that's not what I'm looking for

rugged sparrow
#

so decorators become something like ```py
def foo():
pass
foo = delete_function(foo)

#

so if you want to completely invalidate foo as a name you'd need to somehow have a function that gets ran after that assignment that runs del container[foo.__name__]

#

you could probably use a sys.tracefunc that unsets itself

slate wasp
#

Doing del globals()["foo"] works perfectly, but that can't really be done from the decorator (where things will probably have to be done)

#

I'll look into that

formal sandal
#

@slate wasp you can just repost your code here, that'd be more accurate ๐Ÿ™‚

slate wasp
#

I think the most important part is the deletion, right? Maybe something with creating another one makes things odd

#
def call_bar(fn):
    old_name = fn.__name__
    new_name = "bar"
    fn.__name__ = new_name
    fn.__qualname__ = new_name
    globals()[new_name] = fn

@call_bar()
def say_hello_there():
    print("hello there")
#

This is it (with some minor tweaks). I'm basically trying to rename a function

#

@rugged sparrow in other words, I'm trying to change the name of a function and not let the previous name be valid. My deletion question may have been an XY-question to some extent

rugged sparrow
#

you could set the previous name to a func like ```py
def fail(*args,**kwargs):
raise Exception('na')

slate wasp
#

You mean making it raise an error from being used?

rugged sparrow
#

yea

slate wasp
#

That would still not remove it, though. You could do something like foo and still see that it's a function

#

Maybe there is no way to do this with a decorator?

rugged sparrow
#

well if you wanted to go full nuclear, you could install a tracefunc that unsets itself after it runs twice, on the second run it would be the frame after the assignment

#

so you could delete foo from being a valid name

slate wasp
#

What are tracefuncs?

rugged sparrow
#

!d sys.settrace

night quarryBOT
#
sys.settrace(tracefunc)```
Set the systemโ€™s trace function, which allows you to implement a Python source code debugger in Python. The function is thread-specific; for a debugger to support multiple threads, it must register a trace function using [`settrace()`](#sys.settrace "sys.settrace") for each thread being debugged or use [`threading.settrace()`](threading.html#threading.settrace "threading.settrace").

Trace functions should have three arguments: *frame*, *event*, and *arg*. *frame* is the current stack frame. *event* is a string: `'call'`, `'line'`, `'return'`, `'exception'` or `'opcode'`. *arg* depends on the event type.

The trace function is invoked (with *event* set to `'call'`) whenever a new local scope is entered; it should return a reference to a local trace function to be used for the new scope, or `None` if the scope shouldnโ€™t be traced.... [read more](https://docs.python.org/3/library/sys.html#sys.settrace)
slate wasp
#

Ah, so I could make it delete itself before anything happens the second time?

rugged sparrow
#

yea

#

its hacky but if thats what you really want it should work

slate wasp
#

Ah, nice. I assume it would also be possible to make sure that it only applies to functions decorated with that specific decorator?

rugged sparrow
#

yea but how to do that is up to you

slate wasp
#

Yep. Thanks :)

formal sandal
#

lmao I found a trick

#

so funny

#

first of all, you can use tuple unpacking in with:

#
with manager as (a, b, c):
    ...
#

A context manager can suppress errors, which is a new thing for me (this isn't the trick)

#

If you throw in the __enter__ method, it will not suppress it

#

but

rugged sparrow
#

yea you can actually use that to oneline try/except

formal sandal
#

!e

class Manager:
    def __enter__(self):
        raise ValueError
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):    
        print(exc_type, exc_value, exc_tb)
        return True

with Manager() as m:
    ...
night quarryBOT
#

@formal sandal :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 10, in <module>
003 |   File "<string>", line 3, in __enter__
004 | ValueError
formal sandal
#

^ so if you throw in __enter__, it doesn't go to __exit__

#

but

#

!e

class Manager:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):    
        print(exc_type, exc_value, exc_tb)
        return True

with Manager() as (a, b, c):
    ...
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

<class 'TypeError'> cannot unpack non-iterable Manager object <traceback object at 0x7f96a07bbb00>
formal sandal
#

if unpacking fails, the exception goes to __exit__

rugged sparrow
#

ohhh thats interesting

formal sandal
#

so now I can do evil pattern matching!!

#
with match(arg) as (case, m):
    with case("(int, int)") as case.m:
        print(m[0], m[1])
    with case("_") as case.m:
        print(m, "-- literally anything")
#

let me try it now

#

Or maybe just

with match(arg) as case:
    with case("(int, int)") as _, m:
        print(m[0], m[1])
    with case("_") as _, m:
        print(m, "-- literally anything")
rugged sparrow
#
>>> import muttuple
>>> x = ()
>>> x.append(1)
>>> print(x)
(1,)
>>> dir(x)
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> 
``` @formal sandal notice anything weird?
formal sandal
#

nah, it's fine ๐Ÿ™‚

#

wait, is x also a metaclass?

high garnet
#

oh no

#

they're doing it again...

#

why not just case(int, int)

formal sandal
#

cause there may be more complicated patterns, with custom classes and stuff

high garnet
#

for example?

formal sandal
#

well, for example, I want to use pattern matching to parse an AST

#
with match(arg) as case:
    with case("Quoted(Name(name))") as _, m:
        print(1, m.name)
    with case("Quoted(Sexpr(Name(name), String(value)))") as _, m:
        print(2, m.name, m.value)
    with case("Quoted(_)") as _, m:
        print(3, "aaaAA!")
    with case("other") as _, m:
        print(4, m.other)
rugged sparrow
#

@formal sandal x is a tuple

high garnet
#

I'm sure with sufficient work it's possible to get around using strings ๐Ÿ™‚

#

@formal sandal x is a tuple
@rugged sparrow I think it was sarcasm

formal sandal
#

@rugged sparrow Yeah, that's the elephant in the room, I thought I missed something subtle ๐Ÿ™‚

rugged sparrow
#

oh lmao

high garnet
#

okay I guess you wouldn't be able to bind to arbitrary names

rugged sparrow
#

it uses the patchy module i wrote in the past couple days

high garnet
#

if you didn't use strings

rugged sparrow
#
>> x = (0,)
>>> x[0] = 1
>>> print(x)
(1,)
>>> ``` also enables this
formal sandal
#
x[0] = x

๐Ÿ™‚

high garnet
#

๐Ÿ›‘

formal sandal
#

I did that manually, and it actually prints out fine

#

it's like... they have foreseen that

rugged sparrow
#

its because they recommend using tuples as python compatible arrays in cpython extensions

#
>>> x[0] = x
>>> print(x)
((...),)
>>> ```
slate wasp
#

I'm trying to apply a decorator to all global functions created. Do you know of a way to do this?

#

Or at least do something on the creation of every function

zealous widget
#

you could load the module and then decorate each function in it

slate wasp
#

I'm thinking that this should happen continuously

#

If I do it in an interactive shell, it should still apply the decorator to all functions created

#

@zealous widget or if this isn't really possible with decorators, any other way of performing some code in response to newly created functions would be great

zealous widget
#

well, you can subclass the console to do whatever when you enter stuff --- ipython let's you run input through arbitrary functions as well

slate wasp
#

Hmm. It doesn't sound like I'll be able to make this work for "normal" programs, then. If I just have global function being created in a program, I'd like them to be noticed/affected by this as well

zealous widget
#

is a user typing something in or something?

slate wasp
#

For both of these cases, I'd like the functions to be decorated, or at least that python notices that they've been created and let's me add some hook: ```py

Whatever black magic is needed

def foo():
pass
def bar():
pass

```py
>>> def foo():
...     pass
>>> def bar():
...     pass
zealous widget
#

what i mean is, if you have some app with your own python console --- you can add whatever logic you want to the push method of the console

slate wasp
#

Hmm, okay. I assume that wouldn't let me do it quite as above?

zealous widget
#

if you want to decorate all functions in some file --- that's doable too

slate wasp
#

Doing it continuously? Both of the cases above should lead to the functions being auto-decorated

zealous widget
#

how do you load a file continuously

slate wasp
#

Well, that mostly applies to the second case

zealous widget
#

second case you need to change the push method of the console

#

you could do as in the example above --- but before you clear the stack, check if it's a valid function with ast.parse or something similar and if it is --- decorate it

slate wasp
#

Hmm, okay. I'll have to look into that

#

Thanks

zealous widget
#

it's not the most relevant code, but it's the only time i've subclassed console

slate wasp
#

Yeah

zealous widget
slate wasp
#

Oh wow. That's looks great

zealous widget
#

project needs some love -- it hasn't been touched since early in the year

formal sandal
#

@zealous widget It's like 3d models embedded in HolyC ๐Ÿ‘€

sick hound
#

holyc lmao

formal sandal
#

Pattern matching is working, yay https://repl.it/@int6h/WithPatternMatching#main.py

def what_is(arg):
    print(arg, "is", end=" ")
    with match(arg) as case:
        with case("Thing(x)") as [m]:
            print("a thing with", m.x)

        with case("Pair(Thing(x), Thing(_))") as [m]:
            print("a pair with a thing of", m.x, "and some other thing")

        with case("_") as [m]:
            print("something completely different")


what_is(42)
what_is(Thing(42))
what_is((1, 5))
what_is((Thing(7), Thing(2)))

output:

42 is something completely different
Thing(42) is a thing with 42
(1, 5) is something completely different
(Thing(1), Thing(2)) is a pair with a thing of 7 and some other thing
#

Now I only have to make automatic derivation for dataclasses

zealous widget
#

i've been doing a lot of my own code generators lately

#

this is more fun than dataclasses:

In [1]: from pigsty.q import q
   ...:
   ...: class Expr(q):
   ...:     pass
   ...:
   ...: class Op(Expr):
   ...:     name, func
   ...:
   ...: class BinOp(Op):
   ...:     left, right
   ...:
   ...: class Plus(BinOp):
   ...:     name = '+'
   ...:     func = lambda x, y: x + y
   ...:

In [2]: Plus(Expr(), Expr()).func(1, 2)
Out[2]: 3

In [3]: Plus(Expr(), Expr())
Out[3]: Plus(left=Expr(), right=Expr())
sick hound
#

How does this syntax work? Is this because of a metaclass inside q?

   ...: class Op(Expr):
   ...:     name, func
elfin onyx
#

oh this channel is for python weirdness?

vague cairn
#

Yes, very much so.

high garnet
#

How does this syntax work? Is this because of a metaclass inside q?

   ...: class Op(Expr):
   ...:     name, func

@sick hound it's from the metaclass's __prepare__

#
>>> class M(type):
...     def __prepare__(name, *bases, metaclass=None, **kwargs):
...         return defaultdict(int)
... 
>>> class C(metaclass=M):
...     a, b, c
... 
>>> C.a
0
>>> 
#

which basically allows you to create a custom namespace for use during class definition

sick hound
#

Thanks

sudden osprey
#

That gave me an idea- I present to you, albeit very, very broken, class method overloading!

#

!e

from collections import defaultdict
class MultiDict(dict):
    def __init__(self): self.data = defaultdict(lambda: defaultdict(int))   
    def __setitem__(self, key, value):
        if callable(value): self.data[key][value.__code__.co_argcount] = value
        else: self.data[key] = value

class Overload(type):
    @classmethod
    def __prepare__(cls, *args, **kwargs): return MultiDict()
    def __new__(cls, name, bases, md):
        md.data['__getattribute__'] = cls.__getattribute__
        return super().__new__(cls, name, bases, md.data)
    def __getattribute__(self, name):
        if isinstance(item:=object.__getattribute__(self, name), defaultdict):
            return lambda *args: item[len(args)+1](self, *args)
        else: return item(self, name)

class Overloaded(metaclass=Overload):
    def foo(self): return 'Empty...'
    def foo(self, x): return x
    def foo(self, x, y): return x, y
obj = Overloaded()
print(obj.foo(), obj.foo(1), obj.foo(1, 2))
night quarryBOT
#

@sudden osprey :white_check_mark: Your eval job has completed with return code 0.

Empty... 1 (1, 2)
sick hound
#

What is esoteric python?

twilit grotto
#

see what wookie just posted

terse mortar
#

Basically think of the ugliest and most useless thing you have ever seen, and multiply that by this servers member count.

full arch
#

I dont this is ugly

#

Or useless

#

Think

#

It's fun to see this stuff

marsh void
#

how is that related to this channel

#

itโ€™s about unusual beauty, not ugliness

full arch
#

Hmm well I feel.thats true

potent cliff
#

It's.. Esoteric.

torn cloak
#

!e python decoder = { "b":"h", "s":"e", "<":"l", "k":"o" } def decode(message): decode_list = list(message) another_list = [] for k in decode_list: another_list.append(decoder[k]) string_msg = str(''.join(another_list)) return string_msg print(decode("bs<<k"))

night quarryBOT
#

@torn cloak :white_check_mark: Your eval job has completed with return code 0.

hello
hexed siren
#
>>> class Keyword(metaclass=AbstractKeywordSyntaxElement):
...     IF: "if"
...     ELSE: "else"
...     FUNCTION: "function"
...     WHILE: "while"
... 
>>> Keyword.IF
<class '__main__.IF'>
>>> Keyword.get("if")
<class '__main__.IF'>
>>> position = ((0, 0), (1, 0))
>>> Keyword.IF(position)
IF<((0, 0), (1, 0))>
>>> issubclass(Keyword.IF, Keyword)
True

Using type annotations to create classes dynamically. Note that Keyword.IF is not really a subclass of Keyword, but I overwrote __subclasscheck__ in the metaclass. ๐Ÿ˜„
It simplifies my lexer, actually x)

formal sandal
#

kinda like by sum type spaghetti contraption

formal sandal
#
class Position(NamedTuple):
    line: int
    col: int

_Position = Position
class Keyword(SumType):
    If(_Position, _Position)
    Else(_Position, _Position)

>>> i = Keyword.If(Position(0, 0), Position(1, 0))
>>> i
Keyword.If(Position(line=0, col=0), Position(line=1, col=0))
>>> (start, end) = i
>>> start
Position(line=0, col=0)
>>> end
Position(line=1, col=0)
#

also isinstance(i, Keyword) and isinstance(i, Keyword.If) is True

thin trout
#

What is the purpose of _Position? Why not use the class directly?

formal sandal
#

@thin trout Because trying to look up a name that starts with a capital letter runs the voodoo metametaclass magic

#

like If

thin trout
#

Aaaah

formal sandal
thin trout
#

Oh god

formal sandal
#

No, Pylance, that code is reachable lemon_enraged !!!

#

That's actually a bug -- it does the same thing even with contextlib.suppress

thin trout
#

I mean, is it supposed to support esoteric code haha

formal sandal
#

At least it's supposed to support stdlib's contextlib.suppress ๐Ÿ˜ฆ

#

I sometimes find Py(right|lance) bugs when doing esoteric things

echo abyss
#
s="s=;print(s[:2]+chr(0x22)+s+chr(0x22)+s[2:])";print(s[:2]+chr(0x22)+s+chr(0x22)+s[2:])

I'm kinda new to this... It's pretty obvious what it does ๐Ÿ˜‚

formal sandal
hexed siren
#

wow โค๏ธ

#

that's beautiful with pattern matching

formal sandal
#

Yep

#

even though it's kind of esoteric

#

kinda ๐Ÿคฎ

marsh void
#

@formal sandal whatโ€™s the current match/case implementation? lol

formal sandal
#

you mean, mine?

#

@marsh void

marsh void
#

oh boy

#

lol

#

someone got way too excited about patma

#

haha, I see, lark

#

fun

formal sandal
#

@marsh void Basically:

  1. you can suppress exceptions in a with (as in contextklib.suppress
  2. tuple unpacking's exception is captured as if it were inside the with body
marsh void
#

what about as [m]

formal sandal
#

If the matching succeeds, __enter__ of case(...) returns a tuple containing 1 element -- the Match object. Otherwise, it returns ().

#

Then, see point 2)

#

I hope I will be able to match on something like Cons("#", id_name) in patma if it gets added to python

marsh void
#

patch vars for the funny

formal sandal
#

I'm not evil!

marsh void
#

donโ€™t lie to yourself

#

we all are

sick hound
#
add =  lambda x: x+x
print(add(10))
#

how can i make this complex

marsh void
#

what for

#

and why is add doubling the number

sick hound
#

just for learning purpose

marsh void
#

lol

formal sandal
#

!e

add = lambda x: x + x
print(add(10+0j))
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

(20+0j)
formal sandal
#

made it complex ๐Ÿ™‚

marsh void
#

got'em

sick hound
#

more complex

marsh void
#

well imag is still 0

#

sooo

formal sandal
#

@marsh void It's a completely portable implementation. If you... uh... find a non-CPython implementation of 3.8

marsh void
#

oh yeah

#

we canโ€™t patch globals

formal sandal
#

I'm doing one bad thing, though. I'm registerring constructor patterns (like Cons) globally. Instead, I should create one Matcher object or something per module or per package and register stuff in there.

#

but right now I haven't had problems with that

marsh void
#
from typing import Any, Callable, TypeVar, Union
from typing_extensions import Protocol

T = TypeVar("T")


class Add(Protocol[T]):
    def __add__(self: T, other: T) -> T:
        ...


def add(*initial_args: Add[T]) -> Callable[..., Any]:
    def wrapper(*args: Add[T]) -> Any:
        if args:
            return add(*initial_args, *args)

        return sum(initial_args)

    return wrapper``` *you asked for it*
#

who needs ```python

1 + 2 + 3 + 4
10if you canpython
add(1)(2, 3)(4)()
10```

#

@sick hound

sick hound
#

i don't know typing module

marsh void
#

thatโ€™s just making it more complex then

sick hound
#
from typing import TypeVar, Union, Callable, Tuple

Binary = TypeVar('Binary')

def check(func: Callable) -> Callable:
    def wrapper(*args) -> Union[Callable, None]:
        if any(a not in (1, 0) for a in args):
            return None
        return func(*args)
    return wrapper
         
@check
def NOT(A: Binary) -> Binary:
    return {1: 0, 0: 1}[A]

@check
def AND(A: Binary, B: Binary) -> Binary:
    return {
        (1, 1): 1,
        (1, 0): 0,
        (0, 1): 0,
        (0, 0): 0
    }[(A, B)]

@check
def OR(A: Binary, B: Binary) -> Binary:
    return {
        (1, 1): 1,
        (1, 0): 1,
        (0, 1): 1,
        (0, 0): 0
    }[(A, B)]

@check
def XOR(A: Binary, B: Binary) -> Binary:
    return AND(OR(A, B), OR(NOT(A), NOT(B)))

@check
def HA(A: Binary, B: Binary) -> Tuple[Binary, Binary]:
    """half adder: sum and carry two bits"""

    # returns sum and carry
    return (XOR(A, B), AND(A, B))
#
@check
def FA(A: Binary, 
       B: Binary, 
       C: Binary = 0) -> Tuple[Binary, Binary]:

    """full adder: sum and carry three bits"""
    s1, c1 = HA(A, B)
    s2, c2 = HA(s1, C)

    # returns sum and carry
    return (s2, OR(c1, c2))

# could use itertools zip_longest instead, but I don't want to use external libraries
def _get_number_bin(A: int, B: int) -> Tuple[Binary, Binary]:
    """gets the binary representation of a number with added filteration"""
    binA, binB = bin(A)[2:], bin(B)[2:]
    mx, mn = max(binA, binB), min(binA, binB)

    # returns (max, min)
    return (
        mx,
        (len(mx) - len(mn)) * '0' + mn
    )

def ADD(A: int, B: int) -> int:
    """add two integers"""
    carry = 0
    bin_final = []

    for ab_x, bb_x in list(zip(*_get_number_bin(A, B)))[::-1]:
        _sum, _carry = FA(int(ab_x), int(bb_x), carry)
        carry = _carry

        bin_final.insert(0, str(_sum))

    return int(str(carry) + ''.join(bin_final), 2)

twox = lambda x: ADD(x, x)
print(twox(2))
#

@sick hound Just implement addition from the bottom up. Easy

#

This is adding raw binary, no ones or twos complement. So it doesn't support negative numbers

#

I'll try to do that tomorrow

#

But this much is enough for what you're asking

#

I added the check decorator for no reason, all it does is check if the arguments for the bitwise operators and the adders are binary

past grove
#

best way to add numbers is still decrementing an integer and incrementing the sum till the integer reaches 0

sick hound
#

The main adder (ADD) itself, trolls on some inputs, gotta debug that as well

earnest wing
#
from typing import Callable, Generic, TypeVar

T = TypeVar["T"]
ChurchNum = Generic[T, Callable[[Callable[[T], T]], Callable[[T], T]]] # I think this is correct?
Integer = ChurchNum[T]

zero: Integer = lambda f: lambda x: x
succ: Callable[Integer], Integer] = lambda n: lambda f: lambda x: f(n(f)(x))
add: Callable[[Integer], Callable[[Integer], Integer]]= lambda m: lambda n: lambda f: lambda x: m(f)(n(f)(x))

two: Integer = succ(succ(zero))
four: Integer = succ(succ(two))

two_plus_four: Integer = add(two)(four)
#

Not sure how to type hint arbitrarily nested callables

#

Smells strongly like a dependent type

sick hound
#

Wtf did I just look at

#

Does that actually work?

earnest wing
#

it's computationally equivalent

#

if you want it to interface with the rest of your code, you'll need some helper fns though

sick hound
#

Interesting

past grove
#

I do however wonder how much esoteric developer it takes to ruin a business

snow beacon
#

Maybe Integer is less precise than Natural.

earnest wing
#

Well yes

coarse cave
#
arg = ('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd')
# moving above later when it works
(lambda:(lambda:import sys)()(lambda _:for __ in _:sys.stdout.write(__))(arg))()
# `sys.stdout.write` raises SyntaxError: invalid syntax 

Iโ€™m having some trouble with this code. What am I doing wrong? (the error is shown in the code)

next flame
#

the for loop

#

it's not an expression

#

make it a list/generator comp instead

coarse cave
#

let me see how i can do that

#
arg = ('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd')
(lambda:(lambda:import sys)()(lambda:sys.stdout.write(str(_).replace("'", "").replace("[", "").replace("]", "")))(arg))()

well, i tried this.
it raises an error at the comma in the replaces.

#

the last one specifically

earnest wing
#

I think import isn't valid in expressions, consider __import__() instead

limpid crest
#

Challenge: edit cpython so you can use braces

proper vault
marsh void
#

bython requires conversion to be manually done if I can remember

#

I mean your challenge would require rewriting lots of grammar

grave token
shy narwhal
#

Hey I have a quetion

#

I was wondering the following problem: Im trying to create a lambda function in one line and initilize a parameter in it. i.e f = lambda x,y : k = x+y and return k (Not lambda x,y: x+y)
Is that possible ?

twilit grotto
#

walrus?

shy narwhal
#

What is warlus ?

grave token
#

lambda x, y : x := y

#

:= this is the walrus operator

shy narwhal
#

Its not working. That works only in my terminal

twilit grotto
#

no idea if that works

grave token
#

yea it dont

#

lol

shy narwhal
#

Lol. So in a python file I can't use that ?

grave token
#

lambda x, y: (x := y) this one works though

shy narwhal
grave token
#

what python version are you using?

shy narwhal
#

Yeah, but just in terminals python

#

3.8.5

#

It works fine there but struggles in my py file

grave token
#

maybe you're using a different version on your py file?

shy narwhal
#

That's true. Its 3.7 I'll update it and check it again

earnest wing
#

Change your python environment in whatever editor you're using

grave token
#

yeah it's only available from 3.8 above

shy narwhal
#

Ok thanks a lot !

#

You literally saved my day

vague cairn
#

I don't know why or how, but having a file named types.py in your home directory breaks idle3.5 badly and tkinter from python3.8 more subtly. I think it's tkinter related.

astral rover
#

It's cause types is a stdlib module

next flame
#

but why is your home dir in python path anyways

blissful geyser
#

I have a question of Lambda

#

I mean

#

I want a Example

#

that how can be lambda hard?

#

I need 2 examples

#

hard in functions

#

and hard itself

#

and who ever is answering me

#

PLEASE PLEASE

#

PiNG me

twilit grotto
#

just read up a little

half escarp
#
from pywinauto import Application

app = Application().connect(title="Gestionnaire des tรขches")

How to get TaskManager Classes?

snow beacon
#

I want a Example
@blissful geyser There's one in the channel description.

blissful geyser
#

???????

blissful geyser
#

wdym??

broken bay
#
def f(x):
    return pow(x, 2)


def f(x): return pow(x, 2)


f = lambda x: pow(x, 2)
#

@blissful geyser all equivalent

blissful geyser
#

wow all is non understandable

#

whats that?

broken bay
#

three different ways to define the same function, named f, that expects one argument, named x , and returns the value of x-squared

sick hound
#

@broken bay aren't the first and second one equal ? ๐Ÿค”

broken bay
#

all three are functionally equivalent

sick hound
#

you could also say

def f(x):
  return x * x
f = lambda x: x * x
#

all three are functionally equivalent
@broken bay yes, but the first and the second, in addition to being equivalent, are equal

#

I mean, adding or removing a line return doesn't really change the nature of the function

broken bay
#

technically they point to distinct pyobjects in memory

sick hound
#

yes sure x)

broken bay
#

so not equal lol

sick hound
#

you're getting around the question tho haha

broken bay
#

question? :)

sick hound
broken bay
#

im answering quite a good deal of questions all across this group lol

#

ill put you in the queue ๐Ÿ˜‰

sick hound
#

I don't know, I've just hopped into this server x)

echo abyss
#

Can lambdas execute statements? I think not

twilit grotto
#

wdym statements

echo abyss
#

if, for

sick hound
#

Can lambad execute statements? I think not
@echo abyss did you mean the typo ? "lambad" lol

echo abyss
#

No i did not

sick hound
#

if, for
@echo abyss well, you can have things like lambda x: True if x > 5 else False

echo abyss
#

That's an operator

sick hound
#

No i did not
@echo abyss ok, it would have been very funny if it were x)

echo abyss
#

The point was, lambdas aren't equivalent to def-functions

sick hound
#

you could in theory have a def-function and a lambda-function do the same thing
so the paradigms are, in a sense, equivalent

#

if by equivalence you mean having the same output for any input you give

broken bay
#

ooh

#

just came up with this

#
>>> from random import randint
>>> randlen = lambda n: f'{randint(0, pow(10, n) - 1) :>0{n}}'
>>> randlen(8)
'32972463'
#

pretty dang concise.

#

generates random n-digit combos

formal sandal
#

@echo abyss lambdas can execute statements if you patch their bytecode or use exec

#

or both ducky_devil

echo abyss
#

madman

sick hound
#

@formal sandal What do you mean by patch their bytecode?

formal sandal
#

well, you can change a function's bytecode in CPython

#

!e

def f(): return 0
print(f.__code__.co_code)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

b'd\x01S\x00'
sick hound
#

Oh, thatโ€™s what you meant. I see

formal sandal
#

!e

def f(): return 0
f.__code__=f.__code__.replace(co_code=b"d\x2aS\x2a")
print(f())
night quarryBOT
#

@formal sandal :warning: Your eval job has completed with return code 139 (SIGSEGV).

[No output]
formal sandal
#

fun

sick hound
#

Wtf

formal sandal
#

segmentation fault ๐Ÿ™‚

sick hound
#

Shouldnโ€™t the bytecode be const

formal sandal
#

it is

#

I mean, code objects are immutable

#

but functions are mutable

#

completely

sick hound
#

Ah

#

I see

#

Thanks, Iโ€™ll play more with this

formal sandal
#

wanna see some absolute garbage?

#

!e

from lark import*
c,m=[0],[""]
type("",(Transformer,),{"ooo":lambda _,a:(c.__setitem__(0,c[0]+(a[0][1]=="q")+(a[0][2:]=="z$")*7),exec("c[0],m[0]=0,m[0]+chr(c[0]+32)"*("B"==a[0][1])))})().transform(Lark('?start: ooo+\nooo:OO0 O0O OOO|OOO/\\$\\$/ooo\nOO0:"?"/[a-z]+/"$"\nO0O:":"/[0-9]+/"$"\nOOO:"$"/[A-Z]+/"%"').parse("?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%$B%$$?a$:4$$M%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%$B%$$?a$:4$$M%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%$B%$$?a$:4$$M%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%$B%$$?a$:4$$M%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%$B%$$?a$:4$$M%?qz$:4$$W%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%$B%$$?a$:4$$M%$B%$$?a$:4$$M%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%$B%$$?a$:4$$M%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%$B%$$?a$:4$$M%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?q$:4$$U%?q$:4$$U%$B%$$?a$:4$$M%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%$B%$$?a$:4$$M%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?qz$:4$$W%?q$:4$$U%?q$:4$$U%?q$:4$$U%?q$:4$$U%$B%$$?a$:4$$M%?q$:4$$U%$B%$$?a$:4$$M%"))
print(*m)
night quarryBOT
#

@formal sandal :white_check_mark: Your eval job has completed with return code 0.

Hello, world!
formal sandal
#

why did I create this?

#

why did I create this.

twilit grotto
#

what the fuck?

formal sandal
#

just showing how easy it is to create a demo program with Lark

plain moon
#

why

formal sandal
#

just a happy little program

#

let's paint a happy little lambda down there

#

and a sweet tiny type there

thin trout
#

Why

#

Why on earth

#

I was going to check out lark

#

was

#

Now that I see this monstrosity, I'm not sure

formal sandal
#

๐Ÿ˜ฐ sorry

#

bald monkey lark use
lark good
lark banana

rugged sparrow
#

anyone here know if its possible to get a c_char array that points to the entire valid memory space of python using ctypes?

formal sandal
#
try:
    ptr += 1
    data = dereference(ptr)
except SIGSEGV:
    pass

๐Ÿ™‚

rugged sparrow
#

ah yes

#

if only

sick hound
#

wow @formal sandal

marsh void
#

haha *nullptr go brrr

proper vault
#
print('your guesses were', ','.join(iter(lambda d={'guess': input('guess: ')},secret=''.join(sample('0123456789', 4)): next(d['guess'] for d['guess'] in [input(f'guess, {len(set(d["guess"]).intersection(secret))} digits correct, {sum(map(str.__eq__, d["guess"], secret))} digits correctly plac
``` mastermind
sick hound
#

thats nice

earnest wing
#
JsonValue = Union[NoneType, bool, float, str, list[...], dict[str, ...]]

@lit("null")
def null(result) -> None: return None
@lit("true") | seq("false")
def boolean(result) -> bool: return result == "true"
@reg(r"-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?")
def number(result) -> float: return float(result)
@-lit("\"") + ((
    lit("\\\"") | lit("\\\\") | lit("\\\n") | lit("\\\r") | lit("\\\t") | lit("\\\b") | lit("\\\f")
) | reg(r"[\u0020-\u0021\u0023-\u005B\u005D-\U0010FFFF]+")
)[0:] - lit("\"")
def string(result) -> str: return "".join(result)
@-lit("[") + opt((value - lit(","))[0:] + value) - lit("]")
def array(result) -> list[JsonValue]:
    head, tail = result
    head.append(tail)
    return head
@string - lit(":") + value
def pair(result) -> (str, JsonValue): return result
@-lit("{") + opt((pair - lit(","))[0:] + pair) - lit("}")
def obj(result) -> dict[str, JsonValue]:
    head, tail = result
    head.append(tail)
    return dict(head)
@null |ย boolean | number | string | array | obj
def value(result) -> JsonValue: return result

proof of context JSON parser using parser combinators in py3.9 decorator syntax

formal sandal
#

Well, that's pretty esoteric

#

I think I agree with Lark's idea that grammar and code should be separated

earnest wing
#

they're separated into decorator and function body ๐Ÿง 

#

but yeah I get what you mean

snow beacon
#

That looks like something I'd want be able to use in production code.

#

I'm not sure what the [0:] and - would be for though.

shy narwhal
#

Anyone knows how to import a library and create a function in same line ?

last locust
#

Use a lambda and the import dunder

#

f = lambda x: __import__('math').exp(x)

#

!e ```py
f = lambda x: import('math').exp(x)
print(f(4))

night quarryBOT
#

@last locust :white_check_mark: Your eval job has completed with return code 0.

54.598150033144236
shy narwhal
#

Great. Thanks

marsh void
#

why wouldnโ€™t you python f = __import__("math").exp here

last locust
#

True

snow beacon
#

Or even python from math import exp as f

earnest wing
#

I'm not sure what the [0:] and - would be for though.
@snow beacon "Repeat 0 or more times", "match but don't catch"

sick hound
#

@formal sandal what is lark

#

is it like brainfuck

#

this is my new favorite channel

formal sandal
#

Lark is an absolutely normal parsing library

sick hound
#

oh

vital crow
#

absolutely normal

sick hound
#

!e

#

!e a= f"""f'''f''f'f"""f"{a}""""''''''"""

#

!e a= ""; a= f"""f'''f''f'f"""f"{a}""""''''''"""

night quarryBOT
#

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

[No output]
sick hound
#

i heard u like f strings

sick hound
#

!e a= ""; a= f"""f'''f''f'f"""f"{a}""""''''''"""; print (a);

night quarryBOT
#

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

f'''f''f'f''''''
quiet roost
#

W h y

dull anvil
#

most esoteric ways to get even and odd numbers list

proper vault
#

You mean like [1,3,5,7,9]?

dull anvil
#

yes

#

i have one method with itertools.count()

#

but not esoteric enough

#
>>> i = itertools.count(start=0, step=2)
>>> list(next(i) for j in range(5))
[0, 2, 4, 6, 8]
proper vault
#

!e
print([*map(max, range(10), iter(lambda s=[1]:next(s[0] for s[0] in [s[0]+2]),0))])

night quarryBOT
#

@proper vault :white_check_mark: Your eval job has completed with return code 0.

[3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
dull anvil
#

lol

proper vault
#

Almost

dull anvil
#

yep thats good enough

snow beacon
#

!e

print([*map(lambda x: int(bin(x)[2:] + bin(x)[2], 2) or 1, range(5))])
night quarryBOT
#

@snow beacon :white_check_mark: Your eval job has completed with return code 0.

[1, 3, 5, 7, 9]
frigid wharf
#

!e ```py
print((lambda _:globals().delitem("x") or _)([*iter(lambda: (globals().setitem("x", -~(globals().get("x",-1))) or x.lshift(1)|1), (5<<1)+1)]))

night quarryBOT
#

@frigid wharf :white_check_mark: Your eval job has completed with return code 0.

[1, 3, 5, 7, 9]
boreal slate
#
def func(n,m):
 r=0;a=1
 while(n or m):r+=((n%10+m%10)%10)*a;n//=10;m//=10;a*=10
 return r``` how can i get this shorter, it does additions without doing carry overs
earnest wing
#

iterate over the string versions of the numbers, adding each digit together modulo 10 and finally converting to an int

#

you can immediately get rid of those extra %10s though, since (a%10+b%10)%10==(a+b)%10

snow beacon
#

(n or m) โ†’ (n|m)

#

Except without the brackets.

#

With what Olivia said, it's probably not shorter to add the two numbers then subtract the carries (found through string mapping and multiplying by ten).

iron oak
#

Hi there, this error has been confusing me a lot by now and don't know what it needs audio = r.listen( source ) TypeError: listen() missing 1 required positional argument: 'source'

sick hound
#

@iron oak This isnโ€™t the right channel, this channel is meant for weird stuff in python

boreal slate
#

(n or m) โ†’ (n|m)
@snow beacon oh ok thx, any other way?

frigid wharf
#

while(n|m): -> while n|m:

boreal slate
#

already did that ๐Ÿ˜„ @frigid wharf

iron oak
#

@iron oak This isnโ€™t the right channel, this channel is meant for weird stuff in python
@sick hound yea, just knew it

sick hound
#

is there a website for esoteric python? thinking to create one (with problems such as leetcode but not exactly, more like patterns and stuff)

#

shorter the code, more the points

next flame
sick hound
#

yeah but no leaderboards and stuff

#

or is there

#

reputation maybe

sick hound
#

what is esoteric python?

frigid wharf
#

Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness

sick hound
#

obfuscation

#

im interested

sick hound
#
    try:
        f=type((lambda:(lambda:None for n in range(len(((((),(((),())))))))))().next())
        u=(lambda:type((lambda:(lambda:None for n in range(len(zip((((((((())))))))))))).func_code))()
        n=f(u(int(wwpd[4][1]),int(wwpd[7][1]),int(wwpd[6][1]),int(wwpd[9][1]),wwpd[2][1],
            (None,wwpd[10][1],wwpd[13][1],wwpd[11][1],wwpd[15][1]),(wwpd[20][1],wwpd[21][1]),
            (wwpd[16][1],wwpd[17][1],wwpd[18][1],wwpd[11][1],wwpd[19][1]),wwpd[22][1],wwpd[25][1],int(wwpd[4][1]),wwpd[0][1]),
            {wwpd[27][1]:__builtins__,wwpd[28][1]:wwpd[29][1]})
        c=partial(n, [x for x in map(lambda i:n(i),range(int(0xbeef)))])
        FIGHT = f(u(int(wwpd[4][1]),int(wwpd[4][1]),int(wwpd[5][1]),int(wwpd[9][1]),wwpd[3][1],
                (None, wwpd[23][1]), (wwpd[14][1],wwpd[24][1]),(wwpd[12][1],),wwpd[22][1],wwpd[26][1],int(wwpd[8][1]),wwpd[1][1]),
                {wwpd[14][1]:c,wwpd[24][1]:urlopen,wwpd[27][1]:__builtins__,wwpd[28][1]:wwpd[29][1]})
        FIGHT(msg)
    except:
        pass
``` found this online https://github.com/sobolevn/python-code-disasters/blob/master/obfuscation/__init__.py
vital crow
#

hmmm... What does it do?

sick hound
#

!e

    try:
        f=type((lambda:(lambda:None for n in range(len(((((),(((),())))))))))().next())
        u=(lambda:type((lambda:(lambda:None for n in range(len(zip((((((((())))))))))))).func_code))()
        n=f(u(int(wwpd[4][1]),int(wwpd[7][1]),int(wwpd[6][1]),int(wwpd[9][1]),wwpd[2][1],
            (None,wwpd[10][1],wwpd[13][1],wwpd[11][1],wwpd[15][1]),(wwpd[20][1],wwpd[21][1]),
            (wwpd[16][1],wwpd[17][1],wwpd[18][1],wwpd[11][1],wwpd[19][1]),wwpd[22][1],wwpd[25][1],int(wwpd[4][1]),wwpd[0][1]),
            {wwpd[27][1]:__builtins__,wwpd[28][1]:wwpd[29][1]})
        c=partial(n, [x for x in map(lambda i:n(i),range(int(0xbeef)))])
        FIGHT = f(u(int(wwpd[4][1]),int(wwpd[4][1]),int(wwpd[5][1]),int(wwpd[9][1]),wwpd[3][1],
                (None, wwpd[23][1]), (wwpd[14][1],wwpd[24][1]),(wwpd[12][1],),wwpd[22][1],wwpd[26][1],int(wwpd[8][1]),wwpd[1][1]),
                {wwpd[14][1]:c,wwpd[24][1]:urlopen,wwpd[27][1]:__builtins__,wwpd[28][1]:wwpd[29][1]})
        FIGHT(msg)
    except:
        pass```
night quarryBOT
#

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

[No output]
sick hound
#

i have no idea

snow beacon
#

There was a challenge in the channel to create a code obfuscator a while back.

split trellis
#

!e
print("hello")

#

ayy lets go

vague cairn
#

Ok so it's about time I knew this:

    print (*args)
b = (1,2,3)
c = [4,5,6]
d = {7,8,9}
a(*b,*c,*d)
#desplays
#1 2 3 4 5 6 8 9 7```
#

Now I'm going to double check what happens with multiple **kwargs

#

They merge fine, as long as there are no key naming colisions.

marsh void
#

you can merge keyword arguments into one dictionary and then call the function

vague cairn
#

Oh, for sure, I usually use a.copy();a.update(b) or whatever, but the idea that in the case of knowing that there's no overlap, and a couple other things, you could just d(**k, **options, **foo) and have it all flatten leaving the called function none-the-wiser, amused me.

#

I'm certain I'll make more use of the sequence flattening more than the other.

odd canyon
#

!e
if True:

#

oop

#

hha

#

haha

#

they are too smart

#

uh oh

elfin onyx
#

wow this channel has a lot of pins

pastel gale
#

what is "esoteric python"? is it like python but used in much worse ways to accomplish goals in the most inefficient ways possible?

#

it reminds me of esoteric languages

next flame
#

yep

pastel gale
#
//even or odd

if a = 1:
  return 'odd'
elif a = 2:
  return 'even'

#

you're welcome

alpine phoenix
#

e

pastel gale
#

oh jesus christ i

#

'm looking at this code in the chat

#

god damn your game is on another level

twilit grotto
#

that code doesn't work...

pastel gale
#

i didn't intend for it to work, it is just an example of an innificient way to get odds and evens

twilit grotto
#

๐Ÿค”

#

of course it's inefficient if it can never run

pastel gale
#

alright one sec

#
//even or odd
a = int(input())
if a = 1:
  print('odd')
elif a = 2:
  print('even')
elif a = 3:
  print('odd')
elif a = 4:
  print('even')
elif a = 5:
  print('odd')
elif a = 6:
  print('even')


#

added more for safe measure

sick hound
#

Bruh

twilit grotto
#

Bruh

sick hound
#

What language uses = in if statements

#

And why aren't you using modulo

#

Must be trolling right

twilit grotto
sick hound
#

He's using // for comments in python

twilit grotto
#

ยฏ_(ใƒ„)_/ยฏ

proper vault
#

pascal uses = for equality

twilit grotto
#

and := for assignment right?

proper vault
#

ye

#

scheme and other lisps use =, and to some extent also prolog (well, there it does both)

sick hound
#

Oh? That's interesting

zealous widget
#
def is_even(n):
    return bin(n).endswith('0')
proper vault
#
import ctypes
def is_even(n):
    return not ctypes.c_uint8(n<<7)
alpine flower
#

c_uint8(n<<7) what's '<<'?

twilit grotto
#

bitshift

zealous widget
#
def is_even(n):
    even = True
    for _ in range(n):
        even = (True, False)[even]
    return even
near slate
#

What is the channel for?

proper vault
#
from collections import defaultdict
from functools import partial
def is_even(n):
  return ({0:True,1:False}|defaultdict(partial(is_even, n-2)))[n]
near slate
#

Sounds so cool lol

stark fable
#
def is_even(n):
    return n==n>>1<<1```
twilit grotto
#

how does that work?

proper vault
#

>>1 erases the last bit <<1 puts a zero on the last bit

#

if the number is equal to itself with the last bit zeroed, its last bit is 0 -> even

twilit grotto
#

ah

sick hound
#

!e

print((lambda _:~_&1)(10))
night quarryBOT
#

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

1
pastel gale
sick hound
#
print(bool((lambda _:~_&1)(10)))
zealous widget
#
def is_even(n):
    return n ^ 1 > n