#esoteric-python

1 messages Β· Page 63 of 1

grave rover
#

or well, this week

sick hound
#

Did you solve or you are going to solve?

grave rover
#

going to

#

gonna time myself to do this

sick hound
#

i'm currently working on that with python's internal parser interface

#

and lib2to3's utils

grave rover
#

neat

sick hound
#

i'm thinking about using ast, it is really hard to find relevant info from CST

grave rover
#

I've come pretty far, but getting the context a function was created in is quite the pain

grave rover
#
def v():  # float
    return 10.0


def w():  # str
    return "abc"


def y() -> int:  # int
    # note: annotation not used, just to test function return inheritance
    z = 1
    return z


def x():  # int
    return y()


def z():  # None
    pass


v -> <class 'float'>
w -> <class 'str'>
x -> <class 'int'>
y -> <class 'int'>
z -> None
#
def u():  # Tuple[int, bool]
    return 10, True

u -> typing.Tuple[int, bool]
#
def s():  # List[Union[str, int]]
    return ["10", 15, "abc", 1, 2, 3]


def t():  # List[int]
    return [10, 20]


s -> typing.List[typing.Union[str, int]]
t -> typing.List[int]```
grave rover
#

added support for indexing and simple operators \o/

calm rampart
#

does typing let you represent a tuple of arbitrary size of one type, or a list with specific elements?

grave rover
#

yeah kinda I guess

#

List[Union[type_1, type_2]]

#

no arbitrary size tuples tho

#

AND YES I GOT LISTCOMPS WORKING

calm rampart
#

no i meant like, using List like you would Tuple, if you want "a list of 'str int str int int'"

#

i guess the answer is "you're not supposed to do that"

grave rover
#

not really nope

tropic gulch
calm rampart
#

ah so you can do that, just not the other way around

tropic gulch
#

For arbitrary tuple size, you use an ellipsis

grave rover
#

yeah but he means a Tuple of a repeating pattern iirc

tropic gulch
#

What's the other way round? Just joined the convo

calm rampart
#

no i just meant the way your list example works

grave rover
#

though I guess you could do Tuple[Sequence[x, y, z], ...]

#

oh

calm rampart
#

@tropic gulch if you can specify a list of N specific elements, the way you would with a tuple

grave rover
#

List[Union[str, int]] is just a List of both str and int

calm rampart
#

also somewhat curious if typing can specify limited value "types"

grave rover
#

wdym

calm rampart
#

like, a type for only positive integers, or only integers that can be represented as a 32-bit signed value, or only a str that is exactly "A", "B", or "C"

tropic gulch
#

I don't think a "List with fixed length" type is supported, probably due to lists being mutable

#

at least I don't see one in the docs right now

fallen heath
#

you could make one though

calm rampart
#

a type for only integers that are valid indices for the list that is passed in as another argument

grave rover
#

now I need to support KT/VT

calm rampart
#

imagine like list.find -> ValueConstrainedToRange[int, -1, Expr["len(self)-1"]]

tropic gulch
#

idk

grave rover
#

not really

fallen heath
#

extend list?

grave rover
#

oh also

#

what the fuck is the Optional for

calm rampart
#

Optional is just Union[None, whatever] iirc

grave rover
#

oh wait

#

yeah

#

Optional[X] is equivalent to Union[X, None].

#

time to refactor that in my API and wrapper

#

n -> typing.Dict[str, typing.Union[str, int]] dicts are now supported yay

tropic gulch
#

I'm still a bit pissed that they don't really let us do typing literals, similar to TypeScript

#

like you have to do Dict[str, List[int]] instead of {str: [int]}

grave rover
#

hm

#

DictComps are annoying to impl

#

ah fuck all my comps are fucked

#

sstill pretty proud of what I've done so far tho

#

so aside from comprehensions and more complex operators (cause I was lazy), generics and function arguments, I've got everything covered

tropic gulch
#

comprehensions are Awesome

grave rover
#

not when you have to estimate the result type

tropic gulch
#

πŸ€” example?

grave rover
#
def o():
    y = [1, 2, 3, 4]
    return ["a"*(x+1) for x in y]

#

getting just function o, I have to estimate output type for my challenge I posted

tropic gulch
#

it's pretty obvious, don't you think?

#

I mean, not really less obvious than a for-loop, unless you split out every single operation into a lengthy named temp variable assignment

grave rover
#

the issue is

#

I need to work with ast

#

and that's a pain

#

especially when working with e.g. generators that can run out

tropic gulch
#

ok, I never touched ast yet

grave rover
#

I shouldnt be doing this while watching jojos

tropic gulch
#

pictures of code... RageCoggersButItExplodes

grave rover
#

do you want the full code?

tropic gulch
#

no thanks

grave rover
#

get ready to download about 20MB of code

brisk zenith
#

20MB?

grave rover
#

I'm kidding

calm rampart
#

My version of the Javascript Private Variable Trick

#
import weakref
class MagicKey: pass


def _():
    mydict = weakref.WeakKeyDictionary()
    class TemperatureProperty:
        def __init__(self):
            nonlocal mydict
            mydict[self] = weakref.WeakKeyDictionary()
        def __get__(self, obj, otype):
            nonlocal mydict
            return mydict[self][obj.magic_key]
        def __set__(self, obj, value):
            nonlocal mydict
            value = float(value)
            if value < 0: raise ValueError()
            mydict[self][obj.magic_key] = value
    return TemperatureProperty


TemperatureProperty = _()


class HasTemperatureObj:
    __slots__ = ('magic_key')
    temperature = TemperatureProperty()
    def __init__(self, temperature):
        self.magic_key = MagicKey()
        self.temperature = temperature
tropic gulch
#

from what I can see, your only project file has roughly 300 lines

grave rover
#

250, 100 of which are test cases and logging

calm rampart
#

Of course, even that isn't truly private... ```py

TemperatureProperty.init.closure[0].cell_contents[HasTemperatureObj.dict['temperature']][o.magic_key] = -1
o.temperature
-1```

grave rover
#

lmfao

#

why do you need private vars tho

calm rampart
#

just for fun

vague gust
#

i hate this, thanks

grave rover
#

also, just use inspect.stack and verify it's being accessed from the same class, otherwise error

#

btw yw joseph

brisk zenith
#

visit_ListComp

grave rover
#

ignore shit_Case

#

it's the ast.NodeVisitor standard

snow beacon
#

Well, my lambda f:object code may not get the regular points for working with all of those types, but it certainly gets the shortness and no-AST bonus points

grave rover
#

it doesnt accomplish the task at hand very well though

#

at least do lambda f:[object,type][type(f)==type]

grave rover
grave rover
worthy quiver
#

its kinda pythonic

#

well, it was

#

its ded now

stone apex
#

rip

snow beacon
#

It looks like Python with static types

worthy quiver
#

from my understanding it was made by one guy, who couldnt keep working on it because of his job..and hes been looking to sell it for someone to keep working on.....that was 2 year sago

#

pretty sure its just dead

#

its also fully .net compatible

calm rampart
#

did you know you can destructure an empty iterable into an empty "tuple"? for () in [()]*100: pass perfectly valid. Don't know what it could be useful for, but seems worth mentioning here

brisk zenith
#

yup, i use this when doing one-liners and golfing at the same time. it can be used to raise custom exceptions in lambda functions. ```py

