__init__.py, __path__ and packaging

Scott David Daniels scott.daniels at acm.org
Wed May 3 19:01:54 EDT 2006


Sandro Dentella wrote:
> The structure of my package:
> 
> python/
> `-- dbg/
>    |-- __init__.py
>    `-- lib
>        |-- __init__.py
>        |-- debug.py
>        `-- gtk_dbg.py
> 
> my sys.path includes 'python' and I wanted that the content of debug.py was
> simply included by: 'import dbg', so I wrote dbg/__init__.py as follows:
> 
>     import os
>     Dir = os.path.dirname(__file__)
>     __path__ = [os.path.join(Dir, 'lib')]
>     from debug import *

What you probably want in python/dbg/__init__.py to get values is:

     from dbg.lib.debug import *

> BUT, if I set some variables they are not correctly seen:
>     import dbg
>     dbg.DBG = 1
> function test included in debug.py raises NameError:
>     def test():
>         print DBG
> NameError: global name 'DBG' is not defined`
> 
> What's happening? DBG seems to be set, as shown by dir(dbg)... any hints?
You misunderstand modules and python variables.  Each module has a
dictionary associating the names of its globals and their current
values.  After:
     import dbg.lib.debug, dbg.lib.gtk_dbg
you have four modules:
     dbg             # Corresponds to python/dbg/__init__.py
     dbg.lib         # Corresponds to python/dbg/lib/__init__.py
     dbg.lib.debug   # Corresponds to python/dbg/lib/debug.py
     dbg.lib.gtk_dbg # Corresponds to python/dbg/lib/gtk_dbg.py
Each has its own globals.
after:
     dbg.DBG = 1
the dbg module's global dictionary contains an entry mapping 'DBG' to 1
after:
     dbg.DBG = 1+2
the dbg module's global dictionary contains an entry mapping 'DBG' to 3

In no case will an assignment to a global in dbg cause an assignment to
anything in dbg.lib.debug.  The "from dbg.lib.debug import *" statement
can be seen as a module import followed by a fancy multiple assignment,
where module dbg.lib.debug is first imported, then its globals are
assigned to globals of the same names in module dbg.

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list