#esoteric-python
1 messages · Page 132 of 1
is it really a lambda if it has a name though...
i need to use the function in other places
copy paste it then
no
Three layers of parentheses that actually do something with the values in them is enough esoteric for me
I was going to comment that "well you can't exactly have an unnamed recursive lambda" but combinators are a thing
fixpoint go brrrr
What's that and can u give an example on how to use it
@robust bramble how would i do the things u told me
give an example code of using lambda + conprehension plz
!e
import dis
dis.dis("""somedict, otherdict = {}, {}
{**somedict, **otherdict}
{**somedict, "t":1, "u":5}""")
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 BUILD_MAP 0
002 | 2 BUILD_MAP 0
003 | 4 ROT_TWO
004 | 6 STORE_NAME 0 (somedict)
005 | 8 STORE_NAME 1 (otherdict)
006 |
007 | 2 10 BUILD_MAP 0
008 | 12 LOAD_NAME 0 (somedict)
009 | 14 DICT_UPDATE 1
010 | 16 LOAD_NAME 1 (otherdict)
011 | 18 DICT_UPDATE 1
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/kicipihuse.txt?noredirect
DICT_MERGE is used when unpacking into kwargs
!e
import dis
dis.dis('test(**{1:2}, **{1:2})')
@woven bridge :white_check_mark: Your eval job has completed with return code 0.
001 | 1 0 LOAD_NAME 0 (test)
002 | 2 LOAD_CONST 2 (())
003 | 4 BUILD_MAP 0
004 | 6 LOAD_CONST 0 (1)
005 | 8 LOAD_CONST 1 (2)
006 | 10 BUILD_MAP 1
007 | 12 DICT_MERGE 1
008 | 14 LOAD_CONST 0 (1)
009 | 16 LOAD_CONST 1 (2)
010 | 18 BUILD_MAP 1
011 | 20 DICT_MERGE 1
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/inuhikuyiz.txt?noredirect
!e
def test(**kwargs):
pass
test(**{1:2}, **{1:2})
@woven bridge :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | TypeError: __main__.test() got multiple values for keyword argument '1'
!e
import sys
print(
sorted(map(
lambda i: (len(i), i),
(m.__name__ for m in sys.modules.values())
))
)
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
[(2, 'io'), (2, 'io'), (3, 'abc'), (3, 'sys'), (4, '_abc'), (4, '_imp'), (4, 'time'), (5, 'posix'), (6, 'codecs'), (7, '_codecs'), (7, '_signal'), (7, '_thread'), (7, 'marshal'), (8, '__main__'), (8, '_weakref'), (8, 'builtins'), (9, '_warnings'), (9, 'encodings'), (9, 'zipimport'), (15, 'encodings.utf_8'), (17, '_frozen_importlib'), (17, 'encodings.aliases'), (26, '_frozen_importlib_external')]
who ping
that was me
yw
is 1 even a legal kwarg
nah, that's the next thing it'll complain about 🙂
interestingly enough, in 3.8 and below the string check came first
using this apparently slow op that is now gone https://docs.python.org/3.8/library/dis.html#opcode-BUILD_MAP_UNPACK_WITH_CALL
in 3.8 and below the string check happens during code eval https://github.com/python/cpython/blob/3.8/Python/ceval.c#L4124
in 3.9 and above it happens during locals initialization
https://github.com/python/cpython/blob/4575c01b750cd26377e803247c38d65dad15e26a/Python/ceval.c#L5442
oh nvm hold on, actually it's only 3.10 that moves it into locals initialization. so then why does the duplicate check happen before the string check in 3.9?
whatever, too tired for this rabbithole atm 😅
lol, so it used to type check first and now it type checks some other time (at least after checking for duplicate keywords)
i wrote this function, thinking it might be useful, but i don't have a use for it atn
!e
import sys; from importlib import import_module
from textwrap import dedent
def eval_key(key: str, cut_ns: int=0):
parts = key.split("."); module, rest = None, ""
for i in range(len(parts)-1, 0, -1):
module_name = ".".join(parts[0:i])
try:
module = import_module(module_name)
except ImportError:
pass
if module is not None:
rest = ".".join(parts[i:]); break
while cut_ns > 0:
rest = rest.rpartition(".")[0]; cut_ns -= 1
return eval(rest, vars(module))
print(dedent(f'''
{eval_key("sys.prefix")=}
{eval_key("pathlib.Path.absolute")=}
{eval_key("importlib.metadata.distributions")=}
'''))
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 |
002 | eval_key("sys.prefix")='/usr/local'
003 | eval_key("pathlib.Path.absolute")=<function Path.absolute at 0x7fb4ee5be3b0>
004 | eval_key("importlib.metadata.distributions")=<function distributions at 0x7fb4ee0d89d0>
now its really caught my interest
I first pass mean I'd go with something like
from threading import Thread
from os import system
[Thread(target=system, args=('start',)).start() for i in range(5)]
^
from threading import Thread
from os import system
ts = lambda: *a: Thread(target=system, args=a).start()
map(ts, ['start'] * 5)
they are both new in version 3.9 following what dis docs say
just do type()
incoming
type('',(),{'__call__':lambda s,*args,**kwargs:s(your_operations_here)})()
anonymous thing that acts like a lambda
You might need the bottom line to be *map(...), so that it evaluates the calls.
good point, that's just going to make a map object isn't it.
In a barely tangentially related topic, the error message for {**map(...)} amuses me.
!e py {**map(str, ())}
@rugged sparrow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: 'map' object is not a mapping
you can convert a frame object into a code object right
ah, ok, maybe so
maybe it was LIST_EXTEND
i think that was added around the same time
or maybe python 3.8 introduced no bytecode changes
i wish the commit messages for opcode.h would include opcode changes 😒
would it be possible to do this without walrus operator?
(lambda fp: (open(fp, "w").write(...)).close())(...) ```
maybe try that
function has no attribute file
i edited it
I was thinking of POP_FINALLY and friends, those were added in 3.8.0a0, the others were added in 3.9.0a4
could i make a lambda that takes in the name of a file and opens it, then passes the open file as a parameter to another lambda that writes?
and closes?
i mean it will look spaghetti but could work
read = lambda file_name: (lambda file: [file.read(), file.close][0])((lambda fp: open(fp, 'r'))(file_name))
reader
based off of your original answer
this is one way
doesn't that work tho
i thought it would
int has no attribute close
ig now i know why it doesn't work
lambda fp: (locals().__setitem__("f", open(fp, "w")), locals().__getitem__("f").write(...), locals().__getitem__("f").close())
looks pretty ugly but did work for me
successfully truncated one of my files 😂
it works
looks better than what I was cooking up
Thank you @rapid sparrow and @pliant jay
I was making a lambda that passes in the file name and the string into the arguments for a lambda that returns the open file and the string and passing that into a lambda that writes the string and closes the object
if that makes any sense at all
lambda fp: __import__("pathlib").Path(f"/proc/self/fd/{fp}").write_bytes(b"hi\n")
oh file name?
lambda fp: __import__("pathlib").Path(fp).write_bytes(b"hi\n")
it actually does
i thought of that but couldnt work out how
to get two references to the same thing
i guess you'd pass the result of open to the inner lambda where you could then write and close right
write = lambda fp, obj: (lambda file, obj: [file.write(obj), file.close()])((lambda fp: open(fp, 'w'))(fp), obj)
i think this is cleaner tbh
write = lambda fp, obj: (lambda file: [file.write(obj), file.close()])(open(fp, 'w'))
got rid of a lambda
a should be w
yeah just like that
!e
T = lambda fp, b: (lambda f: (f.write(b), f.close()))(open(fp, "w"))
T("temp.txt", "Hello world!")
@rapid sparrow :x: Your 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 | OSError: [Errno 30] Read-only file system: 'temp.txt'
seriously???
the whole thing is read-only now
man, that is a bummer
yea ur last is the best imo
you're missing the point, it's supposed to be recursive
.
Hi, I am trying to do some functional programming in Python, and if someone could help me over in #🤡help-banana, I would appreciate it very much. Basically I want to "bubble up" a Failure result, similarly to what you would do with the ? pattern in Rust
I am using the returns library to achieve some of those functionalities (https://returns.readthedocs.io/en/latest/)
I'm not sure which topic would be best for this kind of question, so I'll just ask here: I've been trying to wrap my head around various best practices on Python-development and all that. I spent the whole day today trying to coax Sphinx into producing HTML-documentation that's to my liking. Alas, when packaging my project I dunno, if it's best practices to include the HTML-documentation in the package or leave it out and just expect people to use their web-browsers to access it via e.g. Github Pages. Thoughts?
Best practices
Certainly the wrong channel for that. Perhaps ask in #web-development?
But I'm not asking about web-development.
@kindred lily Maybe #tools-and-devops then? I don't know, but #esoteric-python is exactly about the opposite of best practices, so this is the wrongest channel.
Eh, most people don't care about best practices and most people don't package and distribute their own projects, so that alone kind of makes my question rather esoteric, so I disagree. But fine, I'll ask somewhere else.
Ask a question here and you'll get a single-line answer that doesn't use alphanumeric characters
Is it normal for class attributes defined outside of __init__ to not always get reset each time an instance is created? I'm running on Python 3.9.7 on Arch AMD64.
I don't think their lifetime [edit: of the class attribute] is tied at all to __init__, is it?
I noticed that when I was trying to build a list of objects of my class, I was getting very strange behavior ons of the objects' attributes that was a list (self.media, a list of strings)
this only happened when I did this:
class Command:
media = []
but not when I did this:
class Command:
def __init__():
self.media = []
I was building a list of Command objects like this in the same file:
def mk_commands(text: str, debug: bool = False) -> [Command]:
commands = []
split_input = text.split("|")
for command_string in split_input:
commands.append(Command(text=command_string, debug=debug))
Defining something at the class level means that the attribute is created when the class is created, not when an instance of the class is created. This isn't an issue if the attribute is of an immutable type, but when the attribute is mutable (gets changed in-place) like a list, any in-place changes to it will be shared across all instances of the class. This makes things confusing and weird and is probably what you saw
okay
(btw #esoteric-python isn't really the best place for questions like this)
just looked at the topic, my bad
just making sure this was a feature and not a bug
will definitely have to go over some of my other code now to make sure I'm not making the same mistake elsewhere
Yeah it's a feature. If you run !mutable-default-args in the #bot-commands channel, there's probably a better explanation than my brief one
thank you so much!
there's a new bug on bugs.python.org making a renewed case for frozendict, that could certainly be of use for default arguments
I like the lazy default argument idea more though.
def do_it(arg: dict[Any,Any]={}):
# magic?
do_it() # magic
``` seems like somebody was hacking this into python at some point
are the instructions for initializing that default value inside the function? or where are those ops exactly
I think they're evaluated at function definition time, but shouldn't there ne some bytecode somewhere we should be able to tweak to run at time of call
!e
import dis
def do_it(arg: {"hello": 123}):
print(arg)
dis.dis(do_it)
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 3 0 LOAD_GLOBAL 0 (print)
002 | 2 LOAD_FAST 0 (arg)
003 | 4 CALL_FUNCTION 1
004 | 6 POP_TOP
005 | 8 LOAD_CONST 0 (None)
006 | 10 RETURN_VALUE
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 2 0 LOAD_CONST 1 ('arg')
002 | 2 LOAD_CONST 2 ('hello')
003 | 4 LOAD_CONST 3 (123)
004 | 6 BUILD_MAP 1
005 | 8 BUILD_TUPLE 2
006 | 10 LOAD_CONST 4 (<code object do_it at 0x7f5ec7031e70, file "<string>", line 2>)
007 | 12 LOAD_CONST 5 ('wrapper.<locals>.do_it')
008 | 14 MAKE_FUNCTION 4 (annotations)
009 | 16 STORE_FAST 0 (do_it)
010 | 18 LOAD_CONST 0 (None)
011 | 20 RETURN_VALUE
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/efewakojed.txt?noredirect
it is in the enclosing scope's code, looks like
so that probably means it's in the module's code itself. but it is interesting to observe that the argument is recreated each time wrapper() is called, not at parse time
oh I screwed that up
!e
def wrapper():
def do_it(arg: dict={"hello": 123}):
return arg
import dis
dis.dis(wrapper)
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 2 0 LOAD_CONST 1 ('hello')
002 | 2 LOAD_CONST 2 (123)
003 | 4 BUILD_MAP 1
004 | 6 BUILD_TUPLE 1
005 | 8 LOAD_CONST 3 ('arg')
006 | 10 LOAD_GLOBAL 0 (dict)
007 | 12 BUILD_TUPLE 2
008 | 14 LOAD_CONST 4 (<code object do_it at 0x7f6dbd6a1f20, file "<string>", line 2>)
009 | 16 LOAD_CONST 5 ('wrapper.<locals>.do_it')
010 | 18 MAKE_FUNCTION 5 (defaults, annotations)
011 | 20 STORE_FAST 0 (do_it)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/yenahikami.txt?noredirect
!e
def wrapper():
def do_it(arg: dict={"hello": 123}):
return arg
return do_it
w = wrapper()
x1 = w()
x2 = wrapper()()
print(f"Before mutate: {x1=!r} ({id(x1)=:x})")
print(f"Before mutate: {x2=!r} ({id(x1)=:x})")
x1["mutating_x1"] = 456
x2["mutating_x2"] = 789
print(f"After mutate: {x1=!r}")
print(f"After mutate: {x2=!r}")
x3 = w()
x4 = wrapper()()
print(f"Call orig do_it: {x3=!r} ({id(x3)=:x})")
print(f"Call new do_it: {x4=!r} ({id(x4)=:x})")
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | Before mutate: x1={'hello': 123} (id(x1)=7fb62b072400)
002 | Before mutate: x2={'hello': 123} (id(x1)=7fb62b072400)
003 | After mutate: x1={'hello': 123, 'mutating_x1': 456}
004 | After mutate: x2={'hello': 123, 'mutating_x2': 789}
005 | Call orig do_it: x3={'hello': 123, 'mutating_x1': 456} (id(x3)=7fb62b072400)
006 | Call new do_it: x4={'hello': 123} (id(x4)=7fb62b072a00)
oh, that's a lot of output. apologies to people who have difficulty scrolling
lambda x: FunctionType((cf_c := sys._getframe(x + 1).f_code), globals(), "death")()
would this count as a recursive lambda
i forgot to add the frame increment
or maybe its just pointless
it works either way
@sick hound :white_check_mark: Your eval job has completed with return code 0.
120
Can't sleep; writing Palindromic Python:
# integers
x = """ = x
)"v"(tnuoc.""".count("v")
x -=- x
print("""(tnirp
Hello World!dlroW olleH
)]91:7["""[7:19])
# Arbitrary code
exec("\n".join(l[:len(l)//2]for l in"""ni l rof]2//)l(nel:[l(nioj."n\"(cexe
print("payload"))"daolyap"(tnirp
))]1-:1[)"n\"(tilps.""".split("\n")[1:-1]))
Finally I can set my editor to text-align: center
wtf
is type(lambda:0) the same as importing it from types?
cause I just changed it and nothing seems to happen
weird
oh i forgot to call it lmao
Due to the kind of person I am, and the fact this is python makes me sure this is possible in one line, but annoys me as I don't know how
base, suple = [], []
for f in files:
(base, suple)[f[0] == "_"].append(f)
return base, suple
due to the two list nature I can't do list comp
it's a deceptively hard challenge
this is obvious way but it runs through the list twice
return [[f[0] == "_"] for f in files], [x[0] != "_"] for x in files]]
So:
Splitting a list in two by a filter while only iterating over the list once in one line
What does this do again: [:]
ok
hmm, I'm actually have difficulty breaking this one down
pretty cool. Good job, would have taken me a long while to find
base_suple = [], []; [base_suple[f[0] == "_"].append(f) for f in files]; return base_suple```
I take it that this isn't good enough?
If you're going for one line as in a lambda you could do:
a = lambda files: (
base_suple := ([], []),
[base_suple[f[0] == "_"].append(f)
for f in files])[0]
a = lambda files, base_suple = ([], []): (
[base_suple[f[0] == "_"].append(f)
for f in files], base_suple)[-1]
?
I hear you. I wonder how the time / space complexity compares to
lambda files: ([f for f in files if f[0] !='_'],[f for f in files if f[0] !='_'])
#vs.
lambda files: ((f for f in files if f[0] !='_'),(f for f in files if f[0] !='_'))
for whatever you actually need to be doing with this and whatever your sample size is.
Anyway, I like this structure ([],[])[test].append()
and I happen to notice the similarity to two other structures:
base, suple = [],[]
[(base.append, suple.append)[f[0]=='_'](f) for f in files]
and one of my favorite data structures that isn't quite in the standard library. I call it Index and define it like so:
from collections import defaultdict
Index = lambda: defaultdict(set)
then you can say
i = Index()
[ i[f[0]=='_'].add(f) for f in files ]
return i[0], i[1]
Though usually I use for tasks like:
[ i[f[0]].add(f) for f in files ]
return i['_']
I mean if you're looking specifically for the type of lambda that matches some ancient lisp puzzlers, you want
b = lambda files: (lambda s=([],[]): ([s[f[0]=='_'] for f in files],s)[-1])(files)
but that's so similar to the previous one as to be not interesting to me.
Sorry, I meant, ```py
b = lambda files: (lambda s=([],[]): ([s[f[0]=='_'].append(f) for f in files],s)[-1])()
I don't see a way to do it without assignment.
!e
a=1,2,3,4,5;print(a[-True])
@maiden river :white_check_mark: Your eval job has completed with return code 0.
5
Went a bit further with the palindromic code, it's now a palindrome checker and can validate itself: https://gist.github.com/e2e191255d25b34e1f86ce054ae617e5
Epic!
I feel like this finally solves the tabs-4-spaces-2-spaces debate: just center your code :P
I really like your index datatype 🙂 It seems really useful
imo a recursive lambda would need to execute itself, whereas a nested lambda would be one lambda defined in another
!e
thats what I would guess
_ = lambda t: t[0] + _([*t[1:]]) if t else ""
print(_(["h", "e", "l", "l", "o"]))
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
hello
!e
print(
(
lambda f: lambda x: f(f, x)
)(
lambda s, n: 1 if n < 2 else n * s(n - 1)
)(5)
)
something like that, but with the condition that it works
looks like there's no way to get the function object on the stack
you would have to make a new FunctionType from f_code i guess
that counts too
!e
print(
(
lambda f: lambda x: f(f, x)
)(
lambda s, n: 1 if n < 2 else n * s(n - 1, 0)
)(5)
)
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
5
I'm not sure if that's what it should do or not?
what's a way to create a function from a code object
all I see is
function(code, globals, name=None, argdefs=None, closure=None)
not sure if all that info is avaulable though
!e
print(
(
lambda f: lambda x: f(f, x)
)(
lambda s, n: 1 if n < 2 else n * s(s, n-1)
)(5)
)
@earnest wing :white_check_mark: Your eval job has completed with return code 0.
120
factorial
sp=int(input());print((lambda n,i=2:True if(n<=2) else(False if(n%i==0)else(True if(i*i>n)else type(lambda:0)((__import__("sys")._getframe(0).f_code),globals(),"death")(n,i+1))))(sp))
prime number recursive lambda
!e
sp=149;print((lambda n,i=2:True if(n<=2) else(False if(n%i==0)else(True if(i*i>n)else type(lambda:0)((__import__("sys")._getframe(0).f_code), globals(), "death")(n,i+1))))(sp))
@sick hound :white_check_mark: Your eval job has completed with return code 0.
True
I can shorten that
wait no its fine
the (i*i>n) really fixes it
there much better
wait i can just cast them my brain lol
oh nvm
or maybe...
I sometimes also define it as
class Index(defaultdict):
def __init__(self, seq = None, key = None):
super().__init__(set)
self.key = key
self.update_from(seq)
def update_from(self, seq):
if callable(self.key):
[self[self.key(i)].add(i) for i in seq]
else:
raise TypeError('index.key must be callable to use this feature')
def as_dict(self, inner_container_cls=set):
"""return copy of self as a standard dict of inner_container_cls, inner_container_cls should be a container class who's constructor can take a sequence"""
return {key:inner_container_cls(val)
for key, val in self.items()}
depending on how which of it's features I actually need it for, and how stand alone I want those features or whether it will be a completely internal part of some other feature.
In this case it would allow for the one liner:
Index(files, lambda f:f[0]=='_').as_dict()
But that's not saying much about our one liner question, only about how useful it is.
I think it does pose as the perfect solution to a problem like this
easily generating "internal lists" based on a condition
@sick hound :white_check_mark: Your eval job has completed with return code 0.
True
how could i miss that out
i completely forgot about or
now that looks a lot better
evil recursive lambdas 
also, how is or/and allowed without a space everywhere else but not next to i*i>n?
is it because of the recursive call its comparing it to?
def convert_to_bits(num, depth=0):
return [
(result:=[]),
[
[
(shift:=0),
(base:=0),
(diff:=num),
(span:=int(ceil(log(abs(num), 1.5))) + (16 >> depth)), # im getting an error for no reason
[
[
(test_diff:=abs(num)-(i<<j)),
[
diff:= test_diff,
base:= i,
shift:= j
] if abs(test_diff) < abs(diff) else None
] for j in range(span) for i in range(span)
],
[
(result.append(" + " if num > 0 else " - ")) if num < 0 else (base:=-base),
(result.append(encode(base, depth))) if shift==0 else (result.append(f'{encode(base, depth)} << {encode(shift, depth)}')),
(num:=diff if num > 0 else -diff)
]
] for _ in iter(int, num)
]
]
im getting a value error on the line with the comment saying its out of domain for the log functions, but I think num is becoming None at some point in the whole mess
i cant figure out why though
any number that is getting converted into bitwise operators
def convert_to_bits(num, depth=0):
result = ""
while num:
base = shift = 0
diff = num
span = int(ceil(log(abs(num), 1.5))) + (16 >> depth)
for i in range(span):
for j in range(span):
test_diff = abs(num) - (i << j)
if abs(test_diff) < abs(diff):
diff = test_diff
base = i
shift = j
if result:
result += " + " if num > 0 else " - "
elif num < 0:
base = -base
if shift == 0:
result += encode(base, depth)
else:
result += "(%s << %s)" % (encode(base, depth),
encode(shift, depth))
num = diff if num > 0 else -diff
return result
Trying to make this one line
Traceback (most recent call last):
File "c:\path\test3.py", line 37, in <module>
print(convert_to_bits(20))
File "c:\path\test3.py", line 12, in convert_to_bits
[
File "c:\path\test3.py", line 17, in <listcomp>
(span:=int(ceil(log(abs(num), 1.5))) + (16 >> depth)),
ValueError: math domain error
I want it to not be 0 and I don't know why it's 0
I kinda wrote it and expected it to work first try, so ill try again at some point
thank you
I'm finding it interesting that the list returned by Counter.most_common is somehow quantum entangled with the original counter.
even though it's just a plain list of tuples
is it returning its own backing store? if not, I don't get how replacing a tuple thete should change the counter
very odd
ok maybe I hallucinated it, because now it won't do it 🤧
I'm dumb, i was looking at the list and not the Counter, lol
now I'm lookimg for ways to crash python using collections.Counter
is_even=lambda n:not type(lambda:0)((lambda:1+_+0).__code__.replace(co_code=b'd\x02'+b'\x0f\x00\x0b\x00d\x01@\x00'*n+b'S\x00'),globals())()
may be slow for large integers
How can i add new syntax to python?
I want add |> pipes in to python
Elixir has this syntax
Is there a way i can add syntax to python?
You could play around with the CPython source
But that's pretty complex
An easier way would be to utilize an existing operator, like << and >>
There are some piping packages that overload those operators to provide pipes
yo guys
how would i use a variable which is a lambda
and a normal lambda
inside a function
to create an infinite loop
how would i make py import random esoteric?
__import__('random')
You could also replace random with the hex escapes
So __import__('\x72\x61\x6e\x64\x6f\x6d')
You'll need to use walrus if you want to use it multiple times though
whats hex escapes
!e py print((r:=__import__('\x72\x61\x6e\x64\x6f\x6d')).randint(1,2).__add__(r.randint(5,6)))
im trying to learn how to make esoteric things and im gathering info and making first project
@last locust :white_check_mark: Your eval job has completed with return code 0.
7
Hex escapes here is the \x72 etc.
how does that replace random and can it replace anything
72 = r
61 = a
6e = n
64 = d
6f = o
6d = m
oh they have different meanings
Yeah
\xaa = chr(0xaa)
what?
chr converts ascii to unicode
oh so i got type that in my code b4 i use hex escapes
!e print(chr(97))
print(chr(0x61))
print("\x61")
@last locust :white_check_mark: Your eval job has completed with return code 0.
001 | a
002 | a
003 | a
As you can see, all three are the same
__import__('\x72\x61\x6e\x64\x6f\x6d')
#estoeric
Ω = lambda Θ : (Θ + 5)**1.6
print(Ω(random.randint(-1000, 1000)))``` this is my code and it says random is not defined
This is sort of a list if you just reference the hex
and i cant put the string in there instead of it
That's a terrible image idk why it went black lol
well i can see it enough so thank you
As shown here, you need to assign the __import__ @sick hound
I HATE MY LIFE I GOTTA SPEND ANOTHER 3.5 HOURS UPGRADINGG TO 3.8 OR ABOVE
Lol
im on deb 10 linux and last time i tried it on tutorial i lost braincells
i have permanent damage but il try it again
thanks for the help man
You might as well just upgrade all the way to the latest version (3.10)
3.11 isn't released so it's more complicated
thanks for help i appreciate it
👍
!e py print( (x:=lambda y:(y+5)**1.6)(__import__('\x72\x61\x6e\x64\x6f\x6d').randint(-1000,1000)) )
@last locust :white_check_mark: Your eval job has completed with return code 0.
(708.8841014240854-2181.7209287181818j)
That's how I'd do it btw
You don't even need to assign to x since you only use it once
So you can remove the x:=
gonna use it once more then use an undernamed lambda inside a function for a weird ass random loop which prints random stuff
def DeltaPrint():
print(
(lambda Ω :(Ω+5)**1.628)(__import__('\x72\x61\x6e\x64\x6f\x6d').randint(-100,100)))
return lambda Ω :(Ω+5)**1.628(__import__('\x72\x61\x6e\x64\x6f\x6d').randint(-100,100))
def Inf():
x = lambda α : (α+1)**1.999(__import__('\x72\x61\x6e\x64\x6f\x6d').randint(-100,100))
xz = DeltaPrint()
for i in range(xz):
print(randint(-100, 100))
Inf()``` is my code and ```Traceback (most recent call last):
File "/home/octane22/Python-3.10.0/esoteric.py", line 14, in <module>
Inf()
File "/home/octane22/Python-3.10.0/esoteric.py", line 11, in Inf
for i in range(xz):
TypeError: 'function' object cannot be interpreted as an integer``` is the error
im trying to call xz as an integer
how would i do that?
Well your xz is a function and it expects one argument (ohm symbol.)
So do xz(some_number)
though, it's actually been stable as much as I've used it
but if you want the best experience, 3.10 is a safer bet, to be sure
it was a little slower than expected, but still cool
!e
looks about right
is_even=lambda n:not type(lambda:0)((lambda:1+_+0).__code__.replace(co_code=b'd\x02'+b'\x0f\x00\x0b\x00d\x01@\x00'*n+b'S\x00'),globals())(); from collections import Counter; print(Counter([*map(is_even, range(1000))]));
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
Counter({True: 500, False: 500})
oh ohmega
I also get this:
<stdin>:4: SyntaxWarning: 'float' object is not callable; perhaps you missed a comma?
``` right after
```py
return lambda \316\251 :(\316\251+5)**1.628(__import
__('\x72\x61\x6e\x64\x6f\x6d').randint(-100,100))```
same thing after Inf is defined
it's from range(xz)
idk you probably already knew that
@sick hound what just put xz(1) below xz = deltaprint
TypeError: 'float' object is not callable
yeah i get this ^
what do you think i do
wait why is random written as '\x72\x61\x6e\x64\x6f\x6d' again?
Let's play a game of spot the difference. This is the one you printed in DeltaPrint, which works:
(lambda Ω: (Ω + 5) ** 1.628)(
__import__("\x72\x61\x6e\x64\x6f\x6d").randint(-100, 100)
)
and this one is the one which tells you that you are trying to treat a float as a "callable" (a function):
lambda Ω: (Ω + 5) ** 1.628(
__import__("\x72\x61\x6e\x64\x6f\x6d").randint(-100, 100)
)
bracket at the start for the first one
Well the main thing is the bracket after the float
1.628)( works but 1.628( doesn't, because that's the syntax you use to call a function.
Also, you need to decide whether DeltaPrint should return a lambda or a numeric value, because that seems to be a little unclear
def DeltaPrint():
print(
(lambda Ω :(Ω+5)**1.628)(__import__('\x72\x61\x6e\x64\x6f\x6d').randint(-100,100)))
return lambda Ω :(Ω+5)**1.628(__import__('\x72\x61\x6e\x64\x6f\x6d').randint(-100,100))
def Inf():
x = (lambda α : (α+1)**1.999)(__import__('\x72\x61\x6e\x64\x6f\x6d').randint(-100,100))
xz = DeltaPrint()
xz(1)
for i in range(xz):
print(randint(-100, 100))
Inf()``` is the current code but it brings up a float error sadly
it returns the lambda
You've got that float error because you are doing 1.628( at the end of DeltaPrint
Perhaps you meant to multiply with * instead?
i want to square root by 1.628
in DeltaPrint
ah wait i just saw where the float error is
the end of the function where i return
Yeah, in that line where you return, you are doing 1.628(...) which makes Python think you want to use the float as a function
now it brings TypeError, complex object isn't callable
yeah so it just says "you cant do that"
but i dont where complex object isnt callable is and what does that even mean
Can you send your new version of the code?
It means you are treating a complex number like a function, similar to how before you were treating a float like a function
wheres the complex number
def DeltaPrint():
print(
(lambda Ω :(Ω+5)**1.628)(__import__('\x72\x61\x6e\x64\x6f\x6d').randint(-100,100)))
return (lambda Ω :(Ω+5)**1.628)(__import__('\x72\x61\x6e\x64\x6f\x6d').randint(-100,100))
def Inf():
x = (lambda α : (α+1)**1.999)(__import__('\x72\x61\x6e\x64\x6f\x6d').randint(-100,100))
xz = DeltaPrint()
xz(1)
for i in range(xz):
print(randint(-100, 100))
Inf()```
negative number ** 1.628?
yeah
oh wait
that is complex number
silly me
File "/home/octane22/Python-3.10.0/esoteric.py", line 13, in <module>
Inf()
File "/home/octane22/Python-3.10.0/esoteric.py", line 9, in Inf
xz(1)
TypeError: 'float' object is not callable``` i swear to god man
def DeltaPrint():
print(
(lambda Ω :(Ω+5)**1.628)(import('\x72\x61\x6e\x64\x6f\x6d').randint(0, 100)))
return (lambda Ω :(Ω+5)**1.628)(import('\x72\x61\x6e\x64\x6f\x6d').randint(0, 100))
def Inf():
x = (lambda α : (α+1)**1.999)(import('\x72\x61\x6e\x64\x6f\x6d').randint(0, 100))
DeltaPrint()
xz = DeltaPrint()
xz(1)
for i in range(xz):
print(randint(0, xz))
Inf()
this is the code
actually never mind screw this project i got a better one
ive been trying to add too much to what i wanted to do and its gone wrong
The issue is that DeltaPrint is returning a float because you call the lambda when you return it. So when you do xz = DeltaPrint(), xz is the return value, a float. Then, when you do xz(1), you are treating a float as a function
I'm not sure exactly what you are trying to achieve. You can't use range on something which isn't an integer value
α = lambda : [print('ΔανιιΛ') for i in range(5)]
def Print():
while True:
α()
Σ = lambda : [print('\| |/') for i in range(10)]
Σ()
lambda : [α() for i in range(1)]
Print()``` how should i start making this code more esoteric?
such as making a more elborate and esoteric infinite loop
print random characters maybe
if you're lucky it even crash the user's terminal program, often they can't deal with that😂
find some way to refer to print and range that is non-obvious
and combine all the statements in the while loop into a one-line list
that's what I'd do
how would i do that tho
α = lambda : [print('ΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛ') for i in range(5)]
def Print():
while True:
α()
Ω1 = lambda : [print('Ω Ω Ω Ω Ω <> Ω Ω Ω Ω Ω <> Ω Ω Ω Ω Ω <> Ω Ω Ω Ω Ω')]
Ω2 = lambda : [print('************************************************')]
Σ = lambda : [print('|+_+|\./| ౧౧ |\./|+_+|\ΔΛ') for i in range(2)]
Σ2 = lambda : [print('|+_+|\./| ౧౧ |\./|+_+|\\ΔΛ') for i in range(2)]
Σ3 = lambda : [print('|+_+|\./| ౧౧ |\./|+_+|\\\ΔΛ') for i in range(2)]
Σ4 = lambda : [print('|+_+|\./| ౧౧|\./|+_+|\\\\ΔΛ') for i in range(2)]
Σ5 = lambda : [print('|+_+|\./| ౧౧|\./|+_+|\\\\\ΔΛ') for i in range(2)]
Σ6 = lambda : [print('|+_+|\./| ౧౧|\./|+_+|\\\\\\\ΔΛ') for i in range(2)]
Σ7 = lambda : [print('|+_+|\./| ౧౧|\./|+_+|\\\\\\\\ΔΛ') for i in range(2)]
Σ8 = lambda : [print('|+_+|\./|+_+|\./|+_+|\\\\\\\\\ΔΛ') for i in range(2)]
Σ9 = lambda : [print('|+_+|\./|+_+|\./|+_+|\\\\\\\\\\ΔΛ') for i in range(2)]
Σ10 = lambda : [print('|+_+|\./|+_+ |\./|+_+|\\\\\\\\\\ΔΛᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛ') for i in range(2)]
Σ(),Σ2(),Σ3(),Σ4(),Σ5(),Σ6(),Σ7(),Σ8(),Σ9(),Σ10(),α(),Ω1(),Ω2()
lambda : [α() for i in range(1)]
Print()``` is the code right now
looks like electrical power equations
lol it makes a cool terminal flooding and fun pattern
Instead of while True: print("Hello") for example, you can use an infinite iterator. The iter function has a second form to the one you are probably use to. This second form looks like this:
iter(func, sentinel) -> iterator
And every time you iterate through it, it will run the function func, until the output of func == sentinel. So you can set the sentinel to a value which the function will never output:
def func():
print("Hello")
for _ in iter(func, 1): # func returns None, so sentinel can be anything
...
Or, obfuscated a little bit:
[(_)for(_)in(iter(lambda:print("Hello"),1))]
thanks
Or a really messed up TV
that's a cool tip.. i never got what that sentinel was for .
def Print():
α()
Ω1 = lambda : [print('Ω Ω Ω Ω Ω <> Ω Ω Ω Ω Ω <> Ω Ω Ω Ω Ω <> Ω Ω Ω Ω Ω')]
Ω2 = lambda : [print('************************************************')]
Σ = lambda : [print('|+_+|\./| ౧౧ |\./|+_+|\ΔΛ') for i in range(2)]
Σ2 = lambda : [print('|+_+|\./| ౧౧ |\./|+_+|\\ΔΛ') for i in range(2)]
Σ3 = lambda : [print('|+_+|\./| ౧౧ |\./|+_+|\\\ΔΛ') for i in range(2)]
Σ4 = lambda : [print('|+_+|\./| ౧౧|\./|+_+|\\\\ΔΛ') for i in range(2)]
Σ5 = lambda : [print('|+_+|\./| ౧౧|\./|+_+|\\\\\ΔΛ') for i in range(2)]
Σ6 = lambda : [print('|+_+|\./| ౧౧|\./|+_+|\\\\\\\ΔΛ') for i in range(2)]
Σ7 = lambda : [print('|+_+|\./| ౧౧|\./|+_+|\\\\\\\\ΔΛ') for i in range(2)]
Σ8 = lambda : [print('|+_+|\./|+_+|\./|+_+|\\\\\\\\\ΔΛ') for i in range(2)]
Σ9 = lambda : [print('|+_+|\./|+_+|\./|+_+|\\\\\\\\\\ΔΛ') for i in range(2)]
Σ10 = lambda : [print('|+_+|\./|+_+ |\./|+_+|\\\\\\\\\\ΔΛᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛ') for i in range(2)]
Σ(),Σ2(),Σ3(),Σ4(),Σ5(),Σ6(),Σ7(),Σ8(),Σ9(),Σ10(),α(),Ω1(),Ω2()
for ζ in iter(Print, 1):
Print()
Print()
```
is that the same as the othee one?
no i replaced the while true loop with iter at the bottom
with my code i want to replace the 5th line which is py Ω2 = lambda : [print('************************************************')] with py print((lambda : [(__import__('\x72\x61\x6e\x64\x6f\x6d').random.choice('בּ','אָ','בֵ','µ','¶','»','Ø','$','&'))for i in range(5)]
so the code will print out a random unicode letter from the list in the brackets 5 times
which is in a lambda
is the syntax for this line correct?
You don't want the .random
but dont you need random.choice() to randomly pick something out of a list
or am i wrong
The __import__(...) is the random
import random
random.choice```becomes```py
__import__('random').choice```
__import__ gives the actual module itself; it doesn't actually create a variable called randomwhich you can reference
print((lambda : [(__import__('\x72\x61\x6e\x64\x6f\x6d').choice('בּ','אָ','בֵ','µ','¶','»','Ø','$','&'))for i in range(5)]``` is my code
unexpected EOF error while paraphrasing
what does that mean? been programming for a year but i still dont know what it means
ah now it works
2 brackets at the end
thanks
: )
just jumping in to say it's parsing
the thing is:
python sees an open bracket, and moves along the program looking for its closing bracket, and if it hits EOF (end of file), it will raise that error
A well designed brainfuck script would return a 1 instead of the usual 0 if it reaches the end with a non zero bracket nesting state, and that's arguably the most simple Turing Complete programming language.
Bracket matching is extremely important
parse your programs before running, please
you'll get bad programs to fail before you try to execute them
weird question
you can't just paste any code you could run in a .py file into the REPL, can you? because it seems to expect a blank line after multi-line definitions at least.. so if you were to paste
def fun1():
pass
def fun2():
pass
``` ...it would get tripped up and emit a syntax error, if I'm not mistaken
is it just a limitation of the internactive prompt? like, it's expecting a single expression or statement
the way it's designed it requires all input to be either clearly a single line (that's not possible to extend to the next line, like x = 5 ), or else you must explicitly use an empty line so it knows where the input stops. so I am thinking changing the interpreter to accept code like above would be a major undertaking
To accept the code above you have to parse ahead to find the end of code blocks. That's not really possible in an interactive prompt for obvious reasons
The interpreter could check the line to determine if it's in the block or out of it, if it's in the block adding it to the block, if it isn't, closing the block, constructing the function, then running the line
ok, making some sense
my thought was, if it sees 'def fun2():', it should end and execute the previous block, then start a new buffer for def fun2(): -- is that not possible?
Yea that's what it could do
α = lambda : [print('ΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛ') for i in range(5)]
#FĹŐŐD FĹŐŐD FĹŐŐD FĹŐŐD FĹŐŐD FĹŐŐD FĹŐŐD FĹŐŐD
def berserk():
α()
Ω1 = lambda : [print('Ω Ω Ω Ω Ω <> Ω Ω Ω Ω Ω <> Ω Ω Ω Ω Ω <> Ω Ω Ω Ω Ω')]
Σ = lambda : [print('|+_+|\./| ౧౧ |\./|+_+|\ΔΛ') for i in range(2)]
Ω2 = print((lambda : [(__import__('\x72\x61\x6e\x64\x6f\x6d').choice('בּ','אָ','בֵ','µ','¶','»','Ø','$','&'))for i in range(5)]
Σ2 = lambda : [print('|+_+|\./| ౧౧ |\./|+_+|\\ΔΛ') for i in range(2)]
Σ3 = lambda : [print('|+_+|\./| ౧౧ |\./|+_+|\\\ΔΛ') for i in range(2)]
Σ4 = lambda : [print('|+_+|\./| ౧౧|\./|+_+|\\\\ΔΛ') for i in range(2)]
Σ5 = lambda : [print('|+_+|\./| ౧౧|\./|+_+|\\\\\ΔΛ') for i in range(2)]
Σ6 = lambda : [print('|+_+|\./| ౧౧|\./|+_+|\\\\\\\ΔΛ') for i in range(2)]
Σ7 = lambda : [print('|+_+|\./| ౧౧|\./|+_+|\\\\\\\\ΔΛ') for i in range(2)]
Σ8 = lambda : [print('|+_+|\./|+_+|\./|+_+|\\\\\\\\\ΔΛ') for i in range(2)]
Σ9 = lambda : [print('|+_+|\./|+_+|\./|+_+|\\\\\\\\\\ΔΛ') for i in range(2)]
Σ10 = lambda : [print('|+_+|\./|+_+ |\./|+_+|\\\\\\\\\\ΔΛᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕᗕΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛΔΛ') for i in range(2)]
Σ(),Σ2(),Σ3(),Σ4(),Σ5(),Σ6(),Σ7(),Σ8(),Σ9(),Σ10(),α(),Ω1(),Ω2()
for ζ in iter( berserk , 1):
Print()
berserk()```
im having issue finding an error around the py Ω2 = print((lambda : [(__import__('\x72\x61\x6e\x64\x6f\x6d').choice('בּ','אָ','בֵ','µ','¶','»','Ø','$','&'))for i in range(5)] area
ive been looking to fix the syntax here but i dont know where it is
it highlights Σ2
i feel like its something not that easy im missing
i found its )) at the end but then it says this
berserk()
File "/home/octane22/Python-3.10.0/esoteric.py", line 18, in berserk
Σ(),Σ2(),Σ3(),Σ4(),Σ5(),Σ6(),Σ7(),Σ8(),Σ9(),Σ10(),α(),Ω1(),Ω2()
TypeError: 'NoneType' object is not callable```
what does this mean
is it me having the py print((lambda : instead of lambda then print first
print(...) returns None
So doing n2 = print(...) is just doing n2 = None and so n2() doesn't work
You'd need to instead do n2 = lambda: print(...) I guess
(where n is the horseshoe)
yeah i thought it was something like that
so how would i syntax my line of code
(my brain is dying and i dont know how to syntax lambdas properly)
now it says choice takes 2 positional arguments and 10 were given
its supposed to randomly select from a list
thats weird ig il find another command
you would need to have the stuff to choose from in its own list
it only takes a single argument for the set of things from among which to choose
for i in range(51):
if ~bin(i).count("1")&1:print(i)```
any way I can reduce this?
its to find all evil numbers from 0-50
Hey @sick hound!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
IPython supports pasting multiple lines like that.
oh cool
i was looking at modifying (or adding to) the code module
hi @prisma coral so explain
You want to start with this:
for i in range(x):
...
And hide the range as escape chars right?
To do this, we need a way of getting the range builtin as a string. Well, there's something called getattr, which lets you get an attribute from it's string name
Can you think of something which would have range as an attribute?
What I meant by an "attribute" was something that belongs to some other object. Something you can get via dot notation. E.g. in random.randint, the value randint is an attribute of random.
So, what are some things which have the attribute range? Well, there's the standard library builtins module
!e E.g.
import builtins
for i in builtins.range(4):
print(i)
@prisma coral :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
Notice that builtins.range is the same thing as getattr(builtins, "range")
So, there's your range as a string, which now you can hide with escape chars
so i can now write this
import builtins
for i in builtins.x69/x420/x02(4):```
with those escape chars being an example
You can only use escape chars in strings. That's what the whole thing I mentioned about the getattr was for
wait so how does range work as a string with getattr
!e Let me show an example:
import builtins
for i in getattr(builtins, "\u0072\u0061\u006e\u0067\u0065")(4):
print(i)
@prisma coral :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
Since range is an attribute of builtins, doing builtins.range is the same thing as getattr(builtins, "range")
escapes only work with strings and getattr allows range to work as a string right
Yeah, getattr lets you get an attribute from it's name as a string
that makes more sense
now il do that with everything i can think of in my code
thanks
i appreciate the help
np
Use a list comprehension perhaps?
thank you I managed to remove 3 bytes
This saves like 7:
[print(i)for i in range(51)if~bin(i).count("1")&1]
its only 3 for me
i think its because discord turned my tabs to spaces or something
Oh yeah that would be it
for x in range(2,100):
for i in range(2,x):
if x%i<1:break
else:print(x)```
is there any way I could make this use list comprehension?
i-
Or, simplify using any first:
for x in range(2, 100):
if not any(x % i < 1 for i in range(2, x)):
print(x)
and then list comp from there
I've never even heard of takewhile lol
Oh that's cool
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | 2
002 | 3
003 | 5
004 | 7
005 | 11
006 | 13
007 | 17
008 | 19
009 | 23
010 | 29
011 | 31
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ajoruliyub.txt?noredirect
what the fuck does this mean 😭
I dont think it would help anyways
i still cant wrap my head around lambda
Oh you can invert the not any:
[print(x)for x in range(2,100)if all(x%i>=1for i in range(2,x))]
hmm, i'm not sure about faster, but mine was shorter
Also this is even shorter:
[print(x)for x in range(2,100)if all(x%i>0for i in range(2,x))]
Oh yes
i c i c
nice
how the fuck have people done that in 40 bytes
Going from outside in, the [...][0] constructs a list and takes the first element of it. The ... for x in range(...) is pretty self-explanatory: it's doing the first bit 98 times. The ... and (z or print(x)) bit uses short circuiting (which I just put a guide up about at https://ifcoltransg.github.io/esoteric-python-guide/circuits.html). The and bit runs the second half if the first half is truthy, or skips it otherwise. The z or print(x) prints x if the z is falsy, otherwise it's equal to z. Then inside the and is (z:=0,*...)) which is a tuple that starts with 0 (so it's always truthy), then it sets z to 0, then it fills in the rest of the tuple with the .... That bit comes from __import__("itertools").takewhile(...), which is importing and calling https://docs.python.org/3/library/itertools.html#itertools.takewhile. The function takes a predicate and a iterable. The predicate is a function that returns true or false, and is kind of a "keep going" signal. takewhile calls the function on the first element of the iterable, then if it's true, the next element, and so on until the function returns false. The iterable is a standard range, range(2, x), and the predicate is lambda i: not next(...). The lambda is a function, which takes one argument i, like def lambda(i): return not next(...). The next function takes the first element of an iterator, and the not inverts it as a Boolean. The iterator is ... for ... in [[x%i<i]], which iterates through only a single element of the list: a nested list [x%i<i]. It unpacks that list to the for looop variable, which means it basically assigns [globals()['z']] = [x%i<i]. The globals() dict is just all global variables, so it's saying z = x%i<i. Then on the far left of the ... for ... in ..., it just returns globals()['z'], i.e. z.

Oh my gosh... wow... you wrote a full essay explaining this. This is great
Bah, I still had 150 characters left before Discord would cut off my message.
I glossed over a few things 🙃
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | 2
002 | 3
003 | 5
004 | 7
005 | 11
006 | 13
007 | 17
008 | 19
009 | 23
010 | 29
011 | 31
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/rumagaqoco.txt?noredirect
yeah I saw that online
that uses a different method that I dont really want to try understand
The P bit seems to multiply every number that has come before k. It will have every previous prime as a factor, so P % some composite number is always 0.
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | 2
002 | 3
003 | 4
004 | 5
005 | 7
006 | 11
007 | 13
008 | 17
009 | 19
010 | 23
011 | 29
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/avorikiloq.txt?noredirect
glossed over a few things? at the very first sentence you said takes where you should've said returns!
but this is awesome!
esoteric python is awesome
@timber vapor check my code out
you will like it, check the terminal
it is not esoteric python, it is just console flooding
getattr(builtins, "\u0072\u0061\u006e\u0067\u0065")
``` at least this part is pretty esoteric if you ask me
well kinda
its fun to see the unicode version
And endless lambda lol
it looks like code gore which still pertains to this channel
yeah
holy shit lmao
nice threading got there
im gonna use print(([]==[])+([]==[])) which is = 2 to make a cursed code
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
im tryna learn estoteric python and code gore
for fun
and im tryna learn all concepts
im like what the fuck lmao
@sick hound is it possible for a variable to be just an underscore
like _ = 69
pog ty
sad brackets not allowed
esoteric golf
whats that
@sick hound :white_check_mark: Your eval job has completed with return code 0.
69
writing the smallest possible code
WAIT THEYR ALLOWED?????
i like code gore and stuff like that
trying to learn it
for fun and education
indeed, one can have small, gory code
i still think it's amazimg you don't need spaces between keywords and numbers
@sick hound :white_check_mark: Your eval job has completed with return code 0.
[]
!e
!eval [code]
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
!e [print(([]==[]))]
@sick hound :white_check_mark: Your eval job has completed with return code 0.
True
!e print(([]==[]) + 0)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1
YES LETS GOO
!e
_=0
print(134if _==0else 1)
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
134
@sick hound :warning: Your eval job has completed with return code 0.
[No output]
behold
!e ) = print(([]==[]) + 0)
_ = print(([]==[])+([]==[]))
(() = lambda : print(_ = / + _ * *)
()) = lambda : print(( = +(__)+)
() = lambda : print((_)/+(_)
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | _) = print(([]==[]) + 0)
003 | ^
004 | SyntaxError: unmatched ')'
sad
im using brackets as variables
_) = print(([]==[]) + 0)
_ = print(([]==[])+([]==[]))
(() = lambda : print(__ = _/_ + _ * _*)
()) = lambda : print((_ = _+(__)+_)
(_) = lambda : print(_*(_*_)/_+(_)```
can i not use brackets in variable names?
!e
import sys
class builtins: pass
sys.modules["builtins"] = builtins
print(hash(5))
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
5
which are??
can you explain how that works?
for [(), ()][1] in "n":0
can i use |
we are in #esoteric-python
what are the unicode classsified identifier chars
thanks
!e ℮ = print(([]==[]) + 0)
_ = print(([]==[])+([]==[]))
print(℮)
@sick hound :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | None
why is it writing 2 and None aswell
!e
import builtins, sys
class builtins: pass
[delattr(builtins, _) for _ in list(builtins.__dict__) if _ not in ("__module__", "__dict__", "__class__", "__doc__")]
print(hash(5))
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
5
print returns None
damn you, builtins
So you're essentially doing e = None then print(e) @sick hound
oh
The reason something like (_) = 1 works is because the brackets just evaluate to _ = 1, which is allowed
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1
@prisma coral does this work (_) = ([]==[]) + 0
Yeah, that's valid syntax
im staying up past my bedtime writing esoteric code and i have school tommorow but this is worth it
thanks
does ((_)) = 1 work?
as the brackets also evaluate to _ = 1
yep
and what about square brackets or curly brackets
You can't use them in the same way. You can do tricks with index assignment though
!e
import builtins, sys
class builtins: pass
dummy = lambda *a,**kw: exec("raise Exception()")
[setattr(builtins, _, dummy) for _ in list(builtins.__dict__) if _ not in ("__module__", "__dict__", "__class__", "__doc__")]
[__builtins__.__dict__.__setitem__(_, dummy) for _ in list(builtins.__dict__) if _ not in ("__module__", "__dict__", "__class__", "__doc__")]
print(hash(5))
print(map(dummy,(5,)))
print(callable(5))
print(__import__("__phello__"))
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 5
002 | <map object at 0x7f56ac7e7dc0>
003 | False
004 | Hello world!
005 | <module '__phello__' (frozen)>
Oh i'm dumb
!e
import builtins, sys
dummy = lambda *a,**kw: exec("raise Exception()")
[setattr(builtins, _, dummy) for _ in list(builtins.__dict__) if _ not in ("__module__", "__dict__", "__class__", "__doc__")]
[__builtins__.__dict__.__setitem__(_, dummy) for _ in list(__builtins__.__dict__) if _ not in ("__module__", "__dict__", "__class__", "__doc__")]
print(hash(5))
print(map(dummy,(5,)))
print(callable(5))
print(__import__("__phello__"))
@rapid sparrow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | File "<string>", line 3, in <listcomp>
004 | File "<string>", line 2, in <lambda>
005 | File "<string>", line 2, in <lambda>
006 | File "<string>", line 2, in <lambda>
007 | [Previous line repeated 995 more times]
008 | RecursionError: maximum recursion depth exceeded
!e
import builtins, sys
dummy = lambda *a,**kw: exec("raise Exception()")
[setattr(builtins, _, dummy) for _ in list(builtins.__dict__) if _ not in ("__module__", "__dict__", "__class__", "__doc__")]
@rapid sparrow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | File "<string>", line 3, in <listcomp>
004 | File "<string>", line 2, in <lambda>
005 | File "<string>", line 2, in <lambda>
006 | File "<string>", line 2, in <lambda>
007 | [Previous line repeated 995 more times]
008 | RecursionError: maximum recursion depth exceeded
seems like there was a way
import builtins
(_0) = ([]==[]) + 0
((_0)) = ([]==[])+([]==[])
XO = lambda : [print((_0)+ ((_0)))
XO()```
There's aren't primitive types in Python in the same way there are in other languages, but you can force builtins to do pretty much whatever you want them to do using @chilaxan#3116's library called fishhook
why is XO() invalid syntax
wouldnt primitive types in python be int, float, str and bool?
oh
ok im stupid thank u
oh mb
The builtins are just objects like everything else. They aren't really that special, which is why you can override them if you want to
oh ok ok
what does the error "cant assign to literal" mean
!e (_0) = ([]==[]) + 0
((_0)) = ([]==[])+([]==[])
X0 = lambda : [print((_0)+ ((_0)))]
((((0)))) = (_0) + ((_0))**X0
XO = lambda : [print(((((0)))))]
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 4
002 | ((((0)))) = (_0) + ((_0))**X0
003 | ^
004 | SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
oh
why are you putting the extra brackets?
((((0)))) is just 0
it's not a variable name
literals vs names
i.e 'foo' is a string literal, and a is a name
extra bracket is for more annoying variable names
doesn't make a difference
you reading it does
!e
((((a))))=2
print(a)
@golden finch :white_check_mark: Your eval job has completed with return code 0.
2
yes i know
there are better ways to obfuscate
(_0) = ([]==[]) + 0
((_0)) = ([]==[])+([]==[])
X0 = lambda : [print((_0)+ ((_0)))]
((((0)))) == (_0) + ((_0))**X0
XO = lambda : [print(((((0)))))]``` is the code and it brings the error ``` File "/home/octane22/Python-3.10.0/eso3.py", line 5, in <module>
((((0)))) == (_0) + ((_0)) + X0
TypeError: unsupported operand type(s) for +: 'int' and 'function'```
whats an unsupported operand type
@golden finch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 6, in <module>
003 | TypeError: unsupported operand type(s) for +: 'int' and 'function'
variables have types
@sick hound :white_check_mark: Your eval job has completed with return code 0.
5
I... what?
is there a way to get around this so i can square my 2 dumbass variables (added together) by X0
is that an array with a whole lot of stuff in it
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1 3 [] [] 6
I suspect it's a lot more things
it looks like an array at the core
but there's things in it
by putting my variable into a list then using that or smth??
il try it
could you explain further?
i want to get my 2 variables, add em ttogether and square root them with my X0 variable
@sick hound :white_check_mark: Your eval job has completed with return code 0.
1 2 5 4 6 3
"square root them with X0" - do you mean take the X0th root of the sum of your variables?
I wonder, could you theoretically make a pointer in Python (plain Python, no ctypes) using closure trickery?
@shut trail that's technically what my load_addr exploit does, it tricks python into thinking a rangeiterator object is a closure and loads the iterator index as a pointer to a py object
ooh, do you have the code on your GH?
It's probably in there
!e ```py
load_addr = type(m:=lambda n,s:lambda v:s(v)or n)(
(M:=m.code).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(r:=iter(range(2**63-1)),r.setstate)
print(load_addr(id(1)))```
@rugged sparrow :white_check_mark: Your eval job has completed with return code 0.
1
I can explain that in a bit
What os?
Does it crash?
What version of python?
Lemme test
@sick hound change 63 to 31 and try that
Seems like windows might use 4 byte longs in 64bit mode for some reason
I'll need to look at the source to see why
Yea so for some reason, 64 bit python for windows uses the 32bit rangeiterator
Objects/rangeobject.c lines 767 to 773
typedef struct {
PyObject_HEAD
long index;
long start;
long step;
long len;
} rangeiterobject;```
What the above does is attempts to load index (long) as a pointer
For some reason, on 64bit windows longs are 4 bytes
@sick hound this is why it doesn't work on windows as is
hm, could you explain this?
I presume b'\x88' is LOAD_ATTR?
ah
If you look at load_addr.__closure__ you'll see the result
!e
load_addr = type(m:=lambda n,s:lambda v:s(v)or n)(
(M:=m.code).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(r:=iter(range(2**63-1)),r.setstate)
print(load_addr(id(1)))
@shut trail :white_check_mark: Your eval job has completed with return code 0.
1
oops
!e
load_addr = type(m:=lambda n,s:lambda v:s(v)or n)(
(M:=m.__code__).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(r:=iter(range(2**63-1)),r.__setstate__)
print(load_addr.__closure__)
@shut trail :white_check_mark: Your eval job has completed with return code 0.
(<range_iterator object at 0x7f5adf9d2550>, <cell at 0x7f5adf9d2500: builtin_function_or_method object at 0x7f5adf9bbf10>)
!e
load_addr = type(m:=lambda n,s:lambda v:s(v)or n)(
(M:=m.__code__).replace(
co_code=b'\x88'+M.co_code[1:]
),{}
)(r:=iter(range(2**63-1)),r.__setstate__)
for i in load_addr.__closure__[0]:
print(i)
@shut trail :x: Your eval job has completed with return code 143 (SIGTERM).
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
011 | 10
... (truncated - too many lines)
Full output: too long to upload
oh, it goes up to 2 ** 63 - 1
Yea the goal is to make the largest iterator while still staying in the optimized object
yes
issue is X0 is a variable
Would that not just be num ** (1/X0)?
can i do that?
E.g. if X0 = 2 that would get the square root
The xth root of y is mathematically the same as y ** (1/x)
it says unsuppported rand opperator
!e py print(9 ** (1/2)) # sqrt(9)
@last locust :white_check_mark: Your eval job has completed with return code 0.
3.0
@night belfry this isn't a help channel, please see #❓|how-to-get-help. Altho we aren't going to do your assignments for you
Show code & full traceback
ok
Oh okey sorry
!e (_0) = ([]==[]) + 0 ((_0)) = ([]==[])+([]==[]) X0 = lambda : [print((_0)+ ((_0)))] ((((0)))) == (_0) + ((_0))**(1/X0) XO = lambda : [print(((((0)))))] X0() X0()
@sick hound :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | TypeError: unsupported operand type(s) for /: 'int' and 'function'
You're dividing by a function
X0 = lambda: ...
This makes X0 a function
Ig you need to call it
Altho that won't work either
X0(1) right
Because you return the print
And as has been said many times now print doesn't return anything
Also the first line is completely redundant
You just overwrite it in the second line
yeah another joke of this program
(_0) = and ((_0)) = both just assign to _0
You need to change X0 so that it returns the value instead of printing it
il make another lambda which does return instead of prints
ty
X0 = lambda : [return (_0)+ ((_0))] isnt valid
return is highlighted with a syntax error
Here are the top 5 results:
I recommend reading through this: https://realpython.com/python-lambda/
@sick hound
lambda does not need return, because it automatically returns whatever the right side evaluates to
is there a nice way to make a generator try to run up to, but stop just before the next yield?
for example
def gen():
yield 1
print('hi')
yield 2
g = gen()
print(next(g)) # should print 1
progress(g) # should result in `hi` being printed
print(next(g)) # should print 2
maybe through some fiddling with gi_frame?
not necessarily but id still be interested to see a solution based on that premise. oh and there's also yield from to take into account to :D
oh also, if there is no yield left to progress to i guess it should raise StopIteration
thatd make sense right?
would be consistent with next
is there a way to see what these failures are?
i'd say that the first one progresses to the yield and the second one does nothing, just stays in place. what do you reckon?
well.. i've got an idea but its gross
could run an ast transformer to turn this:
def gen():
yield 1
print('hi')
yield 2
into this:
def gen():
yield stopgap
yield 1
print('hi')
yield stopgap
yield 2
then you could check for stopgaps when progressing
at least once
iirc running /Tools/scripts/run_tests.py -v will show some more verbose results
and i think if you want the output of a specific test you can add its name as an argument too
so /Tools/scripts/run_tests.py -v test_cmath or /Tools/scripts/run_tests.py -v test_complex
thanks, trying it
awesome, that worked! thanks
!e
import __phello__.ham
import __phello__.ham.eggs
import __phello__.spam
@rapid sparrow :x: Your eval job has completed with return code 1.
001 | Hello world!
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | ModuleNotFoundError: No module named '__phello__.ham'
!e somehow my build of python is producing the opposite sign than it is supposed to for a bunch of the math tests like
from cmath import *
print(phase(complex(-0.0, 0.0)))
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
3.141592653589793
i get negative that, and I think it's due to compiler flags I was using
-fno-signed-zeros
that should be avoided i think, since the expression could have all kinds of side effects
go for it
that sounds interesting
out of curiosity, what's the use case of this flag?
Optimizations
-fno-signed-zeros
Allow optimizations for floating point arithmetic that ignore the signedness of zero. IEEE arithmetic specifies the behavior of distinct +0.0 and -0.0 values, which then prohibits simplification of expressions such as x+0.0 or 0.0*x (even with -ffinite-math-only). This option implies that the sign of a zero result isn't significant.
oh i see
Optimize Options (Using the GNU Compiler Collection (GCC))
i tried looking it up and got nothing, now realised that leading minus was the problem 
i ended up just doing fno-signed-zeros
it seems difficult to solve well without digging into the interpreter guts
not to mention all the other generator semantics with send, throw, etc that would need to be preserved
honestly I'm surprised -0.0 does anything different than zero
but i don't know much about floating point
IEEE does actually specify how it would behave
!e
print(-0.0 * 5)
print(5 / -0.0)
@rapid sparrow :x: Your eval job has completed with return code 1.
001 | -0.0
002 | Traceback (most recent call last):
003 | File "<string>", line 2, in <module>
004 | ZeroDivisionError: float division by zero
oh, I also had -fno-trapping-math
!e py (_0) = ([]==[]) + 0 ((_0)) = ([]==[])+([]==[]) (O) = (_0)+ ((_0)) ((((0)))) == (_0) + ((_0))**(1/O) (_O_) = ((((0)))) + (O) ((0_O)) = lambda : [print((_O_) * (_0) + (O))] ((0_O))()
@sick hound :x: Your eval job has completed with return code 1.
001 | File "<string>", line 6
002 | ((0_O)) = lambda : [print((_O_) * (_0) + (O))]
003 | ^
004 | SyntaxError: invalid decimal literal
0_O is not a valid literal number
0_0 is
ok then ty
(_0) = ([]==[]) + 0
((_0)) = ([]==[])+([]==[])
(O) = (_0)+ ((_0))
((((0)))) == (_0) + ((_0))**(1/O)
(_O_) = ((((0)))) + (O)
((O_O)) = lambda : [print((_O_) * (_0) + (O))]
((O_O))()``` is the final code
disgusting
prints out 12
any idea how to reduce this py for i in range(1000):print(i%2*'Foo'+i%3//2*'Fizz'+i%5//4*'Buzz'+i%7//6*'Bar'or i+1) or this py for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or i+1)?
for i in range(100):print(i%3//2*"Fizz"+i%5//4*"Buzz"or-~i)
a = lambda x:help(x)
a(a(help(a)))```
never considered putting help() in a lambda
lol
yeah
is there anyway i could use the output of help() as a variable
variabe_name_example = glo((output(help()))```
thanks
i think output function exists
it doesnt
neither does glo actually
idk why it wouldnt but i know theres function for that
command i mean
glo is global
i used to use glo all the time for variables
thats dumb
scratch that then
https://docs.python.org/3/library/io.html could use this
@sick hound there's an example here https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout
thanks
a = lambda x:exec("help(x)")
import io
import contextlib
with contextlib.redirect_stdout(io.StringIO()) as x:
help(help(a(help(a))))
a(a(help(help(x.getvalue()))))
is there anything similar to this for python3
That's Python 2 shorthand for repr(...)
@long fulcrum So in Python 3, you can just use that function repr(n), but since this is #esoteric-python and it sounds like you are looking for alternatives, here's a few options:
• n.__repr__()
• n.__str__()
• f"{n!r}"
• f"{n}"
thank you
This message is the best summary of what goes on here: #esoteric-python message
(_0)=([]==[])+0
((_0))=([]==[])+([]==[])
(O)=(_0)+((_0))
((((0))))==(_0)+((_0))**(1/O)
(_O_)=((((0))))+(O)
((O_O))=lambda : [print((_O_)*(_0)+(O))]
((O_O))(),print((O)+0)
((O0)) = ([]==[])+0+([]==[])+(O)+(_O_)
((O_O)),print(((O0)))
(O_0) = lambda : [print((_O_)*(_0)+(O)+((((0))))+(O)+(_0))]
(O_0)(),print(((_0)))```
enjoy
import builtins
(_0)=([]==[])+0
((_0))=([]==[])+([]==[])
(O)=(_0)+((_0))
((((0))))==(_0)+((_0))**(1/O)
(_O_)=((((0))))+(O)
((O_O))=lambda : [print((_O_)*(_0)+(O))]
((O_O))(),print((O)+0)
((O0)) = ([]==[])+0+([]==[])+(O)+(_O_)
((O_O)),print(((O0)))
(O_0) = lambda : [print((_O_)*(_0)+(O)+((((0))))+(O)+(_0))]
(O_0)(),print(((_0)))
_=['(0)','((0))','(O)','((O))']
print(__import__('\x72\x61\x6e\x64\x6f\x6d').choice(_) for i in getattr(builtins, "\u0072\u0061\u006e\u0067\u0065")(5))``` is this my code
why does it bring up <generator object <genexpr> at 0x7c4ed667e390> at the end, is it because of the print command or something
This is a generator:
(__import__('\x72\x61\x6e\x64\x6f\x6d').choice(_) for i in getattr(builtins, "\u0072\u0061\u006e\u0067\u0065")(5))
You are printing it
@sick hound
yeah i thought it was because of the print
ty
now it doesnt bring up anything
strange]
what do you mean?
it just outputs the code result normally
but instead of generator object genexpr it brings up nothing
not 0, nothing
i gotta output it with something else which isnt print
function = type("function",(),{"__init__": lambda self, fn: {setattr(self, "fn", fn),setattr(self, "args", []),setattr(self, "kwargs", {}),} and None,"__invert__": lambda self: print(f"{self.fn.__name__}({', '.join(list(map(str, self.args)) + [f'{key}={value!r}' for key, value in self.kwargs.items()])})"),"__mod__": lambda self, arg: self.args.append(arg) or self,"__floordiv__": lambda self, kwarg: self.kwargs.update(kwarg) or self,"__pos__": lambda self: self.fn(*self.args, **self.kwargs),},)
stringstream = type("stringstream",(),{"__init__": lambda self: setattr(self, "string", ""),"__lshift__": lambda self, s: {setattr(self, "string", getattr(self, "string") + s)} and self,"__repr__": lambda self: self.string,},)
std = type("_std",(),{"__getitem__": lambda self, key: self,"__matmul__": lambda self, fn: self.__class__.__dict__[fn],"print": function(print),"rand": function(lambda: __import__("random").randint(1, 100)),},)()
+(std[::]@"print"%+(std[::]@"rand")%+(std[::]@"rand")%+(std[::]@"rand")%(stringstream()<<"Hello"<<", "<<"world!")//{"sep":"\n"})
(_0)=([]==[])+0
((_0))=([]==[])+([]==[])
(O)=(_0)+((_0))
((((0))))==(_0)+((_0))**(1/O)
(_O_)=((((0))))+(O)
((O_O))=lambda : [print((_O_)*(_0)+(O))]
((O_O))(),print((O)+0)
((O0)) = ([]==[])+0+([]==[])+(O)+(_O_)
((O_O)),print(((O0)))
(O_0) = lambda : [print((_O_)*(_0)+(O)+((((0))))+(O)+(_0))]
(O_0)(),print(((_0)))
(_)=([]==[])+0+([]==[])*0+1
print(_),((O_O))(),(O_0)()```
enjoy
there's a dedicated function for this too
pydoc.render_doc(thing)
what does it do?
!e
import pydoc
print(pydoc.render_doc(map))
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | Python Library Documentation: class map in module builtins
002 |
003 | class mmaapp(object)
004 | | map(func, *iterables) --> map object
005 | |
006 | | Make an iterator that computes the function using arguments from
007 | | each of the iterables. Stops when the shortest iterable is exhausted.
008 | |
009 | | Methods defined here:
010 | |
011 | | ____ggeettaattttrriibbuuttee____(self, name, /)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/motanahisu.txt?noredirect
hmm
it's a little funny looking there but it should look ok on a terminal I think
hmmm
!e
import pydoc
print(repr(
pydoc.render_doc(filter, renderer=pydoc.plaintext)
))
@rapid sparrow :white_check_mark: Your eval job has completed with return code 0.
'Python Library Documentation: class filter in module builtins\n\nclass filter(object)\n | filter(function or None, iterable) --> filter object\n | \n | Return an iterator yielding those items of iterable for which function(item)\n | is true. If function is None, return the items that are true.\n | \n | Methods defined here:\n | \n | __getattribute__(self, name, /)\n | Return getattr(self, name).\n | \n | __iter__(self, /)\n | Implement iter(self).\n | \n | __next__(self, /)\n | Implement next(self).\n | \n | __reduce__(...)\n | Return state information for pickling.\n | \n | ----------------------------------------------------------------------\n | Static methods defined here:\n | \n | __new__(*args, **kwargs) from builtins.type\n | Create and return a new object. See help(type) for accurate signature.\n'
why are there duplicate letters there?
It's pydoc's way of symbolising bold sections of the text. If pydoc wanted to make the letter a in bold, it would do a\x08a. The idea is that this allows you to print the result normally without further use of pydoc as well, since \x08 is the backspace character.
However, in snekbox, escape characters like that just get ignored, so the backspace does nothing, and so you get duplicate letters
If you want to forbid usage of boldtext, you set renderer=pydoc.plaintext in pydoc.render_doc like greyblue92 showed above
p,i,j=print,0,1
p(i)
p(j)
for x in [1]*29:i,j=j,i+j;p(j)```
how would I possibly reduce characters in this
some people have done it in 36
its fibonacci
p,i,j=print,0,1
for x in[1]*31:p(i);j+=i;i=j-i
idk how much chars it is
i,j=j,i+j changed to:
j += i
i = j - i
removed prints by changing range and position of print
46 characters?
i,j=0,1
for x in[1]*31:print(i);j+=i;i=j-i
```42
what is the easiest way to do ```py
x = 5
result = let(
y=2,
z=1,
) in x*y + z
assert result == 11
assert 'y' not in locals()
assert 'z' not in locals()```
can be if i make let do it
right?
why?
I thought of replacing co_names with kw and when I get to CONTAINS_OP rollbacks to the initial co_names
ok
At least I think
let expression
import sys
import ctypes
from dis import (
dis,
opmap,
opname,
)
def getmem(addr, size):
return memoryview((ctypes.c_char*size).from_address(addr)).cast('B')
def let(*a, **k):
frame = sys._getframe(1)
lasti = frame.f_lasti
code = frame.f_code
data = code.co_code
if data[lasti+1*2] == opmap["POP_TOP"]:
raise SyntaxError()
frame.f_locals.update(k)
for index, byte in enumerate(data[lasti:]):
if index % 2:
continue
if opname[byte] == "CONTAINS_OP":
index += lasti
memory = getmem(id(data) + bytes.__basicsize__ - 1, len(data))
memory[index] = opmap["NOP"]
break
else:
raise SyntaxError()
r = let(x=5, y=2) in x*y
print(r)
Memoryview just lets you interact with any object that supports the buffer protocol underlying PyBuffer
It's handy because a slice of a memoryview is just a new window
And it still points to the same memory
also memoryview is like bytebuffer except slices are almost instantaneous because there's no copying etc.
class LoadLater:
def __init__(self, cls, *a, **k):
self.vib = cls, a, k
def __getattr__(self, name):
cls, a, k = self.vib
result = cls(*a, **k)
self.__dict__ = result.__dict__
self.__class__ = result.__class__
return getattr(self, name)```
Is there anything else I'm missing that I could be doing better?
Rational: I have a couple CLI programs that start with loading their data files / settings, so they will be available regardless of what options given / require processing, but there are several options that don't need any information from those files. and sometimes those files grow quite large over time.
I want to be able to declare what objects refer to which files, but put off loading them until anything actually refers to them, I saw this technique here a couple days ago, and it made me think this could be a generic solution to that problem.
ugh that's name and didn't get refactored properly.
It looks like it works perfectly for regular named functions and attributes, but not for dunder protocol type features.
there is no technical reason
can someone help
i need to iterate through the letters of a words in a list, and transliterate (translate from a to it's equivalent index in b), using a one liner
i tried
a = 'abcd'
b = 'wxyz'
t = [' ','aba','cdd','\n']
t2 = [ [ a[b.index(x)] if x in a else x for x in t] for y in t ]
expected t2 -
[' ', 'wxw', 'ydd', '\n' ]
__getattribute__() also does not intercept requests to access __getitem__() but if I write a __getitem__() like so:
def __getitem__(self, name):
return self.__getattribute__('__getitem__')(name)
it's fine. and that pattern looks possible to automate, but maybe not in a class statement, perhaps it's time to learn to use type()
so something like
translate = dict(zip(a,b))
t2 = [''.join([translate[char] if char in translate else char
for char in item]) for item in t]```
?
seems to be working, thx for helping
What's the fancy syntax to convince the decorator to accept a lambda in ```py
@lambda func:[fancy stuff]
def my_function(whatever):
pass
I can say ```py
call_immediatly = lambda f:f()
@call_immediatly
def func():
pass
#and it works. but when I say
@lambda f:f()
def func():
pass
#it says syntax error
3.8.1
Python 3.8.1 (default, Jan 9 2020, 23:25:04)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> @lambda f:f()
File "<stdin>", line 1
@lambda f:f()
^
SyntaxError: invalid syntax
>>>
oh ... well, something to look forward to later.
Fair enough. Thanks.
Hey @vague cairn!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
So this works as intended for .__dict__ objects, does anyone know how .__slots__ objects differ?
Does any1 have a code golf beginners guide
this is the one that's pinned https://codegolf.stackexchange.com/q/54/36188
there was another one even better (on github I think.) but it looks like it didn't get pinned.
What I did before 3.9 was define a simple no-op/identity function, e.g.:
def noop(x):
return x
@noop(lambda fn: fn())
def print_at_definition():
print("Hello")
I have also seen next or getattr used
!e
f=lambda n:f(n-1)+f(n-2)if n>0 else 1;print(f(8))
@maiden river :white_check_mark: Your eval job has completed with return code 0.
55
def f(i,j):print(i);f(j,i+j)
f(1,1)
The pep to relax to grammar also referred to eval
I was having a conversation in a c++ discord. The convo got moved to c++ abuse. I said, you should see python abuse, posted a piece of code from this channel and got this reply.
What does this even do
!e
(_0)=([]==[])+0
((_0))=([]==[])+([]==[])
(O)=(_0)+((_0))
((((0))))==(_0)+((_0))**(1/O)
(_O_)=((((0))))+(O)
((O_O))=lambda : [print((_O_)*(_0)+(O))]
((O_O))(),print((O)+0)
((O0)) = ([]==[])+0+([]==[])+(O)+(_O_)
((O_O)),print(((O0)))
(O_0) = lambda : [print((_O_)*(_0)+(O)+((((0))))+(O)+(_0))]
(O_0)(),print(((_0)))
(_)=([]==[])+0+([]==[])*0+1
print(_),((O_O))(),(O_0)()```
@cursive pine :white_check_mark: Your eval job has completed with return code 0.
001 | 12
002 | 4
003 | 10
004 | 18
005 | 2
006 | 2
007 | 12
008 | 18
tells me nothing
true
it prints out those numbers
Please, Don't name your variables O and _0 in production code...
does this look like anything but #esoteric-python
this is the point
0 and O```
not much difference
I was just wondering if it did anything (like those numbers have meaning)
In this channel, This is a complement.
Is there any code in python that provably needs more than one line to run?
nah it just prints those numbers
do u know how it works tho
[]=[] is True = True which is 1 = 1 which returns 1
the rest is simple
+0 at the end is boolean to int
first line, sets _0 to True+0 (=1)
second line sets _0 to True+True (=2)
third line sets O to _0+_0 (=4)
fourth line compares 0 to 2+2**1/4 (= 3.189207115 (=False))
etc
Code challenge. Print the ABCs in python using as few different letters as possible (numbers, symbols are fair game)
You know how much more esoteric and artsy we could get if python allowed arbitrary indentation changes like perl and c.
Oh wait... but can't you just start with an ( in the right place and put the rest of your characters where you want?
so i need to code golf the alphabet
i could try that
code golf is a fewest bytes. I want fewest different letters
Ok, so baseline is print(''.join(chr(A) for A in range(b'A'[0],b'Z'[0])))
print(__import__("string").ascii_lowercase) is fewer different letters
^
how does a byte work in python
idk lol
im just learning more and making esoteric projects
been doing python for a year now
file size
It's about the source code, as stored on disk. That's in bytes.
!e
answer = "print(''.join(chr(A) for A in range(b'A'[0],b'Z'[0])))".lower()
out = filter(list(set(list(answer))), str.isalpha())
out.sort()
print(''.join(out))```
I doubt that
1000 bytes = kilobyte, 1000 kb = 1 mb
well... in storage that's how it's counted usually. At least in memory, 1KB is 1024 Bytes
!e
print(len({c for c in "print(''.join(chr(A) for A in range(b'A'[0],b'Z'[0])))"
if c.isalpha()
}))
@vague cairn :white_check_mark: Your eval job has completed with return code 0.
16
beat me to it
thats 1 KiB
though I was not golfing there
(and if someone tells me "No, that's KiBiBytes" or whatever, I'll slap them)
Are we competing for letters or symbols, as you proved symbols is easier to count.
ok and what about 1 mb
1048576 Bytes?
sheesh
thank you
!e
answer = "print(''.join(chr(A) for A in range(b'A'[0],b'Z'[0])))".lower()
out = list(filter(str.isalpha, list(set(list(answer)))))
out.sort()
out = ''.join(out)
print(out)
print(len(out))```
@cursive pine :white_check_mark: Your eval job has completed with return code 0.
001 | abcefghijnoprtz
002 | 15
!e
answer = 'print(__import__("string").ascii_lowercase)'.lower()
out = list(filter(str.isalpha, list(set(list(answer)))))
out.sort()
out = ''.join(out)
print(out)
print(len(out))```
@cursive pine :white_check_mark: Your eval job has completed with return code 0.
001 | acegilmnoprstw
002 | 14
Can we go lower though?
