1

Where can I learn about fluent style of writing python?

I recently learnt basics of python with a little background in JavaScript (Node.js). I was trying to automate video transcoding with the ffmpeg-python. In the example , code 1

import ffmpeg 
stream = ffmpeg.input('input.mp4')
stream = ffmpeg.hflip(stream) 
stream = ffmpeg.output(stream, 'output.mp4') 
ffmpeg.run(stream)

Does the same job as , code 2 (fluent)

import ffmpeg 
(
   ffmpeg
   .input('input.mp4') 
   .hflip()
   .output('output.mp4')
   .run() 
)
  1. I find the code 2 style better and would like to learn how it works
  2. What are the parenthesis that encode ffmpeg chain imply?
  3. Can it used with most of the popular python modules ? Atleast the popular ones

The closes thing I could find was fluentpy but ffmpeg-python examples doesn't specify importing it or I missed it

Solaris
  • 674
  • 7
  • 22
  • 1
    2) The parenthesis are just regular grouping parentheses so you can put it on multiple lines 3) No, you can't. It isn't super common, but, for example, `pandas` supports a fluent interface – juanpa.arrivillaga Jun 19 '20 at 19:01
  • 1
    There is nothing mysterious about this, `.input` returns some object with a `.hflip` method, which returns some object with an `output` method, which returns some object with a `.run` method. These could all be objects of the same class, where the methods simply `return self` at the end or return a new object of that same class. Here is [one related question](https://stackoverflow.com/questions/37827808/fluent-interface-with-python). But what are you asking, *exactly*? – juanpa.arrivillaga Jun 19 '20 at 19:03
  • @juanpa.arrivillaga Are those parenthesis optional ? Or is grouping necessary ? – Solaris Jun 20 '20 at 03:45
  • 1
    Those parentheses are there to allow you to do it on *multiple lines*. You can do it all on one line without parentheses – juanpa.arrivillaga Jun 20 '20 at 03:46
  • @juanpa.arrivillaga so the input passes the return value to hflip and so on ? Also can you move your comment to answer so I could accept it ? – Solaris Jun 20 '20 at 03:48
  • @juanpa.arrivillaga Exactly what I wanted to ask would be , how the chaining works? – Solaris Jun 20 '20 at 03:50
  • 1
    No, there's no passing. Thing about it this way. let's say you have some string, `my_string = 'foo'`, you can do something like `my_string.lower().strip('x').capitalize()`. Because `.lower()` returns a string, which has a `.strip`, method. Which is called by `.strip('x')`, which returns a string which has a `.capitalize` method, which also returns a stiring. – juanpa.arrivillaga Jun 20 '20 at 04:16
  • @juanpa.arrivillaga thank you , that made things clear for me – Solaris Jun 21 '20 at 05:09

0 Answers0