Modules and Libraries

Using External Code: Modules and Libraries

One of Python's greatest strengths is its vast ecosystem of modules and libraries. A module is a file containing Python definitions and statements. A library (or package) is a collection of modules that provide functionality for a specific purpose.

Importing Modules

You can use the import statement to use code from another module. Python has a rich standard library with many built-in modules.

# Import the built-in math module to use its functions and constants
import math

print(math.pi) # 3.14159... print(math.sqrt(16)) # 4.0

You can import specific items from a module to use them directly

from datetime import datetime print(datetime.now())

You can also give a module an alias (a nickname)

import random as rd print(rd.randint(1, 10)) # a random integer between 1 and 10

Installing Third-Party Libraries with PIP

PIP is the package installer for Python. You can use it from your command line to install packages from the Python Package Index (PyPI), a huge repository of software for Python.

# In your computer's terminal (not the Python interpreter):
# Install 'requests', a popular library for making HTTP requests
$ pip install requests

Install 'pandas', a powerful data analysis library

$ pip install pandas

Virtual Environments

It's a best practice to use virtual environments to manage dependencies for different projects. A virtual environment is an isolated Python setup that allows packages to be installed for use by a particular application, rather than being installed system-wide. This prevents conflicts between projects that might require different versions of the same library.

# In your terminal, navigate to your project folder
# Create a virtual environment named 'myenv'
$ python -m venv myenv

Activate the environment on MacOS/Linux

$ source myenv/bin/activate

Activate the environment on Windows

$ .\myenv\Scripts\activate

Your terminal prompt will change to show you're in the environment.

Now, any 'pip install' will only install into this environment.