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!
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'
>>> some_func() 'from_finally'
- When a
continuestatement is executed in the
trysuite 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
returnstatement executed. Since the
finallyclause always executes, a
returnstatement executed in the
finallyclause will always be the last one executed.
2. Time for some hash brownies!
>>> some_dict[5.5] "Ruby" >>> some_dict[5.0] "Python" >>> some_dict "Python"
- 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
5.0as the same keys of the dictionary
- This StackOverflow answer explains beautifully the rationale behind it.
wtfpython : github