[Tutor] Storing information as attributes or in a dictionary

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Sep 18 16:49:08 CEST 2012


On 18 September 2012 15:14, Michiel de Hoon <mjldehoon at yahoo.com> wrote:

> Dear all,
>
> Suppose I have a parser that parses information stored in e.g. an XML
> file. I would like to design a Python class to store the information
> contained in this XML file.
>
> One option is to create a class like this:
>
> class Record(object):
>     pass
>
> and store the information in the XML file as attributes of objects of this
> class, as in
>
> >>> handle = open("myxmlfile.xml")
> >>> record = parse(handle) # returns a Record object
> >>> record.name
> "John Doe"
> >>> record.birthday
> "February 1, 1920"
>
> Alternatively I could subclass the dictionary class:
>
> class Record(dict):
>     pass
>
> and have something like
>
> >>> handle = open("myxmlfile.xml")
> >>> record = parse(handle) # returns a Record object
> >>> record['name']
> "John Doe"
> >>> record['birthday']
> "February 1, 1920"
>
> I can see some advantage to using a dictionary, because it allows me to
> use the same strings as keys in the dictionary as in used in the XML file
> itself. But are there some general guidelines for when to use a
> dictionary-like class, and when to use attributes to store information? In
> particular, are there any situations where there is some advantage in using
> attributes?
>

Some people find attribute access a bit "nicer" when they are using an
object.

Attributes have the disadvantage that they're a bit awkward if they aren't
valid identifiers, where as any string is ok for a dictionary key.

A valid identifier is any string...
1) consisting only of alphanumeric characters (a-z, A-Z, 0-9) and the
underscore (_)
2) that does not begin with a numeric character (0-9).
3) and that is not a Python keyword (is, not, and, def, class, ...).

To see what happens otherwise:

>>> class A(object): pass
...
>>> a = A()
>>> a.class = 'some value'
  File "<stdin>", line 1
    a.class = 'some value'
          ^
SyntaxError: invalid syntax

Also if your objects are instances of a class that has any methods you'll
need to ensure that the method names don't conflict with the XML keys as
well.

Oscar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120918/34054e9b/attachment.html>


More information about the Tutor mailing list