#esoteric-python
1 messages Β· Page 63 of 1
Did you solve or you are going to solve?
i'm currently working on that with python's internal parser interface
and lib2to3's utils
neat
i'm thinking about using ast, it is really hard to find relevant info from CST
I've come pretty far, but getting the context a function was created in is quite the pain
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]```
added support for indexing and simple operators \o/
does typing let you represent a tuple of arbitrary size of one type, or a list with specific elements?
yeah kinda I guess
List[Union[type_1, type_2]]
no arbitrary size tuples tho
AND YES I GOT LISTCOMPS WORKING
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"
not really nope
To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. Tuple[int, ...]. A plain Tuple is equivalent to Tuple[Any, ...], and in turn to tuple.
https://docs.python.org/3/library/typing.html#typing.Tuple
ah so you can do that, just not the other way around
For arbitrary tuple size, you use an ellipsis
yeah but he means a Tuple of a repeating pattern iirc
What's the other way round? Just joined the convo
no i just meant the way your list example works
@tropic gulch if you can specify a list of N specific elements, the way you would with a tuple
List[Union[str, int]] is just a List of both str and int
also somewhat curious if typing can specify limited value "types"
wdym
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"
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
you could make one though
a type for only integers that are valid indices for the list that is passed in as another argument
now I need to support KT/VT
imagine like list.find -> ValueConstrainedToRange[int, -1, Expr["len(self)-1"]]
maybe you could make some class with https://docs.python.org/3/library/typing.html#user-defined-generic-types for that?
idk
not really
extend list?
Optional is just Union[None, whatever] iirc
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
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]}
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
comprehensions are Awesome
not when you have to estimate the result type
π€ example?
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
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
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
ok, I never touched ast yet
pictures of code... 
do you want the full code?
no thanks
get ready to download about 20MB of code
20MB?
I'm kidding
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
from what I can see, your only project file has roughly 300 lines
250, 100 of which are test cases and logging
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```
just for fun
i hate this, thanks
also, just use inspect.stack and verify it's being accessed from the same class, otherwise error
btw yw joseph
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
it doesnt accomplish the task at hand very well though
at least do lambda f:[object,type][type(f)==type]
https://pastebin.com/4JdihBug
Everything should work now
Yup
anyone ever used cobra?
http://cobra-language.com/
its kinda pythonic
well, it was
its ded now
rip
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
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
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
>>> 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
import os as t1, ast as t2
how is it confusing?
from sys import version_info[:2] as (major, minor) π
import os as T_, ast as _1
T1 = T_, _1```
too bad import (os, ast) as t1 doesn't work
That looks like something you could emulate using importlib. But I would have to spend some time thinking about it
T1 = tuple(import_module(modname) for modname in ('os', 'ast'))
MUCH better π
Username checks out
lmao
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')
@stone apex Your eval job has completed.
See http://www.python.org/3.6/license.html
Hm, different results from snekbox than local python
print(license)
print(*license._Printer__lines[225:230], sep='\n')
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```
Well are you gonna click it or not?
Tfw nobody has completed the challenge yet aside from me
I completed a challenge
Oh, the ++ thing also works with --. It just doesn't save the result.
==============================
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>
Any preference of return vs print?
Two options: functions should return, or your code gets called with python file.py N, where it should be printed
That second one seems harder.
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?
so does it return the nth number or the first n numbers
oh that was just asked
does it have to print or return
If your code takes input from file arguments you print, and if you have a function then return it
I do not abide by these rules
It's probably simplest to make a function
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
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]
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.
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
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.
a=5**.5;f=lambda p,n=(1+a)/2:(n**p-(-n)**-p)/a//1```
Returns the n-th Fibonacci number without recursion
Neither does mine, and yours is exactly the same length as mine. Spooky.
Oh, you used that cool ΙΈ formula!
Yeah
//1 is only needed to remove the floating point issues like 0.300000004
Made it 1 byte shorter
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
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
So does this mean that the canonical implementation returns a single value rather than a list of values?
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
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
@snow beacon both work tbh
f=lambda n:n<2or f(n-1)+f(n-2)``` in that case
a=5**.5;f=lambda p:round((.5+a/2)**p/a)``` shortest I can muster using direct calc
https://codegolf.stackexchange.com/a/179323/69746 comment I made as explanation
I'm on a fb page
@snow beacon no like, I meant for the task, True is not a number so doesn't count
Python: lang = lang(Java) - ";"
Wat
He tries to say python is a version of java without semilcons (and he is wrong)
True is almost a number
True is a number in my heart ||and my code||.
True should be -1, but at least 0 is False
well you know
it doesn't throw errors if you're using built ins
only linter gives you a warning
so..this makes sense
What the fuck Py2
Here's the math for Fibonacci for n>0 btw
The β§ is and, right?
not python but https://www.youtube.com/watch?v=E9nKk33aAa8
In 1999 I experimented a bit with creating a minimal C program that can create music. Here is the source code and the music. Admittedly it is more than 1 lin...
In the description there's a tool that will let you experiment with these
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...
python confuses me. how does it handle things like "hello!".__str__.__str__.__str__.__str__ ...? where (well, how) does it store these methods? π
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
interesting each of those actually has a unique memory address
they all exist seperately in memory
each of them is probably a lazily generated instance of method_wrapper that gets only made when you look it up
considering the address changes every time that is probably correct
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
method-wrapper?. Python Forums on Bytes.
not exactly a high quality source, but it seems to be a C method wrapper
That's basically what I was thinking
hmm okay sure
@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
removing assignment is not allowed because now there's no variable you can call
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
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:
!sayecho bot!calcdo 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
dam nice code @brisk zenith
thanks :D
I've never coded a Discord bot, so I expect my reign of terror is coming to an end.
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?
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
Fibonacci number?
@snow beacon and real number should work
(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
__=__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
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
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
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.
@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
you could perhaps solve an issue on the Tenderbot repo if you want to have a look at how a slightly more readable discord bot works. https://github.com/python-discord/seasonalbot/issues
although there's nothing esoteric about that I guess.
Yeah it's horrible code
it's fun, though.
And it works
example output?
Picture is above
oh. sorry. for some stupid reason I thought you meant rhyming in your love letter thing :D
brainfart
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
if you're going for minimal character count, you can lose a space in the argument list and use shorter variable names
true that
man things can get small
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
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```
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?
what the fuck did i do
probably parentheses or something
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
anyway they said it's a love calculator
so just some random numerology thing on people's names i guess
yeah
Takes two numbers, multiplies them together and takes the modulus of 100 from them as the percentage
shouldn't it be 101
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
l=lambda*a:hash(a)%100```
Esoteric is code word for python lambda
not quite, but usually yes.
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
yes
ellipsis is cool
i think people here have already established that it's my favourite singleton
I'm partial to NotImplemented
yeah but ....
5a878f7 add challenge 05: text hearts - Kingsley McDonald
f98243c fix bad readme format, oops. - Kingsley McDonald
(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! β€
I know exactly how to do this
but can you do it with ONE HUNDRED PERCENT SPICE? :D
lol
i'll get started on my own solution soon, i've got some ideas.
Well, sometimes it works...
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
On a phone even, nice
yeah good effort :D
my first attempt produces this.... π π₯
#####
#########
###########
#############
###############
#################
#####################
#######################
#######################
########## ##########
######### #########
######### #########
######### #########
######### #########
######### #########
######### #########
########## ##########
########## ##########
#########################
#########################
#########################
#######################
#######################
#####################
#####################
#################
#############
hahaha that's great!
it's a love egg
# ## ## #
# ##### #
# ##### #
#####
# ### #
# # # #
#### ####
#### ####
#### ####
#### ####
#### ####
#### ####
### ###
## ##
## ##
# #
## ##
#######
#####
#####
###

Halo mask
weird iron man
This channel may appreciate this one-liner from diabolical genius David Beazley
_ = type('',(),dict(__getattr__=lambda s,_:s))()
#### ####
## ## ## ##
# ### ### #
# ## ## #
## ## ## ##
# ### ### #
# ## ## #
# ###### #
# #
# #
# #
# #
# #
## ##
# #
# #
## ##
# #
## ##
# #
## ##
## ##
# #
## ##
## ##
## ##
## ##
### ##
### ###
#######
```
good enough
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
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 π
Description in the code comments.
So, how do I actually submit something? Do I just open up a PR?
Love is in the air. Is it in your Python, too?
π π¦
Β―_(γ)_/Β―
so, that's what I came up with, instead of doing my job or being productive at work π
amidoinitrite?
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.
x<3 x β€ π
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.
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
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.
Got a working impl based on that formula, now to fancify code
I actually have another idea but it'd be a bit much
I've got a code thing, is there an easy way to post it, or do I have to learn Git?
!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!")
I mean the heart challenge
I've made a GitHub account, and I'll upload my code in the morning.
Uses complex number inequalities and underhanded tricks to get a heart shape. Might be a little golfed in parts, sorry.
I just used GitHub to add the file. (The morning can wait.)
@snow beacon sample output?
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!
dose it have to be ritten in python?
Yes
New PR Incorporated
Solution uses (x**2 + y**2 - 1)**3 - x**2 * y**3 = 0
Function is shaped like a heart too
Beat this
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
impressive
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)
all four of the solutions so far are super fun
Yee
great to see people participating
haha mart, that's what i was gonna do
beat ya to it fam
i've got an interesting idea which is probably going to be real difficult to do
challenge accepted
heart-shaped quine
oh no
still accepted? :^)
@brisk zenith no u I thought of that the moment mart sent his thing
i am now home, two hours later lmao. i'm taking a gander at the submissions now.
2e170cc Create bytecommander.py - ByteCommander
b63568e Merge ByteCommander's Solution - kingdom5500
i think i should squerge these actually
i don't like squerging :(
very well, i shalln't
squerging is nicer tbh
for these small PRs i'd prefer it
it doesnt make the tree
*
|
*
|\
**
|/
*
|```
@brisk zenith consider that if you squerge that, byte is no longer a contributor
if you don't, he gets credit.
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
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.
28aa629 Create IFcoltransG's Heart solution IFcoltransG.py - IFcoltransG
cbdd0c8 Merge pull request #4 from IFcoltransG/patch-1 - kingdom5500
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
not sure how that works
git merge --ff
should actually be the default though
might have to do a rebase first if needed though
Made with a webscraper and img2txt
I used this guys code
@brisk zenith feel free to merge
hahaha i was actually expecting somebody to give an actual heart
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
8139c80 Create martmists.py - martmists
3638754 Merge Martmist's solution to challenge 5 - kingdom5500
there are existing gif2ascii converters too
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
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.
that's fine, feel free to fix it if you wish to make any other changes.
Hmm. #esoteric-python is the one place where everyone is fine with my horrible coding style.
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?
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```
ungolfed version available upon request
ΒΏam I doing it right?
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.
huh, I assumed everyone has dejavu sans and 256 colours on the terminal
matrix heart
How do you get the picture of the heart? Is that the font thing?
yup
Ah, so I was right the first time. A brilliant idea, and golfed too!
what else would I need a truetype font for in a console program? π
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
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
hmm map(print, [p(a)...]) perhaps
time to check the python golfing tips again... but tomorrow π
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
thx
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.
thanks, I'm happy someone appreciates my unreadable code
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"
I knew somebody speaks Japanese here! patches welcome ;)
i don't speak japanese but that's one of the few phrases (i think) i know.
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
'''
I thought that was an obscure enough bit of code to be shared here.
oh that's pretty neat
lol thats kinda cool
thats very esoteric but also really neat idea
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
I know π¦ I was sad when I saw that. But you can call it poetic license.
Turns out it is actually a thing
wow
I like the Lisp one, even though it's probably not a good idea to post it here.
This one's pretty cool, mostly because of how the code functionality symbolises the message
I liked that one a lot too^. Seems like a joke a programing teacher would make.
The Lisp one was one of my favorites.
what exactly is a raspberry pi useful for?
iot
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.
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
Is there a version of a for loop that calls send("Something") instead of next()?
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
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.
@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 π
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 π
What's esoteric python?
Weird python you should not use for real stuff but because it's funny or challenging doing certain things certain way
Nice
might as well just read the channel description
Oh sorry I'm on the phone
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
Anyone read any good books lately?
I mean, has anyone parsed any good long-form text files recently?
the classic: The Moon is a Harsh Mistress
Esoteric Python was what Thulsa Doom from Conan was into, right?
Some sort of snake cult?
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)
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
'''```
Challenge: write a backtick "` " to any file in as few characters as possible.
print('`')
since stdout is a file :^)
technically stdout is an iostream
everything is file
:thisisfile:
technically stderr is a file, and it doesn't say to not write anything else... py ` File "bt.py", line 1 ` ^ SyntaxError: invalid syntax

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
One could also argue that IO streams aren't files
*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].
thx
After I wake up, my
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.
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.
you could play with bits directly
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.
Shortened my thing significantly.
[redacted] (below but simple for loop and 8-digit precision limit due to slow computation time)
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 *fixedfor c in ynum:
I'm still trying to figure out how to get arbitrary values less than one.
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.
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.
infinite os forking keeps me up at night.
purposefully not providing the code there :)
why not :(
because no :D
There's a bash fork bomb in less than ten characters. From personal experience, it's not fun.
why would you forkbomb your pc?
I didn't know it would crash the windows bit of my computer, I thought Windows Subsystem for Linux was like a vm
but why would anyone do it
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
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 :/
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.
oh
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
I've finished my multiplication program. I'll fix it up a bit and maybe add support for complex numbers before I post it.
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.
[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.
@sick hound that's trying to concatenate 50 things from the stack, which only contains 2
what created that code object?
[0] we did, with types.CodeType
You did it wrong then
[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β’
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
Try pushing a bunch of stuff first and see
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.
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!'
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
Yeah, I do that with promises
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
>>> import sys
>>> import json
>>> json.load(sys.stdin)
{"hello":["world"]}
^Z
{'hello': ['world']}
>>> json.dump(_,sys.stdout)
{"hello": ["world"]}>>>```
The only problem is that I wrote it in JS π
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
It won't be hard, I made it in desmos first :P
https://www.desmos.com/calculator/zllapigzr6
(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)
You can use #{ and #}
https://i.redd.it/j1asakndj4221.jpg my stance on this...
!e
from __future__ import braces```
@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
rip
Didn't show the top
I use braces all the time just for clean formatted code
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
The added () really throw me off
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);
}

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
if (False).__class__.__base__(a == b) is ~-2:
@fallow cairn come on, make it worse. :^)
Not sure if I can
let's try to fuck up ```py
if a == b:
print("hello world!")
as much as we can.
if not (a != b) != False: <-- Returns True (I think)
oof
I'm not sure bracketing laws for thy if statement
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()
@brisk zenith Your eval job has completed.
hello world!
i just had a terrible idea
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.
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)
yeah sure that works
i often use condition and (do_stuff) as an alternative to if condition: do_stuff
I often use things like ["foo","bar"][a==42] in golf
yeah i've done that before.
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!")))()
@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!
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?
I can't read this without dying internally (also it is late already), but there might be something in it https://baruchel.github.io/python/2018/06/20/python-exceptions-in-lambda/
haha, that's what i do best.
probably same as https://stackoverflow.com/a/50916686/4464570
but it seems to only let you "catch" StopIteration
ooh interesting.
StopIteration is the exact exception i'm trying to suppress, yeah.
for some reason that last answer does not work for me. however, i think i figured out a solution for it maybe?
The stopiteration lambda code reminds me of Lisp, because of the weird bracket placement.
How about creating a sophisticated program without using the return statement
What about that
Every program can be written in a way so you don't have to use return statements
There no point of not returning anything
Unless u r gonna store something
Writting a program that only utilizes asterics (*) only?
Without conditional jumps you can't implement everything @autumn moss
You just need a form of while loop to be Turing complete
(Other than assignment and sequencing)
how would that work without conditionals
While is a conditional
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)?
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
yield is a pretty important keyword
Generator functions act differently from regular functions
i know that yield from definitely is, it's mentioned on the PEP that introduces it.
!pep 380
Yeah, that's true
Yes, but that's the specific thing for yield from, yield itself is different: https://www.python.org/dev/peps/pep-0255/#specification-yield
holy fuck. i just realised that pep 628 is named that because tau = 6.28...
that is a good.
!pep 628
PEP 628 does not exist.
!pep 0628
PEP 628 does not exist.
Don't know
@cunning wave come take a look at this
yeah i considered pinging him but i didn't want it to get lost with the rest of his packets.
Issue 12345, nice
oh I found the reason it breaks
yeah?
we have this conditional https://github.com/python-discord/bot/blob/301e877beff8436de0b0d6f3360e3bcf0d81bf01/bot/cogs/utils.py#L40-L43
but if you look at this actual pep, it uses txt not rst https://raw.githubusercontent.com/python/peps/master/pep-0628.txt
ha, the special PEP 628 fucked it. should we make an issue for it for after the feature freeze?
Sorry, I meant the PEP that says that PEPs will be in .rst format.
I read somewhere either in the psf repos or in a PEP that peps will be rst
@snow beacon
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
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
malloc = memory allocation
it's C function
It gives allocates memory for you and gives you it's address
that's sort of off topic for this channel
also that :D
we may be deep into creepy, unstructured esoteric python but that doesn't mean C π
I'm not asking about c either
It's a build file for python.. uses malloc..
Hence creepy..
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'}"
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
Well the funny thing to me is I can format the string, use conditionals, but not at the same time.
Sure, but you can't escape the specifier either
Hold on, isn't that what Ava is doing right there? Escaping from the specifier?
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 \'\'}}'
or even just '\n'.join(...)
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
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?
I doubt they'd call one another in the first place.
that's also a possibility
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...?
...it's just on string isn't it...
cuz i tried tuple.find and that didn't work either
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.
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
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.
index throws exceptions
why would I use in additionally and search the string twice?
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
Doesn't that have a confidential authorisation key?
Is it the one where if anyone has it they can control your bot?
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
...?
invite not builtin in async? must be able to pull from somewhere instead...
Does anyone know any good projects that involve disabling Garbage Collection in python?
import gc
gc.disable()
However I'm not sure if that's a good idea considering the purpose of the gc
@civic walrus
I know how to disable it. I am looking for project ideas @cunning wave
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
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.
@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?
it could use some improvements but it's just a rough draft
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.
@honest juniper expression should support callables too
https://github.com/clarete/forbiddenfruit is a fun little package
Oh it's been mentioned before
This is the first I've heard of it π
yeah it lets you monkeypatch builtins right?
lol why did they implement it in pure python if it obviously only works on cpython
@brisk zenith yep
@open ore here's a discord bot as a one line lambda: https://github.com/mental32/lambda_bot/blob/master/lambda_bot.py
A discord bot written with pure lambdas using discord.py - mental32/lambda_bot
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.
why is func not a def?
i've accidentally gotten into the habit of using lambdas for everything when i'm working on #esoteric-python stuff
oops Β―_(γ)_/Β―

