converting dict to object

John Machin sjmachin at lexicon.net
Sat Dec 2 15:16:24 EST 2006


Neil Cerutti wrote:
> On 2006-12-02, Michel Claveau <mcPas.De.Spam at mclaveauPas.De.Spam.com> wrote:
> > Hi!
> >
> > Yes.
> >
> > But...
> >
> > Try:    d = {'a': 1, 'b': 2, 'def': 123}
> >
> > Ok, I go out...
>
> How to convert a list of strings into a list of integers:
>
>  a = ['82', '4', '16']
>
>  ai = [int(i) for i in a]
>
> Yes.
>
> But...
>
> Try:  a = ['82', '4', '16', 'foo']
>
> Ok, I go out...


Michel was making (part of) a valid point: dictionaries have more
flexibility in choice of keys than objects have in attribute names.
More completely:

Suppose d.keys() produces ["one", "def", "foo bar", 3, "3"]

o.one is OK.

o.def is not OK ["def" is a keyword] but getattr(o, "def") still works.

o.foo bar is not OK ["foo bar" is not a valid identifier] but
getattr(o, "foo bar") still works.

o.3 is not OK ["3" is not a valid identifier] but getattr(o, "3") still
works.

getattr(o, 3) doesn't work [3 is not a string]; you would have to do
o.__dict__[3] to access the value -- no advantage over keeping it in a
dict.

The OP might consider adding code to the __init__ method to check for
cases where the dictionary key is not a string containing a valid
Python identifier (not a keyword).

Note: I have done a reasonable number of exercises that involved taking
a database table definition or a flat file record definition or the
headings in an XLS worksheet or CSV file and ending up with names for
attributes of Python objects. Various heuristics are necessary of
course to get valid identifers without duplicates, but I've never been
bitten by the keyword problem. I'll have to confess that I wasn't aware
of the problem until the 3rd reading of Michel's message :-)

Any experiences of keyword-bite?

Observation: the keyword module's iskeyword() function gives an easy
check. If one is supporting multiple versions of Python, a more
complicated (overkill?) approach might be desirable: use the latest
version of Python to generate a source file containing the latest
keywords from keyword.kwlist.

Cheers,
John




More information about the Python-list mailing list