How to avoid explicit 'self' in Python?

Viewed 66761

I have been learning Python by following some pygame tutorials.

Therein I found extensive use of the keyword self, and coming from a primarily Java background, I find that I keep forgetting to type self. For example, instead of self.rect.centerx I would type rect.centerx, because, to me, rect is already a member variable of the class.

The Java parallel I can think of for this situation is having to prefix all references to member variables with this.

Am I stuck prefixing all member variables with self, or is there a way to declare them that would allow me to avoid having to do so?

Even if what I am suggesting isn't pythonic, I'd still like to know if it is possible.

I have taken a look at these related SO questions, but they don't quite answer what I am after:

11 Answers

Python requires specifying self. The result is there's never any confusion over what's a member and what's not, even without the full class definition visible. This leads to useful properties, such as: you can't add members which accidentally shadow non-members and thereby break code.

One extreme example: you can write a class without any knowledge of what base classes it might have, and always know whether you are accessing a member or not:

class A(some_function()):
  def f(self):
    self.member = 42
    self.method()

That's the complete code! (some_function returns the type used as a base.)

Another, where the methods of a class are dynamically composed:

class B(object):
  pass

print B()
# <__main__.B object at 0xb7e4082c>

def B_init(self):
  self.answer = 42
def B_str(self):
  return "<The answer is %s.>" % self.answer
# notice these functions require no knowledge of the actual class
# how hard are they to read and realize that "members" are used?

B.__init__ = B_init
B.__str__ = B_str

print B()
# <The answer is 42.>

Remember, both of these examples are extreme and you won't see them every day, nor am I suggesting you should often write code like this, but they do clearly show aspects of self being explicitly required.

Actually self is not a keyword, it's just the name conventionally given to the first parameter of instance methods in Python. And that first parameter can't be skipped, as it's the only mechanism a method has of knowing which instance of your class it's being called on.

You can use whatever name you want, for example

class test(object):
    def function(this, variable):
        this.variable = variable

or even

class test(object):
    def function(s, variable):
        s.variable = variable

but you are stuck with using a name for the scope.

I do not recommend you use something different to self unless you have a convincing reason, as it would make it alien for experienced pythonistas.

yes, you must always specify self, because explicit is better than implicit, according to python philosophy.

You will also find out that the way you program in python is very different from the way you program in java, hence the use of self tends to decrease because you don't project everything inside the object. Rather, you make larger use of module-level function, which can be better tested.

by the way. I hated it at first, now I hate the opposite. same for indented-driven flow control.

self is part of the python syntax to access members of objects, so I'm afraid you're stuck with it

Here I follow the idea from the answer by @argentum2f to copy the attributes. This can be automated by a decorator and it works with Python 3. Of course copying the attributes means that they cannot be changed, hence the name @const_self for the decorator.

With @const_self you define a method with first arguments that have the same names as the attributes you want to use — and no self.

from cmath import sqrt

def const_self(fun):
    fun_args = fun.__code__.co_varnames[:fun.__code__.co_argcount]

    def fun_with_self(*args, **kwargs):
        self = args[0]
        other_args = list(args[1:])

        used_attributes = [arg for arg in fun_args if hasattr(self, arg)]
        self_args = [getattr(self, attr) for attr in used_attributes]

        return fun(*(self_args + other_args), **kwargs)

    return fun_with_self

class QuadraticEquation:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    @const_self
    def roots(a, b, c, dummy, lazy = False):
        print("Dummy is", dummy)
        if lazy: return # A lazy calculator does not calculate
        return (-b - sqrt(b**2 - 4*a*c)) /2/a, (-b + sqrt(b**2 - 4*a*c)) /2/a

Of course a lot should be improved in that code: At least it fails if you define a method like def fun(a, dummy, b, c): print(a,b,c) here and it does not preserve the docstring. But I think it demonstrates the idea well enough.

Related