Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much input validation should I be doing on my python functions/methods?

I'm interested in how much up front validation people do in the Python they write.

Here are a few examples of simple functions:

def factorial(num):
    """Computes the factorial of num."""

def isPalindrome(inputStr):
    """Tests to see if inputStr is the same backwards and forwards."""

def sum(nums):
    """Same as the built-in sum()... computes the sum of all the numbers passed in."""

How thoroughly do you check the input values before beginning computation, and how do you do your checking? Do you throw some kind of proprietary exception if input is faulty (BadInputException defined in the same module, for example)? Do you just start your calculation and figure it will throw an exception at some point if bad data was passed in ("asd" to factorial, for example)?

When the passed in value is supposed to be a container do you check not only the container but all the values inside it?

What about situations like factorial, where what's passed in might be convertible to an int (e.g. a float) but you might lose precision when doing so?

like image 673
Lawrence Johnston Avatar asked Dec 15 '08 05:12

Lawrence Johnston


People also ask

How do you validate inputs in Python?

Uses the isdigit() Function to Check if the User Input Is Valid in Python. The isdigit() function can be utilized to check whether the value provided of an input is a digit (0-9) or not. It returns a True value if the string contains numeric integer values only; it does not consider floating-point numbers.

How do you validate a function in Python?

The validation can be done in two different ways, that is by using a flag variable or by using try or except which the flag variable will be set to false initially and if we can find out that the input data is what we are expecting the flag status can be set to true and find out what can be done next based on the ...

When should input validation occur?

Because it is difficult to detect a malicious user who is trying to attack software, applications should check and validate all input entered into a system. Input validation should occur when data is received from an external party, especially if the data is from untrusted sources.

What should input validation be based on?

Input validation should be applied on both syntactical and Semantic level. Syntactic validation should enforce correct syntax of structured fields (e.g. SSN, date, currency symbol).


1 Answers

I assert what's absolutely essential.

Important: What's absolutely essential. Some people over-test things.

def factorial(num):
    assert int(num)
    assert num > 0

Isn't completely correct. long is also a legal possibility.

def factorial(num):
    assert type(num) in ( int, long )
    assert num > 0

Is better, but still not perfect. Many Python types (like rational numbers, or number-like objects) can also work in a good factorial function. It's hard to assert that an object has basic integer-like properties without being too specific and eliminating future unthought-of classes from consideration.

I never define unique exceptions for individual functions. I define a unique exception for a significant module or package. Usually, however, just an Error class or something similar. That way the application says except somelibrary.Error,e: which is about all you need to know. Fine-grained exceptions get fussy and silly.

I've never done this, but I can see places where it might be necessary.

assert all( type(i) in (int,long) for i in someList ) 

Generally, however, the ordinary Python built-in type checks work fine. They find almost all of the exceptional situations that matter almost all the time. When something isn't the right type, Python raises a TypeError that always points at the right line of code.

BTW. I only add asserts at design time if I'm absolutely certain the function will be abused. I sometimes add assertions later when I have a unit test that fails in an obscure way.

like image 176
S.Lott Avatar answered Oct 23 '22 13:10

S.Lott