f = lambda e: (0for()in()).throw(e)
f(IndexError("nope you can't do that"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
File "<stdin>", line 1, in <genexpr>
IndexError: nope you can't do that

cunning wave
#
>>> import ast,os as t1
>>> t1
<module 'os' from 'C:\\Users\\Henrik\\AppData\\Local\\Programs\\Python\\Python37\\lib\\os.py'>
>>> ast
<module 'ast' from 'C:\\Users\\Henrik\\AppData\\Local\\Programs\\Python\\Python37\\lib\\ast.py'>
>>>

i dont like this

snow beacon
#

import os as t1, ast as t2

cunning wave
#

yes but no

#

this is highly confusing

brisk zenith
#

how is it confusing?

cunning wave
#

i want it to work like tuples 😦

#

as in

#

import ast, os as t1,t2

calm rampart
#

from sys import version_info[:2] as (major, minor) πŸ˜›

wind maple
#

it works the same way as as anywhere else

#

e.g. with statements

snow beacon
#
import os as T_, ast as _1
T1 = T_, _1```
grave rover
#

too bad import (os, ast) as t1 doesn't work

tropic night
#

That looks like something you could emulate using importlib. But I would have to spend some time thinking about it

frozen fog
#
T1 = tuple(import_module(modname) for modname in ('os', 'ast'))

MUCH better πŸ˜„

snow beacon
#

Username checks out

tepid glacier
#

lmao

stone apex
#
print(*license._Printer__lines[225:230], sep='\n')```
#

Actually, I need to amend that, because it doesn't work without setup

#

!e python print(__builtins__.license) print(*license._Printer__lines[225:230], sep='\n')

night quarryBOT
#

@stone apex Your eval job has completed.

See http://www.python.org/3.6/license.html
stone apex
#

Hm, different results from snekbox than local python

#
print(license)
print(*license._Printer__lines[225:230], sep='\n')
vague gust
#

probably varies on version

#

snekbox is running 3.6.6

wind maple
#
8. By clicking on the "ACCEPT" button where indicated, or by copying,
installing or otherwise using Python 1.6.1, Licensee agrees to be
bound by the terms and conditions of this License Agreement.

        ACCEPT```
stone apex
#

Well are you gonna click it or not?

snow beacon
#

What's it meant to do?

#

Turn 3 into 4?

#

Except only when you put ++ at the start?

grave rover
#

Tfw nobody has completed the challenge yet aside from me

snow beacon
#

I completed a challenge

grave rover
#

Yea true

#

So 1 point to you

snow beacon
#

Oh, the ++ thing also works with --. It just doesn't save the result.

grave rover
#

==============================
Another week has passed, and here's a fun one:
Fibonacci February is coming up, so write the shortest Fibonacci code you can muster!
It must be a function with as argument the n-th number it wants, implementation is up to you.

Returns: n-th number OR sequence of n items


Scoreboard:
Week 1:

  • IFcolstransG: 1

Week 2:

  • <Open Bounty>

Week 3:

  • <This Week>
snow beacon
#

Any preference of return vs print?

grave rover
#

Two options: functions should return, or your code gets called with python file.py N, where it should be printed

snow beacon
#

That second one seems harder.

snow beacon
#

I don't think you need to print the function. Just create it.

#

Should we output all the numbers up to the desired amount, or just the last one?

#

And do we need a specific start value? e.g. 0,1,1,2 or 1,1,2,3

#

And does the function need to work more than once?

wind maple
#

so does it return the nth number or the first n numbers

#

oh that was just asked

#

does it have to print or return

snow beacon
#

If your code takes input from file arguments you print, and if you have a function then return it

wind maple
#

I do not abide by these rules

snow beacon
#

It's probably simplest to make a function

wind maple
#
def f(n,a=1,b=1):
 print(a)
 if n:f(n-1,b,a+b)```
#

enjoy

snow beacon
#
f=lambda n,a=[1]:exec("a+=sum(a[-2:]),;"*~-n)or a```
#

f(n) returns the list of Fibonacci numbers up to the nth

snow beacon
#

After the first time, it returns more of the sequence rather than the first terms again.

#

e.g. f(5) -> [1, 1, 3, 5]
f(5) -> [1, 1, 3, 5, 8, 13, 21, 34]

brisk zenith
#

oh hey, a*~-b is a good alternative to a*(b-1), nice :D

#

well, "good". it's horrific, but i love it.

#

well, when a is a 1-char literal (like 5) then you could just do 5*b-5

#

but when a is longer (like in your case), that other way's pretty good.

snow beacon
#

I can't claim to have invented it. I saw it online. It looks nice too, and can be used to either add or subtract depending on the order

snow beacon
#

What I did do is think it was neat, remember it for later, then apply it here.

#

By the way, I did a bit of comparisons of what would be shortest if ~-n didn't work.

#
f=lambda n,a=[1]:exec("a+=sum(a[-2:]),;"*(n-1))or a
f=lambda n,a=[1]:exec(("a+=sum(a[-2:]),;"*n)[16:])or a
f=lambda n,a=[1]:exec("a+=sum(a[-2:]),;"*n)or a[:-1]``` The shortest seems to be the first.
grave rover
#
a=5**.5;f=lambda p,n=(1+a)/2:(n**p-(-n)**-p)/a//1```
#

Returns the n-th Fibonacci number without recursion

snow beacon
#

Neither does mine, and yours is exactly the same length as mine. Spooky.

#

Oh, you used that cool ΙΈ formula!

grave rover
#

Yeah

#

//1 is only needed to remove the floating point issues like 0.300000004

#

Made it 1 byte shorter

snow beacon
#

Wait, why not do //a instead?

#

Oh, a is float.

#
a,n=5**.5,.5+a/2;f=lambda p:(n**p-(-n)**-p)//a``` works for me. Saves 2 more characters
snow beacon
#

Actually, I think I might not have tested the multiple assignment properly.

#
a=5**.5;f=lambda p,n=(1+a)/2:(n**p-(-n)**-p)//a```should do the job
snow beacon
#

So does this mean that the canonical implementation returns a single value rather than a list of values?

slim nimbus
#
f=lambda n:n if n<2 else f(n-1)+f(n-2)
f=lambda n:f(n-1)+f(n-2)if n>1else n
snow beacon
#
f=lambda n:+(n<2)or f(n-1)+f(n-2)``` would be shorter. And you can get rid of the `+( )` near the start if you don't care about it returning `True` instead of 1.
#

You probably can't actually make it shorter by moving parts around to get rid of the space between f(n-1) and or.

#

You might be able to shorten the conversion to int

#

or turn the condition into an integer

grave rover
#

@snow beacon both work tbh

snow beacon
#
f=lambda n:n<2or f(n-1)+f(n-2)``` in that case
grave rover
#
a=5**.5;f=lambda p:round((.5+a/2)**p/a)``` shortest I can muster using direct calc
honest spruce
#

I'm on a fb page

grave rover
#

@snow beacon no like, I meant for the task, True is not a number so doesn't count

frosty maple
#

Python: lang = lang(Java) - ";"

grave rover
#

Wat

sick hound
#

He tries to say python is a version of java without semilcons (and he is wrong)

snow beacon
#

True is almost a number

brisk zenith
#

True is a number in my heart ||and my code||.

snow beacon
#

True should be -1, but at least 0 is False

pine edge
#

behold

#

python2

#
>>> True is 1
False
>>> True = 1
>>> True is 1
True
sick hound
#

well you know

#

it doesn't throw errors if you're using built ins

#

only linter gives you a warning

#

so..this makes sense

grave rover
#

What the fuck Py2

snow beacon
#

True is basically just a variable, initialised to True

#

But not in Py3

grave rover
snow beacon
#

The ∧ is and, right?

wind maple
#

In the description there's a tool that will let you experiment with these

snow beacon
#

I wrote a python version of the C thing

#

I wanted to see how it worked.

#

Unfortunately, I don't have aplay

#

So I used some tool to convert the resultant file into a .wav

#

I don't remember the details.

#

But I might be able to find the code...

brisk zenith
#

python confuses me. how does it handle things like "hello!".__str__.__str__.__str__.__str__ ...? where (well, how) does it store these methods? πŸ‘€

slim pecan
#

They're not necessarily python methods all the way down

#

At some point you're calling C code

#

Although in this case it just returns self because duh

#

Oh right, you didn't call it

#

Gotta be there though

cunning wave
#

interesting each of those actually has a unique memory address

#

they all exist seperately in memory

tropic gulch
#

each of them is probably a lazily generated instance of method_wrapper that gets only made when you look it up

cunning wave
#

considering the address changes every time that is probably correct

tropic gulch
#

After looking at the code in descrobject.c, I think a method-wrapper is
used to create a Python object out of internal methods (stored as C
function pointers in the type structure), as if they were actual Python
methods.
That is, they wrap an internal function pointer (defined in the type)
along with a Python object ("self"), so it can be used in Python code as
it were a normal instance method. But certainly I can be wrong...

--- https://bytes.com/topic/python/answers/802984-method-wrapper

#

not exactly a high quality source, but it seems to be a C method wrapper

slim pecan
#

That's basically what I was thinking

brisk zenith
#

hmm okay sure

glacial rampart
#

@grave rover you could make it shorter as lambda p,a=5**.5:round((.5+a/2)**p/a) if it's ok to remove the assignment to f

grave rover
#

removing assignment is not allowed because now there's no variable you can call

brisk zenith
#

i decided to make a program which dumps a load of info about an object to JSON for my esoteric debugging needs. it's not really polished but if you want me to put the code on github or something then lemme know.
for example, when told to dump my_var at the bottom of this: ```py

class ParentClass:
parent_class_var = "spoooooooky"

class SomeClass(ParentClass):
class_var = {
"this is a simple value": 694201337,
"this is a complicated value": lambda: "lambda thing!"
}

def __init__(self, thing):
    self.thing = thing
    self.something_else = "hiya!"

def __str__(self):
    return self.thing

def __iter__(self):
    yield from self.thing

def regular_method(self):
    return self.something_else.stuff

my_var = SomeClass("Hello!")

it produces the following JSON: https://hastebin.com/emunemiral.json
grave rover
#

WEEK 4

Last week's results:
@snow beacon got the shortest with the following solution:
f=lambda n:+(n<2)or f(n-1)+f(n-2)

Scoreboard:
Week 1:

  • IFcoltransG: 1
    Week 2:
    <open bounty>
    Week 3:
  • IFcoltransG: 1

As for this week's challenge:
Write the shortest discord bot that does the following:

  • !say echo bot
  • !calc do simple addition/subtraction (no eval/safe_eval)
  • bonus if this is all within a lambda (shortest lambda will also get a point)

One point for each, assuming your code is the shortest in the category

opaque narwhal
#

dam nice code @brisk zenith

brisk zenith
#

thanks :D

snow beacon
#

I've never coded a Discord bot, so I expect my reign of terror is coming to an end.

snow beacon
#

Can !calc be made to only parse positive integers with no leading 0s?

#

And only two numbers per message?

#

And is output in a message or a return value?

wind maple
#

Today in things absolutely no one asked for py [print(a) for a, b in [(0, 1)] for x in __import__('itertools').cycle('a') for a, b in [(a + b, a)]]

#

cc @grave rover

valid grove
#

Fibonacci number?

grave rover
#

@snow beacon and real number should work

grave rover
#

(lambda bot: bot.command("say")(lambda ctx, *, message: asyncio.ensure_future(ctx.send(message)))(...)!say command using lambdas only

#

Now just calc left

#

Done calc

grave rover
#
__=__import__;f=(lambda t,_=__("discord").Client(),____=__("asyncio").ensure_future:(lambda **f:setattr(_,"_",f))(say=(lambda ___:____(___.channel.send(" ".join(___.content.split()[1:])))),calc=(lambda ___:(lambda _____,______,_______:____(___.channel.send({"+":_____+_______,"-":_____-_______,"*":_____*_______,"/":_____/_______}[______])))(*(lambda ________,_________,__________:[float(________),_________,float(__________)])(*___.content.split()[1:4]))))or(lambda:setattr(_,"on_message",lambda ___:_._[___.content.split()[0][1:]](___)if ___.content[0]=="!"else""))()or(lambda:_.run(t))())

f(TOKEN_HERE)
#

I cant make it any less readable

#

674 chars

snow beacon
#

Wait, does the bot need to do division?

#

And what's with all the underscores?

#

Anyway, I'm going to steal your code, pull it apart, then make it different, because I have no idea how discord bots work.

#

I feel like you could make that code a lot shorter by changing the variable names and replacing all the (lambda:blah)() with blah

grave rover
#

most of the lambdas are to store stuff in variables to make it a bit more workable, and the underscores are just for the memes

#

I could probably reduce some of these variable name lengths

snow beacon
#

What about the lambda at the very end?

#

(lambda:_.run(t))()

#

Isn't that just _.run(t)?

#

In any case, I'm not sure this was the best piece of code for me to dissect in order to learn how to make a discord bot.

#

I've not really got it into a form I understand.

#

I meddled with it by replacing all the variable names and stuff, and then I changed parenthesis until it ran properly.

#

Ran properly with the token being "TOKEN_HERE" and client replaced with None

#

This seems like the sort of thing where I just give up and write my own.

#

I'm going to go to bed. When I wake up, hopefully I'll have the sense to give up on this.

dense spire
#

@snow beacon this might in fact be the worst possible code you could dissect in order to learn how to make a discord bot :D

#

although there's nothing esoteric about that I guess.

grave rover
#

Yeah it's horrible code

dense spire
#

it's fun, though.

grave rover
#

And it works

dense spire
#

example output?

grave rover
#

Picture is above

dense spire
#

oh. sorry. for some stupid reason I thought you meant rhyming in your love letter thing :D

#

brainfart

grave rover
#

Ah

#

Doing that in half an hour or so

silk ruin
#
def l(n,k):return(sum(map(ord,n))*sum(map(ord,k)))%100```
Had that laying around. It's a love calculator for non-discord usage
calm rampart
#

if you're going for minimal character count, you can lose a space in the argument list and use shorter variable names

silk ruin
#

true that

calm rampart
#

also map(ord,...)

#

and unless there's a reason to use split(' ')

silk ruin
#

man things can get small

calm rampart
#

actually, n.replace(' ','') is shorter

#

well, if you needed to still omit the spaces my first suggestion was split() - either that or omitting it entirely are both semantic changes though, technically. But replace is shorter and no semantic change from what you had

#
def l(n,k):return(sum(map(ord,n.replace(' ','')))*sum(map(ord,k.replace(' ',''))))%100
#

hmm do you need the outermost parenthesis?

#

lambda is shorter ```py
l=lambda n,k:(sum(map(ord,n.replace(' ','')))*sum(map(ord,k.replace(' ',''))))%100

brisk zenith
#

heck

#

beat me to it

calm rampart
#

well i honestly don't know, are * and % left-associative?

#
l=lambda n,k,F=lambda x:sum(map(ord,x.replace(' ',''))):F(n)*F(k)%100```
brisk zenith
#

i swear sum had a key argument but apparently not

#

probably thinking of max and min

#

πŸ‘€

#

oh hm

#

very well

#

also what does this code do?

calm rampart
#

what the fuck did i do

brisk zenith
#

probably parentheses or something

calm rampart
#

oh wait

#

i didn't remove the outer parens from the other one

#

doesn't matter because sum doesn't have a key argument though lol

brisk zenith
#

yeah haha

#

shame really

#

what does the code do?

calm rampart
#

anyway they said it's a love calculator

#

so just some random numerology thing on people's names i guess

brisk zenith
#

i see

#

oh okay sure

silk ruin
#

yeah

#

Takes two numbers, multiplies them together and takes the modulus of 100 from them as the percentage

wind maple
#

shouldn't it be 101

silk ruin
#

no that there is no 100 is intentional

#

I mean I couldve done that on my commit for the seasonal bot now that you say it

pine edge
#

an equally random but persistent love calculator

#
l=lambda a,b:hash((a,b))%100
snow beacon
#

How aboutpython l=lambda a,b:hash(a+b)%100

#
l=lambda*a:4``` Is probably cheating
brisk zenith
snow beacon
#
l=lambda*a:hash(a)%100```
amber tide
#

Esoteric is code word for python lambda

brisk zenith
#

not quite, but usually yes.

snow beacon
#
l=lambda*a:63&hash(a)```if you don't mind restricting it to up to 63%
#

It's a bit pessimistic about love.

#

Anyway, did you know that ....__sizeof__() == 8

brisk zenith
#

yes

#

ellipsis is cool

#

i think people here have already established that it's my favourite singleton

snow beacon
#

I'm partial to NotImplemented

brisk zenith
#

yeah but ....

snow beacon
#

If only an ellipsis literal could be an attribute of an ellipsis

#

.......

stray needleBOT
brisk zenith
#

(shhh, tell nobody)

#

challenge 05 is here!

to follow the server's current seasonal theme, this challenge is about hearts. i've decided to pick a relatively simple task for this one because there's already #542272993192050698 going on right now. anyway, the goal of this challenge isn't necessarily to get the shortest code, so i encourage you to add your own features and extensions while adding your own spicy weirdness to the program! i'm looking for the most spectacularly esoteric code you can create, so give it your best shot. details can be found over on the repository: https://github.com/python-discord/esoteric-python-challenges/tree/master/challenges/05-text-hearts

happy hacking! ❀

grave rover
#

I know exactly how to do this

brisk zenith
#

but can you do it with ONE HUNDRED PERCENT SPICE? :D

vague gust
#

oWo

#

also @brisk zenith you have a bad gitconfig somewherer

brisk zenith
#

yeah well

#

i'll deal with that at some point soonβ„’

vague gust
#

lol

brisk zenith
#

i'll get started on my own solution soon, i've got some ideas.

grave rover
brisk zenith
#

hey i mean, if it works for one case it must work for all of them, right?

#

also, don't forget, it doesn't have to perfectly match the examples provided on the repo.

#

just as long as it looks remotely like a heart, that's fine

#

and if it breaks hilariously for large numbers, then that's fine too :D

fallen heath
#

On a phone even, nice

brisk zenith
#

yeah good effort :D

tropic gulch
#

my first attempt produces this.... πŸ˜‚ πŸ₯š

             #####             
           #########           
          ###########          
         #############         
        ###############        
       #################       
     #####################     
    #######################    
    #######################    
   ##########     ##########   
   #########       #########   
  #########         #########  
  #########         #########  
  #########         #########  
  #########         #########  
  #########         #########  
  ##########       ##########  
   ##########     ##########   
   #########################   
   #########################   
   #########################   
    #######################    
    #######################    
     #####################     
     #####################     
       #################       
         #############                                
brisk zenith
#

hahaha that's great!

tropic gulch
#

it's a love egg

#
        #   ##   ##   #        
      #      #####      #      
     #       #####       #     
             #####             
    #         ###         #    
                               
                               
                               
    #  #               #  #    
    ####               ####    
    ####               ####    
    ####               ####    
    ####               ####    
    ####               ####    
    ####               ####    
     ###               ###     
       ##             ##       
        ##           ##        
          #         #          
           ##     ##           
            #######            
             #####             
             #####             
              ###              
fallen heath
#

Halo mask

fallow cairn
#

weird iron man

dense spire
#

strongbad

#

whatever it is, I love it

frozen fog
#

This channel may appreciate this one-liner from diabolical genius David Beazley

_ = type('',(),dict(__getattr__=lambda s,_:s))()
tropic gulch
#
                                   
   ####                     ####   
  ##  ##                   ##  ##  
  #    ###               ###    #  
  #      ##             ##      #  
 ##       ##           ##       ## 
 #         ###       ###         # 
 #           ##     ##           # 
 #             ######            # 
 #                               # 
 #                               # 
 #                               # 
 #                               # 
 #                               # 
 ##                             ## 
  #                             #  
  #                             #  
  ##                           ##  
   #                           #   
   ##                         ##   
    #                         #    
    ##                       ##    
     ##                     ##     
      #                     #      
      ##                   ##      
       ##                 ##       
        ##               ##        
         ##             ##         
          ###         ##           
            ###     ###            
              #######              
                                   ```
#

good enough

frozen fog
#

Anyhow... regarding ascii hearts... What I'd want to do is create a context manager to monkey-patch the print function, so that whatever you print is arranged in a appropriately sized heart like

with love_printer:
    print('Hello World!')

would produce something like

 Hell   o Wo
r    l d    !
H     e     l
 l         o
          W
   o     r
    l   d
     ! H
      e
tropic gulch
#

😍 nice one

#

now write it πŸ˜„

frozen fog
#

What I got so far, which I used just to be able to show the idea:

s = '''
 ####   ####
#    # #    #
#     #     #
 #         #
  #       #
   #     #
    #   #
     # #
      #
'''
from itertools import cycle
chars = cycle(list('Hello World!'))
for line in s.split('\n'):
    while '#' in line:
        line = line.replace('#', next(chars), 1)
    print(line)
#

But apparently monkey patching builtins is tricky because of how early they get created.

#

The idea would be that you could magically transform any existing program using print to write a bunch of these hearts πŸ˜›

frozen fog
#

So, how do I actually submit something? Do I just open up a PR?

tropic gulch
#

yeppers

#

also first 😁

stray needleBOT
tropic gulch
#

GWchadLENNYTHINK 🐍 πŸ’¦

frozen fog
#

Β―_(ツ)_/Β―

#

so, that's what I came up with, instead of doing my job or being productive at work πŸ˜›

#

amidoinitrite?

snow beacon
#

I'm working on a weird one, and it involves more maths than I anticipated.

#

It involves complex loci/Argand diagrams

#

Hopefully I can boil it all down to whether x<3, where x is yet to be determined.

frozen fog
#

x<3 x ❀ πŸ˜ƒ

snow beacon
#

Exactly. Currently, I'm up to my neck in complex numbers, but once I'm done with that I'll reformat it to include that sort of inequality.

grave rover
#

Dangit my answer is gonna look like copying byte

#

I do the exact same but with (x**2 + y**2 - 1)**3 - x**2 * y**3 = 0

snow beacon
#

Looking across my tabs, I can see I have Desmos open twice, two Wolfram|Alphas, 5 questions from stackexchange, 3 python docs, 3 Wolfram Mathworld tabs, and a bunch of other assorted miscellany. This is going to be an esoteric program, no doubt.

grave rover
#

Got a working impl based on that formula, now to fancify code

#

I actually have another idea but it'd be a bit much

snow beacon
#

I've got a code thing, is there an easy way to post it, or do I have to learn Git?

eager inlet
#

!codeblock

night quarryBOT
#
codeblock

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:

```python
print("Hello world!")
```

This will result in the following:

print("Hello world!")
snow beacon
#

I mean the heart challenge

#

I've made a GitHub account, and I'll upload my code in the morning.

grave rover
#

@snow beacon gist would be easiest

stray needleBOT
snow beacon
#

I just used GitHub to add the file. (The morning can wait.)

grave rover
#

@snow beacon sample output?

snow beacon
#

I just closed down all my stuff. It looks like the 5th Wolfram Mathworld heart curve, filled in with octothorpes.

#

It scales resolution based on an input number.

#

Anyway, see you in ten hours!

topaz fable
#

dose it have to be ritten in python?

grave rover
#

Yes

grave rover
#

aight guys

#

new PR inc

slim pecan
#

New PR Incorporated

stray needleBOT
grave rover
#

h =                    (lambda n:(lambda               o=int(.5*n//1):
                    [([(                lambda   m=(x/n             *3),l=(
                  y / n                   *3):  print              ([" ","#"
                    ][(                      m**2                   +l**2
                     -1)                                            **3
                      -m**2                                        *l
                        **3                                       <0
                         ],end                                  =""
                          ))                                   ()
                            for                              x in
                              range                        (-o,
                                o)]                     ,print
                                  ())                  for
                                    y                 in
                                     range          (o,
                                        -o,       -1
                                          )]     )(
                                             ))


if __name__ == "__main__":
    h(10)
    h(50)
    h(100)```text version for people too lazy to open link
wind maple
#

impressive

dense spire
#

@grave rover that's amazing

#

nice work, dude!

grave rover
#

Thanks! I knew I could do something like this if I had the code in functions, turning it into lambdas was easy but making it look like a heart in code was quite the challenge :D

#

Fun fact: anything can be done using lambdas only, even asyncio (with a limit tho)

dense spire
#

all four of the solutions so far are super fun

grave rover
#

Yee

dense spire
#

great to see people participating

brisk zenith
#

haha mart, that's what i was gonna do

grave rover
#

beat ya to it fam

brisk zenith
#

i've got an interesting idea which is probably going to be real difficult to do

grave rover
#

challenge accepted

brisk zenith
#

heart-shaped quine

grave rover
#

oh no

brisk zenith
#

still accepted? :^)

grave rover
#

dunno, never been good with quines

#

and inspect.getsource isnt allowed :(

cunning wave
#

@brisk zenith no u I thought of that the moment mart sent his thing

brisk zenith
#

then do it

#

i'll look at the submissions once i get home in a few minutes :D

brisk zenith
#

i am now home, two hours later lmao. i'm taking a gander at the submissions now.

brisk zenith
#

i think i should squerge these actually

vague gust
#

i don't like squerging :(

brisk zenith
#

very well, i shalln't

wind maple
#

squerging is nicer tbh

brisk zenith
#

for these small PRs i'd prefer it

wind maple
#

it doesnt make the tree

*
|
*
|\
**
|/
*
|```
brisk zenith
#

although sure, we can not squerge

dense spire
#

@brisk zenith consider that if you squerge that, byte is no longer a contributor

#

if you don't, he gets credit.

brisk zenith
#

yeah that's what i was thinking

#

everyone deserves credit, so squergen't it is.

#

@grave rover @snow beacon are you guys okay with having your PRs merged, or are you still making tweaks to them? i've checked both of them, they're real neat :D

snow beacon
#

I'm done for now

#

Thanks

brisk zenith
#

okay, cool! if you think of any changes you want to make, or if you want to create a second submission, feel free to make a new PR. :)

#

good work.

stray needleBOT
tropic gulch
#

Can't you just do a fast-forward instead of a merge commit? That would also keep the tree equally clean as most contributions there are only one or two commits anyway

brisk zenith
#

not sure how that works

tropic gulch
#

git merge --ff

#

should actually be the default though

#

might have to do a rebase first if needed though

sick hound
#

I used this guys code

grave rover
#

@brisk zenith feel free to merge

brisk zenith
#

hahaha i was actually expecting somebody to give an actual heart

sick hound
#

so not very original, but it was fun to make and used tools I had already

#

I wanted to make it beat too, but that sounded like entirely too much work

tropic gulch
#

there are existing gif2ascii converters too

sick hound
#

i think img2txt can do that

#

maybe

#

you can do it with cacaview which comes with img2txt

#

You can convert entire moves and watch them in terminal with cacaview, lol

snow beacon
#

I just realised I made a typo in one of my comments for my heart code.

#

It's one character, so I can't be bothered fixing it.

brisk zenith
#

that's fine, feel free to fix it if you wish to make any other changes.

snow beacon
#

Hmm. #esoteric-python is the one place where everyone is fine with my horrible coding style.

snow beacon
#

If x=" Insert a sequence of one or more characters not including " or ' here ", then how can I make len(x) divided by the sequence of characters be as small as possible? Basically, what's the least character efficient way to use escape sequences to produce a string?

sick hound
#

interesting
spam the 8-char \Uxxxxxxxx escapes, i'd say -- len('\U00000000') == 1

#

oh shoot wait even better

#

use \N{} to type the name of some character that has a really long name

#
>>> len('\N{LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON}')
1```
stray needleBOT
candid cobalt
#

ΒΏam I doing it right?

snow beacon
#

I had no idea those types of escape character sequences existed, but I figured there'd be something juicy. \N{} certainly qualifies

#

@candid cobalt do you just rasterise a heart shape from a font? Neat!

#

Oh, is it the reverse?

#

You display a heart with a picture?

#

Damn Traceback (most recent call last): File "C:\Users\<Data Excised>\Desktop\<Data Excised>", line 5, in <module> m=ImageFont.truetype('DejaVuSans.ttf',32).getmask('\u2665') File "C:\Users\<Data Excised>\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\ImageFont.py", line 280, in truetype return FreeTypeFont(font, size, index, encoding, layout_engine) File "C:\Users\<Data Excised>\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\ImageFont.py", line 145, in __init__ layout_engine=layout_engine) OSError: cannot open resource I can't test it out on my machine.

candid cobalt
#

huh, I assumed everyone has dejavu sans and 256 colours on the terminal

snow beacon
#

How do you get the picture of the heart? Is that the font thing?

candid cobalt
#

yup

snow beacon
#

Ah, so I was right the first time. A brilliant idea, and golfed too!

candid cobalt
#

what else would I need a truetype font for in a console program? πŸ˜ƒ

snow beacon
#

I was thinking it might not have been just a console program, it's a little hard to tell with all the punctuation and lack of whitespace

#

But it does quite clearly say print

#

I'm guessing p converts a greyscale value to a character

candid cobalt
#

here's the ungolfed version, with more presets πŸ˜ƒ

snow beacon
#

That's... quite a bit bigger.

#

It looks like it has more features though

#

I thought for a second it was the exact same thing.

#

Anyway, you can golf the final script a bit more, but it would mainly be things like removing whitespace, changing the imports and doing multiple assignment.

#

Oh, actually, you might be able to do something with that ''.join

candid cobalt
#

hmm map(print, [p(a)...]) perhaps

#

time to check the python golfing tips again... but tomorrow πŸ˜‰

snow beacon
#

I was thinking print(*[p(m.getpixel((x,y)))for x in range(m.size[0])for y in range(m.size[1])],sep="")

#

It might not work, I didn't test it

candid cobalt
#

thx

snow beacon
#

But even if what I just said doesn't work, you can get rid of the square brackets inside the join and turn it into a generator expression. for y in range(m.size[1]):print(''.join(p(m.getpixel((x,y)))for x in range(m.size[0])))

#

Come to think of it, if you went a,b=m.size on the line before, you would probably save some chars too.

#

a,b=m.size for y in range(a):print(''.join(p(m.getpixel((x,y)))for x in range(b)))

#

But perhaps you'd find it more fun to figure this stuff out on your own. You've certainly pulled it off so far.

candid cobalt
#

thanks, I'm happy someone appreciates my unreadable code

dense spire
#

@candid cobalt that's beautiful. :)

#

nice work

brisk zenith
#

oh hey that's amazing! it would be even cooler if the text was an itertools.cycle of "私は、あγͺγŸγ‚’ζ„›γ—γ¦γ„γΎγ™" which i believe is japanese for "i love you"

candid cobalt
#

I knew somebody speaks Japanese here! patches welcome ;)

brisk zenith
#

i don't speak japanese but that's one of the few phrases (i think) i know.

sick hound
#

Here is a little set of haiku I wrote in python XD I thought I made it pretty good, but unfortunately there is an error.

class of_recursion:
    #we fight begining to end
    def end_your(self, now):

        end_your("restless thoughts")
        #of being stuck in a loop
        #that will never start
'''
language advances
spoken in so many ways
we communicate
'''
sick hound
#

I thought that was an obscure enough bit of code to be shared here.

brisk zenith
#

oh that's pretty neat

autumn moss
#

lol thats kinda cool

sick hound
#

Ty. I made one about a save function too.

#

They are fun to write!

autumn moss
#

thats very esoteric but also really neat idea

brisk zenith
#

i misread "def end_your(self, now)" as just "end_your(self, now)" πŸ€”

#

but anyways

#

i guess my only issue with that is that you'd need to do self.end_your("restless thoughts") but that's baaddd

#

it's cool enough as it is :D

sick hound
#

I know 😦 I was sad when I saw that. But you can call it poetic license.

#

Turns out it is actually a thing

autumn moss
#

wow

snow beacon
#

I like the Lisp one, even though it's probably not a good idea to post it here.

sick hound
#

I liked that one a lot too^. Seems like a joke a programing teacher would make.
The Lisp one was one of my favorites.

autumn moss
#

what exactly is a raspberry pi useful for?

dense hare
#

iot

snow beacon
#

Raspberry Pis are tiny computers. You can use them for computing.

#

They also have Wi-Fi

#

Lot's of people use them for robots.

#

They are slightly higher level than Arduinos. Arduinos are C++ versions that sometimes come in dishwashers and other appliances. They're for if you want your magic box to calculate something more than "not (a xor b)" but don't want to put a whole PC in there.

#

And they come with Minecraft preinstalled.

cunning wave
#

Yes
Not all of them have WiFi (and there are ways to give Arduinos WiFi access too)
Yes
They are a lot higher level than Arduinos an Arduino directly executes the C code you give it and nothing else on a 8 bit AVR CPU Raspberries usually run (you can also use them like an Arduino but with more power if you want ) an operating system on a 32 or 64 bit ARM CPU which then executes the stuff you give it exactly like a normal PC
Also an Arduino can execute any programming language if its compiler can produce AVR assembly like Rust or Ada for example
And no most raspberries come without anything installed and out of the dozens of operating systems you can choose only one I know has Minecraft

grizzled cloak
#

The rpi zero has a similar size

#

Very powerfull

snow beacon
#

Is there a version of a for loop that calls send("Something") instead of next()?

wind maple
#

not really because the generator has to reach a yield in order to be able to be sent to

#

and to start a generator you're gonna have to call next

#

guess you could do this

#
>>> def foo():
...     for i in range(10): yield i
... 
>>> f = foo()
>>> f.send(None)
0
>>> f.send(None)
1
>>> f.send(None)
2
>>> f.send(None)
3
snow beacon
#

I'm imagining```python
def foo(start_value):
last = yield start_value
while True:
if last is None:
last = 0
last = yield last

f = foo(0)
for number in f sending x:
print(number)
x = number + 1```
x would contain the next value to send to the generator, initialised to None (so that the for loop always starts by sending None, which is equivalent to calling next())

#

sending would be a keyword, part of the for structure

#

Or maybe the last line would be something like python x.value_to_send = number + 1

#

I figured it probably wouldn't exist.

sick hound
#

@autumn moss I use my pi to block all adds that come through the router, to transfer files between the two partitions on my laptop, I am working on making a lego robot with it, and I have plans to make a gameboy out of it. It's cool because I can just hook it up to my router and I have another computer that I can access from anywhere in the house. I could get a server to point to it so I can access it from anywhere but don't have a reason to expose it to the greater internet at the moment.

#

My friends use them as cheap servers for webscraping projects.

#

One friend has one that monitors all traffic that comes into the modem so it is basically an extra layer of security. Another has like 3 of them all working on finding trades within the economy of some game.

#

They are pretty epic really πŸ˜ƒ

autumn moss
#

servers hmm?

#

that sounds nice

#

my internet is spotty at best so a server for me wouldnt work

#

but i could make an emulator that sounds fun πŸ˜„

winter cloud
#

What's esoteric python?

cunning wave
#

Weird python you should not use for real stuff but because it's funny or challenging doing certain things certain way

winter cloud
#

Nice

cunning wave
#

might as well just read the channel description

winter cloud
#

Oh sorry I'm on the phone

sick hound
#

formerly #barely-python, as in 'this is python, if just barely', but people started using it as an off-topic channel because the actual off-topic channels do not stand out

snow beacon
#

Anyone read any good books lately?

#

I mean, has anyone parsed any good long-form text files recently?

candid cobalt
#

the classic: The Moon is a Harsh Mistress

sick hound
#

^That was a great book!

#

something something...python

unborn field
#

Esoteric Python was what Thulsa Doom from Conan was into, right?

#

Some sort of snake cult?

sick hound
#

A contextlib.contextmanager implementation in one-line with 160 char

#
exec("c=%sf:(%s`:type('H',(),{'__init__':%ss,f,`:setattr(s,'g',f(`)),'__enter__':%ss:next(s.g),'__exit__':%s*a:None})(f,`))".replace('`','*a,**k')%(("lambda ",)*5))
#

usage:

#
exec("c=%sf:(%s`:type('H',(),{'__init__':%ss,f,`:setattr(s,'g',f(`)),'__enter__':%ss:next(s.g),'__exit__':%s*a:None})(f,`))".replace('`','*a,**k')%(("lambda ",)*5))

@c
def my_func(tot):
    a_list = []
    try:
        yield a_list
    finally:
        print(tot, a_list)
        
with my_func(15) as l:
    l.append(1)
    l.append(2)
snow beacon
#

I suppose I should have expected this to break everything.```python
def recursive():
itself = yield "This will get sent and printed properly"
print(itself.send("This won't get sent properly"))

generator = recursive()
print(next(generator))
#next line will break things
print(generator.send(generator))

#will print the following:
r'''
This will get sent and printed properly
Traceback (most recent call last):
File "C:\Users<Data Excised><Data Excised>\Generator Test.py", line 8, in <module>
print(generator.send(generator))
File "C:\Users<Data Excised><Data Excised>\Generator Test.py", line 3, in recursive
print(itself.send("Won't get sent properly"))
ValueError: generator already executing

'''```

snow beacon
#

Challenge: write a backtick "` " to any file in as few characters as possible.

humble tartan
#
print('`')

since stdout is a file :^)

