Archive
Posts Tagged ‘instance of’
Determine which class an object belongs to
January 20, 2012
Leave a comment
Problem
In a unit test, I wanted to verify that a function returns a cookielib.LWPCookieJar object. How to do that? In more general: how to figure out the type of an object?
Solution
First I tried to figure out the object’s type with type(obj) but it was “<type 'instance'>“.
Then, obj.__class__ .__name__ told me that obj is an ‘LWPCookieJar’. Better.
Finally, here is how I did the unit test:
assert isinstance(obj, cookielib.LWPCookieJar)
Note however that explicit typechecking is often discouraged in favor of duck typing.
Credits
Thanks also to Chris on the Python mailing list.
Categories: python
class name of an instance, instance of, object type, py.test
