Last active
August 29, 2015 14:07
-
-
Save elyezer/b9e76cb3067e632fc633 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import types | |
class HammerMeta(type): | |
def __new__(cls, name, bases, attrs): | |
for key, value in attrs.items(): | |
if isinstance(value, HammerCommand): | |
value.__name__ = key # to correctly allow inspecting methods | |
if value.command is None: | |
# syntatic sugar to avoid repeating the command | |
# this will convert attr_name to command attr-name | |
value.command = key.replace('_', '-') | |
return super(HammerMeta, cls).__new__(cls, name, bases, attrs) | |
class HammerCommand(object): | |
"""Descriptor that creates hammer commands for CLI classes | |
Example:: | |
class Model(Base): | |
delete = HammerCommand( | |
'name', | |
)) | |
""" | |
def __init__(self, command=None, options=None): | |
self.command = command | |
self.options = options | |
def __get__(self, obj, objtype=None): | |
return types.MethodType(self, obj, objtype) | |
def __call__(self, instance, *args): | |
"""This is the call to the descriptor | |
Model().delete() for example will call this | |
""" | |
print self, instance, args | |
# logic to handle the command which is repeated for every CLI method |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage:
Instead of: