When to use cascading method in Python?

From my understanding of Pythonic's coding style (and in particular PEP20), the code should be simple and readable. With that in mind, is the cascading method considered Pythonic?

For example, let's say we have a Cascade class:

 class Cascade(object): def __init__(self, pythonic): self.question = 'Is this Pythonic?' self.answer = pythonic def copy(self): import copy return copy.deepcopy(self) def is_pythonic(self): return self.answer 

Then what is better:

 >>> cas = Cascade(False) >>> cas.copy().is_pythonic() False 

Or else:

 >>> cas1 = Cascade(False) >>> cas2 = cas1.copy() >>> cas2.is_pythonic() False 

The first option, in my opinion, is more readable, since my eyes run from left to right - almost akin to reading a book, while the second contains one simple statement in a line (which, admittedly, is also well read).

EDIT

Following the helpful comments by Haleemur Ali , Lutz Horn and claust , I would like to rephrase the question in the broader "When should I use the cascading method in Python?"

+6
source share
2 answers

Both are acceptable.

Long chains are becoming harder to read, so try to avoid really long chains.

In addition, if you divide it into separate statements, you can find reuse, i.e.

 c = cas1.copy() c.method1() c.method2() c.is_pythonic() 

change the following comment from @claust Also note that cascading is useful for anonymous objects: I use it a lot in GUI programming, where you can create object grids without having to reference it later: tkinter.Label ("label"). Grid (row = 0, column = 0)

+7
source

It depends. If you need a result

 cas.copy() 

later, you should use the second approach. If you don’t need it and you only want to call is_pythonic() , the first approach will be fine.

+3
source

Source: https://habr.com/ru/post/987560/


All Articles