#esoteric-python

1 messages Β· Page 152 of 1

sick hound
#

make a golfed version of that

wheat river
#

!e

numbers = [1, 2, 3]
print([*map(hex, numbers)])
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

['0x1', '0x2', '0x3']
sick hound
#

preferably something cursed

quartz wave
#

!e ```py
print(a:=[*map(hex,[1,2,3])],[*map(eval,a)],sep='\n')

night quarryBOT
#

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

001 | ['0x1', '0x2', '0x3']
002 | [1, 2, 3]
clever rivet
#

My goal was to make an obfuscated hello world with the least amount of alphanumeric characters. Only symbols.

pastel sparrow
#

ooh looks like an interesting challenge

#

that's 16 alphanumeric characters hm

#

lambda or chr print

floral meteor
#

!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

night quarryBOT
#

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

Hello, World
pastel sparrow
#

fair enough

wheat river
#

globglogabgolab 😳

floral meteor
#

I am the globlogabgolab...

pastel sparrow
#

just print(chr(...)+...)

#

or actually, just be cheaty and use exec and chr

floral meteor
#

I could make python stack based

#

I can make a stack in the __getitem__ title line

clever rivet
# pastel sparrow thinking about it, you really only need to use `print` and `chr` no?

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:])
pastel sparrow
#

ah

floral meteor
#

!e hiding variables in functions ```py
def f(n, stack=[]):
stack.append(n)
return stack

*map(f,'Hello World!'),
print(''.join(f("\n")))

night quarryBOT
#

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

Hello World!
wheat river
#

oh i didnt notice the , i was like how r u unpacking into nothingness

floral meteor
#

I'm unpacking into the void

wheat river
#

python has void

floral meteor
#

the void shall consume all...

pastel sparrow
#
void def main():
    ...
#

wait no

floral meteor
#
def main() -> void:{
  ...
}
pastel sparrow
royal whale
#

@floral meteor no, I wanted to read that

#

it looked really cool

floral meteor
#

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;

night quarryBOT
#

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

Hello World!
floral meteor
#

I got it!

royal whale
#

w h a t

#

that is amazing

floral meteor
#

I kinda cheated a little by swapping arguments.

#

and using anything other than integers

carmine sun
carmine sun
#

how about

void = None
pastel sparrow
#

wait shouldn't MUL just multiply the top two stack values

floral meteor
#

depends if an argument is given

pastel sparrow
#

eh

floral meteor
#

aight ill fix it hang on

#

done

pastel sparrow
#

nah that's too many qol opcodes you provide, i need native assembly torture

floral meteor
#

be careful what you wish for...

pastel sparrow
#

ohshit

floral meteor
#

even better: machine language

cloud fossil
floral meteor
#

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

night quarryBOT
#

@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

floral meteor
#

it compiles noops lol

earnest wing
#

probably to make jump offsets easier to compute

#

one optimization done but not another

floral meteor
#

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

night quarryBOT
#

@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

floral meteor
#

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)

night quarryBOT
#

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

I can work with that, I think.

#

although that's 16 bit machine language

pastel sparrow
floral meteor
#

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

night quarryBOT
#

@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,)
pastel sparrow
# clever rivet It’s not only about using the least number of alphanumeric characters (otherwise...

!e ```py
(:=getattr,:=dir,:=(:=(:=()==())+)+,:=()==[],(:=(((((),(())[]),(())[][:]+(())[(+)**()+][(+)**()+]+(())[][:+]+(())[(+)*(+)][-(+):]),(())[-(+)][:()**(+)+()]+(())[][(+)**()]+(())[+][---:])()**(++)-(*(+____)),(())[][+]+(())[()*(+)][+]+(())[____][:]+(())[(+)*(()**(+)-)][:+]+(())[()*(+)][+]+(())[()*(*(+))][:()*(+)]+(())[(+)*(()*(+))][:])(()[()**()][()*(+):(+)*()]+()[][:(+)*()]+()[()**(()*(+))--][()*(+)+:()**()-]+(())[+][()**(+):(+)*()]),(())[*(+)+][:+]+()[*(+)-][:+])((:=(______,(())[(+)*(+)][:+])(),()[**(+)-(*)])((,(())[*][+:+-]+(())[*(+)+][])((,(())[][]+(())[*(+)+][]+(())[][+]),(**(+)+(+),(+)**+(*(+)),**(++)-(*(+)),**(++)-(*(+)),**(++)-(**+),**(+),(+)**++,**(++)-(**+),**(++)-((+)*+),**(++)-(*(+)),*(+),(+)+)))))

night quarryBOT
#

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

Hello World!
pastel sparrow
#

10 alphanumeric chars

#
  • no boring exec print chr eval
true owl
#

hi

royal coral
royal whale
royal coral
#

Oh, right.

clever rivet
pastel sparrow
#

:/

#

drawbacks of using dir rather than chr

clever rivet
#

hum… mine had better portability 😁

pastel sparrow
#

fair enough

#

i mean I could replace dir with chr

vague cairn
burnt pasture
fleet bridge
#

save that annotations in function dictionary

#

in f.__annotations_body__ for example

#

or in f.__annotations__['__code__']

languid hare
#

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

@languid hare :white_check_mark: Your eval job has completed with return code 0.

001 | APPLE: 🟩⬜⬜⬜🟩
002 | PLANT: ⬜⬜🟩⬜⬜
003 | WAKER: 🟨🟨🟨🟨⬜
004 | AWAKE: 🟩🟩🟩🟩🟩
005 | πŸŽ‰ Congrats! πŸŽ‰
languid hare
#

wordle, but cursed

vague cairn
#

That's very cursed.

vague cairn
floral meteor
#

I kinda expected it to be locals()['__annotations__']

pastel sparrow
versed laurel
#

!e

night quarryBOT
#
Missing required argument

code

#
Command Help

!eval <code>
Can also use: e

*Run Python code and get the results.

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

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

floral meteor
#

Otherwise they're just comments

#

!e ```py
"""
Docstring
"""

