469,332 Members | 6,612 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,332 developers. It's quick & easy.

check if var is dict

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?
Thanks
Astan
Aug 13 '07 #1
1 1333
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...
Aug 13 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

9 posts views Thread by Robin Cull | last post: by
2 posts views Thread by GrelEns | last post: by
15 posts views Thread by Cruella DeVille | last post: by
15 posts views Thread by George Sakkis | last post: by
5 posts views Thread by micklee74 | last post: by
5 posts views Thread by consternation | last post: by
12 posts views Thread by jeremito | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
reply views Thread by Marylou17 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.