#esoteric-python

1 messages · Page 120 of 1

floral meteor
#

in this one im replacing NameError after it's raised, so that it shows up weird in the traceback of the next raise

woven bridge
#

very dank

tribal moon
#

one line it

floral meteor
#

correct

#

blew my mind for about 5 seconds then i exploited it for obfuscation

woven bridge
floral meteor
#

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

night quarryBOT
#

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

001 | <__main__.struct object at 0x7f17cf429fd0>
002 | Hello World!
tribal moon
#

what is this

#

ohhh

floral meteor
#

how i use annotations ;)

tribal moon
#

I wish :: existed in Python lol

floral meteor
#

as i said earlier, type hints are overrated

#

I wish || and && existed in python

tribal moon
#

closest is xor and and

floral meteor
#

|| is a much better syntax for that failed expression exception handling pep

tribal moon
#

I wish #define existed in Python

floral meteor
#

then a except B:c or whatever it was

tribal moon
#

imagine that

#

oh boy

#

that'd be awesome

#

imagine the things you can make

floral meteor
#

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

tribal moon
#

I wanna make structs

#

I made like the c thing before I forgot where it was

#

it was fun but it needs a struct

floral meteor
#

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

night quarryBOT
#

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

Hello World!
floral meteor
#

"safe hacking"

floral meteor
#

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,
m
n
};

night quarryBOT
#

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

[No output]
floral meteor
#

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?

tribal moon
#

!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

night quarryBOT
#

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

yes! it works

#

I know that's not how you set struct things rect.width(5) but it's an expression so yeah

floral meteor
#

setattr?

tribal moon
#

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

floral meteor
#

ah i see

tribal moon
#

like making these typeclass things is really confusing

floral meteor
#

I legit broke pycharm

tribal moon
#

my god its so confusing

floral meteor
#
Process finished with exit code -1073740791 (0xC0000409)
#

haven't seen that exit code yet

tribal moon
#

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

night quarryBOT
#

@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'
tribal moon
#

cool

#

you can also access dynamic memory allocating functions like malloc, calloc, and realloc

#

it does what expected

#

pretty cool I like ctypes

tribal moon
#

python can't take it anymore from you lol

floral meteor
#

I killed missing is what happened

tribal moon
#

How do you like get the value with ctypes

#

hold on one second

floral meteor
#
Process finished with exit code -1073741819 (0xC0000005)
tribal moon
#

What does that even mean

floral meteor
#

so far I've seen ```py
-1073741819: 0xC0000005
-1073741818: 0xC0000006
-1073740791: 0xC0000409

tribal moon
#

yeah error codes are confusing

floral meteor
#

especially these ones

tribal moon
#

typing

#

must be a horrible error code

floral meteor
#

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

tribal moon
#

Yeah I have no idea

#

my code is not esoteric enough to get those codes

floral meteor
#

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)

night quarryBOT
#

@floral meteor :warning: Your eval job has completed with return code 32.

[No output]
floral meteor
#

note: 0xC0000420 != 32

tribal moon
#

Didn't know you could do that

tribal moon
#

add some other cool stuff

maiden blaze
#

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

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

001 | hello
002 | world
sick hound
night quarryBOT
#

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

001 | hello
002 | world
sick hound
#

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

maiden blaze
#

whomst hath pingedeth me

#

O

#

hm

sick hound
#

:D

maiden blaze
#

i stole the code for that part from Jack

sick hound
#

