__init__.py question

Terry Hancock hancock at anansispaceworks.com
Sat Apr 23 00:49:19 EDT 2005


On Friday 22 April 2005 07:19 am, codecraig wrote:
> Ok,  I have the following directory structure
> 
> C:\pycode
>    --> blah.py
>    --> mynewdir
>       --> __init__.py
>       --> abc.py
> 
> [[ C:\pycode\mynewdir\abc.py ]]
> 
> def doFoo():
>     print "hi"
> 
> def doBar():
>     print "bye"
> 
> [[ C:\pycode\mynewdir\__init__.py ]]
> 
> from mynewdir import *

This didn't work, did it?  There is no module
"mynewdir.py" nor a package "mynewdir" in
the "mynewdir" directory, and I don't think import
will search up to find the container.

I suspect you meant that __init__.py says:

from abc import *

> [[ C:\pycode\blah.py ]]
> 
> ????
> 
> what do i import in blah.py so that I can accesss, 
abc.doFoo() ?

Assuming the above, and that you want to access
it as you have written it, that would be:

from mynewdir import abc

Note that in order to use this form, you don't have
to have *anything* in mynewdir/__init__.py --- it can
be an empty file, as long as it exists.

You only need to use an import in __init__.py if you
want it to automatically run when you import the
package.

E.g. if you did:

import mynewdir

You could access your function as:

mynewdir.abc.doFoo

(which requires the import statement in __init__.py).

Cheers,
Terry


--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list