grave rover
#

technically stdout is an iostream

tropic gulch
#

everything is file

grave rover
#

:thisisfile:

calm rampart
#

technically stderr is a file, and it doesn't say to not write anything else... py ` File "bt.py", line 1 ` ^ SyntaxError: invalid syntax

tropic gulch
calm rampart
#

more seriously - exit prints a string argument to stderr, so exit('`') is one character shorter than print('`')

#

though one could argue that site builtins aren't part of the language

snow beacon
#

One could also argue that IO streams aren't files

cursive fox
#

*line 6 fixed
*fixed again

# Use string bullshittery to multiply x and y without using *, /, % operators.
def product(x, y):
    xint = int(x)
    xdec = 0
    if x != xint:
        xdec = "{0:f}".format(x-int(x)).split('.')[1] 
        # xdec = "{0:f}".format(x-int(x))[2:]  # OLD
        # xdec = str(x).split('.')[1]  # OLDER

    # Product of int(x) and y
    result = 0
    for i in range(abs(xint)):
        result += y

    # Product of [decimal part of x] and y
    prod_dec = 0
    for i in range(int(xdec)):
        prod_dec += abs(y)

    len_xdec = len(xdec) if xdec else 0  # How many decimal places
    prod_dec = str(prod_dec).rjust(len_xdec+len(str(prod_dec)), '0')
    len_pdec = len(prod_dec)

    # If decimal point exists, move it leftward.
    if prod_dec.find('.') != -1:
        dec_pos = prod_dec.find('.')
        prod_dec = prod_dec.replace('.', '')
        prod_dec = float(prod_dec[:dec_pos-len_xdec] + '.' +
                         prod_dec[dec_pos-len_xdec:])
    else:  # Else, add decimal point leftward from the end.
        prod_dec = float(prod_dec[0:len_pdec-len_xdec] + '.' +
                         prod_dec[len_pdec-len_xdec:])

    result += prod_dec if y > 0 else -prod_dec
    if x >= 0:
        return result
    else:
        return -result

