Skip to content

Commit b65910f

Browse files
author
Jian Wei Gan
committed
Default to function name if none specified.
Supports both @command and @command().
1 parent 1bda1e5 commit b65910f

File tree

3 files changed

+31
-4
lines changed

3 files changed

+31
-4
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ dist
33
.project
44
.pydevproject
55
*.pyc
6+
*.swp

commandr/commandr.py

+12-4
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ def __init__(self):
133133
self._command_info = namedtuple(
134134
'_COMMAND_INFO', ['name', 'callable', 'category'])
135135

136-
def command(self, command_name, category=None):
136+
def command(self, command_name=None, category=None):
137137
"""Decorator that marks a function as a 'command' which can be invoked with
138138
arguments from the command line. e.g.:
139139
@@ -145,15 +145,23 @@ def Hi(name, title='Mr.'):
145145
146146
python something.py greet --name=Nick --title=Dr.
147147
148+
If 'command_name' is not specified, defaults to function name.
149+
148150
If 'category' is specified, commands with the same category are grouped
149151
together when listing all available commands.
150152
"""
151-
def command_decorator(cmd_fn):
152-
self._all_commands[command_name] = cmd_fn
153+
def command_decorator(cmd_fn, cmd_fn_name=None):
154+
final_name = cmd_fn_name or command_name or cmd_fn.func_name
155+
self._all_commands[final_name] = cmd_fn
153156
self._command_list.append(
154-
self._command_info(command_name, cmd_fn, category))
157+
self._command_info(final_name, cmd_fn, category))
155158
return cmd_fn
156159

160+
# Handle no command_name case.
161+
if callable(command_name):
162+
cmd_func = command_name
163+
return command_decorator(cmd_func, cmd_func.func_name)
164+
157165
return command_decorator
158166

159167
def SetOptions(self,

example.py

+18
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,24 @@ def SayGreeting(name, title='Mr.', times=1, comma=False, caps_lock=False):
3737
for _ in xrange(times):
3838
print message
3939

40+
@command
41+
def simple_greet(name):
42+
"""An example of @command without arguments.
43+
44+
Arguments:
45+
name - Name to greet.
46+
"""
47+
print 'Hi %s!' % name
48+
49+
@command()
50+
def another_simple_greet(name):
51+
"""An example of @command() without arguments.
52+
53+
Arguments:
54+
name - Name to greet.
55+
"""
56+
print 'Aloha %s!' % name
57+
4058
def some_decorator(fn):
4159
@wraps(fn)
4260
def _wrapper(*args, **kwargs):

0 commit comments

Comments
 (0)