Some Python programs use no import statements. But more often, programs require access to external packages and their modules.
With the from and import directives, we include those names into a program. This avoids errors. The star syntax may also be used.
This program requires the date and timedelta
modules from the datetime
package. It signals this by using an asterisk (star) after the import keyword.
datetime
are imported.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
The star syntax is not the only option. We can specify the modules directly, by naming them. This may be preferred in many projects.
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.
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
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.
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.