Allows negative and decimal numbers smaller than 1.
Known issue: errors when x has more than 3 leading decimal zeroes.
Oof, the "fix" errors when x is negative decimal. Now the fix fix combines the two and is finally Bug-Free[tm].

snow beacon
#

Neat!

#

I'm going to see if I can do that.

stray needleBOT
candid cobalt
#

thx

cursive fox
#

After I wake up, my smallbrainwojak realizes the decimal point isn't a "real thing". 123.456 is simply 123456E-3. The script would be cleaner if it doesn't split into two parts; rather, "do the thing" to the whole sequences of numbers. E.g. 123.456 squared is 123456E-3 * 123.456 (we don't need to touch y) = 15241383.936E-3.

snow beacon
#

I'm trying to do the multiplication thing, and having trouble generating arbitrary floats without division and without messing around with strings.

#

If I could generate negative powers of 2, it would be doable, but pow() is kind of against the spirit of things.

#

I would also be able to construct the numbers I want if I could find the reciprocal of an integer, because I can construct the positive powers of 2 easy enough.

#

I just realised I can get square roots.

#

I don't know how useful that will be, but I'll keep thinking on it.

lone ruin
#

you could play with bits directly

snow beacon
#

I'm not sure how to do that with floats

#

1.0 & 1.0 throws an error

#

I've figured out I can use the absolute value of complex numbers to find sqrt(a^2 + b^2)

#

I'm trying to figure out if I can use that to construct the floats I want.

#

Basically, I've got integer multiplication down, and I've reduced float multiplication to division of an integer by 2^n

#

I can also multiply an integer by a float, so if I got the reciprocal of 2^n, I could just multiply it and be done.

cursive fox
#

Shortened my thing significantly.
[redacted] (below but simple for loop and 8-digit precision limit due to slow computation time)

cursive fox
#

Final revision. Binary multiplication makes it fast and accurate.

def mult(x, y):
    """String Bullshittery v3: Return x*y without */%<<>>// operators or calling
    things related to these. Allow negative and decimal numbers.
    """
    if x == 0 or y == 0:
        return 0
    xnum, xpow = f"{abs(x):.99e}".split('e')  # Scientific notation, split
    ynum, ypow = f"{abs(y):.99e}".split('e')
    xnum = xnum.replace('.', '').rstrip('0')  # Into "integer"
    ynum = ynum.replace('.', '').rstrip('0')
    xpow = int(xpow) - len(xnum.replace('-', '')) + 1  # And exponent
    ypow = int(ypow) - len(ynum.replace('-', '')) + 1
    rexp = xpow + ypow
    result = 0

    # Binary multiplication
    xnum, ynum = bin(int(xnum))[2:], bin(int(ynum))[2:]
    binmul = []
    for i in range(len(xnum)):
        binmul.append('')
        for c in ynum:
            binmul[i] += '1' if int(xnum[i]) and int(c) else '0'
        # binmul[i] += '0' * (len(xnum) - i - 1)
        for n in range(len(xnum) - i - 1):
            binmul[i] += '0'
    for item in binmul:
        result += int(item, 2)

    result = float(str(result) + 'e' + str(rexp))
    return -result if (x > 0) ^ (y > 0) else result```
#

oh shit there's one * after for c in ynum: *fixed

snow beacon
#

I'm still trying to figure out how to get arbitrary values less than one.

snow beacon
#

I'm reasonably certain it's possible to multiply exact floats, but for anything inexact, like 0.1, it takes far too long to be practical.

#

I've decided to allow myself to use pow(x, -1) in order to make this thing achievable.

wind maple
#

the decimal module

#

then again I don't know what the rules are

snow beacon
#

The decimal module might use division and multiplication, so I'm trying to do it all by hand.

#

If I can copy the decimal module into my own code, then sure, but I suspect I can't, because it'll use banned operations.

autumn moss
#
def func():
    while True:
        func();```
#

πŸ€”

#

code like this keeps me up at night

brisk zenith
#

infinite os forking keeps me up at night.

#

purposefully not providing the code there :)

