# the annoying, verbose self

Kay Schluehr kay.schluehr at gmx.net
Sat Nov 24 05:48:06 CET 2007

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

> The correct solution to your example is to get rid of the attribute
> lookups from the expression completely:
>
> 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
>
> --
> Steven.

I like this pattern but less much I like the boilerplate. What about
an explicit unpacking protocol and appropriate syntax?

def abs(self):
x, y, z by self
return math.sqrt(x**2 + y**2 + z**2)

expands to

def abs(self):
x, y, z = self.__unpack__("x","y","z")
return math.sqrt(x**2 + y**2 + z**2)

This would have another nice effect on expression oriented programming
where people use to create small "domain specific languages" using

x,y,z by Expr

class Expr(object):
def __init__(self, name):
self.name = name
self._sexpr = ()

def __unpack__(self, *names):
if len(names)>1:
return [Expr(name) for name in names]
elif len(names) == 1:
return Expr(names[0])
else:
raise ValueError("Nothing to unpack")

e = Expr("")
e._sub = ('+',(self, other))
return e

def __repr__(self):
if self._sexpr:
return self._sexpr[0].join(str(x) for x in self._sexpr[1])
return self.name

>>> x,y by Expr
>>> x+y
x+y
>>> 4+x
4+x

```