package module import name clash with global package

Alex Martelli aleaxit at yahoo.com
Sat Sep 11 09:19:49 EDT 2004


George P <georgeplex at yahoo.com> wrote:
   ...
> Not all that simple. Let's say I give my submodule some fairly generic
> name like utils. I would think that was fine because my module is
> really mypkg.utils. But then someone out in the rest of the python
> universe creates a package called utils and that eventually becomes
> standard and gets installed on all systems. Then if I wanted to access
> it within my module, I would have a problem.

Right: in this case, in the release of your module where you suddenly
want to use a module of the same name from elsewhere, you have to take a
little more care than just adding an 'import utils'.  But there's no
guessing involved: it was your "who could guess" that made no sense.

Your module mypkg.utils which wants to import a module named simply
utils must carefully do something like:

import sys, imp

utils = sys.modules.get('utils')
if not utils: utils = imp.load_module('utils',*imp.find_module('utils'))

> The problem is easily overcome in my code - all I'd have to do is to

Sure, see above.

> rename my module to myutils or something, but if any other code has
> been written that relied on my package and imported mypkg.util, they'd
> suddenly stop working with the new release that has the module renamed
> to mypkg.myutil.

If you change the published interface of your package, yup, you'll break
client code relying on the previous version of the interface.  If
everybody used the preferred form "from mypkg import utils" you'd have
no trouble (just add 'import myutils as utils' to mypkg/__init__.py) but
if they use the popular form "import mypkg.utils" you'd break their
code.  Which is why, to avoid risking that, I'd suggest the imp solution
sketched above, rather than running the risk of changing your own
published interface.


> I'm not saying that these aren't insurmountable problems, I'm just
> looking for a better solution. In C++, I would be able to refer to the
> global utils in my code as ::utils, and there would be no more
> problems. Does anyone know of a similar workaround in python?

Yep, http://www.python.org/peps/pep-0328.html -- but it looks like only
the multiline-import part of PEP 328 is going to make it into Python
2.4, unless I've missed something, not the absolute and relative imports
which are presumably what you're looking for.


Alex
 



More information about the Python-list mailing list