Modules

Unit 06

This Section is slightly adjusted from Fabien Maussion’s lecture material.

Python modules are used to store a collection of functions and variables that can be imported into other modules, scripts, notebooks, etc.

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.

Consider the following module mytimemodule.py:

"""My own module about important time questions"""

import datetime

hours_per_day = 24

def get_current_datetime():
    """
    Get current time and day
    """
    now = datetime.datetime.now()
    return now


def days2hours(days):
    """
    Convert days to hours

    This function takes a number of days as input 
    and calculates the equivalent number of hours.
    """
    hours = days * hours_per_day
    return hours

If you put the file in the working directory of your notebook or current python session (important!), you can import it and use it like other modules:

import mytimemodule
mytimemodule.get_current_datetime()
datetime.datetime(2024, 3, 17, 11, 18, 16, 388433)

Also the global variable hours_per_day

print(f"There are {mytimemodule.hours_per_day} hours per day!")
There are 24 hours per day!

That’s how easy you can reuse code in another script. Next week, you will learn how to avoid the inconvenience of putting the module in your current working directory, by putting your module in a package and making the package available in your conda environment.

reload: a useful trick

You regularly use the import statement at this point. Now that you also start coding your own modules you will likely find this trick useful:

Imagine you create a copy of mytimemodule.py yourself and import it to a notebook to explore its functions. You have a great idea for adding a new function. After implementing your new function in the module, you want to test it in your notebook, but you get an error.

The python interpreter of your session still uses the state of the module at the time of the initial import. So it thinks the new function does not exist. Running the import again does not work. You could either restart the kernel and run all cells of your notebook again, or you can use a special function to reload it:

from importlib import reload
reload(mytimemodule)

Learning checklist

  • I know that modules are a great place to store functions and variables that I will need to reuse in future projects, notebooks, and scripts.
  • I know how to import module files (and I am aware that the file needs to be located in the current working directory for the import to work).
  • I can apply functions that are given to me in modules.
  • I know how to reload modules when I am actively changing code in the module file that I want to use right away in a notebook or script.