What are the most common improvements of Python code you've applied or seen applied (to you or someone else) here on codereview?
|
Looking through my own reviews, I'd say that the two issues that come up almost every time are:
The third most common problem is probably inappropriate choice of data structures and algorithms (for example, trying to write a parser without a lexer). But that's not really specific to Python. |
||||
|
Have as little code as possible in the global namespace. Most logic should be in functions, classes, or methods. This helps prevent polluting the global namespace and will run faster. On a related note, the main function should look something like this:
This is to avoid the globally-defined things, e.g. |
||||
|
LoopsIn python you should rarely use Don't write
instead write:
Don't write
Write
Don't write
Write
|
|||||||||||||
|
file handlingInstead of closing files yourself, have the
and not:
Beyond saving you to have to close the file manually, the
|
|||||
|
Consider this:
This should be written as:
That is, you don't need to put stuff in brackets. |
||||
|
PEP 8 -- Style Guide for Python CodeTo follow a standard coding style is very important. It's even more important if you want other people to look at your code. By following the official coding style guide your code will be more readable and it will be way more easy for others programmers to understand it. You should really read PEP8, it may seem long, but it's just a bunch of rules, the sooner you'll start to follow them, the better will be. Anyway this is an attemp to summarize the most "overlooked" ones: 1) IndentionUse 4 spaces per indentation level and never mix tabs and spaces. 2) Maximum Line LengthLimit all lines to a maximum of 79 characters. 80 is okey too. 3) Leave a space around the operators:Yes:
No:
4) Documention stringsConventions for writing good documentation strings (a.k.a. "docstrings") are immortalized in PEP 257, so take a look at that one too. Anyway in brief:
I don't want to make this section too complex, so other than PEP 257 you can find more in the google guidelines, at this example of pypi project, and this SO question: Docstrings - one line vs multiple line. Note: If a docstring become too complex to write/read/follow it's usually a sign that the function need to be refactored in two or more simple ones. 5) Naming ConventionsYou should read them all, anyway here's a small summary of the most common ones:
|
|||||||
|
Naming:
|
||||
|