You can import a module by using the import statement. The syntax of the import statement is this:
import module1[,module2[,... moduleN]
A module can be imported in another module or in the main module. The main module forms the top level of the collection of variables that you can access in a script and in the calculator mode.
When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the inter- preter searches before importing a module. We will discuss the search path later in this chapter.
To import the module welcome.py, type the following command in the interpreter:
>>>import welcome
>>>welcome.print_func(‘Jim’)
The output of the preceding statement will be:
Welcome Jim
Here’s another example of a module called fib.py, which generates the Fibonacci series.
#fib.py
def fibonacci(a,num1=0,num2=1): print num1
while num2<a: print num2 num2=num1+num2 num1=num2-num1
In the Python interpreter, type the following command:
>>>import fib
This command does not execute the functions defined in the module directly; it only enters the module fib in the current symbol table. To access the function inside the module, use the following command:
>>>fib.fibonacci(100) 0 1 1 2 3 5 8 13 21 34 55 89
When a module is imported, the interpreter creates a byte-compiled version of the module. This byte-compiled version of the Python file has the .pyc extension, and this version is created in the same directory that contains the module. For example, for the module fib.py, the byte-compiled version will be fib.pyc.
Namespaces and Variable Scope
A namespace maps names with objects. When a name is added to a namespace by declaring a variable or a function, binding occurs and the name is said to have bound to the object. Similarly, the process of changing the mapping of the name with the object is called rebinding, and removing the mapping is called unbinding. At any given time during execution, there are only two or three active namespaces. These are local, global, and built-in namespaces. The names that can be accessed by the Python inter- preter from these namespaces depend on the order in which the namespaces are brought into the system.
First, the built-in namespace, which consists of names in the __builtins__ module, is loaded. Then, the global namespace for executing the module is loaded. When the module starts executing, the global namespace becomes the active name- space. If a function call is made during execution, the local namespace is created.
Therefore, namespaces involve the mapping of objects with their names. The scope of a name decides the locations within the code from which the name can be accessed.
For any attribute such as a variable or a function, the names within and outside the local namespace are in the local and global scope, respectively. In any program, local namespaces are created and deleted along with function calls, but the built-ins and global namespaces are permanent. When a module is imported for the first time, all the executable statements and function definitions are executed. Each module has its own private symbol table. This table is used as the global symbol table for all the functions inside that module. The global variables within a module can be used as any other global variables inside that module; however, these variables will be local to that mod- ule. For example, here is an example of a call to the function fibonacci that generates an error. The fibonacci function is local to the module fib.
>>>import fib >>> fibonacci(100)
Traceback (most recent call last):
File “<interactive input>”, line 1, in ? NameError: name ‘fibonacci’ is not defined
In order to access variables and functions local to a module outside that module, you need to use the name of the attribute following the module name. For example,
>>>import fib >>>fib.fibonacci(100) 0 1 1 2 3 5 8 13 21 34 55 89
Reference to an object made using the dotted attribute notation is called fully quali- fied name. This notation prevents an exact conflicting match in the importing module’s current namespace. The syntax for the notation is this:
modulename.functionname
For example, the function fibonacci() in the module fib.py is called fib. fibonacci(). There can be only one module with a given name that can be loaded on the Python interpreter. Therefore, fib. fibonacci() cannot conflict with another name. If there is another module named fibnew.py containing the function fibonacci(), the function will be called fibnew. fibonacci(). Therefore, there is no chance of conflict between the names of attributes.
If a function in a module returns a value instead of printing the value, the fully qual- ified name of a function can also be assigned to a variable. Consider the following example: #casemod.py def case(inp): if (inp >= ‘A’): if(inp <= ‘Z’): return ‘Uppercase’ elif (inp >= ‘a’):
if(inp <= ‘z’): return ‘Lowercase’ else:
return ‘Input character > z’ else:
return ‘Input character > z but less than a’ else:
return ‘Input character less than A’
The preceding module checks whether an input variable is in uppercase or lower- case and returns a string. After importing the module, you can capture the value returned by the case() function in a variable as follows:
>>>import casemod >>>c=casemod.case(‘H’) >>>c
‘Uppercase’
The variable c has the value returned by the function casemod.case(). You can now use the variable c for executing this function.
More on Importing Modules
A module can be imported by another module. Python allows you to place an import statement, wherever required, in the importing module before using the attributes of the imported module. Conventionally, though, all import statements are placed at the beginning in the importing module. After importing a module, the attributes in the imported module are placed in the global symbol table of the importing module.
A variant of the import statement places the attributes of the imported module in the global symbol table of the importing module. Using the from-import statement, you can import specific elements from a module into your namespace. The syntax of the from-import statement is this:
from module import item1[,item2....[,itemN]]
For example, to import the function fibonacci from the module fib, use the fol- lowing statement:
This statement does not import the entire module fib into the current namespace; it just introduces the item fibonacci from the module fib into the global symbol table of the importing module. In other words, when you import only names from other modules, the names become a part of the current namespace. When changes are made to these names in the importing module, only copies of the variables denoted by these names are altered. The original variables in the namespace of the imported module remain unaltered. Let’s discuss this with the help of two modules, importing_mod.py and imported_mod.py.
#imported_mod.py ruf=’xyz’ def bee():
print “ruf in importing_mod”, ruf #importing_mod.py
from imported_mod import ruf,bee bee()
ruf=’507’
print “ruf in imported_mod”, ruf bee()
When you run the script in importing_mod.py, you obtain the following output:
ruf in importing_mod xyz ruf in imported_mod 507 ruf in importing_mod xyz
Notice that when the imported function name is called for the first time, the value of the variable ruf is the same as that assigned in the imported module originally. Even when the value of the variable ruf is changed in the importing module, it still remains the same in the imported module. This can lead to a conflict when you actually want to change the value of a variable in the importing module. The only solution to this is to use a fully qualified name by using the attribute dotted notation. Therefore, change the code of importing_mod.py as follows:
#importing_mod.py
from imported_mod import ruf,bee imported_mod.bee()
imported_mod.ruf=’507’
print “ruf in imported_mod”, imported_mod.ruf imported_mod.bee()
When you run the script in importing_mod.py, you obtain the following output:
ruf in importing_mod xyz ruf in imported_mod 507 ruf in importing_mod 507
It is also possible to import all names from a module into the current namespace by using the following import statement:
from fib import *
N OT E
“from module import *”provides an easy way to import all theitems from a module into the current namespace; however, this statement should be used sparingly. After all the items are imported from a module by using from module import *, they become a part of the current namespace. This can lead to conflicts because the names from the imported module can clash with the names already present in the current namespace. The names from the imported module can even override the names that are already present in the current namespace.
If you do not want to import all the attributes in a module by using the "from module import *" statement, you can begin the name of the attribute with an under- score (_). In this way, you can hide data in your module even if you import all the attributes of the module. This technique is not useful, though, if the entire module is imported.
Python also contains a library of standard modules. Some modules are built into the interpreter. These provide access to the core of the language but are programmed to access operating system variables. Some of these modules are sys, os, and time. We will discuss some built-in modules as and when required in the later chapters of this book.