wtfpython – A Collection of Surprising Python Snippets and Lesser-known Features

Python is a beautifully designed high-level and interpreter-based programming language. Python provides many powerful features for the programmer’s comfort. However, sometimes, the outcomes of a Python snippet may not seem obvious to a regular user at first sight.

wtfpython is a set of surprising Python snippets and lesser-known features. You may be already familiar with some of these examples, and I might be able to revive sweet old memories of yours being bitten by these gotchas.

It’s a fun project to collect such tricky & counter-intuitive examples and lesser-known features in Python, attempting to discuss what exactly is happening under the hood!

While some of the examples you see below may not be WTFs in the truest sense, but they’ll reveal some of the interesting parts of Python that you might be unaware of. I find it a nice way to learn the internals of a programming language, and I think you’ll find them interesting as well!

wtfpython - An interesting collection of surprising snippets and lesser-known Python features.

If you’re an experienced Python programmer, you can take it as a challenge to get most of them right in the first attempt.

Let’s us see an example:


1. Return return everywhere!

def some_func():
    try:
        return 'from_try'
    finally:
        return 'from_finally'

Output:

>>> some_func()
'from_finally'

💡 Explanation:

  • When a returnbreak or continue statement is executed in the try suite of a “try…finally” statement, the finallyclause is also executed ‘on the way out.
  • The return value of a function is determined by the last return statement executed. Since the finally clause always executes, a return statement executed in the finally clause will always be the last one executed.

2. Time for some hash brownies!

some_dict = {}
some_dict[5.5] = "Ruby"
some_dict[5.0] = "JavaScript"
some_dict[5] = "Python"

Output:

>>> some_dict[5.5]
"Ruby"
>>> some_dict[5.0]
"Python"
>>> some_dict[5]
"Python"

“Python” destroyed the existence of “JavaScript”?

💡 Explanation

  • Python dictionaries check for equality and compare the hash value to determine if two keys are the same.
  • Immutable objects with same value always have the same hash in Python.
    >>> 5 == 5.0
    True
    >>> hash(5) == hash(5.0)
    True

    Note: Objects with different values may also have same hash (known as hash collision).

  • When the statement some_dict[5] = "Python" is executed, the existing value “JavaScript” is overwritten with “Python” because Python recognizes 5 and 5.0 as the same keys of the dictionary some_dict.
  • This StackOverflow answer explains beautifully the rationale behind it.

wtfpython : github