A.Wan
A.Wan

Reputation: 2068

Naming private properties in Python

My question is almost identical to this one, but it looks like a dead thread and the question I want to ask looks a little buried.

Question: if I want to use @property to make private attributes, what should I name the underlying variable?

Code:

# I want to replace "NAME" with something.
class MyClass(object):
  def __init__(self, x):
    self.NAME = x

  @property
  def _x(self):
    validate_x_get()
    return self.NAME

  @_x.setter
  def _x(self, val):
    validate_x_set(val)
    self.NAME = val

  ...

Explanation: I want to use @property and @valname.setter to allow MyClass methods to nicely work with self.NAME. Answers to the linked question generally say to just make private getters and setters, but it feels like there should be a better way.

Discussion:

Any suggestions?

Upvotes: 0

Views: 915

Answers (1)

A.Wan
A.Wan

Reputation: 2068

Just to sum up the discussion:

  • This is mostly opinion-based because Python's "private" is by convention;
  • Any solution that's readable, understandable, and consistent is good enough.

In that spirit, I'll be advocating for _x_ in my codebases (fewest additional characters). Thanks to all the commenters.

Upvotes: 3

Related Questions