-1

I'm analyzing some old code that I've inherited, and I have a question about the use of "self" and "None" keywords, specifically in the following example:

def run(self) -> None:

I understand that the self keyword is similar to the "this" keyword in C++ in that, in conjunction with the dot operator, it allows us to access the attributes and methods of the class in question. What I'm really interested in is the use of "-> None" in the declaration of the method named "run." Is this in PEP 8 because I can't find an example. I'm using Python 3.7, in case that matters.

What is the purpose of writing a method in this manner? What does "-> None" do?

Trevor
  • 160
  • 1
  • 12
  • 1
    It is a [PEP-484](https://peps.python.org/pep-0484/) type hint. In short, it tells external typechecker like `mypy` that method `run` returns None. It does not affect runtime and serves as documentation and hint for type validation. – STerliakov May 26 '22 at 17:39
  • 1
    `self` is not a keyword; it's just the conventional name for the parameter which, when the method is invoked by an instance of the class, is bound to that instance. – chepner May 26 '22 at 17:42
  • 1
    `self` is not a keyword. `self` is merely the *conventional name* of the first positional parameter of a method. That parameter is the parameter that will get the instance passed to it as an argument when the method is invoked on the instance. Note, it doesn't matter what that parameter is actually named, you *could* use `this` or `banana` – juanpa.arrivillaga May 26 '22 at 17:44

1 Answers1

1

They're called type hints, and they enable annotating the types of the parameters and return types of functions.

https://peps.python.org/pep-0484/

Tomer Ariel
  • 1,397
  • 5
  • 9
  • 1
    In [How to Answer](https://stackoverflow.com/help/how-to-answer), see the section *Answer Well-Asked Questions*, and therein the bullet point regarding questions that "have been asked and answered many times before". I don't know what the frequency is like now, but for a long time it seemed like we were getting "what is this syntax?" questions about type hints as much as _daily_. – Charles Duffy May 26 '22 at 17:40