Modules

Whenever we use definitions from a module, we first need to import those definitions. There are a number of ways we can import modules and their definitions using the import statement:

1. Import the whole module by name. This is the most common method for importing a module.

# import the module
import csv

# definitions are available using the format
# module_name.definition_name
csv.reader()

2. Import the whole module with an alias. This is especially useful if a module is long and we need to type it a lot.

# import the module with an alias
import csv as c

# definitions are available using the format
# alias.definition_name
c.reader()

3. Import one or more definitions from the module by name. This technique is useful if you want only a single or select definitions and don't want to import everything.

# import a single definition
from csv import reader

# the definition you imported is available
# by name
reader()

4. Import all definitions with a wildcard. This is useful if you want to import and use many definitions from a module.

Choosing which option to use when importing is often a matter of taste, but it's good to think about how each choice can affect the readability of your code:

  • If we're importing a long-name module by name and using it often, our code can become difficult to read.

  • If we use an uncommon alias, it may not be clear in our code which module we are using.

  • If we use the specific definition or wildcard approach, and the script is long or complex, it may not be immediately clear where a definition comes from. This can also be a problem if we use this approach with multiple modules.

  • If we use the specific definition or wildcard approach, it's easier to accidentally overwrite an imported definition.

In the end, there is often more than one "correct" way, so the most important thing is to know the trade-offs when you make a decision on how to import definitions from modules.

Last updated