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
🌐
GeeksforGeeks
geeksforgeeks.org › python › handling-typeerror-exception-in-python
Handling TypeError Exception in Python - GeeksforGeeks
August 22, 2025 - Trying to use a variable like a string or number as if it were a function will raise a TypeError. ... To fix this error, just print the variable without parentheses. ... Python list indices must be integers or slices.
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.7 documentation
Traceback (most recent call last): File "<stdin>", line 2, in <module> raise TypeError('bad type') TypeError: bad type Add some information Add some more information >>> For example, when collecting exceptions into an exception group, we may want to add context information for the individual errors.
🌐
W3Schools
w3schools.com › python › gloss_python_raise.asp
Python Raise an Exception
Python Examples Python Compiler ... to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword....
🌐
Real Python
realpython.com › ref › builtin-exceptions › typeerror
TypeError | Python’s Built-in Exceptions – Real Python
An example of when you may want to raise the exception: ... >>> def run_callback(callback, *args, **kwargs): ... if not callable(callback): ... raise TypeError("callback must be callable") ... return callback(*args, **kwargs) ...
🌐
PythonForBeginners.com
pythonforbeginners.com › home › typeerror in python
TypeError in Python - PythonForBeginners.com
December 28, 2022 - Traceback (most recent call last): File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module> myResult = myInt / myStr TypeError: unsupported operand type(s) for /: 'int' and 'str' Let us take another example, Suppose that we want to concatenate two lists.
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 - For instance, the len() function expects a sequence (like a string or list), but passing an integer will raise an error: # Example: Passing an integer to len() length = len(123) To fix this, pass a valid sequence, such as a string: # Corrected ...
🌐
Python
docs.python.org › 3 › builtins › exceptions.html
Built-in Exceptions — Python 3.14.7 documentation
A writable field that holds the traceback object associated with this exception. 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.
Find elsewhere
🌐
Real Python
realpython.com › python-raise-exception
Python's raise: Effectively Raising Exceptions in Your Code – Real Python
October 20, 2025 - For example, say you’re coding ... ... >>> def squared(numbers): ... if not isinstance(numbers, list | tuple): ... raise TypeError( ......
🌐
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 ...
Published: October 1, 2022
🌐
Better Stack
betterstack.com › community › questions › how-to-raise-exceptions-manually-in-python
How to manually raising (throwing) an exception in Python? | Better Stack Community
January 26, 2023 - For example, to raise a TypeError exception, you can use the following code: ... Keep in mind that it is generally a good idea to only raise exceptions in exceptional circumstances. In most cases, it is better to use standard Python control structures (such as if-else or for loops) to handle ...
🌐
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:
🌐
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 ...
🌐
B-List
b-list.org › weblog › 2023 › dec › 11 › python-exceptions
Raise the right exceptions - James Bennett
December 11, 2023 - The isinstance() check there enforces ... if someone passes in an argument or set of arguments that don’t support division, Python will automatically raise a TypeError anyway. For example, if you try divide(5, "hello") without the explicit type-check, you’ll get:...
🌐
Rollbar
rollbar.com › home › throwing exceptions in python
How to Throw Exceptions in Python | Rollbar
Similar to TypeError, there are several built-in exceptions like: ... You can refer to the Python documentation for a full list of exceptions. ... Sometimes you want Python to throw a custom exception for error handling. You can do this by checking a condition and raising the exception, if ...
Published: May 22, 2026
🌐
Manning
livebook.manning.com › wiki › categories › python › typeerror
TypeError in Python - liveBook · Manning
In this example, the key parameter is set to a lambda function that extracts the value associated with the ‘urgency’ key from each dictionary, allowing Python to sort them accordingly. Python allows handling multiple exceptions using ExceptionGroup, which can be useful when you want to handle different types of exceptions in a single block of code. try: raise ExceptionGroup("Multiple exceptions", [TypeError(), FileNotFoundError(), ValueError()]) except* TypeError: message += "Handling TypeError\n" except* IOError: message += "Handling IOError\n" except* ValueError: message += "Handling ValueError\n" finally: print(message)
🌐
Stack Overflow
stackoverflow.com › questions › 54660092 › when-to-raise-typeerror-exception-in-python
When to raise TypeError exception in Python? - Stack Overflow
Are there any established guidelines or traditions about raising TypeError? ... Option 2 sounds right to me. See, for example, section "2) Comparing objects from different classes/types" from this lecture from one of my college professors: ics.uci.edu/~pattis/ICS-33/lectures/operatoroverloading1.txt
🌐
Openastronomy
openastronomy.org › rcsc18 › chapters › 05-writing-effective-tests › 02-explicit-exceptions
Raising Errors - Research Computing Summer School
This is useful if you want to verify ... with numbers, so we want to make sure we dont pass a string. def square(x): if isinstance(x, str): raise ValueError("the argument x can not be a string") else: return x**2...
🌐
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 ...
🌐
LabEx
labex.io › tutorials › python-how-to-handle-typeerror-exception-in-python-398017
How to handle TypeError exception in Python | LabEx
To identify a TypeError exception in your Python code, you can look for the following symptoms: Your program raises a TypeError exception with a descriptive error message. The error message provides information about the specific operation or function call that caused the exception, as well as the types of the involved objects. For example, if you try to perform an addition operation between a string and an integer, you will see an error message similar to this: