Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Global dictionary or class variables

1 view
Skip to first unread message

Mr.SpOOn

unread,
Oct 24, 2008, 4:44:38 PM10/24/08
to pytho...@python.org
Hi,
in an application I have to use some variables with fixed valuse.

For example, I'm working with musical notes, so I have a global
dictionary like this:

natural_notes = {'C': 0, 'D': 2, 'E': 4 ....}

This actually works fine. I was just thinking if it wasn't better to
use class variables.

Since I have a class Note, I could write:

class Note:
C = 0
D = 2
...

Which style maybe better? Are both bad practices?

Chris Rebert

unread,
Oct 24, 2008, 6:17:01 PM10/24/08
to Mr. SpOOn, pytho...@python.org

Depends. Does your program use the note values as named constants, or
does it lookup the values dynamically based on the note name?
If the former, then the class is marginally better, though putting the
assignments in a (possibly separate) module would probably be best. If
the latter, than the dictionary is fine.

Cheers,
Chris
--
Follow the path of the Iguana...
http://rebertia.com

> --
> http://mail.python.org/mailman/listinfo/python-list
>

Matimus

unread,
Oct 24, 2008, 7:53:55 PM10/24/08
to

It really depends on how you plan to use them. I might use a
dictionary if I'm likely be handling the notes as characters. If they
are just constants that I plan to use in my program, I would probably
just define a set of global names. The best practice I have found is a
combination.

NOTES = C,D,E,F,G,A,B = "CDEFGAB"
note_2_step = dict(C=0, D=2, E=4, F=5, G=7, A=9, B=11)

This allows you to do both. There are schemes where you might want to
use a class, but without more information it doesn't really seem
necessary. Globals are frowned upon, but constant tend to be just
fine.

Matt

Message has been deleted

Fuzzyman

unread,
Oct 25, 2008, 7:56:09 AM10/25/08
to

I would *probably* find 'Note.C' more natural to use than
"natural_notes['C']".

Michael Foord

--
http://www.ironpythoninaction.com/

Arnaud Delobelle

unread,
Oct 26, 2008, 9:06:15 AM10/26/08
to

You can also put them in a module:

notes.py
========

C = 0
D = 2

....

Then you can:

import notes
print notes.F - notes.C

or

from notes import *

print F - C

If your application consists of several files this may be a good idea.

--
Arnaud

0 new messages