asserting types

Paul Prescod paulp at ActiveState.com
Fri Apr 20 21:10:58 EDT 2001


Mick wrote:
> 
> 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?

It is generally considered bad form to try to assert a particular class.
In Python it is more profitable to presume that the users of your module
know what they are doing. If they give you a class that is not a
subclass of yours, they may do it for a good reason (i.e. it is a
C-module for speed, or it is an object from another module that
implements the right interface). 

If you want to do a sanity check, the best thing is to check that the
methods you expect to be available are available. Even just one or two
suffices as a sanity check. If they implement those one or two but not
other important ones then again, they may feel that they know what they
are doing (i.e. a particular code path is known not to call the other
methods) and you should just trust them.
-- 
Take a recipe. Leave a recipe.  
Python Cookbook!  http://www.ActiveState.com/pythoncookbook




More information about the Python-list mailing list