normal comments

"Some random string that compiles to nop"
def f():
annotation: "does nothing"

night quarryBOT
#

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

[No output]
floral meteor
#

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

restive void
#

!e just realized you can put smileys in your code

from __future__ import annotations

sad :C
playful :P
meh :I
night quarryBOT
#

@restive void :warning: Your eval job has completed with return code 0.

[No output]
wheat river
pastel sparrow
#

don't forget ```py
happy :D

wheat river
#

im sad annotations to str is not inbuilt in 3.11 sad :C

pastel sparrow
#
surprised :o
restive void
#

other candidates: :S, :x, :E (Cthulu),:v (Pacman)

night quarryBOT
#

@tribal crown :white_check_mark: Your eval job has completed with return code 0.

Hello, World!
quartz wave
#
from __future__ import annotations

sad     :C
meh     :I
playful :P
woozy   :S
cthulu  :E
silent  :x
happy   :D
pacman  :v
pastel sparrow
#

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

pastel sparrow
#

since every class has to inherit from object

split salmon
#

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]

wheat river
#

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
split salmon
wheat river
#

ah k

split salmon
#

i cant seem to find anyway to do so

wheat river
#

ya i think, hold on

split salmon
wheat river
#

im in game rn xD

split salmon
#

k

split salmon
languid hare
#

oh, you're talking about rsa

split salmon
#

not that complex, but hard math*

languid hare
#

there are other places that use modulo powers, heh

split salmon
split salmon
languid hare
#

even still, weird to call it cryptographic

split salmon
#

@languid hare give me an 64 bit RSA number

languid hare
#

9822358919111718011

wheat river
#
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?

split salmon
#

2327196259 & 4220683529

#

@languid hare sorry wasn't paying attention

wheat river
#

what about

SM=lambda b,e:(a:=b,_:=[a:=a**2*((x=='0')or b)for x in bin(e)[3:]],a)[2]
split salmon
split salmon
wheat river
#

ns

split salmon
#
all([SM(tmp:=random.randint(1,99999),tmp2:=random.randint(1,99999))==tmp**tmp2 for _ in range(9999)])```
#

it takes too long

wheat river
#

f

#
SM=lambda b,e:(a:=b,[a:=a**2*((x=='0')or b)for x in bin(e)[3:]])[1][-1]
split salmon
split salmon
# wheat river ```py SM=lambda b,e:(a:=b,[a:=a**2*((x=='0')or b)for x in bin(e)[3:]])[1][-1] ``...

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

wheat river
#

ya im still in game hold on xD

split salmon
#

k

#

no need for optimizations

wheat river
#

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

@wheat river :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | False
wheat river
#

:<

sick hound
#

do u know an alternative to id()

#

where it would show a different id even if the string value is the same

wheat river
#

uh not sure, python caches stuff like that

split salmon
#

funfact

pastel sparrow
light thunder
pastel sparrow
#

python bytecode

#

use dis.dis

quartz wave
pastel sparrow
#

a lot*

light thunder
#

Eh? dis.dis?

pastel sparrow
#