:(

maiden blaze
sick hound
#

Lmao

terse mortar
tribal moon
#

lambda

maiden vine
#

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

floral meteor
#

Hmm

sly token
#

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

@sly token :white_check_mark: Your eval job has completed with return code 0.

Hello World ! 
floral meteor
#

I made a functional decorator suite for that

#

!e ```py
print(slice(1,8))

night quarryBOT
#

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

slice(1, 8, None)
floral meteor
#

I have to use full raw syntax for slice outside of getitem smh

#

I am fully disappointed

maiden vine
#

Why not just replace the class?

floral meteor
#

Make class getitem for list take a slice and return a range array

floral meteor
maiden vine
#

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

floral meteor
#

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

golden finch
#

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.

zealous widget
#

there's some common idioms in python code golfs

#

but it's been a while since i've golfed something

golden finch
sick hound
#

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

zealous widget
#

the arguments are:

my_class = type(name, bases, namespace)
sick hound
#

namespace MonkaNANI

#

some evil shit

earnest wing
#

just a dict

sick hound
#

its evil.

zealous widget
#

as opposed to :

class name(*bases):
    namespace
sick hound
#

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

for a[b] in [c] ==> a[b] = c

#

anything that can go on the left side of assignments works

#

er, pretty much anything

zealous widget
#
for {}[()] in range(10):
    ...
earnest wing
#

always

#

as an expression at least

golden finch
earnest wing
#

yes

#

but it does define a inside the lambda scope

golden finch
#

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.

earnest wing
#

inside the lambda function, a=2

golden finch
#

Wait, why?

earnest wing
#

Because it's passed as a parameter to the lambda

golden finch
#

Ah, that makes sense. I didn't consider that.

#

So within the scope of None, a=2?

earnest wing
#

👍

golden finch
#

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

earnest wing
#

names are defined in any inner scopes

golden finch
#

So within the scope of the None, a=2 and b=3?

earnest wing
#

Yes

golden finch
#
(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)

woven bridge
#

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
golden finch
#

Seems simple enough. Does
0,3, work?

woven bridge
#

good point

#

there, changed the [1] to [-1]

golden finch
#

oh no

proper vault
#

Wouldn't just a:=2, work

woven bridge
#

no walrus 😛

proper vault
#

globals().__setitem__('a', 2)

woven bridge
#

yep

#

now heres a variation. lets flip the order of the prints:

print(k())
print(a)

make this print

3
1
earnest wing
#

3);(0,

woven bridge
#

lmao

#

ok, no semicolons either

earnest wing
#

3)or(0,

woven bridge
#

nothing that will break the lambda in any way

earnest wing
#

it's the same lambda

woven bridge
#

the lambda must end with the return of a+1

proper vault
#

I mean, 1+

woven bridge
#

theres a subscript

earnest wing
#

0,1+

woven bridge
#

ok i shouldve put more thought into this lmao

#

let me figure out how to describe the exact constraint i want

golden finch
#

there are loopholes in all rules

woven bridge
#

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

last locust
#

If by "improve" you mean "shorten" without changing things there's a few redundant spaces there

woven bridge
#
# 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?

golden finch
#
eval('print("3\n1");raise SystemExit')

or something like that

woven bridge
#

oh good shout, ok every single line of the code must be executed.

last locust
#

Well you haven't said what your definition of "improve" is

#

So it's impossible to know what you're actually after

proper vault
#

globals().__setitem__('print',lambda v,u=iter((3,1)):__builtins__.print(next(u)))

woven bridge
#

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

proper vault
#

!e

a = 1
k = lambda: (
    globals().update(a=2, print=lambda v: __builtins__.print(1)),
    a+1
)[-1]

print(k())
print(a)
night quarryBOT
#

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

001 | 3
002 | 1
proper vault
#

there we go

#

arguably even more esoteric than the previous solution

woven bridge
#

👏

earnest wing
#

forbiddenfruit.curse(tuple,'__getitem__',lambda*_:3)

#

:>

warm cape
#

wts c_void_p and how does this work KannaWonder

turbid patio
#

!e

await ctx.send("h")
night quarryBOT
#

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

001 |   File "<string>", line 1
002 | SyntaxError: 'await' outside function
turbid patio
#

well that happens to me

earnest wing
#

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

warm cape
#

so what does it do here?```py
c_void_p.from_address(id(True)+8).value = id(NoMore)

#

oh

earnest wing
#

er,

#

it replaces the pointer to True's class

#

which is at the +8 offset

warm cape
#

why +8 KannaWonder

earnest wing
#

implementation detail

#

just the offset to the struct field for PyObject

#

Mostly a magic number

warm cape
#

so it's just printing the str for True here?```py

what = love = object()
what is love

earnest wing
#

Yes

warm cape
#

oh

lime bane
#

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

night quarryBOT
#

@lime bane :white_check_mark: Your eval job has completed with return code 0.

hello world
lime bane
#

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

night quarryBOT
#

@lime bane :white_check_mark: Your eval job has completed with return code 0.

hello world
lime bane
night quarryBOT
#

@lime bane :white_check_mark: Your eval job has completed with return code 0.

001 | 3
002 | 1
golden finch
#

Are we allowed vvalrus?

vestal solstice
#

what

golden finch
#

The vvalrus operator :=

vestal solstice
#

ok, what do you mean by allowed

#

you have my permission

golden finch
vestal solstice
#

i see

woven bridge
#

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"

golden finch
#

Hmmm. I'm not skilled enough to do that.

#

fun™️

woven bridge
#

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

golden finch
#

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.

woven bridge
#

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

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

there. replaced all the bytecode in the function with zeros from inside itself.

golden finch
#

dear god

#

So what's frame.f_code?

#

Also, what's the execution order?

woven bridge
#

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

golden finch
#

I'm aware of the structure of code objects. What's a frame?

woven bridge
#

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.

golden finch
#

What's an execution frame, and I'm guessing the call stack is what it usually refers to?

rugged sparrow
#

@woven bridge I used that method in my goto implementation

golden finch
#

Goto in python? That sounds amazing.

rugged sparrow
#

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

night quarryBOT
#

@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}
woven bridge
#

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

