#esoteric-python
1 messages · Page 120 of 1
very dank
one line it
oh @proper vault @rugged sparrow @astral rover and anyone else, if youre still interested: here's a few solutions to the print_nine problem with extra and extra extra points:
https://hastebin.com/olesimenub.py
https://hastebin.com/kebatubipe.py
https://hastebin.com/pedevifiru.py
!e ```py
class struct:
def setitem(self, name, value):
if name in globals():
setattr(self, name, value(globals()[name]))
else:
setattr(self, name, value)
def getattr(self,name):
try:return object.getattribute(self, name)
except AttributeError:
setattr(self, name, self.class())
return getattr(self, name)
annotations:lambda c:print(c) or c = struct()
std:lambda s:s.setitem('cout',type('print',(),{'lt':print})())or s = struct()
std.cout < 'Hello World!'
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | <__main__.struct object at 0x7f17cf429fd0>
002 | Hello World!
how i use annotations ;)
I wish :: existed in Python lol
closest is xor and and
|| is a much better syntax for that failed expression exception handling pep
I wish #define existed in Python
then a except B:c or whatever it was
oh yeah
polyglots go brrrr
how do you use the syntax again?
actually it ends up becoming a c interpreter not a polyglot
the best implementation i can think of, anyway
SyntaxError is my only weakness
I wanna make structs
I made like the c thing before I forgot where it was
it was fun but it needs a struct
yeah ive tried making structs but i get stuck on extended implementation
for example, i wanna just do
cout.__lt__ = print
cout < "Yay"
!e ```py
from ctypes import py_object as p
class gulag:
jail = {}
def hack(self, victim):
return p.from_address(id(victim)+8)
def getitem(self, victim):
return self.hack(victim).value
def setitem(self, name, imposter):
victim = globals().get(name)
if hasattr(victim, 'name'):
self.jail[victim.name] = self[victim]
elif hasattr(victim, 'hash'):
self.jail[victim] = self[victim]
else:self.jail[victim.class.name] = self[victim]
self.hack(victim).value = imposter
def del(self):
for victim, prisoner in self.jail.items():
self.hack(victim).value = prisoner
annotations = gulag()
a : type('tuple',(gulag()[a],),{'lt':print}) = ()
() < 'Hello World!'
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
"safe hacking"
problems with hashy stuff annoying me a little
!e ```py
from ctypes import py_object as p
@lambda c:c()
class gulag:
jail = []
def hack(self, victim):
return p.from_address(id(victim)+8)
def getitem(self, victim):
return self.hack(victim).value
def setitem(self, name, imposter):
try:victim = globals().get(name,name)
except TypeError:victim = name
self.jail += [(victim, self[victim])]
self.hack(victim).value = imposter
def del(self):
for victim, prisoner in self.jail:
self.hack(victim).value = prisoner
class struct:
def init(self, name=''):
self.name = name or 'struct'
def rrshift(self, other):...
def getattribute(self, name):
g = super().getattribute
try:return g(name)
except AttributeError:
__ = type(name,(struct,),{})()
super().setattr(name,__)
return __
def setattr(self, name, value):
g = super().getattribute
s = super().setattr
gulag[self] = type('struct',(gulag[self],),{name:value})
class globals(gulag[globals()]):
def missing(self, name):
try:return super().missing(name)
except KeyError:
_ = self[name] = struct(name=name)
return _
int: type('int',(gulag[int],){'main':lambda s,*a:type('mul':lambda s,f:[*f][-1])()}) = int
void = None
def input(yay):#override
print(end='yay')
user_input = str(import('random').randint(2,10))
print(user_input)
return user_input
gulag[globals()] = globals
cout.lt = print
cout.lshift = lambda s,o:Print(end=str(o))or s
cin.rshift = lambda s,o:globals().setitem(globals[o].name,input(o))
int.main (void)* {
cout << "A number ",
cin >> n,
cout << 'And another number ',
cin >> m,
cout << "Multiplied is " < mn,
mn
};
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
oh cmon
i safe hacked and everything
I have safe hack, globals hack, struct class, input override and a really smart c++ iostreams syntax what's the problem?
lol why does python keep crashing when I start to do something interesting?
!e
Idk
look what I made
!e ```c
metamaker = (lambda meta, cls: ( lambda: [ (dict_.pop(es, None) for es in dict_.get("slots", tuple())) if [None for [globals()["dict_"]] in [[dict(cls.dict)]]][0] is None else None, [None for [globals()["dict_"]["metaclass"]] in [[meta]]], [None for [globals()["dict"]["wrapped"]] in [[cls]]], meta(str(cls.name), tuple(cls.bases), dict), ][-1]))
temp = metamaker(type("", (type,), {"sub":lambda self,:globals().update({: temp}), "getattr":lambda self,:lambda val: setattr(temp, , val)}), type("", (object,), {}))()
struct_type = metamaker(type("", (type,), {"sub":lambda self, : [None for [globals()[]] in [[temp]]]}), type("", (object,), {}))()
name_get_name = metamaker(type("", (type,), {"sub":lambda self,:struct_type-}) , type("", (object,), {}))()
name_maker = metamaker(type("", (type,), {"sub":lambda self,:name_get_name}) , type("", (object,), {}))()
int = metamaker(type("a", (type,), {"sub": lambda self2, : {None} if isinstance(, set) else type("", (object,), {:0}) if len(.split("="))==1 else [None for [globals()[.split("=")[0]]] in [[import('builtins').int(.split("=")[1])]]][0]}), type("a", (object,), {}))()
typedef=metamaker(type("", (type,), {"sub":lambda self,:name_maker}), type("",(object,),{}))()
struct=metamaker(type("", (type,), {"sub":lambda self,p:None}), type("",(object,),{}))()
printf = lambda format_string, *args: print(format_string,end="") if not args else print(format_string % args,end="")
main = metamaker(type("b", (type,), {"call": lambda self, _: {None}}), type("", (object,), {}))()
void = None
return_0 = None
#include <stdio.h>
typedef-struct-{
int-"width",
int-"height"
}-"Rectangle";
int-main(void)-{
Rectangle-"rect",
rect.width(5),
rect.height(5),
printf("Rectangle:\n\twidth: %d\n\theight: %d\n", rect.width, rect.height),
printf("Area: %d * %d = %d\n", rect.width, rect.height, rect.width*rect.height),
int-"variable=6",
printf("Number: %d * %d = %d\n", rect.width, variable, rect.width*variable),
return_0
}```
oops
@tribal moon :white_check_mark: Your eval job has completed with return code 0.
001 | Rectangle:
002 | width: 5
003 | height: 5
004 | Area: 5 * 5 = 25
005 | Number: 5 * 6 = 30
yes! it works
I know that's not how you set struct things rect.width(5) but it's an expression so yeah
setattr?
yeah but it's a bit uglier and like
yeah
#include <stdio.h>
typedef-struct-{
int-"width",
int-"height"
}-"Rectangle";
int-main(void)-{
Rectangle-"rect",
rect.width(5),
rect.height(5),
printf("Rectangle:\n\twidth: %d\n\theight: %d\n", rect.width, rect.height),
printf("Area: %d * %d = %d\n", rect.width, rect.height, rect.width*rect.height),
int-"variable=6",
printf("Number: %d * %d = %d\n", rect.width, variable, rect.width*variable),
return_0
}```
this was horrible to make
ah i see
like making these typeclass things is really confusing
I legit broke pycharm
my god its so confusing
Process finished with exit code -1073740791 (0xC0000409)
haven't seen that exit code yet
!e ```py
import ctypes
string_buffer = ctypes.create_string_buffer(20)
libc = ctypes.cdll.LoadLibrary("libc.so.6")
print(string_buffer.value)
libc.sprintf(string_buffer, b"%s", b"Hello, World!")
print(string_buffer.value, string_buffer.raw, sep="\n")```
@tribal moon :white_check_mark: Your eval job has completed with return code 0.
001 | b''
002 | b'Hello, World!'
003 | b'Hello, World!\x00\x00\x00\x00\x00\x00\x00'
cool
you can also access dynamic memory allocating functions like malloc, calloc, and realloc
it does what expected
pretty cool I like ctypes
that shows how much you're crushing Python
python can't take it anymore from you lol
I killed missing is what happened
Process finished with exit code -1073741819 (0xC0000005)
What does that even mean
so far I've seen ```py
-1073741819: 0xC0000005
-1073741818: 0xC0000006
-1073740791: 0xC0000409
yeah error codes are confusing
especially these ones
i think ...5 is like pocket calculator error 3 (i think 1 is syntax error, 2 is math error, 4 is memory overflow, 3 is hard to explain, similar to segfault)
...6 is process termination error
...409 seems to be like ...5, but when there's an active traceback
that's what i gather from experimentation
lmao
since when does fancy error codes define esoteric code?
!e that would make this esoteric: ```py
from _sitebuiltins import Quitter as Q
leave = Q(*'ab')
leave(0xC0000420)
@floral meteor :warning: Your eval job has completed with return code 32.
[No output]
note: 0xC0000420 != 32
Didn't know you could do that
continue doing this
add some other cool stuff
!e first post here
std,cout,endl=(c:=type("",(),{'__getitem__':lambda _,i:i.step,'__rshift__':lambda _,x:print(x,end='')or _}))(),c(),"\n"
std[::cout] >> "hello" >> std[::endl];
std[::cout] >> "world" >> std[::endl];
@maiden blaze :white_check_mark: Your eval job has completed with return code 0.
001 | hello
002 | world
:0
Sort of a copy but 
!e
!e```py
std,cout,endl=(c:=type("",(),{'getitem':lambda _,i:i.step,'lshift':lambda _,x:print(x,end='')or _}))(),c(),"\n"
std[::cout] << "hello" << std[::endl];
std[::cout] << "world" << std[::endl];
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | hello
002 | world
In C++, >> denotes giving an input with the see-in or cin command, whereas << denotes an output, or the see-out or cout method.
so << makes more sense here
i stole the code for that part from Jack
:(
o nvm jack used lshift too i copied it from eatalian #ot1-perplexing-regexing message
Lmao
Stele also showed me that a few months ago
lambda
A while ago someone posted a way of creating a class that was its own metaclass
Don't suppose anyone has it handy?
XD I laughed myself silly when I first saw it
Hmm
!e
import collections
switch = type(
"switch",
(type("x",(),{"__init__":lambda c, x:setattr(c,'x',x)}),),
{
"__floordiv__"
if not ((case := 0) or (default := None))
else None: lambda a, b: print(
b[a.x] if (case := a.x in b) else b[default], end=" "
)
},
)
for i in range(3):
switch(i) // \
{
case | 0: 'Hello',
case | 1: 'World',
default: '!'
}
@sly token :white_check_mark: Your eval job has completed with return code 0.
Hello World !
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
slice(1, 8, None)
I have to use full raw syntax for slice outside of getitem smh
I am fully disappointed
Why not just replace the class?
Make class getitem for list take a slice and return a range array
What class is being replaced?
I just mean, if the slice class is giving you trouble, why not just whip up a simple subclass of it that does what you want
As I keep saying, SyntaxError is my only weakness
Subclass doesn't fix syntax error or make syntax sugar
Code isn't executed until it passes ast processing
Right now I'm segfault debugging
Problem is when an error is raised, it segfaults before the error finishes raising
So I gotta debug it the old fashioned way
Anyone have a guide to writing bad python?
I'd love to get deep into code gore.
Uh huh. That's not particularly bad.
Yes.
None of those variables will be evaluated.
I can do that. (mostly)
I'm moderately advanced in python.
Check some of my recent posts for an idea of what I've been doing.
there's some common idioms in python code golfs
but it's been a while since i've golfed something
For example, how can I learn to do stuff like this (I mostly understand what this does)?
Well
one sec
from functools import reduce
# Declaring variables
a = 2
(lambda a: None)(2)
# Declaring variables 2
a = 2
b = 3
(lambda a: (lambda b: None)(3))(2)
# Statements
a = 2
print(a)
(lambda a: (print(a),))(2)
# Statements 2
a = []
a.append(1)
print(a)
(lambda a: (a.append(1), print(a)))([])
# Alternating declarations and statements
a = 1
print(a)
b = a + 2
print(b)
(lambda a: (print(a), (lambda b: (print(b),))(a + 2)))(1)
# Inplace operators
a = 1
a += 1
print(a)
(lambda a: (lambda a: (print(a),))(a + 1))(1)
# If statements
a = 1
if a < 3:
print(5)
else:
print(4)
(lambda a: (print(5) if a < 3 else print(4),))(1)
# If statements 2
a = 2
if a < 3:
b = a + 2
print(b)
else:
b = a * 3
print(b)
(lambda a: ((lambda b: (print(b),))(a + 2) if a < 3 else (lambda b: (print(b),))(a * 3),))(2)
# For statements
a = list(range(10))
b = 0
for c in a:
b = b + c
print(b)
(lambda b: (print(b),))(*(lambda a, b: reduce(lambda _vars, c: [_vars[0] + c, *_vars[1:]], a, [b]))(list(range(10)), 0))
# While statements
a = 100
while a > 1:
a /= 2
print(a)
(lambda a: (lambda _: _(a, _))(lambda a, _: (lambda a: _(a, _))(a / 2) if a > 1 else (lambda a: (print(a),))(a)))(100)
read this
u will understand
this isn't too bad, type used this way is a bit like an anonymous class definition
the arguments are:
my_class = type(name, bases, namespace)
just a dict
its evil.
as opposed to :
class name(*bases):
namespace

i recommend you dont, but lets see
you could also do
(lambda __g, __print: [(a.append(1), (__print(a), None)[1])[1] for __g['a'] in [([])]][0])(globals(), __import__('__builtin__', level=0).__dict__['print'])
for a[b] in [c] ==> a[b] = c
anything that can go on the left side of assignments works
er, pretty much anything
for {}[()] in range(10):
...
So what does the
(lambda a: None)(2)
do?
This should always evaluate to None, right?
So within the scope of that line a is defined to a lambda that returns None?
I'm not sure I understand the use of that.
inside the lambda function, a=2
Wait, why?
Because it's passed as a parameter to the lambda
👍
For the 'declaring variables 2' part,
(lambda a: (lambda b: None)(3))(2)
The 3 is passed to the second lambda, so within the scope of the None, b=3. The 2 is passed to the first lambda, and then passed to the second lambda, so...?
names are defined in any inner scopes
So within the scope of the None, a=2 and b=3?
Yes
(lambda a: (print(a),))(2)
This defines a as 2 within the scope of the lambda, but why do we need the tuple? Can't we just do ```py
(lambda a: print(a))(2)
random little challenge:
a = 1
k = lambda: (
# line of code here,
a + 1
)[-1]
print(a)
print(k())
add a single line of code where the comment is to make the output of this snippet:
1
3
Seems simple enough. Does
0,3, work?
oh no
Wouldn't just a:=2, work
no walrus 😛
globals().__setitem__('a', 2)
yep
now heres a variation. lets flip the order of the prints:
print(k())
print(a)
make this print
3
1
3);(0,
3)or(0,
nothing that will break the lambda in any way
it's the same lambda
the lambda must end with the return of a+1
I mean, 1+
theres a subscript
0,1+
ok i shouldve put more thought into this lmao
let me figure out how to describe the exact constraint i want
there are loopholes in all rules
ok, lets jsut go with 1+ doesnt count since its not exactly a+1
the second item in this sequence has to be a+1 and only a+1
hows that
If by "improve" you mean "shorten" without changing things there's a few redundant spaces there
# replace the ellipsis with some code that will result in the final output:
# 3
# 1
# every single line of the code must be executed
a = 1
k = lambda: (
...,
a+1
)[-1]
print(k())
print(a)
ok v2. i think this should be fairly loophole proof. right?
eval('print("3\n1");raise SystemExit')
or something like that
oh good shout, ok every single line of the code must be executed.
Well you haven't said what your definition of "improve" is
So it's impossible to know what you're actually after
globals().__setitem__('print',lambda v,u=iter((3,1)):__builtins__.print(next(u)))
nice
now thats the kind of thing im looking for 😄
not quite there though, output is wrong.
print has already been put on the stack once before k is called
!e
a = 1
k = lambda: (
globals().update(a=2, print=lambda v: __builtins__.print(1)),
a+1
)[-1]
print(k())
print(a)
@proper vault :white_check_mark: Your eval job has completed with return code 0.
001 | 3
002 | 1
👏
wts c_void_p and how does this work 
!e
await ctx.send("h")
@turbid patio :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | SyntaxError: 'await' outside function
well that happens to me
it's a void* in C, the equivalent to "this memory address contains something, probably"
ctypes lets you interface with the low level details of the cpython interpreter
basically that snippet replaces the memory address of True with the memory address (id) of NoMore
why +8 
implementation detail
just the offset to the struct field for PyObject
Mostly a magic number
so it's just printing the str for True here?```py
what = love = object()
what is love
Yes
oh
!e py print(f"hello w{''.join([str(x)[i] for x,i in zip([None] + [bool(x) for x in range(1,-1,-1)],[1,1,2])])}{13:x}")
@lime bane :white_check_mark: Your eval job has completed with return code 0.
hello world
Let's obscure further
!e py print(f"hello w{''.join([str(x)[i] for x,i in zip([None] + [bool(x) for x in range(1,-1,-1)],[1,1,2])])}{13:x}")
@lime bane :white_check_mark: Your eval job has completed with return code 0.
hello world
!e ```
#isnt this more interesting
a = "lol"
k = lambda: (
globals().update(a=2, print=lambda v: builtins.print(1)),
a+1
)[-1]
print(k())
print(a)
@lime bane :white_check_mark: Your eval job has completed with return code 0.
001 | 3
002 | 1
Are we allowed vvalrus?
what
The vvalrus operator :=
#esoteric-python message
For this
i see
with walrus it's so simple that there's no point, so no 😛
if you really want to have some fun do it with: no walrus, no altering globals, no altering builtins
"fun"
well if you want a hint ||the first step would be to figure out how to alter the bytecode of a running function from inside it||
at least thats the solution id use, theres probably something much easier i didnt consider
oh or ||change the value of constants inside the function e.g. 1||
that would actually be a lot easier
I can write bytecode, but I have no clue how to access the function.
Constants would be easy - but ctypes might break a lot of things
@woven bridge I'd love to learn. How would one do this?
I'm aware of how bytecode, CodeTypes and __code__ both work.
so the gist of it is, you get the current fame using inspect.currentframe() or sys._getframe(). once you have the frame, you can get the bytecode with frame.f_code.co_code. then, you can use ctypes to access this bytes object as if it was a plain old c array.
!e
import ctypes
import inspect
def test():
frame = inspect.currentframe()
code = frame.f_code.co_code
code = (ctypes.c_uint8 * len(code)).from_address(id(code)+32)
ctypes.memset(code, 0, len(code))
test()
@woven bridge :x: Your eval job has completed with return code 1.
001 | XXX lineno: 8, opcode: 0
002 | Traceback (most recent call last):
003 | File "<string>", line 10, in <module>
004 | File "<string>", line 8, in test
005 | SystemError: unknown opcode
there. replaced all the bytecode in the function with zeros from inside itself.
f_code is the code object for the current frame. contains the bytecode plus a bunch of extra info that would be needed to execute the bytecode itself. so things like, constant values, names, flags, etc
I'm aware of the structure of code objects. What's a frame?
represents an execution frame on the call stack
or in other words, used to keep track of what functions have been called so far, and the state of the function call. each function call gets its own frame.
What's an execution frame, and I'm guessing the call stack is what it usually refers to?
@woven bridge I used that method in my goto implementation
Goto in python? That sounds amazing.
!e ```py
import sys, dis
from ctypes import c_char
def getmem(addr, size):
return memoryview((c_char*size).from_address(addr)).cast('B')
class Tmeta(type):
def lt(cls, ocls):
frame = sys._getframe(1)
mem = getmem(id(frame.f_code.co_code) + bytes.basicsize - 1, len(frame.f_code.co_code))
instructions = [*dis.get_instructions(frame.f_code)]
for idx, instruction in enumerate(instructions):
if idx * 2 < frame.f_lasti:
continue
if instruction.opname == 'COMPARE_OP' and instruction.argval == '>':
if instructions[idx+1].opname == 'JUMP_FORWARD':
if instructions[idx+2].opname == 'ROT_TWO':
if instructions[idx+3].opname == 'POP_TOP':
inj_code = bytes([
dis.opmap['ROT_TWO'], 0,
dis.opmap['ROT_THREE'], 0,
dis.opmap['CALL_FUNCTION'], 2,
dis.opmap['NOP'], 0,
])
mem[frame.f_lasti] = dis.opmap['POP_TOP']
mem[frame.f_lasti + 2] = dis.opmap['NOP']
mem[idx * 2:idx * 2 + len(inj_code)] = inj_code
return cls
class Array(metaclass=Tmeta):
def init(self, T, args):
self.T = T
self.args = args
def __repr__(self):
return f'{type(self).__name__}<{self.T.__name__}>{self.args}'
class HashMap(metaclass=Tmeta):
def init(self, T, args):
self.T = T
self.args = args
def __repr__(self):
return f'{type(self).__name__}<({", ".join(t.__name__ for t in self.T)})>{self.args}'
a = Array<int>(1,2,3)
b = HashMap<(str, int)>{
'a': 0,
'b': 1
}
print(a, b)
def f():
v = Array<int>(1,2,3)
print(v)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
Array<int>(1, 2, 3) HashMap<(str, int)>{'a': 0, 'b': 1}
in stack based interpreters, like cpython, theres an internal stack called the call stack that gets some info pushed onto it every time a function is called (or in cpythons case also when a module is executed).
also this uses a similar method
lol I remember that that's so cool
this information is the execution frame
in cpython each frame has a reference to the prior frame (until the topmost frame)
its used for things like, figuring out where to return to when a function completes for example. the frame on top of the stack is popped and we continue from where the previous frame left off.
or in tracebacks
when you need to print out the order of calls so far.
Okay, that's what I thought it was. Thanks/
frame.f_lasti is the last instruction executed inside frame
that is used for return
So inspect.currentframe() gets (pops(?)) the top of the call stack?
It just returns a new reference to the topmost frame
Okay.
def getframe(depth=0):
try:raise
except Exception as e:
frame = e.__traceback__.tb_frame
for _ in range(depth + 1):
frame = frame.f_back
return frame``` ^ this also works if you dont want any imports
!e ```py
from ctypes import c_char
def getmem(addr, size):
return memoryview((c_char*size).from_address(addr)).cast('B')
def getframe(depth=0):
try:raise
except Exception as e:
frame = e.traceback.tb_frame
for _ in range(depth + 1):
frame = frame.f_back
return frame
def get_dest(frame, label):
code, names = frame.f_code.co_code, frame.f_code.co_names
frame_var = {**frame.f_globals, **frame.f_locals}.get
ops, args = code[::2], code[1::2]
for idx, (op, arg) in enumerate(zip(ops, args)):
if op == 106 and names[arg] == label and
isinstance(frame_var(names[args[idx - 1]]), Label):
return (idx - 1) * 2
raise RuntimeError(f'label {label!r} not found')
def set_instr(code, idx, op, arg):
code_addr = id(code) + bytes.basicsize - 1
mem = getmem(code_addr, len(code))
(op, arg), mem[idx:idx + 2] = mem[idx:idx + 2], bytes((op, arg))
return op, arg
restore_instr = [None, None, None]
class Goto:
def getattr(self, label):
code = (frame := getframe(1)).f_code.co_code
idx = frame.f_lasti + 2
op, arg = set_instr(code, idx, 114, get_dest(frame, label))
restore_instr[:3] = (idx, op, arg)
mul = getattr
class Label:
def getattr(self, name):
if None not in restore_instr:
frame = getframe(1)
set_instr(frame.f_code.co_code, *restore_instr)
restore_instr[:3] = (None, None, None)
goto = Goto()
label = Label()
x = 0
label .start
print(x)
if x == 10:
goto .end
x += 1
goto .start
label .end```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
011 | 10
^ goto in python
That is art. What's the tb_frame attribute?
so when an exception is raised it has a traceback attached to it __traceback__
the traceback has a reference to the current frame at tb_frame
Oh - tb stands for traceback
@woven bridge what kind of weird stuff have you done with frames?
hmm i think my favourite one was looking ahead in the bytecode to implement the observer pattern for all attributes
it was something like this
class Thing(AllAttributesObservable):
def __init__(self):
self.value = 1234
thing = Thing()
thing.value.on_changed(print)
thing.value = 12 # would print(12)
not sure if that counts as weird necessarily
but i thought it was neat
there was a check in the bytecode to see if the next thing being done was .on_changed and if so it would return some observation proxy instead of whatever attribute
oh yeah i also had a goto implementation that used frame.f_trace and with statements to control flow
I like that accessor thing
code golf again at noon CDT tmrwhttps://emkc.org/contests
let's BEAT LYNDON
also I've been golfin a ruman numeral -> int converter for fun
s=x=0
for y in map(dict(M=1000,D=500,C=100,L=50,X=10,V=5,I=1).get,input()):s-=2*x*(x<y)-y;x=y
print(s)
102 bytes so far
Alright esoteric fun fact.
If you do
@lambda c:c()
class __annotations__:
def __setitem__(self, name, value):
...
You can directly control what annotations do in the global namespace.
Unfortunately local namespaces are less lenient and treat annotations like comments that can still raise SyntaxError
You can even use it to replace the equals sign
this works...
!e ```py
annotations = globals()
ar:[1,2,4] + ar=[5,6]
len: {'len':len}={'len':builtins.len}
Ans: print(Ans) = len['len'] 'len'
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5
This also works
oh
!e ```py
@lambda c:c()
class annotations:
def setitem(self, name, value):
globals()[name] += value
two:0.5 = 2
five:1.0 = 4
print(two + two == five == 5)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
True
wait so could u quickly run thru what happens here lol im a little lost
!e ```py
hack=lambda victim:import('ctypes').py_object.from_address(id(victim)+8)
hack(True).value = type('yay', (int,), {'str':lambda s:'yes, it is.'})
this = beautiful = object()
print( this is beautiful )
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
yes, it is.
So first I set annotations to be the same thing as globals()
So that the setitem does the same as equals
Then annotations are evaluated after the equals
Then ar is instantiated as 5,6, then 1,2,4 plus that.
Then len is made a nested dictionary thing.
Then ans is set, then it's printed
ah ok makes sense
What I did here is a simple example for the general usage of overriding annotations
By default, a dictionary is created when you annotate
!e just seeing if this works ```py
@lambda c:c([0,1,2,3])
class annotations(list):...
0:4
2:1
print(annotations)
@floral meteor :x: Your eval job has completed with return code 1.
001 | File "<string>", line 4
002 | 0:4
003 | ^
004 | SyntaxError: illegal target for annotation
Okay so you're limited a little, you can only use valid names
But type hints are overrated
!e
@lambda c:c()
class __annotations__:
def __init__(self):
self.__items = {}
def __setitem__(self, name, value):
self.__items[name] = globals()[name]
globals()[name] = value
def __str__(self):
return str(self.__items)
test: 5 = 2
print(__annotations__)
print(test)
@gritty mesa :white_check_mark: Your eval job has completed with return code 0.
001 | {'test': 2}
002 | 5
Nice
!e ```py
@lambda c:c()
class annotations(dict):
def setitem (self,name,value):
d=dict.setitem
d(self,name,globals()[name])
d(globals(),name,value)
test: 2+2=5
print(test, annotations)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
4 {'test': 5}
A shorter version, many here code golf so much that using the mouse scroll wheel to read something drives them crazy
You could make a minilang with annotations
print: "Hello World"
set: a = 2
set: b = 2
add: c = a, b
print: c
That's terrifying.
use ctypes.sizeof(ctypes.c_void_p) to get the offset instead
he says, while having \n\n in his program
Can remove 10 redundant spaces there if you wanted
lol
ftr not mine i found it on stack overflow im too dumb to write smtg this succint
Anyone have any idea how I might go about suppressing particular errors globally, for example, I'm handling NameErrors in a sys.excepthook, but I want the process to continue after that exception is raised and handled
Rather than handled then killing the process
a ton of try - except statements?
Not what I'm after here, since I don't want the user to have to add any extra steps to handle it themselves
From math import math as string
from __future__ import annotations
import inspect
@lambda c:c()
class __annotations__:
def __init__(self):
self.__items = {}
def __setitem__(self, name, value):
real_name = inspect.getframeinfo(inspect.currentframe().f_back).code_context[0].split(":")[1].split('=')[0].strip()
globals()[real_name] = globals()[name]
def __str__(self):
return str(self.__items)
let: var = 5
print(var)
```Welp, @maiden blaze found a much nicer solution
*@distant wave
ah yeah it was bast
If you can afford to change your program structure a bit, you could use metaclasses + a custom namespace class to have complete control over names inside a class scope
!e ```py
class N(dict):
def missing(self, key):
print(key)
class M(type):
def prepare(*_): # I forget
return N()
class C(metaclass=M):
foo # normally a NameError
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
001 | __name__
002 | foo
That's a bad habit I've developed cos people complained about my Horror Vacui code style
I just had an evil idea
It involves c and dunder prepare
Remind me tomorrow
First law of code: all whitespace is bad
yes, I know I'm saying this in a python server
what does the victim annotation do?
one viable way i can think of doing as-close-as-possible to this would be to parse the code for a module into an ast, then apply a simple transformation to automatically add try/except around every statement, then recompile back and replace the module with the new code in memory. so minimal extra work needed by the end user aside from a single function call.
aside from that, it is possible to make a frame jump to a different line of code using a combination of sys.settrace and excepthook but the issue is that it seems no matter what, an uncaught exception will result in program termination once it reaches and executes excepthook. id love to be shown otherwise though.
Why doesn't it work for '_' and works for str?(how do I make it work for both?)```py
import(import('ctypes').py_object.from_address(id(import('ctypes'))+(1 << 6)).value).py_object.from_address(id(str)+(1 << 3)).value = type('__', (), {'str':lambda self:'custom str'}); print('_', str)
https://emkc.org/contests/44/sumthing-wrong
Lyndon got the optimal solution again, I thought I had it at 55 and started working on esolangs but they shaved a byte
at least I assume it's optimal
I hope my pyth sol is the shortest of all langs possible >_>
from __future__ import annotations
@lambda c:c()
class __annotations__:
def __setitem__(self, name, value):
globals()[value] = globals()[name]
let: var = 5
print(var)
```Also I just realised half the stuff I had left in was from me messing around with other things earlier, it can be much shorter
ohh so this is what you wanted the exception thing for
it makes annotations into strs instead of expressions
var would need to be defined in the first place otherwise
after much sweat and tears, this now works:
oh you can do string annotations cool
that'd probably make this mess look a bit better
i got so much just to set one attribute on a struct
wow, what but what's that m*n part thing
you know what I mean
also try to add structures like the way I did here: #esoteric-python message, I wanna see how you'd do it, you'd probably do way better than me lol
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
the reason it's so complicated is it's extremely unstable
in fact all exceptions result in an exit -1073741819
and even when it reaches the end or i raise system exit it still exits -1073741819
it doesn't, your screen is too narrow
2 times 4 is 8 :/
i think it's the windows version of 139
just cos it can... doesn't mean you should, naughty python
that's weird
happy?
Yes
included a random asterisk after main(void) cos wierdly placed asterisks are common in various languages
only one colon instead of two in std::cout
I wish in Python there was a way to make a variable with any name, like ANY name, even invalid characters, like the invisible one
what i did with the annotations was actually make a backwards annotations, and then add verbose type hinting and setting the attribute _type of the target to the type
I really wanna see structs
the _garbage_can array was placed to tell over-eager garbage collection where to stick it
cos it was segfaulting on method exit
had to golf it a little```py
class struct:
name='struct'
__obj_id:int=0
class __obj(metaclass=lambda*a:type(*a)()):
count,active=0,[]
def isub(self, obj):
try:
for n,e in enumerate(self.active):
if e is obj:break
self.active[n]=None;self.count-=1
except:pass
return self
def iadd(self, obj):
self.count+=1
self.active+=[None]
for i,e in enumerate(self.active):
if e is None:self.active[i]=obj;obj.__obj_id=int(i);break
return self.active[-1]is None and self.active.pop(-1) or self
def del(self):
struct.__obj-=self
for victim, prisoner in gulag.jail:
if victim is self:gulag[self]=prisoner
def init(self,prev=None,_type=None,**k):
struct.obj+=self
if prev is not None:
g = object.getattribute
for yay in dir(prev):
try:
if g(self, yay)is not g(prev, yay):object.setattr(self, yay, g(prev, yay))
except:pass
[object.setattr(self,*a)for a in k.items()] # !
object.setattr(self, '_type', type or struct)
def repr(self):return'struct: '+self.name+'\n'.join([f'{yay}:{getattr(self,yay)}'for yay in dir(self)if not yay.startswith('')])
def eq(self, other):return hash(self)==hash(other)and dir(self)==dir(other)
def hash(self):return int(self.obj_id)
def rrshift(self, other):return input(other.name+'> ')
def getattribute(self, name):
try:return super().getattribute(name)
except AttributeError:=type(name,(struct,),{})();object.setattr(self,name,);return __
def setattr(self,name,value): # !
try:
object.getattribute(value,'call')
if type(value)is type:raise AttributeError
except AttributeError:object.setattr(self, name, value)
else:
global _garbage_can
sentinal={'name':name,'value':value}
_garbage_can+=[sentinal,(gulag[self],)]
gulag[self]=type('struct',_garbage_can[-1],{name:value})
gulag is previously defined
as
@lambda c:c()
class gulag:
jail = []
def hack(self, victim):
return __import__('ctypes').py_object.from_address(id(victim)+8)
def __getitem__(self, victim):
return self.hack(victim).value
def __setitem__(self, victim=None, imposter=None, name=''):
global _garbage_can
if victim is None:victim = globals()[name]
prisoner = self.hack(victim)
_garbage_can += [victim, prisoner, imposter]
self.jail += [(victim, prisoner.value)]
prisoner.value = imposter
def __del__(self):
for victim, prisoner in self.jail:
self[victim] = prisoner
probably the most dodgy object i've instantiated in python
@lambda c:c()
class __annotations__(dict):
def __setitem__(self, key:str, value:object):
print('declared', value, 'as', key)
t = globals()[key]
super().__setitem__(value.__name__, t)
if hasattr(value, '_type'):
object.__setattr__(value, '_type', t)
assert value._type is t
type: struct
struct._type = struct
class __globals__(gulag[__builtins__.globals()]):
def __missing__(self, name):
global _garbage_can
if type(name)is str:
_ = self[name] = struct(__name__=name)
_garbage_can += [_]
return _
else:return self[name.__name__]
def __setitem__(self, key, value):
super().__setitem__(key, value)
if key in __annotations__ and type(value).__name__ != __annotations__[key].__name__:
print('TypeWarning:', key, 'is not a', type(value).__name__)
type = __builtins__.type
type: int
gulag[__builtins__.int] = type('int',(gulag[int],),{'__name__':'int','main':lambda s,*a:type('function',(),{'__mul__':lambda s,f:f[return_]})()})
void = None
gulag[__builtins__.globals()] = __globals__
cout = struct(__module__='iostreams',_type=struct)
cout.__lt__ = print
cout.__lshift__ = lambda s,o:s.__lt__(end=str(o))or s
std.endl = endl = '\n'
def wrapper(f):
global cin, _garbage_can
cin = struct(__module__='iostreams')
setattr(cin, f.__name__, f)
_garbage_can += [cin, f]
@wrapper
def __rshift__(target:struct,o:struct):
target.entity = globals()[o.__name__]
target.name = target.entity.__name__
target.value = input('')
print('inputting', target.value, 'to variable', target.entity, 'with type', target.entity._type)
for e,t in[*__annotations__.items()]+[(target.entity.__name__,target.entity._type)]:
if e == o.__name__:break
globals()[target.name] = globals()[t](target.value)
#include<iostreams>
int: m;
int: n;
int. main(void)* {
std:cout << "A number: ",
std:cin >> n,
std:cout << 'And another number: ',
std:cin >> m,
std:cout << "Multiplied is " << m*n,
std:cout << std.endl,
return_: m*n,
};
pointers?
the first block is
from ctypes import py_object as p
from builtins import*
import builtins as __builtins__
_garbage_can = []
you know pointers
nope
¯_(ツ)_/¯
It's basically an eight bytes variable whose numeral value stores the memory address of another.
Another thing.
So you can pass copies of the memory address to functions that can later use the address to change the value that's located at that address and thus changing the variable from inside the function
like this? ```py
a = [1,2,3]
p = id(a)
The variable name of an array indeed stores the memory address of the first element
we should make a github repo to work on c methods
That's why you get i+1 for the second element
And whatnot
char *string = "Hello";
putchar(string[3]); // l
putchar(*(string + 3)); // l
Well you could define the array as an actual array with char string[] though
The other code stays the same
It's just that then you can retrieve the actual size of the string in bytes using siseof
And not get 8 which is the size of a pointer, right
sounds like a video driver issue
It's in there somewhere
just somewhere?
Wow 😂
im just saying the stop code VIDEO_DXGKRNL_FATAL_ERROR sounds like a video driver screw up
so unless this module is doing something involving the gpu then i doubt it caused it
huh so there does seem to be something here intended to induce a blue-screen, no idea how it works though. looks like its like some kind of recursion bomb?
DOST THOU DOUBTETH THE CURSEDUTILS?
XD
it makes recursion bomb look like a child's toy
yeah, it only affects windows
!e ```py
from os import abort
class McNuke:#For recreational purposes only
"""Making an instance will do nothing.
deleting an instance will bomb your device.
exit the interpreter or use execute to bomb immediately.
Use provided abort function to cancel."""
purposes = ('recreational',)
def del(self):
try:[self.class()for _ in range(4)]
except BaseException:self.class()
@classmethod
def execute(cls):cls()
McNuke.execute()
@floral meteor :warning: Your eval job timed out or ran out of memory.
[No output]
why does that even work
actually, wait, still have to see it for myself to believe it
it takes about 10 minutes for windows to realise it's dead
it's so bloat ;)
this is like a silver bullet, it is only fatal to windows
but it is still a bit of a pain when you run it in other OSes
!e there's also this: ```py
from os import abort
class McNuke:#For recreational purposes only
purposes = ('recreational',)
def del(self):
try:[self.class()for _ in range(4)]
except BaseException:self.class()
sus = McNuke()
print("I'm perfectly okay!")
@floral meteor :x: Your eval job timed out or ran out of memory.
I'm perfectly okay!
XD
doesn't make sense, right?
It executes the last line but still dies
I shoulda introduced this with the challenge
...
print("done!")
put code at the ellipsis to crash or hang python, but the last line still has to execute
!e ```py
def kill_python(_):
import('os').system("")or import('sys').stderr.write('\x1b[31mFatal Python error: _Py_Decessus: Python has died.\nPython runtime state: deceased\x1b[0m\r\n')
import ctypes,random
while...:ctypes.py_object.from_address(random.randint(111111,id(type("",(),{})())+9)).value=type('DEATH',(type,),{'del':lambdaa:a})('death',(),{})
kill_python()
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
how do i import cursedutils?
@floral meteor
>>> import cursedutils
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\admin\Desktop\cursedutils-cursed\cursedutils-cursed\cursedutils\__init__.py", line 2, in <module>
from.import cursed,death,wrappers,iostreams
File "C:\Users\admin\Desktop\cursedutils-cursed\cursedutils-cursed\cursedutils\cursed.py", line 26
def _bootstrap(*a):
SyntaxError: import * only allowed at module level
rip its broken
!e use this```py
from os import abort
class McNuke:#For recreational purposes only
purposes = ('recreational',)
def del(self):
try:[self.class()for _ in range(4)]
except BaseException:self.class()
sus = McNuke()
print("I'm perfectly okay!")
@floral meteor :x: Your eval job timed out or ran out of memory.
I'm perfectly okay!
alright, now just wait ~10 minutes?
oh
that didnt work
just gave a bunch of memoryerror exceptions and then exited
no blue screen
(bot:=(commands:=__import__("importlib").import_module(".commands", "discord.ext")).Bot(command_prefix="!")) and (hi:=bot.command(name="hi")(__import__("asyncio").coroutine(lambda ctx:(await ctx.send("hello") for _ in '_').__anext__()))) and bot.run("")
one line discord bot lol
code gore 
Nice async lambda
hsp needs to be nerfed
Yes
you on windows?
hmm
whats the mechanism behind it?
it should catch MemoryError
@maiden blaze I didn't know lambdas could be coroutines
me neither
And can you await that thing though?
pretty sure the lambda isnt a coroutine its just the generator inside thats an async generator
anonymity doesnt really factor in here
@maiden blaze add an event to that too
i'm giving a test atm lol
show me
Alright I ran it, nothing happened for about 10 minutes, then pycharm just disappeared.
^before.
After:
well i cant even import cursedutils
hell
let alone run whatever it is youre running there
Then the gpu spiked and the screen went black
check out #❓|how-to-get-help
Alright which red dot is my cursor?
Cos it's one of them
It's been a lot of minutes it ain't blue yet
Last test was on version 3.7
It finally froze
Nope still going
This computer definitely isn't usable
It's definitely a problem with graphics
Does restarting work or did you just screw your computer forever
Of course restart works I'm waiting for bluescreen
Anyways I'm upgrading on Wednesday so I can do anything to this one I don't need it
alright attempt 2
lol the cpu is flat 100%
Hey it worked!
Congratulations, blue screen of death... ACHIEVEMENT UNLOCKED
I got a background app report an error and a dialogue box, then blue.
@woven bridge it seems to work best from the terminal
I.e. command prompt
like this. keyboard interrupt for extra effect
Hey it only took 5 minutes that time
I still haven't got MemoryError
from time import sleep
__import__('os').system('')
def main():
s=0
print('\x1b[s:)',end='\x1b[u')
while True:
sleep(0.1)
s = not s
print(f'\x1b[u\x1b[{31*s}m:\x1b[0m)')
main()
so the question is why does the above sometimes flash the red eyes on the spot, and sometimes prints a new line for each smiley?
Bro I thought you wanted to esoterify that
it's implicit behaviour, implicit behaviour can be exploited
specifically, only the first run keeps the smiley face in the same spot
How does this work?
What's an annotation?
@sick hound :white_check_mark: Your eval job has completed with return code 0.
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': <__main__.__annotations__ object at 0x7f8bbb92df10>, '__builtins__': <module 'builtins' (built-in)>, 'annotations': _Feature((3, 7, 0, 'beta', 1), (3, 10, 0, 'alpha', 0), 16777216), 'let': 5, 'var': 5}
So __annotations__.__setitem__ has been overwritten?
can't talk rn, can I ask later?
# module.py
class FakeAll:
max = 1
def __getitem__(self, key):
if key >= self.max:
self.max += 1
raise KeyError
return f"x_{key}"
__all__ = FakeAll()
for i in range(10):
globals()[f"x_{i}"] = i
# main.py
from module import *
print(x_0)
try:
print(x_1)
except NameError:
print("not defined yet")
from module import *
from module import *
from module import *
from module import *
print(x_1, x_2, x_3, x_4)
# output
0
not defined yet
1 2 3 4
similar trick, but instead overriding __all__
Alright, I'm back
So annotations look like identifier [: expression] [= expression]
So can you just have identifier, or do you need one of expression/=expression
Also, how do annotations happen outside parameters?
Also, is __annotations__ global? I have so many questions.
an annotation is just when you add : whatever to something
Scopes have (usually) an __annotations__ variable storing the dict of top level annotations
Functions & classes have a __annotations__ attribute, for function parameters and class member annotations respectively
x: int __annotations__=={'x':int}
def foo(x:int) foo.__annotations__=={'x':int}
class Foo: x: int Foo.__annotations__=={'x':int}
just starting with one liners and things. how do i make dunders in a class thats made from type()
like
type('Testing', (object,), {'content':{'__init__':lambda self,x:...}})()
doesnt work
That should raise a TypeError cause you aren't passing x
no it doesnt work at all
Oh wait I see what you're doing
if i pass x
yeye
so functions shouldnt be inside the content key heh
!eval
type('Testing', (object,), {'__init__':lambda self,x:[None for self.x in [x]][0],'owo':lambda self:print(self.x),'content':{}})(120).owo()
@nimble heron :white_check_mark: Your eval job has completed with return code 0.
120
Thanks.
So now how does this allow for it to run like code?
Is it being called on the __setattr__ when name and value are being passed?
>>> class __annotations__:
def __setattr__(self,name,value):
print(name,value)
>>> a:2
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
a:2
TypeError: 'type' object does not support item assignment
Why does this throw a typerror?
Is that specific to __annotations__?
Even with __setitem__ it throws the same error
@golden finch You need to create an instance of the class
Otherwise it's trying to call the setitem of the class itself
What does that do?
I'm moderately used to decorators
[as in, I know they exist]
Okay, that's understandable
so it passes annotations to the lambda and returns an instance on calling it
@rugged sparrow whats the deal with str.__basicsize__?
it's way larger than it should be
!e
string = "this is an example string"
print(string.__sizeof__() - len(string))
print(str.__basicsize__)
@woven bridge :white_check_mark: Your eval job has completed with return code 0.
001 | 49
002 | 80
what would decided which strings are fixed length?
if theyre below a certain number of characters?
cause in that case:
for i in range(1_000_000):
string = ' '*i
if string.__sizeof__() - len(string) != 49:
print(i)
this doesnt print any output, if there was some kind of type distinction between small and large strings.
Strings are weird with how python handles them
There are different types of strings internally depending on the content of a string
oh i see thanks
is there somewhere you know of in the docs or the source to see the string type selection methods?
This article is old but seems to still detail most of strings correctly
It's not quite correct anymore, because Python switched to the following flexible representation - depending on the characters, it's stored as 8-bit, 16-bit or 32-bit.
!pep 393
can someone pls give me a basic python exercice
make a calculator in one line
that decorator overthrows the whole hierarchy of class and object.
you start with the object obj, and if you want the class, evaluate cls = type(obj)
instead of the standard cls and obj = cls()
!e here's another example of it's usage ```py
call = lambda*a,**k:lambda c:c(*a,**k) # the magic decorator ;)
@call()
class dunder:
call = lambda self,s:str(s).format(f'_^{4+len(str(s))}s')
def format(self, s):
return self(s)
@call(dunder, print)
def main(dunder, disp):
disp(f"{eval(f'(2).{dunder:add}(3)')=}")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
eval(f'(2).{dunder:add}(3)')=5
;)
!e I think I can add that to my list of wierd edit codes ```py
print(-((1<<32)-0xe0434352))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
-532462766
dafaq is dis
o
imagien using __lshift__ and python's scientific numbers
just translating the error to a signed integer in base 10 with 2s complement
i just realised
ive never printed a negative number in Python wtf
maybe i have like 3 years back
no idea.. i dont think i remember printing one
cookies go brr 
!e you mean ```py
call = lambda*a,**k:lambda c:c(*a,**k) # the magic decorator ;)
@call()
class dunder:
call = lambda self,s:str(s).format(f'_^{4+len(str(s))}s')
def format(self, s):
return self(s)
print(f"{eval(f'(1).{dunder:lshift}(32)')=}")
uhm
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
eval(f'(1).{dunder:lshift}(32)')=4294967296
i mean that lol
!e ```py
call = lambda*a,**k:lambda c:c(*a,**k) # the magic decorator ;)
@call()
class dunder:
call = lambda self,s:str(s).format(f'_^{4+len(str(s))}s')
def format(self, s):
return self(s)
@call('call')
def main(s):
print( dunder(s))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
__call__
can someone pls give me a basic python exersise
how basic?
basic exercise: make a BASIC interpreter
is there a way I can use these expressions in one line?
for _ in __: if __: try: ____() except: _____() finally: if ___: (lambda x: if x: print(x))
Yes, but it requires some rewriting
if -> a if c else b
for -> [a for b in c]
for try give me a bit
you probably shouldn't have exceptions in the first place
always check variables to achieve that true one-liner-ness
thanks!
(but some exceptions don't work that way)
wdym?
can you give me an example?
idk for now
i mean, we can avoid keyerrors
?
how does that work for try excepts
0 if "a" in {"a":1} else 1
else None if I need only if right?
or empty sequence(idk if empty sequence's have different value from None)?
!e
print(type(
'test',
(__import__('contextlib').ContextDecorator,),
dict(__enter__=lambda *_:0, __exit__=lambda s, tb, e, c: isinstance(e, ValueError)),
)()(int)('123'))
```is about how you do it, but it requires an import and it is quite verbose
@proper vault :white_check_mark: Your eval job has completed with return code 0.
123
?
for try excepts?(I still have 3+ common modules to look at so idk wt that does)
yup, that's ```py
def fun(a):
try:
return int(a)
except ValueError:
return None
o
you use a context manager to do the exception handling, and a ContextDecorator to run it on a function
do I look about it later or lemme resume looking through functools/itertools?
cuz it looks fun
up to you
there is also a different solution with excepthook, but that one is even stranger
the only way to achieve a TRUE one-liner is write bytecode
change my mind
wts that
I've got one python line using 12gb of memory and that line is [...,_()][0]
Power usage: Very high
Wait why is it using disk?
40 MB/s
30% cpu
The other process that is actually visually doing something is only using a flat 0.9mb
It's the flashing red eyes ;)
Now it's using 70 mb/s disk
80
Why is it using disk? There's no hardrive read or write operations
The eyes stopped flashing momentarily.
I'm gonna have to beef up cursedutils
Why is it esoteric? It's literally the most memory inefficient code possible
!e
print({True: 'True', 1: '1', 1.0: '1.0'})
@sly token :white_check_mark: Your eval job has completed with return code 0.
{True: '1.0'}
disgusting
hash
I know
!e print(type(1.0))
@knotty delta :white_check_mark: Your eval job has completed with return code 0.
<class 'float'>
hm
pagefile?
ouch
You should learn C++
you wonder?
Yes
I'll only do that if I have to
wow
i got a beefier computer to test death.py and my computer just killed python before it could do any damage
ah here we go, it seems to only work from command prompt 🤔
revision to death.py: summon prompt instance to handle devastation
Memory exhaustion which crashes graphics drivers.
However for some reason it only works from command prompt
I still haven't achieved blue screen on my new laptop, but not for lack of trying
send the code lol
I can't remember how to update packages but I remember it being painful otherwise cursedutils would be fixed already
wdym a float and bool has the same value
A bool is a subclass of int and therefore True==1
pretty sure float and int are quite different
!e print(True==1)
@edgy spire :white_check_mark: Your eval job has completed with return code 0.
True
Anywhere in the standard library (and most other libraries) anywhere you can use a float you can use an int
Sort of but not really. Lakmotioil explained in the message above this
Python demands that all numeric types have compatible hashing and equality
No, they are different types that share a number of interoperable protocols
Duck typing and all that
But python type checkers should accept when 1 is passed as a float
In fact 0.5 and the fraction 1/2 also compare equal
o
!e print({1, True, 1.0})
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
{1}
!e
from decimal import Decimal
from fractions import Fraction
print({1, True, 1.0, Decimal(1), Fraction(1, 1)})
@maiden blaze :white_check_mark: Your eval job has completed with return code 0.
{1}
Hey @rose minnow!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Darn Python bot. lol
Thanks to the brief assistance, I have compiled a list of the first 100,000 prime numbers.
I was gonna send the list but the bot sniped me down. haha
!e
from math import sqrt
n = [2]
x = 2
while len(n) < 100000:
x += 1
prime = True
for y in n:
if y > sqrt(x):
break
if not x % y:
prime = False
break
n += [x] * prime
print(n)
@simple crystal :warning: Your eval job timed out or ran out of memory.
[No output]
!e
from math import sqrt
n = [2]
x = 2
while len(n) < 100000:
x += 1
prime = True
s = sqrt(x)
for y in n:
if y > s:
break
if not x % y:
prime = False
break
n += [x] * prime
print(n)
@simple crystal :warning: Your eval job timed out or ran out of memory.
[No output]
Can a type exist without deriving from object? Including both the class and the mro?
Optimized the algorithm and I used Python to generate the first million primes in about 10 minutes.
https://github.com/Dominexis/Projects/blob/main/Miscellaneous/First Million Primes.txt
I kinda want the first billion primes now but the file is ludicrously large.
It would be like 10 GB if I went the first billion primes.
My computer doesn't even have that much RAM so I'm gonna have to pass for now. lol
Ram wouldn't be the limitation if you wrote each prime to the file as you calculate it.
yeah, just be careful with flushing
Though if the whole thing is one line, you should be fine with the default
Hard to do that since it has to compare the test value against the list of known primes.
from math import sqrt
with open('primes.txt', 'w') as p:
p.write('2\n')
x = 2
n = 1
to = 10000000000
while n < to:
x += 1
prime = True
s = sqrt(x)
with open('primes.txt', 'r') as p:
for y in p:
i = int(y)
if i > s:
break
if not x % i:
prime = False
break
with open('primes.txt', 'a') as p:
p.write((str(x) + '\n') * prime)
n += prime
iterates through file list to test values. slow of course.
hmm but does it open an entire txt file in memory (I don't think so)
Seems slower than it keeping the list in RAM.
of course but it's not hard to do
I see.
looking for python coders to be friends and crating games
hi guys
Is that necessarily faster though?
Assuming you start with a list range(n), and you remove entries as you go to isolate the primes, how would you take a step along the list between multiples of a given prime?
Since if all the even numbers are missing, finding the next multiple of 3 in the list will require an irregular step, should it not?
Unless you don't remove them.
Hmm, having a parallel list to store the state could work.
A binary list.
And every time you find a new prime you add it to a third list.
Maybe you can make an array before you do any of this
let's say n, an array of length n
with just 1s
so an array of length n filled with truthy objects
And set them to 0 if the number associated with it is ruled out?
Yeah
you can see it's getting all the evens first
I'm looking. lol
I'm familiar with the algorithm, I just haven't implemented it before.
you can get these numbers for each time your index is incrementing by: py range(index * index, n+1, index)
Though I worry about memory though since to find the first million primes, the list has to have over 15 million entries from the beginning.
Unless of course you optimize it to skip over certain values.
Oh I see.
got about half a billion primes with a sieve but much more and my 16 gb mem isn't enough
It is a bit inefficient how it's making a HUGE array before hand, but that really depends what n is
Yeah, this was my primary concern.
Maybe you can create checkpoints every something primes it generates, and then just load it from disk
Perhaps, perhaps.
how's this
!e
class MetaMeta(type):
def __new__(mcs, name, bases, namespace):
namespace['__mro__'] = tuple()
cls = super().__new__(mcs, name, bases, namespace)
cls.__class__ = cls
cls.__mro__ = (cls,)
return cls
class Meta(type, metaclass=MetaMeta):
pass
if __name__ == '__main__':
print(type(Meta) is Meta)
print(Meta.__mro__)
@woven bridge :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | (<class '__main__.Meta'>,)
unfortunately isinstance(Meta, object) still returns True though
__instancecheck__?
yeah, MetaMeta.__instancecheck__ can just return False for object
hello everyone
is there such a function as zip_longest from itertools, but that looks at the shortest array instead?
i.e. to stop adding arrays when it reaches the len of the shortest array in zip_shortest
from itertools import zip_longest
A = np.array(list_of_arrays_A)
B = np.array(list_of_arrays_B)
C_vectors_list = [a + b for a, b in zip_longest(A, B, fillvalue=0)]
This is my work
that's just zip
how would this work? isnt __instancecheck__ only for checking instances of the current type?
define it on the meta meta so Meta can be "not an object"
not sure i follow. wouldnt that require overriding object.__instancecheck__ instead?
I tried with these 2 lists
a = np.array([[1,2,3], [1,2,3], [2, 0, 1], [1, 1, 3]])
b = np.array([[1,2,3], [2,6,4], [2, 0, 0]])
And it doesn't work...
this is better suited to one of the help channels. see #❓|how-to-get-help
thanks man 😄
Oh goodness...
The method of checking against every known prime took about 10 minutes for a million primes.
The sieve method took less than a minute.
Yet another massive optimization.
I may have gone overkill. lol
Now I know that there are 5761455 primes below a hundred million.
Good to know.
It finished computing in about a minute.
print("\n Sieve of Eratosthenes\n")
limit = 100000000
boolean_array = [True] * limit
primes = []
for entry in range(2,limit,1):
if boolean_array[entry] == True:
primes.append(entry)
for multiple in range(entry*entry,limit,entry):
boolean_array[multiple] = False
with open("Sieve Prime List.txt", "w") as file:
file.write("First " + str(len(primes)) + " primes: " + str(primes))
print(f"\n First {len(primes)} primes: {primes}")
while True:
pass
Feel free to critique my code style.
Whitespace?
I like whitespaces, it makes it easier to read.
I'm gonna add another zero.
Find every prime up to a billion.
See how long it takes. lol
Duel of the Fates music starts playing.
Nope, guess not. LOL
MemoryError
maybe bit magic instead of an list?
I was thinking something along those lines.
But I think I'm gonna take a break from primes for now.
Got another project to work on.
I disagree.
How do you like your code?
whitespaces?
What am I looking at here?
Do you mean with the indenting or are we using "whitespace" to describe two different things?
indenting?
indenting is overrated i'm talking about the entire column dedicated to the space character, character 32
Why would you do that though?
this is #esoteric-python, these things must be done
Your IDE certainly seems to hate it.
my IDE hates most things I do
Uhuh.
Well, I'm going to continue using plenty of comments, white spacing, and indenting.
Languages that use semicolons to end commands are more kind to these kinds of things in my experience.
Are semicolons taboo here? lol
It hates my version of assertion
This is one of the strangest ways I've seen someone code in a while.
try scrolling up :/
I only came to this channel since none of the others seemed to fit.
Maybe I should just mute this channel. haha
IDE hates my nice, compact code
These bits don't even need to be indented. IDE doesn't like it tho
spaces around brackets is lame
despite complaints from IDE, this script works perfectly
You can make it even faster
I can show you how if you can send your code
I can help you optimize it
though, you would need some external libraries
I don't think I'm interested in the old method considering that the new method did it many times faster.
I sent it here: #esoteric-python message
Alright, I'll be back later
you scare me
boo! 👻
I managed to lower the speed all the down to like 1 second for 100 million primes
The == True is redundant, because x == True is just x for either Boolean. Besides, for singleton values like True, False and None, it can be more precise to compare using is rather than ==.
alright time for my weekly spin on brainfuck
Noted.
!e ```py
chars = '+-<>.,[]'
def call(self,code,input=input):
from collections import defaultdict as d
l=input==builtins.input
if not l:input=lambda i=1:input.pop(i-1)
a,o=d(int),''
i=p=t=0
for c in iter(lambda:code[p],''):
def __0(i,):
a[i]+=1
a[i]%=256
return i,,0
def __1(i,):
a[i]-=1
a[i]%=256
return i,,0
def __2(i,o):
o+=chr(a[i])
return i,o,0
def __3(i,):
a[i]+=ord(input(1))%256
return i,,0
f = [__0,__1,
lambda i,:(i+1,,0),
lambda i,:(i-1,,0),
__2,__3,
lambda i,o:(i,o,int(not a[i])),
lambda i,o:(i,o,---bool(a[i])),
lambda*:(*,0)][chars.find(c)]
if t:
t+=(c=='[')-(c==']')
else:
i,o,t=f(i,o)
p+=1-2*(t<0)
try:code[p]
except IndexError:break
return o
@lambda c:c()
class brainfuck:
def format(self, spec):
return self(code=spec)
call = call
print(f"{brainfuck:++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+This is a comment.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.}")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
@rose minnow maybe try this: ```py
@njit(parallel=True)
def soe(limit: int=100_000_000) -> np.array:
boolean_array: np.array = np.ones(limit, dtype=np.uint32)
for entry in range(2, limit):
if boolean_array[entry]:
boolean_array[entry] = entry
boolean_array[entry*entry::entry] = 0
return boolean_array```, `njit` is from `numba` and `np` is `numpy`
for me, it took about 1.5 seconds to complete
Though, I think using Cython can make it even faster
Not sure what most of these notational tricks do, but cool.
notational tricks?
I only occasionally use Python so most of the more subtle tricks I'm unfamiliar with.
You should try to run it
My primary language is MCFunction.
but you gotta set up the modules before you run it though
!e ```py
chars='+-<>.,[]'
@lambda c:c()
class annotations:
def setitem(self, name, s):
if name in globals():
globals()name
elif name in builtins.dict:
getattr(builtins,name)(s)
else:
globals()[name] = s
def brainfuck(code,input=input):
from collections import defaultdict as d
l=input==builtins.input
if not l:input=lambda i=1:input.pop(i-1)
a,o=d(int),''
i=p=t=0
for c in iter(lambda:code[p],''):
def __0(i,):
a[i]+=1
a[i]%=256
return i,,0
def __1(i,):
a[i]-=1
a[i]%=256
return i,,0
def __2(i,o):
o+=chr(a[i])
return i,o,0
def __3(i,):
a[i]+=ord(input(1))%256
return i,,0
f = [__0,__1,
lambda i,:(i+1,,0),
lambda i,:(i-1,,0),
__2,__3,
lambda i,o:(i,o,int(not a[i])),
lambda i,o:(i,o,---bool(a[i])),
lambda*:(*,0)][chars.find(c)]
if t:
t+=(c=='[')-(c==']')
else:
i,o,t=f(i,o)
p+=1-2*(t<0)
try:code[p]
except IndexError:break
print(o)
print: "executing code."
brainfuck: "++++++++++[>+++>+++++++>++++++++>++++++++++>+++++++++++<<<<<-]>>++.-->>+.+++++++..-------->+This is a comment.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++."
print: "code execution complete" = lambda s:builtins.print(s,end='!')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | executing code.
002 | Hello World!
003 | code execution complete!
O_o
that's rule2ing art
rule2ing art?
I assumed that the second rule in this server was anti-swearing
(discord's terms of service doesn't disallow cursing)
Some servers do though.
What is esoteric python?
see the channel description
I don't get it
weird stuff that youre usually not supposed to do
messing with python internals, trying to bend the language in weird unconventional ways, writing really dense hard to understand code, etc
golfing = get the shortest possible code to do a certain thing
not sure why it's called golfing but thats what it means in programming
python vm languages = i guess making up weird languages that compile to python bytecode, or otherwise writing interpreters for other languages using python
obfuscation = making code hard to understand or decipher
code gore = just unbelievable ugly disgusting abuses of the language that make you look away in horror
ohh i see
ah
lol thats fun
enjoy it
i've written a program that creates ascii triangles
_ = input('instructions:\nthis program makes ASCII right triangles having the right angle vertex on the left.\nWrite "+" if you want it on the top left or "-" if you want it on the bottom.\nThen write the height.\n(example of a valid instruction "+12"): ')
for _ in range([int(_[1:]),0, 0][["-",0,"+"].index(_[0])],[0,0,int(_[1:])+1][["-",0,"+"].index(_[0])],["-",0,"+"].index(_[0])-1):print("#"*_)
originally this was an if statement bruh
ooh if we can talk about languages written in Python here check out Jelly
very weird golfing language which uses "chains" or "links" of various arities
instead of a stack or variables
paradoc is even weirder but since its somewhat undocumented I've never gotten it to work
pyth is also in Python though it's pretty simple, prefix operators and variables and is basically just python
I wanna write a stack-based golfing language that does more stuff implicitly, like digging through the stack and swapping stack values to find suitable arguments for functions
Just type
ctrl-[[48;2;0;0;255m :( DXGKRNL VIDEO FATAL ERROR ctrl-[[0m
In the python console and it looks cool
edit: i had one of the numebrs wrong lol
because golf is going for the fewest hits possible
can I change this to a one-liner without semicolons/multiple statements?```py
if _ == __: nonlocal ; return ( := True)
I presume you don't want eval?
how far back in the scope is ___?
cause you could probably just do something like return __import__('sys')._getframe(n).f_locals['___'] if _==__ else (___:=True)
performance really does not matter in oneliners
if you care about performance and dont want to recalculate stuff - use the walrus operator (:=)
I can't even begin to comprehend the code I wrote a few months back. Not as bad as some of the stuff here though
What does it even do?
!e
print(foo := 100)
print(foo)
print()
print(foo := foo + 1)
print(foo)
@flat zodiac :white_check_mark: Your eval job has completed with return code 0.
001 | 100
002 | 100
003 |
004 | 101
005 | 101
basically, it assigns a value to a name and returns the value
Ohhh
very useful in one-liners, not very much in general coding
I find it useful in ifs and whiles
concept: a __juxtapose__ dunder that's applied when two expressions are next to each other
note: ambiguity. x(), x[y], x+x, x-x, f"" are all ambiguous. for the sake of fun, assume juxtaposition takes precedence unless missing or NotImplemented :)
pros: a couple probably
cons: parsing and readability
Yes but it's not semantically the same and it's gonna hurt
Then to test if it needs a juxtapose, you have to evaluate the left hand side. You have to evaluate the LHS before parsing. So you have to rewrite the entire parser, it's now interpreted char-by-char
I'm thinking of redoing natural number syntax using class prepare overrides
How do I proficiently override how class blocks are parsed?
Parsed or ran?
