Python Forum
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do you do method chaining?
#1
How do you guys do method chaining?  Everything I've tried to break method calls across multiple lines looks pretty ugly.
Or do you guys just not do chaining at all?


class query(object):
    def __init__(self, source):
        self.filters = []
        self.source = source

    def where(self, filter):
        self.filters.append(filter)
        return self

    def get(self):
        all_filters = lambda x: all(func(x) for func in self.filters)
        return list(filter(all_filters, self.source))

things = query(range(1000)
    ).where(lambda x: x % 2 == 0
    ).where(lambda x: x % 3 == 0
    ).where(lambda x: x % 4 == 0
    ).where(lambda x: x % 5 == 0)

#things = query(range(1000)).where(
#    lambda x: x % 2 == 0).where(
#    lambda x: x % 3 == 0).where(
#    lambda x: x % 4 == 0).where(
#    lambda x: x % 5 == 0)

print(things.get())
Output:
[0, 60, 120, 180, 240, 300, 360, 420, 480, 540, 600, 660, 720, 780, 840, 900, 960]
Reply


Messages In This Thread
How do you do method chaining? - by nilamo - May-01-2017, 02:36 AM
RE: How do you do method chaining? - by Mekire - May-01-2017, 06:36 AM
RE: How do you do method chaining? - by nilamo - May-01-2017, 02:01 PM
RE: How do you do method chaining? - by volcano63 - May-01-2017, 04:06 PM
RE: How do you do method chaining? - by nilamo - May-01-2017, 04:34 PM
RE: How do you do method chaining? - by Mekire - May-01-2017, 10:19 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020