Class-level variables - a scoping issue
jjposner at optimum.net
Mon Oct 11 16:43:04 CEST 2010
On 10/10/2010 7:02 PM, Steven D'Aprano wrote:
> On Sun, 10 Oct 2010 18:14:33 -0400, John Posner wrote:
>> Class attributes are often used as "class constants", so how about
>> naming them with UPPERCASE names, like other constants? When you choose
>> to override one of these constants, like this:
>> self.EGGS = 4
> Er what?
> If self.EGGS is meant as a constant, you shouldn't be re-assigning to it
That's why I prefaced my suggestion with, "I'm not sure I like this myself".
> Apart from the ugliness of the attribute name, this does not differ in
> the slightest from the current behaviour. How could it? Merely changing
> the attribute name "eggs" to "NAME" can't change the behaviour.
Right. As I said the beginning of my message, I was proposing a "naming
convention" only, not new functionality. The purpose of my example was
to show how the naming convention would look in practice, not to
demonstrate how new functionality would work.
> Since nothing has changed, what's the point? What exactly is the
> surprising behaviour that you are trying to flag?
No surprising behavior, just a surprising look:
self.EGGS = ...
... which might remind the programmer what's going on -- the redefining
of a "constant". This was just a suggestion; I hoped it might be helpful
to the OP (or might suggest another, better approach to him). But
perhaps he'll react to this suggestion, as Steven did, with "you
shouldn't be re-assigning to it *ever*".
In my own (hobbyist, not professional) Python programs, I sometimes use
ALL-CAPS names for parameters related to the size of the display screen.
These parameters sort of "feel" constant, but they're not, given the
multiplicity of screens and users' ability to adjust screen resolution.
More information about the Python-list