Import packages
Use Python packages and libraries
Python offers a rich ecosystem of pre-written code that you can use in your own projects. This code is organized into packages and modules, making it easy to extend your program's capabilities.
Using packages
Packages are collections of Python modules. Modules are simply .py files containing Python code. When you want to use code from a package, you need to import it first.
Importing a package makes its functions, classes, and variables available for you to use in your current script or interactive session.
Understanding the terminology
- Module: A single Python file (
.py) containing definitions (functions, classes, variables) that can be imported. - Package: A directory of Python modules, often with an
__init__.pyfile (though not strictly required in modern Python). It allows for hierarchical structuring of modules. - Library: A broader term, often used interchangeably with "package" or "module," referring to a collection of non-executable programs that can be reused.
- Framework: A larger structure that defines how you build an application, often providing a foundation and set of tools for a specific type of development (like web development).
Import patterns explained
There are several ways to import code. Each has its own best use case.
# Import the entire module
import math
print(math.pi)
# Import a specific item from a module
from datetime import date
print(date.today())
# Import with an alias (rename for convenience)
import random as rnd
print(rnd.randint(1, 10))
# Import all items (generally discouraged)
from collections import *
print(deque([1,2,3]))Built-in modules
Python comes with a rich set of built-in modules that are always available. You don't need to install them; you just need to import them.
Common built-in modules
math: For mathematical functions and constants.random: For generating random numbers.os: For interacting with the operating system (like file paths).sys: For interacting with the Python interpreter.datetime: For working with dates and times.
Import methods
Imports are usually placed at the top of your Python file. This helps keep your code organized and clearly shows what dependencies your script has.
# my_script.py
import math
from datetime import datetime
def calculate_area(radius):
return math.pi * radius**2
print(f"Today is: {datetime.now().date()}")
print(f"Area of circle with radius 5: {calculate_area(5)}")Installing packages
For packages not included with Python, you'll need to install them. The standard tool for this is pip (Python's package installer).
pip install package_nameLet's say you want to work with dates in a more advanced way; you might install the dateutil package.
pip install python-dateutilSharing your project: requirements.txt
When you share your Python project, others will need to install the same packages you used to run your code. A requirements.txt file lists all your project's dependencies.
Creating requirements.txt
You can automatically generate this file based on your current environment's installed packages.
pip freeze > requirements.txtThis command outputs a list of all installed packages and their versions into the requirements.txt file.
# requirements.txt example
Flask==2.0.1
Jinja2==3.0.1
Werkzeug==2.0.1Installing from requirements.txt
To install all packages listed in a requirements.txt file, use the following pip command:
pip install -r requirements.txtUsing external packages
Once installed, external packages are imported just like built-in ones.
from dateutil.parser import parse
date_string = "2023-10-27 10:30 AM"
parsed_date = parse(date_string)
print(parsed_date)This parse function from the dateutil package is much more flexible than Python's standard datetime functions for parsing various date formats.
Finding packages
The primary place to find Python packages is the Python Package Index, or PyPI (pypi.org). It's a vast repository of community-contributed software.
You can search for packages by name, keyword, or browse by category. Each package page provides installation instructions, documentation links, and project details.
Common mistakes
- Forgetting to install: Trying to
importa package without first runningpip install package_name. - Typos: Misspelling a package name during import or installation.
- Name clashes: Using
from module import *and accidentally overwriting a function or variable you defined.
What's next?
Now that you know how to use packages, explore PyPI to find interesting libraries for your projects. Experiment with popular ones like requests for web requests, pandas for data analysis, or matplotlib for plotting.
Understanding how to leverage existing code is a huge step in becoming an efficient Python developer.