#esoteric-python

1 messages · Page 132 of 1

west cipher
#

im aware ittertools exists but the generic chain from itter breaks apart strings so whatever im just doing this dumb way cuz i dont wanna import xd

proper vault
#

is it really a lambda if it has a name though...

west cipher
#

i need to use the function in other places

proper vault
#

copy paste it then

west cipher
#

no

cloud fossil
#

Three layers of parentheses that actually do something with the values in them is enough esoteric for me

earnest wing
#

I was going to comment that "well you can't exactly have an unnamed recursive lambda" but combinators are a thing

#

fixpoint go brrrr

sick hound
#

What's that and can u give an example on how to use it

sick hound
#

@robust bramble how would i do the things u told me

#

give an example code of using lambda + conprehension plz

rapid sparrow
#

!e

import dis
dis.dis("""somedict, otherdict = {}, {}
{**somedict, **otherdict}
{**somedict, "t":1, "u":5}""")
night quarryBOT
#

@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

rapid sparrow
#

ROT_TWO ?

#

many DICT_UPDATE's; now I'm curious when DICT_MERGE would be used

woven bridge
#

DICT_MERGE is used when unpacking into kwargs

#

!e

import dis
dis.dis('test(**{1:2}, **{1:2})')
night quarryBOT
#

@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

woven bridge
#

!e

def test(**kwargs):
  pass
test(**{1:2}, **{1:2})
night quarryBOT
#

@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'
rapid sparrow
#

!e

import sys
print(
    sorted(map(
        lambda i: (len(i), i),
        (m.__name__ for m in sys.modules.values())
    ))
)
night quarryBOT
#

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

who ping

rapid sparrow
#

that was me

sick hound
#

oh

#

lambda

#

thanks

rapid sparrow
#

yw

woven bridge
#

interestingly enough, in 3.8 and below the string check came first

#

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 😅

rapid sparrow
#

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

@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>
rapid sparrow
#

would use help thinking up something devious to do with it

#

or at least break it

sick hound
vague cairn
#

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) 
rapid sparrow
#

I think DICT_UPDATE was new to 3.8

#

at least that's when I had to add it to stuff

sick hound
#

they are both new in version 3.9 following what dis docs say

golden finch
#

incoming

#
type('',(),{'__call__':lambda s,*args,**kwargs:s(your_operations_here)})()
#

anonymous thing that acts like a lambda

snow beacon
vague cairn
#

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.

rugged sparrow
#

!e py {**map(str, ())}

night quarryBOT
#

@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
rugged sparrow
#

they are referring to this error i assume

#

oh thats not consistent

sick hound
#

you can convert a frame object into a code object right

rapid sparrow
#

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 😒

steady lily
#

would it be possible to do this without walrus operator?

pliant jay
steady lily
#

function has no attribute file

pliant jay
#

i edited it

rapid sparrow
#

I was thinking of POP_FINALLY and friends, those were added in 3.8.0a0, the others were added in 3.9.0a4

steady lily
#

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?

pliant jay
#

i mean it will look spaghetti but could work

steady lily
#
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

rapid sparrow
#

this is one way

pliant jay
#

i thought it would

steady lily
#

int has no attribute close

pliant jay
#

ig now i know why it doesn't work

rapid sparrow
#
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 😂

steady lily
#

it works

#

looks better than what I was cooking up

#

Thank you @rapid sparrow and @pliant jay

rapid sparrow
#

curious what looks even worse

#

oh another way

steady lily
#

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

rapid sparrow
#
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")
rapid sparrow
#

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

steady lily
#
write = lambda fp, obj: (lambda file, obj: [file.write(obj), file.close()])((lambda fp: open(fp, 'w'))(fp), obj)
rapid sparrow
#

oh wel

#

worked on my python 😁

steady lily
#
write = lambda fp, obj: (lambda file: [file.write(obj), file.close()])(open(fp, 'w'))
#

got rid of a lambda

#

a should be w

rapid sparrow
#

yeah just like that

#

!e

T = lambda fp, b: (lambda f: (f.write(b), f.close()))(open(fp, "w"))
T("temp.txt", "Hello world!")
night quarryBOT
#

@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'
rapid sparrow
#

seriously???

steady lily
#

oh yeah thats so cool

#

i believe it

rapid sparrow
#

the whole thing is read-only now

#

man, that is a bummer

#

yea ur last is the best imo

earnest wing
#

.

