Introduction
Python modules are files containing code that can be used within other Python code files. They consist of Python statements and definitions, and allow you to organize code logically into reusable units.
Modules help structure larger projects by breaking them into smaller, manageable components. For example, suppose you are developing a web application that includes functionality for user authentication, database operations, and data visualization. You can create separate modules for each of these components, such as authentication.py
, database.py
, and visualization.py
, respectively. Each module encapsulates related functionality, making it easier to understand, maintain, and extend the application. Additionally, Python’s module system enables code reuse across different projects, promoting efficiency and consistency in software development.
This lesson covers importing Python modules, a process by which code in a module is inserted into another code file.
Importing Python Modules With the import Statement
Importing a module in Python is a straightforward process. You use the import
keyword followed by the name of the module you want to import.
Here is the syntax for importing a module:
import module_name
In this syntax sample, module_name
is the name of the module you wish to import. Once imported the code in the module is executed, and you can access functions, classes, and variables defined within the module using dot notation (module_name.item_name
).
Example:
import math print(math.pi)
Output:
3.141592653589793
In the example above, the math
, a built-in module internal to Python, is imported (line 1). Following the import, pi
, one of the constants defined in math
, is accessed using the dot notation (line 3).
Aliasing Modules
Sometimes modules have long names, making them cumbersome to use repeatedly in your code. In those cases, you can alias modules with shorter names using the `as` keyword. (There is no restriction that limits the alias to shorter names, but that’s the way aliases are usually used.)
Here is the syntax for aliasing modules:
import module_name as alias
By aliasing, you can refer to the module using a new name throughout your code.
Example:
import datetime as dt print("Today's date:", dt.date.today())
Output:
Today's date: 2024-03-12
The example above imports the datetime
module and aliases it to dt
. Then, today’s date is accessed using the dt
alias and printed out.
Importing Items With the from-import Statement
Instead of importing an entire module, you can import individual items from a module using a from
–import
statement. Those items can be anything the module defines, such a function, class, variable or constant.
Importing a Single Item
The simplest use of the from
–import
statement is importing one item from a module with the following syntax:
from module_name import item_name
By importing with a from
–import
statement, you can access the specified item directly, without prefixing it with the module name.
Example:
from math import pi print(pi)
Output:
3.141592653589793
In the example above, pi
is imported using a from
–import
statement (line 1) and can therefore be accessed directly without referencing the `math
` module it is imported from (line 3).
Importing All Items
You can also import all items from a module by using the wildcard *
character.
Here is the syntax for importing all the items from a module:
from module_name import *
This imports all items defined in the module, allowing you to access them directly without the module prefix. However, it’s generally discouraged because it can lead to namespace pollution and makes it unclear where certain items are defined.
Namespace pollution occurs when a programming namespace, (the context in which names are defined and used,) becomes cluttered with too many names, leading to potential naming conflicts and confusion.
Example:
from math import * print(pi) print(e)
Output:
3.141592653589793 2.718281828459045
In the example above, all the items in the math
module are imported using the wildcard *
(line 1). Because of this, we are able to access the mathematical constants pi
and e
directly (lines 3 and 4).
Importing Multiple Specific Items
It’s possible to import multiple specific items from a module using the from
keyword followed by a comma-separated list of the items you want to import. This approach allows you to selectively import only the items you need, rather than importing the entire module or using wildcard imports. It is a convenient way to keep your codebase clean and reduce namespace pollution.
Here is the syntax for importing multiple items:
from module_name import item1, item2, item3, ...
In the above syntax, module_name
is the name of the module you’re importing from, and item1
, item2
, item3
, etc., are the specific items you want to import.
Example:
from math import sqrt, pow print("Square root of 16:", sqrt(16)) print("2 to the power of 3:", pow(2, 3))
Output:
Square root of 16: 4.0 2 to the power of 3: 8.0
The example above imports only the sqrt
and pow
functions from the math
module using the from
–import
statement (line 1). It then directly uses these imported functions without referencing the math
module they were imported from (lines 3 and 4).
Aliasing Imported Items
Just as modules can be aliased, so can imported items. Aliasing allows you to rename imported items without modifying their original names in the module they come from. Aliasing items is particularly useful for shortening long items names, giving more descriptive names when items have generic ones, or avoiding conflicts with existing names in your code.
Aliasing of imported items is also done with the as
keyword, which follows the imported item’s name.
Here is the syntax for aliasing items:
from module_name import item_name as item_alias
In the syntax sample above, module_name
is the name of the module you’re importing from, item_name
is the name of the specific item you’re importing, and item_alias
is the alias you want to assign to that item.
Example:
from math import e as math_const_e print(math_const_e)
Output:
2.718281828459045
In the example above, math
module’s constant e
is aliased as math_const_e
(line 1) to give it a name that is clearer and more descriptive. The value of e
is then printed out using its alias (line 3).
Note that if aliased, the original name of the imported item is not known in the importing code. Python raises an
NameError
if it’s referenced.
You can also alias multiple items in a comma separated list with the following syntax:
from module_name import item1 as alias1, item2 as alias2, item3 as alias3, ...
Summary & Reference for Importing Python Modules
Python modules help organize and reuse code. They allow you to break down your codebase into manageable components, promoting better organization, maintenance, and extension of your projects. Each module is a code file that encapsulates related functionality and can be imported into other Python files.
Importing modules is straightforward in Python using the import
keyword followed by the module name.
import math
Items in an imported module are accessed with the dot notation: module_name.item_name
import math print(math.pi)
You can alias imported modules with different names using the as
keyword. Aliases are typically shorter names, making them easier to use throughout your code.
import datetime as dt
If you only need specific items from a module, you can import them directly using the from
–import
statement.
from math import pi
Items imported with
are accessible directly and do need to be prefixed by the module name and a dot.from
-import
from math import pi print(pi)
To import all items from a module, you can use the *
wildcard character, although this approach is generally discouraged to avoid namespace pollution.
from math import *
You can import multiple specific items from a module with the from
–import
statement by writing a comma-separated list of the imported items. This practice keeps your codebase clean and reduces namespace clutter.
from math import sqrt, pow
You can alias imported items for clearer naming or to avoid conflicts.
from math import e as math_const_e