verify the return value of a function

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Jan 20 10:07:28 EST 2012


On Fri, 20 Jan 2012 08:53:13 -0500, Mel Wilson wrote:

> Jean-Michel Pichavant wrote:
> 
>> isinstance is fine, if you could find the source where it is
>> discouraged... Could be a consequence of some specific context.
>> However, checking types in OOP is in general a failure. Unitary tests
>> are possibly an exception.
> 
> I think it's discouraged when people try to write big overloaded
> functions that check the types of the arguments to decide what they
> should be doing.

I don't agree with that. Writing polymorphic functions using isinstance 
is a perfectly reasonable thing to do. E.g. from the standard library's 
decimal module:

class Decimal(object):
    """Floating point class for decimal arithmetic."""
    # We're immutable, so use __new__ not __init__
    def __new__(cls, value="0", context=None):
        self = object.__new__(cls)
        # From a string
        # REs insist on real strings, so we can too.
        if isinstance(value, str):
            ...
        # From an integer
        if isinstance(value, int):
            ...
        # From another decimal
        if isinstance(value, Decimal):
            ...
        # From an internal working value
        if isinstance(value, _WorkRep):
            ...
        # tuple/list conversion (possibly from as_tuple())
        if isinstance(value, (list,tuple)):
            ...
        if isinstance(value, float):
            ...
        raise TypeError("Cannot convert %r to Decimal" % value)


What should be avoided, when possible, is over-reliance on isinstance 
checks instead of protocol or interface checks. For example, don't check 
for a list if your function doesn't *need* a list but would be happy with 
a tuple or some other sequence.

Worse than isinstance is testing for an exact type:

if type(x) is list  # worse than isinstance(x, list)

although of course, there are times where you need to break the rules.



> In diagnostics and tests like the OP's there should be
> no problem.

Agreed.



-- 
Steven



More information about the Python-list mailing list