Search posts, tags, users, and pages
In this post, I'll present how I changed Python’s source code and compiled from scratch to accept "else-less" if expressions, similar to Ruby's "inline if", also known as conditional modifier 👇 Why? The idea of having an else-less if expression in ...
miguendes.me18 min read
Markdown supported · ⌘↵ to post
Hey Juan, I didn't actually submit this as PR to python. The language remains the same.
This post is just an fun experiment.
The code you suggest has the same result indeed but this example is just an illustration.
There are other use cases as well where this trick wouldn't work.
For example
>>> a = 'hello' * False
>>> type(a)
str
>>> a = 'hello' if False # assuming it uses the patch I did
>>> type(a)
NoneType
As you can see, your suggestion only work for integers, the "else-less" solves other problems as well.
I hope that answers your question and thanks for your comment!
Hello Miguel Brito
Yes, of course I understand that it is an experiment and 99% of your article is about adding your own syntax to Python which is super interesting and worth reading, but I believe it adds value to mention that it could be done already in pure Python.
Best regards!
Note: As you probably know in Python you can use False, 0, None, [], {} and '' as "not True" in "if" clauses, so in all cases: "if a:" should work later in your code, so the multiplication operator does work with str's:
>>> a = 'hello' * True
>>> a
'hello'
>>> a = 'hello' * False
>>> a
''
>>> if a:
... print "True"
...
>>>
Juan Francisco Roco Ah ok, now I see what you mean. I think the problem is that I chose I terrible example to illustrate this feature, as you showed.
Regarding this last example, the idea is to return None in case of False. Your example returns an empty string, which is not the same thing. Besides, the object must support __mul__ protocol, which is not the case for custom objects.
For example:
In [1]: class Person:
...: def __init__(self, name):
...: self.name = name
...: def __bool__(self):
...: return bool(self.name)
...:
In [2]: p = Person('name')
In [3]: a = p * False
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-a2214d15ebd2> in <module>
----> 1 a = p * False
TypeError: unsupported operand type(s) for *: 'Person' and 'bool'
In [4]: a = 'hello' if p
In [5]: a
Out[5]: 'hello'
In [7]: p = Person('')
In [9]: a = 'hello' if p
In [11]: type(a)
Out[11]: NoneType
Juan Francisco Roco
Innovating since the 70s...
Congratulations... I read about this on PyCoder's Weekly
Isn't this enough for your use case (pure and simple Python)?
>>> 42 * True 42 >>> 21 * False 0 >>> a = 42 >>> a += 1 * False >>> a 42 >>> a += 1 * True >>> a 43