Aravind Ramalingam
- Python
- Validation
- Data Type
Validate User Input in Python Function
Writing type hints for function arguments is a good start, but as the name suggests, it only hints at the data type of argument. When the functionality of the code depends on the data type of argument, then we must put validations in place.
Introduction
Type hints are great, they help you to write better code and reduce documentation required for external users or downstream software developers. However, type hints do not validate the input from the user. In my opinion, without any validation, you are playing the odds, but if you are up for a gamble then good luck to you! For the non-gamblers, we will explore how to do this with an example.
Code
Let us write a simple function (add
)
which has a single argument vals
. The
logic for the function is:
- Validate that the input for
vals
argument is aList
of eitherint
orstring
. - Return a list of
integer
after adding 1 or list ofstring
with period appended to the argumentvals
based on the user input.
You can validate the user input with a simple isinstance
function. The above code works, but it\'s not scalable
for the below reasons:
- Have to write validations for every argument of the function.
- Probably requires a lot of effort to rewrite, when the function argument is modified.
- Don't forget about the test cases required for type validations.
Tests
Positive:
Negative:
# Test Function add for int
add(1)
# Test Function add for list of float
add([1.0])
# Test Function add for list of mixed data types
add([1, 1.0])
Better Way
Python's type hints and type_extensions is changing rapidly over the last few iterations, so my recommendation is to use an external package like Typeguard for the following reasons:
- Helps to abstract away the code for type validation with help of a decorator.
- Provides additional functionality (way more than what we wrote or need).
- Support for multiple Python versions have been tested.
- Error message is detailed and easy to understand.
To replicate our example from above, we just have to add the
typechecked
decorator before the
function definition and remove the validations for type checks.
Negative Tests:
# Test Function add_ext for int
add_ext(1)
# Test Function add_ext for list of float
add_ext([1.])
# Test Function add_ext for list of mixed data types
add_ext([1, 1.0])
Takeaway
If you are working on something serious, then don't forget to validate user inputs. Feel free to reach out via Contact for any questions or suggestions.