Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I denote unused function arguments?

When "deconstructing" a tuple, I can use _ to denote tuple elements I'm not interested in, e.g.

>>> a,_,_ = (1,2,3) >>> a 1 

Using Python 2.x, how can I express the same with function arguments? I tried to use underscores:

>>> def f(a,_,_): return a ...   File "<stdin>", line 1 SyntaxError: duplicate argument '_' in function definition 

I also tried to just omit the argument altogether:

>>> def f(a,,): return a   File "<stdin>", line 1     def f(a,,): return a         ^ SyntaxError: invalid syntax 

Is there another way to achieve the same?

like image 367
Frerich Raabe Avatar asked Apr 05 '12 09:04

Frerich Raabe


People also ask

What does unused argument mean in Python?

The “unused argument error in r” message is caused by a mistake in the code when entering an argument or object such as a data frame, vector, or matrix into a base r function. It is not a case of missing values or data but rather a variable that is not expected as an additional argument.

How do you handle unused variables in Python?

To suppress the warning, one can simply name the variable with an underscore ('_') alone. Python treats it as an unused variable and ignores it without giving the warning message.

What is the syntax for a function with arguments?

When one piece of code invokes or calls a function, it is done by the following syntax: variable = function_name ( args, ...); The function name must match exactly the name of the function in the function prototype. The args are a list of values (or variables containing values) that are "passed" into the function.

How do you separate arguments in a function?

The maximum number of arguments (and corresponding parameters) is 253 for a single function. Arguments are separated by commas. However, the comma is not an operator in this context, and the arguments can be evaluated by the compiler in any order. There is, however, a sequence point before the actual call.


1 Answers

A funny way I just thought of is to delete the variable:

def f(foo, unused1, unused2, unused3):     del unused1, unused2, unused3     return foo 

This has numerous advantages:

  • The unused variable can still be used when calling the function both as a positional argument and as a keyword argument.
  • If you start to use it later, you can't since it's deleted, so there is less risk of mistakes.
  • It's standard python syntax.
  • PyCharm does the right thing! (As of 2020, PyCharm no longer does the right thing :( tracking this at https://youtrack.jetbrains.com/issue/PY-39889 )
  • PyLint won't complain and using del is the solution recommended in the PyLint manual.
like image 67
boxed Avatar answered Sep 19 '22 22:09

boxed