autumn moss
#

why not :(

brisk zenith
#

because no :D

snow beacon
#

There's a bash fork bomb in less than ten characters. From personal experience, it's not fun.

autumn moss
#

why would you forkbomb your pc?

snow beacon
#

I didn't know it would crash the windows bit of my computer, I thought Windows Subsystem for Linux was like a vm

autumn moss
#

but why would anyone do it

snow beacon
#

The point is you don't do it to your own computer, and on this server we don't want to help people with their funny pranks

snow beacon
#

Sometimes I forget to close my test windows. This is some of my progress with the multiplication thing

#

It's like a really slow fork bomb :/

autumn moss
#

what exactly is a forkbomb designed to do?

#

brick the OS or just restart it

snow beacon
#

It opens two of itself, so the computer will slow down as more of its resources are used up. Soon it gets impractical to use, and has to be restarted.

autumn moss
#

oh

snow beacon
#

Some don't just open two of themselves, they just repeatedly start themselves.

#

According to my program, 0.5 * 0.5 == 2

#

As is 0.125 * 0.125

#

Logic errors are a lot harder to spot than regular errors

#

Syntax errors I mean

#

Okay, I've fixed one error and now when I multiply range(10) by 2, I get 0, 2, 4, 6, 4, 6, 8, 10, 4, 6

snow beacon
#

I've finished my multiplication program. I'll fix it up a bit and maybe add support for complex numbers before I post it.

snow beacon
#

I also added support for concatenating sequences.

#

I decided not to use for loops, while loops or recursion, so I do a lot of mapping functions to lists, and sum()

#

Anyway, the code works for multiplying positive or negative ints and floats, complex numbers, and also supports multiplying sequences like lists or strings by integers to repeat the sequence.

#

I don't think I mentioned it in the comments, but as well as explicit loops, multiplication, modulo and division, I also tried to avoid using string manipulation to create numbers.

#

Instead, I do something called "Russian Peasant Multiplication" to multiply real numbers by integers.

sick hound
#

[0] ```py

c
<code object test at 0x000001FCE1119F60, file "<code>", line 1>
dis.dis(c)
1 0 LOAD_CONST 0 (42)
2 LOAD_CONST 1 (' world')
4 BUILD_STRING 50
6 RETURN_VALUE
eval(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<code>", line 1, in test
TypeError: sequence item 0: expected str instance, code found``` This is the weirdest error we have ever seen and we have no idea why it is happening

#

[0] We attempt to build a string with 50 things on the stack... and that happens.

hot moss
#

@sick hound that's trying to concatenate 50 things from the stack, which only contains 2

#

what created that code object?

sick hound
#

[0] we did, with types.CodeType

hot moss
#

You did it wrong then

sick hound
#

[0] we know why it doesn't work, but why does getting 50 things off the stack of 2 things suddenly complain about a mysterious code objectβ„’

hot moss
#

I'm not 100% sure how these things work, but my guess is that there was already a code object on the stack to begin with

calm rampart
#

....the fuck

#

there's not a stack verifier when you build code objects?

snow beacon
#

Try pushing a bunch of stuff first and see

snow beacon
#

I just realised I can use iter() as an alternative to while loops.

#

Instead of python while x < 10: x += 1

#

I can say python def function(): x += 1 return x < 10 for truthy in iter(function, False): pass

#

That would have cleaned up some of my weirder multiplication code, but I'm not going to change it.

sick hound
#

pretty cool tip

#

how about a real example..

snow beacon
#

It's probably more useful to use it for something like python inputs = iter(input, "Stop copying me!") for line_of_input in inputs: print(line_of_input) This will repeat lines from stdin until the user types 'Stop copying me!'

muted needle
#

I just wanted to share a stupid thing I made. You ever make something and can't for the life of you figure out why?

from random import random as r
import time
f=open(r"C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.2\Include\um\cordebug.h","r")
t=f.read()[83000:];f.close();c=0
while 1:print(end=t[c]);time.sleep(r()if r()<.003 else 0);c+=1;c=0 if c==len(t) else c
snow beacon
#

Yeah, I do that with promises

sick hound
#

if os.path.exists(binary) is False:
raise ValueError("The BINARY path to Tor firefox does not exist.")
firefox_binary = FirefoxBinary(binary)

#

dont hate this

#

don't hate Tor

sick hound
#
>>> import sys
>>> import json
>>> json.load(sys.stdin)
{"hello":["world"]}
^Z
{'hello': ['world']}
>>> json.dump(_,sys.stdout)
{"hello": ["world"]}>>>```
untold sequoia
brisk zenith
#

unwrite it in JS and plop it into python. make the code as horrible or interestingly weird as possible and it'll be a nice esoteric python solution :D

untold sequoia
#

(But here's the kicker, I know basically no Python, the lack of curly braces scared me away - I don't get the point of formatting dependency)

tropic gulch
#

You can use #{ and #}

untold sequoia
#

😹

#

One of the few things I know is comments

#

That is pretty hilarious

tropic gulch
fallen heath
#

!e

from __future__ import braces```
night quarryBOT
#

@fallen heath Your eval job has completed.

001 | File "<string>", line 5
002 | SyntaxError: from __future__ imports must occur at the beginning of the file
fallen heath
#

rip

untold sequoia
#

These ones are functional to scope let but isn't strictly necessary

#

I can move that group to anywhere and click format and it's sorted πŸ‘Œ

#

Can't think why you wouldn't want that ability

fallen heath
#

The added () really throw me off

untold sequoia
#

Yeah it used to be a single line and I didn't remove them

#

Used to be

{
   let j, k, l;
   grid.map((x, i) => k = grid.length - 1 - i,l = Math.floor(Math.random() * (k + 1)),j = grid[k],grid[k] = grid[l],grid[l] = j);
}
fallen heath
untold sequoia
#

I'm surprised the randomly indented 4 lines didn't throw you, they shouldn't be indented - but it doesn't matter because it's in curly braces 🌈
I'm going to #python-discussion before I'm deemed too off-topic

brisk zenith
#

if (False).__class__.__base__(a == b) is ~-2:
@fallow cairn come on, make it worse. :^)

