PyCharm - how to rename all identifiers in project

2019-07-26 06:55发布

问题:

I have a pretty large project in Python (little over 3000 lines) and unfortunately, the syntax doesn't respect PEP8, which is needed now. I'm looking especially for the way of renaming all the functions from camelCase style to snake_case style.

So far I've only found this answer, which rejects the possibility of renaming all variable automatically in PyCharm and suggests doing it manually, which I don't want to because there are thousands of variables in the code.

So, is there a way, how to rename all the variables automatically according to the rule above?

I'm not interested in functions/regexes, which do it for one string, I'm really only interested in the "collective" solution.

回答1:

You can try camel-snake-pep8, as from official description:

A refactoring tool to help convert camel case to snake case and vice versa in a Python program, in conformity with the PEP-8 style guide. It uses/abuses Python-Rope to find and perform the changes. The program interactively displays proposed changes and queries the user as to whether or not to accept the changes.

To install run these commands:

$ <activate your virtual environment>
$ pip install rope colorama
$ wget https://raw.githubusercontent.com/abarker/camel-snake-pep8/master/src/camel_snake_pep8/camel_snake_pep8.py

After that go to the project's folder and run this command:

$ python2 camel_snake_pep8.py . *.py

The program can be used to refactor either Python 2 or Python 3 code but it must be run with Python 2. This is because, as of Mar. 2017, Python-Rope only supports Python 2 (a Python 3 version is said to be in progress). Sometimes this won't work, because of specific syntax for python 3, e.g.:

def pick(l: list, index: int) -> int:
    return l[index]

In this case you have to make syntax of such expressions compatible with python2. Please, vote/help rope project's issue to support python3.