In Python, what is the preferred naming convention for backup storage of an internal property?

Suppose you have an open method in Python whose main purpose is to retrieve the value of the underlying data attribute (i.e. internal backup storage). A method may have lazy evaluation logic, etc. A property is an example of such a method.

Then it’s natural to use the same name for the method attribute and the data, except for the 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 the Python Documentation "Property" )

But what are some preferred conventions if the method is used internally and therefore has an underscore prefix? The backup storage prefix with two leading underscores will cause name manipulation and is therefore not ideal.

Two possibilities are possible -

 def _get_x(self): return self._x def _x(self): return self._x_ 

Python's style says that the second (adding underscores), however, should only be used to prevent conflicts with reserved keywords.

+7
python properties
source share
2 answers

The preferred condition is to use a single underline.

This is the PEP 8 recommendation for private attributes.

See this example in docstring for property ():

 >>> help(property) Help on class property in module builtins: class property(object) | property(fget=None, fset=None, fdel=None, doc=None) -> property attribute | | fget is a function to be used for getting an attribute value, and likewise | fset is a function for setting, and fdel a function for del'ing, an | attribute. Typical use is to define a managed attribute x: | class C(object): | def getx(self): return self._x | def setx(self, value): self._x = value | def delx(self): del self._x | x = property(getx, setx, delx, "I'm the 'x' property.") | | Decorators make defining new properties or modifying existing ones easy: | class C(object): | @property | def x(self): return self._x | @x.setter | def x(self, value): self._x = value | @x.deleter | def x(self): del self._x | 
+3
source share

Why would you make this property if it is intended for internal use? If it is used internally, simply access the attribute directly.

But then you will still use one underscore, but call it something else. But then again, in this case the whole goal is lost to make it property.

+1
source share

All Articles