sick hound
#

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

kindred lily
#

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?

restive void
#

Best practices
Certainly the wrong channel for that. Perhaps ask in #web-development?

kindred lily
#

But I'm not asking about web-development.

restive void
kindred lily
#

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.

earnest wing
#

Ask a question here and you'll get a single-line answer that doesn't use alphanumeric characters

rapid sparrow
#

or something that uses ctypes

#

not for interoperability

worthy iris
#

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.

rapid sparrow
#

I don't think their lifetime [edit: of the class attribute] is tied at all to __init__, is it?

worthy iris
#

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))
prisma coral
# worthy iris this only happened when I did this: ```python class Command: media = [] ``` ...

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

worthy iris
#

okay

prisma coral
worthy iris
#

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

prisma coral
#

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

worthy iris
#

thank you so much!

rapid sparrow
#

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

@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

rapid sparrow
#

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

@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

rapid sparrow
#

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

@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)
rapid sparrow
#

oh, that's a lot of output. apologies to people who have difficulty scrolling

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

night quarryBOT
#

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

120
sick hound
#

damn you made it better in no time

#

thats cool

restive void
#

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

sick hound
#

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

cursive pine
#

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

vague cairn
#
    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])()

vague cairn
#

I don't see a way to do it without assignment.

maiden river
#

!e
a=1,2,3,4,5;print(a[-True])

night quarryBOT
#

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

5
restive void
restive void
#

I feel like this finally solves the tabs-4-spaces-2-spaces debate: just center your code :P

cursive pine
rapid sparrow
#

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

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

hello
earnest wing
#

!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

rapid sparrow
#

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

rapid sparrow
#

!e

print(
  (
    lambda f: lambda x: f(f, x)
  )(
    lambda s, n: 1 if n < 2 else n * s(n - 1, 0)
  )(5)
)
night quarryBOT
#

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

5
rapid sparrow
#

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

sick hound
#

how do i automate mouse movements with python

#

i know how to automate keyboard

earnest wing
#

!e

print(
  (
    lambda f: lambda x: f(f, x)
  )(
    lambda s, n: 1 if n < 2 else n * s(s, n-1)
  )(5)
)
night quarryBOT
#

@earnest wing :white_check_mark: Your eval job has completed with return code 0.

120
earnest wing
#

factorial

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

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

True
sick hound
#

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

vague cairn
# cursive pine I really like your index datatype 🙂 It seems really useful

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.

cursive pine
#

I think it does pose as the perfect solution to a problem like this

#

easily generating "internal lists" based on a condition

night quarryBOT
#

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

True
sick hound
#

how could i miss that out

#

i completely forgot about or

#

now that looks a lot better

#

evil recursive lambdas ducky_devil

#

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?

steady lily
#
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

rapid sparrow
#

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

rapid sparrow
#

now I'm lookimg for ways to crash python using collections.Counter

golden finch
#
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

vestal vector
#

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?

still lily
#

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

sick hound
#

yo guys

#

how would i use a variable which is a lambda

#

and a normal lambda

#

inside a function

#

to create an infinite loop

sick hound
#

how would i make py import random esoteric?

last locust
#

__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

sick hound
#

whats hex escapes

last locust
#

!e py print((r:=__import__('\x72\x61\x6e\x64\x6f\x6d')).randint(1,2).__add__(r.randint(5,6)))

sick hound
#

im trying to learn how to make esoteric things and im gathering info and making first project

night quarryBOT
#

@last locust :white_check_mark: Your eval job has completed with return code 0.

7
last locust
#

There we go

#

They shows a nice example

last locust
sick hound
#

how does that replace random and can it replace anything

last locust
#

72 = r
61 = a
6e = n
64 = d
6f = o
6d = m

sick hound
#

oh they have different meanings

last locust
#

Yeah

sick hound
#

u got a list for it?

#

that u can link me

last locust
#

\xaa = chr(0xaa)

sick hound
#

what?

last locust
#

chr converts ascii to unicode

sick hound
#

oh so i got type that in my code b4 i use hex escapes

last locust
#

!e print(chr(97))
print(chr(0x61))
print("\x61")

night quarryBOT
#

@last locust :white_check_mark: Your eval job has completed with return code 0.

001 | a
002 | a
003 | a
last locust
sick hound
#
__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
last locust
sick hound
#

and i cant put the string in there instead of it

last locust
#

That's a terrible image idk why it went black lol

