the annoying, verbose self

John Machin sjmachin at lexicon.net
Sat Nov 24 01:46:58 CET 2007


On Nov 24, 10:54 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:

[snip]
>
> The correct solution to your example is to get rid of the attribute
> lookups from the expression completely:

"correct" in what sense?
>
> def abs(self):
>     x, y, z = self.x, self.y, self.z
>     return math.sqrt(x**2 + y**2 + z**2)
>
> It's probably also faster, because it looks up the attributes only once
> each, instead of twice.

Faster still is possible, without any cruft:

>>> def abs1(self):
...     x, y, z = self.x, self.y, self.z
...     return math.sqrt(x**2 + y**2 + z**2)
...
>>> def abs2(self):
...     return math.sqrt(self.x**2 + self.y**2 + self.z**2)
...
>>> import dis
>>> dis.dis(abs1)
  2           0 LOAD_FAST                0 (self)
              3 LOAD_ATTR                0 (x)
              6 LOAD_FAST                0 (self)
              9 LOAD_ATTR                1 (y)
             12 LOAD_FAST                0 (self)
             15 LOAD_ATTR                2 (z)
             18 ROT_THREE
             19 ROT_TWO
             20 STORE_FAST               1 (x)
             23 STORE_FAST               2 (y)
             26 STORE_FAST               3 (z)

  3          29 LOAD_GLOBAL              3 (math)
             32 LOAD_ATTR                4 (sqrt)
             35 LOAD_FAST                1 (x)
             38 LOAD_CONST               1 (2)
             41 BINARY_POWER
             42 LOAD_FAST                2 (y)
             45 LOAD_CONST               1 (2)
             48 BINARY_POWER
             49 BINARY_ADD
             50 LOAD_FAST                3 (z)
             53 LOAD_CONST               1 (2)
             56 BINARY_POWER
             57 BINARY_ADD
             58 CALL_FUNCTION            1
             61 RETURN_VALUE
>>> dis.dis(abs2)
  2           0 LOAD_GLOBAL              0 (math)
              3 LOAD_ATTR                1 (sqrt)
              6 LOAD_FAST                0 (self)
              9 LOAD_ATTR                2 (x)
             12 LOAD_CONST               1 (2)
             15 BINARY_POWER
             16 LOAD_FAST                0 (self)
             19 LOAD_ATTR                3 (y)
             22 LOAD_CONST               1 (2)
             25 BINARY_POWER
             26 BINARY_ADD
             27 LOAD_FAST                0 (self)
             30 LOAD_ATTR                4 (z)
             33 LOAD_CONST               1 (2)
             36 BINARY_POWER
             37 BINARY_ADD
             38 CALL_FUNCTION            1
             41 RETURN_VALUE
>>>

HTH,
John



More information about the Python-list mailing list