Pylint: keyword-arg-before-vararg should not be raised with python2

Created on 12 Jan 2018  路  4Comments  路  Source: PyCQA/pylint

Steps to reproduce

  1. In python 2 define a function like:
def test(a, b=1, c=2, *args, **kwargs):
    print(args)
  1. With pylint 1.8.1 you will get the following error.
Keyword argument before variable positional arguments list in the definition of test function (keyword-arg-before-vararg)
  1. However, the solution is a python2 SyntaxError:
def test(a, *args, b=1, c=2, **kwargs):
    print(args)

Current behavior

As per 1.8.1 release notes:

A new check was added, keyword-arg-before-vararg.
This warning message is emitted when a function is defined with a keyword argument appearing before variable-length positional arguments (*args). This may lead to args list getting modified if keyword argument's value is not provided in the function call assuming it will take default value provided in the definition.

Expected behavior

I think this warning shouldn't be raised in python2.

pylint --version output

pylint --version
Using config file /ifs/work/leukgen/home/s/repos/toil_battenberg/.pylintrc
pylint 1.8.1, 
astroid 1.6.0
Python 2.7.11 (default, Jan 11 2016, 13:50:06) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-16)]

Most helpful comment

While the solution is a syntax error in Python 2, the code is still faulty as per the description of the message. There will be no way to pass b as keyword argument and pass extra positional args as well. IMO, this function signature should be just changed.

All 4 comments

While the solution is a syntax error in Python 2, the code is still faulty as per the description of the message. There will be no way to pass b as keyword argument and pass extra positional args as well. IMO, this function signature should be just changed.

@PCManticore hey thanks so much! you are right

@PCManticore what if I want the b and c parameters to have default values, but I also want the function to take arbitrary number of arguments? E.g. whenever I need these arguments, because a decorator that uses that definition requires it?

It's not a great solution because the defaults aren't included in the function signature but I would do the following in this case:

kwargs.setdefault('b', 1)
kwargs.setdefault('c', 2)

It's not ideal, but mixing keyword arguments and variable arguments can get messy really quickly. So I think that using setdefault is a better solution, especially if you document the new default value in the docstring.

This is a matter of opinion though so feel free to add a new option to cover this case. The 1.9 branch is where the Python 2 compatible version exists.

Was this page helpful?
0 / 5 - 0 ratings