Last active
April 7, 2019 19:24
-
-
Save dhilst/2921533d74f1f597979fe40623a8d3af to your computer and use it in GitHub Desktop.
declarative class expressinons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Using class expressions for declarative programming in python | |
import inspect | |
def route(path, func, *methods): | |
''' | |
An example on how to create function usable for | |
declarative programming in python. These functions | |
will sit on the class body and setup some state for | |
latter use. | |
Since we are in the class body the class wasn't declared | |
yet, so we can't modify it. Instead we hold the declaration in | |
another place so that we can retrieve latter. In this | |
example I'm saving the declarations inside the function as | |
a attribute. | |
Suppose that we have a webframework and we want to declare | |
routes this way: | |
>>> class Routes: | |
... route('/foo', lambda:200, 'POST', 'GET') | |
... route('/bar', lambda:403, 'DELETE') | |
This function will save all the calls to route.routes attribute | |
during the class parsing time. They can be fetched after the class was | |
parsed. | |
To retrieve the first route path we can do | |
>>> route.routes['Routes'][0]['path'] # The first route call path | |
'/foo' | |
The class name is saved within `classname` key, the same approach | |
can be used to retrieve the qualified name of the class with package | |
and module name. | |
''' | |
clsname = inspect.currentframe().f_back.f_code.co_name | |
route.routes.setdefault(clsname, []).append(dict(classname=clsname, path=path, func=func, methods=methods)) | |
route.routes = {} | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment