[vtk-developers] Problem with Python "hasattr"

Ben Boeckel ben.boeckel at kitware.com
Sun Aug 9 20:50:39 EDT 2015


On Sun, Aug 09, 2015 at 17:15:00 -0600, David Gobbi wrote:
> If "self" has no "VTKObject" attribute, it immediately goes into infinite
> recursion.

Doh. Can't __hasattr__ just be implemented directly? :(

> The following is the solution that I used. It checks the __dict__ because I
> know that's where the VTKObject attribute will be kept if it exists.
> 
>     def __getattr__(self, name):
>         try:
>             o = self.__dict__["VTKObject"]
>         except KeyError:
>             o = None
>         if o is None:
>             raise AttributeError("class has no attribute %s" % name)

Better:

    raise AttributeError("%s has no attribute %s" % (self.__class__.__name__, name))

--Ben


More information about the vtk-developers mailing list