Python – How to stop theself overwriting member variables with ‘new’ ones

coding-styledevelopment-processlanguage-agnosticpython

The bulk of my programming experience has been with C++ and (shudder) FORTRAN (I'm a scientist not a programmer as such, but I do my best). I've recently started using python extensively and find it great. However, I just spent a frustrating few hours tracking down a bug that turned out to be caused by me creating a new object member in a function, i.e.

def some_func(self):
    self.some_info = list()

but, I had already created elsewhere the member some_info for this object for a different purpose, so bad things obviously happened later on, but it was tricky to track back to here.

Now obviously in a language like C++ this is impossible to do, since you can't just create object members on the fly. Because I'm used to the language taking care of this, I don't have a well developed procedural discipline to prevent me abusing the freedom that python (and other dynamically typed languages) provides.

So what is the best way to prevent this kind of mistake when using languages like python?

Best Answer

This may be a somewhat trivial advice, but try not to create attributes outside of __init__ method (especially not outside the class's methods), unless you really need to. pylint catches this, among many other things.

Of course, there is still a possibility of reassigning an existing attribute to something else entirely, but at least you will have a single place where you can see all the attributes at once. Also this will ensure that right after the construction your object is valid and does not require calls to any other internal state-changing methods.

Related Topic