Naming the self parameter something else

Question:

In Python, this code is valid:

class A:

    def __init__(me):
        me.foo = 17

    def print_foo(myself):
        print(myself.foo)

    def set_foo(i, v):
        i.foo = v

As you might already have noticed, the self parameter is named me in the __init__ method, myself in the print_foo method and i in the set_foo method.

Is there a situation in which naming the self parameter something other than self is useful? If not, why does Python allow this, as it is certainly a way to write a code that is difficult to read and to maintain, and also a source of confusion?

Asked By: julienc

||

Answers:

The self parameter is really only named self by convention, and that isn’t even a universally accepted convention – I also often see cls or this used instead.

The term self isn’t a keyword in python like it is in, say, Java. The user can choose to name it anything they want – although it would be better to choose one name and stick with that throughout the code for clarity, there isn’t anything stopping you from naming it something different in every method.

Answered By: Triggernometry

This blog post by Guido van Rossum explains a little around the subject. Specifically:

I see no reason with this proposal to make ‘self’ a reserved word or to require that the prefix name be exactly ‘self’.

It is just a convention, and it is nice to stick with it.

Answered By: Martin Hallén

PEP 8 addresses this pretty clearly:

Always use self for the first argument to instance methods.

Always use cls for the first argument to class methods.

Although remember that being the python style guide this is not enforced

However, know when to be inconsistent — sometimes style guide
recommendations just aren’t applicable. When in doubt, use your best
judgment. Look at other examples and decide what looks best.

Sometimes, like in fractions.py in the standard library, it might be clearer to you to use something like a,b instead of self,other because <your specific reasons>

the style guide actually lists a few reasons you might break usual convention right below the above quote:

Some other good reasons to ignore a particular guideline:

  1. When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.
  2. To be consistent with surrounding code that also breaks it (maybe for historic reasons) — although this is also an opportunity to clean
    up someone else’s mess (in true XP style).
  3. Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.
  4. When the code needs to remain compatible with older versions of Python that don’t support the feature recommended by the style guide.

The first part of your question is: “Is there a situation in which naming the self parameter something other than self is useful?” I don’t know of any really compelling cases, but even if someone comes up with the perfect example, they’re rare enough that I wouldn’t look to them as the reason for this design choice: Normal use is far more important than very occasionally having to use self in an unintuitive way. (Note that enforcing the name self would not prevent anyone from getting anything done; it’s just a name.)

So why does python allow this? There are two issues here: Why require self to be explicitly listed among the arguments (which gives us the opportunity to choose another name), and why not make self into a keyword, like this in certain other languages.

Why it’s not a keyword is pretty clear: The designers of python always try to minimize the number of reserved words in the language (to the point of making every effort to reuse already reserved words when new syntax is introduced, e.g. with yield from, from ... import, and while ... else). So if something could reasonably be implemented without being a reserved word, it is.

Once it was decided that self is not a keyword, but a special identifier, how do you make it special? Making it suddenly appear in the locals() dictionary of every class method would introduce “magic” behavior that is again undesirable: “Explicit is better than implicit.” So, self is introduced by declaring in the method signature, and the only special behavior is that this first argument is bound to the object whose method we call. This made it easy to support static and class methods through decorators, without adding special syntax to language. (As this post by Guido explains, “it’s trivial to write a decorator that implements @classmethod or @staticmethod in pure Python.”) So once the language was designed this way, there’s really no going back.

Answered By: alexis
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.