Proper way in Python to raise errors while setting variables

Your code is out of a context so is not obvious the right choice. Following some tips:

  • Don’t use NameError exception, it is only used when a name, as the exception itself said, is not found in the local or global scope, use ValueError or TypeError if the exception concerns the value or the type of the parameter;

  • Don’t print error messages. Raise meaningful exceptions with a meaningful error message:

    raise ValueError("password must be longer than 6 characters")
    
  • Returning a value from a setter is meaningless while assignment is not an expression, i.e. you cannot check the value of an assignment:

    if (user.password = 'short'): ...
    
  • Just raise an exception in the setter and let the code that set the property handle it.

Example:

class Test:

    minlen = 6

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, value):
        if not isinstance(value, basestring):
            raise TypeError("password must be a string")
        if len(value) < self.minlen:
            raise ValueError("password must be at least %d character len" % \
                                 self.minlen)
        self._password = value

Look also at this forms handling library, there the validators , here an example, are entities in their own: they can be set dynamically with higher control and less coupled code, but maybe this is much more than you need.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)