explicit self revisited

Peter Maas peter.maas at somewhere.com
Sat Nov 11 16:39:37 EST 2006


The Python FAQ 1.4.5 gives 3 reasons for explicit self (condensed version):

1. Instance variables can be easily distinguished from local variables.

2. A method from a particular class can be called as
   baseclass.methodname(self, <argument list>).

3. No need for declarations to disambiguate assignments to local/instance
   variables.

All these reasons are valid and retained by the following suggestion: let
self be represented by the dot, e.g. replace

class someTest(unittest.TestCase):
    def setUp(self):
        self.ly = yList()
        self.m1 = self.ly[0].message
        self.m2 = self.ly[1].message
        self.m3 = self.ly[2].message

    def testList(self):
        self.assertEqual(len(self.ly),3)
        self.assertEqual(self.m1),"Ho")
        self.assertEqual(self.m2),"HoHo")
        self.assertEqual(self.m3),"HoHoHo")

by

class x(unittest.TestCase):
    def .setUp():
        .ly = yList()
        .m1 = .ly[0].message
        .m2 = .ly[1].message
        .m3 = .ly[2].message

    def .testList():
        .assertEqual(len(.ly),3)
        .assertEqual(.m1),"Ho")
        .assertEqual(.m2),"HoHo")
        .assertEqual(.m3),"HoHoHo")

Methods could still be referenced e.g. as x.testList(someInstance).
The current self syntax could still be valid (for backward compatibility.)
Advantages of the new syntax:

1. Enhanced readability, less verbosity

2. Unambiguous: no need to tell newbies that a virtuous pythoneer
   has to stick to self instead of abbreviate it as s.

3. One argument less for "Python OO bolted on" propaganda.

The second reason is the most important for me. I consider syntax control
by a code of conduct as lame.

The "leading dot" syntax could have further advantages:

class x(object):
    a = ""  # static variable
    .b = 0  # instance variable

This could replace parameterless __init__ methods. Methods without leading
dots could be considered static without a staticmethod decorator. For
backward compatibility this behaviour should be explicitly activated e.g. by
__autostatic__ = true.

What do you think?

-- 
Regards/Gruesse,

Peter Maas, Aachen
E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64')



More information about the Python-list mailing list