accessing class attributes

eliben eliben at gmail.com
Thu May 29 15:07:48 EDT 2008


On May 29, 3:08 am, Matimus <mccre... at gmail.com> wrote:
> > I have a game class, and the game has a state. Seeing that Python has
> > no enumeration type, at first I used strings to represent states:
> > "paused", "running", etc. But such a representation has many
> > negatives, so I decided to look at the Enum implementation given here:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486
>
> I frequently use strings in place of enumeration in python. I have
> found it to be very useful. I'm curious about the _many negatives_ you
> have found?
>
> For example, I wrote a module and one of the parameters to a function
> was `mode`. Two of the modes were ALL_MODE and ONE_MODE.
>
> At first I enumerated the modes:
>
> MODES = ALL_MODE, ONE_MODE = 0, 1
>
> And code using the mode tended to look something like this:
>
> from package import module
> module.foo(mode=module.ALL_MODE)
>
> Of course, the following would also work, but isn't self descriptive:
>
> module.foo(mode=0)
>
> Then, after some user feedback I changed it to this:
>
> MODES = ALL_MODE, ONE_MODE = "all one".split()
>
> This maintained backwards compatabilty, but users could use the much
> more concise (but still readable) version:
>
> module.foo(mode="all")
>
> Since then, I have adopted using strings in place of enum types as a
> best practice.
>
> Matt

The problem with naming strings explicitly has to do with type safety.
If you make a mistake in a parameter's name, it won't be detected by
the interpreter and you can run into weird errors later. The other
problem is that all the possible options are not documented in one
convenient place, but you solved it by using a mixed approach of
uppercase "constants" having the values of strings.

Eli



More information about the Python-list mailing list