#esoteric-python
1 messages ยท Page 94 of 1
(lambda:(yield))().throw(exc)
(0for()in()).throw(exc)
still shorter ๐
I didn't know you could even yield in a lambda
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...
I'm not sure how to handle nonlocal stuff
You can always implement your own scopes, though.
nonlocal you may have to mod the bytecode of the lambda after compiling
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)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
[1]
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?
a dictionary is probably shorter
I'll try that
x=lambda a,o,b: {'+':a+b,'-':a-b,'*':a*b,'/'a/(b or 1)}[o]
the problem with a dict is division
@proper vault cheers
(0for()in()).throw(exc)
@formal sandal
Wait, how does that syntax work?
(0for()in())
Why does that even work
Oh
@formal sandal :warning: Your eval job has completed with return code 0.
[No output]
^ as well as empty tuples
Wtf
(x, y, z) = [1, 2, 3]
(x, y) = [1, 2]
(x,) = [1]
() = []
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
[expr for a, b in [c]][0]
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
I mean yeah, if you are removing statements, you gotta remove all statements
!e __import__('ctypes').string_at(0)
@rugged sparrow :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
@sick hound ^
!e __import__('ctypes').memset(0,0,1)
@grave rover :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
wait no that's 1 char more
is that like a segfault? What's so special about string at 0 lol
!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))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
hello world
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?
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
any ideas for how to solve these?
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
oh god it doesn't handle scopes properly
@grave rover for double assigns you'll need a temp var to do the swap
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
I assume using [*iter()]?
That will fail eventually right? If you do [*iter(lambda:[condition,body][0],True)] it should work infinitely (until buildlist starts to hang)
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.
you could assign lambda x:getattr(x,"__setitem__") to a variable if you wanted to
even better, assign something to lambda x,y,z:x.__setitem__(y,z)
lambda x,*a:x.__setitem__(*a)
a bit shorter ๐
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]`
your code is so obfusctaed
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.
one issue with doing something like that is that you would end up with an infinite MRO
Yeah, the MRO will probably make the object unusable
๐ฟ
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.
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
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)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
False
>>> 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
>>>```
!e ```py
class A:
pass
old_A = A
class B(A):
pass
class A(B):
pass
print(issubclass(A, old_A))```
@naive roost :white_check_mark: Your eval job has completed with return code 0.
True
!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))
@naive roost :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | False
@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
@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
@sick hound i wrote one similar to forbiddenfruit that can patch a bit more https://github.com/chilaxan/py_future
also this does python preprocessing https://pypi.org/project/brm/
Thanks
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
It annoys me that you put spaces around some =s and not all
i think pep8 says that's what you should do
!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))
@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
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?
sys.excepthook
@snow beacon ^
It gets called when exceptions get raised and you can mod the traceback
Intriguing.
!e ```py
import sys
sys.excepthook = lambda *a:print(*a)
1/0
@rugged sparrow :x: Your eval job has completed with return code 1.
<class 'ZeroDivisionError'> division by zero <traceback object at 0x7fa938647480>
Woah that's a thing?
!d sys.excepthook
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)
!e
del __import__('sys').excepthook
raise RuntimeError('Lost sys.excepthook lol')
@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
O interesting
!e py import sys print(sys.getsizeof(()))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
40
b
!e py print(().__sizeof__())
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
24
Do they grow with the same size for additional fields?
@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
huh that's a lot used by it then, what everything would fall into it?
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)
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)
this isnt really fitting for the channel
@rugged edge #discord-bots
@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.
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.
@sick hound Maybe you'd like to see the attrdict third-party library? ๐
anyway, this is off-topic for this channel
!e
print (test)
!e
print (input("test"))
!e
name = input ("test")
print (name)
!e
print (true-1)
@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
!e
print (True-1)
@wise valve :white_check_mark: Your eval job has completed with return code 0.
0
take this to #bot-commands
i finished writing it. The ultimate data parser for lazy people
Add a__getattr__method instead of adding attributes x)
Val.test4.first would be nice tbh
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`
Hey @vague cairn!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
So I've gotten this behaving the way I want. https://paste.pythondiscord.com/befitiqimu.py
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()?
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
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)
is there a way for an imported module to log code entered interactively?
Oooh, I can imagine about six places to take that if you got it working.
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 ๐ฆ
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
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...
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.
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
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```
@vague cairn it is possible to make the inheritance object -> AttrObject -> everything else but itll be hacky
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 *
Or if you made AttrObject inherit from type then you could make object inherit from AttrObject
Hmm, I've never used type. how different is it?
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
<class 'type'>
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.
oooh
__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 ^
That doesn't look to hard, doesn't set risk randomizing the order, or does that even matter?
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,))
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()
That works
IIRC there is a way to specify a custom parser for a Python module
is there?
or am I remembering wrongly
!warn @haughty basin Spamming "okay" in several channels to pass the voice gate or for any other purpose is not okay.
:incoming_envelope: :ok_hand: applied warning to @haughty basin.
@high garnet you might mean #coding or import hooks, those can afaik do that
@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?
https://discordapp.com/channels/267624335836053506/768219185905270834/768238520450940940 this kind of thing
@proper vault YES
that was it
thank you
I knew I remembered something like that but I couldn't find it
wrong channel?
most likely, yeah
@winter geyser Hi, this video isn't related to this channel
!e
def add_one(n):
return n+1
print(add_one(1))
@ivory parcel :white_check_mark: Your eval job has completed with return code 0.
2
very useful function
!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)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
10
!e
def convert_to_bin(st):
return ' '.join(format(ord(x), 'b') for x in st)
print(convert_to_bin('testing'))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1110100 1100101 1110011 1110100 1101001 1101110 1100111
why format()?
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'))```
@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
oh wait
!e
def convert_to_bin(st):
return ' '.join(ord(x), 'b' for x in st)
print(convert_to_bin('testing'))```
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | SyntaxError: Generator expression must be parenthesized
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'))```
@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
nope nevermind
!e ```python
def convert_to_bin(s):
return ' '.join(bin(ord(c))[2:] for c in s)
print(convert_to_bin("testing"))
@next flame :white_check_mark: Your eval job has completed with return code 0.
1110100 1100101 1110011 1110100 1101001 1101110 1100111
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'))```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1101000 1101001
!e
print(lambda _:' '.join(bin(ord(i))[2:]for i in _))('testing'))
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | SyntaxError: unmatched ')'
Bruh
Ah
i know this prolly isn't the right channel but can i have help with something i cant get help for anywhere ๐
#algos-and-data-structs message
print((lambda _:' '.join(bin(ord(i))[2:]for i in _))('testing'))
!e
print((lambda _:' '.join(bin(ord(i))[2:]for i in _))('testing'))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1110100 1100101 1110011 1110100 1101001 1101110 1100111
!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!*
!e ```py
print((lambda _:' '.join(f"{ord(c):b}"for c in _))('testing'))
@grave rover :white_check_mark: Your eval job has completed with return code 0.
1110100 1100101 1110011 1110100 1101001 1101110 1100111
2 chars shorter 
Another one, though 4 chars longer than mine:```py
print((lambda _:' '.join(f"{c:b}"for c in _.encode()))('testing'))
what is the point of the lambda?
print(*(f"{ord(c):b}"for c in'testing'))
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
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
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
the latter is generally better for cache friendliness, but either is trivial to iterate over.
just use grouper from itertools recipies
and then it should have the same cache friendliness
f'''{f"""{f'{f"{ {}=}"}'=}"""=}'''
what the
@proper vault what was that formatting?
!f-strings
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))
How do you enter the python editor in disc?
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?
!code
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!')
@median lark is this what you were looking for?
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?
!or
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.")
@median lark
Sorry, I couldn't figure it out
@median lark Also what you want might be if line_symbol in (")", "(", "*", "&", "^"):
Which constructs a tuple, then checks membership in it of line_symbol
@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.
you can just do line_symbol in ")(*&^"
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 likewith 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
f'''{1:{f"""{1:{f'{1:{f"{1:{1:1}}":1}}':1}}""":1}}'''```
@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 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
yeah, or store videos of very quickly scrolling plaintext ๐
and then use OCR to retrieve the data
that would be even more complicated
Oh, by the way, you can just store Base85 in subtitles!
Yea but then I'd still need to store something for video
But I'm pretty sure that would be abuse of YouTube anyway, and it's not very nice.
Hello, how can I create a file Browser of another pc (socket) with Python?
@gusty igloo Not the right channel. See #โ๏ฝhow-to-get-help or, well, #networks
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!
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
@sick hound Not the right channel. See #โ๏ฝhow-to-get-help
@formal sandal were you the one who wrote code for destructuring mappings
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
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
This is what I got working:
https://paste.pythondiscord.com/nakosamege.py
works in IPython
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 ๐ค
wdym? works fine in functions for me
@formal sandal in vanilla REPL?
why would you run production code in REPL ๐
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 ๐ฅด
This is what I got working:
https://paste.pythondiscord.com/nakosamege.py
And it works in the REPL too.
But the error detection and messages are not up to par across all three logic branches.
True!
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.
so a, b, *c, d = desrtucture(a_dict) unpacks a_dict["c"] into c?
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.
oh, makes sense
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()
@vague cairn btw, if you want to make this work without a apparent function call, you can patch dict.__iter__
@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.
you could do that. then it would look like part of the lang. or you could just break dicts default iter
๐
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."
๐
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'
that's what #esoteric-python is for
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.
well...that sounds quite unhealthy
!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)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
('a', 1)
@vague cairn ^
for reference on replacing dict.__iter__ incase you decide to go full cursed
"""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()```
@rugged sparrow Thanks!
https://paste.pythondiscord.com/eyozuyerel.py
Humm, that breaks something, once I put it in a better order.
@vague cairn do yield from iter(whatever)
Ah, python silently died when destructure() iterated the dict that was already trying to be iterated.
new version: https://paste.pythondiscord.com/tojojerelo.py
Not return iter(whatever)
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.
@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?
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
@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
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?
yes
Got it, change applied.
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?
You can save the original value to a variable and restore it at shutdown
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.
I was going to say "what the f*ck" but then I realized which channel I was in
I still say that every time
New version, compatable with 3.5.2 and 3.8.1: https://paste.pythondiscord.com/qujeqarevu.py
!e ```py
_id = lambda o:1 .class(().class.base.repr(o).strip('>').split(' ')[-1],16)
print(id(1))
print(_id(1))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 140706928808192
002 | 140706928808192
^ id with no builtins
joli ^^
https://discordapp.com/channels/267624335836053506/267624335836053506/770395093093318666
fix terror told me to come here, so:
something=lambda:print(f" Welcome! Mr.{input('What is your name?')}. Your Room is Room {'A'if(a:=int(input('What is your Age?')))<=10else{70<=a<=79 or 11<=a<=20:'B',21<=a<=30 or 60<=a<=69:'C',50<=a<=59 or 31<=a<=40:'D'}.get(1,'E')}")```
the intent was merely to reduce it to 1 line, not to make it overly esoteric
Consider something like
{70<=a<=79:'A', ...}.get(True, 'E')
edited
edited to do that
You can replace the <= with < if you adjust the bounds by 1, saving a handful of bytes
Your input is all integral anyways
Also, you can do 79 or -> 79or in every case
Given that these all evaluate to bool, can't we use & | instead of and or?
You're right
also,
def something():...
something=lambda:...
counterintuitively, def is 1 character longer.
nothing binds tighter than ., right?
it's not even in the operator precedence list
so that's my guess
I'm pretty sure covalent bonds are stronger 
Well, it's not an operator
because the right side of it is not an expression
my love for you is stronger still
it would be pretty counterintuitive if it didn't
inb4 someone writes some ast hackery to break it
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
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.
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
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
WHAT IS HAPPENING?
yeah
that code allows for hotswapping base class dunders
like list.__getitem__ or str.__add__
im confused
it lets you replace the original methods
im confused
@narrow ridge I mean, this is esoteric stuff
pretty interesting that people understand that
@rugged sparrow Planning to publish to PyPI?
needs some polishing but probably
whats the difference between this and forbidden fruit?
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]
@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__'
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
oh nice
@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?
It's mostly looking through the cpython source code and understanding what the memory structures look like conceptually
@sick hound and lots of experimentation
I see, thanks
@rugged sparrow seems really CPython-magical, I wonder what happens on other implementations
it def is cpython magic, prob wouldnt work on other implementations
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?
I was about to ask you what in the world you were thinking, then I realized what channel I was in
Hahah yeah
@slate wasp your goal is something like ```py
foo() #works
@delete_function
def foo():pass
foo() # no longer works
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
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
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
@slate wasp you can just repost your code here, that'd be more accurate ๐
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
you could set the previous name to a func like ```py
def fail(*args,**kwargs):
raise Exception('na')
You mean making it raise an error from being used?
yea
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?
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
What are tracefuncs?
!d sys.settrace
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)
Ah, so I could make it delete itself before anything happens the second time?
Ah, nice. I assume it would also be possible to make sure that it only applies to functions decorated with that specific decorator?
yea but how to do that is up to you
Yep. Thanks :)
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
yea you can actually use that to oneline try/except
!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:
...
@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
^ 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):
...
@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>
if unpacking fails, the exception goes to __exit__
ohhh thats interesting
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")
>>> 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?
cause there may be more complicated patterns, with custom classes and stuff
for example?
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)
@formal sandal x is a tuple
I'm sure with sufficient work it's possible to get around using strings ๐
@formal sandal
xis a tuple
@rugged sparrow I think it was sarcasm
@rugged sparrow Yeah, that's the elephant in the room, I thought I missed something subtle ๐
oh lmao
okay I guess you wouldn't be able to bind to arbitrary names
it uses the patchy module i wrote in the past couple days
if you didn't use strings
>> x = (0,)
>>> x[0] = 1
>>> print(x)
(1,)
>>> ``` also enables this
x[0] = x
๐
๐
I did that manually, and it actually prints out fine
it's like... they have foreseen that
its because they recommend using tuples as python compatible arrays in cpython extensions
>>> x[0] = x
>>> print(x)
((...),)
>>> ```
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
you could load the module and then decorate each function in it
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
well, you can subclass the console to do whatever when you enter stuff --- ipython let's you run input through arbitrary functions as well
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
is a user typing something in or something?
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
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
Hmm, okay. I assume that wouldn't let me do it quite as above?
if you want to decorate all functions in some file --- that's doable too
this is my only example of subclassing console: https://github.com/salt-die/graphvy/blob/master/graphvy/console/console.py maybe it's an idea, i dunno
Doing it continuously? Both of the cases above should lead to the functions being auto-decorated
how do you load a file continuously
Well, that mostly applies to the second case
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
it's not the most relevant code, but it's the only time i've subclassed console
Yeah
this let me have a console that was directly hooked up to a graph
Oh wow. That's looks great
project needs some love -- it hasn't been touched since early in the year
@zealous widget It's like 3d models embedded in HolyC ๐
holyc lmao
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
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())
How does this syntax work? Is this because of a metaclass inside q?
...: class Op(Expr):
...: name, func
oh this channel is for python weirdness?
Yes, very much so.
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
Thanks
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))
@sudden osprey :white_check_mark: Your eval job has completed with return code 0.
Empty... 1 (1, 2)
What is esoteric python?
see what wookie just posted
Basically think of the ugliest and most useless thing you have ever seen, and multiply that by this servers member count.
Hmm well I feel.thats true
It's.. Esoteric.
!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"))
@torn cloak :white_check_mark: Your eval job has completed with return code 0.
hello
>>> 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)
kinda like by sum type spaghetti contraption
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
What is the purpose of _Position? Why not use the class directly?
@thin trout Because trying to look up a name that starts with a capital letter runs the voodoo metametaclass magic
like If
Aaaah
Finally I can refactor all those ifs with beautiful pattern matching!
Oh god
No, Pylance, that code is reachable
!!!
That's actually a bug -- it does the same thing even with contextlib.suppress
I mean, is it supposed to support esoteric code haha
At least it's supposed to support stdlib's contextlib.suppress ๐ฆ
I sometimes find Py(right|lance) bugs when doing esoteric things
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 ๐
Previous function ^, now without any if statements! 
Yep
even though it's kind of esoteric
The version with if statements: https://github.com/decorator-factory/python-fnl/blob/master/fnl/fnlx.py#L83
kinda ๐คฎ
@formal sandal whatโs the current match/case implementation? lol
you mean, mine?
You can find it on https://github.com/decorator-factory/context_manager_patma
or pip install -e git+ssh://gitgithub.com/decorator-factory/context_manager_patma#egg=context-manager-patma
@marsh void
@marsh void Basically:
- you can suppress exceptions in a with (as in
contextklib.suppress - tuple unpacking's exception is captured as if it were inside the
withbody
what about as [m]
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
patch vars for the funny
I'm not evil!
just for learning purpose
lol
!e
add = lambda x: x + x
print(add(10+0j))
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
(20+0j)
made it complex ๐
got'em
more complex
@marsh void It's a completely portable implementation. If you... uh... find a non-CPython implementation of 3.8
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
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
i don't know typing module
thatโs just making it more complex then
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
best way to add numbers is still decrementing an integer and incrementing the sum till the integer reaches 0
The main adder (ADD) itself, trolls on some inputs, gotta debug that as well
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
it's computationally equivalent
if you want it to interface with the rest of your code, you'll need some helper fns though
Interesting
I do however wonder how much esoteric developer it takes to ruin a business
Maybe Integer is less precise than Natural.
Well yes
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)
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
I think import isn't valid in expressions, consider __import__() instead
Challenge: edit cpython so you can use braces
bython requires conversion to be manually done if I can remember
braces.py uses some magic of custom encoding
I mean your challenge would require rewriting lots of grammar
I forgot that this channel exists lol
So I've been making a py version of donut.c (https://www.a1k0n.net/2011/07/20/donut-math.html), though it looks more like blob.py right now
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 ?
walrus?
Its not working. That works only in my terminal
no idea if that works
Lol. So in a python file I can't use that ?
lambda x, y: (x := y) this one works though
what python version are you using?
Yeah, but just in terminals python
3.8.5
It works fine there but struggles in my py file
maybe you're using a different version on your py file?
That's true. Its 3.7 I'll update it and check it again
Change your python environment in whatever editor you're using
yeah it's only available from 3.8 above
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.
It's cause types is a stdlib module
but why is your home dir in python path anyways
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
just read up a little
from pywinauto import Application
app = Application().connect(title="Gestionnaire des tรขches")
How to get TaskManager Classes?
I want a Example
@blissful geyser There's one in the channel description.
???????
wdym??
def f(x):
return pow(x, 2)
def f(x): return pow(x, 2)
f = lambda x: pow(x, 2)
@blissful geyser all equivalent
three different ways to define the same function, named f, that expects one argument, named x , and returns the value of x-squared
@broken bay aren't the first and second one equal ? ๐ค
all three are functionally equivalent
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
technically they point to distinct pyobjects in memory
yes sure x)
so not equal lol
you're getting around the question tho haha
question? :)
im answering quite a good deal of questions all across this group lol
ill put you in the queue ๐
I don't know, I've just hopped into this server x)
Can lambdas execute statements? I think not
wdym statements
if, for
Can lambad execute statements? I think not
@echo abyss did you mean the typo ? "lambad" lol
No i did not
if, for
@echo abyss well, you can have things likelambda x: True if x > 5 else False
That's an operator
No i did not
@echo abyss ok, it would have been very funny if it were x)
The point was, lambdas aren't equivalent to def-functions
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
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
@echo abyss lambdas can execute statements if you patch their bytecode or use exec
or both 
madman
@formal sandal What do you mean by patch their bytecode?
well, you can change a function's bytecode in CPython
!e
def f(): return 0
print(f.__code__.co_code)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
b'd\x01S\x00'
Oh, thatโs what you meant. I see
!e
def f(): return 0
f.__code__=f.__code__.replace(co_code=b"d\x2aS\x2a")
print(f())
@formal sandal :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
fun
Wtf
segmentation fault ๐
Shouldnโt the bytecode be const
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)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
Hello, world!
what the fuck?
just showing how easy it is to create a demo program with Lark
why
just a happy little program
let's paint a happy little lambda down there
and a sweet tiny type there
Why
Why on earth
I was going to check out lark
was
Now that I see this monstrosity, I'm not sure
anyone here know if its possible to get a c_char array that points to the entire valid memory space of python using ctypes?
try:
ptr += 1
data = dereference(ptr)
except SIGSEGV:
pass
๐
wow @formal sandal
haha *nullptr go brrr
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
thats nice
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

