Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter validation, Best practices in Python

Tags:

python

Lets take an example of a API

def get_abs_directory(self, path):
    if os.path.isdir(path):
       return path
    else:
       return os.path.split(os.path.abspath(path))[0]

My question is what is the pythonic way of validating parameters, should I ignore any type of validations (I observed that all the python code does no validation at all)

  1. Should I check for "path" to be empty and not null
  2. Should I check the "type" of path to be string always
  3. In general should I check for type of parameters ? (I guess not as python in dynamically typed)

This question is not specific to File IO, instead FileIO is used only as an example

like image 839
Bhushan Avatar asked Oct 21 '13 05:10

Bhushan


People also ask

What is validating in Python?

Data validation is when a program checks the data to make sure it meets some rules or restrictions. There are many different data validation checks that can be done. For example, we may check that the data: Is of correct data type, for example a number and not a string.


1 Answers

As mentioned by the documentation here, Python follows an EAFP approach. This means that we usually use more try and catch blocks instead of trying to validate parameters. Let me demonstrate:

import os


def get_abs_directory(path):
    try:
        if os.path.isdir(path):
            return path
        else:
            return os.path.split(os.path.abspath(path))[0]
    except TypeError:
        print "You inserted the wrong type!"


if __name__ == '__main__':
    get_abs_directory(1)  # Using an int instead of a string, which is caught by TypeError

You could however, wish to code in a LBYL (Look Before You Leap) style and this would look something like this:

import os


def get_abs_directory(path):

    if not isinstance(path, str):
        print "You gave us the wrong type, you big meany!"
        return None

    if os.path.isdir(path):
        return path
    else:
        return os.path.split(os.path.abspath(path))[0]

if __name__ == '__main__':
    get_abs_directory(1)
like image 170
Games Brainiac Avatar answered Oct 12 '22 08:10

Games Brainiac