[Q] Type checking...go further...
Michael P. Reilly
arcege at shore.net
Mon Jul 19 20:40:28 EDT 1999
Stidolph, David <stidolph at origin.ea.com> wrote:
: You cannot have typed method parameters (Python is typeless), but can only
: check the types of parameters within the method.
: from types import * #Needed for different types like IntType
: def foo(a, b, c):
: if type(a) is IntType:
: print a,'is a integer'
: elif type(a) is LongType:
: print a,'is a long integer'
: elif type(a) is StringType:
: print a,'is a integer'
: elif type(a) is FloatType:
: print a,'is a floating point number'
: elif type(a) is ListType:
: print a,'is a list'
: elif type(a) is TupleType:
: print a,'is a tuple'
: or
: def foo(a,b,c):
: if not (type(a) is IntType):
: raise "Param a must be integer"
: if not (type(b) is StringType):
: raise "Param b must be string"
: if not (type(c) is ListType):
: raise "Param c must be list"
: ...
The "isinstance()" builtin function also works on types:
def foo(a, b, c):
if not isinstance(a, types.IntType):
raise TypeError, "Param a must be integer"
if not isinstance(b, types.StringType):
raise TypeError, "Param b must be string"
if not isinstance(c, types.ListType):
raise TypeError, "Param c must be list"
It is often better not to call "from types import *" since that can
clutter the namespace unnecessarily.
-Arcege
More information about the Python-list
mailing list