• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2017 The Abseil Authors.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""This modules contains flags DEFINE functions.
15
16Do NOT import this module directly. Import the flags package and use the
17aliases defined at the package level instead.
18"""
19
20import sys
21import types
22
23from absl.flags import _argument_parser
24from absl.flags import _exceptions
25from absl.flags import _flag
26from absl.flags import _flagvalues
27from absl.flags import _helpers
28from absl.flags import _validators
29
30# pylint: disable=unused-import
31try:
32  from typing import Text, List, Any
33except ImportError:
34  pass
35
36try:
37  import enum
38except ImportError:
39  pass
40# pylint: enable=unused-import
41
42_helpers.disclaim_module_ids.add(id(sys.modules[__name__]))
43
44
45def _register_bounds_validator_if_needed(parser, name, flag_values):
46  """Enforces lower and upper bounds for numeric flags.
47
48  Args:
49    parser: NumericParser (either FloatParser or IntegerParser), provides lower
50      and upper bounds, and help text to display.
51    name: str, name of the flag
52    flag_values: FlagValues.
53  """
54  if parser.lower_bound is not None or parser.upper_bound is not None:
55
56    def checker(value):
57      if value is not None and parser.is_outside_bounds(value):
58        message = '%s is not %s' % (value, parser.syntactic_help)
59        raise _exceptions.ValidationError(message)
60      return True
61
62    _validators.register_validator(name, checker, flag_values=flag_values)
63
64
65def DEFINE(  # pylint: disable=invalid-name
66    parser,
67    name,
68    default,
69    help,  # pylint: disable=redefined-builtin
70    flag_values=_flagvalues.FLAGS,
71    serializer=None,
72    module_name=None,
73    required=False,
74    **args):
75  """Registers a generic Flag object.
76
77  NOTE: in the docstrings of all DEFINE* functions, "registers" is short
78  for "creates a new flag and registers it".
79
80  Auxiliary function: clients should use the specialized ``DEFINE_<type>``
81  function instead.
82
83  Args:
84    parser: :class:`ArgumentParser`, used to parse the flag arguments.
85    name: str, the flag name.
86    default: The default value of the flag.
87    help: str, the help message.
88    flag_values: :class:`FlagValues`, the FlagValues instance with which the
89      flag will be registered. This should almost never need to be overridden.
90    serializer: :class:`ArgumentSerializer`, the flag serializer instance.
91    module_name: str, the name of the Python module declaring this flag. If not
92      provided, it will be computed using the stack trace of this call.
93    required: bool, is this a required flag. This must be used as a keyword
94      argument.
95    **args: dict, the extra keyword args that are passed to ``Flag.__init__``.
96
97  Returns:
98    a handle to defined flag.
99  """
100  return DEFINE_flag(
101      _flag.Flag(parser, serializer, name, default, help, **args), flag_values,
102      module_name, required)
103
104
105def DEFINE_flag(  # pylint: disable=invalid-name
106    flag,
107    flag_values=_flagvalues.FLAGS,
108    module_name=None,
109    required=False):
110  """Registers a :class:`Flag` object with a :class:`FlagValues` object.
111
112  By default, the global :const:`FLAGS` ``FlagValue`` object is used.
113
114  Typical users will use one of the more specialized DEFINE_xxx
115  functions, such as :func:`DEFINE_string` or :func:`DEFINE_integer`.  But
116  developers who need to create :class:`Flag` objects themselves should use
117  this function to register their flags.
118
119  Args:
120    flag: :class:`Flag`, a flag that is key to the module.
121    flag_values: :class:`FlagValues`, the ``FlagValues`` instance with which the
122      flag will be registered. This should almost never need to be overridden.
123    module_name: str, the name of the Python module declaring this flag. If not
124      provided, it will be computed using the stack trace of this call.
125    required: bool, is this a required flag. This must be used as a keyword
126      argument.
127
128  Returns:
129    a handle to defined flag.
130  """
131  if required and flag.default is not None:
132    raise ValueError('Required flag --%s cannot have a non-None default' %
133                     flag.name)
134  # Copying the reference to flag_values prevents pychecker warnings.
135  fv = flag_values
136  fv[flag.name] = flag
137  # Tell flag_values who's defining the flag.
138  if module_name:
139    module = sys.modules.get(module_name)
140  else:
141    module, module_name = _helpers.get_calling_module_object_and_name()
142  flag_values.register_flag_by_module(module_name, flag)
143  flag_values.register_flag_by_module_id(id(module), flag)
144  if required:
145    _validators.mark_flag_as_required(flag.name, fv)
146  ensure_non_none_value = (flag.default is not None) or required
147  return _flagvalues.FlagHolder(
148      fv, flag, ensure_non_none_value=ensure_non_none_value)
149
150
151def set_default(flag_holder, value):
152  """Changes the default value of the provided flag object.
153
154  The flag's current value is also updated if the flag is currently using
155  the default value, i.e. not specified in the command line, and not set
156  by FLAGS.name = value.
157
158  Args:
159    flag_holder: FlagHolder, the flag to modify.
160    value: The new default value.
161
162  Raises:
163    IllegalFlagValueError: Raised when value is not valid.
164  """
165  flag_holder._flagvalues.set_default(flag_holder.name, value)  # pylint: disable=protected-access
166
167
168def _internal_declare_key_flags(flag_names,
169                                flag_values=_flagvalues.FLAGS,
170                                key_flag_values=None):
171  """Declares a flag as key for the calling module.
172
173  Internal function.  User code should call declare_key_flag or
174  adopt_module_key_flags instead.
175
176  Args:
177    flag_names: [str], a list of names of already-registered Flag objects.
178    flag_values: :class:`FlagValues`, the FlagValues instance with which the
179      flags listed in flag_names have registered (the value of the flag_values
180      argument from the ``DEFINE_*`` calls that defined those flags). This
181      should almost never need to be overridden.
182    key_flag_values: :class:`FlagValues`, the FlagValues instance that (among
183      possibly many other things) keeps track of the key flags for each module.
184      Default ``None`` means "same as flag_values".  This should almost never
185      need to be overridden.
186
187  Raises:
188    UnrecognizedFlagError: Raised when the flag is not defined.
189  """
190  key_flag_values = key_flag_values or flag_values
191
192  module = _helpers.get_calling_module()
193
194  for flag_name in flag_names:
195    key_flag_values.register_key_flag_for_module(module, flag_values[flag_name])
196
197
198def declare_key_flag(flag_name, flag_values=_flagvalues.FLAGS):
199  """Declares one flag as key to the current module.
200
201  Key flags are flags that are deemed really important for a module.
202  They are important when listing help messages; e.g., if the
203  --helpshort command-line flag is used, then only the key flags of the
204  main module are listed (instead of all flags, as in the case of
205  --helpfull).
206
207  Sample usage::
208
209      flags.declare_key_flag('flag_1')
210
211  Args:
212    flag_name: str | :class:`FlagHolder`, the name or holder of an already
213      declared flag. (Redeclaring flags as key, including flags implicitly key
214      because they were declared in this module, is a no-op.)
215      Positional-only parameter.
216    flag_values: :class:`FlagValues`, the FlagValues instance in which the
217      flag will be declared as a key flag. This should almost never need to be
218      overridden.
219
220  Raises:
221    ValueError: Raised if flag_name not defined as a Python flag.
222  """
223  flag_name, flag_values = _flagvalues.resolve_flag_ref(flag_name, flag_values)
224  if flag_name in _helpers.SPECIAL_FLAGS:
225    # Take care of the special flags, e.g., --flagfile, --undefok.
226    # These flags are defined in SPECIAL_FLAGS, and are treated
227    # specially during flag parsing, taking precedence over the
228    # user-defined flags.
229    _internal_declare_key_flags([flag_name],
230                                flag_values=_helpers.SPECIAL_FLAGS,
231                                key_flag_values=flag_values)
232    return
233  try:
234    _internal_declare_key_flags([flag_name], flag_values=flag_values)
235  except KeyError:
236    raise ValueError('Flag --%s is undefined. To set a flag as a key flag '
237                     'first define it in Python.' % flag_name)
238
239
240def adopt_module_key_flags(module, flag_values=_flagvalues.FLAGS):
241  """Declares that all flags key to a module are key to the current module.
242
243  Args:
244    module: module, the module object from which all key flags will be declared
245      as key flags to the current module.
246    flag_values: :class:`FlagValues`, the FlagValues instance in which the
247      flags will be declared as key flags. This should almost never need to be
248      overridden.
249
250  Raises:
251    Error: Raised when given an argument that is a module name (a string),
252        instead of a module object.
253  """
254  if not isinstance(module, types.ModuleType):
255    raise _exceptions.Error('Expected a module object, not %r.' % (module,))
256  _internal_declare_key_flags(
257      [f.name for f in flag_values.get_key_flags_for_module(module.__name__)],
258      flag_values=flag_values)
259  # If module is this flag module, take _helpers.SPECIAL_FLAGS into account.
260  if module == _helpers.FLAGS_MODULE:
261    _internal_declare_key_flags(
262        # As we associate flags with get_calling_module_object_and_name(), the
263        # special flags defined in this module are incorrectly registered with
264        # a different module.  So, we can't use get_key_flags_for_module.
265        # Instead, we take all flags from _helpers.SPECIAL_FLAGS (a private
266        # FlagValues, where no other module should register flags).
267        [_helpers.SPECIAL_FLAGS[name].name for name in _helpers.SPECIAL_FLAGS],
268        flag_values=_helpers.SPECIAL_FLAGS,
269        key_flag_values=flag_values)
270
271
272def disclaim_key_flags():
273  """Declares that the current module will not define any more key flags.
274
275  Normally, the module that calls the DEFINE_xxx functions claims the
276  flag to be its key flag.  This is undesirable for modules that
277  define additional DEFINE_yyy functions with its own flag parsers and
278  serializers, since that module will accidentally claim flags defined
279  by DEFINE_yyy as its key flags.  After calling this function, the
280  module disclaims flag definitions thereafter, so the key flags will
281  be correctly attributed to the caller of DEFINE_yyy.
282
283  After calling this function, the module will not be able to define
284  any more flags.  This function will affect all FlagValues objects.
285  """
286  globals_for_caller = sys._getframe(1).f_globals  # pylint: disable=protected-access
287  module, _ = _helpers.get_module_object_and_name(globals_for_caller)
288  _helpers.disclaim_module_ids.add(id(module))
289
290
291def DEFINE_string(  # pylint: disable=invalid-name,redefined-builtin
292    name,
293    default,
294    help,
295    flag_values=_flagvalues.FLAGS,
296    required=False,
297    **args):
298  """Registers a flag whose value can be any string."""
299  parser = _argument_parser.ArgumentParser()
300  serializer = _argument_parser.ArgumentSerializer()
301  return DEFINE(
302      parser,
303      name,
304      default,
305      help,
306      flag_values,
307      serializer,
308      required=required,
309      **args)
310
311
312def DEFINE_boolean(  # pylint: disable=invalid-name,redefined-builtin
313    name,
314    default,
315    help,
316    flag_values=_flagvalues.FLAGS,
317    module_name=None,
318    required=False,
319    **args):
320  """Registers a boolean flag.
321
322  Such a boolean flag does not take an argument.  If a user wants to
323  specify a false value explicitly, the long option beginning with 'no'
324  must be used: i.e. --noflag
325
326  This flag will have a value of None, True or False.  None is possible
327  if default=None and the user does not specify the flag on the command
328  line.
329
330  Args:
331    name: str, the flag name.
332    default: bool|str|None, the default value of the flag.
333    help: str, the help message.
334    flag_values: :class:`FlagValues`, the FlagValues instance with which the
335      flag will be registered. This should almost never need to be overridden.
336    module_name: str, the name of the Python module declaring this flag. If not
337      provided, it will be computed using the stack trace of this call.
338    required: bool, is this a required flag. This must be used as a keyword
339      argument.
340    **args: dict, the extra keyword args that are passed to ``Flag.__init__``.
341
342  Returns:
343    a handle to defined flag.
344  """
345  return DEFINE_flag(
346      _flag.BooleanFlag(name, default, help, **args), flag_values, module_name,
347      required)
348
349
350def DEFINE_float(  # pylint: disable=invalid-name,redefined-builtin
351    name,
352    default,
353    help,
354    lower_bound=None,
355    upper_bound=None,
356    flag_values=_flagvalues.FLAGS,
357    required=False,
358    **args):
359  """Registers a flag whose value must be a float.
360
361  If ``lower_bound`` or ``upper_bound`` are set, then this flag must be
362  within the given range.
363
364  Args:
365    name: str, the flag name.
366    default: float|str|None, the default value of the flag.
367    help: str, the help message.
368    lower_bound: float, min value of the flag.
369    upper_bound: float, max value of the flag.
370    flag_values: :class:`FlagValues`, the FlagValues instance with which the
371      flag will be registered. This should almost never need to be overridden.
372    required: bool, is this a required flag. This must be used as a keyword
373      argument.
374    **args: dict, the extra keyword args that are passed to :func:`DEFINE`.
375
376  Returns:
377    a handle to defined flag.
378  """
379  parser = _argument_parser.FloatParser(lower_bound, upper_bound)
380  serializer = _argument_parser.ArgumentSerializer()
381  result = DEFINE(
382      parser,
383      name,
384      default,
385      help,
386      flag_values,
387      serializer,
388      required=required,
389      **args)
390  _register_bounds_validator_if_needed(parser, name, flag_values=flag_values)
391  return result
392
393
394def DEFINE_integer(  # pylint: disable=invalid-name,redefined-builtin
395    name,
396    default,
397    help,
398    lower_bound=None,
399    upper_bound=None,
400    flag_values=_flagvalues.FLAGS,
401    required=False,
402    **args):
403  """Registers a flag whose value must be an integer.
404
405  If ``lower_bound``, or ``upper_bound`` are set, then this flag must be
406  within the given range.
407
408  Args:
409    name: str, the flag name.
410    default: int|str|None, the default value of the flag.
411    help: str, the help message.
412    lower_bound: int, min value of the flag.
413    upper_bound: int, max value of the flag.
414    flag_values: :class:`FlagValues`, the FlagValues instance with which the
415      flag will be registered. This should almost never need to be overridden.
416    required: bool, is this a required flag. This must be used as a keyword
417      argument.
418    **args: dict, the extra keyword args that are passed to :func:`DEFINE`.
419
420  Returns:
421    a handle to defined flag.
422  """
423  parser = _argument_parser.IntegerParser(lower_bound, upper_bound)
424  serializer = _argument_parser.ArgumentSerializer()
425  result = DEFINE(
426      parser,
427      name,
428      default,
429      help,
430      flag_values,
431      serializer,
432      required=required,
433      **args)
434  _register_bounds_validator_if_needed(parser, name, flag_values=flag_values)
435  return result
436
437
438def DEFINE_enum(  # pylint: disable=invalid-name,redefined-builtin
439    name,
440    default,
441    enum_values,
442    help,
443    flag_values=_flagvalues.FLAGS,
444    module_name=None,
445    required=False,
446    **args):
447  """Registers a flag whose value can be any string from enum_values.
448
449  Instead of a string enum, prefer `DEFINE_enum_class`, which allows
450  defining enums from an `enum.Enum` class.
451
452  Args:
453    name: str, the flag name.
454    default: str|None, the default value of the flag.
455    enum_values: [str], a non-empty list of strings with the possible values for
456      the flag.
457    help: str, the help message.
458    flag_values: :class:`FlagValues`, the FlagValues instance with which the
459      flag will be registered. This should almost never need to be overridden.
460    module_name: str, the name of the Python module declaring this flag. If not
461      provided, it will be computed using the stack trace of this call.
462    required: bool, is this a required flag. This must be used as a keyword
463      argument.
464    **args: dict, the extra keyword args that are passed to ``Flag.__init__``.
465
466  Returns:
467    a handle to defined flag.
468  """
469  return DEFINE_flag(
470      _flag.EnumFlag(name, default, help, enum_values, **args), flag_values,
471      module_name, required)
472
473
474def DEFINE_enum_class(  # pylint: disable=invalid-name,redefined-builtin
475    name,
476    default,
477    enum_class,
478    help,
479    flag_values=_flagvalues.FLAGS,
480    module_name=None,
481    case_sensitive=False,
482    required=False,
483    **args):
484  """Registers a flag whose value can be the name of enum members.
485
486  Args:
487    name: str, the flag name.
488    default: Enum|str|None, the default value of the flag.
489    enum_class: class, the Enum class with all the possible values for the flag.
490    help: str, the help message.
491    flag_values: :class:`FlagValues`, the FlagValues instance with which the
492      flag will be registered. This should almost never need to be overridden.
493    module_name: str, the name of the Python module declaring this flag. If not
494      provided, it will be computed using the stack trace of this call.
495    case_sensitive: bool, whether to map strings to members of the enum_class
496      without considering case.
497    required: bool, is this a required flag. This must be used as a keyword
498      argument.
499    **args: dict, the extra keyword args that are passed to ``Flag.__init__``.
500
501  Returns:
502    a handle to defined flag.
503  """
504  return DEFINE_flag(
505      _flag.EnumClassFlag(
506          name,
507          default,
508          help,
509          enum_class,
510          case_sensitive=case_sensitive,
511          **args), flag_values, module_name, required)
512
513
514def DEFINE_list(  # pylint: disable=invalid-name,redefined-builtin
515    name,
516    default,
517    help,
518    flag_values=_flagvalues.FLAGS,
519    required=False,
520    **args):
521  """Registers a flag whose value is a comma-separated list of strings.
522
523  The flag value is parsed with a CSV parser.
524
525  Args:
526    name: str, the flag name.
527    default: list|str|None, the default value of the flag.
528    help: str, the help message.
529    flag_values: :class:`FlagValues`, the FlagValues instance with which the
530      flag will be registered. This should almost never need to be overridden.
531    required: bool, is this a required flag. This must be used as a keyword
532      argument.
533    **args: Dictionary with extra keyword args that are passed to the
534      ``Flag.__init__``.
535
536  Returns:
537    a handle to defined flag.
538  """
539  parser = _argument_parser.ListParser()
540  serializer = _argument_parser.CsvListSerializer(',')
541  return DEFINE(
542      parser,
543      name,
544      default,
545      help,
546      flag_values,
547      serializer,
548      required=required,
549      **args)
550
551
552def DEFINE_spaceseplist(  # pylint: disable=invalid-name,redefined-builtin
553    name,
554    default,
555    help,
556    comma_compat=False,
557    flag_values=_flagvalues.FLAGS,
558    required=False,
559    **args):
560  """Registers a flag whose value is a whitespace-separated list of strings.
561
562  Any whitespace can be used as a separator.
563
564  Args:
565    name: str, the flag name.
566    default: list|str|None, the default value of the flag.
567    help: str, the help message.
568    comma_compat: bool - Whether to support comma as an additional separator. If
569      false then only whitespace is supported.  This is intended only for
570      backwards compatibility with flags that used to be comma-separated.
571    flag_values: :class:`FlagValues`, the FlagValues instance with which the
572      flag will be registered. This should almost never need to be overridden.
573    required: bool, is this a required flag. This must be used as a keyword
574      argument.
575    **args: Dictionary with extra keyword args that are passed to the
576      ``Flag.__init__``.
577
578  Returns:
579    a handle to defined flag.
580  """
581  parser = _argument_parser.WhitespaceSeparatedListParser(
582      comma_compat=comma_compat)
583  serializer = _argument_parser.ListSerializer(' ')
584  return DEFINE(
585      parser,
586      name,
587      default,
588      help,
589      flag_values,
590      serializer,
591      required=required,
592      **args)
593
594
595def DEFINE_multi(  # pylint: disable=invalid-name,redefined-builtin
596    parser,
597    serializer,
598    name,
599    default,
600    help,
601    flag_values=_flagvalues.FLAGS,
602    module_name=None,
603    required=False,
604    **args):
605  """Registers a generic MultiFlag that parses its args with a given parser.
606
607  Auxiliary function.  Normal users should NOT use it directly.
608
609  Developers who need to create their own 'Parser' classes for options
610  which can appear multiple times can call this module function to
611  register their flags.
612
613  Args:
614    parser: ArgumentParser, used to parse the flag arguments.
615    serializer: ArgumentSerializer, the flag serializer instance.
616    name: str, the flag name.
617    default: Union[Iterable[T], Text, None], the default value of the flag. If
618      the value is text, it will be parsed as if it was provided from the
619      command line. If the value is a non-string iterable, it will be iterated
620      over to create a shallow copy of the values. If it is None, it is left
621      as-is.
622    help: str, the help message.
623    flag_values: :class:`FlagValues`, the FlagValues instance with which the
624      flag will be registered. This should almost never need to be overridden.
625    module_name: A string, the name of the Python module declaring this flag. If
626      not provided, it will be computed using the stack trace of this call.
627    required: bool, is this a required flag. This must be used as a keyword
628      argument.
629    **args: Dictionary with extra keyword args that are passed to the
630      ``Flag.__init__``.
631
632  Returns:
633    a handle to defined flag.
634  """
635  return DEFINE_flag(
636      _flag.MultiFlag(parser, serializer, name, default, help, **args),
637      flag_values, module_name, required)
638
639
640def DEFINE_multi_string(  # pylint: disable=invalid-name,redefined-builtin
641    name,
642    default,
643    help,
644    flag_values=_flagvalues.FLAGS,
645    required=False,
646    **args):
647  """Registers a flag whose value can be a list of any strings.
648
649  Use the flag on the command line multiple times to place multiple
650  string values into the list.  The 'default' may be a single string
651  (which will be converted into a single-element list) or a list of
652  strings.
653
654
655  Args:
656    name: str, the flag name.
657    default: Union[Iterable[Text], Text, None], the default value of the flag;
658      see :func:`DEFINE_multi`.
659    help: str, the help message.
660    flag_values: :class:`FlagValues`, the FlagValues instance with which the
661      flag will be registered. This should almost never need to be overridden.
662    required: bool, is this a required flag. This must be used as a keyword
663      argument.
664    **args: Dictionary with extra keyword args that are passed to the
665      ``Flag.__init__``.
666
667  Returns:
668    a handle to defined flag.
669  """
670  parser = _argument_parser.ArgumentParser()
671  serializer = _argument_parser.ArgumentSerializer()
672  return DEFINE_multi(
673      parser,
674      serializer,
675      name,
676      default,
677      help,
678      flag_values,
679      required=required,
680      **args)
681
682
683def DEFINE_multi_integer(  # pylint: disable=invalid-name,redefined-builtin
684    name,
685    default,
686    help,
687    lower_bound=None,
688    upper_bound=None,
689    flag_values=_flagvalues.FLAGS,
690    required=False,
691    **args):
692  """Registers a flag whose value can be a list of arbitrary integers.
693
694  Use the flag on the command line multiple times to place multiple
695  integer values into the list.  The 'default' may be a single integer
696  (which will be converted into a single-element list) or a list of
697  integers.
698
699  Args:
700    name: str, the flag name.
701    default: Union[Iterable[int], Text, None], the default value of the flag;
702      see `DEFINE_multi`.
703    help: str, the help message.
704    lower_bound: int, min values of the flag.
705    upper_bound: int, max values of the flag.
706    flag_values: :class:`FlagValues`, the FlagValues instance with which the
707      flag will be registered. This should almost never need to be overridden.
708    required: bool, is this a required flag. This must be used as a keyword
709      argument.
710    **args: Dictionary with extra keyword args that are passed to the
711      ``Flag.__init__``.
712
713  Returns:
714    a handle to defined flag.
715  """
716  parser = _argument_parser.IntegerParser(lower_bound, upper_bound)
717  serializer = _argument_parser.ArgumentSerializer()
718  return DEFINE_multi(
719      parser,
720      serializer,
721      name,
722      default,
723      help,
724      flag_values,
725      required=required,
726      **args)
727
728
729def DEFINE_multi_float(  # pylint: disable=invalid-name,redefined-builtin
730    name,
731    default,
732    help,
733    lower_bound=None,
734    upper_bound=None,
735    flag_values=_flagvalues.FLAGS,
736    required=False,
737    **args):
738  """Registers a flag whose value can be a list of arbitrary floats.
739
740  Use the flag on the command line multiple times to place multiple
741  float values into the list.  The 'default' may be a single float
742  (which will be converted into a single-element list) or a list of
743  floats.
744
745  Args:
746    name: str, the flag name.
747    default: Union[Iterable[float], Text, None], the default value of the flag;
748      see `DEFINE_multi`.
749    help: str, the help message.
750    lower_bound: float, min values of the flag.
751    upper_bound: float, max values of the flag.
752    flag_values: :class:`FlagValues`, the FlagValues instance with which the
753      flag will be registered. This should almost never need to be overridden.
754    required: bool, is this a required flag. This must be used as a keyword
755      argument.
756    **args: Dictionary with extra keyword args that are passed to the
757      ``Flag.__init__``.
758
759  Returns:
760    a handle to defined flag.
761  """
762  parser = _argument_parser.FloatParser(lower_bound, upper_bound)
763  serializer = _argument_parser.ArgumentSerializer()
764  return DEFINE_multi(
765      parser,
766      serializer,
767      name,
768      default,
769      help,
770      flag_values,
771      required=required,
772      **args)
773
774
775def DEFINE_multi_enum(  # pylint: disable=invalid-name,redefined-builtin
776    name,
777    default,
778    enum_values,
779    help,
780    flag_values=_flagvalues.FLAGS,
781    case_sensitive=True,
782    required=False,
783    **args):
784  """Registers a flag whose value can be a list strings from enum_values.
785
786  Use the flag on the command line multiple times to place multiple
787  enum values into the list.  The 'default' may be a single string
788  (which will be converted into a single-element list) or a list of
789  strings.
790
791  Args:
792    name: str, the flag name.
793    default: Union[Iterable[Text], Text, None], the default value of the flag;
794      see `DEFINE_multi`.
795    enum_values: [str], a non-empty list of strings with the possible values for
796      the flag.
797    help: str, the help message.
798    flag_values: :class:`FlagValues`, the FlagValues instance with which the
799      flag will be registered. This should almost never need to be overridden.
800    case_sensitive: Whether or not the enum is to be case-sensitive.
801    required: bool, is this a required flag. This must be used as a keyword
802      argument.
803    **args: Dictionary with extra keyword args that are passed to the
804      ``Flag.__init__``.
805
806  Returns:
807    a handle to defined flag.
808  """
809  parser = _argument_parser.EnumParser(enum_values, case_sensitive)
810  serializer = _argument_parser.ArgumentSerializer()
811  return DEFINE_multi(
812      parser,
813      serializer,
814      name,
815      default,
816      '<%s>: %s' % ('|'.join(enum_values), help),
817      flag_values,
818      required=required,
819      **args)
820
821
822def DEFINE_multi_enum_class(  # pylint: disable=invalid-name,redefined-builtin
823    name,
824    default,
825    enum_class,
826    help,
827    flag_values=_flagvalues.FLAGS,
828    module_name=None,
829    case_sensitive=False,
830    required=False,
831    **args):
832  """Registers a flag whose value can be a list of enum members.
833
834  Use the flag on the command line multiple times to place multiple
835  enum values into the list.
836
837  Args:
838    name: str, the flag name.
839    default: Union[Iterable[Enum], Iterable[Text], Enum, Text, None], the
840      default value of the flag; see `DEFINE_multi`; only differences are
841      documented here. If the value is a single Enum, it is treated as a
842      single-item list of that Enum value. If it is an iterable, text values
843      within the iterable will be converted to the equivalent Enum objects.
844    enum_class: class, the Enum class with all the possible values for the flag.
845        help: str, the help message.
846    flag_values: :class:`FlagValues`, the FlagValues instance with which the
847      flag will be registered. This should almost never need to be overridden.
848    module_name: A string, the name of the Python module declaring this flag. If
849      not provided, it will be computed using the stack trace of this call.
850    case_sensitive: bool, whether to map strings to members of the enum_class
851      without considering case.
852    required: bool, is this a required flag. This must be used as a keyword
853      argument.
854    **args: Dictionary with extra keyword args that are passed to the
855      ``Flag.__init__``.
856
857  Returns:
858    a handle to defined flag.
859  """
860  return DEFINE_flag(
861      _flag.MultiEnumClassFlag(
862          name, default, help, enum_class, case_sensitive=case_sensitive),
863      flag_values,
864      module_name,
865      required=required,
866      **args)
867
868
869def DEFINE_alias(  # pylint: disable=invalid-name
870    name,
871    original_name,
872    flag_values=_flagvalues.FLAGS,
873    module_name=None):
874  """Defines an alias flag for an existing one.
875
876  Args:
877    name: str, the flag name.
878    original_name: str, the original flag name.
879    flag_values: :class:`FlagValues`, the FlagValues instance with which the
880      flag will be registered. This should almost never need to be overridden.
881    module_name: A string, the name of the module that defines this flag.
882
883  Returns:
884    a handle to defined flag.
885
886  Raises:
887    flags.FlagError:
888      UnrecognizedFlagError: if the referenced flag doesn't exist.
889      DuplicateFlagError: if the alias name has been used by some existing flag.
890  """
891  if original_name not in flag_values:
892    raise _exceptions.UnrecognizedFlagError(original_name)
893  flag = flag_values[original_name]
894
895  class _FlagAlias(_flag.Flag):
896    """Overrides Flag class so alias value is copy of original flag value."""
897
898    def parse(self, argument):
899      flag.parse(argument)
900      self.present += 1
901
902    def _parse_from_default(self, value):
903      # The value was already parsed by the aliased flag, so there is no
904      # need to call the parser on it a second time.
905      # Additionally, because of how MultiFlag parses and merges values,
906      # it isn't possible to delegate to the aliased flag and still get
907      # the correct values.
908      return value
909
910    @property
911    def value(self):
912      return flag.value
913
914    @value.setter
915    def value(self, value):
916      flag.value = value
917
918  help_msg = 'Alias for --%s.' % flag.name
919  # If alias_name has been used, flags.DuplicatedFlag will be raised.
920  return DEFINE_flag(
921      _FlagAlias(
922          flag.parser,
923          flag.serializer,
924          name,
925          flag.default,
926          help_msg,
927          boolean=flag.boolean), flag_values, module_name)
928