Member-only story
Python: Uncovering the Overlooked Core Functionalities
Update 25/07: Endless thanks for all the numerous tips, comments, and suggestions I received from the Hacker News community. I really appreciate it. I have incorporated some of them into this article. If you wish to read all of them, you can do so here.
What Kyle Simpson mentions about JavaScript in his books, Luciano Ramalho mentions in his book ‘Fluent Python’ about Python. They basically address the same issue of both languages. To put it in my own words:
Because the language is so easy to learn, many practitioners only scratch the surface of its full potential, neglecting to delve into the more advanced and powerful aspects of the language which makes it so truly unique and powerful
So let’s discuss briefly all functionalities you might haven’t heard of, but you definitely want to know if you aim to become a truly seasoned Pythonista.
Evaluation of Default Arguments
Python arguments are evaluated when the function definition is encountered. Good to remember that! This means that each time the fib_memo function (which is mentioned below) is called without explicitly providing a value for the memo argument, it will use the same dictionary object that was created when the function was defined.
def fib_memo(n, memo={0:0, 1:1}):
"""
n is the number nth number
you would like to return in the sequence
"""
if n not in memo:
memo[n] = fib_memo(n-1) + fib_memo(n-2)
return memo[n]
# 6th Fibonacci (including 0 as first number)
fib_memo(6) # should return 8
So this code works, in Python. This also means that you could execute the fib_memo function in a single script multiple times, like in a for loop, with each execution increasing the fibonacci number to be computed, without hitting the “maximum recursion depth exceeded” limit, as the memo will keep expanding. More information can be found in my other article.
Important note (thanks to the Hacker News community)
Keep in mind that, although the mutable default arguments (as mentioned above) can lead to less code, not everyone might be aware of its behavior. It might even lead to hardly solvable bugs. Some even…