add type predicates to types module?
Jeremy Hylton
jeremy at cnri.reston.va.us
Fri Apr 2 17:57:38 EST 1999
This is a really good idea. I know I've got type predicates of many
different flavors in code I've been working on recently. The tough
question, I think, is how to decide which predicates are needed and
how to implement them.
The folkloric "file-like object" type is a good example. When people
say "file-like object" they mean an object that responds in a
reasonable way to the particular subset of methods on a builtin file
object that they are interested in.
isSequence might be a better example, since you want to capture
instances that implement the sequence protocol along with tuples,
lists, and strings. I use:
def isSequence(s):
try:
0 in s
except TypeError:
return 0
else:
return 1
def isCallable(obj):
if type(obj) in (types.BuiltinFunctionType,
types.BuiltinMethodType, types.LambdaType,
types.MethodType):
# XXX could include types.UnboundMethodType
return 1
if type(obj) == types.InstanceType:
return hasattr(obj, '__call__')
return 0
In the particular application I needed, I know I would not want to
include UnboundMethodTypes. In the general case, though, I think it
should be included.
Jeremy
More information about the Python-list
mailing list