Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...