rugged sparrow
#

also this uses a similar method

tribal moon
#

lol I remember that that's so cool

woven bridge
#

this information is the execution frame

rugged sparrow
#

in cpython each frame has a reference to the prior frame (until the topmost frame)

woven bridge
#

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.

golden finch
#

Okay, that's what I thought it was. Thanks/

rugged sparrow
#

frame.f_lasti is the last instruction executed inside frame

#

that is used for return

golden finch
#

So inspect.currentframe() gets (pops(?)) the top of the call stack?

rugged sparrow
#

It just returns a new reference to the topmost frame

golden finch
#

Okay.

rugged sparrow
#
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```

night quarryBOT
#

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

^ goto in python

golden finch
rugged sparrow
#

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

golden finch
#

Oh - tb stands for traceback

rugged sparrow
#

@woven bridge what kind of weird stuff have you done with frames?

woven bridge
#

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

rugged sparrow
#

I like that accessor thing

simple crystal
#

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

floral meteor
#

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

weary shoal
#

this works...

floral meteor
#

!e ```py
annotations = globals()
ar:[1,2,4] + ar=[5,6]
len: {'len':len}={'len':builtins.len}
Ans: print(Ans) = len['len'] 'len'

night quarryBOT
#

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

5
floral meteor
#

This also works

weary shoal
#

oh god

#

what do the colons do

#

im so confused

floral meteor
#

That you can set by defining annotations

#

As a class object with setitem

weary shoal
#

oh

floral meteor
#

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

night quarryBOT
#

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

True
weary shoal
#

wow

#

this is beautiful

weary shoal
floral meteor
#

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

night quarryBOT
#

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

yes, it is.
floral meteor
#

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

weary shoal
#

ah ok makes sense

floral meteor
#

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)

night quarryBOT
#

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

Okay so you're limited a little, you can only use valid names

#

But type hints are overrated

gritty mesa
#

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

@gritty mesa :white_check_mark: Your eval job has completed with return code 0.

001 | {'test': 2}
002 | 5
gritty mesa
#

Nice

floral meteor
#

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

night quarryBOT
#

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

4 {'test': 5}
floral meteor
#

A shorter version, many here code golf so much that using the mouse scroll wheel to read something drives them crazy

floral meteor
#

You could make a minilang with annotations

#

print: "Hello World"
set: a = 2
set: b = 2
add: c = a, b
print: c

golden finch
#

That's terrifying.

marsh void
#

use ctypes.sizeof(ctypes.c_void_p) to get the offset instead

