seeking the "Hello World" of Packages

Gabriel Genellina gagsl-py at yahoo.com.ar
Fri Aug 11 19:53:33 EDT 2006


At Friday 11/8/2006 14:48, Bell, Kevin wrote:

>I'm trying to get an idea of how packages work and I've read about it in
>the Py Tutorial and Nutshell, but I'm still craving a concrete example
>that I can poke through.  Does anyone have a really basic package that
>does very little that I could look at?
>
>What I've gathered thus far is that a package is simply a directory, say
>C:\MyPackage, that would contain __init__.py which tells Python to be
>aware of all the other modules in C:\MyPackage.  Am I correct?
>
>C:\MyPackage\
>             \__init__.py
>             \justPrintHelloWorld.py
>             \multiply5By10.py
>
>Would I expect the following behavior?:
>
> >>>import MyPackage
> >>>MyPackage.justPrintHelloWorld
>"Hello World"
> >>>MyPackage.multiply5by10
>50

Not exactly. Assuming your __init__.py is empty, 
MyPackage.justPrintHelloWorld references that *module*. If you have a 
function called "printHelloWorld" there, you could call it this way 
from another unrelated module:

import MyPackage
MyPackage.justPrintHelloWorld.printHelloWorld()

or

from MyPackage import justPrintHelloWorld
justPrintHelloWorld.printHelloWorld()

or

from MyPackage.justPrintHelloWorld import printHelloWorld
printHelloWorld()

But sometimes, either by convenience or to hide implementation 
details, you put something into the package's namespace:

<<<__init__.py>>>
from justPrintHelloWorld import printHelloWorld

Then you could use:

import MyPackage
MyPackage.printHelloWorld()

Note: In order to be able to import MyPackage, the directory 
MyPackage must be a subdir of anything listed on sys.path. It's 
unlikely that C:\MyPackage would work. Try using 
python\lib\site-packages instead.

Read the Tutorial, section Modules, for more information.



Gabriel Genellina
Softlab SRL 


	
	
		
__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas




More information about the Python-list mailing list