Reputation: 21056
Problem: I have to check that the a returned value is a Python dictionary.
Q1. Which of these options is the proper way to do this?
type(x) == dict
type(x) == type(dict)
isinstance(d, dict)
Then there are the other variants using is
operator instead of ==
.
Q2. Many people say that checking the type of an object is generally a bad practice, but regarding to my initial problem, do I have any other choice?
Upvotes: 3
Views: 6494
Reputation: 96258
Rely on behaviour, not on actual type (see other answers).
Lot of objects can act like dictionaries, you don't want to force users of your function/API to use plain dicts, right?
On the pragmatic side:
>>> type({})
<type 'dict'>
>>> dict
<type 'dict'>
>>> type(dict)
<type 'type'>
>>> isinstance({}, dict)
True
>>> isinstance("", dict)
False
Upvotes: 2
Reputation: 391820
Q1. Which of these options is the proper way to do this?
Don't waste time on type checking.
It's error-prone because it's based on assumptions.
Q2. ... do I have any other choice?
Yes do this.
try:
x.the_dict_operation()
except TypeError:
# x was not the expected type for the operation
raise # or whatever.
In most cases, this amounts to "do nothing".
Just write the code. If "somehow" a malicious sociopath uses the wrong type, it will just crash like it's supposed to.
Upvotes: 8
Reputation: 129754
Check for __getitem__
rather than verifying the type. If you really want to type-check, any is fine (well, except type(x) == type(dict)
, that will never be true for a dict
instance). isinstance
is probably the most standard way to do it.
Upvotes: 1