To learn more about the concepts covered in this lesson, check out the following:
Validating Input Values
Data validation is a common requirement in code that takes input from users or other information sources that you consider untrusted. Python’s
property() provides a quick and reliable tool for dealing with input data validation. Thinking back to that
Point example, you may require the values of
.y to be valid numbers.
The setter methods uses a
except block that validates input data using the Python EAFP (easier to ask for forgiveness than permission) style. If the call to
float() succeeds, then the input data is valid, and you get
Validated! on your screen.
float() raises a
ValueError, then the user gets a
ValueError with a more specific message. Note that in this code, you use the syntax
from None to hide internal details related to the context in which you are raising the exception.
From the end user’s viewpoint, these details can be confusing and make your class look unpolished. Check out the section on the
raise statement in the documentation for more information about this topic.
.y property follows the same pattern as
x. It’s important to note that assigning the
.y properties directly in
.__init__() ensures that the validation also occurs during object initialization. Not doing so is a common mistake when using
property() for data validation.
03:13 You have repetitive code that follows specific patterns. This repetition breaks the DRY (Don’t Repeat Yourself) principle, so you would want to refactor this code to avoid it. To do so, you can abstract out the repetitive logic using a descriptor.
Become a Member to join the conversation.