#esoteric-python
1 messages Β· Page 152 of 1
!e
numbers = [1, 2, 3]
print([*map(hex, numbers)])
@wheat river :white_check_mark: Your eval job has completed with return code 0.
['0x1', '0x2', '0x3']
preferably something cursed
!e ```py
print(a:=[*map(hex,[1,2,3])],[*map(eval,a)],sep='\n')
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | ['0x1', '0x2', '0x3']
002 | [1, 2, 3]
thank you
https://paste.pythondiscord.com/esepebuxec
What do you think about it ?
(itβs to long to paste here, unfortunately)
My goal was to make an obfuscated hello world with the least amount of alphanumeric characters. Only symbols.
ooh looks like an interesting challenge
that's 16 alphanumeric characters hm
lambda or chr print
!e ```py
from collections import defaultdict as d;
from ctypes import py_object as p;
globglogabgolab = p.from_address(id(globals())+8);
class flogbals(globglogabgolab.value):
slots=()
def getitem(self, name):
import builtins as builtins;
try:return builtins.dict.getitem(self,name);
except builtins.KeyError:...;
try:return builtins.getattr(builtins,name);
except builtins.AttributeError:...;
try:return self['annotations']name
except:raise builtins.NameError(name+' does not exist');
globglogabgolab.value=flogbals;
stack:lambda x=[]:x
Hello:lambda:stack.append("Hello, World")#push greeting to stack
World:lambda:print(stack.pop())#broadcast from top of stack
Hello, World
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello, World
fair enough
globglogabgolab π³
I am the globlogabgolab...
thinking about it, you really only need to use print and chr no?
just print(chr(...)+...)
or actually, just be cheaty and use exec and chr
This could perhaps be modified to completely remove reliance on globals, then completely remove original usage of globals, then an entirely new syntax would be required.
I could make python stack based
I can make a stack in the __getitem__ title line
Itβs not only about using the least number of alphanumeric characters (otherwise, the shortest will probably be some exec), itβs also making it obfuscated in some strange way. In that one, I am building one big list containing some functions and numbers for the characters. The lambda is a recurrsive function that convert the list of number to a string.
A cleaner version of the lambda is :
convert = lambda l : [[],'!'][l==[]] or chr(l[0])+convert(l[1:])
ah
!e hiding variables in functions ```py
def f(n, stack=[]):
stack.append(n)
return stack
*map(f,'Hello World!'),
print(''.join(f("\n")))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
oh i didnt notice the , i was like how r u unpacking into nothingness
I'm unpacking into the void
python has void
the void shall consume all...
def main() -> void:{
...
}

almost
!e ```py
stack=[]
@type.call
class annotations:
builtins=builtins.import('builtins')
def setitem(self,item,value,stack=stack):{
'PUSH':lambda v:stack.append(v),
'CHAR':lambda v:stack.append(chr(v)),
'ADD':lambda v:stack.setitem(-1,stack[-1]+v),
'MUL':lambda v:stack.setitem(-1,stack[-1]*v),
'SUB':lambda v:stack.setitem(-1,stack[-1]-v),
'DIV':lambda v:stack.setitem(-1,stack[-1]//v),
'ECHO':lambda v:print(v),
'ARR':lambda v:stack.iadd(v)
}.get(item, lambda v:None)(value);
from ctypes import py_object as p;
globglogabgolab = p.from_address(id(globals())+8);
class flogbals(globglogabgolab.value):
slots=()
def getitem(self, name, stack=stack):
import builtins as builtins;
if name=='VOID':return;
try:return builtins.dict.getitem(self,name);
except builtins.KeyError:...;
try:return builtins.getattr(builtins,name);
except builtins.AttributeError:...;
if name=='POP':return stack.pop()
if name=='ADD':return(lambda a,b:stack.append(b+a)or b+a)(stack.pop(),stack.pop())
if name=='SUB':return(lambda a,b:stack.append(b-a)or b-a)(stack.pop(),stack.pop())
if name=='PULL':return(lambda s:print(end=chr(s)if type(s)is int else s)or s)(stack.pop())
if name=='MUL':return(lambda x:stack.append(x)or x)(stack.pop(-1)*stack.pop())
if name=='FLIP':stack.reverse();return
if name=='CHAR':stack.append(chr(stack.pop()));return stack[-1]
if name=='SWAP':stack.iadd([stack.pop(),stack.pop()]);return
if name=='ORD':stack.append(ord(stack.pop()));return stack[-1]
if name=='DIV':stack.append((lambda a,b:b//a)(stack.pop(),stack.pop()));return stack[-1]
if name in('START','END','NOOP'):return;
if name=='newline':return'\n';
raise builtins.NameError(name+' does not exist');
globglogabgolab.value=flogbals;
START;
PUSH: 'H';
ADD: 'e';
PUSH: 'l';
PUSH: 2;
MUL;
ADD;
ADD: 'o';
CHAR: 32;
ADD;
PUSH: 33;
PUSH: 'W';
ADD: 'o';
ADD: 'r';
ADD: 'l';
PUSH: 100;
CHAR;
ADD;
SWAP;
CHAR;
ADD;
ADD;
PULL;
ECHO: newline;
END;
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
I got it!
I kinda cheated a little by swapping arguments.
and using anything other than integers
it would be None instead of void
how can the colons go there
how about
void = None
ah yes, don't you ever just want to code in assembly in python
wait shouldn't MUL just multiply the top two stack values
depends if an argument is given
eh
nah that's too many qol opcodes you provide, i need native assembly torture
be careful what you wish for...
ohshit
even better: machine language
Type annotation
!e ```py
def f():
0xA9, 0x01;
0xA0, 0x00;
0x99, 0x00, 0x80;
0x99, 0x00, 0x81;
0x99, 0x00, 0x82;
0x99, 0x00, 0x83;
0xc8;
0xD0; 0xF1;
0x60;
from dis import dis
dis(f)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 2 0 NOP
002 |
003 | 3 2 NOP
004 |
005 | 4 4 NOP
006 |
007 | 5 6 NOP
008 |
009 | 6 8 NOP
010 |
011 | 7 10 NOP
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/tebimimaxe.txt?noredirect
it compiles noops lol
probably to make jump offsets easier to compute
one optimization done but not another
!e ```py
def f():
_0360= 0xA9, 0x01;
_0362= 0xA0, 0x00;
_0364= 0x99, 0x00, 0x80;
_0367= 0x99, 0x00, 0x81;
_036A= 0x99, 0x00, 0x82;
_036D= 0x99, 0x00, 0x83;
_0370= 0xc8;
_0371= 0xD0; 0xF1;
_0373= 0x60;
from dis import dis
dis(f)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 2 0 LOAD_CONST 1 ((169, 1))
002 | 2 STORE_FAST 0 (_0360)
003 |
004 | 3 4 LOAD_CONST 2 ((160, 0))
005 | 6 STORE_FAST 1 (_0362)
006 |
007 | 4 8 LOAD_CONST 3 ((153, 0, 128))
008 | 10 STORE_FAST 2 (_0364)
009 |
010 | 5 12 LOAD_CONST 4 ((153, 0, 129))
011 | 14 STORE_FAST 3 (_0367)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/evadogukuh.txt?noredirect
it completely ignores annotations
!e ```py
def f():
_0360= 0xA9, 0x01;
_0362= 0xA0, 0x00;
_0364= 0x99, 0x00, 0x80;
_0367= 0x99, 0x00, 0x81;
_036A= 0x99, 0x00, 0x82;
_036D= 0x99, 0x00, 0x83;
_0370= 0xc8;
_0371= 0xD0, 0xF1;
_0373= 0x60;
print(f.code.co_code,f.code.co_consts)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
b'd\x01}\x00d\x02}\x01d\x03}\x02d\x04}\x03d\x05}\x04d\x06}\x05d\x07}\x06d\x08}\x07d\t}\x08d\x00S\x00' (None, (169, 1), (160, 0), (153, 0, 128), (153, 0, 129), (153, 0, 130), (153, 0, 131), 200, (13, 241), 96)
i mean- the compiler probably was like: "yeah this function actually does nothing so let's optimise it"
if i throw the straight numbers in there without annotations, the opcodes are full of NOPs
!e ```py
def f():
0xA9, 0x01;
0xA0, 0x00;
0x99, 0x00, 0x80;
0x99, 0x00, 0x81;
0x99, 0x00, 0x82;
0x99, 0x00, 0x83;
0xc8;
0xD0, 0xF1;
0x60;
print(f.code.co_code,f.code.co_consts)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
b'\t\x00\t\x00\t\x00\t\x00\t\x00\t\x00\t\x00\t\x00d\x00S\x00' (None,)
!e ```py
(:=getattr,:=dir,:=(:=(:=()==())+)+,:=()==[],(:=(((((),(())[]),(())[][:]+(())[(+)**()+][(+)**()+]+(())[][:+]+(())[(+)*(+)][-(+):]),(())[-(+)][:()**(+)+()]+(())[][(+)**()]+(())[+][---:])()**(++)-(*(+____)),(())[][+]+(())[()*(+)][+]+(())[____][:]+(())[(+)*(()**(+)-)][:+]+(())[()*(+)][+]+(())[()*(*(+))][:()*(+)]+(())[(+)*(()*(+))][:])(()[()**()][()*(+):(+)*()]+()[][:(+)*()]+()[()**(()*(+))--][()*(+)+:()**()-]+(())[+][()**(+):(+)*()]),(())[*(+)+][:+]+()[*(+)-][:+])((:=(______,(())[(+)*(+)][:+])(),()[**(+)-(*)])((,(())[*][+:+-]+(())[*(+)+][])((,(())[][]+(())[*(+)+][]+(())[][+]),(**(+)+(+),(+)**+(*(+)),**(++)-(*(+)),**(++)-(*(+)),**(++)-(**+),**(+),(+)**++,**(++)-(**+),**(++)-((+)*+),**(++)-(*(+)),*(+),(+)+)))))
@pastel sparrow :white_check_mark: Your eval job has completed with return code 0.
Hello World!
hi
What functions were used?
dir and getattr, up in the top
Oh, right.
When I try to run it, I get an error. π€·ββοΈ
i'm guessing it's because you're using a different version of python
:/
drawbacks of using dir rather than chr
humβ¦ mine had better portability π
I'm still angry that this does nothing... either at compile time or at run time, whichever.
what did you want them to do?
save that annotations in function dictionary
in f.__annotations_body__ for example
or in f.__annotations__['__code__']
!e
from ctypes import *
import builtins
import random
import time
_rand = random.Random(time.time() // 86400)
_words = ["APPLE", "MAGIC", "SNAKE", "AWAKE", "MODEL"]
_word = _rand.choice(_words)
# stolen from stackoverflow :heart:
def wordle(actual, guess):
cols = []
actualF = {}
for letter in actual:
if letter not in actualF:
actualF[letter] = 1
else:
actualF[letter] += 1
guessF = {}
for letter in guess:
if letter not in guessF:
guessF[letter] = 1
else:
guessF[letter] += 1
for idx in range(0, 5):
if guess[idx] == actual[idx]:
cols.append((guess[idx], 'π©'))
elif guess[idx] in actual:
if guessF[guess[idx]] > actualF[guess[idx]]:
cols.append((guess[idx], 'β¬'))
guessF[guess[idx]] -= 1
else:
cols.append((guess[idx], 'π¨'))
else:
cols.append((guess[idx], 'β¬'))
out = "".join(list(x[1] for x in cols))
if out == 'π©π©π©π©π©':
out += "\nπ Congrats! π"
return out
obase = py_object.from_address(id(globals()) + 8)
class fglobals(dict):
__slots__ = ()
def __getitem__(self, key, dict=dict, obase=obase, builtins=builtins, getattr=getattr):
try:
obase.value = dict
if len(key) == 5 and key.isalpha() and key.upper() == key:
# wordle
print(f"{key}: {wordle(_word, key)}")
return
return self[key]
except:
try:
return getattr(builtins, key)
except:
return None
finally:
obase.value = __class__
obase.value = fglobals
APPLE
PLANT
WAKER
AWAKE
@languid hare :white_check_mark: Your eval job has completed with return code 0.
001 | APPLE: π©β¬β¬β¬π©
002 | PLANT: β¬β¬π©β¬β¬
003 | WAKER: π¨π¨π¨π¨β¬
004 | AWAKE: π©π©π©π©π©
005 | π Congrats! π
wordle, but cursed
That's very cursed.
Either something similar in effect to annotations directly in the module level, (#esoteric-python message) or just linked to code in a way that would let a debugging decorator helper function reach into the code to see what's up.
I kinda expected it to be locals()['__annotations__']
damn cursed but i kinda like it
!e
code
!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!*
Alternatively, just use global annotations, annotating on run.
Otherwise they're just comments
!e ```py
"""
Docstring
"""
normal comments
"Some random string that compiles to nop"
def f():
annotation: "does nothing"
@floral meteor :warning: Your eval job has completed with return code 0.
[No output]
Therefore, hashtag comments are obsolete when you can semicolon string, or use a colon to comment on the middle of an equals
Or just make a line a string
!e just realized you can put smileys in your code
from __future__ import annotations
sad :C
playful :P
meh :I
@restive void :warning: Your eval job has completed with return code 0.
[No output]
yo ur code has got some personality
don't forget ```py
happy :D
im sad annotations to str is not inbuilt in 3.11 sad :C
surprised :o
other candidates: :S, :x, :E (Cthulu),:v (Pacman)
@tribal crown :white_check_mark: Your eval job has completed with return code 0.
Hello, World!
from __future__ import annotations
sad :C
meh :I
playful :P
woozy :S
cthulu :E
silent :x
happy :D
pacman :v
explain please
i get builtinimporter from ().__class__.__base__.__subclasses__()[104]
that's also why it doesn't work on other python versions, since every python versions has a different number of classes which inherit from object
i dont understand that
().__class__ is just the tuple class
tuple.__base__ is just object
object.__subclasses__ is basically every class in existence
since every class has to inherit from object
My implementation of Square & Multiply in Python (minified): py SM=lambda b,e:(a:=b,_:=[a:=a**2 if x=='0' else a**2*b for x in bin(e)[3:]],a)[2]
its it square multiple and mod?
like
def binstr_pow_mod(base: int, exponent: int, mod: int) -> int:
base_copy = base
for n in bin(exponent)[3:]:
base = base ** 2 % mod
if n == '1':
base = base * base_copy % mod
return base
thats for cryptographic use, the above one is the regular one
ah k
ya i think, hold on
alr
im in game rn xD
k
cryptographic?
yea, web enc requires complex math to work
oh, you're talking about rsa
not that complex, but hard math*
there are other places that use modulo powers, heh
yeah
web enc is the main use
even still, weird to call it cryptographic
fair
@languid hare give me an 64 bit RSA number
9822358919111718011
SM=lambda b,e:(a:=b,_:=[a:=a**2*(b*(x!='0')or 1)for x in bin(e)[3:]],a)[2]
does this work?
alr
2327196259 & 4220683529
@languid hare sorry wasn't paying attention
lemme se
yup
all good1
what about
SM=lambda b,e:(a:=b,_:=[a:=a**2*((x=='0')or b)for x in bin(e)[3:]],a)[2]
It took 8 sec!
Python 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> SM=lambda b,e:(a:=b,_:=[a:=a**2*((x=='0')or b)for x in bin(e)[3:]],a)[2]
>>> SM(999,1000)==999**1000
True```
ns
lemme do 10k random tests
all([SM(tmp:=random.randint(1,99999),tmp2:=random.randint(1,99999))==tmp**tmp2 for _ in range(9999)])```
it takes too long
>>> SM=lambda b,e:(a:=b,[a:=a**2*((x=='0')or b)for x in bin(e)[3:]])[1][-1]
>>> all([SM(tmp:=random.randint(1,99999),tmp2:=random.randint(1,99999))==tmp**tmp2 for _ in range(50)])
True```
lets optimize: ```py
1 0 LOAD_DEREF 1 (b)
2 DUP_TOP
4 STORE_DEREF 0 (a)
6 LOAD_CLOSURE 0 (a)
8 LOAD_CLOSURE 1 (b)
10 BUILD_TUPLE 2
12 LOAD_CONST 1 (<code object <listcomp> at 0x000001F46379B310, file "<stdin>", line 1>)
14 LOAD_CONST 2 ('<lambda>.<locals>.<listcomp>')
16 MAKE_FUNCTION 8 (closure)
18 LOAD_GLOBAL 0 (bin)
20 LOAD_FAST 1 (e)
22 CALL_FUNCTION 1
24 LOAD_CONST 3 (3)
26 LOAD_CONST 0 (None)
28 BUILD_SLICE 2
30 BINARY_SUBSCR
32 GET_ITER
34 CALL_FUNCTION 1
36 BUILD_TUPLE 2
38 LOAD_CONST 4 (1)
40 BINARY_SUBSCR
42 LOAD_CONST 5 (-1)
44 BINARY_SUBSCR
46 RETURN_VALUE
Disassembly of <code object <listcomp> at 0x000001F46379B310, file "<stdin>", line 1>:
1 0 BUILD_LIST 0
2 LOAD_FAST 0 (.0)
>> 4 FOR_ITER 14 (to 34)
6 STORE_FAST 1 (x)
8 LOAD_DEREF 0 (a)
10 LOAD_CONST 0 (2)
12 BINARY_POWER
14 LOAD_FAST 1 (x)
16 LOAD_CONST 1 ('0')
18 COMPARE_OP 2 (==)
20 JUMP_IF_TRUE_OR_POP 12 (to 24)
22 LOAD_DEREF 1 (b)
>> 24 BINARY_MULTIPLY
26 DUP_TOP
28 STORE_DEREF 0 (a)
30 LIST_APPEND 2
32 JUMP_ABSOLUTE 2 (to 4)
>> 34 RETURN_VALUE```
ya im still in game hold on xD
!e
import random
def fast_exp(base, exp):
result = 1
for _ in iter(lambda:exp, 0):
if _ & 1:
result *= base
base *= base
exp >>= 1
# print(_)
return result
SM=lambda b,e:[r:=1,[[r:=r*b,b:=b*b,e:=e>>1][_%2:]for _ in iter(lambda:e,0)],r][2]
print(all([fast_exp(tmp:=random.randint(1,99999),tmp2:=random.randint(1,99999))==tmp**tmp2 for _ in range(10)]))
print(all([SM(tmp:=random.randint(1,99999),tmp2:=random.randint(1,99999))==tmp**tmp2 for _ in range(10)]))
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | False
:<
yo ryuga
do u know an alternative to id()
where it would show a different id even if the string value is the same
uh not sure, python caches stuff like that
golfed it down ever so slightly: ```py
SM=lambda b,e:(a:=b,[a:=aa(<'1'or b)for()in bin(e)[3:]],a)[2]
Is this assembly?
assembly is a little worse
a lot*
Eh? dis.dis?
!e ```py
from dis import dis
print(dis("print('Hello World!')"))
@pastel sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (print)
002 | 2 LOAD_CONST 0 ('Hello World!')
003 | 4 CALL_FUNCTION 1
004 | 6 RETURN_VALUE
005 | None
aight
Python bytecode
To see what a function does
realistically: never
unless you're bored or doing some esoteric stuff then yeah
or trying to analyze obfuscated code
or trying to make optimized python code
any func is immediately translated to bytecode, which is optimized, its not fully compiled, but not fully the source
bytecode isn't optimised though
case in point: dict() and {}
both will have different bytecodes but one is more efficient over the other since it saves one function call
!e ```py
from dis import dis
print(dis("{}"))
print(dis("dict()"))
@pastel sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 BUILD_MAP 0
002 | 2 RETURN_VALUE
003 | None
004 | 1 0 LOAD_NAME 0 (dict)
005 | 2 CALL_FUNCTION 0
006 | 4 RETURN_VALUE
007 | None
bytecode is optimized, but it is not "perfectly" optimized
!e
import dis
dis.dis("(1 << 8) - 1")
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_CONST 0 (255)
002 | 2 RETURN_VALUE
also, optimizing dict() to {} is not necessarily always correct
Isn't there a module for optimising byte code by hand?
ah true
@hax
def doubled(items):
bdl | 0
ldf | items
git
~ loop
fit @ end
dpt
lap | 3
lap | 2
jmp @ loop
~ end
ret
or something of the sort 
lmao it looks like half assembler, half lua
broken in 3.11
Are any zero-width characters valid in identifiers in Python?
foo() doesn't call type(foo).__call__, is there a way I can hook onto this. Without using a decorator is it possible?
^ foo is a regular function
everything cursed is broken in 3.11
some
this would require an intermediate wrapper that converts a function to a hax readable function
i managed to fix chilaxan's builtinexc that broke because of changes to the code object structure in 3.11
Or for the person who broke it to also fix it before the 3.11 final release. π
I'm not sure I want to go past 3.9 at this stage.
I was a little put off at 3.10 with the introduction of match case
doesn't even has default or otherwise, just has case _ which sucks if you have a variable called _ and I usually do
!e ```py
_ = 5
match 7:
case :
print()
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
5
!e ```py
_ = 5
match 5:
case 7: print('')
case : print()
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
5
well this is weird it acts as both default and case underscore
well i suppose you're right
!e ```py
spy = type('',(),{'getattribute':print})()
match(1,2):
case spy:print(0)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
0
why can't the spy see anything?
case spy doesn't make sense though
it should call whatever it calls to determine the nature of the instance. In this case everything is intercepted and redirected to stdout.
But it is not calling __class__ or __eq__
!e ```py
spy = type('',(),{'getattribute':print})()
match spy:
case _:print(0)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
0
spy doesn't report anything from this position either
match spy takes in the spy, the spy acts as a mole reporting whatever is done.
well, theoretically
!e ```py
spy = type('',(),{'eq':print})()
match spy:
case None:print(0)
case _:print(1)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
1
hm
so how does it determine if a pattern matches?
it's probably some under the hood magic ig
there must be a new dunder
!e ```py
spy = type('Spy',(),{this:print for this in dir(object)if this!='class'})()
match spy:
case 0:print(0)
case _:print(1)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | <class '__main__.Spy'>
002 | 1
I think I know how to see which comparison it's making
_ matches anything, no questions asked.
!e ```py
spy = type('Spy',(),{this:(lambda s,*data,t=this:print(s,*data,t))for this in dir(object)if this!='class'})()
match spy:
case 0:print(0)
case _:print(1)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | <class '__main__.Spy'> __new__
002 | 1
spy.__new__(Spy) so where is it getting Spy from when it should only be in spy.__class__ which isn't being accessed?
why is it making a copy of spy?
aren't you creating an instance of spy by yourself
there is no spy, it died at birth
!e ```py
spy = type('Spy',(),{this:(lambda s,*data,t=this:print(s,*data,t))for this in dir(object)if this not in{'class','new','repr','str'}})()
match spy:
case 0:print(0)
case _:print(1)
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | <__main__.Spy object at 0x7f220f2eab00> __init__
002 | <__main__.Spy object at 0x7f220f2eab00> 0 __eq__
003 | 1
!e
code
!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 this is where it reaches the realm of pointless ```py
a = b = 5
match a:
case b if a==b:print(':)')
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
:)
!e I still much prefer the old ways ```py
a = b = 5
{a:lambda:print(1)}.get(b,lambda:print(0))()
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
1
you see then calling it is optional and you can return the function instead
!e ```py
x = 0
def runifzero(n):
def inner(f):
return{0:f}.get(n,lambda:f)()
return inner
@runifzero(x)
@runifzero(1)
def greet():
print("Hello World!")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
!e as opposed to ```py
x = 0
def runifzero(n):
def inner(f):
match n:
case 0:return f()
case _:return f
return inner
@runifzero(x)
@runifzero(1)
def greet():
print("Hello World!")
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
Hello World!
or the more classic```py
if n==0:return f()
else:return f
I'm assuming from your role you participate in the creation of python.
How does it make you feel to open up this channel #esoteric-python and see your creation get tortured in so many different ways?
you seem to misunderstand case identifier: patterns @floral meteor
any instance of case x: is like a wildcard case except it shadows x
the idea behind structural pattern matching is first of all to match structure
everything else is delegated to guards (or you can use the namespace patterns which are maybe a little clunky)
so if you have a long elif x == y chain then sometimes that's all you need
anyways if you want to know how to write terrifying code with match read the spec
!pep 634
!e
match globals():
case {**copy}: copy["e"] = 42
print(e) #?
is while 1:1 the shortest python program that runs forever 
damn execution just timed out?
that's weird, the bot normally says it times out I thought 
maybe it's an undiscovered bug 
!e
match globals():
case {**copy}: copy["e"] = 42
print(e) #?
@earnest wing :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | NameError: name 'e' is not defined
nope
while 1:1
[*iter(int,1)]
(f:=lambda:f())()
2**2**30
i will try to disprove this
note: try
!e
print(len('while 1:1'))
@unreal echo :white_check_mark: Your eval job has completed with return code 0.
9
!timeit
9**999999
@unreal echo :white_check_mark: Your timeit job has completed with return code 0.
1 loop, best of 5: 283 msec per loop
!timeit
99**99999
@unreal echo :white_check_mark: Your timeit job has completed with return code 0.
10 loops, best of 5: 22.5 msec per loop
.wa msec
edit cpython, change the name of while :)
I see... so it's backwards structure building this is usefuller than I previously thought
!e ```py
var1 = 0,
var2 = 1
def process(x):
match x:
case y,:return y
case y:return y
print(*map(process,(var1, var2)))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
0 1
except if x is _
Hello, is there a better way to declare a decorated method? The function sync() is a decorator for converting coroutines to synchronous functions
class Client:
async def get_current_scan(self):
pass
sync_get_current_scan = sync(get_current_scan)```
you're probably better off getting help from a help channel, this is the torture chamber.
#βο½how-to-get-help
I tried
twice
but no one actually responded
I get that this is for esoteric stuff but I'm just looking for a way to have 2 versions of the same function in a class, one decorated and the other one undecorated
!e ```py
def a(f):
return lambda*a:f(*a)+9
@a
def timesten(n):
return int(str(n)+'0')
print(timesten(6))
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
69
does the "at" symbol not work on a coroutine?
it does
so what's the issue?
default values
match message.content.split()[1:]:
case[w,x,y,z]:w,x,y,z=w,x,y,int(z)
case[w,x,y]:w,x,y,z=w,x,y,0
case[w,x]:w,x,y,z=w,x,None,0
case[w]:w,x,y,z=w,'',None,0
case[]:w,x,y,z='','',None,0
but I still prefer
w,x,y,z = (lambda _,w='',x='',y=None,z='0':(w,x,y,int(z)))(*message.content.split())
anything useful I can think of with match case I can also think of a better way
match json.loads(z):
case True|False|None:print("unit")
case float(x):print(f"ohoho {x}")
case str(_):pass
case [*x]:print(len(x))
case {**_}:1/0
the first case maybe but the rest of it...
(lambda x=json.loads(z):{
float:lambda:print(f"ohoho {x}"),
# str:lambda:None, # this line might not even be needed since there's no default case
list:lambda:print(len(x)),
dict:lambda:1/0
}.get(type(x),lambda:x in[True,False,None]and print("unit")or None)())()
this one better because backwards compatibility and onelinerisability :P
also reading the former I'm asking myself "does case float(x) mean x is a float, or x is something such that when coerced to a float it equals json.loads(z)?"
whilst the latter explicitly compares the instance type
of course the simple examples are easy to replace π
part of me wants to say "fite me", part of me wants to quit while im still ahead.
XD
why are you fighting
anyways python patma is unfortunately limited by being runtime
as opposed to static
so
match expression:
case BinaryOp("+", left, UnaryOp("-", right)): return BinaryOp("-", left, right)
case ...
is not as efficient as it could be
π’
the curse and blessing of __match_args__
okay realistically it would be Op.Plus and Op.Minus instead, in an enum
!e wait I thought of one ```py
d = {4:'f'}
e = {'f':4}
for f in d,e:
match f:
case{int(a):str(b)}:print(a*(b+'oo'))
case{str(a):int(b)}:print(b*(a+'oo'))
@floral meteor :x: Your eval job has completed with return code 1.
001 | File "<string>", line 5
002 | case{int(a):str(b)}:print(a*(b+'oo'))
003 | ^
004 | SyntaxError: invalid syntax
well that's the only one I could think of that would be useful
!e ```py
d = {2:'o'}
match f:
case{a:b}:print('f'+a*b)
@floral meteor :x: Your eval job has completed with return code 1.
001 | File "<string>", line 3
002 | case{a:b}:print('f'+a*b)
003 | ^
004 | SyntaxError: invalid syntax
oh cmon
!e ```py
a = 2
d = {2:'o'}
match f:
case{a:b}:print('f'+a*b)
@floral meteor :x: Your eval job has completed with return code 1.
001 | File "<string>", line 4
002 | case{a:b}:print('f'+a*b)
003 | ^
004 | SyntaxError: invalid syntax
Python Enhancement Proposals (PEPs)
it's is existing value :P
I like my dictionary switching specs better still
"{" case0 ":lambda:" body0["," casen ":lambda:" bodyn] "}" (".get(" switch ",lambda:" defaultbody ")" | "[" switch "]") "()"
!e ```bf
#[-][
@type.call
class :
input,en_in="",True
B=2<<2
def init(s):
s.i=s.o=2>>2
s.a=[s.i]((2<<s.o)s.B)
def pos(s):
s.o += 1
return s
def neg(s):
s.o -= 1
return s
def add(s,o):
s.a[s.i] += +(s.o,setattr(s,'o',0))[0]+ 1
s.a[s.i] %= 2s.B
return s
def sub(s,o):
s.o =- +s.o+ 1
s.a[s.i] -= (s.o,setattr(s,'o',0))[False]
s.a[s.i] %= 2**s.B
return s
def getattr(s,a):
try:return object.getattr(s,a)
except:return print(end=chr(s.a[s.i]))or s
def getitem(s,f):{
f is...:lambda:s[...],
type(f)is tuple:lambda:{s(f)for _ in iter(lambda:s.a[s.i],0)},
f is s:lambda:[lambda:None,lambda:(
s.a.setitem(s.i,0),setattr(s,'o',0)
),lambda:(()for()in()).throw(RecursionError)]bool(s.o)or 2*bool(s.a[s.i]),
type(f)==type(lambda:0):lambda:{f()for _ in iter(lambda:s.a[s.i],0)} }1;return s
def gt(s,o):s.i += 1;s.a += [0] (s.i- +len(s.a)+ 1);return s
def lt(s,o):s.a.insert(0,0)if not s.i else s.setattr('i',s.i-1);return s
def rshift(s,o):s>o;return s>o
def lshift(s,o):s<o;return s<o
def call(s,*a):
if len(a)<2:return s
if s.en_in:s.a[s.i],s.input[:] = '\0'if len(a)-1>len(s.input)else s.input[len(a)-1],s.input[len(a)-1:]
else:s.a[s.i]=import('sys').stdin.read( +len(a)+ -True)[-True]
return s
#]
if name=='main':
[-]
++++++++++
[
lambda:((>)+++++ <)-_
]>;(++).--;(.--)._
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
420
a python-brainfuck polyglot to print the number 420
but the preprocessor should be able to run more complex brainf programs
they just gotta be written with underscores brackets and lambdas
what on earth
oh god
i have a question
how do u find a sentence repeating in a txt document
not a word, a whole sentence / line
use regular expressions
!e
print("i love you, i don't want to".replace("you", "me"))```
@queen kestrel :white_check_mark: Your eval job has completed with return code 0.
i love me, i don't want to
sad = all('people')
you = all('alone')
if you is sad:
exit('life')
You can use str.count to check if a substring is repeating
Yes, if you need to check for any repeating substring then use regex
itertools.chain(*iterables)```
Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Roughly equivalent to:
```py
def chain(*iterables):
# chain('ABC', 'DEF') --> A B C D E F
for it in iterables:
for element in it:
yield element
wait so how do i imply it here
with open("log.txt", "r") as pr:
read = pr.readlines()
with open("log.txt", "a") as pa:
pa.write(info + "\n")
Wait I think I'm think of something else
yeah
!d collections.Counter
class collections.Counter([iterable-or-mapping])```
A [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter "collections.Counter") is a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict") subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter "collections.Counter") class is similar to bags or multisets in other languages.
Elements are counted from an *iterable* or initialized from another *mapping* (or counter):
```py
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8) # a new counter from keyword args
There
str.splitlines and that
Wait
!e
from collections import Counter
lines = "Hello", "World", "Hello", "There"
print(Counter(lines))
@cloud fossil :white_check_mark: Your eval job has completed with return code 0.
Counter({'Hello': 2, 'World': 1, 'There': 1})
can it split lines from this
[['2', 'bedroom', 'terraced', 'house'], ['Sutton Scotney, Winchester'], ['Β£375,000'], ['15/01/2022']] 1
[['3', 'bedroom', 'semi-detached', 'house'], ['Birch Grove, Boyatt Wood, Eastleigh, Hampshire, SO50'], ['Β£375,000'], ['19/05/2022']] 2
[['3', 'bedroom', 'terraced', 'house'], ['Fraser Road, Kings Worthy, SO23'], ['Β£375,000'], ['28/04/2022']] 3
[['3', 'bedroom', 'terraced', 'house'], ['Kings Worthy'], ['Β£375,000'], ['13/05/2022']] 4
[['3', 'bedroom', 'terraced', 'house'], ['Longfield Road, Winchester'], ['Β£375,000'], ['02/06/2022']] 5
I wonder if it works for lists
What are lines here
i wrote the line number next to it for reference to what i mean
no
but when i rerun the program
it print few of them out again
so when i write in in txt file, i dont want them to be repeated again
cause i need to repeat this twice
1st when im making a txt file for reference
If you already have the lines, you can use a set to get rid of duplicates
and 2nd when i send it to my in whatsapp
Set objects are great for if you only care about having data about something without any particular order
oh so how do i use it
Just to be clear, what kind of repeating lines appear here?
the lists
like this
[['3', 'bedroom', 'terraced', 'house'], ['Fraser Road, Kings Worthy, SO23'], ['Β£375,000'], ['28/04/2022']]
and this
[['3', 'bedroom', 'terraced', 'house'], ['Longfield Road, Winchester'], ['Β£375,000'], ['02/06/2022']]
so something similar
Why are these considered repeating
no but im giving an example
of what the lines look like
but repeating lines are basically the same line twice
without iterations
so bascially read if the same line is in the file
and replace or dont write the string
Something like
with open("that file.txt") as f:
unique_lines = set(f.read().splitelines())
unique_lines is guaranteed to drop duplicates
By
drop duplicates
I mean not include duplicates
As in, duplicate lines aren't appended if they already exist in the set
I mean, I also created HAX, which probably enables some of the worst offenders here. π I honestly sort of like esoteric code thatβs creative (as opposed to just frustrating and complicated for the sake of adding complexity). When done right, it can be a really cool marriage of abstract CS theory and concrete, low-level implementation details.
Is it possible to use Ctypes to change an object? example: 1 which returns 4.
very much so
But in the case of 1, not for long.
That should be really easy.
First of all note that you have lists within lists. So you have to go from one list to the next list and get each word one by one.
def seperatelist(biglist,list_str=''):
for small_list in biglist:
for word in small_list:
list_str += str(word)+' '
list_str.split()
return list_str```
list_str.split() does nothing
also where did he say split words??
!e
def seperatelist(biglist,list_str=''):
for small_list in biglist:
for word in small_list:
list_str += str(word)+' '
list_str.split()
return list_str
abc = [[1,2,3,4,5], [2,3,4,5]]
print(seperatelist(abc))```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1 2 3 4 5 2 3 4 5
It works.
ok but i think he only said split lines
!e ```py
seplist=lambda b:" ".join(f"{w}"for s in b for w in s)
abc = [[1,2,3,4,5], [2,3,4,5]]
print(seplist(abc))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
1 2 3 4 5 2 3 4 5
@sick hound this does the same thing
Lmao. Great but not really readable.
you've come into the wrong channel then
this channel is all about discarding readability for shorter code
and some more stuff
I came because I wanted to see if there are any things new to me. I saw someone who needed help, that is why I wanted to help. Thanks for your evaluation of the situation though.
!e
def seperatelistlines(biglist,list_str=''):
for row in biglist:
list_str += str(row)+'\n'
return list_str
abc = [[1,2,3,4,5], [2,3,4,5]]
print(seperatelistlines(abc))```
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | [1, 2, 3, 4, 5]
002 | [2, 3, 4, 5]
Here you go.
!e ```py
seplistlines=lambda b:"\n".join(map(str,abc))
abc = [[1,2,3,4,5], [2,3,4,5]]
print(seplistlines(abc))
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | [1, 2, 3, 4, 5]
002 | [2, 3, 4, 5]
How does map() work?
applies the given function throughout the entire list
it's like doing py def map(func, iterable): for x in iterable: yield func(x) where yield is the syntax for a generator (it means returning one value at a time)
Thanks.
!e
map = lambda f, it: (f(x) for x in it)
print(*map(repr, map(str, range(10))))
@fleet bridge :white_check_mark: Your eval job has completed with return code 0.
'0' '1' '2' '3' '4' '5' '6' '7' '8' '9'
Whyβd u use a f string
yes
you'd get a "not a string" error or something if you don't do that
!timeit py x = (129419807128912312312, 21382039330301923, 18260669.283173, "hajsdakasofaof''\"", [1, 218412, 2133]) ```py
str(x)
@quartz wave :white_check_mark: Your timeit job has completed with return code 0.
100000 loops, best of 5: 1.95 usec per loop
!timeit py x = (129419807128912312312, 21382039330301923, 18260669.283173, "hajsdakasofaof''\"", [1, 218412, 2133]) ```py
f"{x}"
@quartz wave :white_check_mark: Your timeit job has completed with return code 0.
100000 loops, best of 5: 2.02 usec per loop
@sick hound maybe not
Interesting
what's faster though is repr(x) vs f"{x!r}"
!timeit py x = (129419807128912312312, 21382039330301923, 18260669.283173, "hajsdakasofaof''\"", [1, 218412, 2133]) ```py
repr(x)
@quartz wave :white_check_mark: Your timeit job has completed with return code 0.
100000 loops, best of 5: 2.06 usec per loop
!timeit py x = (129419807128912312312, 21382039330301923, 18260669.283173, "hajsdakasofaof''\"", [1, 218412, 2133]) ```py
f"{x!r}"
@quartz wave :white_check_mark: Your timeit job has completed with return code 0.
100000 loops, best of 5: 2.12 usec per loop
huh π€
xD
>>> main(['-s', """x = (129419807128912312312, 21382039330301923, 18260669.283173, "hajsdakasofaof''\\"", [1, 218412, 2133])""", "repr(x)"])
100000 loops, best of 5: 2.63 usec per loop
>>> main(['-s', """x = (129419807128912312312, 21382039330301923, 18260669.283173, "hajsdakasofaof''\\"", [1, 218412, 2133])""", "f'{x!r}'"])
100000 loops, best of 5: 2.58 usec per loop
!e ```py
from timeit import main
main(['-s', """x = (129419807128912312312, 21382039330301923, 18260669.283173, "hajsdakasofaof''\"", [1, 218412, 2133])""", "repr(x)"])
main(['-s', """x = (129419807128912312312, 21382039330301923, 18260669.283173, "hajsdakasofaof''\"", [1, 218412, 2133])""", "f'{x!r}'"]) #
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 100000 loops, best of 5: 2.08 usec per loop
002 | 100000 loops, best of 5: 1.94 usec per loop
damn
what does timeit do different from the !timeit command π€
!e
cond1 = True
cond2 = True
cond3 = True
cond4 = False
word = "Python"
print(word[cond4: cond1 + cond2 + cond3])
@light thunder :white_check_mark: Your eval job has completed with return code 0.
Pyt
while num:=(locals()["num"] if "num" in locals() else -1) != (ans:=(locals()["ans"] if "ans" in locals() else __import__("random").randint(1, 100))) and (score:=(locals()["score"] if "score" in locals() else 7))>0: print(((f'The number is greater than {num}',f'The number is less than {num}')[num>ans] if ((num:=int(num)) != ans and (score:=score-1) > -1) else f'You win! [{8-score}/{7} attempts]') if ((num:=input(("I'm thinking of a number between 1 and 100...\n\n" if score==7 else "")+f'{8-score}/7 attempts: ').strip()).isnumeric()) else f'{num} isn\'t a valid number :/')
``` for some ungodly reason, i created this
it's a guess-the-number game
I have a version of that ```py
=print("guess a number between 1 and 100"),(w:=[0]),(lambda r,n=[8]:{n.setitem(0,n[0]-1)or print(f"The number is {['greater','less'][>r]} than {_}")for _ in iter(lambda:(lambda g:w.setitem(0,g==r)or[g,r][n[0]<0])(int(input())),r)})(import('random').randint(1,100)),print(f"You {['lose','win'][w[0]]}.")
damn the odds of this happening though
now time to see if i can golf this even more
this isn't so nice with weird user inputs though
the user inputs are easily customised
wait why does this only print once 
q=iter([1])
while True:
[print(i) for i in q]
q.__setstate__(0)
Does it unpack the list?
i mean- it's a list comprehension, so yes?
__setstate__ on iterators works only once before yielding first value
other calls to .__setstate__ does nothing
ahhhhhhh okay
thanks
(P:=print,n:=__import__('random').randint(1,100),P("Guess a number between 1 and 100"),q:=iter([1]),w:=iter([1]),[([(i:=input("Enter a number: ")).isdigit()and 0<(I:=int(i))<101or P("That's not a valid number")or q.__setstate__(0)for(_)in q],q:=iter([1]),P("You win!"*(I==n)or w.__setstate__(0)or f"Your guess is {(I<n)*'smaller'or'bigger'} than the number"))for(_)in w])
a bit longer than this, but it does input validation
dope
what's q:=iter([1]) do ?
it's just my way of making a while loop
it's the same as ```py
q = iter([1])
i basically set its state to 0 to allow it to loop infinitely
if you want an infinite iterator, you can do iter(int, 1)
well yeah, but how do you break out of that then
perhaps using __setstate__?
...or just break
hook int.eq
ah, I see what you are doing
then you can doiter(lambda: l[0], 1) and use setitem on l
or your setstate thing IG
next(_ for _ in iter(int, 1) if ...)
i something i do sometimes, not sure if it works here though
never thought of that, but it's probably shorter in code to use iter and __setstate__
don't think that works because then you'd have to infinitely call that too :P
cursed code
!e ```py
from ctypes import *
class flogbals(dict):
slots=()
def init(self,globs=globals()):
self.update(globs)
def missing(self, name):
import builtins as builtins
self.update(builtins.dict)
return any(x.isdigit() and int(x) > 4 for x in name)
py_object.from_address(id(globals())+tuple.itemsize).value = flogbals
twoοΎ plusοΎ two = 5
if itοΎ isοΎ 4:
print("2 + 2 != 5")
else:
if itοΎ isοΎ 5:
print("what??")
cursed code
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
what??
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
what??
finally
__setstate__ will work until the iterator is exhausted, because when it is exhausted the backing list is decrefed
!e ```py
i = iter([1])
for v in i:
print(v)
i.setstate(0)
@rugged sparrow :x: Your eval job has completed with return code 143 (SIGTERM).
001 | 1
002 | 1
003 | 1
004 | 1
005 | 1
006 | 1
007 | 1
008 | 1
009 | 1
010 | 1
011 | 1
... (truncated - too many lines)
Full output: too long to upload
^ there the iterator is never exhausted before setstate is called
So you can make an in-line while loop with iter and setstate fairly trivially (by conditionally calling setstate)
to elaborate,
... = (expression to run, condition to break)[1]
something like this would be a do while
!e
x = 0
next(_ for _ in iter(int, 1) if (
(x := x+1),
(x >= 10)
)[1])
print(x)
@languid hare :white_check_mark: Your eval job has completed with return code 0.
10
while is a little trickier, but the idea is the same
ah that's neat!
this method doesnt let you do arbitrary breaks inside the expression to run sadly
you'd have to do if/elses within the expression to simulate a break
Wait, what? How does two plus two work??
π€·ββοΈ
it just does
!e ```py
from ctypes import *
class flogbalsοΎ orοΎ whatever(dict):
slots = ()
d = {}
lastοΎ item = [None]
def init(self,globs=globals()):
self.d.update(globs)
def getitem(self, expr):
import builtins as builtins
self.d.update(builtins.dict)
if "α
isα
notα
" in expr:
ref, otherοΎ expr = expr.split("α
isα
notα
")
otherοΎ expr = eval(otherοΎ expr, self, self)
if ref == "it" and "it" not in self.d:
return self.lastοΎ item[-1] != otherοΎ expr
return self.d[ref] != otherοΎ expr
if "α
isα
" in expr:
ref, otherοΎ expr = expr.split("α
isα
")
otherοΎ expr = eval(otherοΎ expr, self.d, self.d)
if ref == "it" and "it" not in self.d:
return self.lastοΎ item[-1] == otherοΎ expr
return self.d[ref] == otherοΎ expr
return self.d.get(expr, expr)
def setitem(self, name, val):
self.d[name] = val
self.lastοΎ item.append(val)
py_object.from_address(id(globals())+tuple.itemsize).value = flogbalsοΎ orοΎ whatever
twoοΎ plusοΎ two = 5
if itοΎ isοΎ 4:
print("2 + 2 != 5")
if itοΎ isοΎ notοΎ 4 and itοΎ isοΎ 5:
print("what??")
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
what??
updated
ok fine it's a halfwidth hangul filler
that's Ll? that's amazing!
it's Lo
Huh, I thought only Ll was allowed in names. Is it any of the L classes?
probably
Time to bind U+FFA0 to a key..
!e not all of the characters are ```py
import unicodedata
for x in map(chr,range(0x110000)):
if 'L' in unicodedata.category(x) and not x.isidentifier():
print(f"{x}:\n category = {unicodedata.category(x)}\n name = {unicodedata.name(x)}")
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | ΝΊ:
002 | category = Lm
003 | name = GREEK YPOGEGRAMMENI
004 | ΰΈ³:
005 | category = Lo
006 | name = THAI CHARACTER SARA AM
007 | ΰΊ³:
008 | category = Lo
009 | name = LAO VOWEL SIGN AM
010 | βΈ―:
011 | category = Lm
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/wigilotodo.txt?noredirect
these are part of the L class but they're not allowed as identifiers
Sadly, U+FFA0 doesn't look like a space in my system font (doesn't take up any space) nor in my terminal (looks like U+FFFD)
what about a hangul filler
yep. that works. Not as nice of course, but I figure this might anyways get flagged in code review :>
Damn nice
!e reminds me of the classic ```py
x = 1
Ρ
= 2
print(x)
@pastel sparrow :white_check_mark: Your eval job has completed with return code 0.
1
!e
a = 1
Π° = 2
assert a == 2, Π°
@fleet bridge :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | AssertionError: 2
!e My new rickroll py print(chr(s:=(lambda:(exec('global s;s=3\nwhile s<78:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<101:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=1\nwhile s<118:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=2\nwhile s<101:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=2\nwhile s<114:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=4\nwhile s<32:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=1\nwhile s<71:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<111:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=3\nwhile s<110:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<110:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<97:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=3\nwhile s<32:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<71:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=2\nwhile s<105:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=2\nwhile s<118:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<101:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=2\nwhile s<32:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<89:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<111:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=3\nwhile s<117:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<32:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=4\nwhile s<85:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=4\nwhile s<112:s+=1'),s)[1])()))
@split salmon :white_check_mark: Your eval job has completed with return code 0.
Never Gonna Give You Up
Esoteric python means it is intended to be understood by a small group of people with a specialized knowledge or interest
Mostly codes that are written in a non-pythonic way
I assume something as common like this has been posted here before already? π
import builtins
from typing import Any
class Hook:
def __init__(self, attr: str, value: Any) -> None:
self.attr = attr
self.value = value
def __eq__(self, other: Any) -> None:
other[self.attr] = self.value
def setattr(obj: Any, attr: str, value: Any) -> None:
if hasattr(builtins, getattr(obj, '__name__', obj.__class__.__name__)):
if not isinstance(obj, type):
obj = obj.__class__
obj.__dict__ == Hook(attr, value)
else:
builtins.setattr(obj, attr, value)
setattr(str, 'test', 1)
>>> print(''.test)
1
yes something like it has been posted but not in that approach
the only thing i found esoteric about it is obj.__dict__ == class_with___eq__
yea true, Im not that good to be writing very esoteric code like some of the ones above
if you could could you link where it has been posted previouly? Im curious
!e it's in a module ```py
from fishhook import hook, unhook
hook(str, "test")(1) # setattr(str, "test", 1)
print("".test)
unhook(str, "test") # delattr(str, "test")
"".test
@quartz wave :x: Your eval job has completed with return code 1.
001 | 1
002 | Traceback (most recent call last):
003 | File "<string>", line 5, in <module>
004 | AttributeError: 'str' object has no attribute 'test'
not built-in though
for letter in ["01101000011101000111010001110000011100110011101000101111001011110111100101101111011101010111010001110101001011100110001001100101001011110110010001010001011101110011010001110111001110010101011101100111010110000110001101010001"[character:8 + character] for character in range(0, len("01101000011101000111010001110000011100110011101000101111001011110111100101101111011101010111010001110101001011100110001001100101001011110110010001010001011101110011010001110111001110010101011101100111010110000110001101010001"),8)]:print(chr(int(letter, 2)), end = "")
@plain estuary module was made by this guy
ahh okay nice I took a look.
I just checked my impl does not work for dunder methods
but thats expected seeing its complexity vs the other modules
π
π€£
what the heck is this place?
pure bliss
how this thing works?
like these codes
Eh?
i was asking how this code works
Have you tried that yet?
no

oh so this thing is called esoteric python
cool
No, that's just rick roll code
only esoteric language i know is brainfk
!e ```py
print(chr(78)+chr(101)+chr(118)+chr(101)+chr(114)+chr(32)+chr(71)+chr(111)+chr(110)+chr(110)+chr(97)+chr(32)+chr(71)+chr(105)+chr(118)+chr(101)+chr(32)+chr(89)+chr(111)+chr(117)+chr(32)+chr(85)+chr(112))
@low sage :white_check_mark: Your eval job has completed with return code 0.
Never Gonna Give You Up
is there a way to make 1 + 1 = 3
by any means necessary
overwriting the numerical value of 2 ?
!e
from fishhook import hook
@hook(int)
def __repr__(self):
if self == 2:
return '3'
return self
print(1 + 1)
@wheat river :white_check_mark: Your eval job has completed with return code 0.
3
!e I got it too lmao (sort of)
from ctypes import c_char; two_buf = (c_char * 2 .__sizeof__()).from_address(id(2)); two_buf[two_buf.raw.index(b"\x02")] = b"\x03"
print(1+1)```
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
3
very nice @wheat river
mine crashes python on my pc
python3 -c 'from ctypes import c_char; two_buf = (c_char * 2 .__sizeof__()).from_address(id(2)); two_buf[two_buf.raw.index(b"\x02")] = b"\x03"; print(1+1)'
3
Traceback (most recent call last):
File "<string>", line 1, in <module>
OSError: raw write() returned invalid length 3 (should have been between 0 and 2)
3
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
OSError: raw write() returned invalid length 3 (should have been between 0 and 2)
3
3
zsh: segmentation fault (core dumped) python3 -c```
π
im largly unfamiliar with ctypes honestly
i think your way was better tbh
silently uses a lib which does ctypes for me
its a good one
this should return orig(self) cuz repr can't be int
trying to remember who wrote it .. i think they're on this discord
ya @chilaxan#3116
ya nice
!e the full list
from importlib.metadata import distributions
print(*sorted((d.metadata["Name"] for d in distributions() if d.metadata["Name"]), key=str.lower))```
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
anyio arrow async-generator attrs beautifulsoup4 fishhook forbiddenfruit fuzzywuzzy idna lark more-itertools mpmath multidict networkx numpy outcome pandas pendulum python-dateutil pytz pytzdata PyYAML six sniffio sortedcontainers soupsieve sympy toml trio tzdata yarl
!e ```py
import sys
from importlib import machinery
class StringLoader:
def create_module(self, spec):
return spec.name
def exec_module(*args): pass
class StringFinder:
def find_spec(self, fullname, *args):
return machinery.ModuleSpec(fullname, StringLoader())
sys.meta_path.append(StringFinder())
import not_found
print(repr(not_found))```
@polar plover :white_check_mark: Your eval job has completed with return code 0.
'not_found'
wait what's BS4 for
BeautifulSoup
that's better than what I had
i dont know, maybe its a transitive dependency?
didn't know about importlib.distributions
what did you use ?
a combination of importlib and pkgutil
!e
import pkgutil
for module in pkgutil.iter_modules():
if module.ispkg and module.module_finder.path.endswith("site-packages"):
print(module.name)β
@plucky plover :white_check_mark: Your eval job has completed with return code 0.
001 | _yaml
002 | anyio
003 | arrow
004 | async_generator
005 | attr
006 | bs4
007 | dateutil
008 | fishhook
009 | forbiddenfruit
010 | fuzzywuzzy
011 | idna
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/jakivozeki.txt?noredirect
actually just pkgutil
just why
about to make sortedcontainers and more-itertools into C extensions because bored
!e
import pkgutil
for module in pkgutil.iter_modules():
exec("from module.name import *")
@carmine sun :white_check_mark: Your eval job has completed with return code 0.
001 | _yaml
002 | anyio
003 | arrow
004 | async_generator
005 | attr
006 | bs4
007 | dateutil
008 | fishhook
009 | forbiddenfruit
010 | fuzzywuzzy
011 | idna
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/tenozitupo.txt?noredirect
!e
import pkgutil
for module in pkgutil.iter_modules():
exec("from module.name import *")β
print(locals())
@carmine sun :x: Your eval job has completed with return code 1.
001 | File "<string>", line 3
002 | exec("from module.name import *")β
003 | ^
004 | SyntaxError: invalid non-printable character U+200A
done the first one (.chunked()) in more-itertools
some many many more to go π
this is the esoteric channel if u didnβt know
smart
might use that
Yeah, man. Slicing string with conditions might come in handy
I learned it from Roie
You turn your string into binary code?
Or did I shared my simple character encryption here before?
this what i did
Oh hahaha
but i need to fix
That's like 87732 characters cut hahaha
lol
my golfed implementation of slowsort (from https://en.wikipedia.org/wiki/Slowsort)
M=max;slow_sort=lambda a:len(a)==1and a or(E:=M(M(slow_sort(a[:(L:=len(a)//2)])),M(slow_sort(a[L:]))),a.remove(E),[*slow_sort(a),E])[2]
found it pretty funny about how inefficient it was
!timeit ```py
from random import shuffle
unsorted = [*range(79)]
shuffle(unsorted)
M=max;slow_sort=lambda a:len(a)==1and a or(E:=M(M(slow_sort(a[:(L:=len(a)//2)])),M(slow_sort(a[L:]))),a.remove(E),[*slow_sort(a),E])[2]
slow_sort(unsorted)
@pastel sparrow :white_check_mark: Your timeit job has completed with return code 0.
1 loop, best of 5: 929 msec per loop
!timeit ```py
from random import shuffle
unsorted = [*range(79)]
shuffle(unsorted)
sorted(unsorted)
@pastel sparrow :white_check_mark: Your timeit job has completed with return code 0.
100000 loops, best of 5: 3.3 usec per loop
LMAO
!e
print(chr(s:=(lambda:(exec('global s;s=3\nwhile s<78:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<101:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=1\nwhile s<118:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=2\nwhile s<101:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=2\nwhile s<114:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=4\nwhile s<32:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=1\nwhile s<71:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<111:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=3\nwhile s<110:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<110:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<97:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=3\nwhile s<32:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<71:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=2\nwhile s<105:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=2\nwhile s<118:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<101:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=2\nwhile s<32:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<89:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<111:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=3\nwhile s<117:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=5\nwhile s<32:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=4\nwhile s<85:s+=1'),s)[1])())+chr(s:=(lambda:(exec('global s;s=4\nwhile s<112:s+=1'),s)[1])()))
@ebon nest :white_check_mark: Your eval job has completed with return code 0.
Never Gonna Give You Up
hey
def f(n):return"".join("1+eval("+"\\"*(2**m-1)+"\""for m in range(n))+"0"+"".join("\\"*(2**m-1)+"\""+")"for m in reversed(range(n)))
!eval
def f(n):return"".join("1+eval("+"\\"*(2**m-1)+"\""for m in range(n))+"0"+"".join("\\"*(2**m-1)+"\""+")"for m in reversed(range(n)))
x = f(8)
print(x)
print(eval(x))
@fading yew :white_check_mark: Your eval job has completed with return code 0.
001 | 1+eval("1+eval(\"1+eval(\\\"1+eval(\\\\\\\"1+eval(\\\\\\\\\\\\\\\"1+eval(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"1+eval(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"1+eval(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"0\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\")\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\")\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\")\\\\\\\\\\\\\\\")\\\\\\\")\\\")\")")
002 | 8
and that interest is never touching grass
or never seeing grass.
home sweet home
monkey see no grass, monkey hear no grass, monkey touch no grass
still works, lmaopy A=7 B=BRAINFUCK[ PRINT[MATCH(A==3)[ TRUE: "Hello", _: "Bye", ]], EXPONENT[27, 2, 2, 7, 3], MOVE_RIGHT[3], ADD[7, 7], ]
('++++++++++[>++++++>++++++++++>++++++++++++<<<-]>++++++.>>+.<+.', '>^^^^^^^^^^^^^^^^^^^^^^^^^^^>^^>^^>^^^^^^^>^^^<<<<<', '>>>', '>+++++++>+++++++<<')```
@floral meteor do you still want to implement oop in brainfuck?
!e
import math
def isEven(n):
return bool((math.e ** (n * math.pi * 1j) + 1). real // 2)
print(isEven(4))
print(isEven(5))β
@trail quest :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | False
what's grass? is it edible?
ah
i want to get a image finder for a project
but idk how to do it
and none of the tutorials in yt is useful
can someone help out?
ping me please
I wrote it better:
f=lambda n,s="\\",q="\"":str(n and f"1+eval({q+f(n-1,s+s,s+q)+q})")
!e
f=lambda n,s="\\",q="\"":str(n and f"1+eval({q+f(n-1,s+s,s+q)+q})")
print(f(5))
@fading yew :white_check_mark: Your eval job has completed with return code 0.
1+eval("1+eval(\"1+eval(\\\"1+eval(\\\\\\\"1+eval(\\\\\\\\\\\\\\\"0\\\\\\\\\\\\\\\")\\\\\\\")\\\")\")")
can I get the thing it looks interesting
flogbals?
hello i am new to python i need some help with this
6.Soit y*a=z avec z=[1.7,1] chercher les solutions de a avec la commande Β« solve Β»
what language is that in?
I can't understand the problem
probably french
for i in range(0, len(("".join(["$" if a == "0" else " " for a in "".join([format(b, "07b") for b in [c - 128 if c == 255 else c - 160 if c > 160 else c for c in [ord(d) for d in "wΓ]Β’Β―s/]>wu!]¦¯v/k>owΓwΒ’wΓΏΓΏΓΏΓΏΓΏx1];Β―wnMΒΊwv.U*ww.Y2Β§xq]:wΓΏΓΏΓΏΓΏΓΏx+P?ΓΏwkWΓΏΓΏv+PΓΏΓΏw-7ΓΏΓΏxnp?ΓΏΓΏΓΏΓΏΓΏΓΏw1]nCzn]n]}n]nC}n]n_}qcq_"]]])]))), 35):print(("".join(["$" if a == "0" else " " for a in "".join([format(b, "07b") for b in [c - 128 if c == 255 else c - 160 if c > 160 else c for c in [ord(d) for d in "wΓ]Β’Β―s/]>wu!]¦¯v/k>owΓwΒ’wΓΏΓΏΓΏΓΏΓΏx1];Β―wnMΒΊwv.U*ww.Y2Β§xq]:wΓΏΓΏΓΏΓΏΓΏx+P?ΓΏwkWΓΏΓΏv+PΓΏΓΏw-7ΓΏΓΏxnp?ΓΏΓΏΓΏΓΏΓΏΓΏw1]nCzn]n]}n]nC}n]n_}qcq_"]]])]))[i: i + 35])
Hi
There's a lot of brainfuck stuff but has someone made a whitespace interpreter?
It's pretty easy to convert a brainfuck into a whitespace interpreter, so it's not that interesting..
yes
Interesting
Y'all be talking obfuscation here lmfao.
In the rest of the server, the aim is to make the code readable and avoid thinking wtf does this code do?
In this channel, the opposite is true
Hello, I'm learning python and I can not understand what stack is declared like this in the function added below
welcome to How Many Ways Can We Violate PEP 8β’
You're in the wrong channel
to the point it doesn't even remotely look like python.
I'm pretty sure I've seen something similar (or even identical) before in this channel, but here's my stab at goto: https://paste.pythondiscord.com/togukimagi
Usage:
import goto
x = 0
print("x =", x)
if x >= 10:
goto +4
pass
x += 1
goto -4
print("done")
there is a goto module which provides this syntax:```py
i = 10
label. start
if i == 0:
goto. end
print(i)
i -= 1
goto. start
label. end
print('ok')
I know that one, but that requires a decorator
http://entrian.com/goto/ - python2 goto
(also I'm doing offset-based jumps rather than labelled ones)
The Python 2 version also uses trace functions (but is 300 lines (lots of comments, to be fair) as opposed to my 32).
but it was the inspiration for trying this myself; clean-room (never worked with trace functions before)
code
!e ```py
def multiplication_table(size):return [list(map(lambda x:x*i,range(1,size+1))) for i in range(1,size+1)]
print(max(max(multiplication_table(14))))```
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
196
@sick hound :white_check_mark: Your eval job has completed with return code 0.
Hallo
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 17
002 | p.right(90)
003 | ^
004 | IndentationError: unindent does not match any outer indentation level
@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 | File "/usr/local/lib/python3.10/turtle.py", line 107, in <module>
004 | import tkinter as TK
005 | File "/usr/local/lib/python3.10/tkinter/__init__.py", line 37, in <module>
006 | import _tkinter # If this fails your Python may not be configured for Tk
007 | ImportError: libtk8.6.so: cannot open shared object file: No such file or directory
in future please keep any code testing that isn't relevant to the topic of this channel over in #bot-commands, thanks
(list(((print("fizzbuzz")if i % 5 == 0 and i % 3 == 0 else ((print('fizz')if i % 3 == 0 else None)),((print('buzz')if i % 5 == 0 else None))),print(i))for i in range(51))[-1])
Easy FizzBuzz program
Suggestions of @rapid sparrow
(list(((print("fizzbuzz")if i%15==0 else((print('fizz')if i%3==0 else None)),((print('buzz')if i%5==0 else None))),print(i))for i in range(51))[-1])
Significantly golfed
give it some space come on
but- but- that's not the code golfing spirit
Hey at least I'm not using semicolons
yeh
list(((print("fizzbuzz")if i%15==0 else((print('fizz')if i%3==0 else None)),((print('buzz')if i%5==0 else None))),print(i))for i in range(51))[-1]```
that's good
I think we call that True 1 liner
!e
(list(((print("fizzbuzz")if i % 5 == 0 and i % 3 == 0 else ((print('fizz')if i % 3 == 0 else None)),((print('buzz')if i % 5 == 0 else None))),print(i))for i in range(51))[-1])```
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | fizzbuzz
002 | buzz
003 | 0
004 | 1
005 | 2
006 | fizz
007 | 3
008 | 4
009 | buzz
010 | 5
011 | fizz
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/rociqerula.txt?noredirect
thats awesome
!e
[*(print((i%3==0)*"fizz"+(i%5==0)*"buzz"or i)for i in range(50))]
@languid hare :white_check_mark: Your eval job has completed with return code 0.
001 | fizzbuzz
002 | 1
003 | 2
004 | fizz
005 | 4
006 | buzz
007 | fizz
008 | 7
009 | 8
010 | fizz
011 | buzz
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/hewodehepo.txt?noredirect
you could just use a for loop directly but hey i wanted to match the style
Well
It's a tuple based
So i can't direct for loop
Or else
Invalid syntax
(for i in range(10): print('hello world'))
!e
for i in range(50):print((i%3<1)*"fizz"+(i%5<1)*"buzz"or i)
@languid hare :white_check_mark: Your eval job has completed with return code 0.
001 | fizzbuzz
002 | 1
003 | 2
004 | fizz
005 | 4
006 | buzz
007 | fizz
008 | 7
009 | 8
010 | fizz
011 | buzz
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/epadegetog.txt?noredirect
i think im happy with this
for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or-~i)
for i in range(100):print('FizzBuzz'[i%~2&4:12&8+i%~4]or i)
[print("Fizz"*(i%3==0)+"Buzz"*(i%5==0)or i)for i in range(1,101)]
for i in range(1,101):print("Fizz"*(i%3==0)+"Buzz"*(i%5==0)or i)
['fizzbuzz'[(0<n%3)*4:8-(0<n%5)*4]or n for n in range(1,l)]
Any way to write this better?
def addtxt(x, mode=0):
with open('data.txt', 'a+') as data_txt:
data_txt.seek(0)
if x in data_txt.read():
return 1
#exec(['data_txt.write(f\'{x}\')', 'data_txt.write(f\'{x} \')', 'data_txt.write(f\'{x}\\n\')'][mode])
data_txt.write([f'{x}',f'{x} ',f'{x}\n'][mode])
return 0```
data_txt.write([f'{x}',f'{x} ',f'{x}\n'][mode])
```is a quick improvement
wouldnt need that exec at all, otherwise there isnt much to make it neater
I see.
How can I be more precise on which position I want to add f'{x} in data.txt?
E.g. Line 2, 15th character.
Currently it would just append it to the last line and last character.
adding would be a pain, as you'd have to rewrite the rest of the file (shifted). overwriting chars is simpler but idk if you want that
Noo haha.
i suppose you'd have to
data_txt.seek(0)
lines = data_txt.readlines()
lines[line_no] = lines[line_no][:char_no]+x+lines[line_no][char_no:]
data_txt.seek(0)
data_txt.writelines(lines)
there is more efficient than this
but would involve some painful logic or using multiple files to avoid reading too much into memory at once
this isn't quite the channel for this discussion though, a help channel would be more appropriate
Than I would just continue asking if there is a shorter way for:
But thanks.
!e
for i in range(1000):
print(i*-+7-8/2*2)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | -3.0
002 | -4.0
003 | -5.0
004 | -6.0
005 | -7.0
006 | -8.0
007 | -9.0
008 | -10.0
009 | -11.0
010 | -12.0
011 | -13.0
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ukarewibil.txt?noredirect
!e
for i in range(1000):
print(i*-1+5+7-8/2*2)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | 4.0
002 | 3.0
003 | 2.0
004 | 1.0
005 | 0.0
006 | -1.0
007 | -2.0
008 | -3.0
009 | -4.0
010 | -5.0
011 | -6.0
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/uluteqixil.txt?noredirect
!e Isn't that just: py for i in range(1000): print(float(-(i-4)))
@split salmon :white_check_mark: Your eval job has completed with return code 0.
001 | 4.0
002 | 3.0
003 | 2.0
004 | 1.0
005 | 0.0
006 | -1.0
007 | -2.0
008 | -3.0
009 | -4.0
010 | -5.0
011 | -6.0
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/xaxokafepa.txt?noredirect
just golf it into -i+4.0
!e ```py
for i in range(4,-996,-1):
print(f"{i}.0")
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
001 | 4.0
002 | 3.0
003 | 2.0
004 | 1.0
005 | 0.0
006 | -1.0
007 | -2.0
008 | -3.0
009 | -4.0
010 | -5.0
011 | -6.0
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/yivugawije.txt?noredirect
i have this concept, but there's a problem with lambdas
A = 3
B = BRAINFUCK[
CLASS()[
SLOT[Callable[[int], int]:
...
],
SLOT[Callable[[str], str]:
...
]
]
]```
no class/slot naming because it will use their position in "memory" as id
also will try to implement type overloading
but then, to use the class/function, it will be required to write assembly-ish style code
like
B = BRAINFUCK[
# we defined a class on pos 47
MOVE_RIGHT[47],
CALL(27) >> 2
# call the slot with type int
# move pointer to right by 2
# save the returned value
]
hola combre
I kinda got distracted from solving a leet code problem and did this
class Solution:
def maxPower(self, s: str) -> int:
from collections import Counter;from typing import Any;res:Any|Counter=Counter(s);new_vmax=str | int | bool;res: new_vmax=max(res,key=res.get);return res;...;[0];
rule no1 for esoteric codes: semi colons belong to python not java
!e
class Solution:
def maxPower(self, s: str) -> int:
from collections import Counter;from typing import Any;res:Any|Counter=Counter(s);new_vmax=str | int | bool;res: new_vmax=max(res,key=res.get);return res;...;[0];
c=Solution()
print(c.maxPower('esdufhdsiufhjksheeeeeeeeeeeee'))
@lyric fern :white_check_mark: Your eval job has completed with return code 0.
e
what is that even supposed to do
return the max occuring letter
in a string
in an esoteric way
class Solution:
def maxPower(self, s: str) -> str:
return max(s,key=lambda c:s.count(c))
why so clean 
Try max(s, key=s.count)
missed that
from statistics import mode as maxPower /s
can anyone help me with a problem
names are overrated anyway
best implementation ive seen ngl
!e
print([x for _ in iter(int,1)if(x:=''.join(__import__("random").choice(__import__("string").printable) for _ in range(len("Hello World"))))!="Hello World"][-1])
@sick hound :warning: Your eval job timed out or ran out of memory.
[No output]
(I dont think that will finish any time soon)
yeah
oh wait memory error, I guess I am storing every string it finds xD
fun fact you can change what happens when you try to import something
How so?
!e ```py
import sys
class ImportLogger:
def find_spec(self, fullname, *args):
print(f"somebody tried to import {fullname}")
return None
sys.meta_path.insert(0, ImportLogger())
import random```
@polar plover :white_check_mark: Your eval job has completed with return code 0.
001 | somebody tried to import random
002 | somebody tried to import warnings
003 | somebody tried to import math
004 | somebody tried to import os
005 | somebody tried to import stat
006 | somebody tried to import _stat
007 | somebody tried to import _collections_abc
008 | somebody tried to import posixpath
009 | somebody tried to import genericpath
010 | somebody tried to import operator
011 | somebody tried to import _operator
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/izadobodat.txt?noredirect
right, imports import other stuff :p
!e ```py
import sys
class ImportLogger:
def find_spec(self, fullname, *args):
print(f"somebody tried to import {fullname}")
return None
sys.meta_path.insert(0, ImportLogger())
import random```
@polar plover :white_check_mark: Your eval job has completed with return code 0.
001 | somebody tried to import random
002 | somebody tried to import warnings
003 | somebody tried to import math
004 | somebody tried to import os
005 | somebody tried to import stat
006 | somebody tried to import _stat
007 | somebody tried to import _collections_abc
008 | somebody tried to import posixpath
009 | somebody tried to import genericpath
010 | somebody tried to import operator
011 | somebody tried to import _operator
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/kitebizova.txt?noredirect
well that is a list of everything that gets imported at some point from just import random π
!e ```py
import sys
from importlib import machinery
class StringLoader:
def create_module(self, spec):
return f"you tried importing {spec.name}, but I couldnt find it so take this string instead!"
def exec_module(*args): pass
class StringFinder:
def find_spec(self, fullname, *args):
return machinery.ModuleSpec(fullname, StringLoader())
sys.meta_path.append(StringFinder())
import not_found
print(not_found)```
@polar plover :white_check_mark: Your eval job has completed with return code 0.
you tried importing not_found, but I couldnt find it so take this string instead!
tl;dr sys.meta_path is what python uses to find modules when you do import, so you can mess with it
so for example you can use this to generate a dependency graph dynamically based on what gets imported by stuff
Whoaaa
wait that photo, is from an old version of the program, I found the fixed version.
https://cdn.discordapp.com/attachments/841669091307814953/922491361524060211/Source.gv.png
I want to code like you, what course did you see?
none
i self-taught myself python with the help of google
So it turns out β I find after months of trying, on and off
That you implement immutable objects in Python with 11 lines of code (excluding whitespace)
from cpython cimport PyTypeObject
cdef class Meta(type):
def __cinit__(prototype, *args, **kwargs):
(<PyTypeObject *> prototype).tp_flags |= 256
@classmethod
def __prepare__(metacls, name, bases):
cdef dict namespace = super().__prepare__(metacls, name, bases)
return {**namespace, '__slots__': ()}
(<PyTypeObject *> Meta).tp_flags |= 256
class Base(object, metaclass=Meta):
attribute = Descriptor()
"Python"
code
!e
from cpython cimport PyTypeObject
cdef class Meta(type):
def __cinit__(prototype, *args, **kwargs):
(<PyTypeObject *> prototype).tp_flags |= 256
@classmethod
def __prepare__(metacls, name, bases):
cdef dict namespace = super().__prepare__(metacls, name, bases)
return {**namespace, '__slots__': ()}
(<PyTypeObject *> Meta).tp_flags |= 256
class Base(object, metaclass=Meta):
attribute = Descriptor()
@royal whale :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | from cpython cimport PyTypeObject
003 | ^^^^^^^
004 | SyntaxError: invalid syntax
Are you referring to the bits that are actually cython, or the fact that immutability is unpythonic
Oh, cimport? That's how you import cython-built extension classes from one module to another
Just the whole idea of cPython with pointers and all of that.
How much of a speed boost are you getting out of that?
Quite a bit actually, if you use the tool correctly
Though the standard attribute lookup machinery is implement in C and very fast, its still a rather involved process. Using the c api (which is what cython does, though in a roundabout sort of way) you just store and then access attributes directly
it was a joke :( my jokes seem to be very bas
There is no course for coding like a mad person; it's something a mad person automatically picks up and sensible people avoid.
how would you go about making the global variable dictionary a default dict, so an undefined variable would be assigned a default value instead?
just hook __missing__
!e ```py
from ctypes import*
def Donct(dict):
def missing(self, kw):
return kw
py_object.from_address(id(globals())+8).value = Donct
builtins.print(Hello, World)
py_object.from_address(id(globals())+8).value = builtins.dict
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | Traceback (most recent call last):
002 | File "<string>", line 6, in <module>
003 | TypeError: sequence index must be integer, not 'str'
that's where hook __missing__ got me
!e ```py
from fishhook import hook
@hook(dict)
def missing(self, x):
return x
print(x)
@quartz wave :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 6, in <module>
003 | NameError: name 'x' is not defined
ok
!e ```py
from ctypes import*
def Dict(dict):
def getitem(self, item):
import builtins
return builtins.dict.get(self, item, builtins.get(item, item))
py_object.from_address(id(globals())+8).value = Dict
builtins.print(Hello, World)
remember to clean up
py_object.from_address(id(globals())+8).value = builtins.dict
@floral meteor :x: Your eval job has completed with return code 139 (SIGSEGV).
001 | Traceback (most recent call last):
002 | File "<string>", line 7, in <module>
003 | TypeError: sequence index must be integer, not 'str'
alright, now that is puzzling
globals().__class__ is more of an evil identical clone of dict
i think...
I am officially puzzled.
i got a clue ```py
SystemError: D:_w\1\s\Objects\dictobject.c:1514: bad argument to internal function
seems like Dict isn't a dictionary?
or what
oh wait you were trying to do def Dict
bro
!e ```py
from ctypes import*
class Dict(dict):
slots=()
def missing(self, kw): return kw
py_object.from_address(id(globals())+8).value = Dict
builtins.print(Hello, World)
@quartz wave :white_check_mark: Your eval job has completed with return code 0.
Hello World
!e
from ctypes import*
class Dict(dict):
__slots__=()
def __missing__(self, kw): return kw
py_object.from_address(id(globals())+8).value = Dict
print(Hello, World)
@wheat river :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 7, in <module>
003 | TypeError: 'str' object is not callable
oh
print became a string. nice
!e
from ctypes import*
class Dict(dict):
__slots__=()
def __missing__(self, kw): return kw
print(globals())
py_object.from_address(id(globals())+8).value = Dict
print(Hello, World)
@plucky plover :x: Your eval job has completed with return code 1.
001 | {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'Union': <class '_ctypes.Union'>, 'Structure': <class '_ctypes.Structure'>, 'Array': <class '_ctypes.Array'>, 'RTLD_LOCAL': 0, 'RTLD_GLOBAL': 256, 'ArgumentError': <class 'ctypes.ArgumentError'>, 'DEFAULT_MODE': 0, 'create_string_buffer': <function create_string_buffer at 0x7f9b571a4d30>, 'c_buffer': <function c_buffer at 0x7f9b571a4ee0>, 'CFUNCTYPE': <function CFUNCTYPE at 0x7f9b57200b80>, 'sizeof': <built-in function sizeof>, 'byref': <built-in function byref>, 'addressof': <built-in function addressof>, 'alignment': <built-in function alignment>, 'resize': <built-in function resize>, 'get_errno': <built-in function get_errno>, 'set_errno': <built-in function set_errno>, 'py_object': <class 'ctypes.py_object'>, 'c_short': <class 'ctypes.c_short'>, 'c_ushort': <class 'cty
... (truncated - too long)
Full output: https://paste.pythondiscord.com/ocecururic.txt?noredirect
!e
from ctypes import*
class Dict(dict):
__slots__=()
def __missing__(self, kw): return getattr(__builtins__, kw, kw)
py_object.from_address(id(globals())+8).value = Dict
print(Hello, World)
@plucky plover :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 7, in <module>
003 | File "<string>", line 4, in __missing__
004 | File "<string>", line 4, in __missing__
005 | File "<string>", line 4, in __missing__
006 | [Previous line repeated 496 more times]
007 | RecursionError: maximum recursion depth exceeded
uh
time to try my luck
!e ```py
from ctypes import*
class Dict(dict):
slots=()
def missing(self, kw): return kw
py_object.from_address(id(globals())+8).value = Dict
print(Hello, World)
aw
@pastel sparrow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 7, in <module>
003 | TypeError: 'str' object is not callable
!e
from ctypes import *
import builtins
obase = py_object.from_address(id(globals()) + 8)
class fglobals(dict):
__slots__ = ()
def __getitem__(self, key, dict=dict, obase=obase, builtins=builtins, getattr=getattr):
try:
obase.value = dict
return self[key]
except:
try:
return getattr(builtins, key)
except:
return key
finally:
obase.value = __class__
obase.value = fglobals
print(hello, world)
@wheat river :white_check_mark: Your eval job has completed with return code 0.
hello world
π β οΈ π
print('π₯');(os:=__import__('os')).delete(os.path("c:/Users/System32")) if (random:=__import__('random').randint(1,6))==random.randint(1,6) else print('π¨')```
Thanks! That's what I wanted. I was hoping to do something like this:
# Use C/C++-style variable declaration but not assignment
x: int
print(x) # Should be None (C would have void instead, right?)
x = 3
print(x) # 3
Makes me wanna create a PyPi package so that all variable names are valid
!e
code
!e
from ctypes import *
import builtins
obase = py_object.from_address(id(globals()) + 8)
class fglobals(dict):
__slots__ = ()
def __getitem__(self, key, dict=dict, obase=obase, builtins=builtins, getattr=getattr):
try:
obase.value = dict
return self[key]
except:
try:
return getattr(builtins, key)
except:
return None
finally:
obase.value = __class__
obase.value = fglobals
a: int
print(a)
a = 10;
print(a)
@wheat river :white_check_mark: Your eval job has completed with return code 0.
001 | None
002 | 10
Yeah. I already got that part, but I don't know all this ctypes sorcery, so I wouldn't have been able to figure that out.
ya ctypes is weird
i understand None of it
thats Cheeki
What does the + 8 do?
Get's the class
What's in the first 8 bytes then?
iirc It should be the ref count? I cannot remember
wow-
Hey @split salmon!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
i have this code```
if username == x[0]:
....
else:
....
and when the usename is correct
it also executes the else
i have also tried `elif username != x[0]:`
!e if "a" == "a":
print(1)
else:
print(2)
@split salmon :white_check_mark: Your eval job has completed with return code 0.
1
what you on about?
!e username = "root"
x = ["root", "secret", "dev", "www-data"]
if username == x[0]:
print("Now the password")
else:
print("Not Allowed")
@split salmon :white_check_mark: Your eval job has completed with return code 0.
Now the password
see?
yes i know. Let me explain to you better
while it prints "Now the password", it also prints "Not Allowed" when the usename does exist in the x
sorry for the ping
Are you saying that when the username is not in x it prints Now the password AND Not Allowed? Just one? Or neither?
this shouldn't belong here, go grab a help channel
what in the world are you doing
actually that's a bad way to do thing
do this instead
>>> a = {"name":"Pete","age":14}
>>> for k, v in a.items():
... print(k, v)
...
name Pete
age 14
this is a lot better imo
welcome to #esoteric-python
oo esoteric python
this is the place where we do things in a bad way
((a:={"name":"Pete","age":14}),(list((print(k,v))for k,v in a.items()))[-1])```
hmmm
({'name': 'Pete', 'age': 14}, None)
i thought list()[-1] will fix this
@rapid sparrow
yo bro
β³
Wat?
nah but like its actually not properly functional
you got a hole in one π
What does that mean
when golfed
you truncated the code as much as possible
not via pythons standards for readability
btw why are you debating this
because this is esoteric python?
it's relatively readable compared to other works of art
indeed
yes, art
print('π₯');(os:=__import__('os')).delete(os.path("c:/Users/System32")) if (random:=__import__('random').randint(1,6))==random.randint(1,6) else print('π¨')``` what is the linux path for the os
why in #esoteric-python
I don't know where is the help channel π¦
Ah sorry
Python
HOHO SEIMICOLONS?
((print('π₯')),((os:=(__import__('os')))).delete(os.path("c:/Users/System32")) if ((random:=(__import__('random'))).randint(1,6))==(random.randint(1,6)) else (print('π¨')))
perfect
((print('π₯')),((os:=(__import__('os')))).delete(os.path("c:/Users/System32"))if((random:=(__import__('random'))).randint(1,6))==(random.randint(1,6))else(print('π¨')))β``` I think this should work
!e ((print('π₯')),((os:=(import('os')))).delete(os.path("c:/Users/System32"))if((random:=(import('random'))).randint(1,6))==(random.randint(1,6))else(print('π¨')))
@split salmon :white_check_mark: Your eval job has completed with return code 0.
001 | π₯
002 | π¨
No spaces required ig
Wait, android has a terminal???
Termux
I don't have it installed
!e can I still swap equals sign and colon? ```py
from ctypes import*
n = 5
@type.call
class annotations(dict):
def setitem(self, key, value):
dict.update(globals(),{key:value})
class globals(dict):
slots=()
def missing(self, key):
return builtins.dict.get(key,key)
def setitem(self, key, value):
dict.update(annotations,{key:value})
py_object.from_address(id(globals())+8).value=globals
n = 2 + 2
print("2 + 2 =", n)
x: 69 = int
print(f"the {annotations['x']} x equals {x}")
py_object.from_address(id(globals())+8).value = dict
@floral meteor :white_check_mark: Your eval job has completed with return code 0.
001 | 2 + 2 = 5
002 | the <class 'int'> x equals 69
oh
hehehehehe
!e
__import__(SystemError.__name__[:3].lower()).__dict__[str.__name__[:2]+dict.__name__[0]+chr.__call__(111)+tuple.__name__[1]+dict.__name__[3]].write("Hello, world!")
@royal coral :white_check_mark: Your eval job has completed with return code 0.
Hello, world!
always wonder how these work
wait __import__ doesnt have to take a string?
@royal coral :warning: Your eval job has completed with return code 0.
[No output]
!e py print(SystemError.__name__[:3].lower())
@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.
sys
Builtin.
π
!e
print(dir(SystemError))
@royal coral :white_check_mark: Your eval job has completed with return code 0.
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'with_traceback']
!e
print(dir(builtins))
@royal coral :white_check_mark: Your eval job has completed with return code 0.
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWar
... (truncated - too long)
Full output: https://paste.pythondiscord.com/sozununije.txt?noredirect