Python Import Statement
In Python, the import statement allows you to load an external library of functions (called a module) into memory.
import libraryname
You can use this statement both in a script and in the interactive Python console.
How to Use Functions from a Library
To use a function from a library, write the library name followed by a dot and the function name.
libraryname.functionname()
Inside the parentheses, provide the arguments required by the function.
Note: If the function does not take any parameters, you still need to include the parentheses, leaving them empty. Otherwise, the Python interpreter will throw an error.
A Practical Example
In this script, I import the math library.
- import math
- x = 1
- sine = math.sin(x)
- print(sine)
Then I use one of its functions (math.sin) to calculate the sine of a value.
The output of the script is:
0.8414709848078965
How to Import a Single Function from a Module
Python also allows you to import just one function from a module, without loading all the others.
Use the from import statement:
from libraryname import functionname
In this case, you can use the function without the library prefix.
functionname()
A Practical Example of from import
In this script, I import only the sin() function from the math module.
- from math import sin
- x = 1
- sine = sin(x)
- print(sine)
Then I use it to calculate the sine of x.
When you import a function with the from import statement, you call it directly (sin) without the library prefix (math.sin). Otherwise, the Python interpreter will throw an error.
The output of the script is:
0.8414709848078965
Why Import a Single Function?
If your program uses only one function from a library, it’s inefficient to load all the other functions into memory.
Additionally, it's more convenient to write your program using only the function names without the module prefix.
Example
>>> sin(x)
However, there’s always a risk that an external function’s name might conflict with an internal function or a local variable in your program.
This is a risk worth considering.
What Are Python Libraries?
They are collections of functions written by other programmers to solve specific problems.
These functions are grouped into modules (libraries) and made available to the Python developer community.
Example of libraries: There are libraries with functions to read a CSV file in Python, perform complex mathematical calculations, compute sine and cosine, and more.
This way, you don’t have to develop a function from scratch every time you need it if someone else has already done it.
Simply call the external function with import or from import and use it.
What’s the difference between import and from import? The import statement loads all the functions in a module. The from import statement loads only the specified functions.
And so on.