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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 10, 2023 (edit).