Python style guide
Writing clean and maintainable code is a major goal for any large python projects and become very important as the team size grows.
PEP8 and Pylint: Python projects should be complaint with pep8 and pylint.
PEP8:
To check whether your code is pep8 complaint you need to run the pep8 checker. Not all the pep8 checks are necessary for your code; sometimes it makes sense to disable some of the pep8 checks and it can be done using the configuration file pep8_config.
A sample pep8 configuration be can be found here.
# Install pep8
pip install pep8pep8 --config=/path/to/pep8_config --statistics /path/to/input_file.py
Pylint:
To check whether your code is pylint complaint you need to run the pylint checker. Also, not all the pylint check may be necessary for your project and you can disable some of the pylint checks using a configuration file.
A sample pylint configuration file can be found here.
# Install pylint
pip install pylintpylint --rcfile=/path/to/pylintrc /path/to/input_file.py
Automating pep8 and pylint formating using YAPF:
There are many code auto-formatters are available for python project. One of the most useful and convenient formatter is YAPF developed by Google.
As per the project requirement you can set the auto-formatter style setting using a .style.yapf file.
A sample style file can found here.
You can auto-format your code as follows,
# Install yapf
pip install yapfyapf --style=/path/to/.style.yapf /path/to/input_file.py
Not all of the pylint checks can be auto-formatted:
Sometime you will need to manually fix pylint errors. Also in some cases pylint check can be disabled in your code for some specific cases without disabling globally in the .pylintrc file.
# pylint: disable=<pylint_check_name>For example, for the following function with many arguments when you run the pylint check you will get an error too-many-arguments , if you function really needs those args you can disable that check for this particular function.
# pylint: disable=too-many-arguments
def test(a,b,c,d,e,f,g,h,i,j,k,l,m):
...
...
return ...Thats all, happy clean coding.