#esoteric-python
1 messages Β· Page 14 of 1
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
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)
@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
!e
passes = "Key: value, Key2: Value2"
# Convert this to dict in one line.
print(passes.strip())
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
Key: value, Key2: Value2
!e
passes = "Key: value, Key2: Value2"
# Convert this to dict in one line.
print(passes.strip(""))
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
Key: value, Key2: Value2
!e
passes = "Key: value, Key2: Value2"
# Convert this to dict in one line.
print(passes.remove(""))
@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'
!e
passes = "Key: value, Key2: Value2"
# Convert this to dict in one line.
print(strip(passes))
@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
Hmm
!e
passes = "Key: value, Key2: Value2"
# Convert this to dict in one line.
print(passes. strip())
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
Key: value, Key2: Value2
BRUH
!e
passes = "Key: value, Key2: Value2"
# Convert this to dict in one line.
print(passes.translate())
@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)
!e
passes = "Key: value, Key2: Value2"
# Convert this to dict in one line.
print(passes.translate(" "))
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
Key: value, Key2: Value2
Still not working
#bot-commands
Ok
!e
__import__("re").finditer(r"", "1")()
@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
!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
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 2541701704993351063
002 | 2541701704993351063
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)
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
ok
proekti
Are you russian? π
!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```
@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
very simple vm in python (and also very slow lmao)
ay nice
what source exactly? if you want the "compiled" it's at the top of the thing i pasted
Also python uses its own memory pools so it kind of circumvents any sort of address randomization to a certain point
okay here's my attempt at a macro codec
Nice. Does it tokenize the source the way Python does and do the transformations on the result, or would it print "foo fn bar" as foo def bar?
tokenize-transform is a little hard but i'm gonna guess that's what happens
>>> pypp.preprocess(b"!define fn def\nfoo fn bar")
'\nfoo def bar '
it does use tokenize.tokenize
it's on github now https://github.com/dzshn/pypp
btw the name is because it's just a play on the C preprocessor (cpp)
pylang -E
Might be too late, but did you get that figured out?
ye, I used that for pypp and I'll see later if I can add it to lispy
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
pycc soon
nice
are you going to support the literal thousands of command line options that gcc does
Why define 1 1 and 30 30
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
fun
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.
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
!warn 621611758141964298 Trying to bypass our filters is not appreciated.
:incoming_envelope: :ok_hand: applied warning to @sick hound.
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)}```
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)
how do you want it to act when you pass it something for D?
Your first code works.
Like intended.
make it a lambda
(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
f=lambda S:{c:S.count(c)for c in S}
``` if `D` is removed
fun
the behaviour changes then
because previously D was kept between calls
I want (o[i]:=v) to be valid syntax
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()])
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
Any way to make imports overly complicated
del builtins.__import__
@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 :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
that would make things complicated
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
is there a deobfuscator for https://pyobfuscate.com ?
Pyobfuscate is completely free tool for obfuscate your python source code with pycryptodome module using AES 256 Bit Encryption.Encryption Codes are Protected with 4 Layers of Algorithm.Its working only v3.9 and v3.10 above. There is no impact on the performance of running script.
just do it by hand :P
there is a way to segfault using invalid bytecode
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
iter(int,1)
that short enough for you? :P
__loader__.exec_module(__loader__.create_module(__loader__.find_spec("builtins")))
Then you can import again.
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__
I think you can get sys by enumerating all instances of module, which could be helpful.
the only exception im making for this is where something is from __builtins__
other than that, must be from __main__
maybe
holy shit this awesome
I love Python
thanks @versed eagle
please don't ping me 
ok bro
not any more
unless there is
@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]
!e
code
!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!
!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)
#bot-commands
thanks
!e
with(open(__import__("sys").stdout, "w")) as f: f.write("test")
@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
sad
sys.stdout is already opened
!e
with((__import__("sys").stdout)as(f)):f.write("hi")```
you can just write to it
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
hi
yay
with((__import__("sys").__stdout__)as(f)):f.write("hi")
context managers to confuse the next person
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__(___))))
@versed eagle :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
wtf
see if you can figure that one out :)
lol i cant
!e
__builtins__.__getattribute__("__import__").__call__("sys").__getattribute__("stdout").__enter__().__getattribute__("write").__call__("Hello, world!")```
@unique heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, world!
instead of .__getattribute__("stdout"), you can use .__stdout__
__builtins__.__getattribute__('print').__call__('hello world',sep='',end='',file=__builtins__.__getattribute__('__import__').__call__('sys').__getattribute__('stdout'))```
!e py __builtins__.__getattribute__('print').__call__('hello world',sep='',end='',file=__builtins__.__getattribute__('__import__').__call__('sys').__getattribute__('stdout'))
@arctic skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
can anyone come up with the code name Meow?
!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:]))
@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'}
is it possible to type hint classes that are looks like type("", (), {})?
if you pass "__annotations__": somedict in the namespace π
it won't be statically analyzed
π₯²
okie ty
what bout typing.cast
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
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
Hey @dreamy pier!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
okay how about this
django views.py π
https://paste.pythondiscord.com/unoqaxipiw
countless hours?
it took like 1 minute to make
on a more interesting note, I made c-style assignments in python
please dont kill me
goes type: varname = value
and then it enforces the type
much better
... 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)
beautiful font fr π
^[\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))
@languid hare :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 5
002 | 514513
lmao
!e ```py
import tokenize
print(tokenize.Intnumber)
@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])*))

xd
there's other regexes u can use there, pretty useful sometimes
planning on making it so that it doesn't use unique underscore counts for better obfuscation
Regex was such a pain for me when making a parser
But then I realised it was some context bullshit
β«i'm making a programming language and here's how tokenizing a string is looking like done manually
that's not even the full thing
there are more stuff under it
and over it
you should add the extra layer of working with utf-8 encoded bytes
one byte at a time
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
it isn't because it's in python
though it's definitely possible someone might use a bytes input
In theory
so like .decode('utf8')
β«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'}
lark is such a good tool when making langs with python
EBNF In general is just good too
i'm just manually doing stuff here
rn i'm working on a parser generator
LALR?
i have no clue
kek
how does a LALR parser look anyway
I prefer lr(0)
Send a better screenshot
Why is there so much code for string parsing
And so much nesting 
majority are just errors
so does it go to the deepest layer and go up from there?
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
π
what is it written in
I use them inter-changeably really depends on what type of grammar I wanna work with
Looks like py
LALR is a lot more powerful in cases of ambiguity though
actually idk i just make it go like ```
START <- E
E <- E + T
| E - T
T <- T * F
| T / F
| T // F
| T % F
F <- +A
| -A
| ~A
A <- INT
| IDENT
| STRING
Is this some weird flavour of BNF/EBNF
Why is your grammar notation so weird
it's not even the grammar notation i use
any notation works as long as you can get shift reduce conflicts by compiling it
(Beloved)
this is what i use
Looks like EBNF but with @
maybe
just copied the style from the python grammar file
is {} with action code inside some extension of bnf
i just copied from python https://github.com/python/cpython/blob/main/Grammar/python.gram
tweaked some stuff and there it is
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
easy as python, coding style as java
I never thought I'd hear that
also php OOP?
$ moment
do basic-syle type suffixes
Yeah java's main critique point is it's syntax lol
I'm fine with the syntax, it's the semantics/style that I hate
Like, the directories are huge
something/bar/foo/baz/qux/java/client
I considered that part of the syntax
the conventions are bad as well
hello
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
true true
π’ π it looks almost like my syntax
[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 ,
Is there something to throw error in one line?
raise ErrorName
no, i mean in expression
1/0
i dont think so
i don't mind which error, so that will be enough for me
ok
Shorter: x (or any other unused name)
!e ```py
throw = lambda: (() for () in ()).throw(ValueError)
throw()
@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
Can be any exception
!d generator.throw
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.
π
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
What library is this for? Something related to functional programming?
Oh wait, embedded haskell?
GitHub link?
no frontends implemented quite yet
technically this would have, like 4 different APIs for different tasks LMAO
- the source transformer
- the magic runtime functions
- the codec + optional autoload
- the CLI for direct execution or autoload toggle
codec has been booming in this channel recently
most of the important stuff is in transform.py and token.py, ignore the __init__ / __main__ since those are stubs
I haven't really looked into codecs', is it used to change the tokens into python valid syntax?
GitHub dying with it encounters match
Looks like a C program with the way you lay out variables
if someone manages to do this ping me
i have to be there to see the moment of peek in programming π
Its supposed to be encoding, but you can use it to match regex before the python program runs. Using that you can modify your coding language grammar into valid python π
it's just the generic way to determine how to convert a source file from bytes to a parseable string
as expected, since you have full control of the result you can have lots of fun
!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))
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello world!
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
!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"
@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
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
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
So do you transform your custom syntax into python syntax? Not transpiling a new ast.Module?
Like fn foo() {} -> def foo(): ...
It's an unfortunately required part of dealing with codecs. Even if you can provide an AST that matches what you want, you need a string source 
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
Does transpiling to an ast.Module then using ast.unparse work?
also what
I had to search for esoteric-python to get the channel to pop-up
Yeah codecs expect expect a sting
Does it package well?
I know you need to do something with a .pth file
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
Alright
i just hook the import pipeline and do full reparsing there
You'll have collapsed the category so it only shows when there are new messages.
Figured that out in #community-meta
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")
It definitely can be shorter
allows windows cmd to have color
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"'))
60**2 is 3600
os.system() allows you to execute cmd codes or something like that. it's something i definitely would use
i know what os.system does
its just that calling it with an empty string shouldnt do anything
windows is so weird lmao
oh i see what you mean, i thought you mean that os.system doesn't do anything by itself
no no lol
that solution doesn't work anyway
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")
chr(10) is "\n"
import os;s=os.system
['',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:]
@languid hare :warning: Your 3.11 eval job has completed with return code 0.
[No output]
nice
(i%60|i//60) is always in between 0 and 64
and im like 90% sure it loops
might be able to use that
ah nvm it doesn't loop
print("".join) is shorter than print sep=""
hmm actually this somehow changes the output? last few lines dont look right
it shouldnt
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")
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)))
os calls are needed for windows cmd
huh
you can shorten it by using the byte in the string directly, instead of using \x1b
saves 3 characters
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
other than that, i dont think there's any more shortenings
but then again, my brain is dead tired so im probably wrong
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
why do you write a semicolon instead of just start a new line?
it doesn't change the amount of characters either way
newline counts as a character
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)
!e
print(''.join('\n'if c=='/'else' '*int(c)if c.isdigit()else ['β','β','β','β','β','βοΈ','β','β','β','β','β','β']['kqrbnpKQRBNP'.index(c)]for c in input().split(' ')[0]))
@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
!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")
@sick hound :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [48;5;16m
002 | [48;5;17m [48;5;18m [48;5;19m [48;5;20m [48;5;21m [48;5;22m [48;5;23m [48;5;24m [48;5;25m [48;5;26m [48;5;27m [48;5;28m [48;5;29m [48;5;30m [48;5;31m [48;5;32m [48;5;33m [48;5;34m [48;5;35m [48;5;36m [48;5;37m [48;5;38m [48;5;39m [48;5;40m [48;5;41m [48;5;42m [48;5;43m [48;5;44m [48;5;45m [48;5;46m [48;5;47m [48;5;48m [48;5;49m [48;5;50m [48;5;51m [48;5;52m [48;5;53m [48;5;54m [48;5;55m [48;5;56m [48;5;57m [48;5;58m [48;5;59m [48;5;60m [48;5;61m [48;5;62m [48;5;63m [48;5;64m [48;5;65m [48;5;66m [48;5;67m [48;5;68m [48;5;69m [48;5;70m [48;5;71m [48;5;72m [48;5;73m [48;5;74m [48;5;75m [48;5;17m
003 | [48;5;17m [48;5;19m [48;5;19m [48;5;21m [48;5;21m [48;5;23m [48;5;23m [48;5;25m [48;5;25m [48;5;27m [48;5;27m [48;5;29m [48;5;29m [48;5;31m [48;5;31m [48;5;33m [48;5;33m [48;5;35m [48;5;35m [48;5;37m [48;5;37m [48;5;39m [48;5;39m [48;5;41m [48;5;41m [48;5;43m [48;5;43m [48;5;45m
... (truncated - too long, too many lines)
Full output: too long to upload
discord doesnβt support 216-color graphics, unfortunately
i dont think discord supports ansi escapes at all :(
\x1b[31mtest\x1b[0m
you need the actual unicode character
ah
and it has to be in a code block with the ansi format
also, doesnt work on mobile at all
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
yeah ive used the ansi color a lot, i do a lot of terminal graphics
ty Lmao
π
like mandelbrot in terminal
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
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?
you're in the wrong channel
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)
@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
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
nice!
"im a never nester"
Is there even a space between (def func)?
Honestly, I get not nesting after 3 but 8 indention makes it as confusing as a 6 nest.
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
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}")```
Yes, but you need to know cursive
this has gotta be my favorite channel of any discord server I'm in
To start withpy [x:='th','st','nd','rd',x,x,x,x,x,x][n%10]could bepy ([x:='th','st','nd','rd']+[x]*6)[n%10]
yeah im just after changing it to that 
"%d%s"%(n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4])
``` :P
that might be more compact
oh lol
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
replace the n/10 with n//10
and this should work
>>> "%d%s"%(n,"tsnrhtdd"[(n//10%10!=1)*(n%10<4)*n%10::4])
'711th'```seems to, yeah
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]
yeah thats odd when I use the latter I also need to do else'th'
It's because of lazy-evaluation of bools
The x := 'th' will only run when the if statement is true
ok this is crazy how the hell does this work
idk lol
So if it's not true, and the else runs, then x := 'th' was never run thus is undefined
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")])```
use dict.fromkeys :)
This?py [i for i in range(a, b+1) if sum(map(lambda num: int(num) ** (mylist.index(num)+1), mylist := list(str(i)))) == i]You can remove a load of whitespace here if you so wish to
π
is there any way to get rid of or remove the int(a) from my code
it feels so annoying to have
ooh so thats how you do it, thanks :d
Not without making it longer
Something like for a in map(int,j)
rip
im not really familiar with walrus operator right now so i had a bit of struggle to make it work :d
The key bit is the map
The walrus isn't needed, but saves having to do list(str(i)) twice
i was getting some weird errors by trying to call list on I
Because i is an integer, which isn't iterable, so can't be converted to a list 
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
this is actually the same length
going to use that its much cleaner
Ah, nice!
as in make a working code using that
well, turns out that [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 89, 135, 175, 518, 598, 1306, 1676, 2427, 2646798, 12157692622039623539] are the answers, nice :d
yeah dont use dict.fromkeys to replace any lol
lolololol π
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
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")])
i wanted to simplify sir
apologies
rephrases
π
well ok f.read().split() is possibly the same as just for i in f
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()
although i dont entirely remember if iter keeps the endline
also is there a diff b/w readlines and read().splt('\n')
it has \r i assume
i dont use windows :)
How can i hide a import with __import__
nvm, understood it by myself XD not that hard
yeah ok so f.iter will keep the \n, as will readlines() unless keepends is true and .split will remove the \n
__import__("<name>")
^
to_sha256 = lambda s: __import__('hashlib').sha256(s.encode('utf-8')).hexdigest()
for my code doesnt seem to affect the condition
im using f instead of read() split()
you can do that inside a line bro, you can't fully hide an import
look at the example
thats not even close to hidden
how are you going to hide it then?
u can still see clearly it says hashlib
idk any other way to really improve the code
idk, encode the name and decode it inside here
dont even need to decode lmao,
to_sha256 = lambda s: __import__('\x68\x61\x73\x68\x6c\x69\x62').sha256(s.encode('utf-8')).hexdigest()
works
what encoding are you using
utf-8
however i wouldn't really suggest to hide your imports
why would you even do it π
wait this is utf-8?
\x68\x61\x73\x68\x6c\x69\x62
([x:='th','st','nd','rd']+[x]*6)[n%10]
[x:='th','st','nd','rd',*[x]*6][n%10]
shorter by a char
if you define x beforehand then you can use it in the else
because you lose 1 char from defining it previously, but save 2 chars by using it in the else
so that makes this 101 chars long
for a in j:n=int(a);x='th';print(f"{n}{[x,'st','nd','rd',*[x]*6][n%10]if(y:=n%100)<11or y>20else x}")
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}")
i think thats the shortest i can make it
hopefully i was helpful
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'))
ah nice
might be possible to trim from here, the 9*(10<n%100<21) is just to make the key invalid
for a in j:n=int(a);print(a+"tsnrhtdd"[(n//10%10!=1)*(n%10<4)*n%10::4])
```71 π
ooh
fun
i think (n//10%10!=1) can be (n//10%10^1)
unless the operator precedence messes it up
seems to work
bit operations are last luckily
& doesnt work but ^ does in my testing
it fails on 941
mm yea just ran it
ok
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
this is 2577 chars and some people have below 650
which site
css-colors?
yep
make a dictionary?
of colour to hex
o.o
i mean it was a dict but this is shorter I think?
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
oh shit yeah
and the other can be a string of all the color names
with spaces in between
and then .split
anyway uh
hm true
A small change to your condition.```py
for a in j:n=int(a);x='th';print(f"{n}{1>(10<n%100<19)and[x,'st','nd','rd',*[x]*6][n%10]or x}")
Oh, wrong reply.
69 ```py
for a in j:n=int(a);print(a+"tsnrhtdd"[(n//10%10+3!=4>n%10)*n%10::4])
Hey @rotund knot!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
one of my first "real" python projects! its results are a bit too... diagonal to me but hey it works!
https://paste.pythondiscord.com/pozakegiza
sorry, but this is wrong channel for that
perhaps try #python-discussion?
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.
wdym by improvements
improvements
like security wise,
obfuscation method
ah, securitywise
inputalready returns astr, you don't need to convert itopenuses'r'automatically if you dont pass stuff to it
in terms of security, you probably shouldn't run a file passed by the user without validating it in some way
i.e., make sure that it isn't something you don't want to run
if you want anything more specific than that, it really depends on what you're doing with it
you're dumping it, encoding it, and then immediately undoing all that and running it
True, π€ trying to find a way to make a custom loader that confusing and very hard to dump.
Yeah, better than using marshal
and your goal is preventing people from being able to analyse it as it runs?
yeah, some-type of fun-crackhead obfuscation
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)
( i was using xdis instead of marshal because xdis cross-supports python bytecode versions)
So any regular person looking at the obfuscated code would be confused because it isn't valid python syntax
βοΈ thats very interesting,
never looked at it that way
that sounds fun
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
i haven't messed around with codecs
do they get evaluated at import time?
ok
so then what stops the person from doing import whatever_file then using something like dis.dis to get at it that way
codecs is very fun to mess with, tho i quickly stopped after realizing how easy it was to decode
I'm curious if that is the returned behaviour cause I really don't know could you write a quick test?
i can write a test but i cant run it
i havent gotten into messing around with codecs yet
haven't had the time :(
i just block dis from getting imported

im pretty sure that can be gotten around
I'll install one of the codec stuff from this channel and test
I haven't done codec stuff either
ah
semi-hard but maybe?
i just checked using sys
import sys
A_V_Modules = [m.__name__ for m in sys.modules.values() if m]
than do something like for module in A_V_Modules:
if module in ['dis']:
exit()
we love -Syy
is that in an import hook?
I don't think so.
so when does it run
wdym?
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
Ahhhh i see, this is a example
nvm poetry config --list
yeah
all i have to do is get the import to run after the check
Yeah hooking would be good but as mentioned.

this, by IFcoltransG, reloads builtins
which would clear the import hook __loader__.exec_module(__loader__.create_module(__loader__.find_spec("builtins")))
I can't even get it to import
dang
...
hm
OT: i love dis.dis()
A normal file with print("hello world") can be imported
but not one with a custom codec
ah
So codec obfuscation method can still be used
Just need to hope they don't check site-packages or GitHub for it
gdb as in gnu?
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
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
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
iirc you have to install some python support package
i dont remember well, its been a while since ive messed with gdb
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
oh I am an idiot
lol i forgot abt run
What should I look for specifically
backtrace?
good question.
iirc there's a way to go through frames
and view variables and whatnot
how do i create a squirrel with python
Ah I need python-dbg package
I'll install from the AUR and use that
otherwise backtrace is empty
from the looks of it, it would be debugging the interpreter in that case
pain
thats a lot of object files-
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
true lol
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
this doesn't work either
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
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)
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
?<
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
Using the codec trick to transform invalid python syntax code into valid code but the user cannot see it
to obfuscate
confusion
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
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
Wait Herald have we every found a method for blocking importing dis?
it'd be pretty much impossible to fully block it imo
Yeah of course but and good methods?
- hook
__import__to check fordisbeing imported - override the globals object for any module you can (should be almost every module thats imported), and then check if that module is
disor hasdisinside it - hook
__loader__to not be able to loaddis
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
im talking about using all of these at once
by the same method
since import hooks can be cleared
so you would want to stop that
So you cannot import dis bc import hook and you cannot override importhooks with sys.path

the globals overriding would be so that you can check if it's already imported
Does __import__ and import go to the same underlying function
__import__ is the underlying implementation for import
Ah alright
__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
Can you get sys without import?
if you replace builtins.__import__ then import calls whatever you used instead
iirc you can
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
you could still get around that, by forcing stuff to be evaluated at runtime
x="di"
__import__(x+"s")
actually wait-
if you're willing to cap the users ability to do "low level" python, you could block it
why remove dis if u still can read __code__
i think __code__ is a lot easier to block than dis
this was a joke
actually no im completely wrong
getattr
python when no interpreter
my method wouldnt care
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
basically, disallow anything that gives access to anything that's internal to python

I think your "no sleep edition" tag is very correct
yep
Byee herald.
How well would this even work?
I'd recommend just deling it instead.
The resulting pyc will have all the replaced contents though
I couldn't even get a pyc to generate
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
yeah ill give it a try
brb
interesting, codecs and zlib
yep
ah
exec and eval
alr I gtg for now but later I'm gonna write a deobfuscator for that
fun challenge
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
Have you tried codecs?
i did think of it but it kind of felt like cheating, want to just import a library and for it to work
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
No, that's not possible with them, as far as I know. Only modules imported afterwards.
you could do stuff inside the module to modify the original file
then run the modified file but don't import the enabler
and part of the modification would be an import hook
that's clever, so you then just prevent the original file from running
im guessing that won't work in the repl since there is no real way to get the source code there
you could still hook imports
but yeah
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
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))
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
oh lol, thats real hacky :D probably easier to hook some internal function in cpython that handles the parsing in that case
the hard part would be differentiating between user requested input (input, etc) and python requested input
I think you could use ast, replace nodes that use and, or, etc
and then ast.unparse
and then python can handle the parsing and executing
if you want to try that, here's the main source file for the REPL
https://github.com/python/cpython/blob/main/Python/pythonrun.c
I gtg but I'll be back later
I'll try to work together a prototype for the repl while I'm gone
byee
haha alright thanks for the help! will try to work out something slightly less janky in the meanwhile ;)
tip: u can overwrite the code attribute on frame objects
yeah that's kind of what i've been doing, except I'm overwriting co_code of the code object. my poc for python 3.10 which only works with two operands is here https://paste.pythondiscord.com/ojacihevor
Anyone wanna attempt to Deobfuscate a obfuscator.
Hey @sick hound!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
got it
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 :(
because I can't do that, I end up just execing the input that I get
which is sad that I have to to that
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
but later I might try to find the buffer and see if I can write to it
...
@sick hound that looks like it has some discord stuff bundled in it, does it steal tokens
No?
What version of Python is this made to run on? I see it has mashall.loads in it.
what is it then
its compatible with any using (xdis)
Please leave this channel it seems u have no clue what your talking about.
eh my scanner didnt work then
I would give the source out, but it would defeat the point of Deobfuscating it,
That's a tad harsh. We're all about alternative solutions here, like 'ask the author'.
Framing someone about stealing tokens is not something to be played with.
anyways looking at it manually, it makes 2 different code objects, one of which looks like it might use marshal to make a third

I have made it pretty hard to auto-deobfuscate it.
i have a really shitty scanner that looks for marshaled code and then just searches online for different strings, co_name, filename and such. one of the filenames your code had looks like one from some discord bot online. my scanner got confused
was not intending to accuse you of anything, was just trying to make sure whatever code you had obfuscated wasnt some prank discord thing
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
You are not allowed to use that command here. Please use the #bot-commands channel instead.
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)
Yeah its part of a obfuscator.
But has nothing to do with discord π€
Β―_(γ)_/Β―
it segfaults when i run it on replit
the source
not the obfuscator uses eval
and exec
just to-do some math operations
wait ile change the source
( new version )
it crashes 3.8.12 with a segfault when it hits the first marshal call
π€
could be xdis
not sure
Hmmm, i see its happening to me in replit as well
Works on replit when using 3.10
it crashes when it unmarshals RemoveLayers
||print('Hello from the other side, '+str(5*5))|| @sick hound
plus || it says Skiddykid if it doesnt see some variables ||
Damn u got that fast
i just wrapped marshal.loads and dumped its args and results, then dissassembled the resulting code objects
ah
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
π
|| 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
co_consts = None
(this is satire)
lol
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)
true.
WhAt ThE
Was this
it's broken
