[Python-ideas] Method chaining notation

Greg Ewing greg.ewing at canterbury.ac.nz
Sat Feb 22 04:28:00 CET 2014


Chris Angelico wrote:
> In Python, as in most languages, method chaining requires the method
> to return its own object.

I don't think Python has much need for method chaining.
Most uses of it I've seen in other languages are better
addressed in other ways in Python.

E.g. a pattern often used in Java for initialising
objects:

    b = new BlockStone().setHardness(1.5F)
       .setResistance(10.0F).setStepSound(soundTypePiston)
       .setBlockName("stone").setBlockTextureName("stone")

is expressed much more Pythonically as

    b = BlockStone(hardness = 1.5, resistance = 10.0,
       step_sound = sound_type_piston, name = "stone",
       texture_name = "stone")

> window = gtk.Window(gtk.WINDOW_TOPLEVEL)
> window.set_title("Hello Buttons!")
> window.connect("delete_event", delete_event)
> window.set_border_width(10)
> box1 = gtk.HBox(False, 0)
> window.add(box1)
> button1 = gtk.Button("Button 1")
> button1.connect("clicked", callback, "button 1")
> box1.pack_start(button1, True, True, 0)
> button2 = gtk.Button("Button 2")
> button2.connect("clicked", callback, "button 2")
> box1.pack_start(button2, True, True, 0)
> window.show_all()

I think this is a symptom of bad API design. A more
Pythonic way to write that would be

    window = Window(style = TOPLEVEL, title = "Hello Buttons!",
       on_delete = delete_event, border_width = 10,
       HBox(False, 0, [
          Button("Button 1", on_clicked = callback),
          Button("Button 2", on_clicked = callback),
       ])
    )

-- 
Greg


More information about the Python-ideas mailing list