I would like to have some validation inside of a property setter in a class. This property has to be set during object creation and then it needs to be read-only from the outside.
I found the following solution and I wonder if there is a more straightforward or Pythonic way to do it.
(I am aware that by calling user._username from the outside it is still possible to set this property, but "we are all consenting adults" etc. - the important thing is that user.username should not have a setter).
class User:
def __init__(self, username):
self._usernname = username
@property
def username(self):
return self.__username
@property
def _username(self):
return self.__username
@_username.setter
def _username(self, value):
if not value or len(value) < 3:
raise ValueError('Invalid username')
self.__username = value
Edit: In addition to the comments here, options for validation in the constructor can be found here: numpy performance and random numbers.
_usernamewith one underscore in the constructor, and remove the_usernameproperty altogether...__init__method. The additional_usernameproperty looks very artificial and serves no real purpose._usernameproperty, where can I validate this value?__init__and adjust accordingly. Get rid of the two_usernameproperty functions._usernameattribute is internal and should have no outward-facing api. It's only ever set once in__init__, so there's no point in creating a property for it.