#esoteric-python

1 messages · Page 113 of 1

cloud fossil
#

this is weird

#

!e

print(False and 1/0)
night quarryBOT
#

@cloud fossil :white_check_mark: Your eval job has completed with return code 0.

False
cloud fossil
#

!e

print(0 and 1/0)
night quarryBOT
#

@cloud fossil :white_check_mark: Your eval job has completed with return code 0.

0
cloud fossil
#

oh okay

proper vault
#

fun fact: Java does this too, to a lesser extent

jshell> boolean weird() {System.out.println("Hello World!"); return true;}
|  replaced method weird()

jshell> weird();
Hello World!
$3 ==> true

jshell> weird() || weird()
Hello World!
$4 ==> true
cloud fossil
#

wait isn't Java a compiled language

proper vault
#

yes it is

cloud fossil
#

or is it because it runs on a virtual machine

#

the jshell

proper vault
#

jshell is a new feature which allows a java repl

cloud fossil
#

i wish for a cshell

proper vault
#

yeah, that is much harder

#

C does short circuiting binops too IIRC

simple crystal
#

if you want to evaluate both sides of an and or or no matter what in Python, make it so you're using bitwise & or |, this requires actually using 1 for True and 0 for False (which is what True and False basically are) or bitwise equivalents and they have pretty high precedence in order of operations

cloud fossil
#

this is a bit off-topic, but PHP has a shell thing as well, right?

simple crystal
#

!e

print(True|1)
night quarryBOT
#

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

1
simple crystal
#

tho

#

!e

print(1|True)
night quarryBOT
#

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

1
simple crystal
#

always 1

naive roost
#

