[Tutor] Testing a variable for being a number, string or other object...

Rodrigues op73418 at mail.telepac.pt
Tue Aug 12 16:31:26 EDT 2003



> -----Original Message-----
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On
> Behalf Of Marc Barry
>
> Dear All:
>
> My first question is how do I test if a variable is a
> number or a string?  I
> need to to do this for error checking on values passed into methods.
>
> The second question I have is does Python have a way of testing for
> instances like Java does?  For example, the "instanceof"
> operator that lets
> you determine if an instance is of a certain type?

Yes, isinstance.

>>> isinstance(1, int)
True
>>> isinstance('', int)
False
>>>

And this answers your first question.

Note though, that the usual Pythonic mode is to code for protocol not
for type, as embodied in Easier to Ask Forgiveness Than Permission
principle. I don't know your cosde, so your constraints may be
different, but in general it really doens't matter the *exact type (or
class)* of the object but only the protocol or interface to which it
responds.

Let me give you an example: What is a string? Well, one answer would
be isinstance(<whatever>, str) returns True, but this is too-stringent
for our needs.

>>> def isstringy(obj):
... 	try:
... 		obj + ''
... 	except TypeError:
... 		return False
... 	else:
... 		return True
...

This defines a function that checks if some object can be *added* to
the empty string. If it can we count it as stringy enough.

Another example: For a lot of code (more than I ever imagined
actually) it really does not matter if we get a list, a tuple,
whatever. It only matter if we can *traverse* the object. In Python >
2.2 this is embodied in the iterator protocol, that is:

>>> def isiterable(obj):
... 	"""Return True if object is iterable, False otherwise."""
... 	try:
... 		iter(obj)
... 	except TypeError:
... 		return False
... 	else:
... 		return True
...

With these ideas in hand, the EAFTP is easy to explain. One just goes
ahead and *tries* to do the operations one wants, taking care of the
exceptions on the way. For an iterable, something like

try:
    #Use object in the way intended.
    ...
except TypeError #Or other exceptions.
    ...

Some care must be exercised, though, to put as little code in the try
block as possible so as not to catch "unwanted" exceptions.

HTH, with my best regards,
G. Rodrigues




More information about the Tutor mailing list