golden finch
weary shoal
#

here is a bit of golf

last locust
#

Can remove 10 redundant spaces there if you wanted

weary shoal
#

lol

#

ftr not mine i found it on stack overflow im too dumb to write smtg this succint

gritty mesa
#

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

golden finch
#

a ton of try - except statements?

gritty mesa
#

Not what I'm after here, since I don't want the user to have to add any extra steps to handle it themselves

noble bloom
#

From math import math as string

gritty mesa
#
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
maiden blaze
#

*@distant wave

gritty mesa
#

ah yeah it was bast

earnest wing
#

!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

night quarryBOT
#

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

001 | __name__
002 | foo
floral meteor
#

I just had an evil idea

#

It involves c and dunder prepare

#

Remind me tomorrow

golden finch
warm cape
woven bridge
# gritty mesa Anyone have any idea how I might go about suppressing particular errors globally...

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.

warm cape
#

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)

simple crystal
#

at least I assume it's optimal

#

I hope my pyth sol is the shortest of all langs possible >_>

gritty mesa
#
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
woven bridge
#

ohh so this is what you wanted the exception thing for

gritty mesa
#

yeah

#

But the future annotations made for a much nicer solution

simple crystal
#

it makes annotations into strs instead of expressions

#

var would need to be defined in the first place otherwise

floral meteor
#

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

tribal moon
#

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

floral meteor
#

!paste

night quarryBOT
#

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.

floral meteor
#

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

floral meteor
floral meteor
tribal moon
#

the thing before it

#

the operator

#

<<--

#

is that just othing

floral meteor
#

yeah that's just nothing

tribal moon
#

Did you find out what that means?

#

that error code

floral meteor
#

i think it's the windows version of 139

#

just cos it can... doesn't mean you should, naughty python

tribal moon
#

that's weird

floral meteor
tribal moon
#

Yes

floral meteor
#

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

tribal moon
#

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

floral meteor
#

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

tribal moon
#

I really wanna see structs

floral meteor
#

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)
tribal moon
#

oh boy wow

#

that is

floral meteor
#
#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,
};
tribal moon
#

make pointers too

#

maybe that's too much

floral meteor
#

pointers?

#

the first block is

from ctypes import py_object as p
from builtins import*
import builtins as __builtins__
_garbage_can = []
tribal moon
#

you know pointers

floral meteor
#

nope

tribal moon
#

a thing that points to another spot in memory

#

like c char *string;

floral meteor
#

¯_(ツ)_/¯

cloud fossil
#

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

floral meteor
#

