Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save navhits/73a9a83d3f2fa88766c7915fdc82282c to your computer and use it in GitHub Desktop.
Save navhits/73a9a83d3f2fa88766c7915fdc82282c to your computer and use it in GitHub Desktop.
A demonstration of validating function arguments in Python using Pydantic library.
from pydantic import validate_arguments, ValidationError
# A function with type hints
def arg_not_validated(s: str, i: int) -> str:
return f'{type(s)}, {type(i)}'
# A function using the Pydantic validate_arugments decorator.
# Refer https://pydantic-docs.helpmanual.io/usage/validation_decorator/
@validate_arguments
def arg_validated(s: str, i: int) -> str:
return f'{type(s)}, {type(i)}'
# When passing arguments with correct datatypes. There was no problem.
print(arg_not_validated('a', 1))
# <class 'str'>, <class 'int'>
# When passing arguments with incorrect datatypes. There is still no problem. :/
print(arg_not_validated(1, 'a'))
# <class 'int'>, <class 'str'>
# When passing arguments with correct datatypes. There was no problem. :)
print(arg_validated('a', 1)) # I'm guessing the Pydantic validation passed :D
# <class 'str'>, <class 'int'>
# One more time providing incorrect datatypes. Pydantic found errors.
# Notice here, only the second argument i had an error.
# This is because Pydantic converted the integer to a string autmatically.
print(arg_validated(1, 'a')) # If we printed arg_validated('a, 'a') this would result in same error
# ValidationError: 1 validation error for ArgValidated
# i
# value is not a valid integer (type=type_error.integer)
print(arg_validated(1, 1)) # To illustrate the above string handling. Here we will have no errors
# <class 'str'>, <class 'int'>
# The same applies to integers as well.
print(arg_validated('a', '1')) # Any integer represented as string can be converted to int type
# <class 'str'>, <class 'int'>
# The last few data conversions in Pydantic happens because that's the Pythonic standard and that has been supported well.
# Pydantic makes development tasks a little easier as compared to writing own validation classes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment