Search code examples
pythonmethod-chaining

Python convention indicating whether method chaining is method cascading?


I am spinning up on Python and Spark. I noticed that Python uses a lot of chaining of methods and/or properties. A lot of what I found online about this for Python describes method cascading, even though it is referred to as method chaining. According to Wikipedia, chaining returns an object, from which another method is invoked. On the other hand, cascading requires that the returned object is "self", so it is a subset of chaining.

Is there a convention by which one can quickly recognize when cascading is specifically being used as opposed to general chaining? Here are two examples I saw from a PySpark tutorial:

df = spark.readStream
        .format("kafka")
        .option("kafka.bootstrap.servers", "192.168.1.100:9092")
        .option("subscribe", "json_topic")
        .option("startingOffsets", "earliest") // From starting
        .load()

df.selectExpr("CAST(id AS STRING) AS key", "to_json(struct(*)) AS value")
   .writeStream
   .format("kafka")
   .outputMode("append")
   .option("kafka.bootstrap.servers", "192.168.1.100:9092")
   .option("topic", "josn_data_topic")
   .start()
   .awaitTermination()

It really helps to accelerate the figuring out of the code, especially when one is unfamiliar with the ecosystem of classes in question. In cascading, it's just consecutive calls to methods of the same object. Chaining that is not cascading, however, requires much more care in deciphering, since the object could change part way through the chain.


Solution

  • This answer is synthesized from links provided in comments by Barmar and deceze.

    Method cascading is rare in Python because Guido van Rossum advises (requires?) that libraries be designed such that methods don't return self as a result of mutating self.

    In turn, the reason for this is to avoid confusion about whether a specific instance of method chaining is method cascading, essentially by (largely) eliminating the latter.

    Here is the cited source.