One thing I’ve often noticed when implementing interfaces from third party libraries in Python is that I can’t explicitly state that I won’t be using several function parameters.
For example, if I make a custom parameter type in the excellent Click library:
class Package(ParamType):
def convert(
self,
value: Any,
_: Optional[click.Parameter],
_: Optional[click.Context]
) -> str:
if str(value) in self.packages():
return str(value)
# More stuff...
self.fail(f"Unrecognized package: {value!r}")
This crashes with:
SyntaxError: duplicate argument ‘_’ in function definition
Using an underscore as a parameter name or variable name is a common and accepted way to communicate that a value won’t be used. For example, this is a common usage of destructuring statements:
_, _, three = (1, 2, 3)
That’s why it seems to me both intuitive and useful if Python allowed multiple function parameters with the same name, as long as that name is “_” (underscore).
What do other people think?
Are there any downsides to this, other than potentially being difficult to implement?
I know there are other workarounds for this issue, but they all seem really awkward and verbose, definitely not Pythonic.
Just use *_
This would work for this specific scenario, but it’s highly situational and it’s ugly to boot.
Prefix with underscore
Use variable names like “_param” and “ctx". This is not as clear as naming the parameter "”. It’s also not as well supported by tools, pyright-langserver still complains about unused parameters, unlike with a plain underscore.
Immediately delete the parameters
Like:
def convert(
self, value: Any, param: Optional[click.Parameter], ctx: Optional[click.Context]
) -> str:
del param # Not used
del ctx # Not used
# ...
This has the advantage that the value is technically used (since it’s part of a del statement) and tools won’t complain, and it can’t accidentally be used later. However, I still find this verbose and awkward, not Pythonic.