fallow cairn
#

Not sure if I can

brisk zenith
#

let's try to fuck up ```py
if a == b:
print("hello world!")

as much as we can.
fallow cairn
#

if not (a != b) != False: <-- Returns True (I think)

brisk zenith
#

oof

fallow cairn
#

I'm not sure bracketing laws for thy if statement

brisk zenith
#

don't even need an if.

#

!eval ```py
f = lambda: (False).class.base(a == b) and import(object.doc.doc[slice(367, 370)]).getattribute("stdout").write("hello world!")

a = 1
b = 2
f()

b = a
f()

night quarryBOT
#

@brisk zenith Your eval job has completed.

hello world!
brisk zenith
#

i just had a terrible idea

tropic gulch
#

😱

#

everyone hide your wives and kids

brisk zenith
#

make a python program which has some reasonably complex functionality, but if, while, for and def are not allowed.

#

maybe import and try/except could be forbidden too.

#

depends on how tricky that gets.

tropic gulch
#

working around if is well possible with two-item lists and the condition as index, as long as you inline all the rest

#

(which is, as we know, possible)

brisk zenith
#

yeah sure that works

#

i often use condition and (do_stuff) as an alternative to if condition: do_stuff

tropic gulch
#

I often use things like ["foo","bar"][a==42] in golf

brisk zenith
#

yeah i've done that before.

brisk zenith
#

is there any hacky way of catching an exception in a lambda?

#

i know there's a hacky alternative to raise that works in lambdas:

#

!e ```py
(lambda: (()for()in()).throw(ValueError("hello!")))()

night quarryBOT
#

@brisk zenith Your eval job has completed.

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 |   File "<string>", line 5, in <lambda>
004 |   File "<string>", line 5, in <genexpr>
005 | ValueError: hello!
brisk zenith
#

so, is there a similar way to catch or just suppress an exception, preferably without imports (because otherwise a solution with contextlib.suppress is likely possible), from within a lambda?

tropic gulch
brisk zenith
#

haha, that's what i do best.

tropic gulch
#

but it seems to only let you "catch" StopIteration

brisk zenith
#

ooh interesting.

#

StopIteration is the exact exception i'm trying to suppress, yeah.

tropic gulch
#

what have I done

#

πŸ˜›

brisk zenith
#

for some reason that last answer does not work for me. however, i think i figured out a solution for it maybe?

snow beacon
#

The stopiteration lambda code reminds me of Lisp, because of the weird bracket placement.

civic walrus
#

How about creating a sophisticated program without using the return statement

cunning wave
#

What about that

#

Every program can be written in a way so you don't have to use return statements

autumn moss
#

how about writing a sophisticated program without if statements

#

or without prints hyperlemon

olive dragon
#

There no point of not returning anything
Unless u r gonna store something

boreal perch
#

Writting a program that only utilizes asterics (*) only?

cunning wave
#

Without conditional jumps you can't implement everything @autumn moss

snow beacon
#

You just need a form of while loop to be Turing complete

#

(Other than assignment and sequencing)

wind maple
#

how would that work without conditionals

snow beacon
#

While is a conditional

frigid nexus
#

Posting here to maybe get better answers than in #python-discussion. Can you just use classes/objects to build coroutines? If so, were generators/yield/yield from introduced/enhanced only for syntactic convenience (of not writing a class)?

brisk zenith
#

how do you mean? you mean like, being able to insantiate a custom object and call/use it as a coroutine?

#

i'm not too familiar with the inner workings of asyncio, but this seems relevant.

#

that's for coroutines, i'm not sure if there's similar dunders for generators.

#

A function or method which uses the yield statement (see section The yield statement) is called a generator function. Such a function, when called, always returns an iterator object which can be used to execute the body of the function: calling the iterator’s iterator.__next__() method will cause the function to execute until it provides a value using the yield statement. When the function executes a return statement or falls off the end, a StopIteration exception is raised and the iterator will have reached the end of the set of values to be returned.