like this? ```py
a = [1,2,3]
p = id(a)

tribal moon
#

kind of

#

but a pointer stores the first byte

cloud fossil
#

The variable name of an array indeed stores the memory address of the first element

floral meteor
#

we should make a github repo to work on c methods

cloud fossil
#

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

floral meteor
#

I got blue screen :(

woven bridge
#

sounds like a video driver issue

floral meteor
#

You want to see the code to make that?

#

!pypi cursedutils

night quarryBOT
floral meteor
#

It's in there somewhere

woven bridge
#

just somewhere?

cloud fossil
woven bridge
#

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?

floral meteor
#

DOST THOU DOUBTETH THE CURSEDUTILS?

#

XD

#

it makes recursion bomb look like a child's toy

woven bridge
#

well

#

gonna run this in a vm 😛

#

is this only supposed to affect windows?

floral meteor
#

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

night quarryBOT
#

@floral meteor :warning: Your eval job timed out or ran out of memory.

[No output]
woven bridge
#

why does that even work

#

actually, wait, still have to see it for myself to believe it

floral meteor
#

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

woven bridge
#

alright hold on

#

getting a windows vm up

floral meteor
#

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

night quarryBOT
#

@floral meteor :x: Your eval job timed out or ran out of memory.

I'm perfectly okay!
floral meteor
#

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':lambda
a:a})('death',(),{})
kill_python()

night quarryBOT
#

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

[No output]
woven bridge
#

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

rip its broken

woven bridge
#

then how did you do the thing to get the blue screen earlier

#

i want to test that

floral meteor
#

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

night quarryBOT
#

@floral meteor :x: Your eval job timed out or ran out of memory.

I'm perfectly okay!
woven bridge
#

alright, now just wait ~10 minutes?

#

oh

#

that didnt work

#

just gave a bunch of memoryerror exceptions and then exited

#

no blue screen

maiden blaze
#
(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

sick steeple
#

What the fuck

#

Well, nice

fair vigil
#

code gore pehehe

sick steeple
#

Nice async lambda

fair vigil
#

hsp needs to be nerfed

sick steeple
#

Yes

floral meteor
woven bridge
#

yes

#

windows 10

floral meteor
#

hmm

woven bridge
#

whats the mechanism behind it?

floral meteor
#

it should catch MemoryError

woven bridge
#

why would that work?

#

and why specifically windows?

cloud fossil
#

@maiden blaze I didn't know lambdas could be coroutines

maiden blaze
#

me neither

cloud fossil
#

And can you await that thing though?

woven bridge
#

pretty sure the lambda isnt a coroutine its just the generator inside thats an async generator

cloud fossil
#

True but like aren't lambdas anonymous or something

#

Idk

woven bridge
#

anonymity doesnt really factor in here

cloud fossil
#

@maiden blaze add an event to that too

maiden blaze
#

i'm giving a test atm lol

floral meteor
#

Alright I ran it, nothing happened for about 10 minutes, then pycharm just disappeared.

#

^before.
After:

woven bridge
#

well i cant even import cursedutils

copper notch
#

hell

woven bridge
#

let alone run whatever it is youre running there

floral meteor
#

Then the gpu spiked and the screen went black

copper notch
#

hello

#

can someone helped me with a code

woven bridge
#

that sounds... dubious

#

im gonna go do something else

floral meteor
#

Why you ask in this channel?

#

Hey the mouse is back

#

But it's cursed

floral meteor
#

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

cloud fossil
#

Does restarting work or did you just screw your computer forever

floral meteor
#

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%

floral meteor
#

Hey it worked!

cloud fossil
#

Congratulations, blue screen of death... ACHIEVEMENT UNLOCKED

floral meteor
#

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

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

cloud fossil
#

Bro I thought you wanted to esoterify that

floral meteor
#

it's implicit behaviour, implicit behaviour can be exploited

#

specifically, only the first run keeps the smiley face in the same spot

golden finch
#

What's an annotation?

night quarryBOT
#

@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}
golden finch
#

So __annotations__.__setitem__ has been overwritten?

#

can't talk rn, can I ask later?

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

golden finch
#

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

golden finch
#

Also, how do annotations happen outside parameters?

#

Also, is __annotations__ global? I have so many questions.

earnest wing
#

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}

nimble heron
#

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

astral rover
#

That should raise a TypeError cause you aren't passing x

nimble heron
#

no it doesnt work at all

astral rover
#

Oh wait I see what you're doing

nimble heron
#

if i pass x

astral rover
#

You don't need to do content as the key

#

You just use the dict of init

nimble heron
#

oh >. > just outside?

#

:o

astral rover
#

Not outside

#

type('Testing', (object,), {'__init__':lambda self,x:...})("x")

nimble heron
#

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

@nimble heron :white_check_mark: Your eval job has completed with return code 0.

120
nimble heron
#

RIGHT

#

im dumb.. thanks

golden finch
#

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

earnest wing
#

__annotations__ is a dict

#

by default

gritty mesa
#

@golden finch You need to create an instance of the class

#

Otherwise it's trying to call the setitem of the class itself

golden finch
#

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

woven bridge
#

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

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

001 | 49
002 | 80
earnest wing
#

Some strings might possibly be "fixed length"?

woven bridge
#

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.

rugged sparrow
#

There are different types of strings internally depending on the content of a string

woven bridge
potent comet
#

!pep 393

night quarryBOT
#
**PEP 393 - Flexible String Representation**
Status

Final

Python-Version

3.3

Created

24-Jan-2010

Type

Standards Track

wintry trout
#

can someone pls give me a basic python exercice

tribal moon
floral meteor
#

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)')=}")

night quarryBOT
#

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

eval(f'(2).{dunder:add}(3)')=5
floral meteor
#

;)

floral meteor
#

!e I think I can add that to my list of wierd edit codes ```py
print(-((1<<32)-0xe0434352))

