[newbie] conditional imports

Peter Otten __peter__ at web.de
Thu May 27 11:27:32 EDT 2004


vincent Salaun wrote:

> - i've written a python xml parser using minidom
> - i've written a Jython xml parser using java dom classes - because
> minidom doesn't work with jython :( -
>  
> Only one generic parser would have been the best solution because it
> will be used by a Java application on one side and by a C++ application
> on the other side but i've failed to find a python xml lib working both
> in python and jython ....
> 
> So, now i'd like to put these 2 modules together as much as possible, to
> finally have only one, if possible...
> To do that, i thought using python shortcuts (actually, the content of
> these 2 modules is quite similar, only method names change)
>  
> Here is my idea:
> 
> #############################################################
>   #module myBothJavaAndPyParser :
>   
>   #if the module is used by the Java app ::
>   from javax.xml.parsers import DocumentBuilder, DocumentBuilderFactory
>   from org.w3c.dom import *
>   
>   factory=DocumentBuilderFactory.newInstance()
>   builder = factory.newDocumentBuilder()
>   parseString=self.builder.parse
>   
>   #else:
>   from xml.dom import minidom,Node
>   parseString=minidom.parseString
>   
>   class myParser:
>      def __init__(self):
>         #...
>   
>      def parse(self,toParse):
>         return parseString(toParse)
> 
>      .....
> #############################################################
> 
> But when i instanciate this class, i don't know how to do to know which
> imports and aliases must be done ... i tried to put the imports in the
> __init__ (and using a boolean) but then i can't access to aliases
> Any suggestions ?

Make a wrapper module that tries to import the Jython/CPython-specific
stuff:

try:
   from preferred_implementation import factory, builder, parseString
except ImportError:
   from fallback_implementation import factory, builder, parseString
  
# code shared by both implementations

> And i have another problem concerning shortcuts : how to make a shortcut
> on an attribute ?
> For example :
> Using java, for a Node, we have the getParentNode() method :
> myNode.getParentNode()
> In python, it's an attribute : myNode.parentNode
>  
> How to do to make a shortcut in this specific case ?
>  
> And if a make the shortcut in another way :
> #if used by Java :
> # imports ...
> parentNode=Node.getParentNode
>  
> But now, i will uses this syntax : myNode.parentNode() .... and it won't
> work anymore using python imports ....

In the CPython implementation code (untested):

import xml.dom.minidom

def getParentNode(self):
    return self.parentNode

xml.dom.minidom.Node.getParentNode = getParentNode

Then you should always be able to use myNode.getParentNode() in your client
code. This is a hack, of course. The clean way would be to subclass Node,
but that is tedious...

Peter




More information about the Python-list mailing list