Class or Dictionary?

John Nagle nagle at animats.com
Sat Feb 12 03:22:59 EST 2011


On 2/11/2011 6:56 AM, Martin De Kauwe wrote:
> Hi,
>
> I have a series of parameter values which i need to pass throughout my
> code (>100), in C I would use a structure for example. However in
> python it is not clear to me if it would be better to use a dictionary
> or build a class object? Personally I think accessing the values is
> neater (visually) with an object rather than a dictionary, e.g.
>
> x = params['price_of_cats'] * params['price_of_elephants']
>
> vs.
>
> x = params.price_of_cats * params.price_of_elephants

    Don't use a class as a dictionary.  It causes various forms
of grief.  A dictionary will accept any string as a key, and
has no reserved values.   That's not true of class attributes.
There are already many names in a class's namespace, including
any functions of the class.  Attribute syntax is restricted -
there are some characters you can't use.  Unicode attributes
don't work right prior to Python 3.  If the names are coming
in from outside the program, there's a potential security
hole if someone can inject names beginning with "__" and
mess with the internal data structures of the class.
And, of course, you can't use a name that's a reserved
word in Python.

    (This last is forever causing grief in programs that
parse HTML and try to use Python class attributes to
represent HTML attributes.  "class" is a common HTML
attribute but a reserved word in Python.  So such parsers
have to have a special case for reserved words.  Ugly.)

    In Javascript, classes are simply dictionaries, but Python
is not Javascript.  If you want a dictionary, use a "dict".

				John Nagle



More information about the Python-list mailing list