16

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Ian C.
  • 3,783
  • 2
  • 24
  • 33

1 Answers1

15

As mentioned over here, use

from __future__ import absolute_import

and use relative imports if needed.

Community
  • 1
  • 1
Roshan Mathews
  • 5,788
  • 2
  • 26
  • 36
  • 2
    The problem is `xml.sax` isn't in *my* package. So a relative import of it doesn't work. That's actually why it's failing for me right now. Python expects `xml.sax` to be relative to my `foo.xml` package, but it's not. – Ian C. Sep 14 '11 at 15:46