!e ```py
from dis import dis

print(dis("print('Hello World!')"))

night quarryBOT
#

@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
light thunder
#

Oh

#

Nice nice

#

I gonna try

pastel sparrow
#

aight

light thunder
#

How and why we use it?

split salmon
split salmon
pastel sparrow
#

realistically: never

unless you're bored or doing some esoteric stuff then yeah

split salmon
quartz wave
#

or trying to make optimized python code

split salmon
#

any func is immediately translated to bytecode, which is optimized, its not fully compiled, but not fully the source

pastel sparrow
#

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

night quarryBOT
#

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

bytecode is optimized, but it is not "perfectly" optimized

#

!e

import dis
dis.dis("(1 << 8) - 1")
night quarryBOT
#

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

also, optimizing dict() to {} is not necessarily always correct

astral rover
#

Isn't there a module for optimising byte code by hand?

earnest wing
#

it depends on a name lookup

#

which cannot be predicted at compile time

astral rover
earnest wing
#

Wonderful, haha

#

Now we just need a DSL with opcode shorthands

pastel sparrow
earnest wing
#

or something of the sort BABAXD

rapid sparrow
quartz wave
golden finch
#

Are any zero-width characters valid in identifiers in Python?

quartz wave
#

idk

#

i currently have no time to read PEP 3131

#

!pep 3131

night quarryBOT
#
**PEP 3131 - Supporting Non-ASCII Identifiers**
Status

Final

Python-Version

3.0

Created

01-May-2007

Type

Standards Track

old socket
#

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

floral meteor
quartz wave
floral meteor
quartz wave
#

i managed to fix chilaxan's builtinexc that broke because of changes to the code object structure in 3.11

trim summit
floral meteor
#

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

quartz wave
#

!e ```py
_ = 5
match 7:
case :
print(
)

night quarryBOT
#

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

5
quartz wave
#

@floral meteor nothing changes?

#

case _ is just a special case

floral meteor
#

!e ```py
_ = 5
match 5:
case 7: print('')
case : print()

night quarryBOT
#

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

5
floral meteor
#

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)

night quarryBOT
#

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

0
floral meteor
#

why can't the spy see anything?

pastel sparrow
#

case spy doesn't make sense though

floral meteor
#

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)

night quarryBOT
#

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

0
floral meteor
#

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)

night quarryBOT
#

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

1
pastel sparrow
#

hm

floral meteor
#

so how does it determine if a pattern matches?

pastel sparrow
#

it's probably some under the hood magic ig

floral meteor
#

there must be a new dunder

pastel sparrow
#

i found a pep proposing for the new dunder

floral meteor
#

!e ```py
spy = type('Spy',(),{this:print for this in dir(object)if this!='class'})()
match spy:
case 0:print(0)
case _:print(1)

night quarryBOT
#

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

001 | <class '__main__.Spy'>
002 | 1
floral meteor
#

I think I know how to see which comparison it's making

trim summit
#

_ matches anything, no questions asked.

floral meteor
#

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

night quarryBOT
#

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

001 | <class '__main__.Spy'> __new__
002 | 1
floral meteor
#

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?

pastel sparrow
#

aren't you creating an instance of spy by yourself

floral meteor
#

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)

night quarryBOT
#

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

!e

night quarryBOT
#
Missing required argument

code

#
Command Help

!eval <code>
Can also use: e

*Run Python code and get the results.

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

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

floral meteor
#

!e this is where it reaches the realm of pointless ```py
a = b = 5
match a:
case b if a==b:print(':)')

night quarryBOT
#

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

:)
floral meteor
#

!e I still much prefer the old ways ```py
a = b = 5
{a:lambda:print(1)}.get(b,lambda:print(0))()

night quarryBOT
#

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

1
floral meteor
#

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

night quarryBOT
#

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

Hello World!
floral meteor
#

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

night quarryBOT
#

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

Hello World!
floral meteor
#

or the more classic```py
if n==0:return f()
else:return f

floral meteor
earnest wing
#

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

night quarryBOT
#
**PEP 634 - Structural Pattern Matching: Specification**
Status

Accepted

Python-Version

3.10

Created

12-Sep-2020

Type

Standards Track

earnest wing
#

!e

match globals():
  case {**copy}: copy["e"] = 42
print(e) #?
sick hound
#

is while 1:1 the shortest python program that runs forever discre3Hmm

earnest wing
sick hound
#

that's weird, the bot normally says it times out I thought pithink

earnest wing
#

maybe it's an undiscovered bug haha

#

!e

match globals():
  case {**copy}: copy["e"] = 42
print(e) #?
night quarryBOT
#

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

nope

fleet bridge
#
2**2**30
unreal echo
#

note: try

#

!e
print(len('while 1:1'))

night quarryBOT
#

@unreal echo :white_check_mark: Your eval job has completed with return code 0.

9
unreal echo
#

!timeit
9**999999

night quarryBOT
#

@unreal echo :white_check_mark: Your timeit job has completed with return code 0.

1 loop, best of 5: 283 msec per loop
unreal echo
#

!timeit
99**99999

night quarryBOT
#

@unreal echo :white_check_mark: Your timeit job has completed with return code 0.

10 loops, best of 5: 22.5 msec per loop
unreal echo
#

.wa msec

wheat river
floral meteor
#

!e ```py
var1 = 0,
var2 = 1
def process(x):
match x:
case y,:return y
case y:return y
print(*map(process,(var1, var2)))

night quarryBOT
#

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