sick hound
#

well i can see it enough so thank you

last locust
sick hound
#

invalid syntax on the ((r:

#

the : bit is highlighted

#

im on 3.7.3

last locust
#

It's :=

#

Which is walrus

#

So you need 3.8+

sick hound
#

I HATE MY LIFE I GOTTA SPEND ANOTHER 3.5 HOURS UPGRADINGG TO 3.8 OR ABOVE

last locust
#

Lol

sick hound
#

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

last locust
#

You might as well just upgrade all the way to the latest version (3.10)

sick hound
#

yeah i tried

#

3.11 tho 😏

last locust
#

3.11 isn't released so it's more complicated

sick hound
#

yeah i heard its unstable and being developed

#

so i should get 3.10

last locust
#

Yeah

#

3.10 is the latest official release

sick hound
#

thanks for help i appreciate it

last locust
#

👍

#

!e py print( (x:=lambda y:(y+5)**1.6)(__import__('\x72\x61\x6e\x64\x6f\x6d').randint(-1000,1000)) )

night quarryBOT
#

@last locust :white_check_mark: Your eval job has completed with return code 0.

(708.8841014240854-2181.7209287181818j)
last locust
#

You don't even need to assign to x since you only use it once

#

So you can remove the x:=

sick hound
#

gonna use it once more then use an undernamed lambda inside a function for a weird ass random loop which prints random stuff

sick hound
#

yet

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

sick hound
rapid sparrow
#

but if you want the best experience, 3.10 is a safer bet, to be sure

rapid sparrow
#

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

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

Counter({True: 500, False: 500})
rapid sparrow
#

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)

rapid sparrow
sick hound
#

@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

rapid sparrow
#

wait why is random written as '\x72\x61\x6e\x64\x6f\x6d' again?

sick hound
#

more esoteric

#

so what do i do about the float error

prisma coral
# sick hound so what do i do about the float error

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

bracket at the start for the first one

prisma coral
#

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

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

prisma coral
#

Perhaps you meant to multiply with * instead?

sick hound
#

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

prisma coral
#

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

sick hound
#

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

prisma coral
prisma coral
sick hound
#

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()```
earnest wing
#

negative number ** 1.628?

sick hound
#

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

prisma coral
sick hound
#

so i would need to do it before?

#

id put xz(1) before

prisma coral
sick hound
#

α = 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

rapid sparrow
#

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

sick hound
#
α = 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
sick hound
#

lol it makes a cool terminal flooding and fun pattern

prisma coral
# sick hound such as making a more elborate and esoteric infinite loop

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

thanks

rapid sparrow
sick hound
#

lol

#

now it looks more esoteric

rapid sparrow
sick hound
#
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()

    ```
rapid sparrow
#

is that the same as the othee one?

sick hound
#

no i replaced the while true loop with iter at the bottom

sick hound
#

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?

sick hound
#

but dont you need random.choice() to randomly pick something out of a list

#

or am i wrong

last locust
#

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

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

#

: )

golden finch
floral meteor
#

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

earnest wing
#

parse your programs before running, please

#

you'll get bad programs to fail before you try to execute them

rapid sparrow
#

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

rugged sparrow
#

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

rapid sparrow
#

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?

rugged sparrow
#

Yea that's what it could do

sick hound
#
α = 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

last locust
#

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)

sick hound
#

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

rapid sparrow
#

it only takes a single argument for the set of things from among which to choose

long fulcrum
#
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

sick hound
#

i solved it dont worry @rapid sparrow

#

these are the modifications

night quarryBOT
#

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:

https://paste.pythondiscord.com

sick hound
snow beacon
rapid sparrow
#

i was looking at modifying (or adding to) the code module

sick hound
#

hi @prisma coral so explain

prisma coral
#

You want to start with this:

for i in range(x):
  ...

And hide the range as escape chars right?

sick hound
#

yeah

#

thats the goal

prisma coral
#

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?

sick hound
#

uh just a number

#

range(4)

prisma coral
#

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.

sick hound
#

cant think

#

just a normal loop

prisma coral
#

So, what are some things which have the attribute range? Well, there's the standard library builtins module

sick hound
#

oh that but idc anything else

#

idk*

prisma coral
#

!e E.g.

import builtins
for i in builtins.range(4):
  print(i)
night quarryBOT
#

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

001 | 0
002 | 1
003 | 2
004 | 3
prisma coral
#

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

sick hound
#

