Is there a consensus on how to check a polymorphic instance?
Robert Brewer
fumanchu at amor.org
Tue Nov 23 01:10:31 EST 2004
Mike Meng wrote:
> Solution #1 is concluded from 'Text Processing in Python', section
> 1.1.3, `Pythonic Polymorphisim', around there, here is an example he
> provides:
>
> def toDOM(xml_src = None):
> from xml.dom import minidom
> if hasattr(xml_src, 'documentElement'):
> return xml_src # it's already a DOM object
> elif hasattr(xml_src, 'read'):
> # it is something that knows how to read data
> return minidom.parseString(xml_src.read())
> elif type(xml_src) in (StringType, UnicodeType):
> # it is a filename of an XML document
> xml = open(xml_src).read()
> return minidom.parseString(xml)
> else:
> raise ValueError, "Must be initialized with " + \
> "filename, file-like object, or DOM object"
>
> What's your opinion?
My name isn't Dan, but IMO hasattr works fine here. The second case
('read') is in one sense looking before leaping. The only change I would
make would be to replace "type(xml_src) in (StringType, UnicodeType)"
with "isinstance(xml_src, basestring)" in recent versions of Python
(2.2+ I think?). A die-hard no-type-checks-for-me fanatic would probably
write something like:
def toDOM(xml_src = None):
from xml.dom import minidom
if hasattr(xml_src, 'documentElement'):
return xml_src # it's already a DOM object
if not hasattr(xml_src, 'read'):
try:
# it is a filename of an XML document
xml_src = open(xml_src)
except (IOError, OSError):
raise ValueError, "Must be initialized with " + \
"filename, file-like object, or DOM object"
return minidom.parseString(xml_src.read())
I don't have a problem with either approach.
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
More information about the Python-list
mailing list