night quarryBOT
#

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

-532462766
floral meteor
#

Negative half a billion

#

And a bit

warm cape
#

o

sick hound
#

imagien using __lshift__ and python's scientific numbers

floral meteor
#

just translating the error to a signed integer in base 10 with 2s complement

sick hound
#

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

floral meteor
sick hound
#

uhm

night quarryBOT
#

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

eval(f'(1).{dunder:lshift}(32)')=4294967296
floral meteor
#

i mean that lol

sick hound
#

o

#

youtube be giving 100 cookies per second

floral meteor
#

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

night quarryBOT
#

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

__call__
wintry trout
#

can someone pls give me a basic python exersise

golden finch
#

how basic?

earnest wing
#

basic exercise: make a BASIC interpreter

warm cape
#

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))
proper vault
#

Yes, but it requires some rewriting

#

if -> a if c else b
for -> [a for b in c]
for try give me a bit

flat zodiac
#

always check variables to achieve that true one-liner-ness

warm cape
#

thanks!
(but some exceptions don't work that way)

flat zodiac
#

wdym?

warm cape
#

I mean, I would need try excepts at some places

#

I can't always avoid them

flat zodiac
#

can you give me an example?

proper vault
#

oh oops, forgot about this

#

checking if something is a valid int literal

warm cape
flat zodiac
#

i mean, we can avoid keyerrors

warm cape
flat zodiac
#
0 if "a" in {"a":1} else 1
warm cape
#

else None if I need only if right?

#

or empty sequence(idk if empty sequence's have different value from None)?

proper vault
#

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

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

123
warm cape
#

?
for try excepts?(I still have 3+ common modules to look at so idk wt that does)

proper vault
#

yup, that's ```py
def fun(a):
try:
return int(a)
except ValueError:
return None

warm cape
#

o

proper vault
#

you use a context manager to do the exception handling, and a ContextDecorator to run it on a function

warm cape
#

do I look about it later or lemme resume looking through functools/itertools?

#

cuz it looks fun

proper vault
#

up to you

#

there is also a different solution with excepthook, but that one is even stranger

flat zodiac
#

the only way to achieve a TRUE one-liner is write bytecode
change my mind

warm cape
#

wts that

floral meteor
#

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

floral meteor
#

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

sly token
#

!e

print({True: 'True', 1: '1', 1.0: '1.0'})
night quarryBOT
#

@sly token :white_check_mark: Your eval job has completed with return code 0.

{True: '1.0'}
sly token
#

disgusting

floral meteor
#

hash

sly token
#

I know

knotty delta
#

!e print(type(1.0))

night quarryBOT
#

@knotty delta :white_check_mark: Your eval job has completed with return code 0.

<class 'float'>
knotty delta
#

hm

floral meteor
#

ouch

tribal moon
#

hmmm I wonder

#

nevermind

tribal moon
floral meteor
#

you wonder?

tribal moon
#

Yes

floral meteor
#

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

tribal moon
#

how does it kill your computer

floral meteor
#

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

tribal moon
#

send the code lol

floral meteor
#

I can't remember how to update packages but I remember it being painful otherwise cursedutils would be fixed already

warm cape
proper vault
#

A bool is a subclass of int and therefore True==1

warm cape
#

pretty sure float and int are quite different

edgy spire
#

!e print(True==1)

night quarryBOT
#

@edgy spire :white_check_mark: Your eval job has completed with return code 0.

True
proper vault
terse mortar
proper vault
#

Python demands that all numeric types have compatible hashing and equality

warm cape
#

o

#

so float is a subclass of int too or.... ?

proper vault
#

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

warm cape
#

o

simple crystal
#

!e print({1, True, 1.0})

night quarryBOT
#

@simple crystal :white_check_mark: Your eval job has completed with return code 0.

{1}
maiden blaze
#

!e

from decimal import Decimal
from fractions import Fraction
print({1, True, 1.0, Decimal(1), Fraction(1, 1)})
night quarryBOT
#

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

{1}
night quarryBOT
#

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:

https://paste.pythondiscord.com

rose minnow
#

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

simple crystal
#

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

@simple crystal :warning: Your eval job timed out or ran out of memory.

[No output]
simple crystal
#

ah damn

#

takes my comp about 6 seconds

simple crystal
#

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

@simple crystal :warning: Your eval job timed out or ran out of memory.

[No output]
earnest wing
#

Can a type exist without deriving from object? Including both the class and the mro?

tawdry barn
#

Please i d'ont see a problem

rose minnow
#

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

tulip burrow
#

Ram wouldn't be the limitation if you wrote each prime to the file as you calculate it.

earnest wing
#

yeah, just be careful with flushing
Though if the whole thing is one line, you should be fine with the default

rose minnow
simple crystal
# rose minnow Hard to do that since it has to compare the test value against the list of known...
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)

rose minnow
#

Seems slower than it keeping the list in RAM.

simple crystal
#

of course but it's not hard to do

rose minnow
#

I see.

nova marsh
#

looking for python coders to be friends and crating games

crude gull
#

hi guys

tribal moon
#

Make it faster by implementing Sieve of Eratosthenes with jit

rose minnow
#

Is that necessarily faster though?

tribal moon
#

Yes it is

#

Especially with something like jit, it'd be very fast

rose minnow
#

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.

tribal moon
#

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

rose minnow
#

And set them to 0 if the number associated with it is ruled out?

tribal moon
#

Yes

#

Look at the gif

rose minnow
#

Yeah

tribal moon
#

you can see it's getting all the evens first

rose minnow
#

I'm looking. lol

tribal moon
#

then all the others

#

and then the others, and so on

rose minnow
#

I'm familiar with the algorithm, I just haven't implemented it before.

tribal moon
#

you can get these numbers for each time your index is incrementing by: py range(index * index, n+1, index)

rose minnow
#

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.

simple crystal
#

got about half a billion primes with a sieve but much more and my 16 gb mem isn't enough

tribal moon
#

It is a bit inefficient how it's making a HUGE array before hand, but that really depends what n is

rose minnow
tribal moon
#

Maybe you can create checkpoints every something primes it generates, and then just load it from disk

rose minnow
#

Perhaps, perhaps.

woven bridge
#

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

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

001 | True
002 | (<class '__main__.Meta'>,)
woven bridge
#

unfortunately isinstance(Meta, object) still returns True though

earnest wing
#

__instancecheck__?

#

yeah, MetaMeta.__instancecheck__ can just return False for object

royal totem
#

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

earnest wing
#

that's just zip

woven bridge
earnest wing
#

define it on the meta meta so Meta can be "not an object"

woven bridge
#

not sure i follow. wouldnt that require overriding object.__instancecheck__ instead?

royal totem
#

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

woven bridge
royal totem
#

thanks man 😄

earnest wing
#

oh wait I forgot how instancecheck worked

#

guess you'd have to patch that then yeah

rose minnow
#

Oh goodness...

rose minnow
#

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.

golden finch
#

Whitespace?

rose minnow
#

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

golden finch
#

maybe bit magic instead of an list?

rose minnow
#

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.

floral meteor
rose minnow
#

How do you like your code?

floral meteor
rose minnow
#

What am I looking at here?

floral meteor
#

one column enforced to be whitespace

#

throughout the entire document

rose minnow
#

Do you mean with the indenting or are we using "whitespace" to describe two different things?

floral meteor
#

indenting?
indenting is overrated i'm talking about the entire column dedicated to the space character, character 32

rose minnow
#

Why would you do that though?

floral meteor
rose minnow
#

Your IDE certainly seems to hate it.

floral meteor
#

my IDE hates most things I do

rose minnow
#

Uhuh.

floral meteor
#

it hates that

rose minnow
#

Well, I'm going to continue using plenty of comments, white spacing, and indenting.

floral meteor
#

it hates that

#

it hates center aligned code

rose minnow
#

Languages that use semicolons to end commands are more kind to these kinds of things in my experience.

#

Are semicolons taboo here? lol

floral meteor
#

It hates my version of assertion

rose minnow
#

This is one of the strangest ways I've seen someone code in a while.

floral meteor
#

try scrolling up :/

rose minnow
#

I only came to this channel since none of the others seemed to fit.

#

Maybe I should just mute this channel. haha

floral meteor
#

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

tribal moon
#

I can show you how if you can send your code

#

I can help you optimize it

#

though, you would need some external libraries

rose minnow
#

I don't think I'm interested in the old method considering that the new method did it many times faster.

tribal moon
#

Yes you can make the new one even faster

#

much faster

rose minnow
tribal moon
#

Alright, I'll be back later

floral meteor
#

improved readability

golden finch
#

you scare me

floral meteor
#

boo! 👻

tribal moon
snow beacon
floral meteor
#

alright time for my weekly spin on brainfuck

floral meteor
# floral meteor alright time for my weekly spin on brainfuck

!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.-<<<<++.-->>+++++++.------->>+.+++.----<++++++++.--------.<<<+++.}")

