townie
townie

Reputation: 322

What is the point of _=None in method python method signature?

What is the purpose of _=None in a method signature?

Example:

def method(_=None): 
    pass

Upvotes: 2

Views: 1023

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295472

_ is a conventional name for an unused placeholder variable in Python (and shell, and some other languages).


When not in the context of a class (that is, when defining a function rather than a method), this would define a function with a single optional (keyword) argument (defaulting to None), with a name indicating that that argument is deliberately unused (and exempting it from warnings about unused variables in some static-checking tools).

When defining a method where the first and only argument accepted is defined in this way, this becomes effectively a poor man's static method. That is to say, it's indicating that self is unused and optional, and allowing the method to be called independently of whether any object instance is associated (that is, whether a self is actually available at runtime).

Note that this is not common idiom, and using the @staticmethod decorator is going to make much more sense to readers of your code.

Upvotes: 4

Related Questions