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