To learn more about the concepts covered in this lesson, check out the following:
Validating Input Values
Validating Input Values. One of the most common use cases of
property() is building managed attributes that validate the input data before storing or even accepting it as secure input.
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.
Since your users are free to enter any type of data, you need to make sure that your
Point only accepts numbers. Here’s an implementation of
Point that manages this requirement.
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.
Here’s how the
Point class works now.
If you assign
.y values that
float() can turn into floating-point numbers, then the validation is successful, and the value is accepted.
Otherwise, you get a
ValueError. This implementation of
Point uncovers a fundamental weakness of
property(), which you may have noticed.
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.
Here, you define
Coordinate as a descriptor that manages your data validation in a single place.
Point now makes use of
04:37 This code works just like the earlier implementation, and you can see it being tested on-screen.
05:16 In general, if you find yourself copying and pasting property definitions all around your code, or if you spot repetitive code, then you should consider using a proper descriptor.
05:27 In the next section, you’ll see an example using computed attributes.
Become a Member to join the conversation.