Ali SH
Ali SH

Reputation: 423

Python-How do I find if a variable is a particular class?

I'm writing a script in python3. I have a variable named r my code is like this:

if type(r) == 'twx.botapi.botapi.Error':
     print('Error!')
else:
     print('success!')

When i use type(r) i get this:

<class 'twx.botapi.botapi.Error'>
or
<class 'twx.botapi.botapi.Message'>

I tried using these too but i got no answer:

if type(r) == <class 'twx.botapi.botapi.Error'>:
     print('Error!')
else:
     print('success!')

How can I find if the class type is a kind of error or message?

Upvotes: 1

Views: 158

Answers (1)

Eugene Yarmash
Eugene Yarmash

Reputation: 149823

Depending on whether the variable points to an instance of a class or the class object itself you can use isinstance or issubclass, e.g.

from twx.botapi.botapi import Error, Message

if issubclass(r, Error):
    print('Error!')
else:
    print('success!')

Both functions accept a tuple of objects for the second parameter.

Upvotes: 2

Related Questions