[IPython-dev] RFC on policy: setting object attributes?
Wed Dec 30 23:06:13 CST 2009
Wed, Dec 30, 2009 at 2:02 PM, Gael Varoquaux
> On Wed, Dec 30, 2009 at 02:00:00PM -0800, Fernando Perez wrote:
>> Opinions? For now I'm going to go with putting things in the class as
>> I need them, but I'd like to hear people's thoughts so we have a
>> policy we're happy with and good reasons to choose it.
> I am fully with you.
Thanks; I've added this to the dev guide (in my branch, coming up for
review soon), I'm happy to take further feedback into account if
Attribute declarations for objects
In general, objects should declare in their *class* all attributes the object
is meant to hold throughout its life. While Python allows you to add an
attribute to an instance at any point in time, this makes the code harder to
read and requires methods to constantly use checks with hasattr() or try/except
calls. By declaring all attributes of the object in the class header, there is
a single place one can refer to for understanding the object's data interface,
where comments can explain the role of each variable and when possible,
sensible deafaults can be assigned.
If an attribute is meant to contain a mutable object, it should be set to
``None`` in the class and its mutable value should be set in the object's
constructor. Since class attributes are shared by all instances, failure
to do this can lead to difficult to track bugs. But you should still set
it in the class declaration so the interface specification is complete and
documdented in one place.
A simple example::
# X does..., sensible default given:
x = 1
# y does..., default will be set by constructor
y = None
# z starts as an empty list, must be set in constructor
z = None
def __init__(self, y):
self.y = y
self.z = 
More information about the IPython-dev