'How to prevent Python class instance variable typo?

A python class function had something like this:

class Widget:
    def __init__(self):
        self.foo_bar = 0

    def fun(self, xyz):
        self.foobar = xyz

A typo. The code for fun() should have referenced self.foo_bar. This took surprisingly long to debug (as the actual functions were more complex).

Is there a way to enforce that class instance variables can only be introduced (declared) in __init__? Python happily created a new class instance variable instead of generating an error. An error would have saved a lot of time.



Solution 1:[1]

If I run pylint on this code, I get the following errors:

test.py:1:0: C0114: Missing module docstring (missing-module-docstring)
test.py:1:0: C0115: Missing class docstring (missing-class-docstring)
test.py:5:4: C0116: Missing function or method docstring (missing-function-docstring)
test.py:6:8: W0201: Attribute 'foobar' defined outside __init__ (attribute-defined-outside-init)
test.py:1:0: R0903: Too few public methods (1/2) (too-few-public-methods)

You can configure pylint to disable the warnings you might not care as much about, e.g. missing-module-docstring, but the one that catches your attribute typo is this one:

test.py:6:8: W0201: Attribute 'foobar' defined outside __init__ (attribute-defined-outside-init)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matyas