Python Forum

Full Version: Author class, with constructor validations
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
class Author:

    def __init__(self, id, firstname, lastname):
        self._validateid(id, "ID")
        self._validate_author(firstname, "First Name")
        self._validate_author(lastname, "Last Name")

        self._id = id
        self._firstname = firstname
        self._lastname = lastname

    def _validateid(self, id, error_message):
        if id < 1:
            raise ValueError(error_message + " is invalid")

    def _validate_author(self, parameter, error_message):
        if not parameter:
            raise TypeError(error_message + " is missing")

    @property
    def iden(self):
        return self._id

    @property
    def first_name(self):
        return self._firstname

    @property
    def last_name(self):
        return self._lastname
I created an Author class and wanted to ensure that all the parameters were valid during construction. I created a private method to validate the parameters, and if it's invalid or missing, it raises an error. Is this okay? What is the Python way of doing it?
I think that would be the way to do it, but I would have _validate_author return a ValueError. I'm guessing it's checking for an empty string, not a non-string, so it's the right type with a bad value.
(Oct-12-2017, 10:09 PM)ichabod801 Wrote: [ -> ]I think that would be the way to do it, but I would have _validate_author return a ValueError. I'm guessing it's checking for an empty string, not a non-string, so it's the right type with a bad value.

Thanks for the feedback. Much appreciated. Smile
You might want to have a TypeError as well, but you would want a separate check for that:

if not isinstance(parameter, str):
    raise TypeError('{} must be a string.'.format(error_message))
elif not parameter.strip()
    raise ValueError('{} must be non-blank.'.format(error_message))