Example. This program requires the date and timedelta modules from the datetime package. It signals this by using an asterisk (star) after the import keyword.
Tip The star character means "import all." All submodules of datetime are imported.
Alternate syntax. The star syntax is not the only option. We can specify the modules directly, by naming them. This may be preferred in many projects.
Tip We can specify multiple modules from one package using a comma between each name. This reduces the line count of the program.
from datetime import date, timedeltafrom datetime import date
from datetime import timedelta
NameError. A NameError is often caused by a missing import statement. Consider this program. It correctly imports date, but lacks the timedelta import that it needs.
However The program fails at the line where we assign "yesterday." The print statement is never reached.
from datetime import date
today = date.today()
yesterday = today - timedelta(days=1)
print(yesterday)Traceback (most recent call last):
File "C:\programs\file.py", line 8, in <module>
yesterday = today - timedelta(days=1)
NameError: name 'timedelta' is not defined
Custom. Here we use a custom Python module. Please create a new Python file in the same directory as your Python program. Give it a name.
Then In the Python program, use the import statement to include it. You can call methods in the module.
Tip The module file must be in the same directory as your program. And its name must equal the name in your "import" statement.
def buy():
print("stock.buy called")import stock
# Call the method in the stock module.
stock.buy()stock.buy called
Python programs can become complex. With the import statement, and its associated keyword "from," we bring in external package resources to our program.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 10, 2023 (edit).