Bug or feature?

Derek Jones dtj at rinconn.com
Fri May 14 10:30:25 EDT 1999


>> > > If this behavior is indeed what is intended, I'm really curious to
>> > > know why.  Why is this confusing (to me at least) behavior considered
>> > > desirable?
>
>The poster had already figured out for himself what was going on. He
>asked "why is it this way?" - and I don't think it's to support class
>data.

Really?  Because class variables are a feature found in other OO
languages.  It doesn't seem like an accident to me.  Has GvR said anything
one way or the other?

>> 2. Sometimes it is useful/necessary to save state or share information
>> among all instances of a certain class.  One way to do that is to 
>> declare a mutable data structure, such as your data1, at the class 
>> level.  Then all instances can modify this shared data, and other 
>> instances will immediately see the updates.  
>
>I have never used this technique. I don't think I've ever seen code
>that does. Module-level globals are (IMHO) generally clearer. For a
>start, if you want mutable data, you more-or-less have to wrap it up
>in a list, and that's confusing.

Do you mean you've never seen Python code that does?  I program an awful
lot of C++, and there are reasons for using it there.  They're called
"static class variables" sometimes, and are variables that are meant to be
associated directly with that class.

Now, if you decide not to define more than one class per module, then yes,
a module-level global is almost the same thing.  Python's approach to
namespaces means that the programmer has to refer to the variable in code
as <module>.<variable> -- unless they've used the "from" statement.  In
that case, it's like C/C++ again, where all global variables are
"flattened" to the same namespace.  But class variables would survive
this; they would also survive what happens when more than one class is
defined in the same module.

>> Perhaps others would like to post some examples of when they've 
>> actually neede the technique in Answer 2 in their Python programs to
>> give you an idea of when you might need this *feature*.
>
>I don't expect there will be many posts to that effect.

I think it comes down to expressing programmer intent.  If you have 2+
classes defined in a module and they need to share some global, that needs
to be a module-level global.  If it only makes sense within that class, it
seems desirable to associate that variable with that class name.

A final note:  static class variables (and methods, especially) make more
sense in a language like C++, where users of a class are normally
prevented from making use of the private data members of that class.  In
Python, the only such protection is by convention, so class statics are
not as *necessary*, but I still say that they can make the code easier to
understand & maintain.

--Derek

-- 
My real email address has only one 'n' in it, for those who care.




More information about the Python-list mailing list