#esoteric-python

1 messages Β· Page 14 of 1

versed eagle
#

and tell it to sleep for an amount of time

#

when it exits, then you can have other stuff done in the first thread

#

and you could have it do something else while it waits
changing the state depending on if something else happened

#

alr now I really do need to sleep

fleet bridge
#

you can calculate some expressions, but every your program will take finite amount of time => it is not turing complete (because turing complete langs can do possibly infinite calculations)

sick hound
#

@earnest wing do you have more information on registering a codec for manipulating syntax
I'm getting some really weird behaviour when it's registered from a .pth file on site-packages

sick hound
#

!e

passes = "Key: value, Key2: Value2"

# Convert this to dict in one line.
print(passes.strip())
night quarryBOT
#

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

Key: value, Key2: Value2
sick hound
#

!e

passes = "Key: value, Key2: Value2"

# Convert this to dict in one line.
print(passes.strip(""))
night quarryBOT
#

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

Key: value, Key2: Value2
sick hound
#

!e

passes = "Key: value, Key2: Value2"

# Convert this to dict in one line.
print(passes.remove(""))
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 4, in <module>
003 | AttributeError: 'str' object has no attribute 'remove'
sick hound
#

!e

passes = "Key: value, Key2: Value2"

# Convert this to dict in one line.
print(strip(passes))
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 4, in <module>
003 | NameError: name 'strip' is not defined
sick hound
#

Hmm

#

!e

passes = "Key: value, Key2: Value2"

# Convert this to dict in one line.
print(passes. strip())
night quarryBOT
#

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

Key: value, Key2: Value2
sick hound
#

BRUH

#

!e

passes = "Key: value, Key2: Value2"

# Convert this to dict in one line.
print(passes.translate())
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 4, in <module>
003 | TypeError: str.translate() takes exactly one argument (0 given)
sick hound
#

!e

passes = "Key: value, Key2: Value2"

# Convert this to dict in one line.
print(passes.translate(" "))
night quarryBOT
#

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

Key: value, Key2: Value2
sick hound
#

Still not working

sick hound
zenith geode
#

!e

__import__("re").finditer(r"", "1")()
night quarryBOT
#

@zenith geode :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: 'callable_iterator' object is not callable
versed eagle
#

!e

# new way to get random numbers
from ctypes import *
from fishhook import *
@hook(str)
def __int__(self):
    py_object.from_address(id(self)+8).value = int
    return self
print(int("10"))
print(int("10"))
# for a string, it's the same within a python session but different for each time it runs
# I'm pretty sure that it tends to get bigger as the string is longer but I haven't actually tested that
night quarryBOT
#

@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 2541701704993351063
002 | 2541701704993351063
fleet bridge
#

object.__int__=id

#

Only if your os is randomising addresses

#

RSP - reg stack pointer
RBP - reg base pointer
right?

#

Windows is not always randomising addresses

#

RBP - address where your code and constants are places, right? If so, it is not always randomised

#

They are placed somewhere near machine code

#

(depends on compiler of course)

versed eagle
#

its pseudorandom

#

then why are you saying it's not? lmao

twin reef
#

It is always going to return the same address (depends on the implementation of malloc, of cource, but both jemalloc and win malloc will return the same address)

#

that's not the point

#

you are talking about ASLR, and it does randomize pointers but in a predictable matter

#

the distribution of such "random" is terrible

#

Its also stupidly platform and hardware dependent

#

you even can disable it on windows lol

lime plinth
#

ok

fleet bridge
#

proekti
Are you russian? πŸ˜„

magic wraith
#

!e ```py

Original source code:

from math import cos, pi

print('cosine of 0.75pi:', cos(0.75 * pi), sep='ΕΎΕΎ')

print(f'this is also formatted string: {pi:.3f}')

import builtins

bytecode = [103, 104, 95, 104, 95, 104, 105, 104, 109, 104, 112, 104, 111, 104, 114, 104, 116, 104, 95, 104, 95, 102, 105, 0, 105, 2, 108, 2, 102, 105, 1, 105, 3, 107, 1, 102, 103, 104, 105, 104, 109, 104, 112, 104, 111, 104, 114, 104, 116, 104, 108, 104, 105, 104, 98, 102, 105, 5, 108, 1, 102, 105, 4, 105, 6, 107, 1, 102, 103, 104, 105, 104, 109, 104, 112, 104, 111, 104, 114, 104, 116, 104, 95, 104, 109, 104, 111, 104, 100, 104, 117, 104, 108, 104, 101, 102, 105, 7, 105, 8, 108, 2, 102, 105, 1, 105, 9, 107, 1, 102, 103, 104, 95, 104, 95, 104, 105, 104, 109, 104, 112, 104, 111, 104, 114, 104, 116, 104, 95, 104, 95, 102, 105, 0, 105, 11, 108, 2, 102, 105, 1, 105, 12, 107, 1, 102, 103, 104, 111, 104, 112, 104, 101, 104, 114, 104, 97, 104, 116, 104, 111, 104, 114, 102, 105, 14, 108, 1, 102, 105, 13, 105, 15, 107, 1, 102, 103, 104, 109, 104, 97, 104, 116, 104, 104, 102, 105, 17, 108, 1, 102, 105, 10, 105, 18, 107, 1, 102, 103, 104, 99, 104, 111, 104, 115, 102, 105, 19, 105, 20, 108, 2, 102, 105, 1, 105, 21, 107, 1, 102, 103, 104, 112, 104, 105, 102, 105, 19, 105, 23, 108, 2, 102, 105, 1, 105, 24, 107, 1, 102, 103, 104, 112, 104, 114, 104, 105, 104, 110, 104, 116, 102, 105, 0, 105, 26, 108, 2, 102, 105, 1, 105, 27, 107, 1, 102, 103, 104, 99, 104, 111, 104, 115, 104, 105, 104, 110, 104, 101, 104, 32, 104, 111, 104, 102, 104, 32, 104, 48, 104, 46, 104, 55, 104, 53, 104, 112, 104, 105, 104, 58, 102, 103, 104, 109, 104, 117, 104, 108, 102, 105, 16, 105, 30, 108, 2, 102, 105, 1, 105, 31, 107, 1, 102, 101, 0.75, 105, 25, 108, 2, 102, 105, 32, 105, 33, 107, 1, 102, 105, 34, 108, 1, 102, 105, 22, 105, 35, 107, 1, 102, 105, 29, 105, 36, 108, 2, 102, 105, 28, 105, 37, 107, 1, 106, 103, 104, 112, 104, 114, 104, 105, 104, 110, 104, 116, 102, 105, 0, 105, 38, 108, 2, 102, 105, 1, 105, 39, 107, 1, 102, 103, 104, 116, 104, 104, 104, 105, 104, 115, 104, 32, 104, 105, 104, 115, 104, 32, 104, 97, 104, 108, 104, 115, 104, 111, 104, 32, 104, 102, 104, 111, 104, 114, 104, 109, 104, 97, 104, 116, 104, 116, 104, 101, 104, 100, 104, 32, 104, 115, 104, 116, 104, 114, 104, 105, 104, 110, 104, 103, 104, 58, 104, 32, 104, 123, 104, 58, 104, 46, 104, 51, 104, 102, 104, 125, 102, 103, 104, 102, 104, 111, 104, 114, 104, 109, 104, 97, 104, 116, 102, 105, 41, 105, 42, 108, 2, 102, 105, 1, 105, 43, 107, 1, 102, 105, 25, 108, 1, 102, 105, 44, 105, 45, 107, 1, 102, 105, 46, 108, 1, 102, 105, 40, 105, 47, 107, 1, 106]

stack = []
names = [builtins, getattr]
pointer = 0

def load_const():
global pointer
stack.append(bytecode[pointer := pointer + 1])

def store_name():
global pointer
names.append(stack.pop())

def load_empty_str():
stack.append('')

def op_inplace_add_char():
global pointer
stack[-1] += chr(bytecode[pointer := pointer + 1])

def overwrite_name():
global pointer
names[bytecode[pointer := pointer + 1]] = stack.pop()

def load_name():
global pointer
stack.append(names[bytecode[pointer := pointer + 1]])

def pop_top():
stack.pop()

def build_tuple():
global pointer
length = bytecode[pointer := pointer + 1]
stack.append(tuple(stack[-length:]))
del stack[-length-1:-1]

def call_function():
global pointer
flags = bytecode[pointer := pointer + 1]
args = stack.pop() if flags & 1 else ()
kwargs = stack.pop() if flags & 2 else {}
stack.append(stack.pop()(*args, **kwargs))

funcs = {
101: load_const,
102: store_name,
103: load_empty_str,
104: op_inplace_add_char,
105: load_name,
106: pop_top,
107: call_function,
108: build_tuple,
109: overwrite_name
}

while pointer < len(bytecode):
try:
op = funcsbytecode[pointer]
pointer += 1
except Exception as e:
print(e)
raise```

