39
39
you can add tab completion for each argument's values using parameters passed
40
40
to add_argument().
41
41
42
- Below are the 5 add_argument() parameters for enabling tab completion of an
42
+ Below are the 3 add_argument() parameters for enabling tab completion of an
43
43
argument's value. Only one can be used at a time.
44
44
45
45
``choices`` - pass a list of values to the choices parameter.
46
46
47
47
Example::
48
48
49
- parser.add_argument('-o', '--options', choices= ['An Option', 'SomeOtherOption'])
49
+ my_list = ['An Option', 'SomeOtherOption']
50
50
parser.add_argument('-o', '--options', choices=my_list)
51
51
52
- ``choices_function `` - pass a function that returns choices. This is good in
52
+ ``choices_provider `` - pass a function that returns choices. This is good in
53
53
cases where the choice list is dynamically generated when the user hits tab.
54
54
55
55
Example::
56
56
57
- def my_choices_function( ):
57
+ def my_choices_provider(self ):
58
58
...
59
59
return my_generated_list
60
60
61
- parser.add_argument('-o', '--options', choices_function=my_choices_function )
61
+ parser.add_argument("arg", choices_provider=my_choices_provider )
62
62
63
- ``choices_method`` - this is equivalent to choices_function, but the function
64
- needs to be an instance method of a cmd2.Cmd or cmd2.CommandSet subclass. When
65
- ArgparseCompleter calls the method, it well detect whether is is bound to a
66
- CommandSet or Cmd subclass.
67
- If bound to a cmd2.Cmd subclass, it will pass the app instance as the `self`
68
- argument. This is good in cases where the list of choices being generated
69
- relies on state data of the cmd2-based app.
70
- If bound to a cmd2.CommandSet subclass, it will pass the CommandSet instance
71
- as the `self` argument.
63
+ ``completer`` - pass a tab completion function that does custom completion.
72
64
73
- Example::
74
-
75
- def my_choices_method(self):
76
- ...
77
- return my_generated_list
78
-
79
- parser.add_argument("arg", choices_method=my_choices_method)
80
-
81
-
82
- ``completer_function`` - pass a tab completion function that does custom
83
- completion. Since custom tab completion operations commonly need to modify
84
- cmd2's instance variables related to tab completion, it will be rare to need a
85
- completer function. completer_method should be used in those cases.
86
-
87
- Example::
88
-
89
- def my_completer_function(text, line, begidx, endidx):
90
- ...
91
- return completions
92
- parser.add_argument('-o', '--options', completer_function=my_completer_function)
93
-
94
- ``completer_method`` - this is equivalent to completer_function, but the function
95
- needs to be an instance method of a cmd2.Cmd or cmd2.CommandSet subclass. When
96
- ArgparseCompleter calls the method, it well detect whether is is bound to a
97
- CommandSet or Cmd subclass.
98
- If bound to a cmd2.Cmd subclass, it will pass the app instance as the `self`
99
- argument. This is good in cases where the list of choices being generated
100
- relies on state data of the cmd2-based app.
101
- If bound to a cmd2.CommandSet subclass, it will pass the CommandSet instance
102
- as the `self` argument, and the app instance as the positional argument.
103
- cmd2 provides a few completer methods for convenience (e.g.,
104
- path_complete, delimiter_complete)
65
+ cmd2 provides a few completer methods for convenience (e.g., path_complete,
66
+ delimiter_complete)
105
67
106
68
Example::
107
69
108
70
# This adds file-path completion to an argument
109
- parser.add_argument('-o', '--options', completer_method=cmd2.Cmd.path_complete)
110
-
71
+ parser.add_argument('-o', '--options', completer=cmd2.Cmd.path_complete)
111
72
112
73
You can use functools.partial() to prepopulate values of the underlying
113
74
choices and completer functions/methods.
114
75
115
76
Example::
116
77
117
78
# This says to call path_complete with a preset value for its path_filter argument
118
- completer_method = functools.partial(path_complete,
119
- path_filter=lambda path: os.path.isdir(path))
120
- parser.add_argument('-o', '--options', choices_method=completer_method)
121
-
122
- Of the 5 tab completion parameters, choices is the only one where argparse
79
+ dir_completer = functools.partial(path_complete,
80
+ path_filter=lambda path: os.path.isdir(path))
81
+ parser.add_argument('-o', '--options', completer=dir_completer)
82
+
83
+ For `choices_provider` and `completer`, do not set them to a bound method. This
84
+ is because ArgparseCompleter passes the `self` argument explicitly to these
85
+ functions. When ArgparseCompleter calls one, it will detect whether it is bound
86
+ to a `Cmd` subclass or `CommandSet`. If bound to a `cmd2.Cmd subclass`, it will
87
+ pass the app instance as the `self` argument. If bound to a `cmd2.CommandSet`
88
+ subclass, it will pass the `CommandSet` instance as the `self` argument.
89
+ Therefore instead of passing something like `self.path_complete`, pass
90
+ `cmd2.Cmd.path_complete`.
91
+
92
+ Of the 3 tab completion parameters, choices is the only one where argparse
123
93
validates user input against items in the choices list. This is because the
124
- other 4 parameters are meant to tab complete data sets that are viewed as
94
+ other 2 parameters are meant to tab complete data sets that are viewed as
125
95
dynamic. Therefore it is up to the developer to validate if the user has typed
126
96
an acceptable value for these arguments.
127
97
128
98
The following functions exist in cases where you may want to manually add a
129
99
choice-providing function/method to an existing argparse action. For instance,
130
100
in __init__() of a custom action class.
131
101
132
- - set_choices_function(action, func)
133
- - set_choices_method(action, method)
134
- - set_completer_function(action, func)
135
- - set_completer_method(action, method)
102
+ - set_choices_provider(action, func)
103
+ - set_completer(action, func)
136
104
137
105
There are times when what's being tab completed is determined by a previous
138
106
argument on the command line. In theses cases, Autocompleter can pass a
@@ -142,8 +110,8 @@ def my_completer_function(text, line, begidx, endidx):
142
110
143
111
Example::
144
112
145
- def my_choices_method (self, arg_tokens)
146
- def my_completer_method (self, text, line, begidx, endidx, arg_tokens)
113
+ def my_choices_provider (self, arg_tokens)
114
+ def my_completer (self, text, line, begidx, endidx, arg_tokens)
147
115
148
116
All values of the arg_tokens dictionary are lists, even if a particular
149
117
argument expects only 1 token. Since ArgparseCompleter is for tab completion,
@@ -295,15 +263,13 @@ class ChoicesCallable:
295
263
Enables using a callable as the choices provider for an argparse argument.
296
264
While argparse has the built-in choices attribute, it is limited to an iterable.
297
265
"""
298
- def __init__ (self , is_method : bool , is_completer : bool , to_call : Callable ):
266
+ def __init__ (self , is_completer : bool , to_call : Callable ):
299
267
"""
300
268
Initializer
301
- :param is_method: True if to_call is an instance method of a cmd2 app. False if it is a function.
302
269
:param is_completer: True if to_call is a tab completion routine which expects
303
270
the args: text, line, begidx, endidx
304
271
:param to_call: the callable object that will be called to provide choices for the argument
305
272
"""
306
- self .is_method = is_method
307
273
self .is_completer = is_completer
308
274
self .to_call = to_call
309
275
@@ -318,34 +284,24 @@ def _set_choices_callable(action: argparse.Action, choices_callable: ChoicesCall
318
284
# Verify consistent use of parameters
319
285
if action .choices is not None :
320
286
err_msg = ("None of the following parameters can be used alongside a choices parameter:\n "
321
- "choices_function, choices_method, completer_function, completer_method " )
287
+ "choices_provider, completer " )
322
288
raise (TypeError (err_msg ))
323
289
elif action .nargs == 0 :
324
290
err_msg = ("None of the following parameters can be used on an action that takes no arguments:\n "
325
- "choices_function, choices_method, completer_function, completer_method " )
291
+ "choices_provider, completer " )
326
292
raise (TypeError (err_msg ))
327
293
328
294
setattr (action , ATTR_CHOICES_CALLABLE , choices_callable )
329
295
330
296
331
- def set_choices_function (action : argparse .Action , choices_function : Callable ) -> None :
332
- """Set choices_function on an argparse action"""
333
- _set_choices_callable (action , ChoicesCallable (is_method = False , is_completer = False , to_call = choices_function ))
334
-
335
-
336
- def set_choices_method (action : argparse .Action , choices_method : Callable ) -> None :
337
- """Set choices_method on an argparse action"""
338
- _set_choices_callable (action , ChoicesCallable (is_method = True , is_completer = False , to_call = choices_method ))
339
-
340
-
341
- def set_completer_function (action : argparse .Action , completer_function : Callable ) -> None :
342
- """Set completer_function on an argparse action"""
343
- _set_choices_callable (action , ChoicesCallable (is_method = False , is_completer = True , to_call = completer_function ))
297
+ def set_choices_provider (action : argparse .Action , choices_provider : Callable ) -> None :
298
+ """Set choices_provider on an argparse action"""
299
+ _set_choices_callable (action , ChoicesCallable (is_completer = False , to_call = choices_provider ))
344
300
345
301
346
- def set_completer_method (action : argparse .Action , completer_method : Callable ) -> None :
347
- """Set completer_method on an argparse action"""
348
- _set_choices_callable (action , ChoicesCallable (is_method = True , is_completer = True , to_call = completer_method ))
302
+ def set_completer (action : argparse .Action , completer : Callable ) -> None :
303
+ """Set completer on an argparse action"""
304
+ _set_choices_callable (action , ChoicesCallable (is_completer = True , to_call = completer ))
349
305
350
306
351
307
############################################################################################################
@@ -359,10 +315,8 @@ def set_completer_method(action: argparse.Action, completer_method: Callable) ->
359
315
360
316
def _add_argument_wrapper (self , * args ,
361
317
nargs : Union [int , str , Tuple [int ], Tuple [int , int ], None ] = None ,
362
- choices_function : Optional [Callable ] = None ,
363
- choices_method : Optional [Callable ] = None ,
364
- completer_function : Optional [Callable ] = None ,
365
- completer_method : Optional [Callable ] = None ,
318
+ choices_provider : Optional [Callable ] = None ,
319
+ completer : Optional [Callable ] = None ,
366
320
suppress_tab_hint : bool = False ,
367
321
descriptive_header : Optional [str ] = None ,
368
322
** kwargs ) -> argparse .Action :
@@ -378,10 +332,8 @@ def _add_argument_wrapper(self, *args,
378
332
to specify a max value with no upper bound, use a 1-item tuple (min,)
379
333
380
334
# Added args used by ArgparseCompleter
381
- :param choices_function: function that provides choices for this argument
382
- :param choices_method: cmd2-app method that provides choices for this argument
383
- :param completer_function: tab completion function that provides choices for this argument
384
- :param completer_method: cmd2-app tab completion method that provides choices for this argument
335
+ :param choices_provider: function that provides choices for this argument
336
+ :param completer: tab completion function that provides choices for this argument
385
337
:param suppress_tab_hint: when ArgparseCompleter has no results to show during tab completion, it displays the
386
338
current argument's help text as a hint. Set this to True to suppress the hint. If this
387
339
argument's help text is set to argparse.SUPPRESS, then tab hints will not display
@@ -393,20 +345,20 @@ def _add_argument_wrapper(self, *args,
393
345
:param kwargs: keyword-arguments recognized by argparse._ActionsContainer.add_argument
394
346
395
347
Note: You can only use 1 of the following in your argument:
396
- choices, choices_function, choices_method, completer_function, completer_method
348
+ choices, choices_provider, completer
397
349
398
350
See the header of this file for more information
399
351
400
352
:return: the created argument action
401
353
:raises: ValueError on incorrect parameter usage
402
354
"""
403
355
# Verify consistent use of arguments
404
- choices_callables = [choices_function , choices_method , completer_function , completer_method ]
356
+ choices_callables = [choices_provider , completer ]
405
357
num_params_set = len (choices_callables ) - choices_callables .count (None )
406
358
407
359
if num_params_set > 1 :
408
360
err_msg = ("Only one of the following parameters may be used at a time:\n "
409
- "choices_function, choices_method, completer_function, completer_method " )
361
+ "choices_provider, completer " )
410
362
raise (ValueError (err_msg ))
411
363
412
364
# Pre-process special ranged nargs
@@ -465,14 +417,10 @@ def _add_argument_wrapper(self, *args,
465
417
# Set the custom attributes
466
418
setattr (new_arg , ATTR_NARGS_RANGE , nargs_range )
467
419
468
- if choices_function :
469
- set_choices_function (new_arg , choices_function )
470
- elif choices_method :
471
- set_choices_method (new_arg , choices_method )
472
- elif completer_function :
473
- set_completer_function (new_arg , completer_function )
474
- elif completer_method :
475
- set_completer_method (new_arg , completer_method )
420
+ if choices_provider :
421
+ set_choices_provider (new_arg , choices_provider )
422
+ elif completer :
423
+ set_completer (new_arg , completer )
476
424
477
425
setattr (new_arg , ATTR_SUPPRESS_TAB_HINT , suppress_tab_hint )
478
426
setattr (new_arg , ATTR_DESCRIPTIVE_COMPLETION_HEADER , descriptive_header )
0 commit comments