Tuesday, October 20, 2009

Packages




I l@ve RuBoard









Packages


Packages are a way of organizing Python modules and a way to prevent one programmer from stomping on the module of another. You assign a module to a package with the form Package_Name.Module_Name. Thus, the module name mystuff.sys indicates a module named sys in a package named mystuff.


Packages are essentially directories that contain a special __init__.py file to indicate to Python that the directory it's dealing with is a package. This file is used when the package is first loaded. Let's create our own package and call it package1/__init__.py.


First we create a directory called package1. Then we create a file named __init __.py with one Python statement that prints "Hello from package1", and save it to the package1 directory. Next we create a module called module1 in package1 and put in it a Python statement that prints "hello from module1 in package1". In module1, we define one do-nothing function and one do-nothing class named class1 that contains a do-nothing method named method1.


Here's package1/__init__.py.



print "Hello from package1"

Here's package1/module1.py:



print "hello from module1 in package1"

def function1():
pass

class class1:

def method1():
pass

Make sure that the package1 directory is in the module search path. Then move out of package1 and fire up the Jython interpreter.



>>> from package1.module1 import class1
Hello from package1
hello from module1 in package1

>>> dir()
['__name__', 'class1']

Here we see that the code in __init__.py and module1 is executed when we load class1.


Now exit and restart the Jython interpreter and try this:



>>> import package1
Hello from package1

>>> dir()
['__name__', 'package1']

>>> dir(package1)
['__file__', '__name__', '__path__']

>>> vars(package1)
{'__file__': 'C:\\python\\book\\chap5\\.\\package1\\__init__.py'
, '__path__': ['.\\package1'], '__name__': 'package1'}

Notice that, when we import the package, its __init__.py module is executed. Look at the package's namespace. (Remember that the vars command is like the dir command except that it lists the namespace's names and values.)


Within __init__.py you can define a list called __all__, which is used with package import* to tell Python to import all modules in this package. Actually, Python imports all modules listed in the package's __all__ list, so if you want to import a module with the * command, you have to put it in __all__.


Packages can have subpackages. These are subdirectories under the package with __init__.py modules. Since __init__.py is part of the package, the package can contain anything that you find in a regular module, such as classes and functions.








    I l@ve RuBoard



    No comments:

    Post a Comment