4 ways to import a module in Python (2024)

Sign in to change your settings

Let's talk about the four ways to import something from a module in Python.

Importing the whole module object

The first way is to use the import statement, using the syntax import module_name:

>>> import math

We've just imported the math module.We can use the things within this module by looking up attributes on the math module object.For example, we can get the square root of a number by calling math.sqrt:

>>> math.sqrt(25)5.0

Or we can access the number π with math.pi:

>>> math.pi3.141592653589793

But we can't access just pi or sqrt (without that math. prefix):

>>> piTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'pi' is not defined>>> sqrt(25)Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'sqrt' is not defined>>>

The reason is, when we import a module using that import module_name syntax, we get just one thing: a variable that points to a module object.

>>> import math>>> math<module 'math' (built-in)>

Everything in that module is accessible as an attribute on that module object:

>>> math.pi3.141592653589793

Importing specific things from a module

If you wanted to just type pi instead of math.pi, you could use the from syntax for importing:

>>> from math import pi>>> pi3.141592653589793

So now we have pi, but not sqrt (because we didn't import it):

>>> sqrt(25)Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'sqrt' is not defined

And we don't have access to the whole math module:

>>> mathTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'math' is not defined

If you want to import multiple things from a module using this from syntax, you could put commas each thing you'd like to import:

>>> from math import pi, sqrt>>> pi3.141592653589793>>> sqrt(25)5.0

That from math import pi, sqrt line plucks out pi and sqrt from the math module, but nothing else.

Avoiding name collision when importing

If you use the from syntax to grab specific things from a module and you grab something of the same name from two different modules, you're in for trouble.

Here we're importing sqrt from the math module and sqrt from the cmath module (cmath is for complex numbers):

>>> from math import sqrt>>> from cmath import sqrt

The sqrt function we end up with came from the cmath module:

>>> sqrt(25)(5+0j)

We imported two different functions named sqrt and the last one won.We first got sqrt from the math module and then we overwrote our local sqrt variable with the sqrt function from the cmath module.

To fix this we could rename sqrt from the cmath module as we import it, by using the as syntax:

>>> from math import sqrt>>> from cmath import sqrt as csqrt

So, sqrt is now the sqrt function from the math module and csqrt is the one from the cmath module:

>>> sqrt(25)5.0>>> csqrt(25)(5+0j)

If you look at the function the csqrt variable points to, you'll even see that it's actually called sqrt:

>>> csqrt<built-in function sqrt>

We pointed our local variable csqrt to the sqrt function within the cmath module.

Importing a module under a different name

You can also use the as syntax when importing a whole module.

>>> import math as m

The variable m now points to the math module object which means we can't say math.pi anymore:

>>> math.piTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'math' is not defined

Instead we can use m.pi or m.sqrt:

>>> m.pi3.141592653589793>>> m.sqrt(25)5.0

You likely won't see this convention used often except in specific Python communities where it's commonplace.

For example, in the Pandas world people often import pandas as pd:

>> import pandas as pd

And in the NumPy world, people often import numpy as np:

import numpy as np

It's not very common to see module names shortened using the as syntax, except in areas where it's conventional (like Pandas and NumPy).

Trey says: If I saw m.pi in your code, I'd probably find it a little bit odd.

The 4 ways to import a module

So there's four different ways to import:

  1. Import the whole module using its original name:import random
  2. Import specific things from the module:from random import choice, randint
  3. Import the whole module and rename it, usually using a shorter variable name:import pandas as pd
  4. Import specific things from the module and rename them as you're importing them:from os.path import join as join_path

That last one is usually done to avoid a name collision or sometimes to make a more descriptive name (though that's not very common).

Trey's recommendations

  1. Use from for short and descriptive variable namesI tend to use the from syntax most (number 2 above) because I prefer short and descriptive variable names.

  2. Import the whole module if needed to avoid ambiguity.If there's a name like choice that isn't as clear as random.choice, then I prefer to import the whole module for a more descriptive name

  3. Avoid renaming imports.I very rarely use the as syntax (unless I'm in the pandas or numpy worlds, where it's common convention).And I almost never use the as syntax with from unless I'm avoiding a name collision.

4 ways to import a module in Python (2024)

FAQs

4 ways to import a module in Python? ›

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.

What are the ways to import modules in Python? ›

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.

How many import modules are in Python? ›

Import Python Standard Library Modules

The Python standard library contains well over 200 modules.

How to import a package in Python? ›

In Python, we can import modules from packages using the dot (.) operator. Now, if this module contains a function named select_difficulty() , we must use the full name to reference it.

How to import Python file in Python? ›

You create a new Python script in the same folder as the module you wish to import. You then use the 'import' keyword followed by the name of the module file (without mentioning the file extension). For instance, if your module file is named my_module.py, you only use import my_module.

Why do we import modules in Python? ›

In Python, you use the import keyword to make code in one module available in another. Imports in Python are important for structuring your code effectively. Using imports properly will make you more productive, allowing you to reuse code while keeping your projects maintainable.

How many types of modules are there in Python? ›

There are two types of python modules: Built-in python modules. User-defined python modules.

What are the Python modules? ›

In Python, Modules are simply files with the “. py” extension containing Python code that can be imported inside another Python Modules Operations Program. In simple terms, we can consider a module to be the same as a code library or a file that contains a set of functions that you want to include in your application.

Where are modules imported from in Python? ›

When we import a module the Python interpreter searches for the module in the following manner: First, it searches for the module in the current directory. If the module isn't found in the current directory, Python then searches each directory in the shell variable PYTHONPATH.

How do I import all Python libraries? ›

The solution is called PyForest. PyForest is a lazy import. As the name says, it imports the most popular Data Science libraries for Python. The PyForest developers aim to import 99% of all the most used libraries.

How to import a list in Python? ›

To import a list from a file in Python 3, you can use the pickle module to serialize and deserialize Python objects.

How to import modules in terminal? ›

To import and alias a module, use the syntax import <module_name> as <alias> . From then on, use the alias to refer to the module.

How to import data in Python? ›

To import the data from the CSV file, we'll create a “Data Frame” object using the “pandas” module. We name the variable “raw_csv_data” and use it to record the values from the integrated function “read_csv” from the “pandas” package. Then, inside the parentheses, in double quotation marks, we add the name of the file.

How do I import files? ›

Here are three steps for how to import files:
  1. Select "File" In many platforms, you can find the "Import" option by selecting "File." In some cases, you might select "File" and "Open" to choose the file to import. ...
  2. Select "Import" ...
  3. Choose the right format.
Jun 24, 2022

When a module is imported, its contents? ›

So when you import a module, you always execute its contents. Otherwise you wouldn't be able to use any functions (or classes) in that module.

What are the three ways to import modules in Python? ›

So there's four different ways to import:
  • Import the whole module using its original name: import random.
  • Import specific things from the module: from random import choice, randint.
  • Import the whole module and rename it, usually using a shorter variable name: import pandas as pd.
Apr 21, 2021

How do I import all from a module in Python? ›

You can import all the code from a module by specifying the import keyword followed by the module you want to import. import statements appear at the top of a Python file, beneath any comments that may exist. This is because importing modules or packages at the top of a file makes the structure of your code clearer.

How do I install and import modules in Python? ›

Install Modules with pip
  1. Ensure the pip module is already installed. ...
  2. Verify the release of pip to ensure it is installed correctly. ...
  3. Install the new Python module using the command pip install <module-name> . ...
  4. To list all installed Python modules and packages, use the pip list command.
Jan 28, 2022

Top Articles
Latest Posts
Article information

Author: Lakeisha Bayer VM

Last Updated:

Views: 6402

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Lakeisha Bayer VM

Birthday: 1997-10-17

Address: Suite 835 34136 Adrian Mountains, Floydton, UT 81036

Phone: +3571527672278

Job: Manufacturing Agent

Hobby: Skimboarding, Photography, Roller skating, Knife making, Paintball, Embroidery, Gunsmithing

Introduction: My name is Lakeisha Bayer VM, I am a brainy, kind, enchanting, healthy, lovely, clean, witty person who loves writing and wants to share my knowledge and understanding with you.