As a software developer, we should always strive to maintain good code quality by following best practices or standards. This is to ensure that the code delivered to solve a problem is readable and maintainable in the long run. To quote Guido van Rossum, “Code is read much more often than it is written.” which pretty much sums up a software developer’s day! 😄
Here, I will try to summarize some of the practices which I have learnt & followed while working with Python programming language
One of the utmost important thing in any programming language is naming. From naming variable, methods and pretty much everything, It sometimes takes a good amount of time just to come up with a good name!
Naming conventions (PEP-8)
- Variables, functions, methods, packages, modules: this_is_a_variable (Snake-case)
- Classes and exceptions: CapWords (Pascal case)
- Protected methods and internal functions: _single_leading_underscore
- Private methods: __double_leading_underscore
- Constants: CAPS_WITH_UNDERSCORES (All caps)
General best practices
- Maintain all dependencies in requirement.txt file for the lambda
- Maintain all constants in constants.py file for the lambda
- Null check before accessing values and Checking against None (very important). For e.g.
if data["state"] == "fixed":
if data and data["state"] == "fixed":
4. Method annotation with expected return type to enforce types. For e.g.
def circumference(radius: float) -> float:
5. Do not use hard-coded strings.use constants instead.
"google.com" in link:
google_link in link:
6. Avoid using messy nested if-else. Use switcher instead if possible.
7. Use constants or enums in-place of magic numbers.
8. Never Ignore the Exceptions you catch! Errors should never pass silently.
catch Exception as ex:
9. Cache/Store frequently used values.
10. Use conditional checks to check against whitelist of conditions.
11. Document __init__ methods in the doc-string for the class.
12. Use getters and setters instead of directly accessing globals and privates
>>> class C:
… def x(self):
… return self.__x
… def x(self, value):
… self.__x = value
13. Use String interpolation or String Templating library to avoid security issues.
14. use ‘in’ and == cautiously for string comparisons.
15. For Reading and Writing to a File, Use With Statement Context Managers as it manages the closing the file handle for you.
These are just some of the practices and there are so much more, if you want to learn more then I recommend to go through the PEP-8 styling guide mentioned in the good reads below. Hope you find this article helpful. Thanks for reading! 😃
Some other good reads -