By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,932 Members | 1,944 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,932 IT Pros & Developers. It's quick & easy.

check if var is dict

P: n/a
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
Share this Question
Share on Google+
1 Reply


P: n/a
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.