Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ?

Timothy Grant timothy.grant at gmail.com
Thu Sep 4 19:15:02 CEST 2008


On Thu, Sep 4, 2008 at 4:09 AM, Marco Bizzarri <marco.bizzarri at gmail.com> wrote:
> Sorry... pressed enter but really didn't want to.
>
> As I said, let's say I have a class
>
> class A:
>    def __init__(self):
>         self.x = None
>
>
>
> Python makes the decision to allow the developers to directly access
> the attribute "x",  so that they can directly write: "a.x = 1", or
> whatever; this has for me the unfortunate side effect that if I write,
> for example "a.y = 1", when I really wanted to write "a.x = 1" no one
> cares about it, and I'm unable to spot this error until later.
>
> Of course, I know that while I'm fresh, I've a good knowledge of the
> code, and anything else, I will be able to avoid such stupid errors;
> however, I'm afraid of the times when I'm tired, when I have to put my
> hands on the code of someone else, and so on.
>
> Please, understand that I'm not stating that python is wrong... after
> all, if it is wrong, I can move to a language like Java, which has a
> different approach on it. I'm really very interested in reading past
> discussion on it, if they are available.
>
> Regards
> Marco

I think the most obvious solution to the problem is effective unit
tests. If you type "a.y =1" and have a test that asserts a.x == 1 then
you would quite quickly discover that you made a typo.


-- 
Stand Fast,
tjg. [Timothy Grant]



More information about the Python-list mailing list