Object type check

Michele Simionato michele.simionato at gmail.com
Wed Feb 7 11:49:52 EST 2007


On Feb 7, 5:17 pm, "king kikapu" <aboudou... at panafonet.gr> wrote:
> Hi to all,
>
> in statically-types languages, let's say C# for example, we use
> polymorphism through interfaces. So we define an interface I with
> method M and then a class C that implements I interface and write code
> for the M method.
> So, if we have a function that takes a parameter of type I, we know
> before-hand that it will have an M method to call.
>
> But in dynamic languages this is not the case and we can pass whatever
> we want to that function. Assuming that someone writes a library in
> Python that other programmers will use, what is the correct way to
> check inside that function if the parameter passed is of the correct
> type, maybe "isinstance" BIF ?

Usually, you don't check anything at all. However, in some cases, it
may make
sense to check that you passed the right object.
For instance if you have the container

class Example(object):
   def __init__(self, innerobj):
          self.innerobj = innerobj
   def amethod(self):
          self.innerobj.amethod()

ex = Example(None)

you will get an error only when calling ex.amethod(). If you are going
to call
ex.amethod() one hour after instantiation, you will get the error too
late.
So, it makes sense to put a check in the __init__ method, something
like

assert hasattr(self.innerobj, 'amethod')

in order to get an error message as soon as possible. Notice that
checking for the existance
of the needed method is better than using isinstance, since it gives
you much more
freedom for innerobj. Do not require more than you need.
HTH,

     Michele Simionato




More information about the Python-list mailing list