0 1
ionic gate
#

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)```
floral meteor
ionic gate
#

twice

#

but no one actually responded

floral meteor
#

oh, okay....

#

umm....

#

use the @ symbol

ionic gate
#

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

floral meteor
#

!e ```py
def a(f):
return lambda*a:f(*a)+9
@a
def timesten(n):
return int(str(n)+'0')
print(timesten(6))

night quarryBOT
#

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

69
floral meteor
#

does the "at" symbol not work on a coroutine?

wheat river
#

it does

floral meteor
#

anything useful I can think of with match case I can also think of a better way

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

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

earnest wing
#

of course the simple examples are easy to replace πŸ˜„

floral meteor
#

part of me wants to say "fite me", part of me wants to quit while im still ahead.

earnest wing
#

uh

#

what

floral meteor
#

XD

earnest wing
#

why are you fighting

floral meteor
#

it's not really a fight

#

it's more a... casual debate

earnest wing
#

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

floral meteor
#

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

night quarryBOT
#

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

well that's the only one I could think of that would be useful

earnest wing
#

ADTs

#

the biggest thing

#

be blessed by haskell

floral meteor
#

!e ```py
d = {2:'o'}
match f:
case{a:b}:print('f'+a*b)

night quarryBOT
#

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

oh cmon

earnest wing
#

keys can only be literals or existing values

floral meteor
#

!e ```py
a = 2
d = {2:'o'}
match f:
case{a:b}:print('f'+a*b)

night quarryBOT
#

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

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

floral meteor
#

!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] %= 2
s.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:((
>
)+++++ <)-_
]>;(++).--;(.--)._

night quarryBOT
#

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

420
floral meteor
#

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

pastel sparrow
#

what on earth

true owl
#

i have a question
how do u find a sentence repeating in a txt document
not a word, a whole sentence / line

royal whale
#

use regular expressions

queen kestrel
#

!e

print("i love you, i don't want to".replace("you", "me"))```
night quarryBOT
#

@queen kestrel :white_check_mark: Your eval job has completed with return code 0.

i love me, i don't want to
shell brook
#
sad = all('people')
you = all('alone')
if you is sad:
    exit('life')
cloud fossil
true owl
#

Oh thanks lemme try it

#

but it needs an argument in it

cloud fossil
#

Yes, if you need to check for any repeating substring then use regex

true owl
#

im trying to find a whole line

#

if its repeated or not

cloud fossil
#

You can use str.splitlines and itertools.chain

#

!d itertools.chain

night quarryBOT
#

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
true owl
#

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")
cloud fossil
cloud fossil
#

!d collections.Counter

night quarryBOT
#

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
cloud fossil
#

There

#

str.splitlines and that

#

Wait

#

!e

from collections import Counter

lines = "Hello", "World", "Hello", "There"
print(Counter(lines))
night quarryBOT
#

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

Counter({'Hello': 2, 'World': 1, 'There': 1})
true owl
#

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

cloud fossil
true owl
#

like the list

#

but i made it in str format so i can write it in txt

true owl
cloud fossil
#

Is any of them repeating

#

I can't see

true owl
#

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

cloud fossil
#

If you already have the lines, you can use a set to get rid of duplicates

true owl
#

and 2nd when i send it to my in whatsapp

cloud fossil
#

Set objects are great for if you only care about having data about something without any particular order

cloud fossil
true owl
#

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

cloud fossil
#

Why are these considered repeating

true owl
#

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

cloud fossil
#

Something like

with open("that file.txt") as f:
    unique_lines = set(f.read().splitelines())

unique_lines is guaranteed to drop duplicates

true owl
#

its for str

#

wait nvm ill solve it np thanks a lo

cloud fossil
#

As in, duplicate lines aren't appended if they already exist in the set

trim summit
royal coral
#

Is it possible to use Ctypes to change an object? example: 1 which returns 4.

pure dew
#

very much so

restive void
#

But in the case of 1, not for long.

languid hare
#

^

#

1 is used plently

#

you'd break python before it finished running the line

sick hound
#

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```
quartz wave
quartz wave
sick hound
#

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

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

1 2 3 4 5 2 3 4 5 
sick hound
#

It works.

quartz wave
#

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

night quarryBOT
#

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

1 2 3 4 5 2 3 4 5
quartz wave
#

@sick hound this does the same thing

sick hound
#

Lmao. Great but not really readable.

quartz wave
#

this channel is all about discarding readability for shorter code

#

and some more stuff

sick hound
#

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

@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]
sick hound
#

Here you go.

quartz wave
#

