[Tutor] [OT] Secure coding guidelines
alan.gauld at btinternet.com
Sun Oct 11 00:28:05 CEST 2009
"Wayne" <srilyk at gmail.com> wrote
> Data validation is also a good thing:
I agree with this bit but...
> def mysum(n1, n2):
> n1 = int(n1)
> n2 = int(n2)
> except ValueError:
> print "Error! Cannot convert values to int!"
> return n1+n2
> Or do something similar.
In a dynamic language like Python this kind of data validation - which
is actually type validation - is not necessary.
It would be better to do:
print "Cannot add %s and %s" % (n1,n2)
One of the most powerful features of Python is that you can use
"Duck Typing" to create powerful polymorphic functions like this
that can add two objects, regardless of type, provided they
support addition. Limiting it to integers would be a big limitation.
In Python data validaton should normally be restricted to catching
invalid data *values* not invalid data types.
Author of the Learn to Program web site
More information about the Tutor