aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorYilei Yang <yileiyang@google.com>2022-08-24 10:45:12 -0700
committerCopybara-Service <copybara-worker@google.com>2022-08-24 10:45:52 -0700
commit0930779ec458c5345b85c93dfdf4fe35877fe88b (patch)
treef5cfe340188f5ccc6cac107f9d74a4617f41e4eb
parent9078fc40dc7809173e51ce8fca600033d17c493a (diff)
downloadabsl-py-0930779ec458c5345b85c93dfdf4fe35877fe88b.tar.gz
Expose the public APIs as the `__all__` attribute in `absl/flags/__init__.py`.
This also makes sphinx autodoc generate docs for exposed APIs. Also make `absl.flags`'s docstring compatible with reST. PiperOrigin-RevId: 469768218 Change-Id: I6fd3807de05d6803a0aa73b3872555e53d504e8d
-rw-r--r--absl/flags/__init__.py75
-rw-r--r--absl/flags/_argument_parser.py10
-rw-r--r--absl/flags/_defines.py160
-rw-r--r--absl/flags/_exceptions.py18
-rw-r--r--absl/flags/_flag.py83
-rw-r--r--absl/flags/_flagvalues.py97
-rw-r--r--absl/flags/_helpers.py18
-rw-r--r--absl/flags/_validators.py80
8 files changed, 317 insertions, 224 deletions
diff --git a/absl/flags/__init__.py b/absl/flags/__init__.py
index e6014a6..45e64f3 100644
--- a/absl/flags/__init__.py
+++ b/absl/flags/__init__.py
@@ -40,6 +40,79 @@ from absl.flags import _flagvalues
from absl.flags import _helpers
from absl.flags import _validators
+__all__ = (
+ 'DEFINE',
+ 'DEFINE_flag',
+ 'DEFINE_string',
+ 'DEFINE_boolean',
+ 'DEFINE_bool',
+ 'DEFINE_float',
+ 'DEFINE_integer',
+ 'DEFINE_enum',
+ 'DEFINE_enum_class',
+ 'DEFINE_list',
+ 'DEFINE_spaceseplist',
+ 'DEFINE_multi',
+ 'DEFINE_multi_string',
+ 'DEFINE_multi_integer',
+ 'DEFINE_multi_float',
+ 'DEFINE_multi_enum',
+ 'DEFINE_multi_enum_class',
+ 'DEFINE_alias',
+ # Flag validators.
+ 'register_validator',
+ 'validator',
+ 'register_multi_flags_validator',
+ 'multi_flags_validator',
+ 'mark_flag_as_required',
+ 'mark_flags_as_required',
+ 'mark_flags_as_mutual_exclusive',
+ 'mark_bool_flags_as_mutual_exclusive',
+ # Key flag related functions.
+ 'declare_key_flag',
+ 'adopt_module_key_flags',
+ 'disclaim_key_flags',
+ # Module exceptions.
+ 'Error',
+ 'CantOpenFlagFileError',
+ 'DuplicateFlagError',
+ 'IllegalFlagValueError',
+ 'UnrecognizedFlagError',
+ 'UnparsedFlagAccessError',
+ 'ValidationError',
+ 'FlagNameConflictsWithMethodError',
+ # Public classes.
+ 'Flag',
+ 'BooleanFlag',
+ 'EnumFlag',
+ 'EnumClassFlag',
+ 'MultiFlag',
+ 'MultiEnumClassFlag',
+ 'FlagHolder',
+ 'FlagValues',
+ 'ArgumentParser',
+ 'BooleanParser',
+ 'EnumParser',
+ 'EnumClassParser',
+ 'ArgumentSerializer',
+ 'FloatParser',
+ 'IntegerParser',
+ 'BaseListParser',
+ 'ListParser',
+ 'ListSerializer',
+ 'EnumClassListSerializer',
+ 'CsvListSerializer',
+ 'WhitespaceSeparatedListParser',
+ 'EnumClassSerializer',
+ # Helper functions.
+ 'get_help_width',
+ 'text_wrap',
+ 'flag_dict_to_args',
+ 'doc_to_help',
+ # The global FlagValues instance.
+ 'FLAGS',
+)
+
# Initialize the FLAGS_MODULE as early as possible.
# It's only used by adopt_module_key_flags to take SPECIAL_FLAGS into account.
_helpers.FLAGS_MODULE = sys.modules[__name__]
@@ -141,5 +214,5 @@ DEFINE_string('undefok', '',
'arguments MUST use the --flag=value format.',
_helpers.SPECIAL_FLAGS) # pytype: disable=wrong-arg-types
-# The global FlagValues instance.
+#: The global FlagValues instance.
FLAGS = _flagvalues.FLAGS
diff --git a/absl/flags/_argument_parser.py b/absl/flags/_argument_parser.py
index 9c6c8c6..7a94c69 100644
--- a/absl/flags/_argument_parser.py
+++ b/absl/flags/_argument_parser.py
@@ -93,9 +93,9 @@ class _ArgumentParserCache(type):
class ArgumentParser(metaclass=_ArgumentParserCache):
"""Base class used to parse and convert arguments.
- The parse() method checks to make sure that the string argument is a
+ The :meth:`parse` method checks to make sure that the string argument is a
legal value and convert it to a native type. If the value cannot be
- converted, it should throw a 'ValueError' exception with a human
+ converted, it should throw a ``ValueError`` exception with a human
readable explanation of why the value is illegal.
Subclasses should also define a syntactic_help string which may be
@@ -458,7 +458,7 @@ class ListSerializer(ArgumentSerializer):
class EnumClassListSerializer(ListSerializer):
- """A serializer for MultiEnumClass flags.
+ """A serializer for :class:`MultiEnumClass` flags.
This serializer simply joins the output of `EnumClassSerializer` using a
provided separator.
@@ -521,9 +521,9 @@ class EnumClassSerializer(ArgumentSerializer):
class BaseListParser(ArgumentParser):
"""Base class for a parser of lists of strings.
- To extend, inherit from this class; from the subclass __init__, call
+ To extend, inherit from this class; from the subclass ``__init__``, call::
- BaseListParser.__init__(self, token, name)
+ super().__init__(token, name)
where token is a character used to tokenize, and name is a description
of the separator.
diff --git a/absl/flags/_defines.py b/absl/flags/_defines.py
index a102652..12335e5 100644
--- a/absl/flags/_defines.py
+++ b/absl/flags/_defines.py
@@ -77,22 +77,22 @@ def DEFINE( # pylint: disable=invalid-name
NOTE: in the docstrings of all DEFINE* functions, "registers" is short
for "creates a new flag and registers it".
- Auxiliary function: clients should use the specialized DEFINE_<type>
+ Auxiliary function: clients should use the specialized ``DEFINE_<type>``
function instead.
Args:
- parser: ArgumentParser, used to parse the flag arguments.
+ parser: :class:`ArgumentParser`, used to parse the flag arguments.
name: str, the flag name.
default: The default value of the flag.
help: str, the help message.
- flag_values: FlagValues, the FlagValues instance with which the flag will be
- registered. This should almost never need to be overridden.
- serializer: ArgumentSerializer, the flag serializer instance.
+ flag_values: :class:`FlagValues`, the FlagValues instance with which the
+ flag will be registered. This should almost never need to be overridden.
+ serializer: :class:`ArgumentSerializer`, the flag serializer instance.
module_name: str, the name of the Python module declaring this flag. If not
provided, it will be computed using the stack trace of this call.
required: bool, is this a required flag. This must be used as a keyword
argument.
- **args: dict, the extra keyword args that are passed to Flag __init__.
+ **args: dict, the extra keyword args that are passed to ``Flag.__init__``.
Returns:
a handle to defined flag.
@@ -107,19 +107,19 @@ def DEFINE_flag( # pylint: disable=invalid-name
flag_values=_flagvalues.FLAGS,
module_name=None,
required=False):
- """Registers a 'Flag' object with a 'FlagValues' object.
+ """Registers a :class:`Flag` object with a :class:`FlagValues` object.
- By default, the global FLAGS 'FlagValue' object is used.
+ By default, the global :const:`FLAGS` ``FlagValue`` object is used.
Typical users will use one of the more specialized DEFINE_xxx
- functions, such as DEFINE_string or DEFINE_integer. But developers
- who need to create Flag objects themselves should use this function
- to register their flags.
+ functions, such as :func:`DEFINE_string` or :func:`DEFINE_integer`. But
+ developers who need to create :class:`Flag` objects themselves should use
+ this function to register their flags.
Args:
- flag: Flag, a flag that is key to the module.
- flag_values: FlagValues, the FlagValues instance with which the flag will be
- registered. This should almost never need to be overridden.
+ flag: :class:`Flag`, a flag that is key to the module.
+ flag_values: :class:`FlagValues`, the ``FlagValues`` instance with which the
+ flag will be registered. This should almost never need to be overridden.
module_name: str, the name of the Python module declaring this flag. If not
provided, it will be computed using the stack trace of this call.
required: bool, is this a required flag. This must be used as a keyword
@@ -159,14 +159,14 @@ def _internal_declare_key_flags(flag_names,
Args:
flag_names: [str], a list of strings that are names of already-registered
Flag objects.
- flag_values: FlagValues, the FlagValues instance with which the flags listed
- in flag_names have registered (the value of the flag_values argument from
- the DEFINE_* calls that defined those flags). This should almost never
+ flag_values: :class:`FlagValues`, the FlagValues instance with which the
+ flags listed in flag_names have registered (the value of the flag_values
+ argument from the ``DEFINE_*`` calls that defined those flags). This
+ should almost never need to be overridden.
+ key_flag_values: :class:`FlagValues`, the FlagValues instance that (among
+ possibly many other things) keeps track of the key flags for each module.
+ Default ``None`` means "same as flag_values". This should almost never
need to be overridden.
- key_flag_values: FlagValues, the FlagValues instance that (among possibly
- many other things) keeps track of the key flags for each module. Default
- None means "same as flag_values". This should almost never need to be
- overridden.
Raises:
UnrecognizedFlagError: Raised when the flag is not defined.
@@ -189,16 +189,17 @@ def declare_key_flag(flag_name, flag_values=_flagvalues.FLAGS):
main module are listed (instead of all flags, as in the case of
--helpfull).
- Sample usage:
+ Sample usage::
- flags.declare_key_flag('flag_1')
+ flags.declare_key_flag('flag_1')
Args:
flag_name: str, the name of an already declared flag. (Redeclaring flags as
key, including flags implicitly key because they were declared in this
module, is a no-op.)
- flag_values: FlagValues, the FlagValues instance in which the flag will be
- declared as a key flag. This should almost never need to be overridden.
+ flag_values: :class:`FlagValues`, the FlagValues instance in which the
+ flag will be declared as a key flag. This should almost never need to be
+ overridden.
Raises:
ValueError: Raised if flag_name not defined as a Python flag.
@@ -225,8 +226,9 @@ def adopt_module_key_flags(module, flag_values=_flagvalues.FLAGS):
Args:
module: module, the module object from which all key flags will be declared
as key flags to the current module.
- flag_values: FlagValues, the FlagValues instance in which the flags will be
- declared as key flags. This should almost never need to be overridden.
+ flag_values: :class:`FlagValues`, the FlagValues instance in which the
+ flags will be declared as key flags. This should almost never need to be
+ overridden.
Raises:
Error: Raised when given an argument that is a module name (a string),
@@ -312,13 +314,13 @@ def DEFINE_boolean( # pylint: disable=invalid-name,redefined-builtin
name: str, the flag name.
default: bool|str|None, the default value of the flag.
help: str, the help message.
- flag_values: FlagValues, the FlagValues instance with which the flag will be
- registered. This should almost never need to be overridden.
+ flag_values: :class:`FlagValues`, the FlagValues instance with which the
+ flag will be registered. This should almost never need to be overridden.
module_name: str, the name of the Python module declaring this flag. If not
provided, it will be computed using the stack trace of this call.
required: bool, is this a required flag. This must be used as a keyword
argument.
- **args: dict, the extra keyword args that are passed to Flag __init__.
+ **args: dict, the extra keyword args that are passed to ``Flag.__init__``.
Returns:
a handle to defined flag.
@@ -339,7 +341,7 @@ def DEFINE_float( # pylint: disable=invalid-name,redefined-builtin
**args):
"""Registers a flag whose value must be a float.
- If lower_bound or upper_bound are set, then this flag must be
+ If ``lower_bound`` or ``upper_bound`` are set, then this flag must be
within the given range.
Args:
@@ -348,11 +350,11 @@ def DEFINE_float( # pylint: disable=invalid-name,redefined-builtin
help: str, the help message.
lower_bound: float, min value of the flag.
upper_bound: float, max value of the flag.
- flag_values: FlagValues, the FlagValues instance with which the flag will be
- registered. This should almost never need to be overridden.
+ flag_values: :class:`FlagValues`, the FlagValues instance with which the
+ flag will be registered. This should almost never need to be overridden.
required: bool, is this a required flag. This must be used as a keyword
argument.
- **args: dict, the extra keyword args that are passed to DEFINE.
+ **args: dict, the extra keyword args that are passed to :func:`DEFINE`.
Returns:
a handle to defined flag.
@@ -383,7 +385,7 @@ def DEFINE_integer( # pylint: disable=invalid-name,redefined-builtin
**args):
"""Registers a flag whose value must be an integer.
- If lower_bound, or upper_bound are set, then this flag must be
+ If ``lower_bound``, or ``upper_bound`` are set, then this flag must be
within the given range.
Args:
@@ -392,11 +394,11 @@ def DEFINE_integer( # pylint: disable=invalid-name,redefined-builtin
help: str, the help message.
lower_bound: int, min value of the flag.
upper_bound: int, max value of the flag.
- flag_values: FlagValues, the FlagValues instance with which the flag will be
- registered. This should almost never need to be overridden.
+ flag_values: :class:`FlagValues`, the FlagValues instance with which the
+ flag will be registered. This should almost never need to be overridden.
required: bool, is this a required flag. This must be used as a keyword
argument.
- **args: dict, the extra keyword args that are passed to DEFINE.
+ **args: dict, the extra keyword args that are passed to :func:`DEFINE`.
Returns:
a handle to defined flag.
@@ -436,13 +438,13 @@ def DEFINE_enum( # pylint: disable=invalid-name,redefined-builtin
enum_values: [str], a non-empty list of strings with the possible values for
the flag.
help: str, the help message.
- flag_values: FlagValues, the FlagValues instance with which the flag will be
- registered. This should almost never need to be overridden.
+ flag_values: :class:`FlagValues`, the FlagValues instance with which the
+ flag will be registered. This should almost never need to be overridden.
module_name: str, the name of the Python module declaring this flag. If not
provided, it will be computed using the stack trace of this call.
required: bool, is this a required flag. This must be used as a keyword
argument.
- **args: dict, the extra keyword args that are passed to Flag __init__.
+ **args: dict, the extra keyword args that are passed to ``Flag.__init__``.
Returns:
a handle to defined flag.
@@ -469,15 +471,15 @@ def DEFINE_enum_class( # pylint: disable=invalid-name,redefined-builtin
default: Enum|str|None, the default value of the flag.
enum_class: class, the Enum class with all the possible values for the flag.
help: str, the help message.
- flag_values: FlagValues, the FlagValues instance with which the flag will be
- registered. This should almost never need to be overridden.
+ flag_values: :class:`FlagValues`, the FlagValues instance with which the
+ flag will be registered. This should almost never need to be overridden.
module_name: str, the name of the Python module declaring this flag. If not
provided, it will be computed using the stack trace of this call.
case_sensitive: bool, whether to map strings to members of the enum_class
without considering case.
required: bool, is this a required flag. This must be used as a keyword
argument.
- **args: dict, the extra keyword args that are passed to Flag __init__.
+ **args: dict, the extra keyword args that are passed to ``Flag.__init__``.
Returns:
a handle to defined flag.
@@ -507,12 +509,12 @@ def DEFINE_list( # pylint: disable=invalid-name,redefined-builtin
name: str, the flag name.
default: list|str|None, the default value of the flag.
help: str, the help message.
- flag_values: FlagValues, the FlagValues instance with which the flag will be
- registered. This should almost never need to be overridden.
+ flag_values: :class:`FlagValues`, the FlagValues instance with which the
+ flag will be registered. This should almost never need to be overridden.
required: bool, is this a required flag. This must be used as a keyword
argument.
- **args: Dictionary with extra keyword args that are passed to the Flag
- __init__.
+ **args: Dictionary with extra keyword args that are passed to the
+ ``Flag.__init__``.
Returns:
a handle to defined flag.
@@ -549,12 +551,12 @@ def DEFINE_spaceseplist( # pylint: disable=invalid-name,redefined-builtin
comma_compat: bool - Whether to support comma as an additional separator. If
false then only whitespace is supported. This is intended only for
backwards compatibility with flags that used to be comma-separated.
- flag_values: FlagValues, the FlagValues instance with which the flag will be
- registered. This should almost never need to be overridden.
+ flag_values: :class:`FlagValues`, the FlagValues instance with which the
+ flag will be registered. This should almost never need to be overridden.
required: bool, is this a required flag. This must be used as a keyword
argument.
- **args: Dictionary with extra keyword args that are passed to the Flag
- __init__.
+ **args: Dictionary with extra keyword args that are passed to the
+ ``Flag.__init__``.
Returns:
a handle to defined flag.
@@ -601,14 +603,14 @@ def DEFINE_multi( # pylint: disable=invalid-name,redefined-builtin
over to create a shallow copy of the values. If it is None, it is left
as-is.
help: str, the help message.
- flag_values: FlagValues, the FlagValues instance with which the flag will be
- registered. This should almost never need to be overridden.
+ flag_values: :class:`FlagValues`, the FlagValues instance with which the
+ flag will be registered. This should almost never need to be overridden.
module_name: A string, the name of the Python module declaring this flag. If
not provided, it will be computed using the stack trace of this call.
required: bool, is this a required flag. This must be used as a keyword
argument.
- **args: Dictionary with extra keyword args that are passed to the Flag
- __init__.
+ **args: Dictionary with extra keyword args that are passed to the
+ ``Flag.__init__``.
Returns:
a handle to defined flag.
@@ -636,14 +638,14 @@ def DEFINE_multi_string( # pylint: disable=invalid-name,redefined-builtin
Args:
name: str, the flag name.
default: Union[Iterable[Text], Text, None], the default value of the flag;
- see `DEFINE_multi`.
+ see :func:`DEFINE_multi`.
help: str, the help message.
- flag_values: FlagValues, the FlagValues instance with which the flag will be
- registered. This should almost never need to be overridden.
+ flag_values: :class:`FlagValues`, the FlagValues instance with which the
+ flag will be registered. This should almost never need to be overridden.
required: bool, is this a required flag. This must be used as a keyword
argument.
- **args: Dictionary with extra keyword args that are passed to the Flag
- __init__.
+ **args: Dictionary with extra keyword args that are passed to the
+ ``Flag.__init__``.
Returns:
a handle to defined flag.
@@ -684,12 +686,12 @@ def DEFINE_multi_integer( # pylint: disable=invalid-name,redefined-builtin
help: str, the help message.
lower_bound: int, min values of the flag.
upper_bound: int, max values of the flag.
- flag_values: FlagValues, the FlagValues instance with which the flag will be
- registered. This should almost never need to be overridden.
+ flag_values: :class:`FlagValues`, the FlagValues instance with which the
+ flag will be registered. This should almost never need to be overridden.
required: bool, is this a required flag. This must be used as a keyword
argument.
- **args: Dictionary with extra keyword args that are passed to the Flag
- __init__.
+ **args: Dictionary with extra keyword args that are passed to the
+ ``Flag.__init__``.
Returns:
a handle to defined flag.
@@ -730,12 +732,12 @@ def DEFINE_multi_float( # pylint: disable=invalid-name,redefined-builtin
help: str, the help message.
lower_bound: float, min values of the flag.
upper_bound: float, max values of the flag.
- flag_values: FlagValues, the FlagValues instance with which the flag will be
- registered. This should almost never need to be overridden.
+ flag_values: :class:`FlagValues`, the FlagValues instance with which the
+ flag will be registered. This should almost never need to be overridden.
required: bool, is this a required flag. This must be used as a keyword
argument.
- **args: Dictionary with extra keyword args that are passed to the Flag
- __init__.
+ **args: Dictionary with extra keyword args that are passed to the
+ ``Flag.__init__``.
Returns:
a handle to defined flag.
@@ -776,13 +778,13 @@ def DEFINE_multi_enum( # pylint: disable=invalid-name,redefined-builtin
enum_values: [str], a non-empty list of strings with the possible values for
the flag.
help: str, the help message.
- flag_values: FlagValues, the FlagValues instance with which the flag will be
- registered. This should almost never need to be overridden.
+ flag_values: :class:`FlagValues`, the FlagValues instance with which the
+ flag will be registered. This should almost never need to be overridden.
case_sensitive: Whether or not the enum is to be case-sensitive.
required: bool, is this a required flag. This must be used as a keyword
argument.
- **args: Dictionary with extra keyword args that are passed to the Flag
- __init__.
+ **args: Dictionary with extra keyword args that are passed to the
+ ``Flag.__init__``.
Returns:
a handle to defined flag.
@@ -824,16 +826,16 @@ def DEFINE_multi_enum_class( # pylint: disable=invalid-name,redefined-builtin
within the iterable will be converted to the equivalent Enum objects.
enum_class: class, the Enum class with all the possible values for the flag.
help: str, the help message.
- flag_values: FlagValues, the FlagValues instance with which the flag will be
- registered. This should almost never need to be overridden.
+ flag_values: :class:`FlagValues`, the FlagValues instance with which the
+ flag will be registered. This should almost never need to be overridden.
module_name: A string, the name of the Python module declaring this flag. If
not provided, it will be computed using the stack trace of this call.
case_sensitive: bool, whether to map strings to members of the enum_class
without considering case.
required: bool, is this a required flag. This must be used as a keyword
argument.
- **args: Dictionary with extra keyword args that are passed to the Flag
- __init__.
+ **args: Dictionary with extra keyword args that are passed to the
+ ``Flag.__init__``.
Returns:
a handle to defined flag.
@@ -857,8 +859,8 @@ def DEFINE_alias( # pylint: disable=invalid-name
Args:
name: str, the flag name.
original_name: str, the original flag name.
- flag_values: FlagValues, the FlagValues instance with which the flag will be
- registered. This should almost never need to be overridden.
+ flag_values: :class:`FlagValues`, the FlagValues instance with which the
+ flag will be registered. This should almost never need to be overridden.
module_name: A string, the name of the module that defines this flag.
Returns:
diff --git a/absl/flags/_exceptions.py b/absl/flags/_exceptions.py
index 0ca2777..b569d94 100644
--- a/absl/flags/_exceptions.py
+++ b/absl/flags/_exceptions.py
@@ -46,13 +46,13 @@ class DuplicateFlagError(Error):
Args:
flagname: str, the name of the flag being redefined.
- flag_values: FlagValues, the FlagValues instance containing the first
- definition of flagname.
- other_flag_values: FlagValues, if it is not None, it should be the
- FlagValues object where the second definition of flagname occurs.
- If it is None, we assume that we're being called when attempting
- to create the flag a second time, and we use the module calling
- this one as the source of the second definition.
+ flag_values: :class:`FlagValues`, the FlagValues instance containing the
+ first definition of flagname.
+ other_flag_values: :class:`FlagValues`, if it is not None, it should be
+ the FlagValues object where the second definition of flagname occurs.
+ If it is None, we assume that we're being called when attempting to
+ create the flag a second time, and we use the module calling this one
+ as the source of the second definition.
Returns:
An instance of DuplicateFlagError.
@@ -97,7 +97,7 @@ class UnrecognizedFlagError(Error):
class UnparsedFlagAccessError(Error):
- """Raised when accessing the flag value from unparsed FlagValues."""
+ """Raised when accessing the flag value from unparsed :class:`FlagValues`."""
class ValidationError(Error):
@@ -105,4 +105,4 @@ class ValidationError(Error):
class FlagNameConflictsWithMethodError(Error):
- """Raised when a flag name conflicts with FlagValues methods."""
+ """Raised when a flag name conflicts with :class:`FlagValues` methods."""
diff --git a/absl/flags/_flag.py b/absl/flags/_flag.py
index d7ad944..28d9219 100644
--- a/absl/flags/_flag.py
+++ b/absl/flags/_flag.py
@@ -31,42 +31,45 @@ from absl.flags import _helpers
class Flag(object):
"""Information about a command-line flag.
- 'Flag' objects define the following fields:
- .name - the name for this flag;
- .default - the default value for this flag;
- .default_unparsed - the unparsed default value for this flag.
- .default_as_str - default value as repr'd string, e.g., "'true'" (or None);
- .value - the most recent parsed value of this flag; set by parse();
- .help - a help string or None if no help is available;
- .short_name - the single letter alias for this flag (or None);
- .boolean - if 'true', this flag does not accept arguments;
- .present - true if this flag was parsed from command line flags;
- .parser - an ArgumentParser object;
- .serializer - an ArgumentSerializer object;
- .allow_override - the flag may be redefined without raising an error, and
- newly defined flag overrides the old one.
- .allow_override_cpp - use the flag from C++ if available; the flag
- definition is replaced by the C++ flag after init;
- .allow_hide_cpp - use the Python flag despite having a C++ flag with
- the same name (ignore the C++ flag);
- .using_default_value - the flag value has not been set by user;
- .allow_overwrite - the flag may be parsed more than once without raising
- an error, the last set value will be used;
- .allow_using_method_names - whether this flag can be defined even if it has
- a name that conflicts with a FlagValues method.
-
- The only public method of a 'Flag' object is parse(), but it is
- typically only called by a 'FlagValues' object. The parse() method is
- a thin wrapper around the 'ArgumentParser' parse() method. The parsed
- value is saved in .value, and the .present attribute is updated. If
- this flag was already present, an Error is raised.
-
- parse() is also called during __init__ to parse the default value and
- initialize the .value attribute. This enables other python modules to
- safely use flags even if the __main__ module neglects to parse the
- command line arguments. The .present attribute is cleared after
- __init__ parsing. If the default value is set to None, then the
- __init__ parsing step is skipped and the .value attribute is
+ Attributes:
+ name: the name for this flag
+ default: the default value for this flag
+ default_unparsed: the unparsed default value for this flag.
+ default_as_str: default value as repr'd string, e.g., "'true'"
+ (or None)
+ value: the most recent parsed value of this flag set by :meth:`parse`
+ help: a help string or None if no help is available
+ short_name: the single letter alias for this flag (or None)
+ boolean: if 'true', this flag does not accept arguments
+ present: true if this flag was parsed from command line flags
+ parser: an :class:`~absl.flags.ArgumentParser` object
+ serializer: an ArgumentSerializer object
+ allow_override: the flag may be redefined without raising an error,
+ and newly defined flag overrides the old one.
+ allow_override_cpp: use the flag from C++ if available the flag
+ definition is replaced by the C++ flag after init
+ allow_hide_cpp: use the Python flag despite having a C++ flag with
+ the same name (ignore the C++ flag)
+ using_default_value: the flag value has not been set by user
+ allow_overwrite: the flag may be parsed more than once without
+ raising an error, the last set value will be used
+ allow_using_method_names: whether this flag can be defined even if
+ it has a name that conflicts with a FlagValues method.
+ validators: list of the flag validators.
+
+ The only public method of a ``Flag`` object is :meth:`parse`, but it is
+ typically only called by a :class:`~absl.flags.FlagValues` object. The
+ :meth:`parse` method is a thin wrapper around the
+ :meth:`ArgumentParser.parse()<absl.flags.ArgumentParser.parse>` method. The
+ parsed value is saved in ``.value``, and the ``.present`` attribute is
+ updated. If this flag was already present, an Error is raised.
+
+ :meth:`parse` is also called during ``__init__`` to parse the default value
+ and initialize the ``.value`` attribute. This enables other python modules to
+ safely use flags even if the ``__main__`` module neglects to parse the
+ command line arguments. The ``.present`` attribute is cleared after
+ ``__init__`` parsing. If the default value is set to ``None``, then the
+ ``__init__`` parsing step is skipped and the ``.value`` attribute is
initialized to None.
Note: The default value is also presented to the user in the help
@@ -307,13 +310,13 @@ class BooleanFlag(Flag):
"""Basic boolean flag.
Boolean flags do not take any arguments, and their value is either
- True (1) or False (0). The false value is specified on the command
- line by prepending the word 'no' to either the long or the short flag
+ ``True`` (1) or ``False`` (0). The false value is specified on the command
+ line by prepending the word ``'no'`` to either the long or the short flag
name.
For example, if a Boolean flag was created whose long name was
- 'update' and whose short name was 'x', then this flag could be
- explicitly unset through either --noupdate or --nox.
+ ``'update'`` and whose short name was ``'x'``, then this flag could be
+ explicitly unset through either ``--noupdate`` or ``--nox``.
"""
def __init__(self, name, default, help, short_name=None, **args): # pylint: disable=redefined-builtin
diff --git a/absl/flags/_flagvalues.py b/absl/flags/_flagvalues.py
index 1b54fb3..c52990c 100644
--- a/absl/flags/_flagvalues.py
+++ b/absl/flags/_flagvalues.py
@@ -37,36 +37,41 @@ _T = TypeVar('_T')
class FlagValues:
- """Registry of 'Flag' objects.
+ """Registry of :class:`~absl.flags.Flag` objects.
- A 'FlagValues' can then scan command line arguments, passing flag
+ A :class:`FlagValues` can then scan command line arguments, passing flag
arguments through to the 'Flag' objects that it owns. It also
provides easy access to the flag values. Typically only one
- 'FlagValues' object is needed by an application: flags.FLAGS
+ :class:`FlagValues` object is needed by an application:
+ :const:`FLAGS`.
This class is heavily overloaded:
- 'Flag' objects are registered via __setitem__:
+ :class:`Flag` objects are registered via ``__setitem__``::
+
FLAGS['longname'] = x # register a new flag
- The .value attribute of the registered 'Flag' objects can be accessed
- as attributes of this 'FlagValues' object, through __getattr__. Both
- the long and short name of the original 'Flag' objects can be used to
- access its value:
- FLAGS.longname # parsed flag value
- FLAGS.x # parsed flag value (short name)
+ The ``.value`` attribute of the registered :class:`~absl.flags.Flag` objects
+ can be accessed as attributes of this :class:`FlagValues` object, through
+ ``__getattr__``. Both the long and short name of the original
+ :class:`~absl.flags.Flag` objects can be used to access its value::
+
+ FLAGS.longname # parsed flag value
+ FLAGS.x # parsed flag value (short name)
+
+ Command line arguments are scanned and passed to the registered
+ :class:`~absl.flags.Flag` objects through the ``__call__`` method. Unparsed
+ arguments, including ``argv[0]`` (e.g. the program name) are returned::
- Command line arguments are scanned and passed to the registered 'Flag'
- objects through the __call__ method. Unparsed arguments, including
- argv[0] (e.g. the program name) are returned.
argv = FLAGS(sys.argv) # scan command line arguments
- The original registered Flag objects can be retrieved through the use
- of the dictionary-like operator, __getitem__:
+ The original registered :class:`~absl.flags.Flag` objects can be retrieved
+ through the use of the dictionary-like operator, ``__getitem__``::
+
x = FLAGS['longname'] # access the registered Flag object
- The str() operator of a 'FlagValues' object provides help for all of
- the registered 'Flag' objects.
+ The ``str()`` operator of a :class:`absl.flags.FlagValues` object provides
+ help for all of the registered :class:`~absl.flags.Flag` objects.
"""
# A note on collections.abc.Mapping:
@@ -821,7 +826,7 @@ class FlagValues:
"""Explicitly marks flags as parsed.
Use this when the caller knows that this FlagValues has been parsed as if
- a __call__() invocation has happened. This is only a public method for
+ a ``__call__()`` invocation has happened. This is only a public method for
use by things like appcommands which do additional command like parsing.
"""
self.__dict__['__flags_parsed'] = True
@@ -1133,14 +1138,15 @@ class FlagValues:
using absl.flags DEFINE_flag() type functions.
Notes (assuming we're getting a commandline of some sort as our input):
- --> For duplicate flags, the last one we hit should "win".
- --> Since flags that appear later win, a flagfile's settings can be "weak"
+
+ * For duplicate flags, the last one we hit should "win".
+ * Since flags that appear later win, a flagfile's settings can be "weak"
if the --flagfile comes at the beginning of the argument sequence,
and it can be "strong" if the --flagfile comes at the end.
- --> A further "--flagfile=<otherfile.cfg>" CAN be nested in a flagfile.
+ * A further "--flagfile=<otherfile.cfg>" CAN be nested in a flagfile.
It will be expanded in exactly the spot where it is found.
- --> In a flagfile, a line beginning with # or // is a comment.
- --> Entirely blank lines _should_ be ignored.
+ * In a flagfile, a line beginning with # or // is a comment.
+ * Entirely blank lines _should_ be ignored.
"""
rest_of_args = argv
new_argv = []
@@ -1296,29 +1302,25 @@ FLAGS = FlagValues()
class FlagHolder(Generic[_T]):
"""Holds a defined flag.
- This facilitates a cleaner api around global state. Instead of
-
- ```
- flags.DEFINE_integer('foo', ...)
- flags.DEFINE_integer('bar', ...)
- ...
- def method():
- # prints parsed value of 'bar' flag
- print(flags.FLAGS.foo)
- # runtime error due to typo or possibly bad coding style.
- print(flags.FLAGS.baz)
- ```
-
- it encourages code like
-
- ```
- FOO_FLAG = flags.DEFINE_integer('foo', ...)
- BAR_FLAG = flags.DEFINE_integer('bar', ...)
- ...
- def method():
- print(FOO_FLAG.value)
- print(BAR_FLAG.value)
- ```
+ This facilitates a cleaner api around global state. Instead of::
+
+ flags.DEFINE_integer('foo', ...)
+ flags.DEFINE_integer('bar', ...)
+
+ def method():
+ # prints parsed value of 'bar' flag
+ print(flags.FLAGS.foo)
+ # runtime error due to typo or possibly bad coding style.
+ print(flags.FLAGS.baz)
+
+ it encourages code like::
+
+ _FOO_FLAG = flags.DEFINE_integer('foo', ...)
+ _BAR_FLAG = flags.DEFINE_integer('bar', ...)
+
+ def method():
+ print(_FOO_FLAG.value)
+ print(_BAR_FLAG.value)
since the name of the flag appears only once in the source code.
"""
@@ -1364,7 +1366,8 @@ class FlagHolder(Generic[_T]):
def value(self):
"""Returns the value of the flag.
- If _ensure_non_none_value is True, then return value is not None.
+ If ``_ensure_non_none_value`` is ``True``, then return value is not
+ ``None``.
Raises:
UnparsedFlagAccessError: if flag parsing has not finished.
diff --git a/absl/flags/_helpers.py b/absl/flags/_helpers.py
index 96f0a85..cb0cfb2 100644
--- a/absl/flags/_helpers.py
+++ b/absl/flags/_helpers.py
@@ -317,14 +317,18 @@ def flag_dict_to_args(flag_map, multi_flags=None):
Args:
flag_map: dict, a mapping where the keys are flag names (strings).
values are treated according to their type:
- * If value is None, then only the name is emitted.
- * If value is True, then only the name is emitted.
- * If value is False, then only the name prepended with 'no' is emitted.
- * If value is a string then --name=value is emitted.
- * If value is a collection, this will emit --name=value1,value2,value3,
- unless the flag name is in multi_flags, in which case this will emit
- --name=value1 --name=value2 --name=value3.
+
+ * If value is ``None``, then only the name is emitted.
+ * If value is ``True``, then only the name is emitted.
+ * If value is ``False``, then only the name prepended with 'no' is
+ emitted.
+ * If value is a string then ``--name=value`` is emitted.
+ * If value is a collection, this will emit
+ ``--name=value1,value2,value3``, unless the flag name is in
+ ``multi_flags``, in which case this will emit
+ ``--name=value1 --name=value2 --name=value3``.
* Everything else is converted to string an passed as such.
+
multi_flags: set, names (strings) of flags that should be treated as
multi-flags.
Yields:
diff --git a/absl/flags/_validators.py b/absl/flags/_validators.py
index 26639c5..c4e1139 100644
--- a/absl/flags/_validators.py
+++ b/absl/flags/_validators.py
@@ -14,13 +14,15 @@
"""Module to enforce different constraints on flags.
-Flags validators can be registered using following functions / decorators:
+Flags validators can be registered using following functions / decorators::
+
flags.register_validator
@flags.validator
flags.register_multi_flags_validator
@flags.multi_flags_validator
-Three convenience functions are also provided for common flag constraints:
+Three convenience functions are also provided for common flag constraints::
+
flags.mark_flag_as_required
flags.mark_flags_as_required
flags.mark_flags_as_mutual_exclusive
@@ -47,20 +49,24 @@ def register_validator(flag_name,
The constraint is validated when flags are initially parsed, and after each
change of the corresponding flag's value.
+
Args:
flag_name: str, name of the flag to be checked.
checker: callable, a function to validate the flag.
- input - A single positional argument: The value of the corresponding
- flag (string, boolean, etc. This value will be passed to checker
- by the library).
- output - bool, True if validator constraint is satisfied.
- If constraint is not satisfied, it should either return False or
- raise flags.ValidationError(desired_error_message).
+
+ * input - A single positional argument: The value of the corresponding
+ flag (string, boolean, etc. This value will be passed to checker
+ by the library).
+ * output - bool, True if validator constraint is satisfied.
+ If constraint is not satisfied, it should either ``return False`` or
+ ``raise flags.ValidationError(desired_error_message)``.
+
message: str, error text to be shown to the user if checker returns False.
If checker raises flags.ValidationError, message from the raised
error will be shown.
flag_values: flags.FlagValues, optional FlagValues instance to validate
against.
+
Raises:
AttributeError: Raised when flag_name is not registered as a valid flag
name.
@@ -73,13 +79,13 @@ def validator(flag_name, message='Flag validation failed',
flag_values=_flagvalues.FLAGS):
"""A function decorator for defining a flag validator.
- Registers the decorated function as a validator for flag_name, e.g.
+ Registers the decorated function as a validator for flag_name, e.g.::
- @flags.validator('foo')
- def _CheckFoo(foo):
- ...
+ @flags.validator('foo')
+ def _CheckFoo(foo):
+ ...
- See register_validator() for the specification of checker function.
+ See :func:`register_validator` for the specification of checker function.
Args:
flag_name: str, name of the flag to be checked.
@@ -115,11 +121,13 @@ def register_multi_flags_validator(flag_names,
Args:
flag_names: [str], a list of the flag names to be checked.
multi_flags_checker: callable, a function to validate the flag.
- input - dict, with keys() being flag_names, and value for each key
+
+ * input - dict, with keys() being flag_names, and value for each key
being the value of the corresponding flag (string, boolean, etc).
- output - bool, True if validator constraint is satisfied.
+ * output - bool, True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise flags.ValidationError.
+
message: str, error text to be shown to the user if checker returns False.
If checker raises flags.ValidationError, message from the raised
error will be shown.
@@ -139,13 +147,13 @@ def multi_flags_validator(flag_names,
flag_values=_flagvalues.FLAGS):
"""A function decorator for defining a multi-flag validator.
- Registers the decorated function as a validator for flag_names, e.g.
+ Registers the decorated function as a validator for flag_names, e.g.::
- @flags.multi_flags_validator(['foo', 'bar'])
- def _CheckFooBar(flags_dict):
- ...
+ @flags.multi_flags_validator(['foo', 'bar'])
+ def _CheckFooBar(flags_dict):
+ ...
- See register_multi_flags_validator() for the specification of checker
+ See :func:`register_multi_flags_validator` for the specification of checker
function.
Args:
@@ -177,20 +185,20 @@ def mark_flag_as_required(flag_name, flag_values=_flagvalues.FLAGS):
"""Ensures that flag is not None during program execution.
Registers a flag validator, which will follow usual validator rules.
- Important note: validator will pass for any non-None value, such as False,
- 0 (zero), '' (empty string) and so on.
+ Important note: validator will pass for any non-``None`` value, such as
+ ``False``, ``0`` (zero), ``''`` (empty string) and so on.
If your module might be imported by others, and you only wish to make the flag
- required when the module is directly executed, call this method like this:
+ required when the module is directly executed, call this method like this::
- if __name__ == '__main__':
- flags.mark_flag_as_required('your_flag_name')
- app.run()
+ if __name__ == '__main__':
+ flags.mark_flag_as_required('your_flag_name')
+ app.run()
Args:
flag_name: str, name of the flag
- flag_values: flags.FlagValues, optional FlagValues instance where the flag
- is defined.
+ flag_values: flags.FlagValues, optional :class:`~absl.flags.FlagValues`
+ instance where the flag is defined.
Raises:
AttributeError: Raised when flag_name is not registered as a valid flag
name.
@@ -212,11 +220,11 @@ def mark_flags_as_required(flag_names, flag_values=_flagvalues.FLAGS):
"""Ensures that flags are not None during program execution.
If your module might be imported by others, and you only wish to make the flag
- required when the module is directly executed, call this method like this:
+ required when the module is directly executed, call this method like this::
- if __name__ == '__main__':
- flags.mark_flags_as_required(['flag1', 'flag2', 'flag3'])
- app.run()
+ if __name__ == '__main__':
+ flags.mark_flags_as_required(['flag1', 'flag2', 'flag3'])
+ app.run()
Args:
flag_names: Sequence[str], names of the flags.
@@ -233,11 +241,11 @@ def mark_flags_as_mutual_exclusive(flag_names, required=False,
flag_values=_flagvalues.FLAGS):
"""Ensures that only one flag among flag_names is not None.
- Important note: This validator checks if flag values are None, and it does not
- distinguish between default and explicit values. Therefore, this validator
+ Important note: This validator checks if flag values are ``None``, and it does
+ not distinguish between default and explicit values. Therefore, this validator
does not make sense when applied to flags with default values other than None,
- including other false values (e.g. False, 0, '', []). That includes multi
- flags with a default value of [] instead of None.
+ including other false values (e.g. ``False``, ``0``, ``''``, ``[]``). That
+ includes multi flags with a default value of ``[]`` instead of None.
Args:
flag_names: [str], names of the flags.