views:

40

answers:

1

In python, I know that looking up a locally scoped variable is significantly faster than looking up a global scoped variable. So:

a = 4
def function()
    for x in range(10000):
        <do something with 'a'>

Is slower than

def function()
    a = 4
    for x in range(10000):
        <do something with 'a'>

So, when I look at a class definition, with an attribute and a method:

class Classy(object):
    def __init__(self, attribute1):
        self.attribute1 = attribute1
        self.attribute2 = 4
    def method(self):
        for x in range(10000):
            <do something with self.attribute1 and self.attribute2>

Is my use of self.attribute more like my first or second function? What about if I sub class Classy, and try to access attribute2 from a method in my sub class?

+1  A: 

Locally scoped variables are fast because the interpreter doesn't need to do a dictionary lookup. It knows at compile-time exactly how many local variables there will be and it creates instructions to access them as an array.

Member attributes require a dictionary lookup, so they execute similar to your first example using globally scoped variables.

For speed, you can do something like:

attribute1 = self.attribute1
# do stuff with attribute1

which shadows attribute1 in a local variable, so only a single dictionary lookup is needed. I wouldn't bother unless I'd done some profiling indicating that a method was a bottleneck, though.

Daniel Stutzbach
While I was curious about the answer to this question generally, the real reason I was asking it was because I have a number of constants that will almost certainly be used by only one method, and I wasn't sure if I should define them within that method, or within init (in case I later realize they need to be accessed elsewhere). Since that possibility is remote, I think I'll be defining them in the method. Thanks.
Wilduck