Skip to main content

Welcome to a Grasp lesson

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

Lesson 6

Importing and Using Python Modules and Packages

Recommended resources

Hello! In our last lesson, you did an excellent job of organizing code into functions. You wrote find_patients_by_diagnosis and is_high_risk, which packaged specific logic into reusable blocks. This is a huge step towards writing clean and efficient code. However, if you wanted to use those functions in a different analysis script, you'd still have to copy and paste them.

Today, we'll solve that problem by learning how to use modules and packages. A module is simply a Python file containing definitions and statements (like your functions) that can be brought into other scripts. A package is a collection of related modules. This concept is the key to unlocking the vast power of Python for data science, as it allows us to use code written by other developers to perform complex tasks, from numerical computation to data visualization.

Our goal is to import and use Python modules and packages. We'll turn your functions from the last lesson into a personal utility module, explore Python's built-in "Standard Library," and finally, see how to install and use the powerful third-party packages that form the backbone of data science.

1. What is a Module?

At its core, a module is a file containing Python code that you can reuse in other programs. This allows you to logically organize your code, making it easier to manage and share. Instead of having one massive script, you can break your project into smaller, more focused files.

Python Modules Tutorial: Importing, Writing, and Using Them

This article from DataCamp provides a concise definition of a Python module.

Please read the introductory section, Simply put. This will solidify the basic idea that a Python file is a module.

The image below provides a perfect visual summary. One file, test.py, contains a function. Another file, display.py, imports test.py and can then use the function defined within it.

This diagram shows the basic principle of modules: a function is defined in `test.py`, which is then imported into `display.py` so the function can be called there.

2. Creating and Using Your Own Module

Let's make this practical by converting the functions from our last lesson into a module. This is a common practice: as you develop useful functions, you collect them into utility modules for future use.

Step 1: Create the Module File

  • In PyCharm, create a new Python file named patient_utils.py. The name utils is a common convention for a file containing various utility functions.
  • Copy the complete find_patients_by_diagnosis and is_high_risk functions you wrote in the last lesson, along with the patient_cohort list, and paste them into this new patient_utils.py file.

Step 2: Create the Main Script File

  • Create another new Python file named lesson6.py. This will be our main script where we perform our analysis.

Step 3: Import and Use the Module

  • In lesson6.py, we can now import our utility module. At the top of the file, write:
    import patient_utils
    
  • Now, you can access the functions and variables from patient_utils.py using dot notation (module_name.function_name). Add this code to lesson6.py:
    
    
    
    # We can access the list from the module
    print(f"Analyzing a cohort of {len(patient_utils.patient_cohort)} patients.")
    
    
    
    
    # We can call the function from the module
    hypertensive_ids = patient_utils.find_patients_by_diagnosis(patient_utils.patient_cohort, 'Hypertension')
    print(f"Hypertensive patient IDs found: {hypertensive_ids}")
    

When you run lesson6.py, you'll see the output from these print statements. You've successfully separated your logic (the functions in patient_utils.py) from your main application (lesson6.py).


3. The if __name__ == '__main__': Guard

You might notice a potential issue. If you had any code in patient_utils.py that wasn't inside a function (e.g., a print() statement for testing), it would run the moment you import it. This is usually not what we want.

Python has a standard mechanism to prevent this. Every module has a special built-in variable called __name__.

  • When you run a Python file directly, its __name__ variable is set to the string '__main__'.
  • When you import a file as a module, its __name__ is set to the module's filename (e.g., 'patient_utils').

We can use this to create a block of code that only runs when the file is executed directly. This is perfect for including tests or examples within your module file.

The following video provides an excellent explanation of this concept.

Python Modules for Beginners

This video from Dave Gray clearly explains the purpose and usage of the if __name__ == '__main__': construct.

Please watch the segment from the discussion of the __name__ variable. Pay close attention to how the code behaves differently when the file is run directly versus when it's imported.

Let's apply this. Go back to your patient_utils.py file. Move the patient_cohort list and any test code you might have under an if __name__ == '__main__': block. Your patient_utils.py might now look like this:




# patient_utils.py