night quarryBOT
#

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

Hello World!
tribal moon
#

@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

rose minnow
#

Not sure what most of these notational tricks do, but cool.

floral meteor
#

notational tricks?

rose minnow
#

I only occasionally use Python so most of the more subtle tricks I'm unfamiliar with.

tribal moon
#

You should try to run it

rose minnow
#

My primary language is MCFunction.

tribal moon
#

but you gotta set up the modules before you run it though

floral meteor
#

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

night quarryBOT
#

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

001 | executing code.
002 | Hello World!
003 | code execution complete!
fringe shuttle
#

O_o

golden finch
#

that's rule2ing art

floral meteor
#

rule2ing art?

golden finch
#

I assumed that the second rule in this server was anti-swearing

earnest wing
#

(discord's terms of service doesn't disallow cursing)

golden finch
#

Some servers do though.

sick hound
#

What is esoteric python?

earnest wing
#

see the channel description

sick hound
#

I don't get it

woven bridge
#

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

earnest wing
#

golf scoring

#

low number = good

woven bridge
#

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

woven bridge
modern fiber
#

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

simple crystal
#

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

rigid stratus
simple crystal
#

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

floral meteor
#

SyntaxError strikes again

#

I'm having a lot of fun today

floral meteor
#

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

golden finch
warm cape
#

