[Tutor] Input validation

Albert-Jan Roskam fomcl at yahoo.com
Thu Sep 3 19:31:00 CEST 2009


Hi,

I'm wondering what is the most common method of input validation. See the example below. 
-Is the code below the most common/recognizable way something like this is done?
-Which of the options #1 and #2 is the preferred method? Option #2 looks less esoteric, but #1 seems better when you have to check for several data types simultaneously.

Thanks!
Albert-Jan

import os.path, textwrap

def main(param):
    if validate_input(param) == "LT":
        return param[-1]
    elif validate_input(param) == "FILE":
        f = open(param, "rb").readlines()
        return " ".join(f)
    elif validate_input(param) == "STR":
        return textwrap.wrap(param)
    else:
        print "Invalid input!"
        return None

def validate_input (param):
    if param.__class__ in (list, tuple): #option 1
        return "LT"
    elif isinstance(param, str):        # option 2
        if os.path.isfile(param):
            return "FILE"
        else:
            return "STR"
    else:
        return None
    
print main(param=[1,2,3])
print main(param="d:/temp/txt.txt")
print main(param="yeah but yeah, but no")
print main(param=1.0)




      


More information about the Tutor mailing list