asserting types

Stephen news at myNOSPAM.org
Fri Apr 20 21:49:58 EDT 2001


    My perception of The Python Way is that, in general, you don't check to
see if you're being passed the correct type of an argument -- you attempt to
use it, and if it fails, then you were passed the wrong type. The reason is
that you want to allow people to substitute 'compatible' classes when
suitable. For instance, if you have a function that is using
'fileobject.read()', you shouldn't check 'if type(fileobject) ==
types.FileType', but instead just try to read from the file... it could be
an alternate file-like object, such as a StringIO, that is being
intentionally passed in. Or, if you're expecting a list, it could be a
user-defined class that implements the appropriate 'magic methods' to behave
like a list.

    There is currently quite a bit of discussion going on about how to make
a class declare that it follows a perticular interface, which would be good
for your solution... but its not ready yet. In the meantime, checking for
the existance of a key method may work for you.

    Take the fileobject example; if you are using 'readline()', check to see
if what you are passed has a readline. E.g:

def isFile(obj):
    try:
        obj.readline
    except AttributeError:
        return 0
    return 1

If you are concerned that 'readline' may be an attribute, you can replace
the 'obj.readline' with something as follows:

if type(obj.readline) is not types(types.MethodType):
    raise AttributeError

HTH,

--Stephen
(replace 'NOSPAM' with 'seraph' to respond in email)


"Mick" <vsl6 at paradise.net.nz> wrote in message
news:mailman.987812911.3136.python-list at python.org...
> What is the cleanest way to assert a class type?  for example if one has a
> function that uses a particular class object then what is the nicest way
to
> assert within the function that the class is of the correct type?  I
assume
> this is simple, so I guess more the question is this the wrong way to
think?
> should I be trying to organise things in a different way so as to generate
> "compile" time errors?
>
> regards
> Mick
>
>





More information about the Python-list mailing list