Python’s hasattr on list values of dictionaries always returns false?

hasattr does not test for members of a dictionary. Use the in operator instead, or the .has_key method:

>>> example = dict(foo='bar')
>>> 'foo' in example
True
>>> example.has_key('foo')
True
>>> 'baz' in example
False

But note that dict.has_key() has been deprecated, is recommended against by the PEP 8 style guide and has been removed altogether in Python 3.

Incidentally, you’ll run into problems by using a mutable class variable:

>>> class example(object):
...     foo = dict()
...
>>> A = example()
>>> B = example()
>>> A.foo['bar'] = 'baz'
>>> B.foo
{'bar': 'baz'}

Initialize it in your __init__ instead:

class State(object):
    info = None

    def __init__(self):
        self.info = {}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)