Let's say I have a simple method which requires a list of strings.
def make_fruits_lower_case(list_of_fruits):
"""make fruits pretty bla bla bla"""
return [fruit.lower() for fruit in list_of_fruits]
Use case 1: a developer provides a list of fruits and it works fine. Expected behaviour.
make_fruits_lower_case(['APPLE', 'ORANGE']) -- > ['apple', 'orange']
Use case 2: Let's say some other developer, intentionally or unintentionally, provides it a string.
make_fruits_lower_case('APPLE') --> ['a', 'p', 'p', 'l', 'e']
What is the pythonic way to handle such situation?
1: Introduce argument validation
def make_fruits_lower_case(list_of_fruits):
if isinstance(list_of_fruits, list):
return [fruit.lower() for fruit in list_of_fruits]raise
TypeError('list_of_fruits must be a of type list')
2: Expect developer in use case 2 to provide a list.
Beside this specific situation, It would be great to know what are pythonic recommendations to handle such situations in general such that we expect the developers to make sure that they provide right arguments or should we add some basic validations?.