Saturday snippet: Python classes, __getattr_, lambda, and-or trick, and getattr


Here’s a snippet of some python posted on the Softimage mailing list this week.

from win32com.client import constants
class Softimage:
    __getattr__ = lambda x, a: getattr(Application, a, False) or getattr(constants, a)
softimage = Softimage()

Let’s break this down…

First, this snippet defines a class named Softimage (lines 1 and 2) and then instantiates an instance of that class (line 4).

Once you have an instance of a class, you can access the attributes of the class. Now this Softimage class doesn’t define any attributes, but it does provide a __getattr__ method. For example, if you ask for softimage.GetValue, then that __getattr__ method gives you back the function object Application.GetValue. If you ask for softimage.ActiveSceneRoot, you get back the value of the Application.ActiveSceneRoot property. And if you ask for softimage.siX3DObjectID, you get back constants.siX3DObjectID.

So, how does that work?

__getattr__ is a method that is called when an attribute isn’t found on a class instance.
If you define __getattr__ without using lambda or the and-or trick, it could look something like this:

from win32com.client import constants
class Softimage:
#    __getattr__ = lambda x, a: getattr(Application, a, False) or getattr(constants, a)
    def __getattr__( self, name ):
        a = getattr(Application, name, False) 
        if not a:
            a = getattr(constants, name)
        return a

getattr is a built-in Python function that gets an attribute on a specified object. Here, we’re getting an attribute of the Softimage Application object. For example:

# Get the scene root
a = getattr(Application, "ActiveSceneRoot", False)
print a
print a.Parameters.Count

# Get the selection with the GetValue command
a = getattr(Application, "GetValue", False)
print a
print a( 'SelectionList' )

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s