Home
Map
import Examples (NameError)Understand the import statement and the from keyword. Use star syntax.
Python
This page was last reviewed on Jun 10, 2023.
Import. Some Python programs use no import statements. But more often, programs require access to external packages and their modules.
Directives. With the from and import directives, we include those names into a program. This avoids errors. The star syntax may also be used.
Error
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.
datetime
Warning This program is correct. But if you remove the "from import" statement, it will result in NameErrors.
from datetime import * def yesterday(): today = date.today() yesterday = today - timedelta(days=1) return yesterday print(date.today()) print(yesterday())
2014-04-17 2014-04-16
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, timedelta
from 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.
Console
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).
Home
Changes
© 2007-2024 Sam Allen.