i suppose to demonstrate that i can do assignment from lambdas
>>> f = lambda: exec("global x; x='Assignment'")
>>> f()
>>> x
'Assignment'
>>>```
@brisk zenith how are you setting variables in local scope? I've been trying to figure that out for ages :P
Could be weird bytecode stuff?
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
huh
i'm not at my computer so i can't show the code, but it is really simple
doesnt solve my issue sadly :(
why's that?
def test():
with scope({"x": 10}):
print(x) # => 10
oh hmm
I tried inspect.stack()[-1].f_locals but that's a copy of the scope
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.
modifying locals() doesn't actually change the variables though, right?
in a function though?
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?
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?
of course, but you could use a metaclass so that you don't have to use parentheses, perhaps :D
i've already done that, hold on
huh, can't find the code. i'll make it again at some point.
now make cin :^)
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?
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)
Would that be reusable?
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
You could make a class that takes in a class and creates an object like the first one I mentioned
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
I like them aesthetically but you have to override or, right?
oh, really? I like that
yeah
Perfect
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
lol operator.div
yup, that's a thing
Is it still in 3.7?
yup
oh, my IDE is mad about it
of course it is :D
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'```
ah okay
The first three examples seemed to work
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
oh does it not
floordiv and truediv?
yeah
Hey, it runs!
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()
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
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
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?
my code?
yeah