#

yup

#

i forgot about that actually, IIRC it's mentioned in Fluent Python

#

@frigid nexus so yeah, from what i can see, yield/yield from and the async shenanigans is all syntactic sugar. (i'm pretty sure)

#

actually, maybe yield itself isn't

nocturne saddle
#

yield is a pretty important keyword

#

Generator functions act differently from regular functions

brisk zenith
#

i know that yield from definitely is, it's mentioned on the PEP that introduces it.

#

!pep 380

night quarryBOT
#
**PEP 380 - Syntax for Delegating to a Subgenerator**
Status

Final

Python-Version

3.3

Created

13-Feb-2009

Type

Standards Track

nocturne saddle
#

Yeah, that's true

brisk zenith
nocturne saddle
brisk zenith
#

holy fuck. i just realised that pep 628 is named that because tau = 6.28...
that is a good.

#

!pep 628

night quarryBOT
#
PEP not found

PEP 628 does not exist.

brisk zenith
#

fuck

#

why didn't that command work though? πŸ€”

nocturne saddle
#

!pep 0628

night quarryBOT
#
PEP not found

PEP 628 does not exist.

nocturne saddle
#

Don't know

vague gust
#

@cunning wave come take a look at this

brisk zenith
#

yeah i considered pinging him but i didn't want it to get lost with the rest of his packets.

vague gust
#

lmfao

#

poor old nix

fallen heath
#

Issue 12345, nice

vague gust
#

oh I found the reason it breaks

brisk zenith
#

yeah?

vague gust
brisk zenith
#

ha, the special PEP 628 fucked it. should we make an issue for it for after the feature freeze?

cunning wave
#

Fucking PEP 628.....

#

I read a PEP which clearly says that after 542 it's rst

snow beacon
#

I can't find that PEP.

#

Maybe it's in an inaccessible format?

whole kiln
snow beacon
#

Sorry, I meant the PEP that says that PEPs will be in .rst format.

cunning wave
#

I read somewhere either in the psf repos or in a PEP that peps will be rst

#

Rst template which must be used PEP 12

#

However I think I just got the information that from pep 542 on everything is in rst by looking at all sources

sick hound
#

hi all..

#

Im using some code that's not mine.. there's something called malloc in the build file..

#

what is it for..

#

I guess it's some remnant from C++ or something

severe plaza
#

malloc = memory allocation

#

it's C function

#

It gives allocates memory for you and gives you it's address

vague gust
#

that's sort of off topic for this channel

severe plaza
#

also that :D

vague gust
#

we may be deep into creepy, unstructured esoteric python but that doesn't mean C πŸ˜„

sick hound
#

I'm not asking about c either

#

It's a build file for python.. uses malloc..

#

Hence creepy..

tame cradle
#

I came upon this problem today and I thought maybe you guys enjoy it. It's impossible to format decimals in a conditional f-string if the outcomes are not all decimals. The only way to solve this (that I found so far) is to either check outside of the f-string or to nest f-strings.

f"{some_float:.2f  if some_float else 'No float found'}"
wind maple
#

yeah because it's parsing the conditional as a format specifier and it's invalid

#
>>> x = 123
>>> f'{x:{".2f" if isinstance(x, float) else ""}}'
'123'
>>> x = 123.567
>>> f'{x:{".2f" if isinstance(x, float) else ""}}'
'123.57'
#

lol cool parsing discord highlighter

tame cradle
#

Well the funny thing to me is I can format the string, use conditionals, but not at the same time.

wind maple
#

yes

#

because a conditional isn't a format specifier

tame cradle
#

Sure, but you can't escape the specifier either

snow beacon
#

Hold on, isn't that what Ava is doing right there? Escaping from the specifier?

calm rampart
#

i wouldn't call that escaping

#

you can't use backslash anywhere within the expression part of a brace pair, which means you have to be careful about nested quotes and certain things become very difficult to express

#

you couldn't do this, for instance: f'{x:{\'.2f\' if isinstance(x, float) else \'\'}}'

mortal ingot
#

or even just '\n'.join(...)

calm rampart
#

right

#

if i needed to do that for some reason I would probably do NL = '\n' or maybe even joinlines = '\n'.join outside

#

for this case, i'd probably just write a function: py def format_decimal(value, n): try: return f'{value:.{n}f}' except ValueError: try: return f'{float(value):.{n}f}' except TypeError: return str(value)

#

and then use f'{format_decimal(x, 2)}'

#

(or just format_decimal(x, 2) if there's nothing else to the format string)

#

second attempt is to handle classes that don't accept float format language but are convertible to float, e.g. Fraction

#

not doing an explicit isinstance check lets it work on int and Decimal as well for the first round

mortal ingot
#

random question:

does sequence.find(elem) call sequence.index(elem) and returns -1 if it errors,
or does sequence.index(elem) call sequence.find(elem) and errors if it returns -1?

trim grove
#

I doubt they'd call one another in the first place.

mortal ingot
#

that's also a possibility

trim grove
#

Looking through this, but I can only find list.index. No trace of find.

#

Oh wait, lists don't have find. I'm thinking of strings.

#

Why don't lists have find...?

mortal ingot
#

...it's just on string isn't it...

#

cuz i tried tuple.find and that didn't work either

trim grove
#

Interesting.

#

I mean, the only reason find exists is because it's commonly used in other languages, and it reduces overhead for index where you'd need to add a try/except just to avoid issues.

#

I guess because in complements that.

calm rampart
#

I kind of wish find returned None

#

the -1 seems very clunky, the kind of design that comes from being implemented in a statically typed language with primitive types

trim grove
#

What's the point of find though? str.index already takes substrings, so if find was removed you'd use in+index just like for lists.

tropic gulch
#

index throws exceptions

#

why would I use in additionally and search the string twice?

open ore
#
import discord as D;import asyncio;import random as R;from config import token as T;c,p,N=D.Client(),print,"Nyan"

@c.event
async def on_ready(): p(N)

@c.event
async def on_message(M): (await c.send_message(M.channel,f"{M.author.name} said {M.content[5:]}")) if M.content.startswith("//say") else (await c.send_message(M.channel,R.choice(["Nyan!","Nya!","Nyaan!","Nyaa!"]))) if M.content.startswith("//nyan") else (await c.send_message(M.channel,R.choice(["Nyaa~!","Nya~!","Nyaan~!","Nyaaa~!"])),p(f"{M.author.name} petted me!")) if M.content.startswith("//pat") else (await c.send_message(M.channel,"https://discordapp.com/oauth2/authorize?client_id=545839351829889024&permissions=67488832&scope=bot")) if M.content.startswith("//invite") else None

c.run(T)```
#

Discord bot is fun

snow beacon
#

Doesn't that have a confidential authorisation key?

autumn moss
#

it does lol i can add it to servers

#

its not online though 😦

snow beacon
#

Is it the one where if anyone has it they can control your bot?

autumn moss
#

no

#

he hid that

#

just the id so we can invite to servers

sick hound
#

to control the bot you need the token, which in that code is imported from config

#

that code just contains the client id, which is not much more secret than a user id and can only be used to add it to servers

open ore
#
#config.py
token = "YOUR BOT TOKEN"```
#

Why not?

sick hound
#

...?

worthy pollen
#

invite not builtin in async? must be able to pull from somewhere instead...

civic walrus
#

Does anyone know any good projects that involve disabling Garbage Collection in python?

cunning wave
#

import gc
gc.disable()

#

However I'm not sure if that's a good idea considering the purpose of the gc

#

@civic walrus

civic walrus
#

I know how to disable it. I am looking for project ideas @cunning wave

honest juniper
#
class Switch:

    def __init__(self, object):
        self._switch = object
        self._setting = False

    def __enter__(self):
        self.cases = []

        def _case(self, expression, todo):
            case_dict = {
                "todo": todo,
                "expression": expression
            }
            self.cases.append(case_dict)

        def _default(self, todo):
            for case in self.cases:
                if case["expression"]:
                    case["todo"]()
                    return
            todo()
            self.__exit__(None, None, None)

        setattr(self, "_default", _default)
        setattr(self, "_case", _case)
        self._setting = True
        return (self.case, self.default)

    def case(self, expression, todo):
        if self._case and self._setting:
            self._case(self, expression, todo)
    
    def default(self, todo):
        if self._default and self._setting:
            self._default(self, todo)

    def __exit__(self, type, value, traceback):
        if self._setting:
            self._setting = False
            return
        return

if __name__ == "__main__":
    number = 0

    with Switch(number) as (case, default):
        case(
            number == 1,
            lambda: print("number 1!")
        )
        case(
            number == 2,
            lambda: print("number 2!")
            )
        default(
            lambda: print("unknown number!")
            )```
#

switch statement using context managers

snow beacon
#

That's pretty neat!

#

If you don't need the default argument, it would be (difficult but) possible to support with Switch(number) as case: as well as (case, default) if you made case pretend to be a tuple of itself and default, and you returned that instead of the real tuple.

#

A callable iterable, basically.

topaz fractal
#

@honest juniper can you explain the _case and and _default parts?

#

oh

#

wait nvm i get it

#

hm but wouldn't it only evaluate once?

#

say you put this entire thing in a for loop

#

wouldn't number==1 only evaluate the first time?

honest juniper
#

it could use some improvements but it's just a rough draft

brisk zenith
#

i remember trying to do something like that a while ago but instead with a function decorator that modified the bytecode of the function

#

should try it again, actually.

grave rover
#

@honest juniper expression should support callables too

tepid glacier
#

Oh it's been mentioned before

#

This is the first I've heard of it πŸ‘€

brisk zenith
#

yeah it lets you monkeypatch builtins right?

calm rampart
#

lol why did they implement it in pure python if it obviously only works on cpython

tepid glacier
#

@brisk zenith yep

glacial rampart
brisk zenith
#

just messing around a bit here. i've made two functions for assigning variables, it's quite interesting actually. ```py
start = "foo"

func = lambda end="bar": (
_assign_local(lambda: (end, "world")),
_assign_global("start", "hello"),

print(start, end)  # prints "hello world" rather than "foo bar" cause of assignments

)

func()

#

i'm still working on some similar stuff so i'll be sending the code here eventually

#

the _assign_global is fairly simple, most people would be able to figure it out. _assign_local is the interesting one imo.

tropic gulch
#

why is func not a def?

brisk zenith
#

i've accidentally gotten into the habit of using lambdas for everything when i'm working on #esoteric-python stuff

#

oops Β―_(ツ)_/Β―

tropic gulch
brisk zenith
#

i suppose to demonstrate that i can do assignment from lambdas

snow beacon
#
>>> f = lambda: exec("global x; x='Assignment'")
>>> f()
>>> x
'Assignment'
>>>```
grave rover
#

@brisk zenith how are you setting variables in local scope? I've been trying to figure that out for ages :P

snow beacon
#

Could be weird bytecode stuff?

brisk zenith
#

nope. i pass a lambda to the _assign_local function which simply returns the local variable and the desired value. however, this lambda is also a closure and the cells in function.__closure__ are mutable @grave rover

#

so it gets the local variable from the cell in function.__closure__ and changes its value

grave rover
#

huh

brisk zenith
#

i'm not at my computer so i can't show the code, but it is really simple

grave rover
#

doesnt solve my issue sadly :(

brisk zenith
#

why's that?

grave rover
#
def test():
    with scope({"x": 10}):
        print(x)  # => 10
brisk zenith
#

oh hmm

grave rover
#

I tried inspect.stack()[-1].f_locals but that's a copy of the scope

brisk zenith
#

yeah

#

isn't there somebody who made a with namespace(...): using bytecode fuckery? not sure if it works in local scope, but it's something to search for perhaps.

grave rover
#

hm

#

maybe we could run locals() in the previous function scope?

brisk zenith
#

modifying locals() doesn't actually change the variables though, right?

grave rover
#

it does

brisk zenith
#

in a function though?

honest juniper
calm rampart
#

i'm working on an approach to allow an async function to pass an async callback to a sync function that requires a sync callback, and... is it possible to resume execution of a frame object?

rare juniper
#
class Eats:
    def __init__(self, eats=None, eaten=None):
        self._eats = eats
        self._eaten = eaten

    # Eats << x
    def __lshift__(self, right):
        self._eats = right
        return self

    # x << Eats
    def __rlshift__(self, left):
        self._eaten = left
        return self

    # Eats >> x
    def __rshift__(self, right):
        self._eaten = right
        return self

    # x >> Eats
    def __rrshift__(self, left):
        self._eats = left
        return self

    def __str__(self):
        return f"The {self._eats} ate the {self._eaten}"


if __name__ == '__main__':
    print('cat' >> Eats() >> 'mouse')  # The cat ate the mouse
    print('cat' << Eats() << 'mouse')  # The mouse ate the cat```

Does this belong here?
brisk zenith
#

of course, but you could use a metaclass so that you don't have to use parentheses, perhaps :D

candid cobalt
#

nice one

#

can we have c++-style iostreams now? (:

brisk zenith
#

i've already done that, hold on

#

huh, can't find the code. i'll make it again at some point.

brisk zenith
#

now make cin :^)

rare juniper
#

of course, but you could use a metaclass so that you don't have to use parentheses, perhaps :D

@brisk zenith WHAT

#

howww? That sounds perfect

#
from abc import ABC, abstractmethod
from typing import Any


class Conjunction(ABC):
    a: Any
    b: Any

    # Keyword << right
    def __lshift__(self, right):
        self.a = right
        return self._next()

    # left << Keyword
    def __rlshift__(self, left):
        self.b = left
        return self._next()

    # Keyword >> right
    def __rshift__(self, right):
        self.b = right
        return self._next()

    # left >> Keyword
    def __rrshift__(self, left):
        self.a = left
        return self._next()

    def _next(self):
        if self.satisfied():
            return self.result()
        else:
            return self

    def satisfied(self):
        return hasattr(self, 'a') and hasattr(self, 'b')

    @abstractmethod
    def result(self):
        return NotImplemented


class Also(Conjunction):
    """
    >>> 1 >> Also() >> 2
    (1, 2)
    >>> 1 >> Also() >> 2 >> Also >> 3
    ((1, 2), 3)
    """
    def result(self):
        return self.a, self.b

class Save(Conjunction):
    def result(self):
        with open(self.b, 'w') as f:
            f.write(self.a)

if __name__ == '__main__':
    print(6 >> Also() >> 7)  # (6, 7)
    print(6 >> Also() >> 7 >> Also() >> 8)  # ((6, 7), 8)
    'Hello world!' >> Save() >> 'hello_world.txt'
    with open('hello_world.txt', 'r') as f:
        print(f.read())  # Hello world!
#

How can I make it so these Also and Save methods don't need to be called using metaclasses?

snow beacon
#

I don't think this is metaclasses, but: make an object that has a >> method that creates a new Also object using Also(), applies the >> to that Also object, then returns the new Also object. Then put the first object in a variable called also. Now you can do 1 >> also >> 5 == (1, 5)

rare juniper
#

Would that be reusable?

brisk zenith
#

well, it would be as reusable as metaclasses

#

remember, classes are just objects

#

instantiated by metaclasses

#

just like regular objects are instantiated by regular classes

#

it's no different at all

snow beacon
#

You could make a class that takes in a class and creates an object like the first one I mentioned

rare juniper
#

That sounds cool.... Ohhh

#

Gosh, I don't wanna overcomplicate this. Also, having >> and << methods is making this a little silly since I don't care about the directionality right now

#

I might try to use pipes instead

#

or maybe matmul... 1 | also | 5 vs 1 @ also @ 5

brisk zenith
#

i prefer pipes

#

could also do something like 1 <also> 5 but that's been done before

rare juniper
#

I like them aesthetically but you have to override or, right?

#

oh, really? I like that

brisk zenith
rare juniper
#

Oooooh.

#

Is the only thing outdated about this the print statements?

brisk zenith
#

yeah

rare juniper
#

Perfect

brisk zenith
#

haha, that code was last updated 14 years ago apparently

#

still works mostly though

#

and if it doesn't, i'll help you out with it

rare juniper
#

lol operator.div

brisk zenith
#

yup, that's a thing

rare juniper
#

Is it still in 3.7?

brisk zenith
#

yup

rare juniper
#

oh, my IDE is mad about it

brisk zenith
#

of course it is :D

rare juniper
#

So, here's what I'm running currently...

#
class Infix:
    def __init__(self, function):
        self.function = function

    def __ror__(self, other):
        return Infix(lambda x, self=self, other=other: self.function(other, x))

    def __or__(self, other):
        return self.function(other)

    def __rlshift__(self, other):
        return Infix(lambda x, self=self, other=other: self.function(other, x))

    def __rshift__(self, other):
        return self.function(other)

    def __call__(self, value1, value2):
        return self.function(value1, value2)


# Examples

# simple multiplication
x = Infix(lambda x, y: x * y)
print(2 | x | 4)
# => 8

# class checking
isa = Infix(lambda x, y: x.__class__ == y.__class__)
print([1, 2, 3] | isa | [])
print([1, 2, 3] << isa >> [])
# => True

# inclusion checking
is_in = Infix(lambda x, y: y.has_key(x))
print(1 | is_in | {1: 'one'})
print(1 << is_in >> {1: 'one'})
# => True

# an infix div operator
import operator

div = Infix(operator.div)
print(10 | div | (4 | div | 2))


# => 5

# functional programming (not working in jython, use the "curry" recipe! )
def curry(f, x):
    def curried_function(*args, **kw):
        return f(*((x,) + args), **kw)

    return curried_function


curry = Infix(curry)

add5 = operator.add | curry | 5
print(add5(6))
# => 11
#
  File "C:/Users/Michael/.PyCharm2018.2/config/scratches/scratch_61.py", line 35, in <lambda>
    is_in = Infix(lambda x, y: y.has_key(x))
AttributeError: 'dict' object has no attribute 'has_key'```
brisk zenith
#

ah okay

rare juniper
#

The first three examples seemed to work

brisk zenith
#

easy enough, just do x in y

#

rather than y.has_key(x)

rare juniper
#

Ahhh, I see. I guess that was how the oldtimers did it

#

AttributeError: module 'operator' has no attribute 'div' hmm. tries to think about how to fix this

brisk zenith
#

oh does it not

rare juniper
#

oh

#

there's some other div methods in operator

brisk zenith
#

floordiv and truediv?

rare juniper
#

yeah

#

probably true

brisk zenith
#

yeah

rare juniper
#

Hey, it runs!

brisk zenith
#

haha, i remember this ```py

@cpp_stdio
def addition():
    cout << "Enter a number: ";
    cin >> x;

    cout << "And another: ";
    cin >> y;

    result = int(x) + int(y);
    cout << x << " + " << y << " = " << result << endl;

addition()
rare juniper
#

From the above, updated these two:

# inclusion checking
is_in = Infix(lambda x, y: x in y)
print(1 | is_in | {1: 'one'})
print(1 << is_in >> {1: 'one'})
# => True```

```py
# an infix div operator
import operator

div = Infix(operator.truediv)
print(10 | div | (4 | div | 2))```
#

Oh gosh, I have no idea what I'm looking at

brisk zenith
#

i've been meaning to rewrite the code that makes that valid

#

original is here

#

it's a bunch of mess

#

give it a go, it still works on python 3.7

rare juniper
#
class Infix:
    def __init__(self, function):
        self.function = function

    def __ror__(self, other):
        return Infix(lambda x, self=self, other=other: self.function(other, x))

    def __or__(self, other):
        return self.function(other)

    def __rlshift__(self, other):
        return Infix(lambda x, self=self, other=other: self.function(other, x))

    def __rshift__(self, other):
        return self.function(other)

    def __call__(self, value1, value2):
        return self.function(value1, value2)


if __name__ == '__main__':
    also = Infix(lambda a, b: (a, b))
    print(2 |also| 3 |also| 4)  # ((2, 3), 4)
#

This is so perfect

#

my code will never be readable again!!!

#

wow wait what that actually ran?

brisk zenith
#

my code?

rare juniper
#

yeah