check type when assignment

Nick Vatamaniuc vatamane at gmail.com
Wed Jul 12 12:40:12 EDT 2006


pipe,

In general it is not possible in one line. You have to do it before
hand or after with an if statement.

As a sidenote though you probably shouldn't use isinstance(), you might
need it less than you think you do, especially if you are using it to
check for some interface. For example, do you really care if bc is of
_type_ klass or just that bc just implements method x, y, z and has
arguments a, b,c? The two things seem to be the same, because they are
the same in C++ or Java, but they are not the same in Python. In Python
an interface and type inheritance can be orthogonal to each other. One
could add methods to objects or change them at will after
instantication such that the type hierarchy would be preserved but the
interface would be broken, or alternatively you could have an object of
a different type that fully implements the interface and  could easily
be used in the code but just because it doesn't pass the isinstance()
test it is flagged as un-usable.
So in your code you could just test for the interface (methods and/or
attributes) with hasattr(bc, 'method') or even better just call the
method and see what happens, if it doesn't exist it will raise an
exception.

A much better explanation about the use and abuse of isinstance() is
here:
http://www.canonical.org/~kragen/isinstance/

Hope this helps,
Nick V.

pipehappy wrote:
> Hello everyone:
>
> Is there a way to check the type when do assignment?
>
> if I write:
> ab = bc
> and want to make sure the return value of isinstance(bc, klass) is True
> or I will raise
> a exception.
> 
> Any suggestion?




More information about the Python-list mailing list