Alex Rivera | Logout

Wondering whether I should just bail on using properties in python

Asked 2010-10-26T08:26:09.377
11

I have been trying to use properties instead of specific setters and getters in my app. They seem more pythonic and generally make my code more readable.

More readable except for one issue: Typos.

consider the following simple example (note, my properties actually do some processing even though the examples here just set or return a simple variable)

class GotNoClass(object):

    def __init__(self):
        object.__init__(self)
        self.__a = None

    def __set_a(self, a):
        self.__a = a

    def __get_a(self):
        return self.__a

    paramName = property(__get_a, __set_a)


if __name__ == "__main__":
    classy = GotNoClass()

    classy.paramName = 100
    print classy.paramName

    classy.paranName = 200
    print classy.paramName

    #oops! Typo above! as seen by this line:
    print classy.paranName

The output, as anyone who reads a little closely will see, is:

100
100
200

Oops. Shouldn't have been except for the fact that I made a typo - I wrote paranName (two n's) instead of paramName.

This is easy to debug in this simple example, but it has been hurting me in my larger project. Since python happily creates a new variable when I accidentally meant to use a property, I get subtle errors in my code. Errors that I am finding hard to track down at times. Even worse, I once used the same typo twice (once as I was setting and later once as I was getting) so my code appeared to be working but much later, when a different branch of code finally tried to access this property (correctly) I got the wrong value - but it took me several days before I realized that my results were just a bit off.

Now that I know that this is an issue, I am spending more time closely reading my code, but ideally I would have a way to catch this situation automatically - if I miss just one I can introduce an error that does not show up until a fair bit of time has p

Edit
Report

1 Answer

2

Depending on how your code works, you could try using slots. You'll get an AttributeError exception thrown when you try to assign something that's not in slots then, which will make such typo's more obvious.

answered 2010-10-26T11:06:31.527

Your Answer