Monday, May 5, 2014

14. Python Modules


Having different files, within a larger program, helps separate the different parts of the code.




The first reason we need more than 1 file, is so their could be namespace separation. However, we may use them merely for separating the main program from the functions.




This is an example of a module. Actually any Python file, ending with a dot py extension is a module. This module just prints a String and initializes a number.


# mod1.py

print 'I am being imported.'
A = 1




When Python is asked to search for modules, it searches a search path. This is inside a list of Strings. However the first string is empty to indicate the current directory. We can put all our modules in the directory with the main program.


# search.py

import sys
searchPath = sys.path()
print "The search path is:" # Either pair of " and ' can be used
print searchPath



Here we go into the directory where we have saved the module, thus that becomes the current directory. Now an import statement will execute any code and also initialize any variables. Note the import is done only once. If we want, we may use the reload importing function, that is, if the file has changed like in a dynamic database.




We can also import a module with some alias. Usually aliases are a few letters and LR would be a better alias than that in the example. This way your file name could be big and descriptive.




When importing, it is possible to import only a select number of variables. Note, we do not have any access to module afterward, just the variables which have been imported.




You can import a variable with an alias. Unless the name is really big, this might not make much sense.




Also we can import everything, that is, all names in the module will become part of current namespace. This is often done to reduce typing and clarifying our code.




A documentation string is created by a pair of triple quotes. This could be any helpful string. First, we imported the Python 3 function, from the __future__ module, so the print statements can look like a function call. Note, we do not have to care where the in-built modules like __future__ and others are located. This also applies for libraries like numpy, whose setup programs should have handled the details. Basically, most of these libraries are located in Lib, site-packages, directory in the Python directory.


"""
I will illustrate modules.
HELLO
"""
# mod2.py
from __future__ import print_function 



print('I am being imported.')
A = 1
B = 5



This is using the previous module and getting the doc with a question mark. We can also write help and the module name in parenthesis. Using the magic function %whos, we find the module has been imported into the namespace.


# modL.py

L=[] # L created

def AddL(*addVals):
  L.extend(addVals)
  return



We can share data, between the main program and an external module. The variable should be created in module and imported to the main program, thus we have an alias to the same object. If the object is mutable like a list, it can be changed by both files.




This is an example of a Module. I went over how the function, AddL, works in Tutorial 13. Basically, it just adds terms to the List variable L. On line 3, the variable L is created.




This is the main program. It imports everything in the module, that is L and the function AddL. Now we can change L using AddL function or directly appending. Furthermore, we can access the list such as is done in line 10. Now the print does not have parenthesis as the the print_function has not been imported from the __future__ module.


# mainL.py

from modL import *
# Thus here, L is alias
# to same object

AddL(1,2,3)
AddL(4,5)
L.append('H')
print "L = ",L



Now the main program is run. We can inquire what are the variables in the namespace.




There is an internal variable __name__, which returns the calling program. The program mainL.py is modified to print this variable.


# mainL.py
print "__name__ = ", __name__
from modL import *
# Thus here, L is alias
# to same object

AddL(1,2,3)
AddL(4,5)
L.append('H')
print "L = ",L



Depending on how the program is executed, the variable __name__, will be either the name of module or the String '__main__'. Thus in modules, we usually have tests like if __name__ == '__main__' and have some test code which is only run if module is directly run. You can see that L keeps on extending as the statement L = [] did not run (this is because import only takes place once.




While Python has much more functionality, such as classes, this should be enough to get a basic idea. Also we will not use classes, as we start with examples using the csound program. I went over csound earlier in Tutorial 6.




You will find additional information at pythonaudio.blogspot.com.



This is the video of Tutorial 14:


2 comments:

About Me

I have used Python for the last 10+ years. I have a PhD in Electrical Engineering. I have taught Assembly Language programming of Intel-compatible chips as well as PC hardware interfacing. In my research, I have used Python to automate my calculations in physics and chemistry. I also use C++ and Java, often with Python.