Pythonic Code

In this chapter, we will explore the way ideas are expressed in Python, with its own particularities. If you are familiar with the standard ways of accomplishing some tasks in programming (such as getting the last element of a list, iterating, searching, and so on), or if you come from more traditional programming languages (like C, C++, and Java), then you will find that, in general, Python provides its own mechanism for most common tasks.

In programming, an idiom is a particular way of writing code in order to perform a specific task. It is something common that repeats and follows the same structure every time. Some could even argue and call them a pattern, but be careful because they are not designed patterns (which we will explore later on). The main difference is that design patterns are high-level ideas, independent from the language (sort of), but they do not translate into code immediately. On the other hand, idioms are actually coded. It is the way things should be written when we want to perform a particular task.

As idioms are code, they are language dependent. Every language will have its own idioms, which means the way things are done in that particular language (for example, how you would open and write a file in C, C++, and so on). When the code follows these idioms, it is known as being idiomatic, which in Python is often referred to as Pythonic.

There are multiple reasons to follow these recommendations and write Pythonic code first (as we will see and analyze), writing code in an idiomatic way usually performs better. It is also more compact and easier to understand. These are traits that we always want in our code so that it works effectively. Secondly, as introduced in the previous chapter, it is important that the entire development team can get used to the same patterns and structure of the code because this will help them focus on the true essence of the problem, and will help them avoid making mistakes.

The goals of this chapter are as follows:

  • To understand indices and slices, and correctly implement objects that can be indexed
  • To implement sequences and other iterables
  • To learn good use cases for context managers
  • To implement more idiomatic code through magic methods
  • To avoid common mistakes in Python that lead to undesired side-effects
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.131.238