Understanding imports in Python

Understanding imports in Python

Comprender importaciones en Python: A comprehensive guide on how to import modules in Python, including examples and best practices.

March 21, 2023· 1 min read
9 score

Python makes it easy to bring modules or packages into a program by using the "import" statement.
There are three main ways to import modules.

  1. import module_name: This allows you to import a complete module. For example to import the "os" module:
import math
  1. from module_name import function_name:
    This allows you to pick out and use a specific function from a module. So instead of importing the entire "math" module when you need to get the square root of a given number, you could import the square root function only like this:
from math import sqrt

this makes the function available so that you can use it directly in the code without the module prefix like this:

x = sqrt(16)
  1. from module_name import * This will import everything and the kitchen sink too. It imports all the functions and variables from a module. So to import everything from the math module:
from math import *

However, this can cause naming conflicts and make it hard to understand where functions are coming from so this is not normally used as a best practice.

Related Articles