In this lesson, you’ll learn more about the import
statement. Module contents are made available to the caller with the import
statement. The import
statement takes many different forms, as you’ll see below.
import <module_name>
The simplest form is the one you already saw:
import <module_name>
Note that this does not make the module contents directly accessible to the caller. Each module has its own private symbol table, which serves as the global symbol table for all objects defined in the module. So, a module creates a separate namespace.
The statement import <module_name>
only places <module_name>
in the caller’s symbol table. The objects that are defined in the module remain in the module’s private symbol table.
From the caller, objects in the module are only accessible when prefixed with <module_name>
via dot notation, as you’ll see below.
After the following import
statement, mod
is placed into the local symbol table. So, mod
has meaning in the caller’s local context:
>>> import mod
>>> mod
<module 'mod' from '/Users/chris/ModulesAndPackages/mod.py'>
But a
, s
, and printy()
remain in the module’s private symbol table and are not meaningful in the local context:
>>> a
Traceback (most recent call last):
File "<input>", line 1, in <module>
a
NameError: name 'a' is not defined
>>> s
Traceback (most recent call last):
File "<input>", line 1, in <module>
s
NameError: name 's' is not defined
>>> printy
Traceback (most recent call last):
File "<input>", line 1, in <module>
printy
NameError: name 'printy' is not defined
gagejesse on Jan. 30, 2020
I dunno how you managed to provide a thorough tutorial on exactly what I needed, two days before I needed it, but I certainly appreciate it. Thank you!