!e ```py
seplistlines=lambda b:"\n".join(map(str,abc))
abc = [[1,2,3,4,5], [2,3,4,5]]
print(seplistlines(abc))

night quarryBOT
#

@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]
sick hound
#

How does map() work?

quartz wave
#

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)

sick hound
#

Thanks.

fleet bridge
#

!e

map = lambda f, it: (f(x) for x in it)
print(*map(repr, map(str, range(10))))
night quarryBOT
#

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

'0' '1' '2' '3' '4' '5' '6' '7' '8' '9'
quartz wave
#

it's more performant

sick hound
#

Wait really

#

Was it even needed tho

quartz wave
#

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)

night quarryBOT
#

@quartz wave :white_check_mark: Your timeit job has completed with return code 0.

100000 loops, best of 5: 1.95 usec per loop
quartz wave
#

!timeit py x = (129419807128912312312, 21382039330301923, 18260669.283173, "hajsdakasofaof''\"", [1, 218412, 2133]) ```py
f"{x}"

night quarryBOT
#

@quartz wave :white_check_mark: Your timeit job has completed with return code 0.

100000 loops, best of 5: 2.02 usec per loop
quartz wave
#

@sick hound maybe not

sick hound
#

Interesting

quartz wave
#

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)

night quarryBOT
#

@quartz wave :white_check_mark: Your timeit job has completed with return code 0.

100000 loops, best of 5: 2.06 usec per loop
quartz wave
#

