Data Structures
Python Modules Explained: Part 9
Modules are essential for structuring Python code, promoting reusability, and making projects manageable. They allow you to break down large programs into smaller, self-contained files.
Ryan McBride
Ryan McBride
alt

Source: Karla Car on Unsplash

Python Modules: Organizing and Reusing Code

1. Importing Modules

To use code from a module, you need to import it. There are several ways to do this:

1.1. Importing the Entire Module

This imports the whole module, and you access its contents using the module name as a prefix.


import my_module

my_module.my_function()
print(my_module.my_variable)
   

You can also assign a shorter alias to the module:


import my_module as mm

mm.my_function()
   

1.2. Importing Specific Names

This imports only the specified functions or variables directly into your namespace, allowing you to use them without the module prefix.


from my_module import my_function, my_variable

my_function()
print(my_variable)
   

You can also rename imported names:


from my_module import my_function as mf

mf()
   

1.3. Importing Everything (Not Recommended)

While possible, importing everything from a module is generally discouraged as it can lead to naming conflicts and make code harder to understand.


from my_module import * # Avoid this
   

2. Module Search Path (sys.path)

When you import a module, Python searches for it in a specific order:

  1. The directory containing the script being run.
  2. Directories listed in the PYTHONPATH environment variable.
  3. Standard library directories.
  4. The site-packages directory (for third-party packages).

If Python can't find the module, you'll get a ModuleNotFoundError.

2.1. Managing Modules in Different Directories

If your module isn't in the same directory as your script, you have a few options:

2.1.1. Modifying sys.path (Less Recommended)

You can add the module's directory to sys.path within your script:


import sys
sys.path.append('/path/to/my_module') # Avoid hardcoding paths

import my_module
   

However, this is usually not the best approach for long-term projects.

2.1.2. Using the PYTHONPATH Environment Variable (Recommended)

The preferred way is to add the module's directory to the PYTHONPATH environment variable. This tells Python to always check that directory for modules. The video explains how to set this up on macOS and Windows.

3. Python Standard Library

Python comes with a rich set of built-in modules called the standard library. These modules provide functionality for many common tasks, so you don't have to install them separately.

Examples of standard library modules:

  • math: For mathematical functions (e.g., math.sin(), math.radians()).
  • datetime and calendar: For working with dates and times (e.g., datetime.date.today(), calendar.isleap()).
  • os: For interacting with the operating system (e.g., os.getcwd()).
  • random: For generating random numbers and making random choices (e.g., random.choice()).
  • sys: Access system-specific parameters and functions, including sys.path.

You can find the location of a standard library module using its __file__ attribute (e.g., os.__file__).

4. Next Steps in Python Learning

With a solid understanding of fundamental concepts like data types, conditionals, loops, functions, and modules, you're well-equipped to explore more advanced Python topics. Some potential next steps include:

  • Object-oriented programming (OOP).
  • File handling.
  • Working with databases.
  • Web frameworks (like Flask or Django).
  • Data analysis and scientific computing (using libraries like NumPy and Pandas).