Lesson · 40 min · Free
Python Modules: Import & Create
Python Modules: Import & Create Python Modules: Import & Create Welcome to this lesson on Python Modules! In the realm of scientific computing, especially in pharmacy and biotech, you'll frequently encounter the need to
Python Modules: Import & Create
Welcome to this lesson on Python Modules! In the realm of scientific computing, especially in pharmacy and biotech, you'll frequently encounter the need to organize your code, reuse functionalities, and leverage powerful external libraries. Python modules are the cornerstone of this organized and efficient approach. Think of a module as a single file containing Python definitions and statements – essentially, a toolbox filled with related functions, classes, and variables that you can bring into your current script. Why are modules so important for pharmacy and biotech? Imagine you're developing a script to analyze drug-target interactions. You might have a set of functions for calculating molecular weights, another for performing statistical analysis on binding affinities, and yet another for visualizing protein structures. Without modules, all these functions would be crammed into one large, unmanageable file. Modules allow you to compartmentalize these functionalities, making your code easier to read, debug, and maintain. Furthermore, many specialized libraries for bioinformatics, cheminformatics, and statistical analysis are distributed as modules, ready for you to import and use, saving you countless hours of re-inventing the wheel.
Importing Modules
The primary way to use a module is by importing it. Python provides several ways to do this, each with its own advantages depending on your needs. The most common method is the import module_name statement. This makes all the contents of the module available under the module's namespace. # Example 1: Importing the 'math' module import math # Now we can access functions from the math module radius = 5 area_of_circle = math.pi * (radius ** 2) print(f"The area of a circle with radius {radius} is: {area_of_circle:.2f}") # We can also use other functions, like calculating square roots value = 16 sqrt_value = math.sqrt(value) print(f"The square root of {value} is: {sqrt_value}") You can also import specific components from a module using the from module_name import object_name syntax. This is useful when you only need a few functions or variables and want to avoid typing module_name. repeatedly. Be cautious not to import too many things directly, as it can lead to name conflicts if multiple modules define objects with the same name. # Example 2: Importing specific functions from the 'statistics' module from statistics import mean, stdev # Let's say we have a list of patient drug concentrations (in mg/L) drug_concentrations = [12.5, 13.1, 11.9, 14.0, 12.8, 13.5] # Calculate the mean concentration avg_concentration = mean(drug_concentrations) print(f"Average drug concentration: {avg_concentration:.2f} mg/L") # Calculate the standard deviation std_dev_concentration = stdev(drug_concentrations) print(f"Standard deviation of drug concentrations: {std_dev_concentration:.2f} mg/L") For convenience, you can also assign an alias to a module during import using import module_name as alias_name . This is particularly common for modules with long names or when standard aliases are widely adopted (e.g., import numpy as np ).
Creating Your Own Modules
The true power of modules comes when you start creating your own. This allows you to encapsulate your specialized functions and classes for drug discovery, clinical trial analysis, or laboratory automation into reusable units. To create a module, simply save your Python code in a file with a .py extension. The name of the file (without the .py ) will be the module's name. Let's imagine you're developing a set of utility functions for pharmacokinetic analysis. You could create a file named pharm_utils.py with the following content: # pharm_utils.py def calculate_half_life(elimination_rate_constant): """ Calculates the half-life of a drug given its elimination rate constant. Formula: t_1/2 = ln(2) / k_e """ if elimination_rate_constant Now, in another Python script (in the same directory or a directory that's in Python's path), you can import and use these functions and the class: # my_analysis_script.py import pharm_utils # Using functions from our custom module k_e = 0.15 # per hour half_life = pharm_utils.calculate_half_life(k_e) print(f"Drug half-life: {half_life:.2f} hours") dose_mg = 500 auc_infinity = 3200 # mg*hr/L clearance = pharm_utils.calculate_clearance(dose_mg, auc_infinity) print(f"Drug clearance: {clearance:.2f} L/hr") # Using the class from our custom module aspirin = pharm_utils.Drug("Aspirin", 180.16) print(f"{aspirin.name} molecular weight: {aspirin.get_molecular_weight()} g/mol") This demonstrates how creating your own modules allows you to build a library of specialized tools relevant to your pharmacy or biotech work, making your projects more modular and scalable.
Key Takeaways:
Modules are Python files ( .py ) containing functions, classes, and variables. They promote code organization, reusability, and maintainability. Use import module_name to import an entire module. Use from module_name import object_name to import specific components. Use import module_name as alias for shorter or more conventional module names. Creating your own modules involves saving your Python code in a .py file and then importing it into other scripts.
Practice Exercise:
Imagine you are developing a set of functions to assist in genetic sequence analysis. Create a Python module named genetics_tools.py . Inside this module, define a function called reverse_complement(sequence) that takes a DNA sequence string (e.g., "ATGC") as input and returns its reverse complement. For DNA, A pairs with T, and G pairs with C. Then, in a separate Python script, import your genetics_tools module and use the reverse_complement function on a sample DNA sequence like "AGCTATCG" to print its reverse complement.
Watch the full lesson — free
This topic is part of Python Programming - Basics, a complete AI-narrated video course. Press play once and watch the entire lecture like a movie.
Start the course free →