check if var is dict
Bruno Desthuilliers
bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Aug 13 06:38:16 EDT 2007
Astan Chee a écrit :
> Hi,
> I have a variable, I want to check if it is a dictionary or a string.
> Is there any better way to do this than I've done. How I did it is by
> doing a .items() and catching a AttributeError that it raises if its not
> a dictionary.
> How do i properly do it?
Checking the presence of one (or more) attributes of the object is so
far the best thing to do. Now wrt/ *how* to check, using hasattr() or
getattr() might be better than a try/except block:
def my_func(some_obj):
if callable(getattr(obj, 'items', None)) \
and callable(getattr(obj, 'keys', None)):
use_obj_as_a_dict(...)
else:
use_obj_as_a_string(...)
Now keep in mind that this may lead to false positives if you don't
carefully choose the attribute(s) to check the presence of...
More information about the Python-list
mailing list