!timeit py x = (129419807128912312312, 21382039330301923, 18260669.283173, "hajsdakasofaof''\"", [1, 218412, 2133]) ```py
f"{x!r}"

night quarryBOT
#

@quartz wave :white_check_mark: Your timeit job has completed with return code 0.

100000 loops, best of 5: 2.12 usec per loop
quartz wave
#

huh πŸ€”

sick hound
#

xD

quartz wave
#
>>> 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}'"]) #

night quarryBOT
#

@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
sick hound
#

damn

quartz wave
#

what does timeit do different from the !timeit command πŸ€”

light thunder
#

!e

cond1 = True
cond2 = True
cond3 = True
cond4 = False
word = "Python"

print(word[cond4: cond1 + cond2 + cond3])
night quarryBOT
#

@light thunder :white_check_mark: Your eval job has completed with return code 0.

Pyt
stable jungle
#
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

floral meteor
#

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

pastel sparrow
#

damn the odds of this happening though

#

now time to see if i can golf this even more

pastel sparrow
floral meteor
#

the user inputs are easily customised

pastel sparrow
#

wait why does this only print once pithink

q=iter([1])
while True:
    [print(i) for i in q]
    q.__setstate__(0)
royal whale
#

Does it unpack the list?

pastel sparrow
#

i mean- it's a list comprehension, so yes?

fleet bridge
pastel sparrow
# floral meteor I have a version of that ```py _=print("guess a number between 1 and 100"),(w:=[...
(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

rapid sparrow
pastel sparrow
#

it's just my way of making a while loop

pastel sparrow
proper vault
#

if you want an infinite iterator, you can do iter(int, 1)

pastel sparrow
plucky plover
#

...or just break

earnest wing
#

hook int.eq

proper vault
#

then you can doiter(lambda: l[0], 1) and use setitem on l

#

or your setstate thing IG

languid hare
#

next(_ for _ in iter(int, 1) if ...)
i something i do sometimes, not sure if it works here though

pastel sparrow
pastel sparrow
quartz wave
#

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

night quarryBOT
#

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

what??
night quarryBOT
#

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

what??
quartz wave
#

finally

rugged sparrow
#

!e ```py
i = iter([1])
for v in i:
print(v)
i.setstate(0)

night quarryBOT
#

@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

rugged sparrow
#

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

languid hare
#

!e

x = 0

next(_ for _ in iter(int, 1) if (
    (x := x+1), 
    (x >= 10)
)[1])

print(x)
night quarryBOT
#

@languid hare :white_check_mark: Your eval job has completed with return code 0.

10
languid hare
#

while is a little trickier, but the idea is the same

pastel sparrow
#

ah that's neat!

languid hare
#

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

restive void
#

Wait, what? How does two plus two work??

quartz wave
#

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

night quarryBOT
#

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

what??
quartz wave
#

updated

quartz wave
restive void
quartz wave
restive void
#

Huh, I thought only Ll was allowed in names. Is it any of the L classes?

quartz wave
#

probably

restive void
#

Time to bind U+FFA0 to a key..

quartz wave
night quarryBOT
#

@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

quartz wave
#

these are part of the L class but they're not allowed as identifiers

restive void
#

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)

quartz wave
#

what about a hangul filler

restive void
pastel sparrow
#

!e reminds me of the classic ```py
x = 1
Ρ… = 2
print(x)

night quarryBOT
#

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

1
fleet bridge
#

!e

a = 1
Π° = 2
assert a == 2, Π°
night quarryBOT
#

@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
split salmon
#

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

night quarryBOT
#

@split salmon :white_check_mark: Your eval job has completed with return code 0.

Never Gonna Give You Up
wild remnant
#

what is esoteric python?

#

it's just unnecessarily complicated ways to do stuff?

light thunder
wild remnant
#

oh

#

seems interesting

light thunder
#

Mostly codes that are written in a non-pythonic way

plain estuary
#

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
quartz wave
plain estuary
#

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

quartz wave
night quarryBOT
#

@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'
quartz wave
#

not built-in though

light thunder
# split salmon !e My new rickroll ```py print(chr(s:=(lambda:(exec('global s;s=3\nwhile s<78:s+...
for letter in ["01101000011101000111010001110000011100110011101000101111001011110111100101101111011101010111010001110101001011100110001001100101001011110110010001010001011101110011010001110111001110010101011101100111010110000110001101010001"[character:8 + character] for character in range(0, len("01101000011101000111010001110000011100110011101000101111001011110111100101101111011101010111010001110101001011100110001001100101001011110110010001010001011101110011010001110111001110010101011101100111010110000110001101010001"),8)]:print(chr(int(letter, 2)), end = "")
quartz wave
split salmon
plain estuary
#

I just checked my impl does not work for dunder methods

#

but thats expected seeing its complexity vs the other modules

#

πŸ˜…

light thunder
low sage
#

what the heck is this place?

languid hare
#

pure bliss

low sage
#

how this thing works?

light thunder
low sage
#

i was asking how this code works

light thunder
#

Have you tried that yet?

low sage
#

no

light thunder
#

Try it

#

It contains a link to learn esoteric python

low sage
#

its a youtube video

#

which seens like a rick roll to me

#

πŸ˜‰

light thunder
low sage
#

cool

light thunder
low sage
#

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

night quarryBOT
#

@low sage :white_check_mark: Your eval job has completed with return code 0.

Never Gonna Give You Up
rapid sparrow
#

is there a way to make 1 + 1 = 3

#

by any means necessary

#

overwriting the numerical value of 2 ?

wheat river
#

!e

from fishhook import hook

@hook(int)
def __repr__(self):
    if self == 2:
        return '3'
    return self
    
print(1 + 1)
night quarryBOT
#

@wheat river :white_check_mark: Your eval job has completed with return code 0.

3
rapid sparrow
night quarryBOT
#

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

3
rapid sparrow
#

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```
wheat river
#

πŸ‘€

wheat river
rapid sparrow
#

i think your way was better tbh

wheat river
#

silently uses a lib which does ctypes for me

rapid sparrow
#

its a good one

wheat river
rapid sparrow
#

trying to remember who wrote it .. i think they're on this discord

rapid sparrow
#

nice

#

one of the honored few libs in snekbox lol

wheat river
#

ya nice

rapid sparrow
#

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

@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
polar plover
#

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

night quarryBOT
#

@polar plover :white_check_mark: Your eval job has completed with return code 0.

'not_found'
plucky plover
rapid sparrow
plucky plover
#

didn't know about importlib.distributions

rapid sparrow
plucky plover
#

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)β€Š
night quarryBOT
#

@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

plucky plover
#

actually just pkgutil

quartz wave
carmine sun
#

!e

import pkgutil
for module in pkgutil.iter_modules():
    exec("from module.name import *")
night quarryBOT
#

@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

carmine sun
#

!e

import pkgutil
for module in pkgutil.iter_modules():
    exec("from module.name import *")β€Š

print(locals())
night quarryBOT
#

@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
quartz wave
sick hound
light thunder
#

I learned it from Roie

sick hound
#

@light thunder i made a string encryptor using what u did and its 90k chars lol

light thunder
sick hound
light thunder
#

Or did I shared my simple character encryption here before?

sick hound
#

this what i did

light thunder
#

Oh hahaha

sick hound
#

but i need to fix

light thunder
#

That's like 87732 characters cut hahaha

sick hound
#

lol

pastel sparrow
#

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)

night quarryBOT
#

@pastel sparrow :white_check_mark: Your timeit job has completed with return code 0.

1 loop, best of 5: 929 msec per loop
pastel sparrow
#

!timeit ```py
from random import shuffle
unsorted = [*range(79)]
shuffle(unsorted)

sorted(unsorted)

night quarryBOT
#

@pastel sparrow :white_check_mark: Your timeit job has completed with return code 0.

100000 loops, best of 5: 3.3 usec per loop
pastel sparrow
#

LMAO

ebon nest
#

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

@ebon nest :white_check_mark: Your eval job has completed with return code 0.

Never Gonna Give You Up
fading yew
#
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))
night quarryBOT
#

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

or never seeing grass.

sly root
#

home sweet home

floral meteor
#

monkey see no grass, monkey hear no grass, monkey touch no grass

sly root
#

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?

trail quest
#

!e

import math
def isEven(n):
    return bool((math.e ** (n * math.pi * 1j) + 1). real // 2)

print(isEven(4))
print(isEven(5))β€Š
night quarryBOT
#

@trail quest :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 | False
pastel sparrow
sly root
#

ah

true owl
#

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

fading yew
#

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

@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\\\\\\\\\\\\\\\")\\\\\\\")\\\")\")")
lofty trench
languid hare
#

flogbals?

lament kraken
#

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 Β»

royal whale
quartz wave
light thunder
#
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])
split salmon
sick hound
#