night quarryBOT
#

@magic wraith :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | cosine of 0.75pi: -0.7071067811865475
002 | this is also formatted string: 3.142
magic wraith
#

very simple vm in python (and also very slow lmao)

versed eagle
#

ay nice

magic wraith
#

what source exactly? if you want the "compiled" it's at the top of the thing i pasted

rugged sparrow
sick hound
#

okay here's my attempt at a macro codec

wheat river
#

You can add newlines like that in pure rust??

#

NVM, i thought it was a .rs lmao

restive void
quartz wave
sick hound
#

it does use tokenize.tokenize

#

btw the name is because it's just a play on the C preprocessor (cpp)

earnest wing
sick hound
versed eagle
# gentle plover `pylang -E`

pylang -std=python3.11 -Wall -c main.py -o main.pyc
pylang -std=python3.11 -Wall -c module.py -o module.pyc
pylang main.pyc module.pyc -o program.pyc

sick hound
#

pycc soon

versed eagle
#

nice

#

are you going to support the literal thousands of command line options that gcc does

sick hound
#

someone suggested golfscript lol

serene stratus
#

Why define 1 1 and 30 30

sick hound
#

cuz the actual code is in a list and it needs a comma lol

#

I should add some way to match tokens only by type

versed eagle
#

fun

night quarryBOT
#

Hey @sick hound!

It looks like you tried to attach file type(s) that we do not allow (.so). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

Feel free to ask in #community-meta if you think this is a mistake.

versed eagle
#

you can put it on github

#

it won't open bc not valid png

#

right

#

what does execute_code take as an argument?

#

what type

#

ok

#

yeah that explains why it segfaulted

#

i passed a str

#

right

#

18446744073709551602

#

it works

#

ah

#

are you making the asm into a function pointer?
my C is rusty lol

#

ok

wintry schooner
#

!warn 621611758141964298 Trying to bypass our filters is not appreciated.

night quarryBOT
#

:incoming_envelope: :ok_hand: applied warning to @sick hound.

solar tulip
#
def f(S:str, D={}): 
    for c in set(S): D[c] = S.count(c)
    return D```
#

Possible to oneline?

#
def f(S, D={}): return [(D[c] := S.count(c)) for c in set(S)]```
#

Did not work though.

#
def f(S:str, D={}): return {c: S.count(c) for c in set(S)}```
split kestrel
#

If you don't mind removing the d parameter you could go withpy def f(s): return {c: s.count(c) for c in set(s)}

There's also collections's Counter py __import__("collections").Counter(s)

solar tulip
#

No no no, I won't import stuff for just one simple idea.

#

Thanks though.

split kestrel
#

how do you want it to act when you pass it something for D?

solar tulip
#

Like intended.

versed eagle
#
(lambda s,D={}:([D.__setitem__(c,S.count(c))for c in S],D)[1])
#

and, you don't need to make it a set to get the correct behaviour

quartz wave
marsh void
#

fun

versed eagle
#

because previously D was kept between calls

versed eagle
#

I want (o[i]:=v) to be valid syntax

versed eagle
#

yeah ik but

#

walrus is fun

#

also it'd be i.__index__() iirc

#

to get the same behaviour

#

(o[i]=v,o)[1] - not valid syntax

#

if hasattr("__index__")

#

you cant do it if it doesn't have it

#

why are you doing o.__index__

#

no

#

i.__index__()

#

!e

class test:
    def __index__(self):
        return 0
print([1][test()])
night quarryBOT
#

@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.

1
versed eagle
#

see

#

o is [1], i is test()

#

it calls __index__

sick hound
#

Any way to make imports overly complicated

fleet bridge
gentle plover
#

!e py print;("Hello")

#

!e py print(;"Hello")

night quarryBOT
#

@gentle plover :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     print(;"Hello")
003 |           ^
004 | SyntaxError: invalid syntax
gentle plover
#

o_o

#

!e py import builtins as _b _b.__import__ = print import HelloWorld

night quarryBOT
#

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

HelloWorld {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '_b': <module 'builtins' (built-in)>} {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '_b': <module 'builtins' (built-in)>} None 0
versed eagle
#

I'm gonna try to find a way to import without __import__ brb

#

well I might have something

#

but I need a way to segfault without importing

remote prawn
versed eagle
fleet bridge
versed eagle
#

ah
bytecode, my nemesis

#

the bane of my existence

#

we meet again

icy cypress
#

guys whats the shortest piece of code that can create an infinite iterator? this is what I currently have:

def x():
  while 1:
    yield 34.4324
list(x())
#

*ideally without importing anything

versed eagle
snow beacon
#

Then you can import again.

versed eagle
#

ah
i was trying to do it without loader

#

bc you can just import via loader

#

which feels too easy

#

my reasoning is that __loader__.__module__ != __main__

snow beacon
#

I think you can get sys by enumerating all instances of module, which could be helpful.

versed eagle
#

other than that, must be from __main__

icy cypress
#

I love Python

#

thanks @versed eagle

versed eagle
#

please don't ping me pithink

icy cypress
#

ok bro

quartz wave
#

unless there is

night quarryBOT
#

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

001 |   File "<string>", line 3
002 |     import 1
003 |            ^
004 | SyntaxError: invalid syntax
#

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

001 |   File "<string>", line 3
002 |     import 1.0
003 |            ^^^
004 | SyntaxError: invalid syntax
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | TypeError: <lambda>() takes 1 positional argument but 5 were given
#

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

['hello_world', {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}, {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}, None, 0]
vestal harbor
#

!e

night quarryBOT
#
Missing required argument

code

#
Command Help

!eval [python_version] <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.

If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside of them.

By default your code is run on Python's 3.11 beta release, to assist with testing. If you run into issues related to this Python version, you can request the bot to use Python 3.10 by specifying the python_version arg and setting it to 3.10.

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

vestal harbor
#

!e # Sieve of Eratosthenes algorithm
def sieve_of_eratosthenes(n):

# Create a boolean array "prime[0..n]" and initialize 
# all entries it as true. A value in prime[i] will 
# finally be false if i is Not a prime, else true. 
prime = [True for i in range(n+1)] 
p = 2
prime_list = []
while (p * p <= n): 
      
    # If prime[p] is not changed, then it is a prime 
    if (prime[p] == True): 
          
        # Update all multiples of p 
        for i in range(p * p, n+1, p): 
            prime[i] = False
    p += 1
  
# Print all prime numbers 
for p in range(2, n): 
    if prime[p]: 
        prime_list.append(p)
return prime_list

Input

n = 3245098723409852734

Output

Count the amount of primes

count = len(sieve_of_eratosthenes(n))
print("The amount of prime numbers smaller than or equal to", n, "is", count)

vestal harbor
#

thanks

versed eagle
#

don't just go to a random channel to do whatever

#

it's annoying

unique heath
#

!e

with(open(__import__("sys").stdout, "w")) as f: f.write("test")
night quarryBOT
#

@unique heath :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper
unique heath
#

sad

versed eagle
unique heath
#

!e

with((__import__("sys").stdout)as(f)):f.write("hi")```
versed eagle
#

