isinstance without importing candidates

We have a function which takes a variety of different types of input: a function, a string, a compiled regular expression, a Hamcrest Matcher, and filters a list appropriately based on the type of the input.

We're currently using isinstance(our_filter, hamcrest.matcher.Matcher), but this requires us to require Hamcrest to be installed.

We're considering using string matches on inspect.getmro(type(POSSIBLE_MATCHER)); but this feels unclean. There might also be options with try/except around the import statement.

What's the best approach?


With help from @dblslash, this is the best I've got so far:

[x.__module__+"."+x.__name__ for x in inspect.getmro(type(POSSIBLE_MATCHER))] ['hamcrest.core.core.isequal.IsEqual', 'hamcrest.core.base_matcher.BaseMatcher', 'hamcrest.core.matcher.Matcher', 'hamcrest.core.selfdescribing.SelfDescribing', '__builtin__.object']


Using type(POSSIBLE_MATCHER).__name__ is IMHO a fairly elegant solution for type checking without having to import the module.


If you want to cater for inheritance, using type(POSSIBLE_MATCHER).__name__ will not cut it. You could then check against all types in the inheritance chain:

class_string in [t.__name__ for t in type(POSSIBLE_MATCHER).__mro__]