the annoying, verbose self

Patrick Mullen saluk64007 at gmail.com
Sat Nov 24 04:01:11 EST 2007


Ton Van Vliet:
> [... using/with ...]

This looks like a really nice little construct, and solves my small
quirk issue (which has popped up maybe twice in my python experience).
 It could also be a solution to the OP's problem.  The issue of course
is disambiguation.  Is EVERY name looked up in the tagged object, or
only assignments?  Does it copy attributes over and make everything
local and then copy it back at the end (like you would kind of expect
in a function)?  Or is everything routed to the parent.  It gets very
sticky very fast, but since it's in a block, the issues aren't as evil
as when they show up if you try to get rid of self altogether.  It
also solves more than just the self issue, allowing you to more
quickly assign multiple attributes of an object as well.

In your example:

def somefunction(self, ...):
   using self:
       a = ...
       b = ...
       ...
       c = a + b

The biggest issue is, what if you need to do more:

def somefunction(self, ...):
   using self:
       a = ...
       b = ...
       c = a + int(b)

What is int?  Is it self.int?  I suppose the simplest solution is to:
always assign as an attribute, and lookup as an attribute first going
to normal lookup rules after that.

As far as using [xxx], I don't think the interpreter needs to deal
with [xxx] until it actually executes the line.  [xxx] would just be a
normal python expression, the result of which is used for the
attribute lookup and assignments within the block.

This would somewhat solve the toy vector example:

def abs(self):
   using self:
      return math.sqrt(x*x + y*y + z*z)

Unfortunately the performance would be slightly worse do to the extra
lookup rules (self.math? no, self.__getattr__(math)? no,
self.parentclass.__getattr__(math)? no, etc)

The OP will probably say, "why not build the [using self] block into a
method definition":

def abs():
   return math.sqrt(x*x .....

But this would cause problems and slowdown for pretty much all python
code in existence, and reopens the whole discussion of why removing
self is bad :)

Anyway, I'm for the "using" construct, as unlikely as it is.  It's not
necessary, but something similar could help alleviate a bit of the
tedium that is perceived by some python users, without affecting
anyone else.

Of course, this is all theory, and it's unknown (by me) if the python
compiler can even handle such a thing.  Even if it could, it's
probably not an easy task.



More information about the Python-list mailing list