Skip to content

Instantly share code, notes, and snippets.

@sgml
Forked from thinkingserious/fluent.py
Created April 14, 2020 04:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgml/e9c3745170f54056b67a52f165ffad2c to your computer and use it in GitHub Desktop.
Save sgml/e9c3745170f54056b67a52f165ffad2c to your computer and use it in GitHub Desktop.
Fluent Interface in Python Using Method Chaining and Reflection
class Fluent:
def __init__(self, cache=None):
self._cache = cache or []
# Build the cache, and handle special cases
def _(self, name):
# Enables method chaining
return Fluent(self._cache+[name])
# Final method call
def method(self):
return self._cache
# Reflection
def __getattr__(self, name):
return self._(name)
# Called with the object is deleted
def __del__(self):
print('Deleting Myself')
fluent = Fluent()
chain = fluent.hello.world
print(chain.method())
# 'for' is a Python reserved word
new_chain = chain.thanks._('for').all.the.fish
print(new_chain.method())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment