#esoteric-python
1 messages ยท Page 95 of 1
that's simpler
def is_even(n, m={1}):
return not(n in m or is_even(n-1) and (m.add(n)or m) )
NO
inb4 someone does is_even with only types
nekit $ python -m timeit -s "n = 13" "n ^ 1 > n"
2000000 loops, best of 5: 123 nsec per loop
nekit $ python -m timeit -s "n = 13" "not not n & 1"
2000000 loops, best of 5: 113 nsec per loop``` how do I express my confusion
not not is really fast
def is_even(n):
return int(str(n)[-bool(int)]) in range(int(),int(str(int(bool(int)))+str(int())),bool(int)+bool(int))```
i'm surprised esoteric python for me is a complicated topic in itself
checks IsTrue and sets the result depending on what that returned https://docs.python.org/3/c-api/object.html#c.PyObject_IsTrue
while True:
try:
while (selection := input(">")) not in option_list and int(selection) not in range(1, 7):
print(f"Invalid selection: {selection}")
break
except ValueError:
print(f"Invalid selection: {selection}")```
any way to shorten this? I tried fire's suggestion of supressing the ValueError but there's no way to catch it + respond if I use it
you can incorporate the range into your option_list, that way you don't have to check for casting error
import timeit
import math
>>> math.sqrt(25) == 25 ** 0.5
True
>>> math.sqrt(2500) == 2500 ** 0.5
True
--------------------------------------------------------
>>> timeit.repeat('sqrt(25)', setup='from math import sqrt')
[0.21578920000000323, 0.21665869999999643, 0.21319249999999101, 0.21543020000000013, 0.21696570000000293]
>>> timeit.repeat('25 ** .5')
[0.015132900000011773, 0.015274300000001517, 0.015007799999992244, 0.01510880000000725, 0.015405400000005898]
``` I just realize that `math.sqrt` is kinda pointless as well as slow compared to just using `0.5` exponent (unless the number is negative in which case they're different, I forgot about that)
I assume that sqrt is approximated in a different way than arbitrary power
def is_even(n):
b = bin(abs(n))
return b[0] == b[-1]
shameless idea theft
or how about this...
def is_even(n):
i = iter(range(abs(n)))
while True:
try:
next(i)
except StopIteration:
return True
try:
next(i)
except StopIteration:
return False
def _is_even(a, b):
if 0 in (a, b):
return True
if 1 in (a, b):
return False
return not _is_even(a - 1, b + 1)
def is_even(n):
return _is_even(n, n)
def _is_even(a, b):
return(0in(a,b)and[1])or(1in(a,b)and[0])or[not _is_even(a-1,b+1)[0]]
def is_even(n):
return _is_even(n,n)[0]
is_even=lambda n:(lambda r:r(r))(lambda r:lambda a,b:(0in(a,b)and[1])or(1in(a,b)and[0])or[not r(r)(a-1,b+1)[0]])(n,n)[0]
there's a minor issue that it returns 1 for 0 and 0 for 1, but it's okay
actually,
is_even=lambda n:(lambda r:r(r))(lambda r:lambda a,b:(0in(a,b)and[1>0])or(1in(a,b)and[1<0])or[not r(r)(a-1,b+1)[0]])(n,n)[0]
yikes
code = """if n == 0:
v[0] = True
elif n == 1:
v[0] = False
else:
exec({!r}.format(code), dict(n=n-2,code=code,v=v))"""
def is_even(n):
v = ['error']
exec(code.format(code),dict(n=n,code=code,v=v))
return v[0]
def even(n):
return (not -n) or int(str(n)[-bool(-n)]) in range(bool(n)+bool(n),int(str(int(bool(n)))+str(int(bool(-0)))), bool(-n)+bool(-n))
Is it dangerous for a function to modify its own code?
I'd assume it is, but is it just a straight segfault, or the interpreter won't care?
I would assume it would only affect the next call of the function
Would it be possible to make an is_even implementation that abuses floating point imprecision and some crazy magic numbers to evaluate K & K+1 to the same value, but K+2 to something else?
honestly
this is cool and all but n % 2 == 0 is the fastest haha (EDIT: not n % 2, how could I have forgotten about it)
specifically in python, that is
the point of this channel is NOT to be the easiest
I didnโt say the easiest
I said the fastest
which is funny because most compilers should and will optimize it down to n & 1 == 0 which is slower in python
is_even = lambda n:int((float(n)/0.9)/2)*2==n```
Probably not n % 2 is faster than n % 2 == 0
def even(n): return not bool(n//2 - n/2)
importing gc appears to affect the result of reading a deallocated tuple ```py
from ctypes import *
from gc import *
x = (1, 2, 3)
x
(1, 2, 3)
(c_longlong*9).from_address(id(x))[0] = 0
x
TypeError: an integer is required (got type str)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
SystemError: <built-in method write of _io.TextIOWrapper object at 0x00000254A5397630> returned a result with an error set
((((((((((((((((((((((((((((((<NULL>, (<class '_ctypes.Structure'>,), {}), 'BigEndianStructure', <class '_ctypes.Structure'>), None, None), (<class '_ctypes.PyCFuncPtr'>,), {2562580367832: <weakref at 0x00000254A54A6188; to '_ctypes.PyCArrayType' at 0x00000254A5B149D8 (c_longlong_Array_9)>}), 'CFunctionType', <class '_ctypes.PyCFuncPtr'>), (), 1), 'This class represents a dll exporting functions using the\n Windows stdcall calling convention, and returning HRESULT.\n HRESULT error values are automatically raised as OSError\n exceptions.\n ', None), 'l', None), 'This class represents a dll exporting functions using the\n Windows stdcall calling convention.\n ', None), 'This class represents the Python library itself. It allows\n accessing Python API functions. The GIL is not released, and\n Python exceptions are handled correctly.\n ', None), 'u', None), 'pointer', '_pointer_type_cache'), '?', None), 'P', None), 'c', None), 'b', None), 'B', None), 'Q', None), 'q', None), 'g', None), 'd', None), 'f', None), 'I', None), 'i', None), 'L', None), 'l', None), None, None), (<class '_ctypes.Array'>,), {'builtins': <symtable entry top(-1), line 0>}), 9, None), 2, 3)```
What is the best way to get started with esoteric python? I find it very interesting
just find an esoteric solution to it>
any concepts I should look into?
String multiplication & lamda
thanks!
def _set(x):
consts = list(is_even.__code__.co_consts)
consts[1] = x
is_even.__code__ = is_even.__code__.replace(co_consts = tuple(consts))
def is_even(n):
r = True
if n == 0:
_set(r)
return r
_set(not is_even.__code__.co_consts[1])
return is_even(n - 1)```
beware
most cursed addition to Python ever
(after @marsh void's braces, of course)
ta da
available on my fork https://github.com/decorator-factory/cpython
now seriously, I would love this addition
How on Earth
@formal sandal now you gotta add automatic interpolation
like `var{val}`
that would be super cursed
@astral rover No magic, I just modified CPython's source
@rugged sparrow that would be a bit more involved than my change ๐
but yes
sigh gets out pitchfork
f-strings for identifiers
from pwn import *
import ctypes
context.arch = "amd64"
libc = ctypes.CDLL("libc.so.6")
def shellcode_to_func(shellcode: bytes, func_type=None):
if func_type is None:
func_type = ctypes.CFUNCTYPE(ctypes.c_int)
buf = ctypes.create_string_buffer(shellcode)
buf2 = ctypes.c_void_p(libc.valloc(len(buf))) # allocate page aligned
libc.mprotect(buf2, len(shellcode), 7) # set to rwx
ctypes.memmove(buf2, buf, len(shellcode))
return ctypes.cast(buf2, func_type)
def run_shellcode(shellcode: bytes):
return shellcode_to_func(shellcode)()
is_even = shellcode_to_func(
asm("mov rax, rdi; and rax, 1; xor rax, 1; ret"), ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)
)
print(is_even(10))
print(is_even(5))
bruh
More math (Bernoulli numbers)
from math import comb
def bernoulli(n):
return sum(
sum((-1) ** v * (v + 1) ** n * comb(k, v) for v in range(k + 1)) / (k + 1)
for k in range(n + 1)
)
def is_even(n):
return not bernoulli(abs(n) + 3)
now seriously, I would love this addition
wow, that's really nice !
But I think this addition would just break the lisibility of a code. And I'm pretty sure you can do something like `2` = 3, right (I haven't check the source code modifications yet ๐ ) ?
Anyway, I find it fun ! ๐
what is the most inefficient way to output hello world?
without using while loops or backspace characters
but the identifier is `2` in this case, not 2
hum... interesting ๐
@rustic aspen There's no answer to that question. For any proposed solution, you can do worse.
write a small program which takes a string as input and checks to to see if the string is a palindrome, if it is, print โYesโ, if it is not,print โNoโ.
This sounds like a homework problem.
def _(__,_____):
for (______)in(__):
(lambda:(__import__('sys').stdout.write(______)))();
(lambda ____:_(____,____))(('H','e','l','l','o',' ','W','o','r','l','d','!'));
how can I make this better? it works but isnโt too hard to understand.
(yes I deliberately added the semicolons to try to make it a bit harder to understand)
what is the most inefficient way to output
hello world?
@rustic aspen this is the best(worst?) way to do that
(lambda _, __, ___, ____, _____, ______, _______, ________:
getattr(
__import__(True.__class__.__name__[_] + [].__class__.__name__[__]),
().__class__.__eq__.__class__.__name__[:__] +
().__iter__().__class__.__name__[_:][_____:________]
)(
_, (lambda _, __, ___: _(_, __, ___))(
lambda _, __, ___:
bytes([___ % __]) + _(_, __, ___ // __) if ___ else
(lambda: _).__code__.co_lnotab,
_ << ________,
(((_____ << ____) + _) << ((___ << _____) - ___)) + (((((___ << __)
- _) << ___) + _) << ((_____ << ____) + (_ << _))) + (((_______ <<
__) - _) << (((((_ << ___) + _)) << ___) + (_ << _))) + (((_______
<< ___) + _) << ((_ << ______) + _)) + (((_______ << ____) - _) <<
((_______ << ___))) + (((_ << ____) - _) << ((((___ << __) + _) <<
__) - _)) - (_______ << ((((___ << __) - _) << __) + _)) + (_______
<< (((((_ << ___) + _)) << __))) - ((((((_ << ___) + _)) << __) +
_) << ((((___ << __) + _) << _))) + (((_______ << __) - _) <<
(((((_ << ___) + _)) << _))) + (((___ << ___) + _) << ((_____ <<
_))) + (_____ << ______) + (_ << ___)
)
)
)(
*(lambda _, __, ___: _(_, __, ___))(
(lambda _, __, ___:
[__(___[(lambda: _).__code__.co_nlocals])] +
_(_, __, ___[(lambda _: _).__code__.co_nlocals:]) if ___ else []
),
lambda _: _.__code__.co_argcount,
(
lambda _: _,
lambda _, __: _,
lambda _, __, ___: _,
lambda _, __, ___, ____: _,
lambda _, __, ___, ____, _____: _,
lambda _, __, ___, ____, _____, ______: _,
lambda _, __, ___, ____, _____, ______, _______: _,
lambda _, __, ___, ____, _____, ______, _______, ________: _
)
)
)
you can use my cpython fork and include spaces in the identifiers
so instead of many _s you can do some evil stuff like
not actually that cursed of a feature. i always wanted ? in functions
well, that part is nice
@terse mortar how did you come up with that?
I was fucking around with weird ways to print hello world, and f1re showed up with that shit from google
ah
this is the best(worst?) way to do that
@terse mortar this channel is for python not brainfuck (joke)
No, I do believe it's for brainfuck
nah bro you went like >-+=<>+-=<><>[*+[]=
!e
(lambda f: (setattr(f, '__code__',f.__code__.replace(co_consts=("Hello, World",))),f()))(lambda:print(None))```
@proper vault :white_check_mark: Your eval job has completed with return code 0.
Hello, World
nice
you could build a code object manually, but imo its neater to transform the code of the function
That's stupid, I love it
any way to redefine keywords?
No, they are handled in the parser level
ayy isidentical always joining in when itโs about parsers or AST >:)
*unless you use some sort of sorcery :-)
ayy isidentical always joining in when itโs about parsers or AST >:)
@marsh void always watching
ah yes
@bitter iris Did my fork summon you?
I need to make a project and write all the tests with these identifiers
Yeah saw it @formal sandal, nice stuff
I should probably also add ? as a valid identifier character
Hmm, what about changing the grammar of if statements? if is_odd()? print('Yes')
then I'd also put the parts of the if expression in the correct order ๐
And can you implement pattern-matching, btw ? ๐ ||(I'm joking)||
||๐||
||this is a very nice feature||
||i feel like it attracts people more than normal text||
||it's secret||
||Indeed||
||๐ณ||
but where are None-aware operators smh
where are the sentient operators smfh
@formal sandal btw here is a similiar hack just like yours (from Anthony) https://twitter.com/anthonypjshaw/status/1273785519764168704?s=19
Patching my favorite feature from Kotlin over to Python, backtick-quoted names, like function names, variable names, etc.
It's super-helpful for test function naming... Its a teeny-tiny-change to the codebase. https://t.co/WGQSnV1QkG
huh
His implementation though a bit different
He parses this in the exact way of parsing a string (check the case he added, it is the same version of string tokenization case), so probably supports multiline things
In case if you want to go that route
but where are None-aware operators smh
@marsh void who needs None-aware operators when we have ||tiefighter|| operators
PEP 505 now or Iโm leaving
last isnโt
if we had PEP 505, T? would be useful instead of Optional[T] or T | None
it makes it much more fun to say
huh?
I'm not on the pc rn, but search for int?
int?
IMHO this is the one of the most useless way to fill up ? token
I'm very in favor of PEP 640 for getting a meaning to ?
!pep 640
no-no-no
so the point is it doesnโt get into bytecode or is just as an _?
too lazy to read :p
Its coupled with other pattern matching peps
Basically it objects to making _ a special character
Even though it is just a normal identifier
So for wildcard pattern, it introduces ?
But not only for pattern matching, but for everywhere
Which is cool
I disagree with that honestly
for patma, the wildcard could just be object(), no?
>>> __import__("ctypes").string_at(0)
segmentation fault``` but I think itโs easier to mess with the parser @twilit grotto
I mean yeah
!e import("ctypes").string_at(0)
@twilit grotto :warning: Your eval job has completed with return code 139 (SIGSEGV).
[No output]
reading at address 0 is kinda uhm
there are 3 different types of source in python
yeah
exec, single, eval
# this is also possible
(lambda:eval("exec(...)"))()```
which pretty much removes lambdas limits
though not sure if the `eval` here needs to be.
this is double stack of a hacky solution
is there to manually split a lexical token for the interpreter, without space?
is there any way to define mutually recursive functions such as this in one expression? py (lambda f = lambda: g(), g = lambda: f() : f() )() (this NameErrors for g ofc)
You could use a combinator.
(lambda f, g: f(f, g))(lambda f, g: g(f, g), lambda f, g: f(f, g))```
is there to manually split a lexical token for the interpreter, without space?
@coarse cave what do you mean by this?
like make the python lexer actually split for a token but manually.
ifTrue:print() # fails because `ifTrue` becomes a singular identifier.
if(True):print() # succeeds because itโs no longer a singular token. the parentheses split a lexical token.
like that, but in some cases it isnโt really a condition.
i.e 2:
xy == xy as a single identifier.
x y == x, y as two identifiers.
basically the same thing spaces (and lots of other characters and character sequences) do, but not using space.
since not having whitespace makes stuff much harder to read.
do you want the tokenize module
since not having whitespace makes stuff much harder to read.
@coarse cave what?
I know, I couldn't parse that sentance either.
What is an alternative to using func.__code__.replace that would work with python 3.6?
manually filling the code constructor arguments from the code object
How do I create a new code code object though, the attributes on it are read only
!e
from types import CodeType
CodeType()
@proper vault :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | TypeError: code() takes at least 14 arguments (0 given)
at least 14 arguments
class types.CodeType(**kwargs)```
The type for code objects such as returned by [`compile()`](functions.html#compile "compile").
Raises an [auditing event](sys.html#auditing) `code.__new__` with arguments `code`, `filename`, `name`, `argcount`, `posonlyargcount`, `kwonlyargcount`, `nlocals`, `stacksize`, `flags`.
Note that the audited arguments may not match the names or positions required by the initializer. The audit event only occurs for direct instantiation of code objects, and is not raised for normal compilation.
`replace`(***kwargs*) Return a copy of the code object with new values for the specified fields.
New in version 3.8.
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
001 | Help on class code in module builtins:
002 |
003 | class code(object)
004 | | code(argcount, posonlyargcount, kwonlyargcount, nlocals, stacksize,
005 | | flags, codestring, constants, names, varnames, filename, name,
006 | | firstlineno, lnotab[, freevars[, cellvars]])
007 | |
008 | | Create a code object. Not for the faint of heart.
009 | |
010 | | Methods defined here:
011 | |
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/oyuvekezuf.txt
yep
Create a code object. Not for the faint of heart.
Sort of confusing that the docs say that it takes **kwargs, but it actually only seems to let you give positional args
I guess that's just because it's a built in thing (C code) so parameters and stuff work differently?
Yeah, it has, like, ficticious arguments
In the C code, it uses a mini-DSL (like printf) to parse positional arguments
and idk how it handles kwargs
but kwargs have to be accessed deliberately
Ah interesting
!e
from string import ascii_letters as letters
def f(): pass
for _ in range(5):
f.__code__ = f.__code__.replace(
co_argcount=len(letters),
co_varnames=tuple(letters),
)
try: f()
except TypeError as err:
print(str(err).partition(':')[0])
@sudden osprey :white_check_mark: Your eval job has completed with return code 0.
001 | f() missing 44 required positional arguments
002 | f() missing 29 required positional arguments
003 | f() missing 24 required positional arguments
004 | f() missing 25 required positional arguments
005 | f() missing 40 required positional arguments
Interesting behaviour if you don't set co_nlocals
yo i made some one-line algorithms to find the root of a function between a and b ```py
import numpy as np
import random
def f(x):
return x**2 - 2
avstand til nullpunktet
toleranse = 0.01
start
a = 0
slutt
b = 2
metode 1 (halveringsmetode)
print((lambda r:lambda a,b: r(r,a,b))(lambda h,a,b:(a+b)/2 if abs(a-b)<toleranse else(h(h,a,(a+b)/2)if f(a)*f((a+b)/2)<0 else h(h,(a+b)/2,b)))(a,b))
metode 2
print((lambda r:lambda dx, a: r(r, dx, a))(lambda w, dx, s:s if abs(dx)<toleranse else w(w,-dx / 10,next(x for x in (np.arange(s,b,dx)if dx>0 else np.arange(s,a,dx))if f(x)*f(s)<0)))(0.1,a))
metode 3
print((lambda r:lambda a, b, n: r(r, a, b, n))(lambda h, a, da, n:a + da / 2 if da < toleranse else h(h,next(x for x in np.arange(a, a + da, da / n) if f(x) * f(x - da / n) < 0)-da/n,da/n,n))(a,b,6))
metode 4
print(min(((x,f(x)) for x in (a + (b - a) * random.random() for i in range(10000))),key=lambda x: abs(x[1]))[0])
metode 5
print((lambda r:lambda dx: r(r, dx))(lambda w, dx:"not found" if dx < 0.00001 else next((x for x in np.arange(a, b, dx) if abs(f(x)) < toleranse),w(w, dx * 0.1)))(0.1))
#esoteric-python message
I mean splitting Python specific tokens, making stuff harder to read.
h. you people might know this. how does one view the current call stack?
inspect.stack?

so you're telling me.. #help-candy was a wast of 5 minutes for me to type :|
i need to basically raise a signal up the call stack somehow
like an exception, minus the whole "function dying" part
#help-candy message if you want more specifics xD
how else would i ?
(did you read said message? it gives quite a bit of useful context)
yes
oki
i just. dunno anyway to do this. i dont want the command to just die. i figured maybe going up the call stack and finding the original command callback and setting a value in a dictionary maybe with the callbcak's hash, and check that periodically in the command?
My instinct would be to use nested co-routines instead of nested functions. Either that, or use exceptions and manage effects so that you can avoid side-effects from restarting any commands that threw an error.
Maybe not all that esoteric though, just complex.
if you're asking for help in #esoteric-python about code for a discord bot, you might want to reconsider what you're trying to do
stuff here shouldn't be going into production code
@sick hound
especially something that looks like xy problem
Lol yeah don't use esoteric code for things that require functionality
yeah i think is mostly for making as unreadable code as possible that functions
and idk how it handles kwargs
@formal sandal the mini dsl (Argument Clinic) unfortunately does not support variadic arguments, not yet at least.
>>> def god_no(func):
... return len(str(func))
...
>>> @god_no
... def innocent_function(inp):
... print(inp)
...
>>> print(innocent_function)
50
This is concerning and exiting.
i've never thought of using decorators this way
๐
>>> @len
... @str
... def innocent_function(inp):
... print(inp)
...
>>> innocent_function
50```
C:\Users\Aaay>python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> @exit
... def innocent_function(inp):
... print(inp)
...
<function innocent_function at 0x000001DC09101E18>
C:\Users\Aaay>```
!e
@print
@hex
@id
def f():
...
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
0x7faf2cae0dc0
yeah, its not a real feature
Ok, I didn't see a good reason for it, except ... something to add to F with people.
it could be useful I suppose
Yeah. There have been projects I've made where the first seveal lines of every function was checking the types of the inputs, but with python, it's possible to define objects, self is ~garunteed to be the type of the object in question, or a decendent or they wouldn't be calling that method to handle it...
@proper vault Well, you can do something like
@transform
def fun(arg: Convert(str, int)):
...
but good luck with making a typechecker like this
I think you meant you can say this (and it run):
arg = int(arg)```
and yes the typechecker hates it when I do that.
typing.Annotated should take care of type checkers
directed here from #internals-and-peps
I have this function and I was wondering whether there was some way to return instead of print
def fib(n):
for i in range(len(funclist := [])+n-1):
(i==(n-2) and print(funclist[i-1]() + funclist[i-2]())) or funclist.append(lambda i=i:funclist[i-1]() + funclist[i-2]() if i>1 else 1)
you can yield
that makes me use next() on the function tho
just the fibonacci number
the thing it prints
found a different/better way
def fibonacci(n):
return [(i==n-1 and (x:=(x[i-1] + x[i-2]))) or (i==0 and (x:=[])) or x.append(x[i-1] + x[i-2] if i>2 else 1 ) for i in range(0,n)] and x
def fib():
return [
d['b']
for d in [{}]
for d['a'], d['b'] in [(0, 1)]
for _ in range(n)
for d['a'], d['b'] in [[d['b'], d['a'] + d['b']]]
]
``` `:=` is overkill for fibbonaci numbers
bruh
that returns a list tho
you also returna list
oh no, you don't
ah, then the OG version
def fib(n):
return max(
d['b']
for d in [{}]
for d['a'], d['b'] in [(0, 1)]
for _ in range(n)
for d['a'], d['b'] in [[d['b'], d['a'] + d['b']]]
)
for assignement is realy nice here
since you can just a, b = b, a rather than having to have temporary variables and other such messes
I had a feeling overwriting my list with it's final result wasn't the best way to go
nor the inline list declaration
yeah, max/min is generally the way to get a single result from a comp
or next if you can filter out undersirable results
I was looking at reduce, but decided to do it in no-import python
reduce is also nice, but not builtin anymore
and the lambda nonsense you need to replace is not nice
better to just inline it into the mess
I guess
I did learn a lot about walrus, conditions and pythons datastructure writing it
Maybe you can [-1] instead of max?
constructing a pydantic model from a NamedTuple!
def model_from_type(t: Type) -> Type:
if isinstance(t, type) and issubclass(t, tuple):
hints = {
k: model_from_type(v)
for k, v in get_type_hints(t).items()
}
return type(t.__name__, (BaseModel,), {"__annotations__": hints}) # type: ignore
elif isinstance(t, type):
return t
elif "GenericAlias" in type(t).__name__:
return t.__origin__[tuple(model_from_type(a) for a in t.__args__)] # type: ignore
else:
return t
how do i get into making esoteric python code
how do i get into making esoteric python code
@sick hound start off simple. Slightly overcomplicated a small bit of code, and keep overcomplicating it
After that is done, convert your variable names into single letters
or multiple underscores
!e
from functools import reduce
from string import ascii_lowercase, ascii_uppercase
def to_upper(s):
return reduce(lambda x, ys: x.replace(ys[0], ys[1]), dict(zip(ascii_lowercase, ascii_uppercase)).items(), s)
print(to_upper('lowercase'))
@high garnet :white_check_mark: Your eval job has completed with return code 0.
LOWERCASE
why NOT?
But
But
.upper()
Altho to be fair this channel is only used for making overcomplicated shit
@terse mortar a few days back there was a trend of making ever more ridiculous versions of is_even
Yeah I saw
def _set(x):
consts = list(is_even.__code__.co_consts)
consts[1] = x
is_even.__code__ = is_even.__code__.replace(co_consts = tuple(consts))
def is_even(n):
r = True
if n == 0:
_set(r)
return r
_set(not is_even.__code__.co_consts[1])
return is_even(n - 1)```
like this
so I'm trying to start a new trend ๐
I secretly read this channel whenever there is a new message, hoping that one day I would be able to make a useful contribution to this channel
Also I'm convinced people are just adding underscores to their variable names just to make it look more complex
Also I'm convinced people are just adding underscores to their variable names just to make it look more complex
@terse mortar that's a valid form of esoteric Python
personally I'm a favour of huge chunks of parentheses/brackets
Like it looks amazing and I love it, but still why
Underscores are the pinnacle of Python. Chef's kiss.
Everything you're interested in has them.
The more the merrier.
from functools import reduce
def fib(n): return reduce(lambda xy,_: (lambda x,y:(y,x+y))(*xy), [(0,1)]*n)[1]
Decided to go back to my heart lambda, got it down in size pretty nicely: ```py
(lambda n:(o:=int(n/2))>n or''.join((m:=x/n3)(l:=y/n*3)0 or" #"[(m2+l2-1)3-m2l**3<0]+"\n"[x<o-1:]for y in range(o,-o,-1)for x in range(-o,o)))
oh that's funny, highlight.js sees or"..." as o and r"..."
What does lambda do? What is it different to define?
lambda is an expression and always gives the function <lambda> as __name__
isn't it like <lambda at 0x...> or whatever
>>> (lambda: None).__name__
'<lambda>'```
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
<lambda>
I understand it better in a functional programming language ๐
compared to many other languages, python lambdas are very long
the goal was to discourage lambdas
but it's really readable
It's kinda verbose imo
@echo abyss you just described the language itself
the goal was to discourage lambdas
oh really ? Why that ?
they are easy to abuse and there are very few actual reasons to use them
I've read some 2005 blog post by Guido van Rossum where he says that lambdas may be removed, is there any continuation to this idea?
Iโve actually come to use attrgetter and itemgetter from operator for many cases haha
lambdas are a nice feature but problematic
they are overused for something you could use a built-in function for
plus most of the time you should just use a single-line def statement
takes glasses off: lambda
puts glasses on: single line def
x**2 more like x * x
nekit $ python -m timeit -s "n = 13" "n ** 2"
200000 loops, best of 5: 789 nsec per loop
nekit $ python -m timeit -s "n = 13" "n * n"
5000000 loops, best of 5: 53.3 nsec per loop``` like come on
When did this channel become interested in performance?
Whenever it implies ridiculous optimizations that verge on writing custom bytecode
wdym verge
Flashbacks to add to both elements of tuple
yeah, I'm already searchin gfor that ๐
from hax import *
@hax
def add_tuples(a, b):
LOAD_FAST("a")
UNPACK_SEQUENCE(2)
ROT_TWO()
LOAD_FAST("b")
UNPACK_SEQUENCE(2)
ROT_THREE()
BINARY_ADD()
ROT_THREE()
BINARY_ADD()
ROT_TWO()
BUILD_TUPLE(2)
RETURN_VALUE()
bruh
I NEED HAX MODULE!
@formal sandal ```py
(lambda x: 10)
<function <lambda> at 0x7ff7de4d50d0>
On 3.8.6 - Arch Linux
!e
print(lambda x: 10)
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
<function <lambda> at 0x7f7b96b8cdc0>
not sure why that would depend on your OS ๐ค
well, I'm guessing you're on windows and getting <lambda>
!e
x = lambda x: x+10
print(x(10))
@red juniper :white_check_mark: Your eval job has completed with return code 0.
20
!e
class Brekception(BaseException):
...
class Brek:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
return exc_type is Brekception
def __call__(self):
raise Brekception
brek = Brek()
for i in range(30):
with brek:
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz", end=" ")
brek()
if i % 3 == 0:
print("Fizz", end=" ")
brek()
if i % 5 == 0:
print("Buzz", end=" ")
brek()
print(i, end=" ")
@formal sandal :white_check_mark: Your eval job has completed with return code 0.
FizzBuzz 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29
๐ฒ
as we all know, a pure function and a dict is pretty much the same thing

so I made a dict backed by a single function https://hastebin.com/nuxotuxixe.py
__iter__ was certainly fun to make
still not sure whether recursively traversing closures or that is better
bruh
the fact this doesnt work makes me sad
aiohttp.__call__ = lambda func: [func.__setattr__("cool_value", "cool"), func][-1]
@aiohttp
def some_function():
pass```
hm would it work with forbidden fruit or the other lib
@rugged sparrow did you ever put this on github?
My input arg splitting code gore! only took me a few hours to figure out
(supposed to be a weird netcat command)
@next flame i havent yet
but that should work with patchy (fyi __call__ as a dunder has a different argument pattern)
@next flame im not gonna put it on github but i just updated the copy on replit
@astral rover you would have to make <class 'module'> callable, not just aiohttp
so all modules would be callable
is patchy on pypi yet?
not yet
TypeError: can't set attributes of built-in/extension type 'module'
well that sucks
i think id need patchy
from patchy import *
@patch(ModuleType, '__call__')
def module_call(mod, args, kwargs):
return mod.__module_call__(mod, *args, **kwargs if kwargs is not Null else {})
not Null :P
that would make module(*args, **kwargs) call module.__module_call__(module, *args, **kwargs)
yah Null is a placeholder from patchy
oh right
its not actually Null
@next flame i prob wont put patchy on github until i can handle Exceptions properly
rn it just ignores exceptions (cause if it doesnt then ctypes shits itself)
i also want to get inheritance to work right
can type(name, bases, dict) set the metaclass of the type? i tried setting __metaclass__ in the dict but it doesnt work
class Foo(metaclass=type('', (type,), {})):
pass
ah sorry i meant the other way. can i make a type with type() and set its metaclass
ie type("Foo", (), {}, metaclass = Bar)
hello everyone. I have a problem I cannot solve. I have a string "something\\nsomething" and I would like to remove a single '\', so I'll have "something\nsomething", but when I try for example .replace, I enter a vicious cycle of escaping \ and quotes etc. I've tried with r'' as well.
I hope this problem is esoteric enough for this room.
this is not really for help at all, but try ```py
import codecs
codecs.escape_decode(string.encode('utf-8'))[0].decode('utf-8')
there's a single \ in that string
@vestal solstice In my "problem string", there are two slashes \ preceeding n. this stuff is so esoteric, it maggles with discord as well
@proper vault I'll try, thank you!
both your answers worked in python 3.9. the codecs and .replace('\n','\n')
thank you guys. this stuff annoyed me whole morning
two slashes + 'n' substituted by one slash + 'n' *
then it didn't work yet
it did on my cli
In [25]: rows[1][0].replace('\n','\n')
Out[25]: '1: 500\n1: 12 500'
"\n" has zero slashes not one slash
jesus these slashes on discord are ridiculous. what they are trying to escape here
if you do replace("\\\\", "\\") you'll get '1: 500\\n1: 12 500'
and that has one slash
what I did, is .replace('<twoslashes>n','<oneslash>n')
and it worked exactly as I wished it did
congrats
thank you. but it's your victory
@next flame I think I just cracked Exceptions within patched methods (I manually insert a raise opcode into the upper frame) but rn it replaces the first const in the upper object which can break things so I'm gonna see if I can inject the exception somewhere else.
Maybe directly into the frame's stack
new idea for an esoteric language
le crocodile = "hello";
les crocodiles = [ crocodile, crocodile ];
use french articles as datatypes
what do sigils do in raku?
signify general type (scalar, array, hash, function)
huh, just do that, but make it french
you could make collections female or something
then "single values" male
wait no that's dumb lol
make collections plural
lol
use french articles as datatypes
@formal sandal what would union types be
le bourgeoisie
@high garnet i don't know that much french ๐
le bourgeoisie
Lol won't le prolรฉtariat be the ppl who union?
Lol won't le prolรฉtariat be the ppl who union?
@fervent hull this is actually excellent
I approve
would the language also have values of different genders?
le x = 42;
la y = 50;
add(x, y); -- ok
le x = 42;
le y = 50;
add(x, y); -- ERROR!
import SameSexMarriage
le x = 42;
le y = 50;
add(x, y); -- ok
HEY what if it's platonic addition? ๐ก
We also have to consider gender fluidity of variables maybe
Petition to create a letter that both looks like a and e
HEY what if it's platonic addition? ๐ก
That'll raise error because platonic variables can't be combined together
That'll raise error because platonic variables can't be combined together
@fervent hull and why NOT
what's wrong with platonic pairing with benefits
hm I'm sure there's a type system somewhere that can encode all of this
They can be as close to one another as possible but not combined for platonic reasons
Unless I don't understand plantonics ๐ค
Petition to create a letter that both looks like
aande
Already exists รฆ
lรฆ x = 0t01221 # ternary because non binary
arguably this whole thing would be possible to implement in python grammar similar to braces.py
not really sure where I'd ask this question , but why isn't python a compiled language? what are the benefits of an interpreter, and the GIL?
I think the question is around default behavior with CPython
but the main point of an interpreter is fast development time
ah gotcha
aren't python modules compiled at execution to .pyc files?
yeah
Sorry I dont know a lot, im just curious
but thats still a lot faster than normal compiled langs
if python can be compiled, why would anyone want to use the interpreter?
Roslyn leading the charge in server-based compilers has been a godsend on the compiled lang front
sure faster development time, but once that is done, couldnt you then compile it?
if python can be compiled, why would anyone want to use the interpreter?
.pycare Python bytecodes
I've never really written an programs, so sorry about my ignorance
plus compiling wont speed it up that much
Which the Python interpreter reads and interprets into cpu instructions
(to native code using cython or something)
depending on the application
and bytecode compilation is cached anyways
how legitimate of a criticism is "python is slow bc its interpreted"? I hear it thrown around a lot, but it sometimes sounds more like tribalism
sure, it is slower than some other langs
but thats not its main selling point anyways
plus runtime speed isn't actually as important as you think it would be
It basically is tribalism. The benefits of compiling python with stuff like cython is only applicable in niche scenarios
a lot of the time, speed issues are either IO related or can be fixed by using c extensions
plus one of the reasons why a lot of compiled langs are fast is that they can make a lot of optimizations b/c static typing
but that doesn't work with python
because of python's dynamicism (? is that a word) it has to do runtime typechecks which slow down things greatly
dynamicness?
dynamicability?
On my OS android developer studio is writen in python. Think about that, an OS based on Java has a devkit that is based on something other than java...
also pypy will git compile and run your python code with almost no changes required. I'm not sure if there's a bytecode compile in between, or not.
Yes, it has bytecodes, and dis.dis() desplays the exactly the same for the first simple function I thought to throw at it.
Android studio is written in kotlin java and c++ according to wikipedia
what OS are you using that's based on java?
@next flame i solved the exceptions issue, ill prob put it on pypi later this week. I ended up having to alter the callers frame code and stack to raise the exception after the c_callback returns (cause the c_callback has to return)
How do you alter the caller's frame/code? I tried and it was only a copy not the active data.
You seem to have done a lot more in 300 lines than I useually hope for.
i still need to go thru and add more clear comments than # Black Magic, alters the callers frame code and stack to raise Exception after return lmao
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
011 | 10
Is their any way/code from which I can download profile picture of all my Instagram followers at once?
well, yes, definitely but that's against tos
@twilit grotto so like one can make a code? To automate the process? As far as i know instagram doesn't allow automation ๐ค๐
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.
Got it ๐๐ผ
!rule 3
!e ```py
from ctypes import *
import sys
all = ['goto', 'label']
def compute_jump(frame, label):
code, names = frame.f_code.co_code, frame.f_code.co_names
get_var = lambda i:{**frame.f_globals, **frame.f_locals}.get(names[i])
instructs = [*zip(code[::2], code[1::2])]
for idx, (inst, arg) in enumerate(instructs):
if inst == 106 and names[arg] == label and
isinstance(get_var(instructs[idx - 1][1]), Label):
return bytes([113, (idx - 1) * 2])
raise RuntimeError(f'could not find label [{label}]')
def replace_inst(code, inst, idx):
code_addr = id(code) + bytes.basicsize - 1
raw_code = (c_char * len(code)).from_address(code_addr)
orig, raw_code[idx:idx + 2] = code[idx:idx + 2], inst
return orig
overwritten = [None, None]
class Goto:
def getattr(self, label):
frame = sys._getframe(1)
idx = frame.f_lasti + 2
orig = replace_inst(frame.f_code.co_code, compute_jump(frame, label), idx)
overwritten[:2] = (orig, idx)
mul = getattr
class Label:
def getattr(self, name):
if all(overwritten):
frame = sys._getframe(1)
replace_inst(frame.f_code.co_code, *overwritten)
overwritten[:2] = (None, None)
goto = Goto()
label = Label()
i = 0
label .start
if i > 10:
goto .end
print(i)
i += 1
goto .start
label .end```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
011 | 10
^ goto .label in python
but why
*why not
it also supports computed labels like goto *str_var
and jumping into/out of loops
it also unpatches its injected JUMP_ABSOLUTE when it hits the label in case the original op was a jump target
Ooooh nice. I'm gonna have to try and work out how that's working at some point ๐
has a context-aware self ever been discussed in PEPs?
anyone want to try code golfing this question? #algos-and-data-structs message
has a context-aware
selfever been discussed in PEPs?
@fervent sonnet what do you mean by a context awareself?
came up with these two
def solution(S):
S = S.split("\n")
h,r = S[0],S[1:]
return "\n".join(x for x in [h]+[",".join(v for v in s.split(",") if v != "NULL") for s in r] if x)
def solution2(S):
return S.replace(",NULL", "").replace("\nNULL", "\n")
def solution3(S):
return "\n".join(x for x in [",".join(v for v in s.split(",") if v != "NULL") for s in S.split("\n")] if x)
@bitter iris it's hard for me to describe, but basically in expressions, that "this" is referenceable
a = {'k': 'v'}
a['k'] = self + 'etc'
# ^ `self` would be `a['k']`
@fervent sonnet that's unlikely due to the existence of assignment operators like +=
I'm not sure how that would be a blocker
@bitter iris it's hard for me to describe, but basically in expressions, that "this" is referenceable
a = {'k': 'v'} a['k'] = self + 'etc' # ^ `self` would be `a['k']`
@fervent sonnet no no no no
yes yes yes yes ๐
a['k'] = self + 'etc'``` aka ```py
a['k'] += 'etc'``` :P
self is definitely not the name to use for it
Some of that is already built into the language, if you want to write a seperate __add__() and __radd__() and __iadd__() you can. I'm not sure if there is a cannonical way for you to check if you're stored in a dict and are getting +='ed instead of getting +'ed and then assigned elsewhere.
you can definitely dis.dis your calling frame's code and try to guess.
@proper vault no, but it expressed what I was looking for the best
well, python is such a dynamic language that allows you to patch into interpreter startup (it actually doesn't allow and discourages, but honestly who cares in this channel). So you can write a very simple AST transformer to replace every self in assign context and replace it with the target. Of course, don't forget that assignment targets is a list, a = b = c (a, b are the targets!)
Feel free to write python, as you'd like. That is one of the features that I really like to abuse ๐
ain't nobody got time for that. I'm struggling to maintain three different apps at work as-is ๐ฉธ
๐
ain't nobody got time for that. I'm struggling to maintain three different apps at work as-is ๐ฉธ
@fervent sonnet there is always time to smuggle some new syntaxes into python!
anyone good with real time image learning in opencv
@sick hound probably wrong channel mate
check the channel description ๐
โณ
@fervent sonnet I made a horrible this implementation
but it will have to be changed from globals to builtins to work across modules, I suppose
thread starting at <#esoteric-python message>
@formal sandal you monster
There really should be a computer vision channel
@sick hound I'm bad with image learning in opencv
but that is better than nothing
also CV is automatically esoteric and wierd
so maybe it should be here
computer vision is a legitimate use case for python though
computer vision is the MOST legit
computer vision is god
openCV is pretty annoying though
unlike the other things in this chat, like goto
I suppose this is where the PEP-8 resistance hangs out
does cv not fall under data science?
I thought it was like ML but correct me if I'm wrong
@final terrace
i thought so too
There really should be a computer vision channel
@final terrace #data-science-and-ml
CV is not data science
how is it not
isn't it machine learning
CV is not data science
@final terrace the name of the channel is #data-science-and-ml, but it includes machine learning, which includes computer vision
and also
"related topics"
CV is its own field completely. You can use it with AI/machine learning but making a CV program is like neuroscience almost
neuroscience for computer vision?
how do you do computer vision without ml?
artificial neuroscience ๐
they're not called artificial neural networks for nothing (this is a joke)
ok that was stupid, not neuroscience
but you are effectively simulating functions of the visual cortex, even if you don't realize it
it's a science of pattern recognition... shit... maybe it is data science
yeah
you use your ML model to guess what stuff is after you feed it a million images
I wouldn't necessarily call computer vision data science, but it is on topic for the #data-science-and-ml channel
but also CV does not really imply ML because you can just manually tweak the algorithms to do basic stuff without any training data
if you are using shapes you don't really need ML at all
basic shapes
It just feels like its own thing. It's also a big thing in automation/testing
It just feels like its own thing. It's also a big thing in automation/testing
@final terrace you could say NLP is its own thing
and in the working world, for example, yes, you would not be able to pull a rando data scientist off the street and thrust them into a CV engineer position
but for the purposes of our little server...all that goes in #data-science-and-ml
I mean, honestly, we don't really have that much people in DS, let alone CV
can someone help me
@strange junco think you want #โ๏ฝhow-to-get-help?
this is a channel for demonic Python and you probably don't want that
alr my bad
sorry I will shut up, but honestly CV in its most common usage belongs 50% in automation category
sorry I will shut up, but honestly CV in its most common usage belongs 50% in automation category
@final terrace fair enough
I wouldn't know because I encounter CV only in ML
in that case, if you want to talk about the CV implementation
perhaps #algos-and-data-structs?
๐คทโโ๏ธ
or maybe not really the right server at all
what do you mean
automation category actually
think aimbots, game bots, JS canvas automation + selenium
yeah, like I said
#data-science-and-ml is the closest we have to that
or for testing purposes, #unit-testing
nope
I'm not
like I'm just answering your question from the perspective of the server
for example, #async-and-concurrency is called "async", but it also covers parallelism
and, yes, I do understand that a ton of CV doesn't involve ML/DL
but again, if you're asking "where to discuss CV", I would say #data-science-and-ml is the best place.
ok. Yeah CV is just really interesting. It covers many categories. I'm not really asking anything
and if you're asking "do you think CV is part of DS"...I think we went through that ๐
but my point stands. They should totally make an OpenCV channel because it's a field of its own if you look at coursera and such there are entire courses dedicated to it and communities
and since python is a huge part of the userbase it would be a good addition here
but my point stands. They should totally make an OpenCV channel because it's a field of its own if you look at coursera and such there are entire courses dedicated to it and communities
@final terrace yes, but Coursera is Coursera (also this is off topic I think #community-meta would be a good place to suggest that)
and I think the PoV of the server owners is "are there enough people who want to talk about it to create a channel dedicated to it?"
and honestly I very rarely see OpenCV-specific questions
very
like once a week or something
I suggested it, thanks
I apologise to the lord of esoteric Python
@high garnet consider you are an active user in this channel, you got a lot more to apologize for them going slightly off topic lol
When I see esoteric I think of this Esolang
++++++++++[>++++++++++<-]>--.++++.
I've made an interpreter in Python
so i just found a way to manipulate the bytecode of the code of Module A when Module B is imported (from within Module B)
wonder what terrible things i can do with that.
macros 
Sadly I can't quite manipulate ast yet, my method happens after compilation
But as long as it compiles to valid byte code then you can mutate that
So ... can you decorate an import?
Wdym by decorate @vague cairn
I think he means applying some function to imported module object with decorator syntax
like
@decorate
import xyz
--- v ---
xyz = decorate(__import__("xyz"))
sadly that is invalid syntax but if you did something like py decorate_func:decorate import xyz
then i could write a bytecode patcher that transforms it
@rugged sparrow How would you go about transforming that?
By mutating the byte code of the module that imported my code
How do you get the byte code of a module?
don't know if it counts as esoteric, but I can finally use my crazy new language in the browser!
(a Python program transpiles it to JS)
@sick hound by traversing the stack frames
People in #python-discussion were talking about how you would go about solving this challenge:
The objective is to make a function that returns x//10, but some operators arenโt allowed, you also arenโt allowed to have any of, โeiouโ in the code
Full details are in webpage above
Iโll give it a try in the morning
Yeah. The best we could come up with is some way to use bitshifting and lambda.
For example
x>>y is the same as x//(2**y)
The problem is that you can only use >> with integers.
The input value would be an integer.
But bit shifts can only multiply/divide by a power of 2.
But bit shifts can only multiply/divide by a power of 2.
@patent fulcrum Yeah and we need to divide by 10 which is not a power of 2.
Right. So there must be some other trick involved.
mhmm
I see no restriction in the problem about using only one variable.
with only 1 variable it seems hard
@crimson zinc Not quite what they're saying. They are saying that the only vowel you can use is "a".
Just certain letters and characters are disallowed.
No need to call input() to solve the problem.
I have an idea too but I have to think about it a bit more.
input has other vowels
@crimson zinc Yesinputhasianduso you can't use it.
@crimson zinc Tried using an accented "e". Did not work
>>> def func():
rรจturn 2
unless thats an exception, its gotta be a lambda
@crimson zinc Can you give any hints, please?
I accidentally found the code you mentioned while looking for information. No way would I have ever figured that out without extensive pencil and paper manipulations.
Alright ty
heres whats available as a starting point 'abs', 'all', 'any', 'chr', 'hasattr', 'hash', 'map', 'max', 'str', 'vars'
This is more of a math challenge than a Python challenge.
Do you guys think that the difficulty is "Elementary"?
The Python is elementary. The mathematical knowledge is not. Well, it is, but you would have to work through it.
hmm
you can make arbitrary strings with chr and concatenation
Using lambda and bit shifts (<< and >>) was the right idea. But you would need to work out a lot of math to find the right sequence of shifts.
Yeah. Basically just how can you find the answer using only addition, subtraction, multiply by a power of 2, and integer divide by a power of 2.
This seems like something you can probably solve by twiddling around in desmos
Just finding a function in the right form and then fuzzing around with constants
I took a different path
_=vars()
devsaan = lambda x: vars(_["\137\137\142\165\151\154\164\151\156\163\137\137"])["\145\166\141\154"](f"\137\137\151\155\160\157\162\164\137\137\50\47\157\160\145\162\141\164\157\162\47\51\56\146\154\157\157\162\144\151\166\50{x}\54\61\60\51")
took a lot of fiddling to get that in its final form
I think thats a much more fun solution than a mathy approach
its basically
eval(f"__import__('operator').floordiv({x},10)")
``` but with extra steps
the biggest hurdle was figuring out how to get access to eval
my approach was basically vars(vars()["__builtins__"])["eval"]
but vars() is basically just locals(), and I needed the globals, so I save it first with _=vars()
ah, actually, I wasnt paying much attention to golfing it, I could use int.floordiv instead
Given that you can encode arbitrary command why not just encode x//10?
you know, thats fair
I dont do much golf
or any, actually
_=vars()
devsaan=lambda x:vars(_["\137\137\142\165\151\154\164\151\156\163\137\137"])["\145\166\141\154"](f"{x}\57\57\61\60")
125 characters
You can put in the characters that are not banned to shorten it
no need to use octal escapes for "allowed" chars
ah, good catch
_=vars()
devsaan=lambda x:vars(_["__b\165\151lt\151ns__"])["\145val"](f"{x}\057\05710")
``` 87 chars
Also you can get rid of the first 0 in \057. The second \057 has to be complete I believe
ah, yep
_=vars()
devsaan=lambda x:vars(_["__b\165\151lt\151ns__"])["\145val"](f"{x}\57\05710")
``` 86
davasaan = lambda x: x.__class__("0" + str(x)[:-1])
no dot allowed
^
Oh right
whoops, I got the name wrong
_=vars()
davasaan=lambda x:vars(_["__b\165\151lt\151ns__"])["\145val"](f"{x}\57\05710")
``` 87 chars
davasaan=lambda x: getattr(x, "__class__")("0" + str(x)[:-1])
you're basically restricted to [] for getting stuff
which is what led me to vars
taking your approach
_=vars()
davasaan=lambda x:vars(_["__b\165\151lt\151ns__"])["\151nt"]("0"+str(x)[:-1])
``` 86
shaved a character from eval to int
A recursive lambda ought to do this with more ease
Here's an ungolfed version
f=lambda x:(x>=0 and f(x-10)+2)-1
fancy, but its supposed to be practical up to 2 billion
implementation dependent => no need to worry about it ๐
all of my python programs are run on an ideal turing machine
Speaking of, can the input and output of the function be church numerals? The challenge doesn't specify that. :v)
Although combinators are unfortunately pretty verbose in python, hitting the 300 char limit
davasaan=lambda x:(1).__class__(str(x)[:-1])
```?
Or replace those brackets with a trailing space for one less character.
Or x instead of (1) actually.
Oh, will that break on 0?
on any 1-digit number it will give a ValueError
davasaan=lambda x:x.__class__(str(x)[:-1]or 0)
I'm on mobile so I haven't either.
A quick test, and good thing it doesn't need to work on negative numbers.
Those are entirely valid criticisms.
You can use vars() to get builtins tho
going the int() route, I havent been able to find anything better for the param than "0"+str(x)[:-1]
!e py d=lambda n,v=vars(),k=lambda w,x:sum(map(lambda k:[k],w),[])[x]:(q:=vars(v[k(v,-2)]))[k(q,64)]('0'+str(n)[:-1]) print(d(100))
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
10
no "u"
ah damn
davasaan=lambda x:vars(x)['__class__']('0'+str(x)[:-1])```
since int ignores leading 0s apparently (i tested it)
oh but actually this doesn't work because you can't vars an int ._.
hmm
davasaan=lambda x,v=vars():vars(v['__b\165\151lt\151ns__'])['\151nt'](f'0{x}'[:-1])``` i think this works
Hello people. I failed turning a modest for loop into a one liner:
dispose = set()
for index, item in enumerate(prosodies, 1):
if item in dispose:
return index
dispose.add(item)
I am looking for the index of the first duplicate in prosodies (the "1" start is irrelevant).
This is what I got so far:
next(filter(lambda enumeration: enumeration[1] in dispose, map(lambda x: dispose.add(x[1]), enumerate(prosodies, 1))))[0]
... and naturally it fails because I am returning the result of dispose.add(x[1]) in the lambda ... among other reasons.
Suggestions?
Heh, I found a way but it sucks ...
dispose = set()
def check_add(couple):
a = couple[1] in dispose
dispose.add(couple[1])
return a
return next(filter(lambda i: check_add(i), enumerate(prosodies, 1)))[0]
I don't like the "a" assignment on line three. Any improvement's welcome.
if couple[1] not in dispose:
dispose.add(couple[1])
return False
return True```ig something like this might be slightly clearer in terms of removing the "a" assignment
Pretty sure you can do stuff with operators too but idk enough about them
also, why invoke lambda if you have defined a function?
@paper bloom using lambda is faster than if you create a new function
but they already created the function...
also, lambdas and functions are the same speed
lambdas are shorter to write sure, but they're also harder to read if you make them complicated
but I guess that's by #esoteric-python exists
!e ```py
import dis
def foo(): return 10
bar = lambda: 10
print(dis.dis(foo))
print(dis.dis(bar))
@paper bloom :white_check_mark: Your eval job has completed with return code 0.
001 | 3 0 LOAD_CONST 1 (10)
002 | 2 RETURN_VALUE
003 | None
004 | 4 0 LOAD_CONST 1 (10)
005 | 2 RETURN_VALUE
006 | None
if lambdas were faster than defed functions, then CPython could make a normal function an alias for creating a lambda and assigning it to a name
as an optimization

dispose = set()
for index, item in enumerate(prosodies, 1):
if item in dispose:
return index
dispose.add(item)
(lambda r=[None]:({*iter(lambda s=set(),i=iter(prosodies):[ r[0] in s for r[0] in [next(i) ] ), [True]}, r)[-1]
```should work, though I did not test it.
Quick question,
How would you type
from typing import *
from ctypes import *
def func(*pointers: ...):
pass
POINTER(T) does not work
One thing I can do is use TypeVar, like PointerT = TypeVar("PointerT"), but is there any better way to do it?
Hey all, so bit of a stupid question. But I am creating a (right now just testing out making it) shell for a program I am writing and part of this is having builtin commands. I was wondering if anyones ever built a shell of sorts with builtins and used something like argparse to parse arguments for your builtin commands? Currently I am getting it to catch but its immediately exiting my program upon parsing the arguments instead of returning control back to the loop.
wrong channel
I've used argparse once or twice, but it's more for a command line interface (someone else's shell, your command just accepts arguments), and less for a read parse evaluate loop. I know there are libraries for parsing Python-like code, but I've never used them.
@flint cradle Well, you could write your own little parser for commands.
foo -abc --bar baz --xxx "hello world"
=> Command("foo", frozenset({"a", "b", "c"}), {"bar": "baz", "xxx": "hello world"})
you could write your own parser or use an existing parser generator library (like lark)
does shlex do that?
uhh... yes, probably ๐
but argparse should also work
wait
Use both
shlex to convert to argv
argparse to parse argv
dispose = set() for index, item in enumerate(prosodies, 1): if item in dispose: return index dispose.add(item)(lambda r=[None]:({*iter(lambda s=set(),i=iter(prosodies):[ r[0] in s for r[0] in [next(i) ] ), [True]}, r)[-1] ```should work, though I did not test it. @proper vault Thanks, hadn't noticed the answer. It looks like an intricate puzzle. Will have a good look at it.
also, why invoke lambda if you have defined a function?
@paper bloom Absolutely. I used the defined function in lieu of the lambda. That was a left over from previous attempts.
@formal sandal @next flame so I mostly seem to have gotten it. I just had some really stupid programatic issues going on. Part of one is passing the entire input from my "commandline" instead of splitting out the command and the args, passing the args as a list caused it to work properly. If I run acommand with everything as needed, it automatically will parse it all and return control to my shell. However invoking the help menu of the command causes it to yeet my shell. I suspect because usage of -h causes a sys.exit() I'd imagine.
Got it. Just had to catch a call for sys.exit
Still some issues but I can figure it out from here.
is there any way to get the actual ctypes type from a Structure field
since apparently it auto coerces to a normal python type
Hey guys, I was wondering if you could execute arbitrary code from ..., which is to say get to eval (and also chr, basically getting to __builtins__), using only attributes of ... and its attributes, and so on.
For instance, you can get 1 as ....__eq___(...), and type as ....__class__.__class__
....mro()[-1].__subclasses__ gets you quite a few types, so you could manually construct a function from bytecode, but I don't remember the proper way to get built ins.
you can get an importer from object.__subclasses__
Hum... thanks, but where's the importer in that mess?
>>> len(....__class__.__mro__[-1].__subclasses__())
749
``` Yep, it's a mess
I'll look at it again later, but thanks for the help
How does it choose the indentation for the python else: passparts?
it doesn't choose. I do.
It was half a parabola but then I had to return after all the loops, so I finished the parabola with no-ops
if Python didn't have significant whitespace, you could even put comments inside the parabola
Now we need a script that takes an increasing function f(n) as input and applies the appropriate level of indentation [f(n) spaces for n-level indents] to a python program.
The only risk is that you mangle the AST.
Somehow.
something like ....__class__.mro()[1].__subclasses__()[132].close.__globals__["__builtins__"]["eval"]("2+2")
except replace all the string literals with slicing docstrings
oh wait we dont have numbers
uh just sum True a bunch of times to get ints
Hi guys,
In [68]: _l= ....__class__.mro()[1].__subclasses__()[7]
In [69]: _l(_l(....__class__.mro()[1].__subclasses__()[132].close.__globals__.values())[7].values())[19]
Out[69]: <function eval(source, globals=None, locals=None, /)>
!e py print(....__class__.mro()[1].__subclasses__()[-1].__call__.__globals__['__builtins__']['eval'])
oh wait -1 would be easier
yea
!e py print(....__class__.__base__.__subclasses__()[True-True-True].__call__.__globals__['__builtins__']['eval'])
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
<built-in function eval>
strings are constructed from small snippets of docstrings, indexed using integers constructed with boolean addition, constructed with ....__eq__
!e py print([*[*....__class__.__base__.__subclasses__()[True-True-True].__call__.__globals__.values()][((True+True+True)*(True+True))+True].values()][(((True+True+True)*(True+True+True))*(True+True))+True])
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
<built-in function eval>
!e ```python
#!/usr/bin/env python3
one = ....eq(...)
two=one+one
three=two+one
four=three+one
five=four+one
twentyfive=fivetwo
seven= five+one+one
_16=fourtwo
nineteen=_16+three
_499 = twentyfive * five * four - one
_407 = fivefive_16+seven
int_doc=....class.mro()[1].subclasses()[4].doc
eval_str = int_doc[_499]+int_doc[_407]+int_doc[_499] # "2+2"
_l= ....class.mro()[1].subclasses()[7]
print(_l(_l(....class.mro()[1].subclasses()[one.neg()].call.globals.values())[seven].values())nineteen)
@next flame :white_check_mark: Your eval job has completed with return code 0.
4
wtf?
Lol
should the arithmetic ops explicitly use the dunders?
....__ne__(...).__invert__() is -1, if that helps with golfing.
....__eq__(...).__neg__() is shorter, I suppose.
Indeed, it looks like this will not help.
!e print(....class.mro()[1])
@thin trout :white_check_mark: Your eval job has completed with return code 0.
<class 'object'>
Noiiice
@naive roost :white_check_mark: Your eval job has completed with return code 0.
001 | 3.8.0 (default, Nov 23 2019, 05:49:00)
002 | [GCC 8.3.0]
>>> ....__class__.__base__.__subclasses__()[....__eq__(...).__neg__()].__call__.__globals__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'method-wrapper' object has no attribute '__globals__'
``` hum... I don't know why it doesn't work that way, though
!e ```py
print(....class.base.subclasses()[....eq(...).neg()])
@frigid wharf :white_check_mark: Your eval job has completed with return code 0.
<class '_sitebuiltins._Helper'>
!e py print(....__class__.__base__.__subclasses__()[....__eq__(...).__neg__()].__call__)
@frigid wharf :white_check_mark: Your eval job has completed with return code 0.
<function _Helper.__call__ at 0x7f4287e92160>
!e ```py
print(....class.base.subclasses()[....eq(...).neg()].call.globals)
@frigid wharf :white_check_mark: Your eval job has completed with return code 0.
001 | {'__name__': '_sitebuiltins', '__doc__': '\nThe objects used by the site module to add custom builtins.\n', '__package__': '', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f0153b23d60>, '__spec__': ModuleSpec(name='_sitebuiltins', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7f0153b23d60>, origin='/usr/local/lib/python3.8/_sitebuiltins.py'), '__file__': '/usr/local/lib/python3.8/_sitebuiltins.py', '__cached__': '/usr/local/lib/python3.8/__pycache__/_sitebuiltins.cpython-38.pyc', '__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <built-in function __import__>, 'abs':
... (truncated - too long, too many lines)
Full output: https://paste.pythondiscord.com/azofayazoh.txt
>>> print(....__class__.__base__.__subclasses__()[....__eq__(...).__neg__()].__call__)
<method-wrapper '__call__' of type object at 0x1bc4d30>
``` yep, that's a problem
its because the layout of object subclasses is completely dependent on interpreter version/the startup order
I think the problem is more about the method-wrapper than it is about the object subclasses layout
well if the class at the end of object.__subclasses__ has a user defined call then it will have a __globals__
if we can do a loop (idk the limitations) then we can do [*[c for c in object.__subclasses__() if type.__sizeof__(c) > type.__sizeof__(type)][-1].__dict__.values()]
which will get us a guarenteed user defined class
!e ```py
print([*[c for c in object.subclasses() if type.sizeof(c) > type.sizeof(type)][-1].dict.values()][2])
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
<function _Helper.__repr__ at 0x7f14172d70d0>
!e py print([*[c for c in object.__subclasses__() if type.__sizeof__(c) > type.__sizeof__(type)][-1].__dict__.values()][2].__globals__['__builtins__'])
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <built-in function __import__>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'breakpoint': <built-in function breakpoint>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <b
... (truncated - too long, too many lines)
Full output: https://paste.pythondiscord.com/lonudabana.txt
I'm not sure you can do the comprehension, though
!e ```python
(....class.mro()[....eq(...)].subclasses()[(((....eq(...)+....eq(...)+....eq(...)+....eq(...))+....eq(...))+....eq(...)+....eq(...))])( (....class.mro()[....eq(...)].subclasses()[(((....eq(...)+....eq(...)+....eq(...)+....eq(...))+....eq(...))+....eq(...)+....eq(...))])(....class.mro()[1].subclasses()[....eq(...).neg()].call.globals.values() )[(((....eq(...)+....eq(...)+....eq(...)+....eq(...))+....eq(...))+....eq(...)+....eq(...))].values())(((....eq(...)+....eq(...)+....eq(...)+....eq(...))+....eq(...))*(....eq(...)+....eq(...)+....eq(...)+....eq(...)))
@next flame :white_check_mark: Your eval job has completed with return code 0.
4
you'll need to use int.__add__ instead of +
#!usr/bin/env python3
import subprocess
import sys
def gen_int(i):
if i == 0:
return "_0"
if i >= 25:
res = f"_25.__mul__({gen_int(i//25)})"
else:
res = "_0"
i = i % 25
if i >= 5:
res += f".__add__(_5.__mul__({gen_int(i//5)}))"
i = i % 5
res += ".__add__(_1)" * i
return res
docs = "....__class__.mro()[1].__subclasses__()[{}].__doc__"
chars = {}
for i in range(100):
doc = eval(docs.format(i))
if isinstance(doc, str):
for j, c in enumerate(doc):
if c not in chars:
chars[c] = (i, j)
def gen_char(c):
try:
i, j = chars[c]
assert eval(gen_int(i), {"_0": 0, "_1": 1, "_5": 5, "_25": 25}) == i, i
assert eval(gen_int(j), {"_0": 0, "_1": 1, "_5": 5, "_25": 25}) == j, j
return f"_s[{(gen_int(i))}].__doc__[{gen_int(j)}]"
except KeyError:
return f"_b[14]({gen_int(ord(c))})"
inp = sys.stdin.read()
res = "+".join(map(gen_char, inp))
with open("template.py") as f:
template = f.read()
template = template.replace("GENERATED", res)
stdout = subprocess.run("cpp", check=True, input=template.encode(), stdout=subprocess.PIPE).stdout
print("".join(line for line in stdout.decode().split("\n") if line and not line.startswith("#")))
#define _0 ....__ne__(...)
#define _1 ....__eq__(...)
#define _4 _1.__add__(_1).__add__(_1).__add__(_1)
#define _5 _4.__add__(_1)
#define _7 _5.__add__(_1).__add__(_1)
#define _20 _5.__mul__(_4)
#define _25 _5.__mul__(_5)
#define _s ....__class__.mro()[_1].__subclasses__()
#define _l _s[_7]
#define _b _l(_l(_s[_1.__neg__()].__call__.__globals__.values())[_7].values())
_b[_20](GENERATED)
that looks a lot like cheating
most of that is just generating the string to exec
!e
import networkx
@zealous widget :warning: Your eval job has completed with return code 0.
[No output]
well, now i know
how do you kill a multithread?
def get_proxies(amount):
N_THREADS=50
if amount < 50:
N_THREADS = amount
with requests.Session() as session:
with ThreadPoolExecutor(max_workers=N_THREADS) as executor:
proxies = scrape_proxies(session, executor, amount)
executor.shutdown(wait=False)
return proxies
.shutdown(wait=False) seems to not work. It stops on that line.
nvm forget my question im switching to nice easy async
you dont kill a thread
does anyone have the link to the oneliner lambda quicksort?
quicksort = lambda a:(lambda f,a:f(f,a))(lambda f,a:a if len(a) < 1 else f(f, [x for x in a[1:] if x <= a[0]])+[a[0]]+f(f, [x for x in a[1:] if x > a[0]]),a)
```I do not, but I can make one
thanks
In JS there's a library that provides a decorator that makes functions optionally curried. It looks like that:
const add = ((x, y) => x + y).autoCurry()
add(4) // y => 4 + y
add(4,5) // 9
add(4)(5) // 9
add(4)()(5) // 9
And it allows it to do with any number of arguments. Is that possible in python?
assuming your function has a fixed number of positional args, yeah
not too hard to come up with a class that can wrapp it with a call that stores the args and returns itself, and executes when it has all of them
How can I get argument count of a function?
look into inspect.getfullargspec
inspect has all kinds of tools for that kind of introspection
class curried:
def __init__(self, fun):
self.fun = fun
self.args = []
def __call__(self, *args):
self.args.extend(args)
if self.fun.__code__.co_argcount <= len(self.args):
return self.fun(*self.args)
return self
def curry(fun):
return lambda *args: curried(fun)(*args)
@curry
def xyzzy(a, b, c):
return a + b - c
It kinda worked
@rugged sparrow can you apply decorator to all functions in the module?
@echo abyss that curry function is entirely redundant
@mint holly call your function two times
ah
Apparently builtins do not have code
import inspect
class curried:
def __init__(self, fun, args=None):
self.fun = fun
self.arg_length = len(inspect.getfullargspec(fun).args)
self.args = args or ()
def __call__(self, *args):
new_args = self.args + args
if len(new_args) == self.arg_length:
return self.fun(*new_args)
return type(self)(self.fun, new_args)
probably want to be more thoughtful with the arg_length check, but you get the idea
@echo abyss you could loop over everything in mod.__dict__ after importing it, or you may be able to use import hooks to do it
It's sad you can't get arguments for operator builtins ๐
sure you can
Didn't worked for me, I'm on python 3.6.9 tho
hmm, seems its >= 3.7
I wasnt aware of that difference
speaking of 3.7 features I was unaware of
thats pretty neat
Is there any silly or esoteric pip modules out there?
but why
five
Fun fact this library is why six is six and not five
AFAIK it (the JS five package) is kind of a mockery of small NPM packages
like this one: https://www.npmjs.com/package/is-number
it's funny until you see that Webpack transitively depends on it 4 times
This one is more funny, though: https://www.npmjs.com/package/is-not-number
yup
Fun fact this library is why
sixissixand notfive
@thin trout wait, really?
I thought it was 2 * 3
The name, โsixโ, comes from the fact that 2*3 equals 6. Why not addition? Multiplication is more powerful, and, anyway, โfiveโ has already been snatched away by the (admittedly now moribund) Zope Five project.
oh, interesting!
Well, 6 is 2 and 3. If had to be 2 or 3 then 5 would be better. Well, finally the weird CS math paid off
i saw a quicksort version
mergesort = lambda a: (lambda f,g,h,a: f(f,g,h,a))(lambda f,g,h,a: a if len(a)<2 else (lambda x: h(f,g,h,x[0],x[1],[]))(g(f,g,h,a)), lambda f,g,h,a: (f(f,g,h,a[:len(a)//2]),f(f,g,h,a[len(a)//2:])), lambda f,g,h,a,b,c: c+a if b==[] else c+b if a==[] else h(f,g,h,a[1:],b,c+[a[0]]) if a[0]<b[0] else h(f,g,h,a,b[1:],c+[b[0]]), a)```
ngl i thought i was in #discord-bots and i was, uhh, rather concerned.

