[XML-SIG] Extending the xml package

Fred L. Drake, Jr. fdrake@beopen.com
Tue, 1 Aug 2000 23:07:50 -0400 (EDT)

Greg Stein writes:
 > This solution is definitely sub-optimal. Specifically:
 >   sys.modules['xml'].__name__ != 'xml'

  So use this:

	import xml
	if xml.__name__ != "xml":
	    # not the standard library...
	    # is the standard library...

  Setting the object referenced in sys.modules is considered as
legitimate as it gets, and this solution allows all path searching to
be handled by the import machinery rather than the package's __init__
module, and has previously been sanctioned by Guido.  (Note that the
Pmw package does something similar, but I think the object inserted
into sys.modules isn't actually a module object.)  This seems to be
the approach which has the least interference with pluggable import
mechanisms, none of which should have to hack deeply in the handling
of sys.modules.

 > Monkeying around with sys.modules is a clue that you are depending on
 > "magic" in the import and module-handling mechanisms. Given some of the
 > import stuff that people are trying to do (various packaging and archiving
 > and stuff), this is dangerous stuff.
 > Here is my suggestion again (with some merging of your code):
 > _xmlplus.__init__:
 > def _setup_package(version):
 >     import xml   # note: available, but empty
 >     from _xmlplus.parsers import xmlproc, xmlsre
 >     xml.parsers.xmlproc = xmlproc
 >     xml.parsers.xmlsre = xmlsre
 > The above code relies on nothing "magic" in the module or import handling.

  The catch being, as I recall someone pointed out earlier, that this
doesn't support "lazy" importing, but is very imports very
agressively.  This is completely unacceptable.

 > The _xmlplus package can extend the xml package in any way that it sees fit.
 > This solution is much more robust in the fact of "funny" import/packaging
 > scenarios. _xmlplus can override stuff in the xml package and it can extend
 > it. But it doesn't override *everything* which your suggested code does.

  The complete override is intentional.  This also allows the _xmlplus
package to provide bug fixes and handle compatibility issues as
_xmlplus itself evolves.

I wrote:
 > ------------------------------------------------------------
 > if __name__ == "xml":
 >     try:
 >         import _xmlplus
 >     except ImportError:
 >         pass
 >     else:
 >         import sys
 >         sys.modules[__name__] = _xmlplus
 > ------------------------------------------------------------

  This can be simplified, though: the surrounding "if __name__ ..."
test can be removed.  There will be three different __init__.py files:
one from the standard library, one in _xmlplus, and one in an xml
package supplied alongside the _xmlplus package (for Python 1.5.2
installations); the later should include only:

import _xmlplus
import sys

sys.modules[__name__] = _xmlplus


Fred L. Drake, Jr.  <fdrake at beopen.com>
BeOpen PythonLabs Team Member