import statement - package visibility problem
Paul Clinch
pclinch at internet-glue.co.uk
Fri Apr 8 11:19:18 EDT 2005
Laszlo,
...
> Importing from a not package related source code is not a problem,
> really. My problem is about importing inside a package.
>
> Lib/Server/Db/__init__.py __can__ import Lib/Server/Db/Adapters usign
> relative paths, but
>
> Lib/Server/Db/Adapters/PostgreSQLConnection.py __cannot__ import from
> Lib/Server/Db using relative paths
>
> Of course I can do the latter import using absolute paths but that is
> something I would like to avoid. In other words:
> it is possible to import using relative lib paths only in one direction.
> Why is that? Why can't I import something
> "from the containing package"?
>
Yes it might be convenient for what you want to do, but importing from
containing package means traversing up the directory structure from
importing module.
> >Or you can define any rules for mapping files and directories to the name space
> >you desire.
> >
> >
> How to do that? By hacking?
Well, yes, Python hacking. See the imp module for interesting
functions such as load_module:-
import imp
filename = 'Lib2/Server/Db/DatabaseConnection.py'
connection = load_module( 'connection', open(filename),
filename,('.py', 'U', 1) )
There is a load_package function not documented, I haven't attempted
to use it, but you could read the source (import.c).
You could also look at the builtin function __import__.
Lastly you could look at the new import hooks (PEP 302) in the sys
module, implemented in 2.3, where you define a find_module that
returns a loader object.
Regards, Paul Clinch
More information about the Python-list
mailing list