def find_patients_by_diagnosis(patients, diagnosis_to_find):



    # ... function code ...
    matching_ids = []
    for patient in patients:
        if patient['diagnosis'] == diagnosis_to_find:
            matching_ids.append(patient['id'])
    return matching_ids

def is_high_risk(patient):



    # ... function code ...
    return patient['age'] > 60 and patient['diagnosis'] == 'Hypertension'




# This block only runs if you execute 'patient_utils.py' directly
if __name__ == '__main__':
    print("--- Running tests for patient_utils ---")
    patient_cohort = [
        {'id': 'A101', 'age': 65, 'diagnosis': 'Hypertension'},
        {'id': 'B202', 'age': 48, 'diagnosis': 'Diabetes'},
        {'id': 'C303', 'age': 72, 'diagnosis': 'Hypertension'},
    ]
    
    test_ids = find_patients_by_diagnosis(patient_cohort, 'Hypertension')
    print(f"Test search found IDs: {test_ids}") # Expected: ['A101', 'C303']
    
    patient_for_test = patient_cohort[0]
    risk_status = is_high_risk(patient_for_test)
    print(f"Test risk status for {patient_for_test['id']}: {risk_status}") # Expected: True

Now, when you import patient_utils in another file, the test code won't run automatically.


4. Exploring Python's Standard Library

You've created your own module, but the real power comes from using modules others have written. Python comes with a Standard Library, a vast collection of modules for common tasks.

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

This video by Corey Schafer gives a great tour of the Standard Library, showing practical examples.

Watch the segment from the introduction to the Standard Library. He demonstrates the random, math, datetime, and os modules. Think about how these could be useful in a healthcare context.

Let's use a couple of these in lesson6.py. The datetime module is essential for working with dates (e.g., admission dates, birth dates), and math provides basic mathematical functions.

Add this code to lesson6.py:

import datetime
import math




# Use the datetime module to work with dates
birth_year = 1978
current_year = datetime.date.today().year
age = current_year - birth_year

print(f"\nA patient born in {birth_year} is approximately {age} years old.")




# Use the math module
# For example, calculating a confidence interval might involve a square root
sample_size = 100
std_dev = 15
standard_error = std_dev / math.sqrt(sample_size)

print(f"With a sample size of {sample_size}, the standard error is: {standard_error:.2f}")

As you can see, importing these modules gives you instant access to well-tested, ready-to-use functionality.


5. From Modules to Packages

When a project grows large, developers group related modules into directories. A directory of modules is called a package. This hierarchical structure is how major data science libraries are organized.

This diagram illustrates a package named 'Math Operation Package'. It contains modules like `calculate.py` and sub-packages like `basic` and `advanced`, which in turn contain their own modules (`add.py`, `multiply.py`, etc.). The `__init__.py` file (which can be empty) tells Python to treat the directory as a package.

Your journey into data science will involve extensive use of powerful third-party packages. Let's look at the most important ones.

Medical Analysis Using Python: Revolutionizing Healthcare with ...

This article from GeeksforGeeks introduces the key Python libraries for medical data analysis, giving you a preview of the tools you'll be using soon.

Read the section on Essential Libraries. This introduces NumPy, Pandas, and Matplotlib, which are central to nearly all data science work in Python.

To use these external packages, you first need to install them using pip, Python's package installer. You do this from your system's command line (Terminal on Mac/Linux, Command Prompt or PowerShell on Windows), not within the Python script itself.

Let's install Pandas, the primary tool for data manipulation.

  1. Open your system's terminal (you can find it through your system's search bar).
  2. Type the following command and press Enter:
    pip install pandas
    

You should see text indicating that the package is being downloaded and installed. Once it's finished, you have Pandas available to any Python script on your system.

Now, let's verify the installation. It's standard practice to import pandas using the alias pd. Add this to the bottom of your lesson6.py file:




# Import a third-party package with a standard alias
import pandas as pd

print(f"\nSuccessfully installed and imported pandas version: {pd.__version__}")

Running lesson6.py should now print the version of pandas you just installed. Congratulations, you've just unlocked a whole new world of capabilities!


6. Practical Exercise: Consolidating Your Tools

Let's put everything together. You will create a new analysis script that uses your own custom module and a module from the standard library.

