473,847 Members | 1,698 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Accessors in Python (getters and setters)

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.

Regards

Jul 10 '06
112 13897
mystilleef wrote:
(snip)
Python doesn't have any philosophy with regards to naming identifiers.
Yes it does.
>
>>But they are in Python and that is the python's philosophy. All attribute or
method not beginning with an '_' *is* API.

Right, and what if I want to change a private API to a public one.
Then you provide a public API on top of the private one.

class MyClass(object) :
def __init__(self, ...):
self._attr = XXX

# seems like we really have enough use
# cases to justify exposing _imp_attr
@apply
def attr():
def fget(self):
return self._attr
def fset(self):
self._attr = attr
return property(**loca ls())
def _method(self, ...):
# code here

# seems like we really have enough use
# cases to justify exposing _imp_method
method = _impmethod

Note that none of this actually breaks encapsulation.
How
does that solve my naming issues.
How could this solve *your* naming issue ? This is totally unrelated.
You choose a bad name for a *public* symbol.
>>And in python the reverse can be true :

The reverse is hardly ever true.
So what are computed attributes ?
90% of public APIs in almost all
languages are methods or functions.
"allmost all languages" lacks computed attributes.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 13 '06 #21

Bruno Desthuilliers wrote:
mystilleef wrote:
Lousy Attribute Name:
self.tmp

Accessors:
set_temporary_b uffer
get_temporary_b uffer

The attribute name I chose, "tmp" sucks.

Well, it's surely not as descriptive as 'temporary_buff er'
I have used that name in
dozens of places spanning over 27000 LOC.

Too bad for you.
Thank you, that was helpful.
>
There's a chance that other
develops might misinterpret exactly what "tmp" does. Plus I don't want
emails from other developers querying me about what "tmp" is/does.
"tmp" is obvious to me, but not necessarily to others.

So why did you name it that way at first ?
What does it matter? There are 10 million and one reasons from given
identifiers bad names.
Now compare that
to the accessors.

But 'tmp' actually *is* an accessor.
I didn't say it wasn't.
>
Not only do they improve readability

Err... do you find:

obj.set_tempora ry_buffer(val)
val = obj.get_tempora ry_buffer()

really more readable than:

obj.temporary_b uffer = val
val = obj.temporary_b uffer
I didn't name the attribute temporary_buffe r, I named it tmp.
>
at the expense
of more code,

Indeed. In both the class and client code.
they actually allow me to change the lousily named
attribute "tmp" to "temporary_buff er" without grepping, seding,
searching, replacing and praying.

You still fail to get the point. You actually choose a crappy name for a
*public* property. It's *exactly* as if, in Java, you had named your
getter/setter 'get_tmp' and 'set_tmp'.
No, it isn't. In Java there's a clear distinction between attributes
and methods.
Sure, if you are dealing with less
than a 1000LOC you can get away with using "tmp" or renaming it easily.
But if you are dealing with a much larger code base and more
developers, issues like this rapidly become a nuisance.

Indeed. But it's *your* responsability to choose good names for the API.
I choose good names for most of my APIs. But there cases when you never
know an attribute will actually be an API before hand.
Yes, it is possible to name crappy accessors too (e.g set_tmp/get_tmp).
or 'tmp'.
But developers tend to pay more attention to given methods/functions
less crappy names, at least when compared to data attributes.

s/developpers/you/
Ha, right! I bet you are perfect developer.
This
stems from the fact that in many languages data attributes aren't
usually part of the API,

Once again, in Python, there is *no* such thing as 'data attributes'.
*All* attributes are *objects* - some of them callable.
I didn't say attributes weren't objects.
as well as the whole OO(Encapsulatio n) blah
blah.

Don't confuse encapsulation with data-hiding.
I don't see the confusion.
>
I know I would not name the accessors set_tmp/get_tmp, because my
philosophy is that methods/functions need to have meaningful names and
state their intended purpose.

That's true for each and every name in a program.
I don't hold data attributes to such
standards

Too bad for you.
Thank you.
and I imagine many developers don't either and least based on
other people's code I've read. Plus there are many occassions when
attributes are not intended to be APIs,

Then mark them as being implementation (ie : prefix them with a single
underscore).
I thought that too was unpythonic.
but eventually become one.
After all most data attributes are created with the purpose of serving
methods.

Nope. You have the class API, and the class implementation. Both made of
both callable and non-callable attributes.
Or objects have state and behavior. Data attributes represent state and
methods represent behavior.
Mystilleef, I do share your pain (really - been here, done that,
etc...), and I understand that grasping Python requires some mental
adjustments when coming from Java and friends (been here, done that,
etc...). But you seriously can't blame the language for your own mistakes.
You don't share my pain. You seem to mock it. I'm not new to Python
either. I've been using it for over 2 years in several capacities. I
only recently decided to use it for a large project.
If you intented 'tmp' to be part of the API, then you're responsible for
the bad naming.
I never intended it to be part of the API. It evolved to be an
important part of the system.
>If you didn't, then you're responsible for breaking the
encapsulation - FWIW, following the convention (single leading
underscore) could have make it clearer to you.
In both cases, you
happily used a bad name in 27 KLOC - so you really had a lot of time and
occasions to notice something wrong with this.
That's nonsense. I only just noticed because I was trying to implement
a plug-in system and I needed to expose an important class. I would not
have considered the issue a problem without this requirement. Except
you are a prophet, you sometimes can't know before hand how certain
classes will end up being used especially if requirements suddenly
change. Saying it's my fault to make yourself feel better about your
favorite language doesn't help solve my problem. I didn't come here to
be berated. I came here to learn the Pythonic way to implementing
accessors. And of course how to deal with issues like the one I have in
medium size to large scale projects. People make mistakes, we deal with
an move on. Sheesh