There's a lot of brainfuck stuff but has someone made a whitespace interpreter?

restive void
sick hound
#

Interesting

pallid thunder
#

Y'all be talking obfuscation here lmfao.

floral meteor
open kite
#

Hello, I'm learning python and I can not understand what stack is declared like this in the function added below

pastel sparrow
covert rivet
restive void
#

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")
fleet bridge
#

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

restive void
#

I know that one, but that requires a decorator

fleet bridge
restive void
#

(also I'm doing offset-based jumps rather than labelled ones)

fleet bridge
restive void
#

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)

night quarryBOT
#
Missing required argument

code

upbeat sonnet
#

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

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

196
night quarryBOT
#

@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
dark wharf
#

in future please keep any code testing that isn't relevant to the topic of this channel over in #bot-commands, thanks

bronze merlin
#
(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

royal whale
bronze merlin
#

give it some space come on

royal whale
#

but- but- that's not the code golfing spirit

bronze merlin
#

Hey at least I'm not using semicolons

royal whale
#

yeh

sick hound
royal whale
#

that's good

bronze merlin
#

I think we call that True 1 liner

rapid sparrow
#

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

@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

rapid sparrow
#

thats awesome

bronze merlin
#

Oh

#

I needa fix

languid hare
#

!e

[*(print((i%3==0)*"fizz"+(i%5==0)*"buzz"or i)for i in range(50))]
night quarryBOT
#

@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

languid hare
#

you could just use a for loop directly but hey i wanted to match the style

bronze merlin
#

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

languid hare
#

!e

for i in range(50):print((i%3<1)*"fizz"+(i%5<1)*"buzz"or i)
night quarryBOT
#

@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

languid hare
#

i think im happy with this

bronze merlin
#

Aw man

#

It's a 1 expression 1 line and no semicolons

#

Project

wheat river
#
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)]
sick hound
#

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```
dark wharf
sick hound
#

Oh true thanks!

#

Anything else?

dark wharf
#

wouldnt need that exec at all, otherwise there isnt much to make it neater

sick hound
#

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.

dark wharf
#

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

sick hound
#

Noo haha.

dark wharf
#

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

sick hound
#

But thanks.

sick hound
#

!e

for i in range(1000):
 print(i*-+7-8/2*2)
night quarryBOT
#

@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

sick hound
#

!e

for i in range(1000):
 print(i*-1+5+7-8/2*2)
night quarryBOT
#

@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

split salmon
night quarryBOT
#

@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

pastel sparrow
#

just golf it into -i+4.0

quartz wave
#

!e ```py
for i in range(4,-996,-1):
print(f"{i}.0")

night quarryBOT
#

@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

sly root
# floral meteor Yes

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 
]
bronze merlin
#

hola combre

lyric fern
#

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];
bronze merlin
#

aw man

#

semi colons

lyric fern
#

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

@lyric fern :white_check_mark: Your eval job has completed with return code 0.

e
pastel sparrow
#

what is that even supposed to do

lyric fern
#

in a string

#

in an esoteric way

pastel sparrow
#
class Solution:
    def maxPower(self, s: str) -> str:
        return max(s,key=lambda c:s.count(c))
lyric fern
#

why so clean hyperlemon

proper vault
pastel sparrow
maiden blaze
#

from statistics import mode as maxPower /s

hoary nest
#

can anyone help me with a problem

floral meteor
#

names are overrated anyway

pastel sparrow
sick hound
#

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

@sick hound :warning: Your eval job timed out or ran out of memory.

[No output]
polar plover
#

(I dont think that will finish any time soon)

sick hound
#

yeah

polar plover
#

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

sick hound
#

How so?

polar plover
#

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

night quarryBOT
#

@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

polar plover
#

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

night quarryBOT
#

@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

polar plover
#

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

night quarryBOT
#

@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!
polar plover
#

tl;dr sys.meta_path is what python uses to find modules when you do import, so you can mess with it

polar plover
sick hound
#

Whoaaa

polar plover
mighty ravine
#

I want to code like you, what course did you see?

quartz wave
#

i self-taught myself python with the help of google

maiden vine
#

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

code

royal whale
#

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

@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
carmine dome
#

good god what is that

#

how is this even python at this point

maiden vine
#

Are you referring to the bits that are actually cython, or the fact that immutability is unpythonic

maiden vine
carmine dome
#

How much of a speed boost are you getting out of that?

maiden vine
#

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

mighty ravine
floral meteor
royal whale
#

how would you go about making the global variable dictionary a default dict, so an undefined variable would be assigned a default value instead?

floral meteor
#

!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

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 6, in <module>
003 | TypeError: sequence index must be integer, not 'str'
floral meteor
quartz wave
#

