Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 1

Creating and Importing Python Modules

Recommended resources

Welcome to the first lesson of your course on building robust automation for your finance work. Your goal is to move beyond copying and pasting code in single scripts or Jupyter notebooks and start building "proper," reusable code that functions like a personal software tool. This lesson marks the first and most fundamental step in that direction.

Today, we will focus on organizing your Python code into modules. You'll learn how to take a set of related functions, save them in a separate .py file, and then import and use them in your main scripts. This simple practice is the cornerstone of writing clean, maintainable, and scalable Python code, and it will be essential for the more complex automation tasks we'll tackle later in this course.

From Notebooks to Modules: The "Why"

You've likely developed a library of useful functions within your Jupyter notebooks for various FP&A tasks. The challenge, as you've noted, is reusing them efficiently. Copying code is tedious and error-prone; if you find a bug or want to improve a function, you have to update it in every notebook where it was pasted.

Moving this reusable code into Python modules solves this problem. A module acts as a central, single source of truth for your functions. Let's watch a brief segment that explains the value of this approach.

7 Tips To Structure Your Python Data Science Projects

The video "7 Tips To Structure Your Python Data Science Projects" from the ArjanCodes channel offers great advice for organizing code.

Please watch the section from tip number five, which discusses the benefits of moving reusable code out of notebooks and into separate modules. Pay attention to how this makes code easier to manage, reuse, and test.

As you saw, this practice is not just about tidiness; it’s about making your workflow more efficient and your code more reliable.


What is a Python Module?

At its core, a Python module is simply a file containing Python definitions and statements. The file name is the module name with the suffix .py added. For example, a file named finance_utils.py is a module named finance_utils.

This module can contain functions, variables, and even classes that you can then access from other Python scripts. Let's start with a foundational reading to solidify this concept.

Python Modules Tutorial: Importing, Writing, and Using Them

This article from DataCamp provides a clear introduction to Python modules. It will walk you through the basic definition and show you how to import a module from Python's standard library.

First, read the introduction to understand what constitutes a module. Then, review the section "Importing Modules in Python" to see a simple example using the built-in math module. This demonstrates the basic syntax for accessing a module's contents.


Creating and Using Your First Module

Now, let's apply this to a practical scenario from your field. Imagine you have a few helper functions for common financial calculations. Instead of rewriting them for every new analysis, we'll put them in a dedicated module.

Step 1: Create the Module (finance_utils.py)

Open your favorite code editor (like VS Code, PyCharm, or even a simple text editor) and create a new file. Save it as finance_utils.py. In this file, add the following Python functions:




# finance_utils.py

def calculate_variance(actual, budget):
    """Calculates the variance between an actual and a budget value."""
    return actual - budget

def calculate_variance_percent(actual, budget):
    """Calculates the variance percentage. Avoids division by zero."""
    if budget == 0:
        return float('inf') if actual > 0 else 0
    return (actual - budget) / budget * 100

This file is now a Python module named finance_utils. It doesn't do anything when run directly, but it provides two functions we can use elsewhere.

Step 2: Create the Main Script (monthly_report.py)

Now, create a second file in the same directory and save it as monthly_report.py. This script will perform our main analysis and will import the functions from finance_utils.

Step 3: Import and Use the Module

In monthly_report.py, you can now import your new module and use its functions.




# monthly_report.py

import finance_utils




# Sample data for a P&L line item
revenue_actual = 110000
revenue_budget = 100000




# Use functions from the module
var = finance_utils.calculate_variance(revenue_actual, revenue_budget)
var_pct = finance_utils.calculate_variance_percent(revenue_actual, revenue_budget)

print(f"Revenue Variance: ${var:,.0f}")
print(f"Revenue Variance %: {var_pct:.2f}%")

When you run monthly_report.py, you should see the following output:

Revenue Variance: $10,000
Revenue Variance %: 10.00%

Notice the syntax: module_name.function_name(). This is how you access the contents of an imported module. The following image illustrates this exact concept of two separate files working together.

This image shows two Python files. `main.py` defines a function and a variable. `Test.py` imports `main` and then calls the function and prints the variable using the `main.` prefix, demonstrating the fundamental import mechanism.

