[Tutor] Input validation

Rich Lovely roadierich at googlemail.com
Fri Sep 4 16:38:41 CEST 2009


2009/9/3 Albert-Jan Roskam <fomcl at yahoo.com>:
> 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)
>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

isinstance can take a tuple of types:

def validate_input (param):
   if isinstance(param, (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

Also, file-type objects aren't instances of str...

-- 
Rich "Roadie Rich" Lovely
There are 10 types of people in the world: those who know binary,
those who do not, and those who are off by one.


More information about the Tutor mailing list