Ian C.
Ian C.

Reputation: 3963

How do I resolve namespace conflicts in my Python packages with standard library package names?

I am developing a package with the following structure on disk:

foo/
   __init__.py
   xml.py
   bar.py
   moo.py

The xml.py package provides a class that does some custom XML parsing and translation for the other package components using a SAX stream parser. So it has in it:

import xml.sax
import xml.sax.handler

But when I go to use foo.xml in an application I get:

Traceback (most recent call last):
  File "testxmlparser.py", line 15, in <module>
    import foo.xml
  File "~/code/foo/xml.py", line 39, in <module>
    import xml.sax
ImportError: No module named sax

I appear to have a namespace conflict. If I rename xml.py to something else like xmlparser.py everything works as expected. But this feels like the wrong thing to do. I feel like I'm missing something fundamental about package names and resolution in Python here.

Is there a proper way to make this work that doesn't involve me renaming the foo/xml.py file? Or is that really the only solution to the conflicting names?

Edit: The "avoid naming things the same as standard Python modules" seems...well..a mineshaft to me. That's a moving target, the standard module set, that's bound to change and grow over time. So unless you get really creative with your names the rename-things-until-you-find-something-that-doesn't-conflict solutions seems poor to me. Besides, I've got it in a unique package name with foo already (I'm not using foo, but something that is definitely unique), shouldn't that be enough?

Upvotes: 16

Views: 15328

Answers (1)

Roshan Mathews
Roshan Mathews

Reputation: 5898

As mentioned over here, use

from __future__ import absolute_import

and use relative imports if needed.

Upvotes: 15

Related Questions