Back to Freecodecamp

What Is the Python Standard Library, and How Do You Import a Module?

curriculum/challenges/english/blocks/lecture-working-with-modules/683ec7b778993c6971b56c83.md

latest9.1 KB
Original Source

--description--

In software development, a library is like a toolbox for developers.

Instead of having to implement every single part of the code yourself from scratch, a library gives you pre-written and reusable code, like functions, classes, and data structures that you can use in your projects.

Python has an extensive standard library with many different built-in modules. They're all standardized, well-vetted solutions for many of the problems and tasks you'll face daily as a programmer, such as:

  • Interacting with the operating system.

  • Working with files.

  • Networking.

  • Working with date and time.

  • Performing mathematical operations.

  • Using regular expressions.

  • Testing and debugging your code.

  • And much more!

Some examples of popular built-in modules are math, random, re (short for "regular expressions"), and datetime.

The math module has helpful functions for performing more complex mathematical operations.

The random module is helpful for generating random numbers.

The re module is used for working with regular expressions.

And the datetime module is helpful for working with dates and times in Python.

But how can you access the variables, constants, functions, and classes defined in these built-in modules?

You use an import statement. These statements let you import modules into your Python script. Import statements are generally written at the top of the file. Also, you can customize them based on your needs. First, you use the import statement, followed by the name of the module:

python
import module_name

Let's say that you want to import the math module. In that case, you would write this at the top of your file:

python
import math

Then, if you need to call a function from that module in your Python script, you would use dot notation, with the name of the module followed by the name of the function:

python
module_name.function_name() 

For example, to get the square root of 36, you would write math followed by a dot and then sqrt, an abbreviation of square root, and within parentheses, you would pass any necessary arguments. In this case, we only need to pass in the number we want the square root of:

python
math.sqrt(36)

This is the most basic version of an import statement, but there are other alternatives.

If you need to import the module with a different name (also known as an "alias"), you can use this syntax, with as followed by the alias at the end of the import statement:

python
import module_name as module_alias

This is often used to shorten long module names, or to avoid naming conflicts.

For example, to refer to the math module as m in your code, you can assign an alias to it, like this:

python
import math as m 

Then, you can access the elements of the module using the alias:

python
m.sqrt(36)

But sometimes you don't need to import everything from a module. Perhaps you only need one or two specific functions or classes. Python has exactly what you need in that case.

Now the import statement starts with from, followed by the name of the module, and then the import keyword followed by the name of the elements that you want to import:

python
from module_name import name1, name2

Then, you can use these names without the module prefix in your Python script.

If you want to assign aliases to these names, you can do that by using the as keyword after each, followed by the alias you want to use:

python
from module_name import name1 as alias1, name2 as alias2

Let's say that you only want to import the radians, sine, and cosine functions from the math module. You would write:

python
from math import radians, sin, cos

Now you can call these functions directly in your code, without the math module as a prefix.

Here we have a more detailed example:

To find the sine and cosine of a specific angle initially expressed in degrees, we can call the radians function to convert it to radians, and then call the sine and cosine functions, passing the angle in radians:

python
from math import radians, sin, cos

angle_degrees = 40
angle_radians = radians(angle_degrees)

sine_value = sin(angle_radians)
cos_value = cos(angle_radians)

print(sine_value) # 0.6427876096865393
print(cos_value)  # 0.766044443118978

Notice how we are calling the functions directly, without the name of the module as a prefix. This is because we imported the functions with this alternative syntax.

This is helpful, but it can result in naming conflicts if you already have functions or variables with the same name defined in the Python script itself. So that's something to keep in mind when choosing which type of import statement you want to use.

And finally, we find this import statement that ends with an asterisk. The asterisk is telling Python that you want to import everything in that module, but you want to import it so that you don't need to use the name of the module as a prefix:

python
from module_name import *

For example, if you do this while importing the math module, you'll be able to call any function defined in that module without specifying the name of the module as a prefix. Here are some examples:

python
from math import *
print(sqrt(36))  # 6.0
print(pow(5, 2)) # 25.0
print(exp(1))    # 2.718281828459045

However, this is generally discouraged because it can lead to namespace collisions, and make it harder to know where certain names are coming from.

Import statements work exactly the same for functions, classes, constants, variables, and any other elements defined in the module.

Here is an example of a constant from the math module, the number pi:

python
import math
print(math.pi)

And here is an example of a class from the datetime module. We create a date object that represents July 15, 1959. Then, we assign that date object to a variable and access the day, month, and year individually using dot notation:

python
import datetime
birthday = datetime.date(1959, 7, 15)
print(birthday.day)    # 15
print(birthday.month)  # 7
print(birthday.year)   # 1959

You can find more information about the content of the module in the official Python documentation for that module.

Great. Now that you know more about modules, you should also know about this very important idiom in Python scripts, because they are very closely related:

python
if __name__ == '__main__': 
    # Code

__name__ is a special built-in variable in Python.

When a Python file is executed directly, Python sets the value of this variable to the string "__main__".

But if the Python file is imported as a module into another Python script, the value of the __name__ variable is set to the name of that module (usually the filename without the .py extension).

This is why you'll often find this conditional in Python scripts. It contains the code that you want to run only if the Python script is running as the main program:

python
if __name__ == '__main__': 
    # Code

But if the script is imported as a module, the code within that block doesn't run.

This is helpful because it allows Python scripts to have two purposes. They can be run directly to execute their main logic, or they can be imported into another module without executing their main logic.

--questions--

--text--

Which of the following statements best describes the Python Standard Library?

--answers--

It is a collection of pre-written modules and packages included with Python.


It is a collection of third-party libraries that need to be installed separately.

--feedback--

Think about what "standard" means in the context of the Python Standard Library.


It is the core syntax of the Python language itself.

--feedback--

Think about what "standard" means in the context of the Python Standard Library.


It consists of external libraries written in other programming languages.

--feedback--

Think about what "standard" means in the context of the Python Standard Library.

--video-solution--

1

--text--

Which of the following is the correct syntax to import the entire datetime module and give it a shorter alias dt?

--answers--

import datetime

--feedback--

Think about the keyword used for creating aliases during the import process.


from datetime import date as dt

--feedback--

Think about the keyword used for creating aliases during the import process.


import datetime as dt


from datetime import dt

--feedback--

Think about the keyword used for creating aliases during the import process.

--video-solution--

3

--text--

If you only want to use the mean function from the statistics module directly in your code without prefixing it with statistics, which import statement would you use?

--answers--

import statistics

--feedback--

Think about the keyword used to import specific names from a module.


from statistics import mean


import mean from statistics

--feedback--

Think about the keyword used to import specific names from a module.


from statistics import *

--feedback--

Think about the keyword used to import specific names from a module.

--video-solution--

2