1

I have a predicate function that determines whether a dictionary (or in fact any collections.abc.Mapping) has the shnudliwutz characteristic. Non-Mapping objects never have it.

Now I would like to extend the function so that it accepts named tuples (instances of collections.namedtuple-generated classes) as well and treats them like the corresponding dictionary. But how do I recognize a named tuple? The best solution I could find (in Python3) is shown below, but there sure must be a nicer one?

def is_shnudliwutz(mydict):
    if isinstance(mydict, tuple) and isinstance(mydict.__dict__, collections.abc.Mapping):
        mydict = mydict.__dict__  # treat named tuple like its dictionary
    if not isinstance(mydict, collections.abc.Mapping):
        return False
    ...  # now do your work
Lutz Prechelt
  • 36,608
  • 11
  • 63
  • 88
  • I had written up an answer to this, but since it's been closed I'll just note that on Python 2.x, `namedtuple`s do not have a `__dict__` attribute. Both 2.x and 3.x implementations, however, do have a "private" `_asdict()` method that returns a dictionary. You could check for that and call it. – kindall Jun 20 '14 at 15:26

0 Answers0