pythonpycharmautomated-refactoringmethod-signaturefunction-signature

PyCharm: is this kind of automatic signature refactoring possible?


A Python code of a project has a lot of function definitions and calls like:

def some_function(a, b="", c=0, d=None, e="something"):
    # whatever
    pass

some_function("a", "b", 1, e="something else")

This is very hairy (bad practice - missing context, etc) and I would like to automatically change it to:

some_function(a="a", b="b", c=1, e="something else")

(well, the first positional argument can maybe stay as is in some cases)

In many cases, keyword parameters are in a different order, so those can also be arranged according to the function definition order:

def some_method(self, a, b=1, c=2): pass
obj.some_method(a, c=12, b=0) -> obj.some_method(a, b=0, c=12)

Can PyCharm with it's Refactor > Change signature be of any help?

Well, PyCharm does the kw arguments reordering, but does not change positional arguments to keyword arguments (in calls). Is it just current limitation or am I missing some way to do it automatically?


Solution

  • Because Python 3's keyword-only arguments are now supported by PyCharm, you can perform said refactoring by adding * as a first argument in the Change signature dialog.