check if var is dict
Lawrence Oluyede
raims at dot.com
Mon Aug 13 06:20:16 EDT 2007
Astan Chee <stanc at al.com.au> wrote:
> 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?
One way is:
In [6]: isinstance(d, dict)
Out[6]: True
In [7]: isinstance("ciao", basestring)
Out[7]: True
This way you won't catch custom classes implementing dict or basestring
"protocols". In order to do that you can check if it implements the
right methods or treat the object as a dict or a string. It depends on
what you're trying to achieve.
--
Lawrence, oluyede.org - neropercaso.it
"It is difficult to get a man to understand
something when his salary depends on not
understanding it" - Upton Sinclair
More information about the Python-list
mailing list