Accessors in Python (getters and setters)

Jason tenax.raccoon at gmail.com
Mon Jul 10 11:55:29 EDT 2006


mystilleef wrote:
> I decided to change the name of an attribute. Problem is I've used the
> attribute in several places spanning thousands of lines of code. If I
> had encapsulated the attribute via an accessor, I wouldn't need to do
> an unreliable and tedious search and replace accross several source
> code files to achieve my goal. I could simply change the name of the
> attribute and move on. Well, I'm glad python has properties. It's a
> feature that should be advertised more, especially for large scale
> python development.
>
> Diez B. Roggisch wrote:
> > mystilleef wrote:
> >
> > > Hello,
> > >
> > > What is the Pythonic way of implementing getters and setters. I've
> > > heard
> > > people say the use of accessors is not Pythonic. But why? And what is
> > > the alternative? I refrain from using them because they smell
> > > "Javaish."
> > > But now my code base is expanding and I'm beginning to appreciate the
> > > wisdom behind them. I welcome example code and illustrations.
> >
> > Which wisdom do you mean? The wisdom that a language that has no property
> > mechanism and thus can't intercept setting and getting of instance members
> > needs a bulky convention called JAVA Beans, so that _all_ uses of
> > properties are tunneled through some code, even if only a few percent of
> > these actually need that?
> >
> > Or the wisdom that strangling developers by putting access modifiers with
> > approx. a dozen different rules in place is an annoyance to adult
> > developers to say the least?
> >
> > These are the reasons they are not pythonic. We can intercept property
> > access (see the property descriptor, http://pyref.infogami.com/property),
> > and we trust in developers being able to judge form themselves if messing
> > with internals of code is a good idea or not.
> >
> > Regards,
> >
> > Diez

The property() mechanism gets rid of the need for getters and setters,
as you can invisibly change a member variable into a getter/setter as
needed.  Nothing else needs to know that its using a property and not a
getter/setter.

Nothing like being forced to write getters and setters in C++/Java
before you feel like shooting your source code.  Please don't bring
this code-rage into Python.

To refactor a name in your code, take a look at Bicycle Repair Man
[http://bicyclerepair.sourceforge.net/].  It integrates into Eclipse
via PyDev, and allows you to refactor variable names, class names, and
method names fairly easily.

Good luck!

    --Jason




More information about the Python-list mailing list