Python is a language that is very particular about how and where you place your code. Because of this it is very important to code to the guides properly. Below is some of the style and standards basic. For a full detailed guide you can find links at the end in the additional resources.
A Few Basics
-
Python does not use {} to manage its closures, instead it uses tabs (or 4 spaces). This means that your code needs to be clean and you need to pay attention to context of a given line.
-
Python = signs are copying references to objects and not the object themselves. So if you set a = b and then change a, it also changes b and visa versa.
Importing
-
Only import the modules you need, instead of an entire file.
-
Keep your imports grouped for easy reading (Standard, Third-Party, application) to avoid duplicates.
-
Beware of circular dependencies. Catch all utility files (That should be split into more specific files) are a common culprit of this.
-
Use the full package name, not relative names in imports.
Errors and Logging
-
Use the build exceptions. For 95% of cases, there is a built in exception that will meet your needs. Exceptions can be wrapped but should rarely need to be created from the base class.
-
Use the standard Python logging library. The print command is ok for some quick debugging, but the logging library will ensure that the logs can be output an stored regardless of where the application is being run.
-
Avoid catching all errors when possible, unless you are re-throwing the error.
-
Make your try catch blocks small, that will help catch specific errors, and use finally blocks to ensure objects and connections are cleaned up.
Quotes
-
Use single quotes as your first option
-
Use double quotes when the string contains and single quote, this is easier to read than the escaped string
-
Use triple quotes for multi-line strings.