For more on this I refer you to the article at Live Code Stream, Make Your Code Great, Python Style which demonstrates a number of these that will elevate your code into more clean and readable code. I also refer you to the Python tutorial and the Python PEP 8 styling guide .
It is advisable to stick naming conventions suggested in the PEP 8 styling guide:
|Function name||lower case; words separated by underscore||function_name|
|Variable names||Same as function names||var_name|
|Constants at module level||All in capital; words separated by underscore||CONST_NAME|
Forming Paths and Strings
I sometimes see code that forms file or directory paths and strings by concatenating them as follows:
a = "something" b = "happened" a + " " + b
A better Pythonic way would be:
" ".join(a, b)
For file and directory paths I see the same approach:
directory_path = "some path to a directory" filename = "filename" fp = directory_path + filename
This might work on one operating system but not on other operating systems. Also this is not the right way to form a path. There are at least two appropriate ways to do so that make this OS-independent:
import os fp = os.path.join(directory_path, filename) # returns a string object
or my preferred method:
from pathlib import Path fp = Path(directory_path).joinpath(filename) # returns a Path object
Using Path allows you to perform other operations without having to write unnecessary code since pathlib provides high-level path objects:
# using os fp = os.path.join(directory_path, filename) os.path.exists(fp) # using Path fp = Path(directory_path).joinpath(filename) fp.exists()
Tip 1: Make use of your editor to help you stick to PEP 8 and other guidelines and best practices. All popular editors are expected to have settings that allow the user to make use of these
Tip 2: Use a linter. Most editors allow you to use a linter.
Tip 2: Use black, the uncompromising code formatter, to automatically format your code as your write it.
Have you faced these before in code you worked on? What other tips or advice would you give?