you can just write to it

night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

hi
unique heath
#

yay

versed eagle
#

__import__("sys").__stdout__.write("hi")

#

it's already open

unique heath
#

with((__import__("sys").__stdout__)as(f)):f.write("hi")

#

context managers to confuse the next person

versed eagle
#

file.__enter__ just returns file iirc

#

Β―_(ツ)_/Β―

#

!e

(________:=__builtins__.__getattribute__(__builtins__.__dir__().__getitem__((__:=(______:=(____:=(__:=__name__.__getitem__((___:=__name__.__class__().__len__()))).__add__(__).__len__()).__mul__(____).__add__((_____:=(__:=__name__.__getitem__(___)).__add__(__).__add__(__).__len__()))).__mul__((_______:=_____.__mul__(____)))))))((_________________________:=(__________:=__name__.__class__.__base__).__doc__.__getitem__((___________:=__name__.__eq__(__name__).__pos__())).__add__((____________:=__builtins__.__dict__.__getitem__(__builtins__.__dir__().__getitem__((_______________:=_____.__mul__((______________:=_____.__mul__(_____).__add__((_____________:=____.__mul__(____))))))))).__doc__.__getitem__(___________)).__add__(__name__.__len__().__class__.__module__.__getitem__(_____)).__add__(__name__.__len__().__class__.__module__.__getitem__(_____)).__add__(__________.__name__.__getitem__(___)).__add__(__________.__doc__.__getitem__(_____)).__add__(__annotations__.__class__.__doc__.__getitem__((____________________:=_____________.__mul__(_____)))).__add__(__________.__name__.__getitem__(___)).__add__((______________________:=(______________________:=__name__.__ne__(__name__).__invert__()).__neg__().__truediv__(______________________.__add__(______________________).__neg__()).__rpow__(______________________).__class__).__doc__.__getitem__(___________)).__add__(__name__.__len__().__class__.__module__.__getitem__(_____)).__add__(__annotations__.__class__.__doc__.__getitem__(___))))
night quarryBOT
#

@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.

hello world
unique heath
#

wtf

versed eagle
#

see if you can figure that one out :)

unique heath
#

lol i cant

#

!e