Jul 13 '06 #22

Marc 'BlackJack' Rintsch wrote:
In <11************ **********@35g2 000cwc.googlegr oups.com>, mystilleef
wrote:
Maric Michaud wrote:
But that's not python philosophy.
Python doesn't have any philosophy with regards to naming identifiers.

But the python community has one. Pythonistas prefer readable source code
so they tend to think about good names. As The Zen of Python says
"Readabilit y counts."
I'm glad I'm in tune with the "python community."
>
But they are in Python and that is the python's philosophy. All attribute or
method not beginning with an '_' *is* API.
Right, and what if I want to change a private API to a public one. How
does that solve my naming issues.

Then you have to change all references to that private attribute. What's
the problem here? As it was private I would expect to find all the
references "nearby" in the same module or class.
Right, but tmp isn't private.
And in python the reverse can be true :
The reverse is hardly ever true. 90% of public APIs in almost all
languages are methods or functions.

Except the ones with properties where ordinary "attributes " may be just
calls in disguise.
Crap! Even in Python too most Public APIs are methods and functions.
Python is not almost all other languages and in Python code you usually
won't find those trivial getters and setters because we have properties if
the access might become a bit more complex in the future.
Ha! I bet you haven't read too many Python codes.
Ciao,
Marc 'BlackJack' Rintsch
Jul 13 '06 #23
Gerhard Fiedler wrote:
On 2006-07-12 06:17:27, mystilleef wrote:

>>But developers tend to pay more attention to given methods/functions
less crappy names, at least when compared to data attributes. This
stems from the fact that in many languages data attributes aren't
usually part of the API, as well as the whole OO(Encapsulatio n) blah
blah.


I'm not sure about which languages you are talking (pretty much all that
allow public methods also allow public attributes), but in general I think
you should get away from the distinction attribute vs method (which doesn't
make much sense in any language)
And even less when one have first-class functions and computed
attributes... In Python, a method is nothing more than a callable attribute.
and start looking at the distinction
public vs private
Since "public" and "private" are now strongly connoted with
"language-inforced access restriction", I'd rather talk of "interface vs
implementation"
(which is what you really are talking about) -- and start
giving the appropriate care to naming public entities, no matter /what/
they are. (Besides, I don't know many coding rules that say that creating
an accessor get/setTemporaryBuf fer that acts on the private member tmp is
good style.)

I'm just starting to get started with Python, but it seems that the leading
underscore marks private entities.
Yes, it means "implementation , don't touch or you're on your own".
So why don't you precede everything with
an underscore that doesn't have a name that fulfills your criteria for a
decent public name -- no matter what kind of entity it is?

It seems you are basically complaining that you used a crappy name in a
public API.
Obviously... And blaming the language for this won't help.
Well... you shouldn't, not in Python, and not in any other
language :) And there's no way around it, not in Python, and not in any
other language, than to rename that entity in the public API. Which can be
a major hassle, close to impossible. There are all kinds of public APIs
with crappy names (using accessors and all :) that got created early on and
never changed. Stuff happens.

Maybe you didn't know about the underscore way to mark private entities.
Maybe this doesn't work as I think it does
If you think that single leading underscores have a special meaning for
the compiler/interpreter, then you got it wrong. It's a convention. Like
using ALL_CAPS for pseudo-constants. Nothing prevents you from accessing
implementation or modifying "constants" - but then you're on your own
and must not complain when something breaks.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 13 '06 #24
"mystilleef " wrote:
Right, and what if I want to change a private API to a public one. How
does that solve my naming issues.
if your code is as muddled as your rhetorics, your only solution might be
to give up programming.

</F>

Jul 13 '06 #25

Bruno Desthuilliers wrote:
mystilleef wrote:
(snip)
Python doesn't have any philosophy with regards to naming identifiers.

Yes it does.
No it doesn't.
>But they are in Python and that is the python's philosophy. All attribute or
method not beginning with an '_' *is* API.
Right, and what if I want to change a private API to a public one.

Then you provide a public API on top of the private one.

class MyClass(object) :
def __init__(self, ...):
self._attr = XXX

# seems like we really have enough use
# cases to justify exposing _imp_attr
@apply
def attr():
def fget(self):
return self._attr
def fset(self):
self._attr = attr
return property(**loca ls())
def _method(self, ...):
# code here

# seems like we really have enough use
# cases to justify exposing _imp_method
method = _impmethod

Note that none of this actually breaks encapsulation.
Ha! Just as bad as getters and setter.
How
does that solve my naming issues.

