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']
if str(data.__class__) == '<class 'somemodule.someclass'>:
.... I would not use try/catch because it requires importing the module at the first use, which can in some cases cause annoying delay and of course takes memory if you then finally find that you actually do not need the imported module because the input was of different type. – Hercule