472,147 Members | 1,256 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,147 software developers and data experts.

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 1395
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
reply views Thread by Saiars | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.