Maximizing code readability

One of the main benefits of using AsyncIO and ReactiveX is that it allows us to write code that can be read quite easily. However, there are two things that can make RxPY code less readable than the ReactiveX equivalent in other languages (especially compared to JavaScript):

  • The intensive use of dictionaries
  • The way to deal with continuation lines

The following code snippet shows a typical way to chain RxPY operators:

obs = Observable.from_([{'count': 5, 'what': 'apple'},
{'count': 3, 'what': 'orange'}])
.filter(lambda i: i['what'] == 'apple')
.map(lambda i: i['count'])
.map(lambda i: {'count': i, 'double': i*2} )
...

When a lot of operators are chained together, in most cases there is a need to return an object that is a composition of several operations on this item. For example, in the last line of this snippet, the map operator returns an object that is composed of the item itself and its double value. This new object is defined as a dictionary. Using dictionaries is probably the first solution that most people use because it is very natural in Python. However, the drawback is that the syntax in using dictionaries is more complex than accessing a field of an object like a class instance. This is something that can be improved.

When a lot of operators are chained together, they are usually written as one operator per line. This makes the code easier to read. However, in Python, line continuation must be done with a backslash, except when a parenthesis is open. The presence of many of these backslashes also adds clutter to the code flow. But more than that, it is not possible to insert a comment in a multiline block like this one. When 10 or more operators are chained together, it usually means that several features are implemented. In these cases, being able to insert comments between two operator lines is something nice to have.

Let's see how to improve these two syntactic defects.

..................Content has been hidden....................

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