!e ```py
from fishhook import hook
@hook(dict)
def missing(self, x):
return x

print(x)

night quarryBOT
#

@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
quartz wave
#

ok

floral meteor
#

!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

night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 7, in <module>
003 | TypeError: sequence index must be integer, not 'str'
floral meteor
#

alright, now that is puzzling

floral meteor
#

i think...

floral meteor
quartz wave
#

seems like Dict isn't a dictionary?

#

or what

quartz wave
#

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)

night quarryBOT
#

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

Hello World
wheat river
#

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

@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
wheat river
#

oh

plucky plover
#

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

@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

plucky plover
#

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

@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
plucky plover
#

uh

pastel sparrow
#

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

night quarryBOT
#

@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
wheat river
#

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

@wheat river :white_check_mark: Your eval job has completed with return code 0.

hello world
upbeat sonnet
#

πŸ’€ ☠️ πŸ’€

#
print('πŸ’₯');(os:=__import__('os')).delete(os.path("c:/Users/System32")) if (random:=__import__('random').randint(1,6))==random.randint(1,6) else print('πŸ’¨')```
pastel sparrow
#

LMAOO

#

should include linux distros in this roulette too

royal whale
#

Makes me wanna create a PyPi package so that all variable names are valid

wheat river
#

!e

night quarryBOT
#
Missing required argument

code

wheat river
#

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

@wheat river :white_check_mark: Your eval job has completed with return code 0.

001 | None
002 | 10
royal whale
wheat river
#

ya ctypes is weird

royal whale
#

i understand None of it

wheat river
#

thats Cheeki

old socket
serene stratus
#

What's in the first 8 bytes then?

old socket
#

iirc It should be the ref count? I cannot remember

split salmon
#

wow-

night quarryBOT
#

Hey @split salmon!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

torn lion
#

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]:`
split salmon
#

!e if "a" == "a":
print(1)
else:
print(2)

night quarryBOT
#

@split salmon :white_check_mark: Your eval job has completed with return code 0.

1
split salmon
#

!e username = "root"
x = ["root", "secret", "dev", "www-data"]
if username == x[0]:
print("Now the password")
else:
print("Not Allowed")

night quarryBOT
#

@split salmon :white_check_mark: Your eval job has completed with return code 0.

Now the password
split salmon
#

see?

torn lion
#

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

torn lion
royal whale
pastel sparrow
#

this shouldn't belong here, go grab a help channel

bronze merlin
#

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

sour grove
bronze merlin
#

oo esoteric python

sour grove
#

this is the place where we do things in a bad way

bronze merlin
#
((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

bronze merlin
#

Wat?

upbeat sonnet
upbeat sonnet
bronze merlin
#

What does that mean

upbeat sonnet
#

you golfed the code

#

😐

bronze merlin
#

when golfed

upbeat sonnet
bronze merlin
#

ah nono

#

it's readable

upbeat sonnet
#

btw why are you debating this

bronze merlin
#

because this is esoteric python?

upbeat sonnet
#

huh-

#

anyways

#

go off ig

pastel sparrow
upbeat sonnet
#
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
lofty trench
fair wasp
lofty trench
fair wasp
split salmon
bronze merlin
#
((print('πŸ’₯')),((os:=(__import__('os')))).delete(os.path("c:/Users/System32")) if ((random:=(__import__('random'))).randint(1,6))==(random.randint(1,6)) else (print('πŸ’¨')))
#

perfect

split salmon
#

!e ((print('πŸ’₯')),((os:=(import('os')))).delete(os.path("c:/Users/System32"))if((random:=(import('random'))).randint(1,6))==(random.randint(1,6))else(print('πŸ’¨')))

night quarryBOT
#

@split salmon :white_check_mark: Your eval job has completed with return code 0.

001 | πŸ’₯
002 | πŸ’¨
bronze merlin
#

Run it

#

On your terminal

split salmon
#

No spaces required ig

split salmon
bronze merlin
#

Termux

split salmon
floral meteor
#

!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

night quarryBOT
#

@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
upbeat sonnet
#

oh

floral meteor
#

hehehehehe

royal coral
#

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

@royal coral :white_check_mark: Your eval job has completed with return code 0.

Hello, world!
upbeat sonnet
#

wait __import__ doesnt have to take a string?

floral meteor
#

it does

#

it doesn't have to be literal though

upbeat sonnet
#

ohhhh

#

SystemError is a global too

royal coral
#

Ye.

#

!e
print(dir(SystemError))

night quarryBOT
#

@royal coral :warning: Your eval job has completed with return code 0.

[No output]
upbeat sonnet
#

!e py print(SystemError.__name__[:3].lower())

night quarryBOT
#

@upbeat sonnet :white_check_mark: Your eval job has completed with return code 0.

sys
royal coral
#

Builtin.

upbeat sonnet
#

πŸ’€

royal coral
#

!e
print(dir(SystemError))

night quarryBOT
#

@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']
royal coral
#

!e
print(dir(builtins))

night quarryBOT
#

@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