For a dynamic walkthrough of this process, the following video by Corey Schafer is an excellent resource.

Python Tutorial for Beginners 9: Import Modules and Exploring The Standard Library

This video, "Python Tutorial for Beginners 9," clearly demonstrates how to create a custom module and import it.

Watch the segment from the beginning until the first example is complete. The demonstrator creates a my_module.py and imports it into another script, explaining how to access its functions and variables. This mirrors the finance_utils example we just did.


Different Ways to Import

Python offers a few different syntaxes for importing, which provide flexibility depending on your needs.

  1. import module as alias: If a module's name is long, you can assign it a shorter alias. This is the standard practice for libraries like pandas and numpy.

    import finance_utils as fu
    var = fu.calculate_variance(110000, 100000)
    
  2. from module import name: If you only need one or two specific functions, you can import them directly. This allows you to call them without the module prefix, but it can make it less clear where the function originated.

    from finance_utils import calculate_variance
    var = calculate_variance(110000, 100000)
    
  3. from module import * (Use with Caution!): This imports all names from a module into your current script's namespace. While convenient, it is strongly discouraged in professional code because it can lead to naming conflicts and makes your code very difficult to read and debug. You lose track of where functions and variables came from.

Let's refer back to our resources to see these import styles in action.

Python Modules Tutorial: Importing, Writing, and Using Them

The DataCamp article details these alternative import syntaxes.

Read the sections on using from..import and renaming modules. Pay close attention to the Note that advises against using from..import * in professional settings.


A Note on Jupyter Notebooks and Modules

Your current workflow is heavily based in Jupyter, and you can—and should—use modules there as well. The process is nearly identical: you place your .py module file in the same directory as your .ipynb notebook file. Then, in a notebook cell, you can write import finance_utils.

Using Custom .py file in Jupyter - by Daniel Gurzi

This article is tailored specifically to what you're trying to achieve: bridging the gap between Jupyter notebooks and reusable .py files.

Skim through Steps 1-3 which cover creating the .py file and placing it in the correct directory. Then, focus on Step 4, which shows the import statement within a notebook. Finally, read the crucial Edit at the end of the article, which explains what happens when you modify your module.

This last point is a critical "gotcha" for Jupyter users. If you import finance_utils and then go back and edit the finance_utils.py file (e.g., to fix a bug), your notebook will not see the changes automatically. It will continue using the old, cached version of the module. To load the new version, you must restart the Jupyter kernel.


How Does Python Find Your Modules?

You might be wondering how Python knew where to find finance_utils.py. The answer lies in Python's module search path. When you write import finance_utils, the interpreter searches for the module in a specific sequence of locations.

Python Tutorial for Beginners 9: Import Modules and Exploring The Standard Library

The Corey Schafer video provides an excellent conceptual explanation of this search path.

Please watch the segment from "how does it know where to find this module". This will introduce you to sys.path and the order in which Python searches for modules.

The most important takeaway for now is that the very first place Python looks is the directory of the script you are running. This is why our import finance_utils command worked in monthly_report.py—both files were in the same folder. In a future lesson, we'll discuss how to structure larger projects where your modules might live in different directories.


Conclusion

In this lesson, you've taken the first major step toward writing structured, professional Python code. You've learned how to isolate reusable logic into a module, import it into a main script, and understand the basic mechanisms that make this work. This is the foundation upon which all the automation projects in this course will be built.

Key Takeaways:

  • A Python module is any .py file containing functions, variables, or classes.
  • Modules allow you to organize code, promote reusability, and avoid duplication.
  • You can import a module using import module_name and access its contents with module_name.function().
  • Alternative syntaxes like import ... as ... and from ... import ... offer flexibility, but from ... import * should be avoided.
  • Python finds modules by searching directories listed in sys.path, starting with the current script's directory.

In our next lesson, we will build upon this concept. You've seen that a module file is meant to be imported. But what if you also want to make that same file runnable on its own, perhaps to include some simple tests or examples? We'll explore the special if __name__ == '__main__' construct that elegantly solves this problem, making your modules even more powerful and self-contained.