so i can now write this

#
import builtins
for i in builtins.x69/x420/x02(4):```
#

with those escape chars being an example

prisma coral
#

You can only use escape chars in strings. That's what the whole thing I mentioned about the getattr was for

sick hound
#

wait so how does range work as a string with getattr

prisma coral
#

!e Let me show an example:

import builtins
for i in getattr(builtins, "\u0072\u0061\u006e\u0067\u0065")(4):
  print(i)
night quarryBOT
#

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

001 | 0
002 | 1
003 | 2
004 | 3
prisma coral
#

Since range is an attribute of builtins, doing builtins.range is the same thing as getattr(builtins, "range")

sick hound
#

escapes only work with strings and getattr allows range to work as a string right

prisma coral
#

Yeah, getattr lets you get an attribute from it's name as a string

sick hound
#

that makes more sense

#

now il do that with everything i can think of in my code

#

thanks

#

i appreciate the help

prisma coral
#

np

prisma coral
long fulcrum
prisma coral
long fulcrum
#

its only 3 for me

#

i think its because discord turned my tabs to spaces or something

prisma coral
#

Oh yeah that would be it

long fulcrum
#
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?
prisma coral
#

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

night quarryBOT
long fulcrum
#

what the fuck does this mean 😭

#

I dont think it would help anyways

#

i still cant wrap my head around lambda

prisma coral
#

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

long fulcrum
#

how the fuck have people done that in 40 bytes

snow beacon
# long fulcrum what the fuck does this mean 😭

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.

long fulcrum
prisma coral
snow beacon
#

Bah, I still had 150 characters left before Discord would cut off my message.

#

I glossed over a few things 🙃

night quarryBOT
long fulcrum
#

yeah I saw that online

#

that uses a different method that I dont really want to try understand

snow beacon
#

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.

long fulcrum
#

yeah it is wilsons theorem

#

i just dont understand what wilsons theorem is

night quarryBOT
floral meteor
sick hound
#

esoteric python is awesome

#

@timber vapor check my code out

#

you will like it, check the terminal

fleet bridge
#

it is not esoteric python, it is just console flooding

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

sick hound
#

And endless lambda lol

sick hound
#

yeah

sick hound
#

holy shit lmao

#

nice threading got there

#

im gonna use print(([]==[])+([]==[])) which is = 2 to make a cursed code

night quarryBOT
#

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

[No output]
sick hound
#

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

rapid sparrow
#

esoteric golf

sick hound
#

whats that

night quarryBOT
#

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

69
rapid sparrow
sick hound
#

WAIT THEYR ALLOWED?????

sick hound
#

trying to learn it

#

for fun and education

rapid sparrow
#

indeed, one can have small, gory code

#

i still think it's amazimg you don't need spaces between keywords and numbers

night quarryBOT
#

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

[]
sick hound
#

!e

night quarryBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

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

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

sick hound
#

!e [print(([]==[]))]

night quarryBOT
#

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

True
sick hound
#

!e print(([]==[]) + 0)

night quarryBOT
#

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

1
sick hound
#

YES LETS GOO

rapid sparrow
#

!e

_=0
print(134if _==0else 1)
night quarryBOT
#

@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]
rapid sparrow
#

!e

[] or True
#

neither did you

#

so was I

#

but not really

sick hound
#

behold

#

!e ) = print(([]==[]) + 0)
_ = print(([]==[])+([]==[]))
(() = lambda : print(
_ = / + _ * *)
()) = lambda : print((
= +(__)+)
() = lambda : print((_)/+(_)

night quarryBOT
#

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

001 |   File "<string>", line 1
002 |     _) = print(([]==[]) + 0)
003 |      ^
004 | SyntaxError: unmatched ')'
sick hound
#

sad

#

im using brackets as variables

#
_) = print(([]==[]) + 0)
_ = print(([]==[])+([]==[]))
(() = lambda : print(__ = _/_ + _ * _*)
()) = lambda : print((_ = _+(__)+_)
(_) = lambda : print(_*(_*_)/_+(_)```
#

can i not use brackets in variable names?

rapid sparrow
#

!e

import sys
class builtins: pass
sys.modules["builtins"] = builtins
print(hash(5))
night quarryBOT
#

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

5
sick hound
#

which are??

cerulean rivet
#

can you explain how that works?

for [(), ()][1] in "n":0
sick hound
#

can i use |

#

what are the unicode classsified identifier chars

