Python Import Syntax Examples: Modules, NameError

Understand the import statement and the from keyword. Use star syntax.

Import. Some programs use no import statements. But often we require access to external packages and their modules. With the from and import directives, we include those names into a program. This avoids errors.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. This means "import all." All submodules of datetime are imported.

Caution: This program is correct. But if you remove the "from import" statement, it will result in NameErrors.

Python program that uses import star syntax from datetime import * def yesterday(): today = yesterday = today - timedelta(days=1) return yesterday print( print(yesterday()) Output 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. It makes clear which modules are being used. This may be less complex.

Tip: We can specify multiple modules from one package using a comma between each name. This reduces the line count of the program.

Alternate syntax 1: Python from datetime import date, timedelta Alternate syntax 2: Python 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. This results in a NameError being thrown. Try python, Exceptions.

However: The program fails at the line where we assign "yesterday." The print statement is never reached.

Python program that causes NameError from datetime import date today = yesterday = today - timedelta(days=1) print(yesterday) Output Traceback (most recent call last): File "C:\programs\", 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.

Example file, Python def buy(): print(" called") Python program that uses stock module, import stock # Call the method in the stock module. Output called

Summary. Python programs can become complex. They are not always simple scripts. With the import statement, and its associated keyword "from," we bring in external package resources to our program.Built-ins
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to