the annoying, verbose self

samwyse samwyse at gmail.com
Sat Nov 24 10:55:38 CET 2007


On Nov 23, 7:16 pm, "Patrick Mullen" <saluk64... at gmail.com> wrote:
> Most of the time self doesn't bother me in the slightest.  The one
> time it does bother me however, is when I am turning a function into a
> method.  In this case, often I have many local variables which I
> actually want to be instance variables, so I have to add self to all
> of them.  Of course, this is going to cause me some grief no matter
> which language I am using.  If it was enough trouble, it wouldn't be
> hard to make a filter that converts my code automatically.

I've had the same thought, along with another.  You see, on of my pet
peeves about all OO languages that that when creating new code, I
generally begin by writing something like this:

cat = 'felix'
dog = 'rover'
def example():
  global cat, dog  # not always required, but frequently needed
  return ', '.join((cat, dog))

Later, I inevitably decide to encapsulate it inside a class, which
means lots of source changes to change my function into a method:

class my_pets:
  cat = 'felix'
  dog = 'rover'
  def example(self):
    return ', '.join((self.cat, self.dog))

My idea is to introduce syntax that treats top-level functions as
methods of a global, anonymous, class:

cat = 'felix'
dog = 'rover'
def example():
  return ', '.join((.cat, .dog))

(btw, we'll also stop auto-magically recognizing global variables
inside functions, forcing the use of the '.' in global names.)  Thus,
to convert the above into a class, we just need to add one line and
alter the indentation:

class my_pets:
  cat = 'felix'
  dog = 'rover'
  def example():  # anonymous 'self' is implicit inside class defs.
    return ', '.join((.cat, .dog))

You'd need someway to refer to higher lexical levels, possibly by
chaining periods; this would break ellipsis but that could be replaced
by a keyword such as 'to'.  And you'd probably want to keep 'global',
but as a keyword for those rare cases where you need to force a
reference to the outer-most lexical level:

warming = 42
def generator(factiod):
    def decorator(func):
        def wrapper(*args, **kwds):
            if ..factoid == None:
              return .func(*args, **kwds)
            else:
              return ..factoid + global.warming
        return wrapper
    return decorator





More information about the Python-list mailing list