#

thanks

#

!e ℮ = print(([]==[]) + 0)
_ = print(([]==[])+([]==[]))
print(℮)

night quarryBOT
#

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

001 | 1
002 | 2
003 | None
sick hound
#

why is it writing 2 and None aswell

rapid sparrow
#

!e

import builtins, sys
class builtins: pass
[delattr(builtins, _) for _ in list(builtins.__dict__) if _ not in ("__module__", "__dict__", "__class__", "__doc__")]
print(hash(5))
night quarryBOT
#

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

5
last locust
rapid sparrow
#

damn you, builtins

last locust
#

So you're essentially doing e = None then print(e) @sick hound

sick hound
#

oh

prisma coral
sick hound
#

ah thanks

#

!e ℮ = ([]==[]) + 0
_ = ([]==[])+([]==[])
print(℮)

night quarryBOT
#

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

1
sick hound
#

@prisma coral does this work (_) = ([]==[]) + 0

prisma coral
#

Yeah, that's valid syntax

sick hound
#

im staying up past my bedtime writing esoteric code and i have school tommorow but this is worth it

#

thanks

sick hound
#

as the brackets also evaluate to _ = 1

prisma coral
#

yep

sick hound
#

and what about square brackets or curly brackets

prisma coral
#

You can't use them in the same way. You can do tricks with index assignment though

rapid sparrow
#

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

@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)>
rapid sparrow
#

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

@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
rapid sparrow
#

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

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

any way of replacing primitive types for custom ones

rapid sparrow
#

seems like there was a way

sick hound
#
import builtins
(_0) = ([]==[]) + 0
((_0)) = ([]==[])+([]==[])
XO = lambda : [print((_0)+ ((_0)))
XO()```
prisma coral
sick hound
#

why is XO() invalid syntax

sick hound
#

oh

#

ok im stupid thank u

#

oh mb

prisma coral
sick hound
#

oh ok ok

golden finch
#

@sick hound you can use basically anything as dict keys

#

(well, anything hashable)

sick hound
#

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

night quarryBOT
#

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

oh

golden finch
#

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

sick hound
#

extra bracket is for more annoying variable names

golden finch
sick hound
#

you reading it does

golden finch
#

!e

((((a))))=2
print(a)
night quarryBOT
#

@golden finch :white_check_mark: Your eval job has completed with return code 0.

2
sick hound
#

yes i know

golden finch
#

there are better ways to obfuscate

sick hound
#
(_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
#

you can't add ints and functions

#

!e

def f(x):
  return x

a=2

a+f
night quarryBOT
#

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

X0 is a variable

#

ah wait i goes under the int catagory

golden finch
#

variables have types

night quarryBOT
#

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

5
golden finch
#

I... what?

sick hound
#

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

night quarryBOT
#

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

1 3 [] [] 6
golden finch
#

I suspect it's a lot more things

#

it looks like an array at the core

#

but there's things in it

sick hound
#

il try it

golden finch
#

could you explain further?

sick hound
#

i want to get my 2 variables, add em ttogether and square root them with my X0 variable

night quarryBOT
#

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

1 2 5 4 6 3
sick hound
#

what does ~- do

#

oh nice

golden finch
shut trail
#

I wonder, could you theoretically make a pointer in Python (plain Python, no ctypes) using closure trickery?

rugged sparrow
#

@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

shut trail
#

ooh, do you have the code on your GH?

rugged sparrow
#

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

night quarryBOT
#

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

1
rugged sparrow
#

I can explain that in a bit

rugged sparrow
#

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

night quarryBOT
#

Objects/rangeobject.c lines 767 to 773

typedef struct {
        PyObject_HEAD
        long    index;
        long    start;
        long    step;
        long    len;
} rangeiterobject;```
rugged sparrow
#

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

shut trail
#

I presume b'\x88' is LOAD_ATTR?

rugged sparrow
#

It is LOAD_DEREF

#

It replaces LOAD_CLOSURE

shut trail
#

ah

rugged sparrow
#

If you look at load_addr.__closure__ you'll see the result

shut trail
#

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

night quarryBOT
#

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

1
shut trail
#

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

@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>)
shut trail
#

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

@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

shut trail
#

oh, it goes up to 2 ** 63 - 1

rugged sparrow
#

Yea the goal is to make the largest iterator while still staying in the optimized object

last locust
sick hound
#

can i do that?

last locust
#

