Tool for fixing trivial problems with your code.
Project description
pybetter
Tool for fixing trivial problems with your code.
Originally intended as an example for my PyCon Belarus 2020 talk about LibCST.
Usage
Simply provide a valid Python source code file as one of the argument and it will try to fix any issues it could find.
Usage: pybetter [OPTIONS] [SOURCES]...
Options:
--noop Do not make any changes to the source files.
--help Show this message and exit.
Example
# cat test.py
def f():
return (42, "Hello, world")
# pybetter test.py
--> Processing 'test.py'...
[+] (B003) Remove parentheses from the tuple in 'return' statement.
All done!
# cat test.py
def f():
return 42, "Hello, world"
Available fixers
-
B001: Replace 'not A in B' with 'A not in B'
Usage of
A not in B
overnot A in B
is recommended both by Google and PEP-8. Both of those forms are compiled to the same bytecode, but second form has some potential of confusion for the reader.# BEFORE: if not 42 in counts: sys.exit(-1) # AFTER: if 42 not in counts: sys.exit(-1)
-
B002: Default values for
kwargs
are mutable.As described in [Common Gotchas] (https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments) section of "The Hitchhiker's Guide to Python", mutable arguments can be a tricky thing.
This fixer replaces any default values that happen to be lists or dicts with None value, moving initialization from function definition into function body.
# BEFORE def p(a=[]): print(a) # AFTER def p(a=None): if a is None: a = [] print(a)
Be warned, that this fix may break code which intentionally uses mutable default arguments (e.g. caching).
-
B003: Remove parentheses from the tuple in 'return' statement.
If you are returning a tuple from the function by implicitly constructing it, then additional parentheses around it are redundant.
# BEFORE: def hello(): return ("World", 42) # AFTER: def hello(): return "World", 42
Installation
# pip install pybetter
Getting started with development
# git clone https://github.com/lensvol/pybetter
# poetry install
License
This project is licensed under the MIT License - see the LICENSE file for details
Authors
- Kirill Borisov (lensvol@gmail.com)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.