Your Task:

  1. In your lesson6.py file, define a new list of patients.
  2. Use the find_patients_by_diagnosis function from your patient_utils module to identify all patients with 'Diabetes'.
  3. import the random module from the standard library.
  4. Use random.sample() to select 2 patients from the diabetic cohort for a hypothetical follow-up study. random.sample(population, k) takes a list (population) and returns a new list of k unique items.
  5. Print the IDs of the selected patients.

Copy and paste the following code into your lesson6.py file and complete the parts marked # YOUR CODE HERE.




# --- Exercise Start ---
import patient_utils



# YOUR CODE HERE: import the 'random' module

print("\n--- Exercise: Patient Screening ---")

new_patient_cohort = [
    {'id': 'P701', 'age': 68, 'diagnosis': 'Diabetes'},
    {'id': 'P702', 'age': 55, 'diagnosis': 'Asthma'},
    {'id': 'P703', 'age': 75, 'diagnosis': 'Diabetes'},
    {'id': 'P704', 'age': 62, 'diagnosis': 'Hypertension'},
    {'id': 'P705', 'age': 59, 'diagnosis': 'Diabetes'},
]




# YOUR CODE HERE:
# 1. Call the `find_patients_by_diagnosis` function from the `patient_utils` module.
#    Pass it `new_patient_cohort` and the diagnosis 'Diabetes'.
#    Store the result in a variable called `diabetic_patient_ids`.
diabetic_patient_ids = [] # Replace this line with your function call

print(f"Found diabetic patients: {diabetic_patient_ids}")




# 2. Check if you have at least 2 diabetic patients before sampling.
if len(diabetic_patient_ids) >= 2:



    # YOUR CODE HERE:
    # Use `random.sample()` to select 2 patient IDs from `diabetic_patient_ids`.
    # Store the result in `selected_for_followup`.
    selected_for_followup = [] # Replace this line with your function call
    print(f"Selected for follow-up study: {selected_for_followup}")
else:
    print("Not enough diabetic patients for the study.")
    



# --- Exercise End ---
Click to see the solution



# --- Solution ---
import patient_utils
import random # Import the 'random' module

print("\n--- Exercise: Patient Screening ---")

new_patient_cohort = [
    {'id': 'P701', 'age': 68, 'diagnosis': 'Diabetes'},
    {'id': 'P702', 'age': 55, 'diagnosis': 'Asthma'},
    {'id': 'P703', 'age': 75, 'diagnosis': 'Diabetes'},
    {'id': 'P704', 'age': 62, 'diagnosis': 'Hypertension'},
    {'id': 'P705', 'age': 59, 'diagnosis': 'Diabetes'},
]




# Call the function from the patient_utils module
diabetic_patient_ids = patient_utils.find_patients_by_diagnosis(new_patient_cohort, 'Diabetes')

print(f"Found diabetic patients: {diabetic_patient_ids}")




# Check if you have at least 2 diabetic patients before sampling
if len(diabetic_patient_ids) >= 2:



    # Use random.sample() to select 2 patients
    selected_for_followup = random.sample(diabetic_patient_ids, 2)
    print(f"Selected for follow-up study: {selected_for_followup}")
else:
    print("Not enough diabetic patients for the study.")
    



# --- Exercise End ---

Conclusion

Excellent work! This lesson was a critical step, moving you from writing self-contained scripts to being a user and creator within Python's vast ecosystem.

Here are the key takeaways:

  • Modules are .py files that let you reuse code and keep your projects organized.
  • Packages are directories of modules, forming larger libraries.
  • You can import your own modules, modules from the Standard Library (like datetime and random), and third-party packages.
  • The if __name__ == '__main__': block is essential for creating reusable modules that can also be run directly for testing.
  • pip is the command-line tool used to install third-party packages.
  • Using aliases like import pandas as pd is a standard and highly recommended convention.

You have now completed the "Python Programming Fundamentals" module. You have all the basic building blocks you need to start working with data.

In our next lesson, we will begin the "Data Manipulation with NumPy and Pandas" module. We'll dive into NumPy, the fundamental package for scientific computing in Python, and learn how to use its core data structure, the NumPy array. This will lay the groundwork for using Pandas to analyze real-world datasets.