E.g. if X0 = 2 that would get the square root

#

The xth root of y is mathematically the same as y ** (1/x)

sick hound
#

it says unsuppported rand opperator

last locust
#

!e py print(9 ** (1/2)) # sqrt(9)

night quarryBOT
#

@last locust :white_check_mark: Your eval job has completed with return code 0.

3.0
night belfry
#

can you help

last locust
#

@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

last locust
sick hound
#

ok

night belfry
#

Oh okey sorry

sick hound
#

!e (_0) = ([]==[]) + 0 ((_0)) = ([]==[])+([]==[]) X0 = lambda : [print((_0)+ ((_0)))] ((((0)))) == (_0) + ((_0))**(1/X0) XO = lambda : [print(((((0)))))] X0() X0()

night quarryBOT
#

@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'
last locust
#

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

sick hound
#

X0(1) right

last locust
#

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

sick hound
#

yeah another joke of this program

last locust
#

(_0) = and ((_0)) = both just assign to _0

last locust
sick hound
#

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

last locust
#

That's not how lambda works

#

.rp lambda

glass drumBOT
#

Here are the top 5 results:

How to Use Python Lambda Functions
Functional Programming in Python: When and How to Use It
Code Evaluation With AWS Lambda and API Gateway
Python's reduce(): From Functional to Pythonic Style
Building Serverless Python Apps Using AWS Chalice
last locust
golden finch
#

lambda does not need return, because it automatically returns whatever the right side evaluates to

brazen geyser
#

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?

brazen geyser
#

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

rapid sparrow
#

is there a way to see what these failures are?

brazen geyser
#

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

brazen geyser
#

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

rapid sparrow
#

!e

import __phello__.ham
import __phello__.ham.eggs
import __phello__.spam
night quarryBOT
#

@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'
rapid sparrow
#

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

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

3.141592653589793
rapid sparrow
#

i get negative that, and I think it's due to compiler flags I was using

#

-fno-signed-zeros

brazen geyser
#

that should be avoided i think, since the expression could have all kinds of side effects

#

go for it

#

that sounds interesting

brazen geyser
earnest wing
#

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.

brazen geyser
#

oh i see

earnest wing
brazen geyser
#

i tried looking it up and got nothing, now realised that leading minus was the problem lemon_unamused

proper vault
#

ye

#

googling flags is a nuisance

#

do "-fno-signed-zeros"

brazen geyser
#

i ended up just doing fno-signed-zeros

proper vault
#

also works

#

though sometimes that ends up giving unrelated results

brazen geyser
#

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

rapid sparrow
#

honestly I'm surprised -0.0 does anything different than zero

#

but i don't know much about floating point

proper vault
#

IEEE does actually specify how it would behave

rapid sparrow
#

!e

print(-0.0 * 5)
print(5 / -0.0)
night quarryBOT
#

@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
rapid sparrow
#

oh, I also had -fno-trapping-math

sick hound
#

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

night quarryBOT
#

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

this is my code

#

it highlights ((0_ and says invalid token

#

what does that mean?

rapid sparrow
sick hound
#

ah ffs

#

does it need to not start with a number?

rapid sparrow
#

0_0 is

sick hound
#

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

long fulcrum
#

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

earnest wing
#
for i in range(100):print(i%3//2*"Fizz"+i%5//4*"Buzz"or-~i)
long fulcrum
#

oh my god thank you

#

I saw that trick the other day and forgot about it

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

prisma coral
sick hound
#

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()))))
long fulcrum
#

is there anything similar to this for python3

prisma coral
#

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}"

long fulcrum
#

thank you

sick hound
#

not minimoding

#

jk jk

#

basicly the weirdness of python

prisma coral
sick hound
#
(_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

prisma coral
#

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

sick hound
#

yeah i thought it was because of the print

#

ty

#

now it doesnt bring up anything

#

strange]

prisma coral
sick hound
#

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

