Interesting Problem

alex23 wuwei23 at gmail.com
Thu Jan 21 01:08:29 EST 2010


Victor Subervi wrote:
> I think I finally have an interesting problem for y'all. I need to import a
> script from a lower dir, forcing me to change dirs:

I'm surprised that no one has yet mentioned packages.

Suppose you have the following folder layout and you stick an empty
__init__.py in each subfolder, like so:

    app/
        tools/
            __init__.py
            open.py
            close.py
            extensions/
                __init__.py
                inner.py
                outer.py

Scripts in the 'app' folder can then import from the subfolders using
dotted notation:

  import tools
  from tools import open, close
  import tools.extensions
  from tools.extensions import inner, outer

However, with empty __init__ files, you can't use attribute lookup on
nested modules, so if you started with an 'import tools' any attempts
to reference the contents of the module in the following ways will
fail:

  tools.open
  tools.close
  tools.ext.inner
  tools.ext.outer

To provide this functionality, you need to import the items you want
available in the __init__ of the package they belong to. So by adding
the following:

  tools/__init__.py:      import open, close, ext
  tools/ext/__init__.py:  import inner, outer

You can then do a single 'import tools' and use standard attribute
lookup to access the contents of your subfolders.



More information about the Python-list mailing list