Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 294
Ian C. Avatar asked Sep 14 '11 15:09

Ian C.


1 Answers

As mentioned over here, use

from __future__ import absolute_import

and use relative imports if needed.

like image 88
Roshan Mathews Avatar answered Oct 17 '22 04:10

Roshan Mathews