How do you code well in python?
All veteran Python developers (Pythonistas) preach about writing Pythonic code. If you're someone who has spent some time writing Pythonic code, you will have come across the best practices. But what exactly is Pythonic code, and how should you remember the major pain points/avoid obvious (bad) practices? Show
Fortunately, the Python community is blessed with a relatively simple and complete set of code style guidelines and "Pythonic" idioms. These are one of the key reasons for the high readability of Pythonic code. Readability and simplistic syntax is at the heart of Python. In this post, we are going to talk about a few very important style guidelines and Pythonic idioms, and how to deal with legacy code. One Statement of Code per LineIf you're writing disjointed statements in a single line, you're violating the essence of Python. The only exception is list comprehensions and a few other compound statements. These are allowed and accepted for their brevity and their expressiveness. Bad practice
Best practice
Explicit codeThe simplest (and easiest to understand) way of writing code is always the best. Bad practice
The above code returns:
The above function will return ‘z’:3 too in the locals dict. Best practice is to specify what’s needed, and follow the most straight-forward approach. Remember to keep things simple and explicit. Best practice
Passing args to FunctionsThere are four different ways of passing arguments to a function:
Note: In the above two examples, you can also call functions with different orders using keywords like:
The output will be:
Note: The same caution as for arbitrary argument lists is necessary. The reasons are similar: these powerful techniques are only to be used when there is a proven necessity, and should not be used if the simpler and clearer construct is sufficient to express the function’s intention. If the coding style guide is followed wisely, your Python functions will be:
Return StatementsAs a function grows in complexity, it becomes susceptible to having multiple return statements inside the function’s body. However, in order to keep a clear intent and a sustained readability level, it is preferable to avoid returning meaningful values at multiple output points in the function body. For instance, take a look at the example below (explained by the inline comments) on how to avoid adding multiple output points and raise exceptions instead: Bad practice
Best practice
Writing Idiomatic PythonAn idiom is a phrase that doesn't make literal sense, but makes sense once you're acquainted with the culture in which it arose. Programming idioms are no different. They are the little things you do daily in a particular programming language or paradigm that only make sense to a person familiar with its culture. Python beginners can be unaware of writing idiomatic Python, so we’ve listed some common Python idioms: UnpackingIf you want to assign names or references to the elements of a list while unpacking it, try using
You can use swap variables:
Nested unpacking works too:
In Python 3, PEP 3132 has introduced a new method of extended unpacking:
Creating throwaway variablesIf you need to assign something (for instance, in unpacking), but will not need that variable, use
Note: Using a double underscore instead is just as clear and almost as convenient. The benefit of this practice is eliminating the risk of accidentally interfering with either of these other use cases. Create a length-N list of the same thingUse the Python list
Output: Search for an item in a collectionSometimes we need to search through a collection. Let’s look at two options: lists and sets. Take the following code for example:
Both functions look identical, because the To determine whether an item is in a list, Python will have to go through each item until it finds a matching item. This is time consuming, especially for long lists. In a set, on the other hand, the hash of the item will tell Python where in the set to look for a matching item. As a result, the search can be done quickly, even if the set is large. Because of these differences in performance, it is often a good idea to use sets or dictionaries instead of lists in cases where:
Access a Dictionary ElementDon’t use the dict.has_key() method. Instead, use x Note: Python2 is about to be retired in 2020. It is advised to use Python 3.x for any sort of development, as most of the Python packages have/will stop releasing updates for Python 2.x. Read more here. Bad practice
Best practice
Filtering a ListNever remove items from a list while you are iterating it. Why? If your list is accessed via multiple references, the fact that you're just reseating one of the references (and NOT altering the list object itself) can lead to subtle, disastrous bugs. Read more about it here. Bad practice
Don’t make multiple passes through the list.
Best practice Use a list comprehension or generator expression:
Updating Values in a ListRemember that assignment never creates a new object. If two or more variables refer to the same list, changing one of them changes them all. Bad practice
Best practice
Read From a FileUse the Bad practice
Best practice
The Dealing with Legacy CodeWe’ve covered the basics of writing good code in Python. It’s now worth looking at the art of handling big projects in Python. How can you take up new open-source or closed-source projects? What are the steps to refactor legacy code? What are the best practices to get yourself up to speed on a new project? Often when you join a new organization, you're given a codebase to comprehend and refactor, or you need to take up legacy code to refactor. Sometimes, thanks to this situation you'll find yourself in deep distress, and unable to figure out the starting point. At this point, it's important to define “legacy code/project” so that we're all on the same page. Here's what you'll come across:
All of the above are somewhat right, but sometimes projects are done in haste and put into production before everyone realizes that there is a lot of scope for improvement. So, how shall we tackle a legacy project? Below is a quick list of steps you should follow in order to make your journey of refactoring simpler and smoother:
ConclusionWith the exploding Python community and budding Pythonistas, we have Python in almost all development fields such as data science, web development, mobile development, and AI, etc. As such, it is increasingly important to make sure we always ship enterprise-grade code following proper guidelines. Thanks to these basic tools — and the beauty of the Python language itself — producing awesome code and products doesn’t have to be a scary proposition. Now that you’ve gone through these guidelines, go ahead and try these on an open source Python project! For more Python best practices, check out these posts:
Notes and references: [1] One Statement of Code per line - Code Style from The Hitchhiker's Guide to Python [2] Passing args to function - Code Style from The Hitchhiker's Guide to Python How do you code better in Python?Pythonic Code: Best Practices to Make Your Python More Readable. One Statement of Code per Line.. Explicit code.. Passing args to Functions.. Return Statements.. Writing Idiomatic Python.. Access a Dictionary Element.. Filtering a List.. Updating Values in a List.. What is the fastest way to code in Python?Use the Built-In Functions
Many of Python's built-in functions are written in C, which makes them much faster than a pure python solution. Take a very simple task of summing a lot of numbers. We could loop through each number, summing as we go.
|