Home > python > Determine which class an object belongs to

Determine which class an object belongs to

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.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: