On Apr 6, 2011, at 7:39 AM, pierreth wrote:
> 
> Here are my conclusion on using the "modules" directory.
> 
> What is working:
> 
> - Using local_import avoid collisions of modules or packages that may
> have the same names in other applications.
> - Explicit and implicit relative imports are working well for modules
> located in the "modules" directory.
> 
> What is not working:
> 
> - Absolute imports does not work because "modules" is not in the
> Python path.
> 
> What this mean in practice:
> 
> - Modules located in "modules" can import each other if there are not
> located in a package. This is implicit relative import.
> - local_import is working well with both modules and packages.
> - Modules located in "modules", regardless of if they are or not
> located in a package, can only import other modules located both in a
> package and in "modules" using explicit relative imports. Absolute
> imports only work for modules and packages located in the Python path.
> 
> So if you drop both a module "a" depending on module "b" in "modules",
> they will probably work very well. But if you drop both a package "a"
> depending on package "b" (or a module "b"), it will probably not work.
> Using relative imports in this case is not the norm. Inter packages
> dependencies will not work in "modules". Is this a bug?
> 
> See: http://docs.python.org/tutorial/modules.html#packages
> 
> I suggest to add this message to the web2py book.

It's worth reflecting on why this is the case. 

Ordinarily, in the Python environment, we'd solve this problem by adding our 
local module repository to sys.path from inside the application, which would 
work fine because the edited sys.path is local to the current instance of the 
interpreter. But in a web2py environment, sys.path (and the interpreter) is 
shared among all the applications.

The brute-force solution, I think, is to run separate web2py instances, with 
top-level routing in the external server (Apache, whatever).

I can think of a couple of directions to look for alternatives. One is PEP 302 
(import hooks and such). A simpler approach would be for web2py to rebind 
sys.path to a thread-local variable and add the app-specific modules directory 
to it. If that worked (offhand I can't think why not, but I'm no doubt missing 
something), it'd be pretty simple, as long as it didn't get re-bound later, 
which is a hazard (note that web2py's idiom for adding to sys.path rebinds it).

Going down that road, rather than rebinding sys.path to a thread-local version, 
what if we added a thread-local member to sys.path that pointed to the current 
application's modules directory? That'd be *really* simple, again if I'm not 
missing something.

Reply via email to