#esoteric-python
1 messages · Page 113 of 1
@cloud fossil :white_check_mark: Your eval job has completed with return code 0.
False
!e
print(0 and 1/0)
@cloud fossil :white_check_mark: Your eval job has completed with return code 0.
0
oh okay
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
wait isn't Java a compiled language
yes it is
jshell is a new feature which allows a java repl
i wish for a cshell
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
this is a bit off-topic, but PHP has a shell thing as well, right?
!e
print(True|1)
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
1
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
1
always 1
!e ```py
print(True|2)
@naive roost :white_check_mark: Your eval job has completed with return code 0.
3
ᓚᘏᗢ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
that does not work on objects from libraries like discord.py though
lol that's why you need to use 1 and 0
yeah, | will not work on non-bools
it's just bitwise or
it will but you need to know what's going on
will it even work on negatives
it isn't a boolean operator
bool is a subclass of int
of course, you can do bool(a)|bool(b)
!e
print(True|int(False))
now this is more esoteric to my liking
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
1
sometimes it lets you when you edit
!source e
Run Python code and get the results.
as long as you edit within ten seconds
ah
that's cool
!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)
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | ((...),)
002 | True
idek what i'm looking at
so you get a reference to a tuple while python still assumes it can run PyTuple_SetItem safely?
yea
fancy
!e
apple = ["apple"]
print(apple)
apple.append(apple)
print(apple)
@cloud fossil :white_check_mark: Your eval job has completed with return code 0.
001 | ['apple']
002 | ['apple', [...]]
so that's what i'm looking at
https://github.com/python/cpython/blob/f0a6fde8827d5d4f7a1c741ab1a8b206b66ffd57/Objects/abstract.c#L1966 @proper vault it happens in this function
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
cool
i wonder what other weird stuff can be done using gc inside of initalizers
Can you put two keys that are equal in a dict?
I mean, without __hash__ shenanigans.
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
...infinite_list = collections.defaultdict(lambda: object())?
Assuming object() to be the default value?
is that all the spec has to say?
something like that, though perhaps it should be the same object and not a new one each time
you don't want to use a dict as an infinite tape, lol
Watch me.
indexing has less overhead
why not? 🙂
Overhead is for nerds
I disagree, indexing has a ton of overhead when your indexes go to +-infinity 😉
if you're indices are infinite, use a dict with float keys :>
No
why float keys? int is infinite-sized
neither is float
Neither is your mother
float("inf")
!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()
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
bad
I like it
defaultdict(int) 
I did int. XD
😮
Jk pulling your leg
There just for you I removed all the numeric literals
thanks
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()
What's this supposed to do
raise errors?
why do you do int()**int() instead of int()+int()
Because they are different numbers.
python has 0**0 be 1 😔
wait I'm dumb
It also closes all the files after use. (Stdin included.)
it raises errors
A small price to pay for file safety.
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
Personally I use pathlib.
I don't need to get into the nitty-gritty when there are abstractions.
I am the nitty-gritty abstractions.
aight im gonna nitty gritty abstractions literally bound the entire global namespace to an object cos I can
So the abstractions are a fatal Python error. I see.
!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=lambdas: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())
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
bad
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=lambdas: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())
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
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
Follow your dreams, even if your dreams are... that.
sounds more like a gosh-darned nightmare
XD
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?
!e
print([0xfor x in (1, 2, 3)])
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
[15]
__getattr__ I think it is?
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
Would have weird consequences so I'll try to make one in the cursedutils package
Inheritance doesn't cut it?
let me give a little more context...
I made some code that copied all of the methods of boolean objects for one of the Esoteric Python Challenges: https://github.com/python-discord/esoteric-python-challenges/blob/master/challenges/06-maybe-keyword/solutions/IFcoltransG/Maybe.py
Dunders are impotent unless properly bound.
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
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.
here's the actual issue in my codebase: https://github.com/perrygoy/screenpy/issues/51
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
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.
i feel i might be in the right place
this Maybe/Might_Be class is great
Other people made entries for the same challenge, that might also be worth looking into.
i would just brute force the Maybe object
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.
watch me.
It's not that it's hard, it's just that it's pointless.
there done but it's 2600 chars
Hey @floral meteor!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
excuse me?!
real, imag, numerator and denominator are properties, not functions.
(If only there were an automated solution.)
would it be possible to import python into itself?
It depends on your definition of "importing python"
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
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
Can anyone help me with programming a coding language
my var command is not wrking
if you want a slower turtle, you stack another turtle on top of the first turtle
- Albert Einstein
wouldnt the top turtle be twice as fast
If it tried to walk it would fall off
hmm i guess you'd have to make the bottom turtle faster to keep up with it
that's how PyPy works
@finite rose :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | True
clearly not in special relativity, and this is an einstein quote 😛
ok but how much did einstein really know about turtles
Einstein, famed physicist turtle researcher
Hopefully better than Freud with eels.
@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
I am using the fact that PyHeapTypeObjects are a regular PyTypeObject followed directly by its tp_as_* structs to calculate the size of the structs (and their pointer offset inside the PyTypeObject)
is there any chance other data as ints will be the same as the memory addresses?
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
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
You need to look for pointers within the heap class size (between start and end)
And go by multiples of base_size
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
!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
@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
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
Pm me the total code I want to look at it
kk
I'll need to sift thru it in like an hour
it's usually only 1 or 2 wtfs per run if any
kk lemme know if you figure out what's happening haha
It's probably some uninstalized memory containing big values
So pure chance
I don't think my logic is wrong
ah okay and that's why it stops after a bit
because it overwrites uninstalized memory where heap classes are being stored
It shouldn't be overwriting anything?
In the code you sent nothing should be getting overwritten
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
why's that?
Need to look at source
!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()
@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
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
If the type has cached keys then the just getting the mem of type.sizeof gets some random memory at the end
ah cool
I'll figure out a way to fix that
ohhh is it because I made type(__scratch__) into type?
No
ok forgot I did that
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
makes sense
...could you jut use static_size?
instead of _size in the first for loop
Did it fix the weird issue,
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()
@simple crystal :warning: Your eval job timed out or ran out of memory.
[No output]
nice
Yea it causes the class to have no cached keys
I'll update that in fishhook tonight
ah neat
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
nice
Hey ,guys can you make python file find a largest amoung the five numbers. you can?After make it send the code to DISCORD.
If you go to #❓|how-to-get-help it will tell you how to get help with that.
Without exec and eval is python turing complete if you aren't allowed to use whitespace? 
well, you won't be able to define functions
nor classes
and maybe even not import anything
do newlines count as whitespace to you?
that just means one line statements i think idk
i mean... one line entire code XD
and no tabbing
!e you can use semicolons, but yeah, no indents py print(9);print(8);print(7);
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | 9
002 | 8
003 | 7
no need for the last one btw
true
!e
import(time)
@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
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
I was thinking you could do some fancy stuff with __import__ but
idk how 
same
oh i know
!e
time=__import__("time");print("sleeping");time.sleep(2);print("slept","for","two","seconds!")
@cloud fossil :white_check_mark: Your eval job has completed with return code 0.
001 | sleeping
002 | slept for two seconds!
meh, it works
!e you can use type to make methods thopy print(type("main",(),{"__init__":lambda*a:(setattr(a[0],"i",a[1]),setattr(a[0],"j",a[2]))[0],"add":lambda*a:(a[0].i+a[0].j)})(1,3).add())
@vague hearth :white_check_mark: Your eval job has completed with return code 0.
4
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)
You cal also directly instantiate types.CodeType() and then types.FunctionType() with all the correct values, to create a function that does anything.
Might as well just exec(your code encoded in a funny way, decoded at runtime)
Or take a function and replace its bytecode.
@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
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
offsets are 100% right
https://github.com/python/cpython/blob/76beadb8ff86eb2bb248bf918bfb20c4069932f4/Objects/abstract.c#L156 the you should be getting to here in the source
unless something changed between 3.9 and 3.10 but isn't listed as being different on the docs
A new slot was added to tp_as_async
Yea there is a 4th slot now
@grave rover those functions actually return a PyObject
Well mp_subscript does
right, I made a slight mistake when I moved over lol
Other than those it should work as is (with a crash due to memory execution issues)
wait so how would I map that as executable?
 you can use libc
I have an example In my asm_hook code
On my GitHub @grave rover
https://github.com/chilaxan/pysnippets/blob/cf8a8701969adeb54bc91fa1f135061d942b95e5/asm_hook.py#L21
I'm starting to not like how python handles negative numbers
ob_size of 1 for negative numbers becomes 0xffffffff
That is cause ob_size is a signed 8byte number
So it actually becomes -1
it just makes my life a little less enjoyable
it also somehow makes printing 10 an issue
It does?
10[20] = -30 # Injected code: 10.ob_digit = 20.ob_digit + -30.ob_digit
print(10) # segfault
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
yeah but I was looking for a way to inject custom C code :^)
Ah
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; }
Where are you injecting that?
take a look at the raw memory of 10 to see if what happened was expected
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
are you sure the assembly is doing things correctly?
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
ah nice
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```
That's technically not the same though
Because it gives an int
>>> var = True
>>> var ^=1
>>> var
0
>>> var^=1
>>> var
1```
aww
Still the same truthiness but not strictly bool anymore
they are different
True is a bool and 1 is an int
you can't return 1 from __bool__ for example
https://pastebin.ubuntu.com/p/cbn238sTmv/ hi the complexity of this code is n ^ 2 can you help me
You could probably get it to n^3 by wrapping everything in an extra loop.
This makes me sad
the shortest way to invert an actual bool (1 or 0) is ~-
!e
if ~-True:
print('~-1 is 0')
if~-False:
print('~-0 is -1')
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
~-0 is -1
it doesn't return a bool
but it evaluates as the opposite of the bool in the majority of cases
When doesn't it?
1-(bool) seems easiest (although ^=1 is best for in-place)
Or if you want to be consistent use ^ for both
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
I wanted it to be strictly bool
Besides it's not any shorter
var=~-var
var^=True
why stop at n^3?
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.
Nontrivial complexity is way more fun
that's only for 3 char var and there's no reason to actually use more than 1 char when golfing
if only you could combine augmented assignments
like
>>> a = 0
>>> b = (a +:= 3)+1
>>> b %+*= 2
>>> print(b*a)
12
I think you can with match case sorta
instead of
>>> a = 0
>>> a += 3
>>> b = a + 1
>>> b %= 2
>>> b = (b+2)*2
>>> print(b*a)
12
this ain't no darn ++ langy here now
walrii are not well known for their hat wearing
what about helmet?
[:=
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
actually, I was hoping 'bracket-equals' operators would exist and do something
but you can d12 = d1 | d2
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
!e ```py
a = {'a':1, 'b':3}
b = {'b':2, 'c':3}
print(a|b)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
{'a': 1, 'b': 2, 'c': 3}
show me some haskell
!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)
@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)}
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
alright, now turn this mess into dict comprehension
from a picture? pssh
it's an extract of your code
o
haha
seems p easy
just make ternaries with isinstance or some shortcuts for equivalent
I gotta walk and buy more beer rn tho
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
!e ```py
print(~3 <=- 1)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
True
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?
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
!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)
@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__
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
!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
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5
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.
ah nice
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
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
1
@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
exec does not insert the line, rather makes a subprocess
ah
can't break a superprocess loop
I guess allowing something to return break
would be the most implicit thing ever
!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)
@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 :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
this is cursed
i like it
!e ```py
exec('',(d:={}),d)or d['builtins']'globals'.update({'a':4})
print(a)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
4
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)
@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
ah
!e
exec('',d:={})
d['__builtins__']['globals']().update({'a':4})
print(a)
lol
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
4
!e ```py
d, e = {}, {}
exec('locals()["a"]=4',d,e) or d['builtins']'globals'.update(e)
print(a)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
4
EVEN MORE OBFUSCATED VERSION
and if you multiply the string it's a for loop lol
!e exec('', globals().update({'a':4})),print(a)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
4
b:*+%/=5
You can use an If Expression instead of a statement, if you like
Better to use a onelinerifier
Does anyone know a bank transaction GUI ???????
!e
(lambda t:(__import__('sys').__stdout__.write('sleeping\n'),t.sleep(2),__import__('sys').__stdout__.write(''.join(x for x in('slept ','for ','two ','seconds ')))))(__import__('time'))
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
001 | sleeping
002 | slept for two seconds
Ew ;
!e [x() for x in (lambda: print("sleeping"), lambda: import("time").sleep(2), lambda: print("slept for two seconds"))]
@fluid tree :white_check_mark: Your eval job has completed with return code 0.
001 | sleeping
002 | slept for two seconds
cute
!e
@lambda v: globals().get('c')()
@lambda v: globals().__setitem__('c', lambda: print('hello'))
class v: pass
forgot to eval pain
!e
@lambda v: globals().get('c')()
@lambda v: globals().__setitem__('c', lambda: print('hello'))
class v: pass
@sudden willow :white_check_mark: Your eval job has completed with return code 0.
hello
I just found this thing I wrote that looks like brainfuck, but can find the fattest cat in a pet adoption website.
wait this can be abused by using dict-like custom classes
!e ```py
__ =()==()==()==()==()==()==()==()==()==()==()
+=++++++++++++++++++++
*=--------------------
<<=-//--++--++--++--**
print(__)
@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
why?
!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
@timid imp :warning: Your eval job has completed with return code 0.
[No output]
F U
!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)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
baby don't hurt me
!e ~~~~True
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
!e print(~~~~True)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1
i love python
@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
!e print(~~~True)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
-2
!e print(~~~~-True)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
-1
!e print(~~~~[True])
@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'
!e print(~~~~bool([True]))
@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
!e print(~~~~bool(..))
@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
!e print(~bool('False'))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
-2
!e print(~bool(False))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
-1
!e @sick hound
a ,= [0x00for x in input('Hello World!')]
print(a)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
15
Is that using hex? 0x0f
So sneaky. Is that just a tuple of one on the LHS?
that's what the comma does, yes
Python. The language where whitespace matters, until it doesn't..
pfft, whitespace can go die
Python. The language where whitespace doesn't matter, until it does.
refrains from advertising their guide on esoteric whitespace
!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)
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
baby don't hurt me
wtf?
Ive never seen such a helpful error
Lol
Is there some esoteric trick to make an if statement without using “if”
print(('more than 1', 'less than or equal to 1')[int(input())<=1])
functions are probably the easiest for that
If 5==5:
Print hi
Print help
Somedef()
or tuple literals
Can’t do it well on mobile
there is also always
while condition:
code
break
else:
code
for _ in iter(lambda: bool(condition), False):
code
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”)
@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 :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
!e ```py
for _ in iter(lambda: bool(1==1), False):
print("hi")
break
@sick hound :white_check_mark: Your eval job has completed with return code 0.
hi
you can use dict to a similar effect, unless you need fallthrough
yes
Only in dicts though right
Ah ok
!e
def switch(obj):
v = {'owo': lambda: print('owo')}
v.get(obj)
switch('owo')()
@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
oh wait
!e
def switch(obj):
v = {'owo': lambda: print('owo')}
v.get(obj)()
switch('owo')
@toxic jewel :white_check_mark: Your eval job has completed with return code 0.
owo
called at wrong place
Another way to use exec for it
!e
not_if = False
exec(not_if*"print('conditional 1')")
not_if = True
exec(not_if*"print('conditional 2')")
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
conditional 2
oh someone did that
now that I sorta know haskell I rly can't wait for match case
yes
You just gotta make them yourself
Without a dictionary ?
without a dictionary
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
Ty
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")
@floral meteor that is because obj.__{attr_name} is mangled to obj.__{type(obj).__name__}_{attr_name}
when inside the class definition
mangled? I like mangled
!e ```py
class a:
def __test(self):
print('a')
print(dir(a))
a()._a__test()
@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
!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(lambdaNo,**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(lambdaNo,**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")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | success
002 | pass
SyntaxError: invalid character '' (U+20E3)
Holy that is stuff that I don’t even understand lmao
I got so much more py to learn
wat
Your code ^ is a syntax error, unfortunately.
what's this, chopped liver?
@snow beacon
It ran perfectly there is no syntaxerror
No, not that code. The one I replied to.
actually it's mangled to obj._{type(obj).__name__}__{attr_name}
Ah I flipped it
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
!eval [code]
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*
!e ```py
#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()
!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)))))))))))
@cerulean osprey :white_check_mark: Your eval job has completed with return code 0.
hello world
!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)))))))))))
@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
!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)))))))))))
@cerulean osprey :white_check_mark: Your eval job has completed with return code 0.
hello world
#include<iostream>
int main(){std::cout<<"SSSS.DYNAZENON";return 0;}
!e import time
@cerulean osprey :warning: Your eval job has completed with return code 0.
[No output]
!e
import time
print("OwO");time.sleep(1);print("OwO")
@cerulean osprey :white_check_mark: Your eval job has completed with return code 0.
001 | OwO
002 | OwO
!e print(":pypi:")
@cerulean osprey :white_check_mark: Your eval job has completed with return code 0.
:pypi:
!e print("
")
@cerulean osprey :white_check_mark: Your eval job has completed with return code 0.

!e print("
")
@cerulean osprey :white_check_mark: Your eval job has completed with return code 0.

@cerulean osprey this is starting to look like #bot-commands territory
In that case, let's switch to #bot-commands.
!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)),)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
yas i made a new operator
making an operator?
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=lambdaa:3
_0 <_2 .add(_3) # is it 5 or 6?
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
4
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=lambdaa:3
_0 <_2 .add(_3) # 6
@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__'
!e ```py
print((int.mul.call.text_signature))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
($self, /, *args, **kwargs)
dafuq is the $self?
__text_signature__ of a builtin method, which should
be in the following format: '($param1, ...)'.```
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?
Because only functions defined in python have code
But before it was bound, it wAS a function defined in python
No it wasn't
not enough lambdas and decorators
Annotations with unary plus?
@floral meteor how to custom operator owo
yea
!e
@lambda c: 1()
@lambda c: globals().__setitem__(1, lambda: print(2))
class c: ...
@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
:^(
Gotta do a globals lookup
Weirdest way to assign a string to a variable ?
some way you would code it in another language
!e
import ctypes
@lambda c: 1()
@lambda c: setattr(ctypes.py_object.from_address(id(1)+8),'value',type('int',(int,),{'__call__':lambda s:print(2)}))
class c: ...
@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
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)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
True False
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
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
7
!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=lambdab:a.matmul(*b)))(9)
print(b.matmul(),b@5)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 7
002 | 7 6
!e ```py
ex=lambda*a,**k:lambda c:c(a)
funcshinator=lambda m:lambdaa,**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 = lambdaa: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
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
6
so essentially im passing 5 to a method bound to both derp and woop, which are instantiated with 5 and 9 respectively
class var(metaclass=lambda*a:str(a)):0
!e class hello_world(metaclass=lambda*a:str(a)):...
print(hello_world)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
('hello_world', (), {'__module__': '__main__', '__qualname__': 'hello_world'})
It's a string, you see.
perhapses we could control it
!e ```py
@print
class var("XD",metaclass=lambda*a:str(a[1][0])):0
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
XD
Now that is cursed i like it
hmm
im gonna try too bootstrapinator this struct class
!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.xdata.y
@floral meteor :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
!e ```py
print(dir(type("",(),{})()))
@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__']
!e ```py
class cout(metaclass=lambda*a:type(*a)()):lt=print
cout < "lol"
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
lol
!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='')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | bar
002 | 420
!e ```py
class wat('wheeeeeee', 69, metaclass=print):self=print
@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>}
now i can make fake classes
!e class wat('Hello World',metaclass=lambda n,a,d:print(*a)):...
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World
!e ```py
def echo(a):
class wat(metaclass=lambda_:print(*a)):...
echo(420)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
420
!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):...
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
@hexed tangle exit dusint need to be called
Can you write a valid python program that contains every printable ascii character except # exactly once 
no but i can make python exit without calling anything
🌶️

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
No, since you can't match ' or "
agree to disagree there
good point
Old but yes
It's easy lol (excluding generators and async)
If anyone has a oneline generator tell me
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
two-arg iter might come in handy
something like [... for x in iter(query.next, falsey-value)]
data = [Form(x[0], x[1]...) for x in iter(query.next, 0)]```?
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
You're not originally accessing the result of next, though?
so why would you do that here
What's the ... supposed to be here?
I was lazy to put something there
But what would it be
It'd be a Form(...) like in your snippet
Because I don't understand what you're suggesting
But doing that gives an error
query.value(0), not x[0]
Oh yea 
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 👍
!e
import ctypes
for i in range (10):
print(a:=ctypes.pythonapi.PyType_GetSlot(ctypes.py_object(True), i))
@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
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
@simple crystal PyType_GetSlot does not do any checking to ensure its argument is actually a Type object
oh, it says exception gets raised if uts not heap type
in docs
but somehow my implementation doesn't for True
ah 3.10 changed it
usin 3.9 for this
I'm not sure you need the *( ).
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
You could still probably do *map(query.value, range(4)) like Olivia suggested.
If that one doesn't work I'm more tired than I thought.
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
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
that is technically doable without inspect using some trickery
gimme a sec, drafting it up
it works by adding an __exit__ and __enter__ method to object
that sounds like magic
!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)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3]
@drifting grove ^
doesnt quite work inside functions (deleting locals is weird)
itll store the variable but wont delete it after
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)
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)
@simple crystal :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3]
oh it's not temporary
yeah
but that is shorter so it is probably better if you don't need it to be temporary
Oh
I just realized
I never properly thanked you for showing me that or for going to the trouble of making it
Thanks so much, and sorry about that
Nah you're all good, happy to show you
Interesting stuff
How did you come to know about this being possible, just curious about what you looked into that gave you this idea
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
Ahh, I see
there are lots of interesting quirks of cpython that you can use to do tricky things
!pypi fishhook
^ 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)```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
((...),) True
^ that uses a bug in how tuples are made from iterators
(and how the cpython garbage collector works)
Ooh, I suppose I'll start by looking into cpython got a better idea of what I'm dealing with
https://github.com/chilaxan/pysnippets this repo has a bunch of my random experimentation (some of it has some comments)
Aye, I'll check it out
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
that's a good one!
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'
I wonder whether it's possible to intercept a nameerror, avoiding needing a LambdaVariable
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.
Unless you could hook into tuple/set/list/dict literal creation
Most likely through some c tricks
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?
that's a design decision though, isn't it
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)
)
function composition using __getattr__ is also possible
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.
yeah
the >>_ "operator" applies a function to the object inside the container, not to the container itselfd.
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)
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?
use a tuple df.loc[(uid, iid)]
thanks
How would you do this to make ints callable by the way 🤔
like
>>> 1(2)
2
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?
less spaces
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
ah, i didnt even think about using \t, thanks
can you from pygame import *? So then you can get rid of all A.
I dont think the .display and .event would work then
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 *
i would assume exec would allow it, yes
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.
yeah pretty much just make it as small as possible
yeah but the render function takes a bool and idk if 1 will work
Unless it gets propagated all the way down to C, it should work.
okay ill try that
But again, I don't use pygame, so the only way of knowing is trying.
yep it works
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.
Yeah it needs to be a tuple
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
You would need to insert a function pointer into the tp_call slot on int
fishhook can do that all automatically
Oh cool
what is lambda
!d lambda
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
it's a way of making a function without naming it or using def
nope
well actually technically you can use ```py
class Hello:
print("hello World")
!e```py
class Hello:
print("hello World")
Hello
What they said is exactly what lambdas are
oh
This is just running code inside the class creation scope
I didn't know that you could define a function without def
you can define a function without def and without lambda
not if you're faint of heart
!e
from types import FunctionType
print(FunctionType(compile('print("Hello, World")', __name__, 'exec'), globals()))
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
<function <module> at 0x7fd8cbe90280>
!e
from types import FunctionType
my_func = FunctionType(compile('print("Hello, World")', __name__, 'exec'), globals())
my_func()
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
Hello, World
could do my_func = type(lambda:...)(...) but I guess that is with lambda
this is cursed code
well that's kinda how functions get initialized...
interesting
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',)))
@viscid nymph :white_check_mark: Your eval job has completed with return code 0.
<function <module> at 0x7f60720e5280>
interesting
take it out of exec, the only reason to use exec to make stuff smaller is if you're using an f string, concatenating a named long repeated command, or multiplying the string to loop it
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
yeah but im trying to make it one line
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)
!d 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.
So it would be fine?
The conventional way to check if something is None is using x is None.
>>> not None
True
That's probably fine too.
Be wary of people passing in empty strings, 0, empty lists, and things like that.
or even False
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
lol
If you want to let people pass None as well, you'd create an object() and compare equality to that specific object.
(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
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
The 64 bit of .co_flags, it seems.
!e ```py
h = lambdakwargs: 0
e = (lambda x: lambda: x)(None)
l = (lambda: lambdakwargs: 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))
@snow beacon :white_check_mark: Your eval job has completed with return code 0.
hello world
(Don't ask me to do capitals or punctuation.)
Dewit
I use ...
Do I recognize Arabic numbers?
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])))
@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
Discord, stop screwing with my rtl
Well to begin with don't use """ or \t, and avoid \n. Do indent with only a single space.
I must share this beauty I found
!e
@__import__
@getattr('','',lambda f:f.__name__)
class __hello__:...
@terse mortar :white_check_mark: Your eval job has completed with return code 0.
Hello world!
oh, getattr as an identity function is smart
this looks a lot like my code 
actually not sure
did you do that so it works before 3.9?
Well i didn't say I made it lol
I just said I found it
lol
The getattr trick isn't needed in 3.9 anymore, right
Probably not.
I could probably just do this with @glacial rampart
Whoops poor person lol
I did the eval on a python3.8 bot so it was needed lol


