Python Hidden Treasures: Exploring Obscure Features and Easter Eggs

matib

Mati B

Posted on December 23, 2023

Python Hidden Treasures: Exploring Obscure Features and Easter Eggs

Beyond Python's clear and intuitive syntax lies a world of hidden features, quirky behaviors and delightful Easter eggs, that even seasoned developers might not be aware of. This is going to be a deep dive into Python's lesser-known features, so grab your explorer's hat and join me as we embark on an adventure into the hidden depths of Python.

Obscure Features

Walrus operator

Introduced in Python 3.8, the walrus operator := allows you to assign values to variables as part of an expression, often making the code more concise.

# without the walrus operator
num = input("Enter a number: ")
if int(num) > 10:
    print("You entered a number greater than 10!")

# with the walrus operator
if (num := int(input("Enter a number: "))) > 10:
    print("You entered a number greater than 10!")
Enter fullscreen mode Exit fullscreen mode

I personally don't like it that much, but it can be useful as long as you avoid using it with complex expressions that could make the code harder to read.

Ellipsis operator

The ellipsis operator, denoted as ..., is another unique and often overlooked feature in Python. The built-in Ellipsis object can be used in various interesting ways:

  • As a placeholder for code that hasn't been written yet (like the pass statement).
def not_implemented_yet():
    ...
Enter fullscreen mode Exit fullscreen mode
  • In multi-dimensional slicing, especially with NumPy arrays, the ellipsis represents the rest of the dimensions. In this example, array[..., 1] is a shorthand for "select the second element of every innermost list".
import numpy as np

array = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(array[..., 1])  # prints: [[2 5] [8 11]]
Enter fullscreen mode Exit fullscreen mode
  • In type hinting, it can be used to indicate only a part of the type, like Tuple[int, ...].

Else clause in loops

Python's loops have a quite unique feature that often surprises most programmers: the else clause.

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num > 10:
        print("Found number greater than 10")
        break
else:
    print("Didn't find a number greater than 10")
Enter fullscreen mode Exit fullscreen mode

In this code, the else block executes only if the loop completes without encountering a break statement. So it is as if the else block is saying "do this if the loop didn't break".

Chaining comparison operators

Python allows for an elegant syntax where multiple comparison operators can be chained together, making certain expressions clearer and more concise. This feature is particularly handy when you need to check if a value falls within a range.

a = 5
if 1 < a < 10:
    print("a is between 1 and 10")
Enter fullscreen mode Exit fullscreen mode

The chaining operation is equivalent to if a > 1 and a < 10.
But if you use this feature, you should only do it with simple expressions, otherwise it can make your code harder to read and understand, like in the following example.

a, b, c = 5, 7, 10
if a < b < c != 15:
    print("a is less than b which is less than c, and c is not 15")
Enter fullscreen mode Exit fullscreen mode

Ternary operator

While not exactly obscure, Python's ternary operator is a handy tool that deserves mention for its elegance and utility in writing concise conditional statements. It allows you to assign a value based on a condition in a single line.

# without ternary operator
if x % 2 == 0:
    result = "even"
else:
    result = "odd"

# with ternary operator
result = "even" if x % 2 == 0 else "odd"
Enter fullscreen mode Exit fullscreen mode

While the ternary operator is a powerful tool, clarity is more important, so avoid overusing it or nesting it too deeply, leading to code that would be hard to follow.

False midnight

This could be one of the most obscure features Python ever had, but only before Python 3.5 (it was then changed).

from datetime import time

midnight_time = time(0, 0, 0)

if midnight_time:
    print("Time at midnight is", midnight_time)
else:
    print("Midnight time is False :)")
Enter fullscreen mode Exit fullscreen mode

With Python < 3.5, the above code would print Midnight time is False :), because midnight time (UTC) was interpreted as a False value. As you can imagine, this was extremely error prone and confusing, with code potentially glitching once in a while because of this. And this wasn't even a bug, it was documented and done on purpose by design.

Easter Eggs

The Zen of Python

One of Python's most charming Easter eggs is the Zen of Python, a collection of aphorisms that capture the essence of the Python community's philosophy. To reveal this hidden treasure, simply type import this into your Python interpreter.

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Enter fullscreen mode Exit fullscreen mode

Interestingly, if you take a look at the implementation, you will see that the code for the Zen violates itself. If you are wondering what's going on in that piece of code, it is a ROT13 substitution cipher.

Braces vs Indentation

If you would like to be able to use curly braces in Python instead of indentation to denote code blocks, I have some bad news for you.

>>> from __future__ import braces
  File "<stdin>", line 1
SyntaxError: not a chance
Enter fullscreen mode Exit fullscreen mode

The __future__ module is typically used to import features from future versions of Python, but in this case it is used as a joke to acknowledge the debates around syntax preferences while affirming Python's commitment to keep using indentation.

Antigravity

Have you ever wondered why the Python tag in dev.to says import antigravity? Try importing it in your Python interpreter and you will find out why. Running that line of code doesn't give you the secrets of defying physics, but it does open up a web browser to a classic XKCD comic that humorously discusses Python's simplicity and power.

Infinite Pi

This one requires some previous context:

  • The float type in Python supports the concept of infinity, which can be expressed with float('inf').
  • The hash function returns an integer representation of an object. Combining these two features, you can get the first digits of the number pi (3.14159...).
>>> hash(float("inf"))
314159
>>> hash(float("-inf"))
-314159
Enter fullscreen mode Exit fullscreen mode

And there's more. In Python 2, hash(float("-inf")) would return -271828 (the number e), matching the Python major version.

Friendly Language Uncle For Life (FLUFL)

This final Easter Egg references PEP 401, the "BDFL's Retirement" April Fool's joke written by Barry Warsaw, a prominent Python developer. FLUFL stands for "Friendly Language Uncle For Life," a playful nod to the term BDFL (Benevolent Dictator For Life), which was often used to refer to Python's original creator, Guido van Rossum.

PEP 401 jokingly proposed replacing != with <> as the primary inequality operator, a syntax reminiscent of older programming languages like BASIC.

>>> from __future__ import barry_as_FLUFL
>>> 0 != 1
  File "<stdin>", line 1
    0 != 1
      ^^
SyntaxError: with Barry as BDFL, use '<>' instead of '!='
>>> 0 <> 1
True
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
matib
Mati B

Posted on December 23, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related