Sourcery is now available as a command line interface. This enables several new use cases:
This functionality is only available with Pro/Team subscriptions. If you'd like to try it out for your team please contact us.
The Sourcery command line interface can be installed by running:
pip install sourcery
Once installed you can interactively login with:
sourcery login
which will open up a browser tab and ask for confirmation.
To display suggested refactorings as a diff:
sourcery refactor {file_or_directory}
And to apply those changes to the files:
sourcery refactor --in-place {file_or_directory}
Full documentation is available here.
You can now hover over a method definition to see a quick view of its code quality. The metrics available are:
This can be switched off in the Sourcery section of the plugin settings.
with
context manager to ensure file closureA common way of opening and using files is:
file = open("welcome.txt")
data = file.read()
print(data)
file.close()
However if an exception is thrown in between the file being opened and closed
the call to file.close()
may end up being skipped. By using Python's with
context manager the file is closed for you as soon as the block is exited.
with open("welcome.txt") as file:
data = file.read()
print(data)
list-comprehension
refactoringWe have now extended this refactoring to include an additional case, where
augmented assignment is used to add to the list rather than append
.
The following code:
files = []
for x in file_iterator:
if x[-4:] == ".csv":
files += [x]
will now be refactored as:
files = [x for x in file_iterator if x[-4:] == ".csv"]
if
expression by using or
Often we find ourselves setting a value if it evaluates to True, and otherwise using a default.
currency = args["currency"] if args["currency"] else DEFAULT_CURRENCY
This can be simplified to the following, which is a bit easier to read and
avoids the duplication of args['currency']
.
currency = args["currency"] or DEFAULT_CURRENCY
use-assigned-variable
from re-using properties