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.

Answer from mg. on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.7 documentation
As you can see, the finally clause is executed in any event. The TypeError raised by dividing two strings is not handled by the except clause and therefore re-raised after the finally clause has been executed.
🌐
W3Schools
w3schools.com › python › gloss_python_raise.asp
Python Raise an Exception
To throw (or raise) an exception, use the raise keyword. Raise an error and stop the program if x is lower than 0: x = -1 if x < 0: raise Exception("Sorry, no numbers below zero") Try it Yourself » · The raise keyword is used to raise an exception.
🌐
Python
docs.python.org › 3 › builtins › exceptions.html
Built-in Exceptions — Python 3.14.7 documentation
See also: The raise statement. ... Add the string note to the exception’s notes which appear in the standard traceback after the exception string. A TypeError is raised if note is not a string.
🌐
GeeksforGeeks
geeksforgeeks.org › python › handling-typeerror-exception-in-python
Handling TypeError Exception in Python - GeeksforGeeks
August 22, 2025 - Using a string or float as an index will raise a TypeError. ... To fix this error, convert the string "1" to an integer using int(). ... Objects like integers and floats are not iterable. Trying to use them in a loop will cause a TypeError.
🌐
Real Python
realpython.com › ref › builtin-exceptions › typeerror
TypeError | Python’s Built-in Exceptions – Real Python
>>> def run_callback(callback, *args, **kwargs): ... if not callable(callback): ... raise TypeError("callback must be callable") ... return callback(*args, **kwargs) ... >>> run_callback(42) Traceback (most recent call last): ... TypeError: callback must be callable ... In this tutorial, you'll get to know some of the most commonly used built-in exceptions in Python.
Top answer
1 of 3
70

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.

2 of 3
10

The standard way of signalling an error in python is to raise an exception and let the calling code handle it. Either let the NameError & TypeError carry on upwards, or catch them and raise an InvalidPassword exception that you define.

While it is possible to return a success/fail flag or error code from the function as you have done, it is not recommended - it is easy for the caller to forget to check the return value and have errors get lost. Besides you are returning a value from a property setter - this is meaningless in Python since assignments are not expressions and cannot return a value.

You should also never print a message for the user in your exception handling - what if you later want to use the function or class in a GUI program? In that case your print statement will have nowhere to print to. Logging an error to a logfile (using Python's logging module) is often helpful for debugging though.

🌐
Pronod's Blog
data-intelligence.hashnode.dev › handling-typeerror-in-python-guide
Understanding and Fixing Python TypeErrors - Pronod's Blog
September 13, 2024 - Calling a function with the wrong number of arguments will trigger a TypeError. For example: # Example: Function missing an argument def add(a, b): return a + b result = add(3) This will raise a TypeError since the add() function expects two ...
🌐
Real Python
realpython.com › python-raise-exception
Python's raise: Effectively Raising Exceptions in Your Code – Real Python
October 20, 2025 - Note how Python presents the first exception as the direct cause of the second one. This way, you’ll be in a better position to track the error down and fix it. This technique is pretty handy when you’re processing a piece of code that can raise multiple types of exceptions. Consider the following divide() function: ... >>> def divide(x, y): ... for arg in (x, y): ... if not isinstance(arg, int | float): ... raise TypeError( ...
Find elsewhere
🌐
PythonForBeginners.com
pythonforbeginners.com › home › typeerror in python
TypeError in Python - PythonForBeginners.com
December 28, 2022 - TypeError is an exception in Python programming language that occurs when the data type of objects in an operation is inappropriate. For example, If you attempt to divide an integer with a string, the data types of the integer and the string object will not be compatible.
🌐
W3Schools
w3schools.com › python › ref_keyword_raise.asp
Python raise Keyword
❮ Python Keywords · Raise an error and stop the program if x is lower than 0: x = -1 if x < 0: raise Exception("Sorry, no numbers below zero") Try it Yourself » · The raise keyword is used to raise an exception.
🌐
Python Morsels
pythonmorsels.com › how-to-throw-an-exception
How to raise an exception in Python - Python Morsels
January 17, 2022 - First we'll ask whether the given number is an instance of the float class, and we'll raise a TypeError exception if it is:
🌐
B-List
b-list.org › weblog › 2023 › dec › 11 › python-exceptions
Raise the right exceptions - James Bennett
December 11, 2023 - Which then raises the question of which exception(s) to raise, and that’s the real tip I want to get across today. The short answer is: TypeError for the case of a non-numeric argument, ValueError for the case of divisor=0. The longer answer is that when you want to do some sort of validation ...
🌐
Rollbar
rollbar.com › home › how to fix typeerror exceptions in python
How to Fix TypeError Exceptions in Python | Rollbar
Here’s an example of a Python TypeError thrown when trying to add a string and an integer: my_integer = 1 my_string = "Hello World" my_result = my_integer + my_string · In the above example, the string my_string is attempted to be added to an integer my_integer. Since addition cannot be performed between these two types, a TypeError is raised...
Published: October 1, 2022
🌐
Manning
livebook.manning.com › wiki › categories › python › typeerror
TypeError in Python - liveBook · Manning
A TypeError can also occur when mandatory positional parameters are not provided during a function call. Positional parameters are arguments that must be passed to a function in the correct order. Consider a function that requires two positional parameters: ... If you attempt to call this function without providing both arguments, Python will raise a TypeError:
🌐
Openastronomy
openastronomy.org › rcsc18 › chapters › 05-writing-effective-tests › 02-explicit-exceptions
Raising Errors - Research Computing Summer School
TypeError should be raised when the type (i.e. str, float, int) is incorrect. Not all programming errors raise an exception, some are errors in the functioning of the code. i.e. this: ... This is obviously incorrect, but Python does not know any difference, it executes the code as written and ...
🌐
Coursera
coursera.org › tutorials › how to catch, raise, and print a python exception
How to Catch, Raise, and Print a Python Exception | Coursera
August 13, 2024 - In the code block above, TypeError is the specified error. It has been set to occur anytime the variable x is not a string. The text inside the parentheses represents your chosen text to print to the user. How would you raise an exception that prints "Sorry, please enter a number greater than or equal to 0" if x is a negative number? ... In an exception block, define the exception and use the print() function. Here’s an example: ... Why isn’t Python ...
🌐
Hyperskill
hyperskill.org › university › python › python-raise-exception
Python Raise Exception
August 2, 2024 - When working with Python exceptions are triggered to signal when an error or unexpected situation arises while a program is running. The raise keyword is employed to specifically trigger these exceptions. This feature enables developers to generate and handle both customized exceptions.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-raise-keyword
Python Raise Keyword - GeeksforGeeks
May 12, 2026 - raise TypeError · Example: In the below code, we try to convert a string into an integer. If conversion fails, we raise a ValueError. Python · s = 'apple' try: num = int(s) except ValueError: raise ValueError("String can't be changed into integer") Output ·
🌐
Stack Overflow
stackoverflow.com › questions › 54660092 › when-to-raise-typeerror-exception-in-python
When to raise TypeError exception in Python? - Stack Overflow
check the type of every argument of every function and of every method if only certain particular types are expected (like float or str) and raise TypeError if the argument type is not among the expected ones.