Skip to content

Instantly share code, notes, and snippets.

@elyezer
Last active August 29, 2015 14:07
Show Gist options
  • Save elyezer/b9e76cb3067e632fc633 to your computer and use it in GitHub Desktop.
Save elyezer/b9e76cb3067e632fc633 to your computer and use it in GitHub Desktop.
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
@elyezer
Copy link
Author

elyezer commented Oct 14, 2014

Sample usage:

class Model(object):
    create = HammerCommand(options=('name', 'description'))
    delete = HammerCommand(options=('name', 'id'))

Instead of:

class Model(object):
    def create(options):
        #logic to handle the command

    def delete(options):
        # same logic to handle the command, but with a different sub-command

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment