[mod_python] __import__ error

Graham Dumpleton grahamd at dscpl.com.au
Tue Jun 13 00:22:22 EDT 2006


On 13/06/2006, at 11:34 AM, Detmar Meurers wrote:

> Hi Graham (et al.),
>
> related to where you write:
>
>     When import in mod_python is done, it will not necessarily look
>     in current working directory anyway. You need to add directory
>     to Python PATH explicitly using the directive:
>
>     PythonPath 'sys.path+["/var/www-studio/"]'
>
>     in your Apache configuration for where you are using mod_python.
>
> I was wondering about the motivation for adding this as part of the
> Apache configuration and whether there are alternatives.

There are alternatives, but I only wanted to go into the simplest one
because aspects of other options will/may change when new module
importer is available for use in next major version of mod_python.

> As
> motivation for this question: During development, I have various
> versions of code checked out (from cvs) to different directories, so
> it's rather impractical to add each such directory to the Apache
> configuration.
>
> Instead, I call sys.path.append(dirname(__file__)) in each .py file
> that's in a directory from which I want to import other code (or
> actually sys.path.append(join(dirname(__file__), 'include')) since I
> store other python modules in an include subdirectory).

This is actually not a good idea. This is because if the module doing  
this
is reimported because of autoreload being enabled (default), then the
path gets appended to sys.path again. Thus over time the same directory
could be added many many times to sys.path slowing down module
searches.

> As far as I can tell, this seems to work (i.e., I can then use
> import or apache.import_module to load files from those directories)
> but several replies on this topic only mention the PythonPath
> solution in the apache configuration, which made me wonder whether
> there are downsides to using sys.path.append in the python code for
> this?

If you are using apache.import_module() anyway, don't modify sys.path
at all, instead use the "path" argument to the function. Thus:

   __here__ = os.path.dirname(__file__)
   module = apache.import_module("mymodule", path=[__here__])

It will search those directories without them being added to sys.path.

If the child modules use the "import" statement to import a subsequent
module from the same directory, it will not find it though as  
sys.path has
not been changed to reference that directory. Thus need to use the
apache.import_module() function consistently for your own stuff in that
directory.

BTW, you might want to read:

   http://www.dscpl.com.au/articles/modpython-003.html

which details various module importer problems.

Graham


More information about the Mod_python mailing list