How could this solve *your* naming issue ? This is totally unrelated.
You choose a bad name for a *public* symbol.
My point exactly! It doesn't solve my problem!
>And in python the reverse can be true :
The reverse is hardly ever true.

So what are computed attributes ?
90% of public APIs in almost all
languages are methods or functions.

"allmost all languages" lacks computed attributes.
*sighs*

Jul 13 '06 #26
Marc 'BlackJack' Rintsch wrote:
In <11************ **********@35g2 000cwc.googlegr oups.com>, mystilleef
wrote:

>>Maric Michaud wrote:
(snip)
>>>But they are in Python and that is the python's philosophy. All attribute or
method not beginning with an '_' *is* API.

Right, and what if I want to change a private API to a public one. How
does that solve my naming issues.


Then you have to change all references to that private attribute.
Not even - cf my answer on this point.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 13 '06 #27

Fredrik Lundh wrote:
"mystilleef " wrote:
Right, and what if I want to change a private API to a public one. How
does that solve my naming issues.

if your code is as muddled as your rhetorics, your only solution might be
to give up programming.

</F>
There's no correlation between rhetorics and programming. That's like
me saying if you are trying to be sarcastic your only solution might be
to give up programming.

Jul 13 '06 #28
mystilleef wrote:
Marc 'BlackJack' Rintsch wrote:
>>In <11************ **********@35g2 000cwc.googlegr oups.com>, mystilleef
wrote:

>>>Maric Michaud wrote:
(snip)
>>>>But they are in Python and that is the python's philosophy. All attribute or
method not beginning with an '_' *is* API.

Right, and what if I want to change a private API to a public one. How
does that solve my naming issues.

Then you have to change all references to that private attribute. What's
the problem here? As it was private I would expect to find all the
references "nearby" in the same module or class.

Right, but tmp isn't private.
Right, but that's your choice. Would you complain about "almost any
other language" if you had to hunt a badly named public method thru 27KLOC ?

(snip)
>>Python is not almost all other languages and in Python code you usually
won't find those trivial getters and setters because we have properties if
the access might become a bit more complex in the future.
Ha! I bet you haven't read too many Python codes.
I have read tens of thousands LOC of Python in the seven past years.
Computed attributes came in with 2.2x IIRC, so there's a lot of 'legacy'
code that uses getters and setters. Porting this code to a
computed-attribute style would break all client code. Having the two
schemes coexisting would make for bloated APIs and
too-many-ways-to-do-it. So we live with this until Py3K. And none of
these considerations contradicts the point that there's no more use for
javaish getters/setters in Python, nor that javaish getters/setters are
not pythonic.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 13 '06 #29

Bruno Desthuilliers wrote:
mystilleef wrote:
Marc 'BlackJack' Rintsch wrote:
>In <11************ **********@35g2 000cwc.googlegr oups.com>, mystilleef
wrote:
Maric Michaud wrote:
(snip)
>>>But they are in Python and that is the python's philosophy. All attribute or
method not beginning with an '_' *is* API.

Right, and what if I want to change a private API to a public one. How
does that solve my naming issues.

Then you have to change all references to that private attribute. What's
the problem here? As it was private I would expect to find all the
references "nearby" in the same module or class.
Right, but tmp isn't private.

Right, but that's your choice. Would you complain about "almost any
other language" if you had to hunt a badly named public method thru 27KLOC ?
Methods are used to perform actions. Data attributes usually aren't. We
are on different planes.
(snip)
>Python is not almost all other languages and in Python code you usually
won't find those trivial getters and setters because we have properties if
the access might become a bit more complex in the future.
Ha! I bet you haven't read too many Python codes.
I have read tens of thousands LOC of Python in the seven past years.
Computed attributes came in with 2.2x IIRC, so there's a lot of 'legacy'
code that uses getters and setters. Porting this code to a
computed-attribute style would break all client code. Having the two
schemes coexisting would make for bloated APIs and
too-many-ways-to-do-it. So we live with this until Py3K. And none of
these considerations contradicts the point that there's no more use for
javaish getters/setters in Python, nor that javaish getters/setters are
not pythonic.
I never made any contradictory points regarding the matter. I wanted to
know the pythonic way of using accessors in Python. That's all. You are
the person making wild assumptions about my queries, programming
background and code.

Jul 13 '06 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
5798
by: Zap | last post by:
Widespread opinion is that public data members are evil, because if you have to change the way the data is stored in your class you have to break the code accessing it, etc. After reading this (also copied below for easier reference): http://groups.google.it/groups?hl=en&lr=&safe=off&selm=6beiuk%24cje%40netlab.cs.rpi.edu&rnum=95 I don't agree anymore.
21
1931
by: Raj | last post by:
Hi, We just executed a project with Python using TG. The feedback was to use more python like programming rather than C style code executed in Python. The feedback is from a Python purist and for some reasons we cannot solicity his help. So we'd like to do is to scrub through the codebase and identify places where the codebase needs improvement, both from styling as well as design. Is there any website that can provide me with...
0
9887
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9730
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10983
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10707
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10341
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7883
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7056
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5911
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4119
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.