Reputation: 3538
I have an object that I'm passing to a queue to write to a database. I need to perform some logic checks to handle errors:
How can I check to see which model that object is?
c = Candidate(....)
type(c)
<class 'models.Candidate'>
is there anyway I can access Candidates
in an if
statement?
if type(c)... == 'Candidate':
I realize I can just do:
if type(c) == <class 'models.Candidate'>
but didn't know if there was a cleaner way
Upvotes: 1
Views: 2761
Reputation: 1261
If you want to check type of object,,, You can do like this,,,
class Foo:
pass
f = Foo()
print(isinstance(f, Foo)) # True
print(type(f) is Foo) # True (also use == possible)
print(f.__class__ is Foo) # True (also use == possible)
isinstance(obj, type) # this works also on subclasses.
class Boo(Foo):
pass
b = Boo()
isinstance(b, Foo) # True
Upvotes: 0
Reputation: 2279
There are two ways :
1) - By class name
def get_class_name(variable)
return type(variable).__class__.__name__
var = "Hello"
if get_class_name(var) == 'str':
...
2) - By using isinstance
var = "Hello"
if isinstance(var, str):
....
Upvotes: 1
Reputation: 2818
How about isinstance?
if isinstance(c, models.Candidate):
This will return True
if c
is an instance of models.Candidate
or an instance of a subclass.
You'll occasionally see functions that check to see what types they've received, such as:
if isinstance(arg1, str):
or
if isinstance(arg1, list):
Upvotes: 1