!e ```py
print(True|2)

night quarryBOT
#

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

3
proper vault
#
ᓚᘏᗢecho "#include <stdio.h>`n_Bool weird() {puts(`"Hello`");return 1;}int main(){weird()||weird();}" | tcc -run -xc -
Hello
```yeah, C does this as well
#

excuse the code in a string literal

cloud fossil
#

that does not work on objects from libraries like discord.py though

simple crystal
proper vault
#

yeah, | will not work on non-bools

cloud fossil
#

it's just bitwise or

simple crystal
#

it will but you need to know what's going on

cloud fossil
#

will it even work on negatives

proper vault
#

it isn't a boolean operator

viscid nymph
proper vault
#

of course, you can do bool(a)|bool(b)

viscid nymph
#

!e

print(True|int(False))
cloud fossil
#

now this is more esoteric to my liking

night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

1
cloud fossil
#

oh it reevaluated?

#

cool!

simple crystal
#

sometimes it lets you when you edit

viscid nymph
#

!source e

night quarryBOT
#
Command: eval

Run Python code and get the results.

Source Code
viscid nymph
simple crystal
#

ah

cloud fossil
#

that's cool

rugged sparrow
#

!e ```py
import gc

class magic:
def length_hint(self):
return 1
def iter(self):
for obj in gc.get_objects():
if type(obj) == tuple and len(obj) == 1:
try:1 in obj
except SystemError:
yield obj
break

weird = tuple(magic())
print(weird)
print(weird[0] is weird)

night quarryBOT
#

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

001 | ((...),)
002 | True
cloud fossil
#

idek what i'm looking at

proper vault
#

so you get a reference to a tuple while python still assumes it can run PyTuple_SetItem safely?

rugged sparrow
#

yea

proper vault
#

fancy

cloud fossil
#

!e

apple = ["apple"]
print(apple)
apple.append(apple)
print(apple)
night quarryBOT
#

@cloud fossil :white_check_mark: Your eval job has completed with return code 0.

001 | ['apple']
002 | ['apple', [...]]
cloud fossil
#

so that's what i'm looking at

rugged sparrow
#

its because the function uses PyTuple_SET_ITEM which is a macro that assigns directly

#

and you need __length_hint__ because _PyTuple_Resize fails if the tuple has more than one reference

proper vault
#

cool

rugged sparrow
#

i wonder what other weird stuff can be done using gc inside of initalizers

snow beacon
#

Can you put two keys that are equal in a dict?

#

I mean, without __hash__ shenanigans.

floral meteor
#

Challenge: make an InfiniteList such that setitem and getitem can write to and read from any index, creating a default value there (hint: extending the data) if it would otherwise not exist or return indexerror.
Negative values do not reference the list backwards, rather extends the list leftways

hard spoke
floral meteor
#

Assuming object() to be the default value?

earnest wing
#

is that all the spec has to say?

hard spoke
#

something like that, though perhaps it should be the same object and not a new one each time

floral meteor
#

Huh that'll make brainfuck easier

#

I'll use 0

earnest wing
#

you don't want to use a dict as an infinite tape, lol

floral meteor
#

Watch me.

earnest wing
#

indexing has less overhead

hard spoke
#

why not? 🙂

floral meteor
#

Overhead is for nerds

hard spoke
earnest wing
#

if you're indices are infinite, use a dict with float keys :>

floral meteor
#

No

hard spoke
#

why float keys? int is infinite-sized

earnest wing
#

not in finite time or space

#

i.e. not computable in our universe

hard spoke
#

neither is float

floral meteor
#

Neither is your mother

earnest wing
#

float("inf")

hard spoke
#

floats can represent infinity, but not arbitrarily high numbers 😛

#

unlike ints

floral meteor
#

!e ```py
a = import ('collections').defaultdict(int)
i = int()
BITS=(True<<True)<<(True+False**False+True)
def plus():
a[i]+=True<<int()# cause true to become int
a[i]%=(True<<True)**BITS
def minus():
a[i]-=True<<int()
a[i]%=(True<<True)**BITS
def left():i-=True<<int()
def right():i+=True<<int()
def dot(file=import('sys').stdout):file.write(chr(a[i]))
def comma(file=import('sys').stdin):a[i]=ord(file.read(True))
[plus()for I in range(100)]
minus();minus();dot();minus();dot();plus();plus();plus();dot()

night quarryBOT
#

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

bad
floral meteor
#

I like it

floral meteor
#

I did int. XD

viscid nymph
#

😮

floral meteor
#

Jk pulling your leg

floral meteor
viscid nymph
#

thanks

snow beacon
# floral meteor !e ```py a = __import__ ('collections').defaultdict(int) i = int() BITS=(True<<T...

FTFY ```py
a = import ('collections').defaultdict(int)
i = int()
BITS=((int()**int())<<(int()**int()))<<((int()**int())+(int()**int())+(int()**int()))
def plus():
a[i]+=(int()**int())<<int()
a[i]%=((int()**int())<<(int()**int()))**BITS
def minus():
a[i]-=(int()**int())<<int()
a[i]%=((int()**int())<<(int()**int()))**BITS
def left():i-=(int()**int())<<int()
def right():i+=(int()**int())<<int()
def dot(file=import('sys').stdout):
with file as f:f.write(chr(a[i]))
def comma(file=import('sys').stdin):
with file as f:a[i]=ord(f.read((int()**int())))
[plus()for _ in range(int(bin((int()**int()) << (int()**int()) + (int()**int()))[(int()**int()) + (int()**int()):]))]
minus();minus();dot();minus();dot();plus();plus();plus();dot()

floral meteor
#

Wow

#

Inty

viscid nymph
#

What's this supposed to do

#

raise errors?

#

why do you do int()**int() instead of int()+int()

snow beacon
#

Because they are different numbers.

hard spoke
#

python has 0**0 be 1 😔

viscid nymph
#

wait I'm dumb

snow beacon
#

It also closes all the files after use. (Stdin included.)

viscid nymph
#

it raises errors

snow beacon
#

A small price to pay for file safety.

floral meteor
#

pffft

#

i make my own file class that doesn't block the file when its open

#

you noobs use straight file.open(filename) I make the read method open and close the file ahahahaha

snow beacon
#

Personally I use pathlib.

#

I don't need to get into the nitty-gritty when there are abstractions.

floral meteor
#

I am the nitty-gritty abstractions.

#

aight im gonna nitty gritty abstractions literally bound the entire global namespace to an object cos I can

snow beacon
floral meteor
#

!e ```bf
#[
a,i=import ('collections').defaultdict(int),int()
BITS=((int()**int())<<(int()**int()))<<((int()**int())+(int()**int())+(int()**int()))
def add(*s):
a[i<<int()]+=(int()**int())<<int()
a[i>>int()]%=((int()**int())<<(int()**int()))**BITS
return s[int()]
pos=add
def sub(*s):
a[i<<int()]-=(int()**int())<<int()
a[i>>int()]%=((int()**int())<<(int()**int()))**BITS
return s[int()]
neg=sub
def lt(*s):globals()['i']-=(int()**int())<<int();return s[int()]
def gt(*s):globals()['i']+=(int()**int())<<int();return s[int()]
def lshift(*s):return lt(*s)<int()<<int()
def rshift(*s):return gt(*s)>int()>>int()
def getattr(s,o):
try:return object.getattr(s,o)
except:import('sys').stdout.write(chr(a[i<<int()]>>int()));return s
def call(self,f,a):
if a:a[i>>int()]=ord((f or import('sys').stdin).read(len(a)<<int()))
return self
bool=lambda
s:not int()
def getitem(s,item):
while a[i>>int()]:(v:=item()if hasattr(item,'call')else+s if item>=int()else-s).class is int and(v<int()and-s or+s)
return s
=type("brainfucker",(int,),globals())(int())
#]
(
++++++++++)[lambda:>int()and ++++++++++<int()and-int()**int()]>int()and -- and (.int-int()).int+++ and _.int(int())

night quarryBOT
#

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

bad
floral meteor
#

gottim

#

it's a polyglot with no numeric literals!

#

evidence the bot runs brainfuck, not python.

#

!e ```py
#[
a,i=import ('collections').defaultdict(int),int()
BITS=((int()**int())<<(int()**int()))<<((int()**int())+(int()**int())+(int()**int()))
def add(*s):
a[i<<int()]+=(int()**int())<<int()
a[i>>int()]%=((int()**int())<<(int()**int()))**BITS
return s[int()]
pos=add
def sub(*s):
a[i<<int()]-=(int()**int())<<int()
a[i>>int()]%=((int()**int())<<(int()**int()))**BITS
return s[int()]
neg=sub
def lt(*s):globals()['i']-=(int()**int())<<int();return s[int()]
def gt(*s):globals()['i']+=(int()**int())<<int();return s[int()]
def lshift(*s):return lt(*s)<int()<<int()
def rshift(*s):return gt(*s)>int()>>int()
def getattr(s,o):
try:return object.getattr(s,o)
except:import('sys').stdout.write(chr(a[i<<int()]>>int()));return s
def call(self,f,a):
if a:a[i>>int()]=ord((f or import('sys').stdin).read(len(a)<<int()))
return self
bool=lambda
s:not int()
def getitem(s,item):
while a[i>>int()]:(v:=item()if hasattr(item,'call')else+s if item>=int()else-s).class is int and(v<int()and-s or+s)
return s
=type("brainfucker",(int,),globals())(int())
#]
(
+++++++)[lambda:>_ and +++++++ and < and -]>_ and +++++ and(.+++_).int(int())

night quarryBOT
#

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

69
floral meteor
#

I am invincible!

#

shood i make a bash interpreter in a brainfuck/python polyglot generated by an obfuscated+code art c++ script and then make the result run a windows command prompt emulator written in bash?

#

and then use that as an IDE to write files in rust.

#

or matlab

#

XD

snow beacon
#

Follow your dreams, even if your dreams are... that.

simple crystal
#

sounds more like a gosh-darned nightmare

floral meteor
#

XD

unique viper
#

heh, well this is probably an appropriate room for this question. Is there a simpler way to override all of the dunder methods rather than just doing it for every one?

simple crystal
#

!e

print([0xfor x in (1, 2, 3)])
night quarryBOT
#

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

[15]
snow beacon
#

__getattr__ I think it is?

simple crystal
#

u might wanna try using a dataclass

#

depending on what your goals are

unique viper
#

i tried that, even overriding both __getattr__ and __getattribute__

#

my goal is essentially to get one piece of data to look like another piece of data for all interactions

floral meteor
#

Would have weird consequences so I'll try to make one in the cursedutils package

unique viper
#

let me give a little more context...

snow beacon
floral meteor
unique viper
#

i have a library that does a lot of deferred actions. It's a web-browser automated testing library.

I wrote a thing that lets you write down a note, but the note-writing part is in the deferred action, so if you try to access that note before the deferred action is performed, the note won't be there yet.

I'm trying to make an imposter class that will just store the lookup key for the note, so when it actually needs to be used, it can go get the note instead

snow beacon
#

If you were to do it idiomatically, that would probably be writing a wrapper around all of the note logic, then making a different wrapper that goes and gets the note.

#

You could also consider overwriting the __class__ of the note proxy once it fetches the note.

unique viper
#

it's got an example in the OP, but i'm not sure if it's easy to understand without more context

#

basically i don't want the rest of my codebase to have to know how to go and get the note themselves

#

i want the rest of my codebase to just be able to use the Imposter as if it were the stored value

snow beacon
#

The "right" way would be wrapping both types of note/defining a clear API for what notes have to implement. The "fun" way would be one of the other things this channel has to offer.

unique viper
#

i feel i might be in the right place

floral meteor
#

huh

#

Maybe

unique viper
#

this Maybe/Might_Be class is great

snow beacon
#

Other people made entries for the same challenge, that might also be worth looking into.

floral meteor
#

i would just brute force the Maybe object

snow beacon
#

I wrote that solution using a program, then tidied it up.

#

The one I ended up with is adaptable and maintainable.

#

There is no benefit to spelling out all umpteen hundred methods by hand.

floral meteor
#

watch me.

snow beacon
#

It's not that it's hard, it's just that it's pointless.

floral meteor
#

there done but it's 2600 chars

night quarryBOT
floral meteor
#

aww

snow beacon
#

(If only there were an automated solution.)

rustic aspen
#

would it be possible to import python into itself?

thin trout
rustic aspen
#

i obviously could just make a file called python.py but thats not what im looking for

#

im not 100% sure what importing python would be, but i think i have the vague idea that it contains all the defaults and compilers and stuff

thin trout
#

Hmmmm

#

Well, since python is a language with huge introspection, you can almost hook into anything

#

For example, you can use the ast module to compile code

opaque hemlock
#

Can anyone help me with programming a coding language

#

my var command is not wrking

simple crystal
#

if you want a slower turtle, you stack another turtle on top of the first turtle

#
  • Albert Einstein
edgy spire
#

wouldnt the top turtle be twice as fast

fluid tree
edgy spire
#

hmm i guess you'd have to make the bottom turtle faster to keep up with it

simple crystal
#

that's how PyPy works

finite rose
#

!e
print(set() == {*()})
print(dict() == {**{}})

night quarryBOT
#

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

001 | True
002 | True
hard spoke
edgy spire
plucky wedge
#

Einstein, famed physicist turtle researcher

snow beacon
#

Hopefully better than Freud with eels.

simple crystal
#

@rugged sparrow okay so I looked at new fishhook stuff and it looks like you are looking for pointers in a heap class which point to memory addresses within the heap class itself?

#

I wonder if it's technically possible to find other data which happen to have integer values within the memory addresses of the heap class, tho I doubt that's likely

#

ah okay they point to deeper in the class

#
byte: b'(\xb0]\x99M\x02\x00\x00' val: 2532308791336, pointer: 10 points to: 51
byte: b'@\xb0]\x99M\x02\x00\x00' val: 2532308791360, pointer: 12 points to: 54
byte: b'x\xb1]\x99M\x02\x00\x00' val: 2532308791672, pointer: 13 points to: 93
byte: b'`\xb1]\x99M\x02\x00\x00' val: 2532308791648, pointer: 14 points to: 90
byte: b'\xc8\xb1]\x99M\x02\x00\x00' val: 2532308791752, pointer: 20 points to: 103
byte: b'\x00\xb2]\x99M\x02\x00\x00' val: 2532308791808, pointer: 30 points to: 110
#

which makes sense cuz that's the memory allocated for it on the heap

rugged sparrow
simple crystal
#

is there any chance other data as ints will be the same as the memory addresses?

rugged sparrow
#

Not in the same way

#

There are a few other structures that are stored inside the PyHeapTypeObject struct but they aren't super useful for monkey patching

simple crystal
#

ah okay

#

and what are the pointers at 20 and 30?

#

tp_as_buffer and tp_members?

simple crystal
#

after a few tries I managed to find one with an int that looked like a pointer within the heap class at 120 from _start but that wouldn't change the functionality apparently

#

another at 118

#

124

#

points to 2 slots up

rugged sparrow
#

You need to look for pointers within the heap class size (between start and end)

#

And go by multiples of base_size

simple crystal
#

yah I just stuffed this in your code and looped it

            if i//base_size not in (10, 12, 13, 14, 20, 30):
                print(f'wtf {i//base_size} points to: {(_val-_start)//base_size}')
#

but running only sometimes produces 1 or 2 wtfs

rugged sparrow
#

You prob bugged up something

#

It should only find those struct pointers

simple crystal
#

!e

from ctypes import *
import sys
base_size = sizeof(c_ssize_t)
wrapper_type = type(int.__add__)

static_size = type.__sizeof__(type) // base_size

def mem(addr, size):
    return (c_char*size).from_address(addr)

def doin():
    class _scratch:...
    _size = type.__sizeof__(_scratch)
    _start = id(_scratch)
    _end = _start + _size
    _cls_mem = mem(_start, _size).raw  # actual memory  # mutable copy
    _intermediate = []
    for i in range(0, _size, base_size):
        _val = int.from_bytes(_cls_mem[i:i + base_size], sys.byteorder)
        if _start < _val < _end:
            if i//base_size not in (10, 12, 13, 14, 20, 30):
                print(f'wtf {i//base_size} points to: {(_val-_start)//base_size}')
            _intermediate.append((i//base_size, _val))
    _last_addr = None
    _offsets, _sizes = [0], [static_size]
    for _offset, _addr in sorted(_intermediate, key=lambda i:i[1]):
        if _last_addr is not None:
            _sizes.append((_addr - _last_addr)//base_size)
        _offsets.append(_offset)
        _last_addr = _addr

while True:
    doin()
#

lol carriage return doesn't work

night quarryBOT
#

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

001 | wtf 130 points to: 51
002 | wtf 130 points to: 51
003 | wtf 130 points to: 51
004 | wtf 130 points to: 51
005 | wtf 130 points to: 51
006 | wtf 130 points to: 51
007 | wtf 130 points to: 51
008 | wtf 130 points to: 51
009 | wtf 130 points to: 51
010 | wtf 130 points to: 51
011 | wtf 130 points to: 51
... (truncated - too many lines)

Full output: too long to upload

simple crystal
#

ah this is different

#

when I run it fro a while with the carriage returns I get

1818237271088wtf 120 points to: 122
1818237340688wtf 124 points to: 126
1818237276608

for example

rugged sparrow
#

Pm me the total code I want to look at it

simple crystal
#

kk

rugged sparrow
#

I'll need to sift thru it in like an hour

simple crystal
#

it's usually only 1 or 2 wtfs per run if any

#

kk lemme know if you figure out what's happening haha

rugged sparrow
#

It's probably some uninstalized memory containing big values

#

So pure chance

#

I don't think my logic is wrong

simple crystal
#

ah okay and that's why it stops after a bit

#

because it overwrites uninstalized memory where heap classes are being stored

rugged sparrow
#

It shouldn't be overwriting anything?

#

In the code you sent nothing should be getting overwritten

simple crystal
#

I mean the heap classes are defined then garbage collected

#

I wonder why my computer always has them as the memory addresses 2 base_sizes away and the bot has one at 130 pointing to 51

rugged sparrow
#

Oh yea

#

I think I know why it's reading uninitialized memory

simple crystal
#

why's that?

rugged sparrow
#

Need to look at source

simple crystal
#

!e

from ctypes import *
import sys
base_size = sizeof(c_ssize_t)
wrapper_type = type(int.__add__)

static_size = type.__sizeof__(type) // base_size

def mem(addr, size):
    return (c_char*size).from_address(addr)

def doin():
    class _scratch:...
    _size = type.__sizeof__(_scratch)
    _start = id(_scratch)
    _end = _start + _size
    _cls_mem = mem(_start, _size).raw  # actual memory  # mutable copy
    _intermediate = []
    for i in range(0, _size, base_size):
        _val = int.from_bytes(_cls_mem[i:i + base_size], sys.byteorder)
        if _start < _val < _end:
            if i//base_size not in (10, 12, 13, 14, 20, 30, 130):  # added 130
                print(f'wtf {i//base_size} points to: {(_val-_start)//base_size}')
            _intermediate.append((i//base_size, _val))
    _last_addr = None
    _offsets, _sizes = [0], [static_size]
    for _offset, _addr in sorted(_intermediate, key=lambda i:i[1]):
        if _last_addr is not None:
            _sizes.append((_addr - _last_addr)//base_size)
        _offsets.append(_offset)
        _last_addr = _addr

while True:
    doin()
night quarryBOT
#

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

001 | wtf 118 points to: 114
002 | wtf 119 points to: 114
003 | wtf 118 points to: 114
004 | wtf 119 points to: 114
005 | wtf 118 points to: 114
006 | wtf 119 points to: 114
007 | wtf 118 points to: 114
008 | wtf 119 points to: 114
009 | wtf 118 points to: 114
010 | wtf 119 points to: 114
011 | wtf 118 points to: 114
... (truncated - too many lines)

Full output: too long to upload

simple crystal
#

typicla output for my computer with same script I gave bot:

wtf 122 points to: 124

or nothing

#

oh and the mutable copy comment was from earlier when I was comparing the array of chars to a create_string_buffer

rugged sparrow
#

If the type has cached keys then the just getting the mem of type.sizeof gets some random memory at the end

simple crystal
#

ah cool

rugged sparrow
#

I'll figure out a way to fix that

simple crystal
#

ohhh is it because I made type(__scratch__) into type?

rugged sparrow
#

No

simple crystal
#

ok forgot I did that

rugged sparrow
#

It shouldn't break anything in fishhook to read that memory because any values there are preceded by the pointers I am looking for

#

Still something I should prob fix

simple crystal
#

makes sense

#

...could you jut use static_size?

#

instead of _size in the first for loop

rugged sparrow
#

No

#
class _scratch:
     __slots__ = ()```
#

Make that scratch

simple crystal
#

oh yeah I tried that earlier

#

actually

rugged sparrow
#

Did it fix the weird issue,

simple crystal
#

haven't tried it with this testing script I'll check

#

just was trying to change the size of scratch

#

seems to, yep

#

!e

from ctypes import *
import sys
base_size = sizeof(c_ssize_t)
wrapper_type = type(int.__add__)

static_size = type.__sizeof__(type) // base_size

def mem(addr, size):
    return (c_char*size).from_address(addr)

def doin():
    class _scratch:__slots__=()
    _size = type.__sizeof__(_scratch)
    _start = id(_scratch)
    _end = _start + _size
    _cls_mem = mem(_start, _size).raw  # actual memory  # mutable copy
    _intermediate = []
    for i in range(0, _size, base_size):
        _val = int.from_bytes(_cls_mem[i:i + base_size], sys.byteorder)
        if _start < _val < _end:
            if i//base_size not in (10, 12, 13, 14, 20, 30):  # added 130
                print(f'wtf {i//base_size} points to: {(_val-_start)//base_size}')
            _intermediate.append((i//base_size, _val))
    _last_addr = None
    _offsets, _sizes = [0], [static_size]
    for _offset, _addr in sorted(_intermediate, key=lambda i:i[1]):
        if _last_addr is not None:
            _sizes.append((_addr - _last_addr)//base_size)
        _offsets.append(_offset)
        _last_addr = _addr

while True:
    doin()
night quarryBOT
#

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

[No output]
simple crystal
#

nice

rugged sparrow
#

Yea it causes the class to have no cached keys

#

I'll update that in fishhook tonight

simple crystal
#

ah neat

simple crystal
#

that also gets rid of the tp_members pointer I think

#

oh it just doesn't register because it points to _end

#

so maybe it's not tp_members

rugged sparrow
#

tp_members is still seen

#

@simple crystal pushed the fix to github/pypi (v0.1.1)

simple crystal
#

nice

unique glacier
#

Hey ,guys can you make python file find a largest amoung the five numbers. you can?After make it send the code to DISCORD.

snow beacon
sick hound
#

Without exec and eval is python turing complete if you aren't allowed to use whitespace? rooHmm

cloud fossil
#

well, you won't be able to define functions

#

nor classes

#

and maybe even not import anything

#

do newlines count as whitespace to you?

sick hound
#

yes

#

or maybe not if that makes it too hard WolfLol

cloud fossil
#

that just means one line statements i think idk

#

i mean... one line entire code XD

#

and no tabbing

sick hound
#

!e you can use semicolons, but yeah, no indents py print(9);print(8);print(7);

night quarryBOT
#

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

001 | 9
002 | 8
003 | 7
cloud fossil
#

no need for the last one btw

sick hound
#

true

cloud fossil
#

!e

import(time)
night quarryBOT
#

@cloud fossil :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     import(time)
003 |           ^
004 | SyntaxError: invalid syntax
cloud fossil
#

oof

#

i mean... maybe you could straight up use the loader or whatever idk how it works

#

maybe it's not a statement so you can use it as a function or something

sick hound
#

I was thinking you could do some fancy stuff with __import__ but rooHmm idk how rooDerpy

cloud fossil
#

same

#

oh i know

#

!e

time=__import__("time");print("sleeping");time.sleep(2);print("slept","for","two","seconds!")
night quarryBOT
#

@cloud fossil :white_check_mark: Your eval job has completed with return code 0.

001 | sleeping
002 | slept for two seconds!
cloud fossil
#

meh, it works

vague hearth
night quarryBOT
#

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

4
vague hearth
#
print(type("main",(),{"add":lambda*a:(a[1]+a[2])})().add(1, 3))```(or use this if you juts want a function without instantiating with the values)
potent comet
#

You cal also directly instantiate types.CodeType() and then types.FunctionType() with all the correct values, to create a function that does anything.

earnest wing
#

Might as well just exec(your code encoded in a funny way, decoded at runtime)

snow beacon
grave rover
#

@rugged sparrow any clue why this wouldn't work? ```py
buffer = b"\x00" * calcsize('3P')
int_type = get_view(id(int), CPyTypeObject.instance())
int_type.tp_as_mapping = get_view(id(buffer), CPyBytesObject.instance()).ob_sval[0]._addr

# bytecode: compiled form of 
# void do_x(PyLongObject* self, PyLongObject* pylong_1) {
#     self->digit = pylong_1->digit;
# }
bytecode = b"\x55" \
           b"\x48\x89\xe5" \
           b"\x48\x89\x7d\xf8" \
           b"\x48\x89\x75\xf0" \
           b"\x48\x8b\x45\xf0" \
           b"\x8b\x50\x14" \
           b"\x48\x8b\x45\xf8" \
           b"\x89\x50\x14" \
           b"\x90" \
           b"\x5d" \
           b"\xc3"
bytecode_py_addr = get_view(id(bytecode), CPyBytesObject.instance()).ob_sval[0]._addr
int_type.tp_as_mapping.mp_subscript = bytecode_py_addr
pythonapi.PyType_Modified(py_object(int))
print(10[30])  # call mp_subscript

# Error: TypeError: 'int' object is not subscriptable
rugged sparrow
#

First of all you need to memory map bytecode as RWX

#

Also make sure to set mp_subscript and sq_item

#

And both of those functions return an PyObject*

#

So can't be void

#

@grave rover ^ also are you sure that your offsets are right

grave rover
#

offsets are 100% right

rugged sparrow
grave rover
#

unless something changed between 3.9 and 3.10 but isn't listed as being different on the docs

rugged sparrow
#

A new slot was added to tp_as_async

grave rover
#

that was in 3.5, no?

#

nvm I see what you mean now

rugged sparrow
#

Yea there is a 4th slot now

#

@grave rover those functions actually return a PyObject

#

Well mp_subscript does

grave rover
#

right, I made a slight mistake when I moved over lol

rugged sparrow
#

Other than those it should work as is (with a crash due to memory execution issues)

grave rover
#

wait so how would I map that as executable?

rugged sparrow
#

 you can use libc

#

I have an example In my asm_hook code

#

On my GitHub @grave rover

grave rover
#

I'm starting to not like how python handles negative numbers

#

ob_size of 1 for negative numbers becomes 0xffffffff

rugged sparrow
#

So it actually becomes -1

grave rover
#

it just makes my life a little less enjoyable

#

it also somehow makes printing 10 an issue

rugged sparrow
#

It does?

grave rover
#

10[20] = -30 # Injected code: 10.ob_digit = 20.ob_digit + -30.ob_digit
print(10) # segfault

rugged sparrow
#

Also if you want to avoid having to stuff raw assembly into your program you can grab the default mp_subscript from a python class

grave rover
#

yeah but I was looking for a way to inject custom C code :^)

rugged sparrow
#

Ah

grave rover
#

injected code is c int do_x(PyLongObject* self, PyLongObject* pylong_1, PyLongObject* pylong_2) { self->digit[0] = pylong_1->digit[0] + pylong_2->digit[0]; return 0; }

rugged sparrow
#

Where are you injecting that?

rugged sparrow
grave rover
#

it's not

#

when I make -30 into 30 it stays 10

#

on -30 the ob_digit value becomes 1

#

even if it doesn't go negative, ob_size becomes negative

rugged sparrow
#

are you sure the assembly is doing things correctly?

grave rover
#

well uh

#

I kinda forgot ob_size was ssize_t

#

and made it an int when it should've been a long

#

works perfectly fine now lol

rugged sparrow
#

ah nice

last locust
#

TIL this is a shorter way of inverting a bool (var ^= True vs var = not var)```py

var = True
var ^= True
var
False
var ^= True
var
True```

hard spoke
#

var^=1

#

I did that in real code too 😛

last locust
#

Because it gives an int

#
>>> var = True
>>> var ^=1
>>> var
0
>>> var^=1
>>> var
1```
hard spoke
#

aww

last locust
#

Still the same truthiness but not strictly bool anymore

proper vault
#

they are different

#

True is a bool and 1 is an int

#

you can't return 1 from __bool__ for example

merry ridge
snow beacon
#

You could probably get it to n^3 by wrapping everything in an extra loop.

fluid tree
simple crystal
#

!e

if ~-True:
    print('~-1 is 0')
if~-False:
    print('~-0 is -1')
night quarryBOT
#

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

~-0 is -1
simple crystal
#

it doesn't return a bool

#

but it evaluates as the opposite of the bool in the majority of cases

fluid tree
#

1-(bool) seems easiest (although ^=1 is best for in-place)

#

Or if you want to be consistent use ^ for both

simple crystal
#

when the bool is getting passed around and having operations done to it that require it to be an actual bool or 0 or 1 I guess

last locust
#

Besides it's not any shorter

#

var=~-var
var^=True

snow beacon
#

At a certain point, passing around the n you have to loop over (in order that you don't accidentally do a constant number of iterations or something equally bad) will just become overhead, making it complex for nothing.

earnest wing
#

Nontrivial complexity is way more fun

simple crystal
floral meteor
#

if only you could combine augmented assignments

#

like

>>> a = 0
>>> b = (a +:= 3)+1
>>> b %+*= 2
>>> print(b*a)
12
simple crystal
#

I think you can with match case sorta

floral meteor
#

instead of

>>> a = 0
>>> a += 3
>>> b = a + 1
>>> b %= 2
>>> b = (b+2)*2
>>> print(b*a)
12
simple crystal
#

but it's a statement

#

and sorta big

#

oh incrementing walrus

floral meteor
#

yes, incrementing walrus.

#

isn't it beautiful?

simple crystal
#

this ain't no darn ++ langy here now

#

walrii are not well known for their hat wearing

floral meteor
#

what about helmet?

[:=
simple crystal
#

that's fine and I will draft the PEP now

#

I made a fake PEP to add ridiculous concatenation functionality to dict class for a technical writing class

floral meteor
#

actually, I was hoping 'bracket-equals' operators would exist and do something

#

but you can d12 = d1 | d2

simple crystal
#

if both dicts have same key, stuff all the values in a tuple lol

#

if the values are tuples concatenate

#

if one isn't a tuple concatenate that value in a tuple with other tuple

#

ridiculous

floral meteor
#

!e ```py
a = {'a':1, 'b':3}
b = {'b':2, 'c':3}
print(a|b)

night quarryBOT
#

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

{'a': 1, 'b': 2, 'c': 3}
earnest wing
#

Can we make python into haskell?

#

Compose operators with .

floral meteor
#

show me some haskell

simple crystal
#

!e

class ConcatenationDict(dict):
    """dict which allows for concatenation."""
    
    def __add__(self, addend):
        """Concatenate this dict with another."""
        updated_self = {}
        for key, value in self.items():
            if key in addend:
                if isinstance(value, tuple):
                    if isinstance(addend[key], tuple):
                        updated_self.update({key: value + addend[key]})
                    else:
                        updated_self.update({key: value + (addend[key],)})
                else:
                    if isinstance(addend[key], tuple):
                        updated_self.update({key: (value,) + addend[key]})
                    else:
                        updated_self.update({key: (value, addend[key])})
            else:
                updated_self.update(key, value)
        addend.update(updated_self)
        return updated_self
        
        
if __name__ == '__main__':
    """Test the functionality of ConcatenationDict with example provided in PEP"""
    a = ConcatenationDict({'key1': 1, 'key2': (1, 2), 'key3': (1,2)})
    b = ConcatenationDict({'key1': 2, 'key2': (3, 4), 'key3': 3})
    a += b
    print(a)

night quarryBOT
#

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

{'key1': (1, 2), 'key2': (1, 2, 3, 4), 'key3': (1, 2, 3)}
simple crystal
#

I will probably learn haskell in the next couple days just to have another entry for a code golf context

#

been itching for an excuse to learn it

#

I guess I should link it lol this week is very easy

floral meteor
#

alright, now turn this mess into dict comprehension

simple crystal
#

from a picture? pssh

floral meteor
#

it's an extract of your code

simple crystal
#

o

#

haha

#

seems p easy

#

just make ternaries with isinstance or some shortcuts for equivalent

#

I gotta walk and buy more beer rn tho

floral meteor
#
        a={key:[value,(value,)][not isinstance(addend[key]),tuple)]+[addend[key],(addend[key],)][not isinstance(addend[key],tuple)]if key in addend else value for key,value in self.items()}
        addend.update(a)
        return a
floral meteor
#

!e ```py
print(~3 <=- 1)

night quarryBOT
#

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

True
floral meteor
#

I name it thus: "rocket operator"

#

def Switch():
    """python can't tell me I can't have a switch suite :/"""
    call=lambda*args,**kwargs:lambda f:f(*args,**kwargs)
    named_as=lambda n:lambda f:setattr(f,'__name__',n)or f
    @call()
    class case:
     def __init__(self): self.state, self.value =- 1, None
     def __getitem__(self, item):
      if self.state <=- 1:raise SyntaxError("Cannot find matching switch") # __annotations__ hack only works in globals
      if self.value == item and not self.state: self.state=1; return(lambda f,*u,**ck:f(*u,**ck))
      else:return(lambda *No, **ne:None) # XD
    def switch(value):case.value,case.state = value,0
    @named_as('default')
    def otherwise(f,*u,**ck):
      if case.state <- 0:raise SyntaxError("Cannot find matching switch")
      elif not case.state:  case.state =- 1; f(*u,**ck)
    return switch, case, otherwise #

How could I improve this?

floral meteor
#

nope?

#

we should move this channel to its own section called The Dark Side, and make specialist channels, like code art, golfing, obfuscation and polyglots

#

haskell look like kabloop

#

i don't think haskell could be made in python syntax

floral meteor
#

!e ```py
def disp(a):print(a)
class struct:
@classmethod
def bootstrap(c,__g):
try:assert __g
except AssertionError as e:__g=e.traceback.tb_frame.f_back.f_globals
@lambda f:setattr(import('ctypes').py_object.from_address(id(__g)+8),'value',type("dict",(dict,),{'missing':f}))
def missing(self,key):
try:return getattr(builtins,key)
except:self[key]=c()
return self[key]
def getattr(self,v):
try:return(f:=lambda:object.getattr(self,v))()
except AttributeError:setattr(self,v,self.class())
return f()
struct.bootstrap(globals())
#---
namespace.globals.data.x = 4
namespace.globals.data.y = 3
function=lambda data: (data.x * data.y) ** 0.5 // 1
namespace.locals.data.output = function(namespace.globals.data)
disp(namespace.locals.data.output)

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 18, in <module>
003 |   File "<string>", line 11, in __missing__
004 | AttributeError: __getitem__
floral meteor
#

dahecc

#

i just realised the dunders will need to be bound

simple crystal
#

I hope you take it as a compliment thay I've learned not to bother trying to figure out what your code does cuz it does weird stuff while looking weird lol

floral meteor
#

!e alright, devoid of the globals() hack, and implementing manual methodification:

class struct:
 def __getattribute__(self,v):
  try:return(f := lambda:object.__getattribute__(self,v))()
  except AttributeError:setattr(self,v,self.__class__())
  return f()
 def __setattr__(self,n,v):
  if isinstance(v,(lambda:None).__class__):
    victim = __import__('ctypes').py_object.from_address(id(self)+8)
    victim.value = type("struct",(victim.value,),{n:v})
  elif isinstance(v,print.__class__):
    victim = __import__('ctypes').py_object.from_address(id(self)+8)
    victim.value = type("struct",(victim.value,),{n:lambda s,*a,**k:v(*a,**k)})#bound builtin behaviour
  else:object.__setattr__(self,n,v)
 __repr__=lambda s:str([f'{this}: {getattr(s,this)}'for this in dir(s)])[1 :- 1] # name the operator XD
namespace=struct()
namespace.globals.function.cout.__lshift__=print
namespace.globals.data.x, namespace.globals.data.y = 3, 4
namespace.locals.function.magnitude=lambda s,d:int(((d.x**2) + (d.y**2)) ** 0.5)
namespace.locals.data.output = namespace.locals.function.magnitude(namespace.globals.data)
namespace.globals.function.cout << namespace.locals.data.output
night quarryBOT
#

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

5
floral meteor
#

gottim

#

@sick hound @simple crystal this is an attempt to integrate the behaviour of the struct object from matlab into python, also making a variable manager in the process, by categorizing variables into a namespace structure.

simple crystal
#

ah nice

floral meteor
#

key behaviour

#

binding functions

#

substruct referencing

#

successful binding behaviour and variable categorisation

#

thus calculating the magnitude of a vector with x value 3 and y value 4

#

which is 5

#

ty

#

because break isn't an expression, rather it is a statement

#

!e ```py
try:
exec ("""for i in range(10):
print(i)or break
""")
except SyntaxError:
for i in range(10):
if not print(i+1):break

night quarryBOT
#

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

1
floral meteor
#

ik

#

but a break constitutes an entire statement

simple crystal
#

whoops

#

lol

night quarryBOT
#

@simple crystal :x: Your eval job has completed with return code 1.

001 | 1
002 | Traceback (most recent call last):
003 |   File "<string>", line 2, in <module>
004 |   File "<string>", line 2
005 |     print(i)or break
006 |                ^
007 | SyntaxError: invalid syntax
008 | 
009 | During handling of the above exception, another exception occurred:
010 | 
011 | Traceback (most recent call last):
... (truncated - too many lines)

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

floral meteor
#

exec does not insert the line, rather makes a subprocess

simple crystal
#

ah

#

can't break a superprocess loop

#

I guess allowing something to return break

#

would be the most implicit thing ever

floral meteor
#

!e you can however update a dict like such

d = {}
exec ("""for i in range(10):
  globals().update({chr(i+97):i})
""",d,d)
print(d)
night quarryBOT
#

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

{'__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in'), '__build_class__': <built-in function __build_class__>, '__import__': <built-in function __import__>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'breakpoint': <built-in function breakpoint>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in f
... (truncated - too long)

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

floral meteor
#

well...

#

!e ```py
d={}
exec('',d,d)
print(d)

night quarryBOT
#

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

{'__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in'), '__build_class__': <built-in function __build_class__>, '__import__': <built-in function __import__>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'breakpoint': <built-in function breakpoint>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in f
... (truncated - too long)

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

floral meteor
#

this is cursed

#

i like it

#

!e ```py
exec('',(d:={}),d)or d['builtins']'globals'.update({'a':4})
print(a)

night quarryBOT
#

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

4
floral meteor
#

I found a way to obfuscate a = 4

#

by executing an empty string

simple crystal
#

the second arg gets processed more than once?

#

oh it's to set it then do stuff to it

#

!e

exec('',(d:={},)or d['__builtins__']['globals']().update({'a':4})
print(a)
night quarryBOT
#

@simple crystal :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 2
002 |     print(a)
003 |     ^
004 | SyntaxError: invalid syntax
simple crystal
#

ah

#

!e

exec('',d:={})
d['__builtins__']['globals']().update({'a':4})
print(a)
#

lol

night quarryBOT
#

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

4
floral meteor
#

!e ```py
d, e = {}, {}
exec('locals()["a"]=4',d,e) or d['builtins']'globals'.update(e)
print(a)

night quarryBOT
#

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

4
floral meteor
#

EVEN MORE OBFUSCATED VERSION

simple crystal
#

and if you multiply the string it's a for loop lol

sick hound
#

!e exec('', globals().update({'a':4})),print(a)

night quarryBOT
#

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

4
fluid tree
#

You can use an If Expression instead of a statement, if you like

#

Better to use a onelinerifier

frigid lava
#

Does anyone know a bank transaction GUI ???????

fluid tree
sudden willow
night quarryBOT
#

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

001 | sleeping
002 | slept for two seconds 
fluid tree
#

!e [x() for x in (lambda: print("sleeping"), lambda: import("time").sleep(2), lambda: print("slept for two seconds"))]

night quarryBOT
#

@fluid tree :white_check_mark: Your eval job has completed with return code 0.

001 | sleeping
002 | slept for two seconds
toxic jewel
#

cute

sudden willow
#

forgot to eval pain

#

!e

@lambda v: globals().get('c')()
@lambda v: globals().__setitem__('c', lambda: print('hello'))
class   v: pass
night quarryBOT
#

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

hello
floral meteor
#

I just found this thing I wrote that looks like brainfuck, but can find the fattest cat in a pet adoption website.

floral meteor
#

!e ```py
__ =()==()==()==()==()==()==()==()==()==()==()
+=++++++++++++++++++++
*=--------------------
<<=-//--++--++--++--**
print(__)

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 4, in <module>
003 | OverflowError: too many digits in integer
floral meteor
#

ooh

#

I found a new error

floral meteor
#

why?

timid imp
#

!eval

from ctypes import c_void_p
class NoMore:
     def __str__(self):
        return "baby don't hurt me"
     __repr__ = __str__

c_void_p.from_address(id(True)+8).value = id(NoMore)
what = love = object()
what is love
night quarryBOT
#

@timid imp :warning: Your eval job has completed with return code 0.

[No output]
timid imp
#

F U

rugged sparrow
#

!e ```py
from ctypes import c_void_p
class NoMore:
def str(self):
return "baby don't hurt me"
repr = str

c_void_p.from_address(id(True)+8).value = id(NoMore)
what = love = object()
print(what is love)```

night quarryBOT
#

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

baby don't hurt me
sick hound
#

!e ~~~~True

night quarryBOT
#

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

[No output]
sick hound
#

!e print(~~~~True)

night quarryBOT
#

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

1
sick hound
#

i love python

night quarryBOT
#

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

1
#

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

-1
sick hound
#

!e print(~~~True)

night quarryBOT
#

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

-2
sick hound
#

!e print(~~~~-True)

night quarryBOT
#

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

-1
sick hound
#

!e print(~~~~[True])

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: bad operand type for unary ~: 'list'
sick hound
#

!e print(~~~~bool([True]))

night quarryBOT
#

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

1
sick hound
#

!e print(~~~~bool(...))

#

!e print(~~~~bool(...))

night quarryBOT
#

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

1
sick hound
#

!e print(~~~~bool(..))

night quarryBOT
#

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

001 |   File "<string>", line 1
002 |     print(~~~~bool(..))
003 |                    ^
004 | SyntaxError: invalid syntax
floral meteor
#

!e print(~bool('False'))

night quarryBOT
#

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

-2
floral meteor
#

!e print(~bool(False))

night quarryBOT
#

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

-1
floral meteor
#

!e @sick hound

a ,= [0x00for x in input('Hello World!')]
print(a)
night quarryBOT
#

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

15
floral meteor
#

what do you think it does?

#

what would a be without the comma?

deft rock
#

So sneaky. Is that just a tuple of one on the LHS?

floral meteor
#

that's what the comma does, yes

deft rock
#

Python. The language where whitespace matters, until it doesn't..

floral meteor
#

pfft, whitespace can go die

#

Python. The language where whitespace doesn't matter, until it does.

snow beacon
#

refrains from advertising their guide on esoteric whitespace

viscid nymph
#

!e

from ctypes import py_object
class NoMore:
     def __str__(self):
        return "baby don't hurt me"
py_object.from_address(id(True)+8).value = NoMore
what = love = object()
print(what is love)
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

baby don't hurt me
cerulean osprey
terse mortar
#

Ive never seen such a helpful error

sick hound
#

Lol

sick hound
#

Is there some esoteric trick to make an if statement without using “if”

proper vault
#

print(('more than 1', 'less than or equal to 1')[int(input())<=1])

sick hound
#

How about multi line statements

#

Like

proper vault
#

functions are probably the easiest for that

sick hound
#

If 5==5:
Print hi
Print help
Somedef()

proper vault
#

or tuple literals

sick hound
#

Can’t do it well on mobile

proper vault
#

there is also always

while condition:
    code
    break
else:
    code
sick hound
#

Now how do I do while without using while

#

Lmao

proper vault
#
for _ in iter(lambda: bool(condition), False):
    code
sick hound
#

Bet ty ty

#
stmts = 'print("some")\nprint("statements")'
exec(stmts * bool(condition))
``` works I think
#

but not as elegant

#

!e ```py
for _ in iter(lambda: bool(1==1), False):
print(“hi”)

night quarryBOT
#

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

001 |   File "<string>", line 2
002 |     print(“hi”)
003 |           ^
004 | SyntaxError: invalid character '“' (U+201C)
sick hound
#

Mobile chars smh

#

!e ```py
for _ in iter(lambda: bool(1==1), False):
print("hi")

night quarryBOT
#

@sick hound :x: Your eval job has completed with return code 143 (SIGTERM).

001 | hi
002 | hi
003 | hi
004 | hi
005 | hi
006 | hi
007 | hi
008 | hi
009 | hi
010 | hi
011 | hi
... (truncated - too many lines)

Full output: too long to upload

sick hound
#

!e ```py
for _ in iter(lambda: bool(1==1), False):
print("hi")
break

night quarryBOT
#

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

hi
sick hound
#

Are switch statements possibly in py?

#

sadly no

#

😦

proper vault
#

you can use dict to a similar effect, unless you need fallthrough

toxic jewel
sick hound
#

Only in dicts though right

toxic jewel
#
def switch(_object):
    {}.get(_object)

#

yes

sick hound
#

Ah ok

toxic jewel
#

!e


def switch(obj):
    v = {'owo': lambda: print('owo')}

    v.get(obj)

switch('owo')()
night quarryBOT
#

@toxic jewel :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 6, in <module>
003 | TypeError: 'NoneType' object is not callable
toxic jewel
#

oh wait

#

!e

def switch(obj):
    v = {'owo': lambda: print('owo')}

    v.get(obj)()

switch('owo')
night quarryBOT
#

@toxic jewel :white_check_mark: Your eval job has completed with return code 0.

owo
toxic jewel
#

called at wrong place

simple crystal
#

!e

not_if = False
exec(not_if*"print('conditional 1')")
not_if = True
exec(not_if*"print('conditional 2')")
night quarryBOT
#

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

conditional 2
simple crystal
#

oh someone did that

simple crystal
#

now that I sorta know haskell I rly can't wait for match case

floral meteor
#

You just gotta make them yourself

sick hound
#

Without a dictionary ?

floral meteor
#

without a dictionary

sick hound
#

Or

#

You mean like that

floral meteor
#

although dictionary is considered the pythonic switch

#

but without dictionary

#

switch, case, default syntax

#

you call switch with whatever you want to switch, then use case and default as wrappers

#

you want me to write one up for you?

#

I'll just clipboard dump...
Oh yeah i get AttributeError for _File__p when i try to __p

#

alrighty then i'll write this up from memory and i'll try to refrain from ctypes hackery

sick hound
#

Ty

floral meteor
#

writing for test case:

switch(5)
case[4]((1).__floordiv__,0)
case[5](print,'success')
@case[6]
def do():raise SyntaxError
@otherwise
def do():return NotImplemented
try:case[5](print,'WARNING')
except:print("pass")
else:raise RuntimeError("WRONG")
sick hound
#

Ooo

#

Where is the switch coming from though

floral meteor
#

you'll find out soon

#

whattup chilaxin?

rugged sparrow
#

@floral meteor that is because obj.__{attr_name} is mangled to obj.__{type(obj).__name__}_{attr_name}

#

when inside the class definition

floral meteor
#

mangled? I like mangled

rugged sparrow
#

!e ```py
class a:
def __test(self):
print('a')

print(dir(a))
a()._a__test()

night quarryBOT
#

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

001 | ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_a__test']
002 | a
floral meteor
#

!e ```py
def Switch():#pretend class
@lambda c:c() # instantiate this mf on the spot
class case:#pretend function
"""This is a docstring lol"""
mul=True # <- change this to disable multiple case matching. -<
def init(s):s.state,s.value =- 1,None
def getitem(s,v):
if s.state <- 0:raise RuntimeError('matching 'switch' not found')
elif(not s.state or s.mul)and v==s.value:return setattr(s,'state',1)or(lambda f,*u,**ck:f(u,**ck))
else:return(lambda
No,**ne:None)
call=getitem
def switch(v):case.state,case.value =- 0,v
@lambda f:setattr(f,'name','default')or f
def otherwise(f,*u,**ck):
if case.state <- 0:raise RuntimeError('matching 'switch' not found')
if not case.state:case.state =- 1;return f(u,**ck)
else:case.state =- 1
return(lambda
No,**ne:None)
return switch,case,otherwise
switch,case,otherwise = Switch()
switch(5)
case4
case5
@case[6]
def do():raise SyntaxError
@otherwise
def do():return NotImplemented
try:case5
except:print("pass")
else:raise RuntimeError("WRONG")

night quarryBOT
#

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

001 | success
002 | pass
floral meteor
#

YAASS

#

@sick hound

floral meteor
#

unicode kinda bloop

#

snow beacon
#

SyntaxError: invalid character '' (U+20E3)

sick hound
#

I got so much more py to learn

floral meteor
snow beacon
floral meteor
#

@snow beacon

#

It ran perfectly there is no syntaxerror

snow beacon
#

No, not that code. The one I replied to.

viscid nymph
rugged sparrow
#

Ah I flipped it

floral meteor
#

ye

#

what was i about to do?

#

something\

#

oh i did the switch

cerulean osprey
#
h="h"
def e(s):return s+"e"
def l(s):return s+"l"
def o(s):return s+"o"
def w(s):return s+"w"
def r(s):return s+"r"
def d(s):return s+"d"
def _(s):return s+" "
print(d(l(r(o(w(_(o(l(l(e(h)))))))))))
#

!e

night quarryBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

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

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

floral meteor
#

!e ```py
#final class
@lambda _0:_0()
class cout:
rgt=lt=print
rrshift=lshift=lambda _0,_1:print(end=_1)or _0
rge=le=lambda _0,_1:print(end=_1)or _1
def write(_0,_1):_1>>_0;return len(_1)
def test(_0):[
_0 << "Hello "<< "World"<'!',
"Hello ">> _0< "World!",
(("AAAAAAA" >= _0 )>> _0 <= "AAAAAA" )> _0,
cout.write("This works!")]
cout.test()

cerulean osprey
#

!e

h="h"
def e(s):return s+"e"
def l(s):return s+"l"
def o(s):return s+"o"
def w(s):return s+"w"
def r(s):return s+"r"
def d(s):return s+"d"
def _(s):return s+" "
print(d(l(r(o(w(_(o(l(l(e(h)))))))))))
night quarryBOT
#

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

hello world
cerulean osprey
#

!e

h="h"
def e(s):return s+"e"
def l(s):return s+"l"
def o(s):return s+"o"
def w(s):return s+"w"
def r(s):return s+"r"
def d(s):return s+"d"
def _(s):return s+" "
print(d(l(r(o(w(_(o(l(l(e(h)))))))))))
night quarryBOT
#

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

001 | Hello World!
002 | Hello World!
003 | AAAAAAAAAAAAAAAAAAAAAAAAAA
004 | This works!
#

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

hello world
floral meteor
#

lol

#

now reverse it

cerulean osprey
#

!e

d="d"
def e(s):return "e"+s
def l(s):return "l"+s
def o(s):return "o"+s
def w(s):return "w"+s
def r(s):return "r"+s
def h(s):return "h"+s
def _(s):return " "+s
print(h(e(l(l(o(_(w(o(r(l(d)))))))))))
night quarryBOT
#

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

hello world
cerulean osprey
#
#include<iostream>
int main(){std::cout<<"SSSS.DYNAZENON";return 0;}
#

!e import time

night quarryBOT
#

@cerulean osprey :warning: Your eval job has completed with return code 0.

[No output]
cerulean osprey
#

!e

import time

print("OwO");time.sleep(1);print("OwO")
night quarryBOT
#

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

001 | OwO
002 | OwO
cerulean osprey
#

!e print(":pypi:")

night quarryBOT
#

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

:pypi:
cerulean osprey
#

!e print("pypi")

night quarryBOT
#

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

![pypi](https://cdn.discordapp.com/emojis/766274397257334814.webp?size=128 "pypi")
cerulean osprey
#

!e print("pypi")

night quarryBOT
#

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

![pypi](https://cdn.discordapp.com/emojis/766274397257334814.webp?size=128 "pypi")
floral meteor
#

@cerulean osprey this is starting to look like #bot-commands territory

cerulean osprey
floral meteor
#

!e ```py
@lambda _0 :+ _0()
class cout:
rgt=lt=print
rrshift=lshift=lambda _0,_1:print(end=str(_1))or _0
rge=le=lambda _0,_1:print(end=str(_1))or _1
str=repr=lambda _:'std::cout'
pos=neg=invert=lambda _0:_0
_1 = lambda:'H'>=-cout
_2 = lambda:'e'>=-cout
_3 = lambda:'l'>=-cout
_4 = lambda:'o'>=-cout
_5 = lambda:' '>=-cout
_6 = lambda:'W'>=-cout
_7 = lambda:'r'>=-cout
_8 = lambda:'d'>>~cout<'!'
(*((lambda:None).class.call(_0)for _0 in(_1,_2,_3,_3,_4,_5,_6,_4,_7,_3,_8)),)

night quarryBOT
#

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

Hello World!
floral meteor
#

yas i made a new operator

sick hound
#

making an operator?

floral meteor
#

the "walrus-speaks-no-evil" operator

#

not sure what to call these ones tho

floral meteor
#

what happens when you bind an already bound function to another class?

#

!e ```py
@lambda _0:_0()
class _0:
rgt=lt=print
rrshift=lshift=lambda _0,_1:print(end=str(_1))or _0
rge=le=lambda _0,_1:print(end=str(_1))or _1
str=repr=lambda _:'std::cout'
pos=neg=invert=lambda _0:_0
@lambda _0:_0(1)
class _1(int):add=lambdaa:import('functools').reduce(int.add,a)
@lambda _0:_0(2)
class _2(int):add=_1.add
@int
@lambda _0:_0()
class _3:int=lambda
a:3
_0 <_2 .add(_3) # is it 5 or 6?

night quarryBOT
#

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

4
floral meteor
#

looks like i'll have to manually bind it

#

!e ```py
@lambda _0:_0()
class _0:
rgt=lt=print
rrshift=lshift=lambda _0,_1:print(end=str(_1))or _0
rge=le=lambda _0,_1:print(end=str(_1))or _1
str=repr=lambda _:'std::cout'
pos=neg=invert=lambda _0:_0
@lambda _0:_0(1)
class _1(int):add=lambdaa:import('functools').reduce(int.add,a)
@lambda _0:_0(2)
class _2(int):add=(lambda:None).class(_1.add.code,globals())
@int
@lambda _0:_0()
class _3:int=lambda
a:3
_0 <_2 .add(_3) # 6

night quarryBOT
#

@floral meteor :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 11, in <module>
003 |   File "<string>", line 11, in _2
004 | AttributeError: 'method-wrapper' object has no attribute '__code__'
floral meteor
#

!e ```py
print((int.mul.call.text_signature))

night quarryBOT
#

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

($self, /, *args, **kwargs)
floral meteor
#

dafuq is the $self?

floral meteor
#

how do you bind to multiple inputs?

#

i.e. ```py
def some_func($param1, $param2, $param3, /, *args, **kwargs_):
...

#

so why does a method not have a code attribute?

rugged sparrow
floral meteor
#

But before it was bound, it wAS a function defined in python

rugged sparrow
#

No it wasn't

viscid nymph
fluid tree
sudden willow
#

@floral meteor how to custom operator owo

opaque hemlock
#

yea

sudden willow
#

!e

@lambda c: 1()
@lambda c: globals().__setitem__(1, lambda: print(2))
class   c: ...
night quarryBOT
#

@sudden willow :x: Your eval job has completed with return code 1.

001 | <string>:1: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 |   File "<string>", line 3, in <module>
004 |   File "<string>", line 1, in <lambda>
005 | TypeError: 'int' object is not callable
sudden willow
#

:^(

astral rover
#

Gotta do a globals lookup

sick hound
#

Weirdest way to assign a string to a variable ?

viscid nymph
#

some way you would code it in another language

viscid nymph
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

001 | <string>:2: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
002 | 2
viscid nymph
#

cool

#

literals don't look up globals btw

floral meteor
# rugged sparrow No it wasn't

before it was bound:

add=lambda*a:__import__('functools').reduce(int.__add__,a)

after it was bound:
~~```py
add=(lambda:None).class(_1.add.code,globals())

#

!e my point is ```py
x='code'in dir((a:=lambda s:None))
y='code'in dir(type("",(),{'a':a})().a)
print(x,y)

night quarryBOT
#

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

True False
floral meteor
#

i.e. a is a function with code, then i bind it to an object and now it's mangled

#

essentially meaning i can't abuse its code to double bind a function

#

without.... functionising it

#

here comes some beautiful hackery...

#

!e ```py
flooravg=lambda a,b:(a+b)//2
a = type("foo",(int,),dict(flooravg=flooravg))(5)
hack = lambda b:a.flooravg(b)
b = type("bar",(int,),dict(flooravg=hack))(9)
print(b.flooravg())#7

night quarryBOT
#

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

7
floral meteor
#

!e hol up ```py
flooravg = lambdaa:sum(a)//len(a)
a = type("foo",(int,),dict(matmul=flooravg))(5)
print(a@9)
b = type("bar",(int,),dict(matmul=lambda
b:a.matmul(*b)))(9)
print(b.matmul(),b@5)

night quarryBOT
#

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

001 | 7
002 | 7 6
floral meteor
#

isn't it beautiful? indirect polybinding

#

now i just need to automate it

floral meteor
#

!e ```py
ex=lambda*a,**k:lambda c:c(a)
funcshinator=lambda m:lambda
a,**k:m(a,**k)
@ex()
def bind():
def decerater(bound_method,name=''):
def wraper(victim):
setattr(victim,name or bound_method.name,funcshinator(bound_method))
return victim
return wraper
return decerater
flooravg = lambda
a:sum(a)//len(a)
@ex(5)
@bind(flooravg,'matmul')
class derp(int):...
@ex(9)
@bind(derp.matmul,'matmul')
class woop(int):...
print(woop@5)#6

night quarryBOT
#

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

6
floral meteor
#

so essentially im passing 5 to a method bound to both derp and woop, which are instantiated with 5 and 9 respectively

snow beacon
floral meteor
#

!e class hello_world(metaclass=lambda*a:str(a)):...
print(hello_world)

night quarryBOT
#

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

('hello_world', (), {'__module__': '__main__', '__qualname__': 'hello_world'})
snow beacon
#

It's a string, you see.

floral meteor
#

perhapses we could control it

#

!e ```py
@print
class var("XD",metaclass=lambda*a:str(a[1][0])):0

night quarryBOT
#

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

XD
floral meteor
#

Now that is cursed i like it

#

hmm

#

im gonna try too bootstrapinator this struct class

floral meteor
#

!e ```py

def matlabinator(__g={}):
class struct:
name='<struct>'
def getattribute(self,v):
try:return(f := lambda:object.getattribute(self,v))()
except AttributeError:setattr(self,v,self.class())
return f()
def setattr(self,n,v):
if isinstance(v,(lambda:None).class):
victim = import('ctypes').py_object.from_address(id(self)+8)
victim.value = type("struct",(victim.value,),{n:v})
elif isinstance(v,print.class):
victim = import('ctypes').py_object.from_address(id(self)+8)
victim.value = type("struct",(victim.value,),{n:lambda s,*a,**k:v(a,**k)})#bound builtin behaviour
else:object.setattr(self,n,v)
repr=lambda s:f"<struct object '{s.name}' len={len(dir(s))}>"
global gulag
try:g=__g or 1/0
except ZeroDivisionError as e:g=e.traceback.tb_frame.f_back.f_globals
hack=lambda o:import('ctypes').py_object.from_address(id(o)+8)
prisoner = hack(g).value
gulag = type('atexit',(),{'del':lambda s:setattr(hack(g),'value',prisoner)})()
rename=lambda name:lambda o:setattr(o,'name',name)or o
@lambda f:setattr(hack(g),'value',type("matlabinated_globals",(prisoner,),{f.name:f}))
def missing(self, key):
try:return getattr(self['builtins'],key)
except AttributeError:return(lambda s:self.setitem(self,key,s))(rename(key)(struct()))
g.update({'struct':struct})
return g
matlabinator(globals())
data.x, data.y = 5,6
std.cout.lshift=print
std.cout << data.x
data.y

night quarryBOT
#

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

[No output]
floral meteor
#

oh cmon

#

weak

floral meteor
#

!e ```py
print(dir(type("",(),{})()))

night quarryBOT
#

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

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
floral meteor
#

!e ```py
class cout(metaclass=lambda*a:type(*a)()):lt=print
cout < "lol"

night quarryBOT
#

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

lol
floral meteor
#

!e ```py
def foo(n,a,d):
print(n)
return(*[defor e in a if e in d],)
class bar('four','two','zero',metaclass=foo):
four=lambda:4
two=lambda:2
zero=lambda:0
print(*bar,sep='')

night quarryBOT
#

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

001 | bar
002 | 420
floral meteor
#

!e ```py
class wat('wheeeeeee', 69, metaclass=print):self=print

night quarryBOT
#

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

wat ('wheeeeeee', 69) {'__module__': '__main__', '__qualname__': 'wat', 'self': <built-in function print>}
floral meteor
#

now i can make fake classes

floral meteor
#

!e class wat('Hello World',metaclass=lambda n,a,d:print(*a)):...

night quarryBOT
#

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

Hello World
floral meteor
#

!e ```py
def echo(a):
class wat(metaclass=lambda
_:print(*a)):...
echo(420)

night quarryBOT
#

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

420
floral meteor
#

!e ```py
def execute(*a,**k):
def wraper(f):
class wat(*a,metaclass=lambda n,b,d:f(*b,**k)):...
return wat
return wraper
@print
@execute(69)
class n(int):...

night quarryBOT
#

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

69
floral meteor
#

@hexed tangle exit dusint need to be called

sick hound
#

Can you write a valid python program that contains every printable ascii character except # exactly once discoHmm

floral meteor
#

no but i can make python exit without calling anything

sick hound
#

witchcraft peepoRiot

#

Did you zalgo-border your status rooBlankBlink

floral meteor
#

🌶️

quaint hound
floral meteor
#

Python is difficult to golf, and makes it hard to onelinerise in python3

#

Other languages you can use the end keyword but python you need either newline or dedent

earnest wing
earnest wing
sick hound
fluid tree
fluid tree
#

If anyone has a oneline generator tell me

last locust
#
Form = namedtuple('Form', ['id', 'tutor_id', 'name', 'room'])
data = []
while query.next():
    data.append(
        Form(query.value(0), query.value(1), query.value(2), query.value(3))
    )
```can anyone think of how to shorten this (aside from making the `data.append()` one line)?
#

Was thinking of a list-comp type thing but don't think that's possible with while loops

earnest wing
#

two-arg iter might come in handy

#

something like [... for x in iter(query.next, falsey-value)]

last locust
#
data = [Form(x[0], x[1]...) for x in iter(query.next, 0)]```?
earnest wing
#

you can test around with it

#

*map(query.value,(0,1,2,3)) etc

last locust
#

Wellpy forms = [Form(x[0], x[1], x[2], x[3]) for x in iter(query.next, 0)]gives an error saying bool isn't subscriptable

earnest wing
#

You're not originally accessing the result of next, though?

#

so why would you do that here

last locust
earnest wing
#

I was lazy to put something there

last locust
#

But what would it be

earnest wing
#

It'd be a Form(...) like in your snippet

last locust
#

Because I don't understand what you're suggesting

last locust
earnest wing
#

query.value(0), not x[0]

last locust
#

Oh yea lemon_sweat

#
forms = [Form(query.value(0), query.value(1), query.value(2), query.value(3)) for x in iter(query.next, 0)]```right so this works 👍
#
forms = [Form(*(query.value(x) for x in range(4))) for _ in iter(query.next, 0)]```slightly shorter
#

I think I'll stick with that

#

Thanks @earnest wing 👍

simple crystal
#

!e

import ctypes
for i in range (10):
    print(a:=ctypes.pythonapi.PyType_GetSlot(ctypes.py_object(True), i))
night quarryBOT
#

@simple crystal :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | SystemError: Objects/typeobject.c:3111: bad argument to internal function
simple crystal
#

I get:

28928
1296791640
0
0
0
743949472
1295814972
0
1298644416
1295474560
#

why is my True a heap object? 🤔

#

or at least being treated as one

#

False gives me that exception

rugged sparrow
#

@simple crystal PyType_GetSlot does not do any checking to ensure its argument is actually a Type object

simple crystal
#

oh, it says exception gets raised if uts not heap type

#

in docs

#

but somehow my implementation doesn't for True

rugged sparrow
#

ah 3.10 changed it

simple crystal
#

usin 3.9 for this

snow beacon
last locust
#

Lemme check

#

I know I needed the () to use the *

snow beacon
#

Never mind.

#

I just tested it and I misremembered.

last locust
#

Right yea I did do that originally and got this errorpy forms = [Form(query.value(x) for x in range(4)) for _ in iter(query.next, 0)] TypeError: <lambda>() missing 3 required positional arguments: 'tutor_id', 'name', and 'room'

#

It tries to convert to a namedtuple with just one value rather than waiting to get all 4

snow beacon
#

You could still probably do *map(query.value, range(4)) like Olivia suggested.

last locust
#

I think I tried that too

#

Lemme check

snow beacon
#

If that one doesn't work I'm more tired than I thought.

last locust
#

Right no that does work

#

It didn't work back when I was doing the wrong thing

#
forms = [Form(*(query.value(x) for x in range(4))) for _ in iter(query.next, 0)]
``````py
forms = [Form(*map(query.value, range(4))) for _ in iter(query.next, 0)]```shorter too 👍
#

Thanks

drifting grove
#

With statements but they assign temporary variables

class __replacement__:__enter__=__exit__=lambda*a,**k:0
__replacement__=__replacement__()
def get_indent(line):
 try:
  if len(line)==0:return-1
  indent=0
  while line[indent]==' ':indent+=1
  return indent-1
 except:return 0
def with_shenanigans(func):
 _next=False
 queue=[]
 code=__import__("inspect").getsource(func).split('\n')
 header=[]
 while code[0].strip().startswith('@'):
  if not code[0].strip().startswith('@with_shenanigans'):header.append(code[0])
  del code[0]
 header.append(code[0])
 del code[0]
 final_code=header
 j=0
 for line in code:
  if line.strip().startswith('with'):
   x=list(line.strip()[5:])
   del x[-1]
   x=list(''.join(x).strip())
   i=len(x)-1
   var_name=[]
   found_var_name=False
   chars_checked=0
   while i>=0:
    if x[i]!=' ':
     var_name.insert(0,x[i])
     found_var_name=True
    else:
     if found_var_name:break
    i +=~ 0
    chars_checked -=~ 0
   for i in range(chars_checked):del x[-1]
   try:
    while x[-1]in" as":del x[-1]
   except:pass
   expr=''.join(x)
   var_name=''.join(var_name)
   final_code.append(f'{" "*(get_indent(line)+1)}{var_name}={expr}')
   final_code.append((' '*(get_indent(line)+1))+'with __replacement__:')
   queue.append((get_indent(line),var_name))
  else:
   if _next:
    final_code.append(_next)
    _next=False
   final_code.append(line)
  try:
   if get_indent(code[j+1])<get_indent(line):
    _next=((queue[-1][0]+1)*' ')+'del '+queue[-1][1]
    del queue[-1]
  except:0
  j-=~0
 final_code.append("globals()['x']=x".replace('x',func.__name__))
 final_code='\n'.join(final_code)
 exec(final_code)
 return globals().get(func.__name__)
@with_shenanigans
def test():
  with "cake" as lie:
    print(lie)
  print(lie)# should give error. "lie" doesn't exist outside of with statement

test()

Link to try it (snekbox won't run it): https://trinket.io/python3/b59ea59b8d?runOption=run&showInstructions=true

rugged sparrow
#

that is technically doable without inspect using some trickery

drifting grove
#

It is?

#

I had no idea

rugged sparrow
#

gimme a sec, drafting it up

#

it works by adding an __exit__ and __enter__ method to object

drifting grove
#

that sounds like magic

rugged sparrow
#

!e ```py
from ctypes import *
import sys, dis

PyType_Modified = pythonapi.PyType_Modified
PyType_Modified.argtypes = [py_object]

queue = {}

def getclsdict(cls):
mapping = cls.dict
if isinstance(mapping, dict):
return mapping
return py_object.from_address(id(mapping) + 2 * sizeof(c_void_p)).value

def object_enter(self, *args):
frame = sys._getframe(1)
lasti = frame.f_lasti
f_code = frame.f_code
co_code = f_code.co_code
if co_code[lasti + 2] == dis.opmap['STORE_NAME']:
name = f_code.co_names[co_code[lasti + 3]]
queue[name] = self
return self

def object_exit(self, *args):
frame = sys._getframe(1)
loc = frame.f_locals
for name, value in queue.copy().items():
if value is self and name in loc and loc[name] is self:
del loc[name]
del queue[name]

obj_dct = getclsdict(object)
obj_dct['enter'] = object_enter
obj_dct['exit'] = object_exit
PyType_Modified(object)

with [1,2,3] as x:
print(x)```

night quarryBOT
#

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

[1, 2, 3]
rugged sparrow
#

@drifting grove ^

#

doesnt quite work inside functions (deleting locals is weird)

#

itll store the variable but wont delete it after

drifting grove
#

oh my goodness

#

I have no idea how that works but it is beautiful

rugged sparrow
#

it starts by getting the dictionary that supports object

#

then i define an enter and an exit func

#

then those are set inside the dictionary (because object.__enter__ = ... will fail)

#

PyType_Modified is a C function that informs all of object's subclasses to reinherit from its namespace

#

the result is that every object now has an __enter__ and an __exit__ method (and so we can use with on them)

drifting grove
#

wow

#

that's really smart

simple crystal
#

nice

#

u can also just implement a context manager that takes any obj

#

!e

from contextlib import contextmanager

@contextmanager
def withy(obj):
    yield obj

with withy([1,2,3]) as a:
    print(a)
night quarryBOT
#

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

[1, 2, 3]
simple crystal
#

oh it's not temporary

drifting grove
#

yeah

#

but that is shorter so it is probably better if you don't need it to be temporary

drifting grove
rugged sparrow
#

Nah you're all good, happy to show you

flat notch
rugged sparrow
#

I wanted to learn how python worked

#

so i read a lot of the source code

#

from there i learned how python code was excecuted by the C code

#

and how to modify it

flat notch
#

Ahh, I see

rugged sparrow
#

there are lots of interesting quirks of cpython that you can use to do tricky things

#

!pypi fishhook

night quarryBOT
rugged sparrow
#

^ that is my module for hooking into C classes

#

!e ```py
import gc

class magic:
def length_hint(self):
return 1
def iter(self):
for obj in gc.get_objects():
if type(obj) == tuple and len(obj) == 1:
try:1 in obj
except SystemError:
yield obj
break

weird = tuple(magic())
print(weird, weird[0] is weird)```

night quarryBOT
#

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

((...),) True
rugged sparrow
#

^ that uses a bug in how tuples are made from iterators

#

(and how the cpython garbage collector works)

flat notch
rugged sparrow
flat notch
#

Aye, I'll check it out

forest harbor
#
import inspect
from unittest.mock import MagicMock

class LambdaVariable(MagicMock):
    pass


class Λ:
    def __getattribute__(self, name):
        def make_lambda(expr):
            code = inspect.stack()[1].code_context[0]
            frame = inspect.stack()[1].frame
            _, code = code.split(f'.{name}(', 1)
            code = code[:find_first_unmatched_bracket(code)]
            return eval(f"lambda {name}: {code}", frame.f_globals, frame.f_locals)
        return make_lambda


def find_first_unmatched_bracket(s):
    stack = []
    for j,i in enumerate(s):
        if i == ')' and not stack:
            return j
        elif i == '(':
            stack.append(i)
        elif i == ')':
            stack.pop()
    raise ValueError


λ = Λ()
x = LambdaVariable()

f = λ.x(x + 1)
print(f"{f(1) = }")

f = λ.x([x, x+1])
print(f"{f(1) = }")

f = λ.x(x + x.upper())
print(f"{f('asd') = }")
#

no more typing lambda

earnest wing
#

that's a good one!

forest harbor
#

wont run on the bot because of dynamic bullshit, but the output is the expected

f(1) = 2
f(1) = [1, 2]
f('asd') = 'asdASD'
earnest wing
#

I wonder whether it's possible to intercept a nameerror, avoiding needing a LambdaVariable

forest harbor
#

My first idea was to not even need teh λ.x to start with, just doing

x = LambdaVariable()
f = x + 1
assert f(1) == 2

But that's limited.

#

You can't resolve [x] into lambda x: [x], for example.

earnest wing
#

Unless you could hook into tuple/set/list/dict literal creation

#

Most likely through some c tricks

forest harbor
#

Yeah, but even if you could it would generate a lot of ambiguity.

x = LambdaVariable()
f = x + 1
g = x * 2
h = [f, g]

Is h meant to be a list of lambdas or a lambda that returns a list?

earnest wing
#

that's a design decision though, isn't it

forest harbor
#

I don't think so. Python is a dynamic language so both should be possible, but the language (or the expanded language i'm proposing here) offers no means of expressing both.

#

Still the limited one has it's uses. I do a lot of pandas with method chaining so it ends up having lambda sprinkled all over.

#

With some haskellisms I managed to turn

df = get_data()
df = df[df['A'] > 0]
df['E'] = df['B'] * df['C']
df['F'] = df['E'] > 0
df = df.groupby('F').max()
plot = df.plot()
df = df.sum()
plot2 = df.plot()   
df = df * 2  

into

df = LambdaVariable()
(   
    StateContainer({}, get_data())
    >>_ (Query, "A > 0")
    >>_ (Assign, E=df['B'] * df['C'])
    >>_ (Assign, F=df['E'] > 0)
    >>_ (Groupby, "F")
    >>_ (GB.max)   
    <<_ (λ.df(StateContainer({"plot": df.plot()}, df)))
    >>_ (Sum)
    <<_ (λ.df(StateContainer({"plot2": df.plot()}, df)))
    >>_ (df * 2)
)
earnest wing
#

function composition using __getattr__ is also possible

forest harbor
#

Yeah, but i'm not composing functions, i'm mapping functors. The functions Query, Assign, etc are just the regular DataFrame methods that I populated into the globals() for the lols, but otherwise unmodified.

earnest wing
#

yeah

forest harbor
#

the >>_ "operator" applies a function to the object inside the container, not to the container itselfd.

earnest wing
#

I admit I haven't done a lot with monads

#

that being said, bending python's syntax to your will like this is the kind of ideal I strive for
(for personal projects at least)

sick hound
#

Can someone get an item through DataFrame using a multi index? My df looks like user_id | item_id | rating . If I set the index as df.set_index(['user_id','item_id']) how can I access the respective rating? In a 2d array you d do something like df[user_id][item_id], what is the dataframe equivalent of that?

forest harbor
#

use a tuple df.loc[(uid, iid)]

sick hound
#

thanks

late talon
#

what is lambda

#

is it a math function

viscid nymph
#

like

>>> 1(2)
2
near umbra
#

just getting into making weird python things

#
exec("""import pygame as A;\nZ=255;R=True;A.init();D=A.display;B=D.set_mode((Z,Z));\nwhile R:\n  if A.event.get(eventtype=A.QUIT): exit()\n  B.blit(A.font.SysFont('arial',25).render('hello world',R,(Z,Z,Z)),(0,0));D.flip()""")
``` how can I make this smaller?
near umbra
#

hmm

#

what spaces can i remove though?

viscid nymph
#
exec("""import pygame as A;\nZ=255;R=True;A.init();D=A.display;B=D.set_mode((Z,Z));\nwhile R:\n\tif A.event.get(eventtype=A.QUIT):exit()\n\tB.blit(A.font.SysFont('arial',25).render('hello world',R,(Z,Z,Z)),(0,0));D.flip()""")
#

slightly smaller

near umbra
#

ah, i didnt even think about using \t, thanks

forest harbor
#

can you from pygame import *? So then you can get rid of all A.

near umbra
#

I dont think the .display and .event would work then

forest harbor
#

I don't use pygame, but you should be able to use just display and event without A..

#

Unless they did some shananigans to avoid importing *

near umbra
#

the display and event are separeate files in pygame

#

not classes

forest harbor
#

ah, fine then

#

are you allowed to use string formatting?

near umbra
#

i would assume exec would allow it, yes

forest harbor
#

Yeah, but what's the goal, make the string the smallest possible? Make the whole program small as possible?

#

You can probably get rid of R and replace it with 1 also.

near umbra
#

yeah pretty much just make it as small as possible

#

yeah but the render function takes a bool and idk if 1 will work

forest harbor
#

Unless it gets propagated all the way down to C, it should work.

near umbra
#

okay ill try that

forest harbor
#

But again, I don't use pygame, so the only way of knowing is trying.

near umbra
#

yep it works

forest harbor
#

replacing (z,z,z) with [z]*3 saves two chars, might not work though if it realy needs a tuple, so (z,)*3 saves one char.

near umbra
#

Yeah it needs to be a tuple

forest harbor
#

do it doesnt, i just tried

#
exec("""from pygame import *;\nZ=255;init();D=display;B=D.set_mode((Z,Z));\nwhile 1:\n\tif event.get(eventtype=QUIT):exit()\n\tB.blit(font.SysFont('arial',25).render('hello world',1,[Z]*3),(0,0));D.flip()""")

this works

rugged sparrow
#

fishhook can do that all automatically

late talon
#

what is lambda

late talon
#

!d lambda

night quarryBOT
#

An anonymous inline function consisting of a single expression which is evaluated when the function is called. The syntax to create a lambda function is lambda [parameters]: expression

ebon ingot
#

it's a way of making a function without naming it or using def

late talon
#

nope

#

well actually technically you can use ```py
class Hello:
print("hello World")

#

!e```py
class Hello:
print("hello World")
Hello

rugged sparrow
late talon
#

oh

rugged sparrow
late talon
viscid nymph
astral rover
#

not if you're faint of heart

viscid nymph
#

!e

from types import FunctionType
print(FunctionType(compile('print("Hello, World")', __name__, 'exec'), globals()))
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

<function <module> at 0x7fd8cbe90280>
viscid nymph
#

!e

from types import FunctionType
my_func = FunctionType(compile('print("Hello, World")', __name__, 'exec'), globals())
my_func()
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

Hello, World
viscid nymph
#

could do my_func = type(lambda:...)(...) but I guess that is with lambda

viscid nymph
#

well that's kinda how functions get initialized...

late talon
viscid nymph
#
class function(code, globals, name=None, argdefs=None, closure=None)
#

!e

from types import FunctionType
print(FunctionType(compile('print(a)', __name__, 'exec'), globals(), 'my_function', ('a',)))
night quarryBOT
#

@viscid nymph :white_check_mark: Your eval job has completed with return code 0.

<function <module> at 0x7f60720e5280>
viscid nymph
#

interesting

simple crystal
fluid tree
#
from pygame import *
Z=255
init()
D=display
B=D.set_mode((Z,Z))
while 1:
 if event.get(eventtype=QUIT):exit()
 B.blit(font.SysFont('arial',25).render('hello world',1,[Z]*3),(0,0))
 D.flip()
#

Much shorter when you remove exec and the escapes

near umbra
#

yeah but im trying to make it one line

chilly grotto
#

This is probably not the right room to ask but would it be proper to give a function a default argument of None so that I can do an if/else inside the function depending on whether or not an argument was passed?

#

Like this:

def my_function(x=None):
  if !x:
    do this
  else:
    print(x)
night quarryBOT
#
not

6.11. Boolean operations


or_test  ::=  and_test | or_test "or" and_test
and_test ::=  not_test | and_test "and" not_test
not_test ::=  comparison | "not" not_test
``` In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: `False`, `None`, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a [`__bool__()`](https://docs.python.org/3/reference/datamodel.html#object.__bool__ "object.__bool__") method.

The operator [`not`](https://docs.python.org/3/reference/expressions.html#not) yields `True` if its argument is false, `False` otherwise.
chilly grotto
#

So it would be fine?

snow beacon
#

The conventional way to check if something is None is using x is None.

viscid nymph
#
>>> not None
True
snow beacon
#

That's probably fine too.

chilly grotto
#

ohhh I see

#

I did a double negative

snow beacon
#

Be wary of people passing in empty strings, 0, empty lists, and things like that.

viscid nymph
#

or even False

chilly grotto
#

damn. Is there a better way to implement that same idea? I feel like having the default argument as none makes the code confusing

#

oh

#

You just told me

#

I'm an idiot

#

Thank you

viscid nymph
#

lol

snow beacon
#

If you want to let people pass None as well, you'd create an object() and compare equality to that specific object.

rugged sparrow
# near umbra yeah but im trying to make it one line
(lambda p,Z:(p.init(),d:=(p.display),(b:=d.set_mode((z,z))),*iter(lambda:exit() if p.event.get(eventtype=p.QUIT)else [b.blit(p.font.SysFont('arial',25).render('hello world',1,[z]*3),(0,0)),d.flip()],0)))(__import__('pygame'),255)```
#

im not sure what the code is supposed to achieve tho

sick hound
#

Is there any function.__code__ attribute to check for variadic parameters?

#
def test(*args): ...

If I do test.__code__.co_argount it'll return 0, and I want to be able to detect the *args

snow beacon
#

The 64 bit of .co_flags, it seems.

snow beacon
#

!e ```py
h = lambdakwargs: 0
e = (lambda x: lambda: x)(None)
l = (lambda: lambda
kwargs: 0)()
@lambda f: f()
def o():
def inner(**kwargs): yield inner
return inner
@lambda f: f()
def w():
def inner(*args): yield inner
return inner
def r(*args): yield from args
d = (lambda: lambda: 0)()

def reverse_bits(n): return int(f"{n:08b}"[::-1], 2)
def to_text(*fs): return bytes(reverse_bits(f.code.co_flags) >> 1 ^ 1 for f in fs).decode()

print(to_text(h,e,l,l,o), to_text(w,o,r,l,d))

night quarryBOT
#

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

hello world
snow beacon
#

(Don't ask me to do capitals or punctuation.)

thin trout
acoustic gust
#

Do I recognize Arabic numbers?

distant wave
#

Perhaps

#

!e ```py
print(*(chr(int(a+b, 16)) for a, b in zip("٤٧٦f٦f٦٤٢٠٤d٦f٧٢٦e٦٩٦e٦٧٢c٢٠٤٦٦٥٦c٦c٦f٧٧٢٠٤٣٦١٧٤٧٣"[::2], "٤٧٦f٦f٦٤٢٠٤d٦f٧٢٦e٦٩٦e٦٧٢c٢٠٤٦٦٥٦c٦c٦f٧٧٢٠٤٣٦١٧٤٧٣"[1::2])))

night quarryBOT
#

@distant wave :white_check_mark: Your eval job has completed with return code 0.

G o o d   M o r n i n g ,   F e l l o w   C a t s
distant wave
#

Discord, stop screwing with my rtl

fluid tree
terse mortar
#

I must share this beauty I found

#

!e

@__import__
@getattr('','',lambda f:f.__name__)
class __hello__:...
night quarryBOT
#

@terse mortar :white_check_mark: Your eval job has completed with return code 0.

Hello world!
proper vault
#

oh, getattr as an identity function is smart

viscid nymph
#

actually not sure

#

did you do that so it works before 3.9?

terse mortar
#

I just said I found it

viscid nymph
#

lol

thin trout
terse mortar
#

I could probably just do this with @glacial rampart

#

Whoops poor person lol

viscid nymph
#

I did the eval on a python3.8 bot so it was needed lol