__builtins__.__getattribute__("__import__").__call__("sys").__getattribute__("stdout").__enter__().__getattribute__("write").__call__("Hello, world!")```
night quarryBOT
#

@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.

Hello, world!
versed eagle
arctic skiff
#

!e py __builtins__.__getattribute__('print').__call__('hello world',sep='',end='',file=__builtins__.__getattribute__('__import__').__call__('sys').__getattribute__('stdout'))

night quarryBOT
#

@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.

hello world
supple jolt
#

can anyone come up with the code name Meow?

dreamy pier
# versed eagle !e ```py (________:=__builtins__.__getattribute__(__builtins__.__dir__().__getit...

!e

(________:=__builtins__.__getattribute__(__builtins__.__dir__().__getitem__((__:=(______:=(____:=(__:=__name__.__getitem__((___:=__name__.__class__().__len__()))).__add__(__).__len__()).__mul__(____).__add__((_____:=(__:=__name__.__getitem__(___)).__add__(__).__add__(__).__len__()))).__mul__((_______:=_____.__mul__(____)))))))((_________________________:=(__________:=__name__.__class__.__base__).__doc__.__getitem__((___________:=__name__.__eq__(__name__).__pos__())).__add__((____________:=__builtins__.__dict__.__getitem__(__builtins__.__dir__().__getitem__((_______________:=_____.__mul__((______________:=_____.__mul__(_____).__add__((_____________:=____.__mul__(____))))))))).__doc__.__getitem__(___________)).__add__(__name__.__len__().__class__.__module__.__getitem__(_____)).__add__(__name__.__len__().__class__.__module__.__getitem__(_____)).__add__(__________.__name__.__getitem__(___)).__add__(__________.__doc__.__getitem__(_____)).__add__(__annotations__.__class__.__doc__.__getitem__((____________________:=_____________.__mul__(_____)))).__add__(__________.__name__.__getitem__(___)).__add__((______________________:=(______________________:=__name__.__ne__(__name__).__invert__()).__neg__().__truediv__(______________________.__add__(______________________).__neg__()).__rpow__(______________________).__class__).__doc__.__getitem__(___________)).__add__(__name__.__len__().__class__.__module__.__getitem__(_____)).__add__(__annotations__.__class__.__doc__.__getitem__(___))))


print(dict(list(globals().items())[7:]))
night quarryBOT
#

@dreamy pier :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | hello world
002 | {'___': 0, '__': 42, '____': 2, '_____': 3, '______': 7, '_______': 6, '________': <built-in function print>, '__________': <class 'object'>, '___________': 1, '_____________': 4, '______________': 13, '_______________': 39, '____________': <built-in function oct>, '____________________': 12, '______________________': <class 'complex'>, '_________________________': 'hello world'}
zenith geode
#

is it possible to type hint classes that are looks like type("", (), {})?

earnest wing
#

if you pass "__annotations__": somedict in the namespace πŸ˜„

#

it won't be statically analyzed

royal brook
earnest wing
#

if you want the actual typing behavior then yeah, you ascribe the type you're expecting to it

#

so e.g. cast()ing as some stub type

sick hound
#

I love the idea of this channel but it seems im always disappointed when opening it.
Everyone here wasting countless hours printing hello world using dunnders

night quarryBOT
#

Hey @dreamy pier!

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

dreamy pier
versed eagle
#

it took like 1 minute to make

#

on a more interesting note, I made c-style assignments in python

muted cipher
#

please dont kill me

versed eagle
#

and then it enforces the type

sick hound
earnest wing
#

... I MIGHT be adding an optional unit test to my library that runs the entire python3 -m test test suite over a fully preprocessed copy of the standard library

#

don't ask me how or why

#

(how: create a virtual environment, add my module to site-packages, recursively find every .py file within the stdlib and run my library over the files, then execute the test suite)

#

(why: to see if my library doesn't accidentally break any features of python)

frosty salmon
languid hare
#
^[\x00\s]*[+-]?(((?!_)(?!.*__.*)[\d_]+)|(0b(?!_)(?!.*__.*)[01_]+)|(0o(?!_)(?!.*__.*)[0-7_]+)|(0x(?!_)(?!.*__.*)[0-9a-fA-F_]+))(?<!_)[\s]*$

i think this works

#

decimal binary octal or hex only

#

im assuming int() with base

#

@maiden blaze

#

hmm now that i think about it

#

!e

print(int("0b101", 2))
print(int("0b101", 36))
night quarryBOT
#

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

001 | 5
002 | 514513
languid hare
#

lmao

sick hound
#

!e ```py
import tokenize
print(tokenize.Intnumber)

night quarryBOT
#

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

(0[xX](?:_?[0-9a-fA-F])+|0[bB](?:_?[01])+|0[oO](?:_?[0-7])+|(?:0(?:_?0)*|[1-9](?:_?[0-9])*))
languid hare
sick hound
#

xd
there's other regexes u can use there, pretty useful sometimes

quartz wave
old socket
#

Regex was such a pain for me when making a parser

#

But then I realised it was some context bullshit

quartz wave
#

that's not even the full thing

#

there are more stuff under it

#

and over it

earnest wing
#

one byte at a time

earnest wing
#

a regular language takes one input unit at a time and changes to one of finitely many states depending on it

#

if your input unit is a byte, handling unicode makes your code much bigger

quartz wave
#

though it's definitely possible someone might use a bytes input

earnest wing
#

In theory

quartz wave
#

‫it's gonna be a problem if my input unit is a byte when they use newlines that aren't any of the first 5 ```py
_newlines = {'\n', '\v', '\f', '\r', '\x85', '\u2028', '\u2029',
'\u240a', '\u240b', '\u240c', '\u240d', '\u2424'}

old socket
#

lark is such a good tool when making langs with python

#

EBNF In general is just good too

quartz wave
#

rn i'm working on a parser generator

old socket
#

LALR?

quartz wave
old socket
#

kek

quartz wave
earnest wing
#

I prefer lr(0)

serene stratus
#

Why is there so much code for string parsing

#

And so much nesting dead

quartz wave
quartz wave
earnest wing
#

honestly I think you could make that a bit clearer with parser combinators that allow for error recovery

#

but I don't think python has good libraries for those

old socket
serene stratus
#

Looks like py

old socket
#

LALR is a lot more powerful in cases of ambiguity though

quartz wave
old socket
#

Is this some weird flavour of BNF/EBNF

serene stratus
#

Why is your grammar notation so weird

quartz wave
earnest wing
#

any notation works as long as you can get shift reduce conflicts by compiling it

#

(Beloved)

quartz wave
old socket
#

Looks like EBNF but with @

quartz wave
#

just copied the style from the python grammar file

earnest wing
#

is {} with action code inside some extension of bnf

quartz wave
quartz wave
#

easy as Python
...
powerful as C++
coding style as Java
‫?what

#

python's coding style is probably the main reason it's easy

#

‫C++ is just a lot of things thrown together which i still don't know much about to this day

old socket
#

easy as python, coding style as java

#

I never thought I'd hear that

#

also php OOP?

#

$ moment

pure dew
#

do basic-syle type suffixes

serene stratus
old socket
#

Like, the directories are huge

#

something/bar/foo/baz/qux/java/client

serene stratus
#

I considered that part of the syntax

versed eagle
#

the conventions are bad as well

gusty solstice
#

hello

gusty solstice
#

help me

#

how we can complete the body of the function in the first image by audnat of the 2nd image

#

I've been stuck on it for 3 hours

dreamy pier
#

This channel is for another goals

languid hare
#

true true

floral vapor
#
[start] -> program 
program -> funcs

funcs -> func | func funcs  

func -> func-qualifiers fn id generic-parameters ( func-parameters ) func-return-type where-clause block-expr 
      | func-qualifiers fn id generic-parameters ( func-parameters ) func-return-type ; 
func-qualifiers -> | const #| Todo add more 
func-parameters -> | func-parameter | func-parameter , func-parameters
# TODO: Maybe add `self` parameter as an option to the start of the parameters if adding oop (rechekc rust docs when u do)
func-parameter -> id : type
func-return-type -> - > type
where-clause -> 
generic-parameters -> 


type -> int | str | float | char

expr -> expr-without-block #| expr-with-block

expr-without-block -> path-expr  
    | literal-expr
    | operator-expr 
    | grouping-expr

literal-expr -> true | false
    | int-literal
    | float-literal
    | char-literal
    | str-literal


# Denotes local variables or items
path-expr -> path-expr-segment
    | : : path-expr-segment
    | path-expr : : path-expr-segment 
path-expr-segment -> path-expr-ident
    | path-expr-ident ::< >
    | path-expr-ident ::< path-types-arg > 
path-expr-ident -> id #| self | Self | super # All other than `id` borrowed from rust (don't implement yet)
path-types-arg -> type | type , # Allowed to end in hanging comma
    | path-types-arg , type | path-types-arg , type ,
dreamy pier
#

Is there something to throw error in one line?

versed eagle
#

raise ErrorName

dreamy pier
#

no, i mean in expression

versed eagle
#

1/0

dreamy pier
#

like you can do

[raise ..., raise ...]

#

hmm, i think it's an option

#

ok thanks

versed eagle
dreamy pier
#

i don't mind which error, so that will be enough for me

versed eagle
#

ok

restive void
#

Shorter: x (or any other unused name)

old socket
night quarryBOT
#

@old socket :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 |   File "<string>", line 1, in <lambda>
004 |   File "<string>", line 1, in <genexpr>
005 | ValueError
old socket
#

Can be any exception

dreamy pier
#

!d generator.throw

night quarryBOT
#

generator.throw(value)``````py

generator.throw(type[, value[, traceback]])```
Raises an exception at the point where the generator was paused, and returns the next value yielded by the generator function. If the generator exits without yielding another value, a [`StopIteration`](https://docs.python.org/3/library/exceptions.html#StopIteration "StopIteration") exception is raised. If the generator function does not catch the passed-in exception, or raises a different exception, then that exception propagates to the caller.

In typical use, this is called with a single exception instance similar to the way the [`raise`](https://docs.python.org/3/reference/simple_stmts.html#raise) keyword is used.
earnest wing
#

Finally, all tests pass :o

#

this is actually a pretty big ask for my library

#

given that one of the tests includes running it over the entire stdlib and checking that nothing has changed

#

haskell in your python scripts? more likely than you think

#

blessed

old socket
#

What library is this for? Something related to functional programming?

#

Oh wait, embedded haskell?

rugged sparrow
earnest wing
#

no frontends implemented quite yet

#

technically this would have, like 4 different APIs for different tasks LMAO

#
  1. the source transformer
  2. the magic runtime functions
  3. the codec + optional autoload
  4. the CLI for direct execution or autoload toggle
old socket
#

codec has been booming in this channel recently

earnest wing
#

most of the important stuff is in transform.py and token.py, ignore the __init__ / __main__ since those are stubs

old socket
#

I haven't really looked into codecs', is it used to change the tokens into python valid syntax?

#

GitHub dying with it encounters match

earnest wing
#

oh looks like it failed to parse the doc comment

#

weird

quartz wave
old socket
#

Looks like a C program with the way you lay out variables

scarlet lantern
#

if someone manages to do this ping me

#

i have to be there to see the moment of peek in programming πŸ‘€

rugged owl
earnest wing
#

as expected, since you have full control of the result you can have lots of fun

sick hound
#

!e

comb = lambda f, n: f(f, n)
convert = lambda f, n: chr(n % 256) + f(f, n // 256) if n else ""
print(comb(convert, 802616035175250124568770929992))
night quarryBOT
#

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

Hello world!
frozen silo
#

if you want to make an programming language you can use the lark module it's easy to use

#

what that means? my english is not good

#

is bison an programing launguage?

#

oh ok

versed eagle
#

!e

from __future__ import annotations
import builtins,sys,ctypes
s=object();t,v={},s;c={}
class __g(dict):
    __slots__=()
    def __getitem__(S,i):
        __getitem__={}.__class__.__getitem__
        try:
            return __getitem__(c,i)
        except:
            try:
                return __getitem__(S,i)
            except:
                try:
                    return __getitem__(S,"builtins").__getattribute__(i)
                except:
                    raise NameError(f"{i} is not defined")
    def __setitem__(S,i,V):
        global t,v
        __setitem__={}.__class__.__setitem__
        if i in t:
            if type(V) is t[i]:
                return __setitem__(c,i,V)
            else:
                try:
                    return __setitem__(c,i,t[i](V))
                except:
                    raise TypeError(f"variable '{i}' of type {t[i]} cannot be set to {V} (of type {type(V)})")
        else:
            v=V
f = sys._getframe()
while 1:
    if"__name__"in f.f_globals and f.f_globals["__name__"]=="__main__":
        break
    f=f.f_back
class __a(dict):
    __slots__=()
    def __setitem__(S,i,V):
        print(i,V)
        global t, v
        if V not in t:
            if i in builtins.__dict__ and type(builtins.__dict__[i]) is type:
                t[V]=__builtins__.__dict__[i]
                if v!=s:
                    if type(v) is t[V]:
                        c.__setitem__(V,v)
                    else:
                        try:
                            c.__setitem__(V,t[V](v))
                        except:
                            raise TypeError()
                v=s
        else:
            raise TypeError()
__import__("__main__").__annotations__=__a();ctypes.py_object.from_address(id(f.f_globals)+8).value=__g

int: test = 4
print(test)
test="not an int"
night quarryBOT
#

@versed eagle :x: Your 3.11 eval job has completed with return code 1.

001 | int test
002 | 4
003 | Traceback (most recent call last):
004 |   File "<string>", line 26, in __setitem__
005 | ValueError: invalid literal for int() with base 10: 'not an int'
006 | 
007 | During handling of the above exception, another exception occurred:
008 | 
009 | Traceback (most recent call last):
010 |   File "<string>", line 59, in <module>
011 |   File "<string>", line 28, in __setitem__
... (truncated - too many lines)

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

versed eagle
#

cstyle variable declaration

#

with type checking

#

the reason for the whole sys._getframe rigamarole is that I originally wrote it as a module and had to adapt it to send here. I got the __main__ globals object that way and I'm too lazy to change it lmao

versed eagle
# versed eagle with type checking

upon assignment to a variable, if the value is the wrong type, it attempts to "typecast" it into the correct type, and if that fails it raises a TypeError

old socket
#

Like fn foo() {} -> def foo(): ...

earnest wing
#

Which, to be fair, is part of the API

#

So I shouldn't complain

#

After all, any use case that doesn't implement a "binary format" is "'misusing" codecs

old socket
#

also what

#

I had to search for esoteric-python to get the channel to pop-up

earnest wing
old socket
#

I know you need to do something with a .pth file

earnest wing
#

Only if you want your codec (or any code in general) to execute at interpreter load time

#

Hold on I can respond when I'm more awake later on

old socket
#

Alright

pure dew
#

i just hook the import pipeline and do full reparsing there

snow beacon
old socket
rough moat
#

wrote this thing using 1 line:
import os;os.system("");w=60;print("".join([f"\x1B[48;5;{16+(i%w|i//w)}m {chr(10)if i%w==0 else str()}" for i in range(w**2)]));os.system("pause >nul")

fleet bridge
#

It definitely can be shorter

versed eagle
#

os.system("") doesn't do anything

#

at least it shouldn't

quartz wave
versed eagle
#

windows is weird

fleet bridge
#

str() == ""

#

chr(10) == '\n'

quartz wave
#

128 ```py
map(import('os').system,('',print([f"\x1B[48;5;{16+(i%w|i//w)}m {'\n'*(i%w<1)}"for i in range(60**2)],sep=''))or"pause >nul"),

#

nvm

#

144 ```py
import os;w=60;exec("os.system(%s);"2%('""',r'print([f"\x1B[48;5;{16+(i%w|i//w)}m "+"\n"*(i%w<1)for i in range(w**2)],sep="")or"pause >nul"'))

sturdy rune
versed eagle
#

its just that calling it with an empty string shouldnt do anything

#

windows is so weird lmao

sturdy rune
#

oh i see what you mean, i thought you mean that os.system doesn't do anything by itself

quartz wave
dreamy pier
#

136

s=__import__("os").system;s("");print(*[f"\x1B[48;5;{16+(i%60|i//60)}m "+['',chr(10)][i%60==0]for i in range(3600)],sep="");s("pause >nul")
earnest wing
#

import os;s=os.system

languid hare
#

['',chr(10)][i%60==0] into "\n"[i%60:]

#

(i think)

#

!e

for i in range(100):
  assert ['',chr(10)][i%60==0] == "\n"[i%60:]
night quarryBOT
#

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

[No output]
languid hare
#

nice

versed eagle
#

(i%60|i//60) is always in between 0 and 64

#

and im like 90% sure it loops

#

might be able to use that

versed eagle
languid hare
#

print("".join) is shorter than print sep=""

languid hare
versed eagle
#

it shouldnt

languid hare
#

ah nvm i was just running an old version

#

yea it doesnt

#

136 + import os + "\n" slice + "" join = 124

import os;s=os.system;s("");print("".join(f"\x1B[48;5;{16+(i%60|i//60)}m "+"\n"[i%60:]for i in range(3600)));s("pause >nul")
versed eagle
#

i get the same output with just this

print("".join(f"\x1B[48;5;{16+(i%60|i//60)}m "+"\n"[i%60:]for i in range(3600)))
dreamy pier
#

os calls are needed for windows cmd

versed eagle
dreamy pier
versed eagle
#

python -c "print('`echo -ne \"\x1b\"`[31mtest`echo -ne \"\x1b\"`[0m')"
prints test in red

#

python is fine with the ESC char being in a string directly

languid hare
#

hmm

#

neat

versed eagle
#

other than that, i dont think there's any more shortenings

#

but then again, my brain is dead tired so im probably wrong

languid hare
#

124 + esc char = 121

import os;s=os.system;s("");print("".join(f"[48;5;{16+(i%60|i//60)}m "+"\n"[i%60:]for i in range(3600)));s("pause >nul")
#

miscounted the first time, it substituted the hex into 1 character when i was counting the length

#

kekw

long needle
#

why do you write a semicolon instead of just start a new line?

versed eagle
#

it doesn't change the amount of characters either way

#

newline counts as a character

echo abyss
#
print(''.join('\n'if c=='/'else' '*int(c)if c.isdigit()else ['β™š','β™›','β™œ','♝','β™ž','β™ŸοΈŽ','β™”','β™•','β™–','β™—','β™˜','β™™']['kqrbnpKQRBNP'.index(c)]for c in input().split(' ')[0]))

given a valid FEN (https://en.wikipedia.org/wiki/Forsyth–Edwards_Notation) string on stdin, print corresponding chess position with unicode chess symbols

rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2
β™œβ™žβ™β™›β™šβ™β™žβ™œ
β™ŸοΈŽβ™ŸοΈŽ β™ŸοΈŽβ™ŸοΈŽβ™ŸοΈŽβ™ŸοΈŽβ™ŸοΈŽ
        
  β™ŸοΈŽ     
    β™™   
     β™˜  
β™™β™™β™™β™™ β™™β™™β™™
β™–β™˜β™—β™•β™”β™— β™–
#

(due to pieces not being monospace in this font they're kinda off)

sick hound
#

!e

print(''.join('\n'if c=='/'else' '*int(c)if c.isdigit()else ['β™š','β™›','β™œ','♝','β™ž','β™ŸοΈŽ','β™”','β™•','β™–','β™—','β™˜','β™™']['kqrbnpKQRBNP'.index(c)]for c in input().split(' ')[0]))
night quarryBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
sick hound
#

!e

import os;s=os.system;s("");print("".join(f"[48;5;{16+(i%60|i//60)}m "+"\n"[i%60:]for i in range(3600)));s("pause >nul")

night quarryBOT
#

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

001 |  
002 |                                                             
003 |                             
... (truncated - too long, too many lines)

Full output: too long to upload

rough moat
#

discord doesn’t support 216-color graphics, unfortunately

versed eagle
#

i dont think discord supports ansi escapes at all :(

rough moat
#

it does

#

it allows 16-color ansi

versed eagle
#

\x1b[31mtest\x1b[0m

rough moat
#

you need the actual unicode character

versed eagle
#

ah

rough moat
#

and it has to be in a code block with the ansi format

versed eagle
#

ok

#

brb

rough moat
#

also, doesnt work on mobile at all

versed eagle
#
test
#

ah nice

#

i didnt know that

#

ty for teaching me something new

rough moat
#

np, also works with background

#
like this, for instance```
versed eagle
#

aha
well, time to go find my old ansi artworks and send them to my friends on discord until they're annoyed out of their minds

rough moat
#

yeah ive used the ansi color a lot, i do a lot of terminal graphics

versed eagle
#

ty Lmao

rough moat
#

πŸ‘

rough moat
#

i dont think it fits here, though without context it would certainly appear esoteric

#

also annoyingly only the chinese font (simsun) supports braille, though imo it actually looks pretty cool

dense abyss
#

def tuple_create():

 numbers1 = tuple(range(1,11))
 numbers2 = tuple(range(11,21))

 for t in zip(numbers1,numbers2):

     total = numbers1[0] + numbers2[0]
 return total

x = create tuple()
print(x)
hi here for is only returning 1 time how can i fix it and why is this happening?

subtle solar
#

who wants a homemade version of collections.namedtuple >:)

#

!e ```py
def named_tuple(name:str, members:list[str]) -> type:
t = type(name, (tuple,), {})
oldnew = t.new
def new(cls, *args):
obj = oldnew(cls, args)
obj.dict |= dict(zip(members, args, strict=True))
return obj
t.new = new
return t

Point = named_tuple("Point", ["x", "y"])
p = Point(2,3)
print(p, type(p))
print(p.x)
print(p.y)

night quarryBOT
#

@subtle solar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | (2, 3) <class '__main__.Point'>
002 | 2
003 | 3
subtle solar
#

i was gonna make a TIL on making your own named tuples via just subclassing yourself, but then I realised - why not go all the way out, and remake namedtuple?
At that point, I realised that maybe this was a little too esoteric for that forum :P

versed eagle
#

nice!

real anvil
proud bone
versed eagle
#

typically, oop makes it a lot harder to avoid nesting

#

in python, two indentation levels can come from just class body and then function body in that class

long fulcrum
#

is there any way I can golf this further

#
for a in j:n=int(a);print(f"{n}{[x:='th','st','nd','rd',x,x,x,x,x,x][n%10]if n%100<11or n%100>20else x}")```
muted cipher
dawn plover
#

this has gotta be my favorite channel of any discord server I'm in

last locust
long fulcrum
#

yeah im just after changing it to that droidcry

astral rover
#
"%d%s"%(n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4])
``` :P
#

that might be more compact

long fulcrum
#

that fails on x11

#

711st instead of 711th

astral rover
#

oh lol

last locust
#
f"{n}{([x:='th','st','nd','rd']+[x]*6)[n%10]if n%100<11or n%100>20else x}"```vs```py
f"{n}{([x:='th','st','nd','rd']+[x]*6)[n%10]if(y:=n%100)<11or y>20else x}"```Same length but latter is more esoteric imo (uses extra walrus -- which also arguably makes more efficient since n%100 is only evaluated once)
#

Although for me else x isn't working for 711 since x is undefined (have to do else'th', making it 2 char longer

astral rover
#

and this should work

last locust
karmic pumice
#

Hi guys, i want to turn this function into a 1liner

def sum_dig_pow(a, b): # range(a, b + 1) will be studied by the function; should return a list of numbers in this range, whose sum of digits raised to the power of their place at the number equals to the number itself
    results = []
    for i in range(a, b+1):
        mylist = list(str(i))
        result = 0
        for num in mylist:
            result += int(num)**(mylist.index(num)+1)
        if result == i:
            results.append(i)
    return results

I understand that its something along the lines

return [i for i in range(a, b+1) if (<some expression>)==i]

But whatever i try fails to some errors that i cannot even understand XD
here's what i tried

return [i for i in range(a, b+1) if (sum(int(num for num in list(str(i))) ** (list(str(i)).index(num for num in list(str(i)))+1)))==i]
long fulcrum
last locust
#

The x := 'th' will only run when the if statement is true

long fulcrum
astral rover
#

idk lol

last locust
astral rover
#

hence very esoteric :)

#

i didnt write this

fresh helm
#

how can i do this without any

#
with open("q1(0).txt") as f,open("q(1).txt","w") as g:g.writelines([i+'\n' for i in f.read().split("\n") if any( j for j in i if j[0].lower() == "a")])```
astral rover
#

use dict.fromkeys :)

last locust
fresh helm
long fulcrum
#

is there any way to get rid of or remove the int(a) from my code

#

it feels so annoying to have

karmic pumice
last locust
#

Something like for a in map(int,j)

long fulcrum
#

rip

karmic pumice
last locust
#

The walrus isn't needed, but saves having to do list(str(i)) twice

karmic pumice
#

i was getting some weird errors by trying to call list on I

last locust
#

What you could do is something like [i] though

#

In fact, that's probably better thinking about it

#

Actually, nvm

#

Because you need each character as a separate item in the list

long fulcrum
#

going to use that its much cleaner

last locust
#

Ah, nice!

fresh helm
#

could u help

astral rover
#

why cant you use dict.fromkeys?

#

oh wait any?

fresh helm
#

as in make a working code using that

karmic pumice
astral rover
#

yeah dont use dict.fromkeys to replace any lol

long fulcrum
#

i have it done in 102 and somehow some people have it in 81 chars

#

its mad

astral rover
#

you did edit that right?

#

it did say set

fresh helm
fresh helm
#

but changed

#

sorry

#

did not inform

astral rover
#

ok just checking im not going insane lol

#

you can always just define any yourself

def any(x):
    for y in x:
        if y:
            return True
    return False
```if you cant do that im not really sure this is possible in one line
fresh helm
#

i tried this earlier
so asked for set

with open('q1(0).txt') as f,open('q1(1).txt',"w") as g:g.writelines(*[set(i+'\n' for i in f.read().split("\n") for j in i if j[0].lower() == "a")])
fresh helm
#

apologies

#

rephrases

#

πŸ™

astral rover
#

well ok f.read().split() is possibly the same as just for i in f

karmic pumice
#

Really new to funky python, how to import something inside a line (if i only need to use 1 function from a module)?

import hashlib
to_sha256 = lambda s: hashlib.sha256(s.encode('utf-8')).hexdigest()
astral rover
#

although i dont entirely remember if iter keeps the endline

fresh helm
#

also is there a diff b/w readlines and read().splt('\n')

fresh helm
astral rover
#

i dont use windows :)

sick hound
#

How can i hide a import with __import__

karmic pumice
astral rover
karmic pumice
karmic pumice
fresh helm
#

im using f instead of read() split()

sick hound
karmic pumice
karmic pumice
#

how are you going to hide it then?

sick hound
#

u can still see clearly it says hashlib

astral rover
#

idk any other way to really improve the code

karmic pumice
#

idk, encode the name and decode it inside here

karmic pumice
karmic pumice
#

utf-8

#

however i wouldn't really suggest to hide your imports

#

why would you even do it πŸ’€

sick hound
sick hound
karmic pumice
#

yes

#

thats hashlib encoded with utf-8

versed eagle
#

shorter by a char

versed eagle
#

also a 101 chars but in a nicer (more esoteric) way
short circuiting is fun

for a in j:n=int(a);x='th';print(f"{n}{(n%100<11or n%100>20)and[x,'st','nd','rd',*[x]*6][n%10]or x}")
versed eagle
#

i think thats the shortest i can make it

versed eagle
languid hare
#

82

for a in j:n=int(a);print(a+{1:'st',2:'nd',3:'rd'}.get(n%10+9*(10<n%100<21),'th'))
versed eagle
#

ah nice

languid hare
astral rover
#
for a in j:n=int(a);print(a+"tsnrhtdd"[(n//10%10!=1)*(n%10<4)*n%10::4])
```71 πŸ˜‰
languid hare
#

ooh

versed eagle
#

i think (n//10%10!=1) can be (n//10%10^1)

#

unless the operator precedence messes it up

astral rover
#

seems to work

languid hare
#

bit operations are last luckily

versed eagle
long fulcrum
#

it fails on 941

versed eagle
#

huh

#

k

languid hare
#

mm yea just ran it

versed eagle
#

ok

long fulcrum
#

ive got another thing im trying to golf now and im honestly so confused

#
import sys
l="IndianRed cd5c5c LightCoral f08080 Salmon fa8072...Black 000000".split()
for i in sys.argv[1:]:print("#"+l[l.index(i)+1])```
#

i cant see any way at all to shorten it

#

at least not significantly

long fulcrum
languid hare
#

which site

long fulcrum
#
languid hare
#

css-colors?

long fulcrum
#

yep

versed eagle
#

of colour to hex

languid hare
#

the bytes vs chars difference be something πŸ‘€

versed eagle
#

o.o

long fulcrum
versed eagle
#

ah true nvm

#

you can use two strs

#

to shorten it

#

one can be a str of hexes

#

with all the spaces removed

#

since they're all exactly 6 long

long fulcrum
#

oh shit yeah

versed eagle
#

and the other can be a string of all the color names

#

with spaces in between

#

and then .split

languid hare
#

anyway uh

versed eagle
#

not giving anymore help though

#

gonna go solve it myself :D

languid hare
#

yea

#

this is a challenge problem so probably not fair to discuss it

versed eagle
#

hm true

snow beacon
#

Oh, wrong reply.

quartz wave
night quarryBOT
rotund knot
versed eagle
sick hound
#
import base64
import marshal
import secrets
from xdis.marsh import dumps


try:
    _code = open(str(input('-> ')),'r').read()
except FileNotFoundError:
    print('[KRNL-CLI] FileNotFoundError!')
    quit(0)

#           dump  compile  code   random secret       compile mode
_compiled = dumps(compile(_code, secrets.token_hex(16), 'exec'))
#                encode to b64    encode to b32    encode compiled code
_compiled_base = base64.b64encode(base64.b32encode(_compiled))

# This is the loader,
# Load to marshal, decode b64,b32 and run.

exec(
    marshal.loads(
        base64.b32decode(base64.b64decode(_compiled_base))
    )
)```
Any better improvements?! there has to be some other safety type precautions i can create.
versed eagle
#

wdym by improvements

sick hound
#

improvements

versed eagle
#

what are you doing here

#

improvements to what

sick hound
#

like security wise,

sick hound
versed eagle
#

ah, securitywise

sick hound
#

( i know its not recommend )

#

just having fun

versed eagle
#

if you want anything more specific than that, it really depends on what you're doing with it

versed eagle
sick hound
versed eagle
#

ah

#

a custom loader

old socket
#

ohhh

#

I just thought of a very cool method

sick hound
#

Yeah, better than using marshal

versed eagle
#

and your goal is preventing people from being able to analyse it as it runs?

sick hound
old socket
#

Using codecs, make a HUGE random jumble of strings that gets transformed to the original code, this is the obfuscation, add a .pth file for the codec and add it to the running file so coding: obfuscator then now you just hope that the person doesn't look into site-packages (granted this is assuming you go through pypi for your file)

sick hound
old socket
#

So any regular person looking at the obfuscated code would be confused because it isn't valid python syntax

sick hound
#

never looked at it that way

old socket
#

this'll only work if someone doesn't look at GitHub and only installs through pypi

#

because you wanna hope they don't find the codec

versed eagle
#

i haven't messed around with codecs
do they get evaluated at import time?

old socket
#

I think they run before?

#

It transforms tokens

versed eagle
#

ok

#

so then what stops the person from doing import whatever_file then using something like dis.dis to get at it that way

sick hound
old socket
versed eagle
#

i can write a test but i cant run it
i havent gotten into messing around with codecs yet
haven't had the time :(

sick hound
versed eagle
#

im pretty sure that can be gotten around

old socket
#

I'll install one of the codec stuff from this channel and test

#

I haven't done codec stuff either

versed eagle
#

ah

sick hound
old socket
#

we love -Syy

sick hound
versed eagle
#

so when does it run

sick hound
#

lol when the payload is about to run

#

right before it

versed eagle
#

ah
so if dis is imported after the other thing is

#

then no problem

sick hound
#

wdym?

versed eagle
#
import something
import dis
#

when something is imported, dis wont be in sys.modules

#

dis gets imported after

#

so you would probably want it to run every time something is imported

#

i.e., an import hook

#

but that can be avoided by reloading the __builtins__ module

old socket
#

Where do I find poetry site-packages in linux

#

I am brain farting

sick hound
old socket
#

nvm poetry config --list

versed eagle
sick hound
versed eagle
#

this, by IFcoltransG, reloads builtins
which would clear the import hook __loader__.exec_module(__loader__.create_module(__loader__.find_spec("builtins")))

old socket
#

I can't even get it to import

sick hound
#

dang

old socket
#

Looks like you cannot dis.dis with a custom codec

#

I guess

sick hound
#

...

versed eagle
#

hm

sick hound
#

OT: i love dis.dis()

old socket
#

A normal file with print("hello world") can be imported

#

but not one with a custom codec

versed eagle
#

ah

old socket
#

So codec obfuscation method can still be used

#

Just need to hope they don't check site-packages or GitHub for it

versed eagle
#

what about gdb

#

does gdb work with codecs?

old socket
#

gdb as in gnu?

versed eagle
#

gnu debugger

#

yeah

#

if gdb python can work with codecs then that would defeat the point

#

since it can do more than dis.dis can

sick hound
#

ah yes codecs
(b'h\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00', 5)
I still like playing around with it.

#

Might make my own custom bytecode interrupter

#

trying to find something someone esoteric thats fun

old socket
#

I've never used GDB on a python file before

#

I must be messing something up, in general I don't use GDB a lot

versed eagle
#

iirc you have to install some python support package
i dont remember well, its been a while since ive messed with gdb

old socket
versed eagle
#

ill figure it out later

#

but im pretty sure gdb can connect to already running processes
which would happen after the codec
so, would defeat the point

old socket
#

oh I am an idiot

#

lol i forgot abt run

#

What should I look for specifically

#

backtrace?

versed eagle
#

good question.

#

iirc there's a way to go through frames

#

and view variables and whatnot

torpid ether
#

how do i create a squirrel with python

old socket
#

Ah I need python-dbg package

#

I'll install from the AUR and use that

#

otherwise backtrace is empty

versed eagle
# old socket

from the looks of it, it would be debugging the interpreter in that case

old socket
versed eagle
#

thats a lot of object files-

old socket
#

It's safe to assume at this point

#

Someone who is using gdb to attempt to view the trace of the obfuscated file would be smart enough to find the codec

versed eagle
#

true lol

old socket
#

And dis.dis doesn't work at the very least

#

And reading the trace would be confusing if you obfuscate your original code, then obfuscate using the codec

versed eagle
#

hm

#

oh-

#

wait

old socket
#

this doesn't work either

versed eagle
#

it would generate a .pyc file

#

you could just analyse that

#

and not go through the trouble of dealing gdb or dis.dis or any of that

old socket
#

I don't see a .pyc file

#

This was right after running the codec file

versed eagle
#

if you do python3 whatever_file

#

it should generate a .pyc

old socket
#

Weird I'm not getting a .pyc with diss.py as well

#

I must be doing something wrong

#

(I'm doing it without importing the codec file)

versed eagle
#

maybe poetry does something with it?

#

hm

#

what directory are you in?

#

for me python refused to make a pyc when it was in /tmp

#

but then worked when it was in ~

#

eh

#

either way i gtg

#

bye

sick hound
#

?<

old socket
#

Yea no .pyc file

#

Oh, I haven't had the .pth file for python-dbg

#

I'm prob messing up with gdb, but I'm gonna assume you could make a custom codec that does something like print("Hello World") -> 1231jasdhaidszsjdakiqiwjqe1231a@sdae1e1 to obfuscate relatively secure

#

@serene stratus What do you think? I know you do a lot of obfuscation stuff, the only issue I see here would be finding the .pth file inside of site-packages

sick hound
#

0-0

#

what are we even talking about now

old socket
#

Using the codec trick to transform invalid python syntax code into valid code but the user cannot see it

#

to obfuscate

sick hound
#

confusion

old socket
# old socket

this uses codec to transform invalid python code into valid python code by transforming the tokens before it is ran

#

So if you just make a codec that turns some original code into a jumbled mess you can get it to work using the codec when running

#

So you wouldn't need to pack nor do anything, just let the codec transform then run

#

oh if you force pycache to go into some folder you can find the codec

#

Then with this you can reverse the jumbled mess

#

I cannot find test.pyc though

versed eagle
#

ive done a bit of testing

#

i think it only makes a .pyc file when you import the file

#

not when you just run it with python3 somefile.py

sick hound
old socket
#

Am I doing this right?

#

or was it py_compile

#

Yea that doesn't work either

versed eagle
sick hound
versed eagle
#
  1. hook __import__ to check for dis being imported
  2. override the globals object for any module you can (should be almost every module thats imported), and then check if that module is dis or has dis inside it
  3. hook __loader__ to not be able to load dis
old socket
#

I think the import hooks would be best here

#

cause you can directly check inside an import hook if the module name is dis

#

you can also check if someone tries to mess with sys

versed eagle
old socket
#

by the same method

versed eagle
#

so you would want to stop that

old socket
#

So you cannot import dis bc import hook and you cannot override importhooks with sys.path

versed eagle
#

the globals overriding would be so that you can check if it's already imported

old socket
#

Does __import__ and import go to the same underlying function

versed eagle
#

__import__ is the underlying implementation for import

old socket
#

Ah alright

versed eagle
#

__import__ takes some arguments and returns a module (or raises if the module cant be found)
import calls __import__ and then adds stuff to the namespace

old socket
#

Can you get sys without import?

versed eagle
#

if you replace builtins.__import__ then import calls whatever you used instead

versed eagle
old socket
#

oh wait

#

you could make an import hook using importlib that just reads parses the whole file as an AST, NodeVisitor then check for any names of dis

#

remove offending node then unparse

#

I cannot remember if that's only for packages and not single files though

#

oh wait that wouldn't would cause you'd need to import the import hook

versed eagle
#

you could still get around that, by forcing stuff to be evaluated at runtime

#
x="di"
__import__(x+"s")
sick hound
#

lol yeah forget that, if someone wanna use dis they can do that

#

its not worth my pain

versed eagle
#

actually wait-

#

if you're willing to cap the users ability to do "low level" python, you could block it

sick hound
#

why remove dis if u still can read __code__

sick hound
#

__code__ = None

versed eagle
sick hound
#

that'll explode

sick hound
versed eagle
old socket
#

python when no interpreter

versed eagle
#

blocking __code__ would take the same methods to do as blocking dis

#

just block any module that gives direct access to the memory (such as ctypes), and then you can hook object.__getattribute__ to raise if the object is a code object

sick hound
#

r/softwaregore
del __builtins__

#

u should hook into sys.settrace probably

versed eagle
#

basically, disallow anything that gives access to anything that's internal to python

sick hound
versed eagle
#

actually I'm gonna write that

#

tomorrow though

#

I gtg rn

sick hound
#

I think your "no sleep edition" tag is very correct

sick hound
#

Byee herald.

versed eagle
#

alr bye everyone

#

have a nice day

sick hound
#

You too.

#

sys.modules['dis'] = None

sick hound
snow beacon
#

I'd recommend just deling it instead.

serene stratus
old socket
#

I've tried py_compile and compileall but nothing, it all errors

#

And I've tried importing to get a pyc but it doesn't work either

#

But there prob is a way to get the pyc I just don't know how

visual crest
#

i made it

versed eagle
#

interesting, codecs and zlib

visual crest
#

yep

versed eagle
#

ah

#

exec and eval

#

alr I gtg for now but later I'm gonna write a deobfuscator for that

#

fun challenge

lunar marsh
#

hi all, I have a bit of a strange question. for fun i am trying to find a way to overload and and or in CPython (and chained comparisons such as a<b<c as well, they are basically the same). They don't compile to single instructions but act as control flow using JUMP_IF_FALSE_OR_POP and JUMP_IF_TRUE_OR_POP. I have been using tracing and ctypes to patch bytecode at runtime, triggered by __bool__, which works for just 2 operands but it becomes very messy when you have several chained expressions. Does anyone have any idea of a way to accomplish this? Cursed answers are of course welcome :D

lunar marsh
lunar marsh
# restive void Import hooks, then?

I am not familiar with them, do they allow you to transform the module that imports another one? i.e

import enable_and_or
print(a and b) # behaves how we want it to
#

using a custom class is also fine

restive void
versed eagle
lunar marsh
versed eagle
#

yeah

#

after the modified file runs, you can just exit

lunar marsh
#

im guessing that won't work in the repl since there is no real way to get the source code there

versed eagle
#

you could still hook imports

versed eagle
#

in that case you'd have to use bytecode editing or something like that

#

because you can't get the entire source beforehand

#

actually
I just had an idea, which may be stupid but may also work

icy cypress
#

getting the count of each item in an iterable:

it = [3, 5, 3, 1, 2, 5, 3]
c = {}
for x in it:
    c[x] = c.get(x, 0) + 1
>>> c
Out[14]: {3: 3, 5: 2, 1: 1, 2: 1}
#

or a oneliner?

it = [3, 5, 3, 1, 2, 5, 3]
c = {}
tuple(map(lambda x: c.__setitem__(x, c.get(x, 0) + 1), it))
versed eagle
#

nvm I don't know enough C to be able to do this :(
my idea is, using something like dup2, hook pythons stdin
then, when python reads from its stdin, you read from the real stdin, modify as needed, and then pass along to python

lunar marsh
versed eagle
#

the hard part would be differentiating between user requested input (input, etc) and python requested input

versed eagle
#

and then ast.unparse

#

and then python can handle the parsing and executing

#

I gtg but I'll be back later

#

I'll try to work together a prototype for the repl while I'm gone

#

byee

lunar marsh
sick hound
#

tip: u can overwrite the code attribute on frame objects

lunar marsh
sick hound
#

Anyone wanna attempt to Deobfuscate a obfuscator.

night quarryBOT
sick hound
#

Someone attempt to deobfuscate it, its decently hard

versed eagle
#

though sadly it doesn't redirect to pythons input

#

I think it closes the previous fd when I dup2 the stdin

#

it might be possible to use ctypes to access the input buffer it uses, but I'm not going to try that bc I don't have time to :(

versed eagle
#

basically, it's the equivalent of repeatedly doing exec(input()

#

but using file descriptors

#

I'm gonna conclude that this is a failure in its current state

versed eagle
sick hound
#

...

rugged sparrow
#

@sick hound that looks like it has some discord stuff bundled in it, does it steal tokens

snow beacon
rugged sparrow
sick hound
sick hound
rugged sparrow
#

eh my scanner didnt work then

sick hound
#

I would give the source out, but it would defeat the point of Deobfuscating it,

snow beacon
sick hound
rugged sparrow
sick hound
#

I have made it pretty hard to auto-deobfuscate it.

rugged sparrow
#

was not intending to accuse you of anything, was just trying to make sure whatever code you had obfuscated wasnt some prank discord thing

sick hound
#

Just scared because the admins/mods are a bit hyper-active and will ban you for anything.

And one more warning and ile get perm banned

#

!u

night quarryBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

rugged sparrow
#

yea its all good, my mistake. (just fyi the collision that tripped up my bot was Imposter-main from your code and The-Imposter/main from the search results)

sick hound
#

But has nothing to do with discord πŸ€”

rugged sparrow
#

Β―_(ツ)_/Β―

rugged sparrow
sick hound
#

the source

#

not the obfuscator uses eval

#

and exec

#

just to-do some math operations

#

wait ile change the source

#

( new version )

rugged sparrow
#

it crashes 3.8.12 with a segfault when it hits the first marshal call

sick hound
#

could be xdis

#

not sure

#

Hmmm, i see its happening to me in replit as well

#

Works on replit when using 3.10

rugged sparrow
#

it crashes when it unmarshals RemoveLayers

sick hound
#

Uhh lemmie take a look

#

Not sure why its happening

rugged sparrow
#

||print('Hello from the other side, '+str(5*5))|| @sick hound

#

plus || it says Skiddykid if it doesnt see some variables ||

rugged sparrow
#

i just wrapped marshal.loads and dumped its args and results, then dissassembled the resulting code objects

rugged sparrow
#

if i had wanted to go nuclear, i have code for hooking individual frame loads any time python changes scope so i could have grabbed code objects from there

rugged sparrow
# sick hound ah

|| also you take the obfuscated source and just wrap it in exec, makes it easy to grab out of the code object because it is in the co_consts array ||

#

clearly i need to work on the Discord token stealer detector i wrote like 5 years ago tho lol

rugged sparrow
#

i mean, you could build the string inside that code object at runtime (that would make it a tad more difficult, but still not nearly impossible)

dreamy pier
#

it's broken