zinc bear
#
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"})
sick hound
#
(_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

rapid sparrow
#

pydoc.render_doc(thing)

sick hound
#

what does it do?

rapid sparrow
#

!e

import pydoc
print(pydoc.render_doc(map))
night quarryBOT
#

@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

sick hound
#

hmm

rapid sparrow
#

it's a little funny looking there but it should look ok on a terminal I think

sick hound
#

hmmm

rapid sparrow
#

!e

import pydoc
print(repr(
  pydoc.render_doc(filter, renderer=pydoc.plaintext)
))
night quarryBOT
#

@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'
astral rover
#

why are there duplicate letters there?

prisma coral
# astral rover 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

long fulcrum
#
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

fleet bridge
#
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
long fulcrum
cerulean rivet
#

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?

rugged sparrow
#

Yes you can

#

if does some magic

#

ie bytecode modification and name hooks

cerulean rivet
rugged sparrow
#

I'll write a proof of concept in a bit

#

@cerulean rivet there's a better way

cerulean rivet
#

ok

rugged sparrow
cerulean rivet
#

let expression

cerulean rivet
#
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)
rugged sparrow
#

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

vague cairn
#

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.

cerulean rivet
#

there is no technical reason

maiden river
#

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

vague cairn
vague cairn
maiden river
vague cairn
#

you mostly just needed ''.join() I guess.

#

NICE!

vague cairn
#

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.

night quarryBOT
#
**PEP 614 - Relaxing Grammar Restrictions On Decorators**
Status

Final

Python-Version

3.9

Created

10-Feb-2020

Type

Standards Track

vague cairn
#

Fair enough. Thanks.

night quarryBOT
#

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:

https://paste.pythondiscord.com

vague cairn
#

So this works as intended for .__dict__ objects, does anyone know how .__slots__ objects differ?

sick hound
#

Does any1 have a code golf beginners guide

vague cairn
#

there was another one even better (on github I think.) but it looks like it didn't get pinned.

restive void
# vague cairn 3.8.1

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")
proper vault
#

I have also seen next or getattr used

maiden river
#

!e

f=lambda n:f(n-1)+f(n-2)if n>0 else 1;print(f(8))
night quarryBOT
#

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

55
maiden river
#
def f(i,j):print(i);f(j,i+j)
f(1,1) 
steep mural
cursive pine
#

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.

cursive pine
#

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

@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
cursive pine
#

tells me nothing

sick hound
#

it prints out those numbers

vague cairn
#

Please, Don't name your variables O and _0 in production code...

cursive pine
#

lol

#

1/O

sick hound
#

this is the point

#
0 and O```
#

not much difference

cursive pine
#

I was just wondering if it did anything (like those numbers have meaning)

vague cairn
cursive pine
#

Is there any code in python that provably needs more than one line to run?

sick hound
#

do u know how it works tho

cursive pine
#

I can parse it

#

you mostly used variable abuse

sick hound
#

[]=[] is True = True which is 1 = 1 which returns 1

cursive pine
#

the rest is simple

sick hound
#

+0 at the end is boolean to int

vague cairn
#

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

sick hound
#

yeah

#

that the idea

#

my first esoteric code

#

its a start

cursive pine
#

Code challenge. Print the ABCs in python using as few different letters as possible (numbers, symbols are fair game)

vague cairn
#

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?

sick hound
#

i could try that

cursive pine
vague cairn
#

Ok, so baseline is print(''.join(chr(A) for A in range(b'A'[0],b'Z'[0])))

astral rover
#

print(__import__("string").ascii_lowercase) is fewer different letters

cerulean rivet
#

^

sick hound
#

idk lol

#

im just learning more and making esoteric projects

#

been doing python for a year now

cursive pine
restive void
sick hound
#

oh and megabyte is 1000 bytes yeah thats it

#

ty

cursive pine
#

!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))```
restive void
astral rover
#

its a kilobyte

#

mega is 10^6

sick hound
#

1000 bytes = kilobyte, 1000 kb = 1 mb

restive void
#

well... in storage that's how it's counted usually. At least in memory, 1KB is 1024 Bytes

vague cairn
#

!e

print(len({c for c in "print(''.join(chr(A) for A in range(b'A'[0],b'Z'[0])))"
          if c.isalpha()
          }))
night quarryBOT
#

@vague cairn :white_check_mark: Your eval job has completed with return code 0.

16
astral rover
#

thats 1 KiB

cursive pine
#

though I was not golfing there

restive void
vague cairn
#

Are we competing for letters or symbols, as you proved symbols is easier to count.

restive void
sick hound
cursive pine
#

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

@cursive pine :white_check_mark: Your eval job has completed with return code 0.

001 | abcefghijnoprtz
002 | 15
cursive pine
#

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

@cursive pine :white_check_mark: Your eval job has completed with return code 0.

001 | acegilmnoprstw
002 | 14
cursive pine
#

Can we go lower though?