Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isinstance without importing candidates

Tags:

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']

like image 308
Dragon Dave Avatar asked Jun 06 '13 14:06

Dragon Dave


2 Answers

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

like image 60
bwind Avatar answered Oct 12 '22 01:10

bwind


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__]
like image 28
jnns Avatar answered Oct 12 '22 01:10

jnns