How can I denote unused function arguments?

梦想的初衷 提交于 2019-11-28 18:31:52

Here's what I do with unused arguments:

def f(a, *unused):
    return a

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!
  • PyLint won't complain and using del is the solution recommended in the PyLint manual.

The underscore is used for things we don't care about and the * in *args denotes a list of arguments. Therefore, we can use *_ to denote a list of things we don't care about:

def foo(bar, *_):
    return bar

It even passes PyCharm's checks.

You can use '_' as prefix, so that pylint will ignore these parameters:

def f(a, _b, _c):

If you have both args and keyword arg you should use

def f(a, *args, **kwargs):
    return a

I think the accepted answer is bad, but it can still work, if you use what I should call "Perl way" of dealing with arguments (I don't know Perl really, but I quit trying to learn it after seeing the sub syntax, with manual argument unpacking):

Your function has 3 arguments - this is what it gets called with (Duck typing, remember?). So you get:

def funfun(a, b, c):
    return b * 2

2 unused parameters. But now, enter improved larsmans' approach:

def funfun(*args):
    return args[1] * 2

And there go the warnings...

However, I still enjoy more the boxed's way:

def funfun(a, b, c):
    del a, c
    return b * 2

It keeps the self-documenting quality of parameter names. They're a feature, not a bug.

But, the language itself doesn't force you there - you could also go the other way around, and just let all your function have the signature (*args, **kwargs), and do the argument parsing manually every time. Imagine the level of control that gives you. And no more exceptions when being called in a deprecated way after changing your "signature" (argument count and meaning). This is something worth considering ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!