Well, that's pretty esoteric
I think I agree with Lark's idea that grammar and code should be separated
they're separated into decorator and function body ๐ง
but yeah I get what you mean
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.
Anyone knows how to import a library and create a function in same line ?
This one in a single line
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))
@last locust :white_check_mark: Your eval job has completed with return code 0.
54.598150033144236
Great. Thanks
why wouldnโt you python f = __import__("math").exp here
True
Or even python from math import exp as f
I'm not sure what the
[0:]and-would be for though.
@snow beacon "Repeat 0 or more times", "match but don't catch"
Lark is an absolutely normal parsing library
oh
absolutely normal
!e
!e a= f"""f'''f''f'f"""f"{a}""""''''''"""
!e a= ""; a= f"""f'''f''f'f"""f"{a}""""''''''"""
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
i heard u like f strings
!e a= ""; a= f"""f'''f''f'f"""f"{a}""""''''''"""; print (a);
@sick hound :white_check_mark: Your eval job has completed with return code 0.
f'''f''f'f''''''
W h y
most esoteric ways to get even and odd numbers list
You mean like [1,3,5,7,9]?
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]
!e
print([*map(max, range(10), iter(lambda s=[1]:next(s[0] for s[0] in [s[0]+2]),0))])
@proper vault :white_check_mark: Your eval job has completed with return code 0.
[3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
lol
Almost
yep thats good enough
!e
print([*map(lambda x: int(bin(x)[2:] + bin(x)[2], 2) or 1, range(5))])
@snow beacon :white_check_mark: Your eval job has completed with return code 0.
[1, 3, 5, 7, 9]
!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)]))
@frigid wharf :white_check_mark: Your eval job has completed with return code 0.
[1, 3, 5, 7, 9]
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
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
(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).
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'
@iron oak This isnโt the right channel, this channel is meant for weird stuff in python
(n or m)โ(n|m)
@snow beacon oh ok thx, any other way?
while(n|m): -> while n|m:
already did that ๐ @frigid wharf
@iron oak This isnโt the right channel, this channel is meant for weird stuff in python
@sick hound yea, just knew it
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
what is esoteric python?
Golfing, Python VM languages, obfuscation, code gore and other general Python weirdness
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
hmmm... What does it do?
!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```
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
i have no idea
There was a challenge in the channel to create a code obfuscator a while back.
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.
you can merge keyword arguments into one dictionary and then call the function
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.
wow this channel has a lot of pins
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
yep
e
oh jesus christ i
'm looking at this code in the chat
god damn your game is on another level
that code doesn't work...
i didn't intend for it to work, it is just an example of an innificient way to get odds and evens
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
Bruh
Bruh
What language uses = in if statements
And why aren't you using modulo
Must be trolling right
i mean, it is #esoteric-python
He's using // for comments in python
ยฏ_(ใ)_/ยฏ
pascal uses = for equality
and := for assignment right?
ye
scheme and other lisps use =, and to some extent also prolog (well, there it does both)
Oh? That's interesting
def is_even(n):
return bin(n).endswith('0')
import ctypes
def is_even(n):
return not ctypes.c_uint8(n<<7)
c_uint8(n<<7) what's '<<'?
bitshift
def is_even(n):
even = True
for _ in range(n):
even = (True, False)[even]
return even
What is the channel for?
from collections import defaultdict
from functools import partial
def is_even(n):
return ({0:True,1:False}|defaultdict(partial(is_even, n-2)))[n]
Sounds so cool lol
def is_even(n):
return n==n>>1<<1```
how does that work?
>>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
ah
!e
print((lambda _:~_&1)(10))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1
stg #esoteric-python is the next APL
print(bool((lambda _:~_&1)(10)))
def is_even(n):
return n ^ 1 > n
