Adam Oudad

Adam Oudad

(Machine) Learning log.

3 minutes read

Python embeds very nifty keywords and writing shorthands to help us in the writing of code that is short and easy to read. In the following, I will review some which are often overlooked.

Control the flow of execution, and filter data on the fly

You may have to work with raw data, with unpredictable structure. Loading or processing such data will likely raise many errors. Here is a way to ignore some minor inconsistencies and at least run your script for, say, a proof of concept.

for i in range(n):
    try:
        data = next(dataiter)
    except ValueError:
        continue
    # The code here is ignored if ValueError is raised in the "try" block
    # Otherwise, run the rest of the loop here ...

Another statement very useful when designing a searching algorithm is break. You can escape any loop (for or while) once a condition has been met.

for i in range(n):
    # Do stuff...
    if condition_is_met:
        break

Better yet, you can use the else keyword to execute some code if the loop has been exhausted.

for i in range(n):
    # Do stuff...
    if condition_is_met:
        break
else:
    # This will be executed only if break is never read.

The keyword pass is useful for leaving things to later. It does nothing at all, and this is precisely why we can use it to define some function or class we plan to write later.

class EmptyClass:
  pass

def some_function():
  pass

This way, the python interpreter won't yield a syntax error because the function body is empty. The pass keyword can be used when designing a data structure, to defer the actual implementation of some parts of the code for later.

Pass function parameters as a dictionary

You may have a function to which you want to pass a handful of arguments. Here is one way to do it.

def myfunc(a, b, c, d, e, f):
    # Do stuff
    pass

myfunc(a=1, b="foo", c=42, d=100, f="bar")

This can quickly become hard to read and redundant. In the event your configuration has a lot of values or your model has a lot of hyperparameters, I highly recommend to use dictionaries. The nice thing about them is they can be passed to a function as keyword arguments.

def myfunc(a, b, c):
    pass

config = {
    "a": 1,
    "b": 2,
    "c": 5
}

myfunc(**config)

By passing the dictionary config with two asterisks **, the Python interpreter will call the function myfunc(a=1, b=2, c=5) with each corresponding parameters of myfunc filled.

Function annotations

Function annotations improve the readability of your code, by documenting a function.

def myfunc(a: int = 1, b: str = "", c: list = []):
    pass

From this code, we easily understand the type of the parameters. However, it will not replace a detailed docstring description of the function. You can follow popular styles of writing docstrings, like Numpy style or Google style.

Conclusion

That's it for a short article on Python keywords. As The Zen of Python says, readability counts. For more, I direct you to the official documentation: https://docs.python.org/3.9/tutorial/controlflow.html

comments powered by Disqus

Recent posts

See more

Categories

About

This website is a weblog were I write about computer science, machine learning, language learning.