fbpx

5 tips for writing more Pythonic Code

Pythonic+code+1

ARTICLE SUMMARY

Python is one of the most popular programming languages right now. Although Python is relatively easy to learn, mastering it is a different story. However, there are simple steps you can use to make your code more Pythonic and easier to read.

Python is one of the most popular programming languages used today. One of the reasons for its popularity is that it is relatively easy to learn and begin with when compared to other languages.

However, producing solid Python code requires a lot of practice. Writing good code is an art form; as with any other art form, the more you practice, the more you will improve.

Writing good Python code, or more “Pythonic” code is not difficult; there are rules to follow which will make your code Pythonic. These rules fall under PEP8. When we describe code as “Pythonic” we mean it is easy to read, follow and understand.

Let’s see how we can make our Python code more Pythonic without further ado.

Image made by the author

1. Your code style

PEP8 suggests cutting your physical lines after 79 characters when we write commands or any type of strings in Python. So, for example, if you want to write a list of strings, you can write each item in a new line instead of writing everything as a very long line.

someList = [ “this list has very very long strings”,

“to make it more readable, each string will be,”

“in a new line.”]

You can do the same with strings. For example, if you have a long string, you can use parentheses around your string to contain it and make it more readable.

longStr = (

“This string is very, very long.”

“to make it more readable, each string will be”

“in a new line.”

)

The 79 characters per physical line of code is not a hard rule; you can extend it to 88 or even 100 characters based on your code if you think it will be more efficient for your particular case. That being said, the Python standard library requires limiting lines to 79 characters if you’re writing coding commands and 72 in case of docstrings or comments.

2. Play with your variables

Python offers many options that allow you to write simple commands containing variable assignment operations. The most useful variable trick in Python is variable unpacking. Unpacking is simply an efficient and short way to assign values to variables, such as variable value swapping.

x, y= y, x

or unpack tuples, for example:

a, (b, c) = 10, (20, 30)

And more so, you can do extended unpacking, for example:

v, *end = [10, 20, 30]

# gives v= 1, end = [2, 3]

v, *middle, z= [1, 2, 3, 4]

# gives v= 1, middle = [2, 3], z= 4

Unpacking is not the only trick you can use with variables. There’s also a Pythonic way to deal with ignored variables or variables that have a specific job during one line of code after which they are not needed, and naming them is not a worthwhile task. For example, in the extended unpacking example, say I don’t need the last item of the list; I can then avoid naming it and use __.

v, *middle, z= [1, 2, 3, 4]

# gives v= 1, middle = [2, 3]

I recommend using __ instead of just _, which is often seen in Python books because the single underscore is used to refer to the gettext() function and used at the interactive prompt to store the value of the last command. So, using the __ is just a way to avoid confusion.

3. Dealing with lists

Lists are a big part of Python and programming,so various list techniques help make your code more Pythonic. Let’s start with list initialisation. In Python, you can initiate a list or create a list with nested lists simply using the * operator.

listOfNones = [None] * 6 #results in [None, None, None, None, None, None]listOfFives = [[5]] *5 #results in [[5], [5], [5], [5], [5]]

There are also Pythonic ways to filter a list if you want to go through a list and delete some items based on a condition. However, you can’t use the ‘remove’ method to delete things because it can cause subtle errors. Instead, you can use list comprehension or generators to achieve the same results more efficiently.

# comprehensions create a new list

filtered_list = [item for item in sequence if item != x]  # to avoid generating a new object, use generators

filtered_list = (item for item in sequence if item != x)

4. Give some attention to your functions

Everything in Python is an object, including functions. Functions are an efficient way to package a part of the code that you can repeatedly use throughout your current or future codes. In Python, there are 4 different ways to pass arguments to a function:

  1. Positional arguments: These arguments are parts of the function’s meaning. They appear in the order in which they were written in the original function definition—for example, send_email(title, recipient, body).
  2. Keyword arguments (r kwargs): These come in handy when dealing with a function with many arguments. In that case, kwargs can be used with default values. For example, send_message(message, recipient, cc=None).
  3. Arbitrary arguments tuple: If your function needs an undefined number of arguments, you can use the *args construct to pass a tuple of arguments to the function. For example, def calc_ave(*nums). The nums will be a tuple with as many values as the user wants.
  4. Arbitrary keyword argument dictionary: Similar to the arbitrary argument tuple, if a function requires an undetermined number of named arguments, you can use the **kwargs construct.

The last two techniques are powerful, so be careful when using them and only do so when you find it necessary if there is no better way to write your function.

 5. Follow the Zen of Python

The Zen of Python is a simple guide for writing Python code, also known as PEP 20. You can read the Zen of Python by simply importing this command.

>>> import this

The Zen of Python, by Tim PetersBeautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.

Flat is better than nested.

Sparse is better than dense.

Readability counts.

Special cases aren’t special enough to break the rules.

Although practicality beats purity.

Errors should never pass silently.

Unless explicitly silenced.

In the face of ambiguity, refuse the temptation to guess.

There should be one– and preferably only one –obvious way to do it.

Although that way may not be obvious at first unless you’re Dutch.

Now is better than never.

Although never is often better than *right* now.

If the implementation is hard to explain, it’s a bad idea.

If the implementation is easy to explain, it may be a good idea.

Namespaces are one honking great idea — let’s do more of those!

If you want to see concrete examples of using the Zen of Python, check out these slides.

I like to think of programming languages the same way I do spoken languages. Some may sound challenging to learn and master, while others seem more manageable. That depends on various factors. If you want to learn English, the difficulty depends on your mother language and your ability to learn a new language.

But, even if you learned the basics of English and mastered the grammar, you won’t be fluent in English. To be considered fluent in a language, you need to be able to use it to communicate effectively with others; basically, you need to master its idioms.

Programming languages, in general, are the same. So, for example, you can master the syntax of Python but knowing that won’t make you fluent in Python.

To be Python fluent, you need to use Python idioms when writing your code, and the only way to get better at Python is to practice. Next time you write code in Python, try following these tips to make your code more readable.

AUTHOR: Sara A Metwalli
– SheCanCode Blog Squad

To find out more about Sara please click here.

RELATED ARTICLES

Regression analysis is one of the most fundamental concepts in machine learning. This article briefly introduces linear and logistic regression and how to implement them...
Bryn Bennett, a Full Stack Engineer at Stealth Startup, shares her experience of becoming a Software Engineer and tips for securing your first job.
Conveying the results of your work is all about telling the story your results are trying to tell. To tell a good story, you need...
Using arrays is one of the most utilised functions when programming. In this article, we break down how to manipulate this data structure efficiently.

This website stores cookies on your computer. These cookies are used to improve your website and provide more personalized services to you, both on this website and through other media. To find out more about the cookies we use, see our Privacy Policy.