Getting rid of "self."

John Roth newsgroups at jhrothjr.com
Fri Jan 7 17:39:07 CET 2005




"BJörn Lindqvist" <bjourne at gmail.com> wrote in message 
news:mailman.293.1105105152.22381.python-list at python.org...
I think it would be cool if you could refer to instance variables
without prefixing with "self." I know noone else thinks like me so
Python will never be changed, but maybe you can already do it with
Python today?

...

It works! exec(magic()) does the needed hi = self.hi. Not so
impressive in this case but much cooler when there is more instance
variables around. But the solution is very ugly because you have to
write exec(magic()) in every method. So I'm asking here if someone
knows a better way, maybe using decorators or metaclasses or other
black magic?

[response]

Having to specify the instance explicitly is something that
Python needs because it isn't a statically typed language.
In a statically typed language, all variables are pre-declared,
so the compiler knows where they all are.

Python's compiler knows about local variables. It
doesn't know where any other variables are, so it
has to search. Including the instance as one of the
method parameters means that the search splits
right at the front: either it starts looking up the
instance, or it goes up the definition chain (usually
empty) to the module namespace and then the
builtins.

Eliminating "self" would mean it would have to
either search the instance before the module and
builtins, or search the module and builtins before
the instance. This is both a performance issue
and a maintenance issue because of the increased
possibility of one shadowing the other.

This is distinct from the issue of how to spell
"self". As another responder has already said,
you can spell it any way you want; it's simply
whatever you choose to call the first paramteter
to the method.

Going the other way, the word "self" could become
a keyword, removing the necessity of specifying it
among the method parameters. While I like the idea,
there's enough dislike of the notion that it's not going
to happen.

John Roth


-- 
mvh Björn 




More information about the Python-list mailing list