views:

78

answers:

1

Say you have a public method in Python whose primary purpose is to retrieve the value of an underlying data attribute (i.e. internal backing store). The method may have lazy evaluation logic, etc. A property is an example of such a method.

Then it is natural to use the same name for the method and data attribute, except for an underscore prefix for the data attribute. For example--

class C(object):
def __init__(self):
    self._x = None

@property
def x(self):
    """I'm the 'x' property."""
    return self._x

(from Python's "property" documentation)

But what are some preferred conventions if the method is for internal use and so is itself prefixed with an underscore? Prefixing the backing store with two leading underscores would invoke name mangling and so is not ideal.

Two possibilities might be--

def _get_x(self):
    return self._x

def _x(self):
    return self._x_

Python style says the second (appending an underscore), though, should only be used to avoid conflicts with reserved keywords.

+1  A: 

Why would you make it a property if it is for internal use? If it's for internal use, just access the attribute directly.

But then you would still use one underscore, but call it something else. But again, the whole point of making it a property is lost in this case.

Lennart Regebro
You would want to make it a property if it needs to execute logic, for example lazy evaluation.
Chris J.
And then you can call that method directly, when it's internal.
Lennart Regebro
-1 because this isn't an answer, though I misread the question initially and so gave you the wrong answer to your question. @Chris J has a good answer.
Omnifarious
Don't mess with Lennart folks.
Hamish Grubijan
It is an answer.
Lennart Regebro
@Hamish: Damn right! :)
Lennart Regebro
@Hamish Grubijan, ahh, so this is a club now that has preferred members? Pity I wasn't informed. Any other untouchables I should know about?
Omnifarious
Omnifarious, I will give you an answer if you can tell me what my name means.
Hamish Grubijan
@Hamish Grubijan, I believe it means 'rowdy scottsman' or 'red-neck scottsman'.
Omnifarious