[vtk-developers] Problem with Python "hasattr"

David Gobbi david.gobbi at gmail.com
Sun Aug 9 19:15:00 EDT 2015


On Sun, Aug 9, 2015 at 4:59 PM, Ben Boeckel <ben.boeckel at kitware.com> wrote:

>
> How about:
>
>     def __getattr__(self, name):
>         return getattr(self.VTKObject, name)


If "self" has no "VTKObject" attribute, it immediately goes into infinite
recursion.

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)
        return getattr(o, name)

It could be simplified a bit except that the "VTKObject" attribute can
sometimes be set to "None", and it would be confusing if the error message
said " 'NoneType' object has no attribute 'name' ".

The solution would be more complicated than the above if the "VTKObject" of
"self" might be kept somewhere other than __dict__, for example if it was
an attribute generated by a descriptor in self's type object.

 - David
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://public.kitware.com/pipermail/vtk-developers/attachments/20150809/c6761325/attachment.html>


More information about the vtk-developers mailing list