can I change this to a one-liner without semicolons/multiple statements?```py
if _ == __: nonlocal ; return ( := True)

golden finch
#

I presume you don't want eval?

woven bridge
#

cause you could probably just do something like return __import__('sys')._getframe(n).f_locals['___'] if _==__ else (___:=True)

warm cape
#

that's.... a bit slow right?

#

maybe sometimes its best to stick with what I have

proper vault
#

performance really does not matter in oneliners

flat zodiac
#

if you care about performance and dont want to recalculate stuff - use the walrus operator (:=)

cursive pine
#

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

flat zodiac
night quarryBOT
#

@flat zodiac :white_check_mark: Your eval job has completed with return code 0.

001 | 100
002 | 100
003 | 
004 | 101
005 | 101
flat zodiac
#

basically, it assigns a value to a name and returns the value

sick hound
#

Ohhh

flat zodiac
#

very useful in one-liners, not very much in general coding

rugged sparrow
#

I find it useful in ifs and whiles

earnest wing
#

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

fluid tree
fluid tree
floral meteor
#

I'm thinking of redoing natural number syntax using class prepare overrides

#

How do I proficiently override how class blocks are parsed?

rugged sparrow
#

Parsed or ran?

pure dew
#

forgot about this place

#

ya'll are gonna love this

#

imagine, traits in python

golden finch
#

/AnonymousD(ap|evelo)per/g