Naming the self parameter something else
Asked Answered
R

4

7

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?

Restaurant answered 17/6, 2016 at 15:32 Comment(6)
Because PEP-20. "Explicit is better than implicit", so you don't want a magic self that just appears, and "special cases aren't special enough to break the rules", so if it's an explicit parameter you are able to assign it whatever name you like.Unceasing
"If not, why does Python allow this," because not allowing it would be a really silly restriction.Homothallic
see #2710321Prat
"why does Python allow this" Then why stop there? I can also create a function with the name subtract that sums two numbers. This will also be a source of confusion yet Python allows that.Seeker
@Seeker And I could have also written myself = self and not asked the question :-)Restaurant
A single function can served as both an instance method and a class method, which precludes requiring a specific name when the function is first defined. class A: pass; def foo(first): pass; A.inst = foo; A.cls = classmethod(foo) creates a class with (trivial) instance and class methods that are implemented using the same underlying function object.Rosendorosene
H
4

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.
Homothallic answered 17/6, 2016 at 15:50 Comment(0)
N
3

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.

Nerissanerita answered 17/6, 2016 at 15:46 Comment(0)
S
3

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.

Scouring answered 17/6, 2016 at 16:4 Comment(0)
T
0

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.

Troth answered 17/6, 2016 at 15:39 Comment(2)
Note that you see cls where the first parameter is a class not an instance (see e.g. https://mcmap.net/q/47564/-difference-between-39-cls-39-and-39-self-39-in-python-classes/3001761), and this where whoever wrote the code is a monster. "that isn't even a universally accepted convention" - it's in the official style guide and everything.Unceasing
To elaborate, just as self is the convention for naming the first argument of instance methods, cls is the convention for naming the first argument of class methods.Seeker

© 2022 - 2024 — McMap. All rights reserved.