absl.flags package
Submodules
Module contents
This package is used to define and parse command line flags.
This package defines a distributed flag-definition policy: rather than an application having to define all flags in or near main(), each Python module defines flags that are useful to it. When one Python module imports another, it gains access to the other’s flags. (This is implemented by having all modules share a common, global registry object containing all the flag information.)
Flags are defined through the use of one of the DEFINE_xxx functions. The specific function used determines how the flag is parsed, checked, and optionally type-converted, when it’s seen on the command line.
- class absl.flags.ArgumentParser(*args, **kwargs)[source]
Bases:
Generic[_T]Base class used to parse and convert arguments.
The
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 aValueErrorexception with a human readable explanation of why the value is illegal.Subclasses should also define a syntactic_help string which may be presented to the user to describe the form of the legal values.
Argument parser classes must be stateless, since instances are cached and shared between flags. Initializer arguments are allowed, but all member variables must be derived from initializer arguments only.
- parse(argument: str) _T | None[source]
Parses the string argument and returns the native value.
By default it returns its argument unmodified.
- Parameters:
argument – string argument passed in the commandline.
- Raises:
ValueError – Raised when it fails to parse the argument.
TypeError – Raised when the argument has the wrong type.
- Returns:
The parsed value in native type.
- class absl.flags.ArgumentSerializer(*args, **kwds)[source]
Bases:
Generic[_T]Base class for generating string representations of a flag value.
- class absl.flags.BaseListParser(*args, **kwargs)[source]
Bases:
ArgumentParserBase class for a parser of lists of strings.
To extend, inherit from this class; from the subclass
__init__, call:super().__init__(token, name)
where token is a character used to tokenize, and name is a description of the separator.
- class absl.flags.BooleanFlag(name: str, default: bool | None | str, help: str | None, short_name: str | None = None, **args)[source]
-
Basic boolean flag.
Boolean flags do not take any arguments, and their value is either
True(1) orFalse(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--noupdateor--nox.
- class absl.flags.BooleanParser(*args, **kwargs)[source]
Bases:
ArgumentParser[bool]Parser of boolean values.
- exception absl.flags.CantOpenFlagFileError[source]
Bases:
ErrorRaised when flagfile fails to open.
E.g. the file doesn’t exist, or has wrong permissions.
- class absl.flags.CsvListSerializer(list_sep: str)[source]
Bases:
ListSerializer[str]
- absl.flags.DEFINE(parser, name, default, help, flag_values=<absl.flags._flagvalues.FlagValues object>, serializer=None, module_name=None, required=False, **args)[source]
Registers a generic Flag object.
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>function instead.- Parameters:
parser –
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.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__.
- Returns:
a handle to defined flag.
- absl.flags.DEFINE_alias(name: str, original_name: str, flag_values: ~absl.flags._flagvalues.FlagValues = <absl.flags._flagvalues.FlagValues object>, module_name: str | None = None) FlagHolder[Any][source]
Defines an alias flag for an existing one.
- Parameters:
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.module_name – A string, the name of the module that defines this flag.
- Returns:
a handle to defined flag.
- Raises:
flags.FlagError – UnrecognizedFlagError: if the referenced flag doesn’t exist. DuplicateFlagError: if the alias name has been used by some existing flag.
- absl.flags.DEFINE_bool(name, default, help, flag_values=<absl.flags._flagvalues.FlagValues object>, module_name=None, required=False, **args)
Registers a boolean flag.
Such a boolean flag does not take an argument. If a user wants to specify a false value explicitly, the long option beginning with ‘no’ must be used: i.e. –noflag
This flag will have a value of None, True or False. None is possible if default=None and the user does not specify the flag on the command line.
- Parameters:
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.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__.
- Returns:
a handle to defined flag.
- absl.flags.DEFINE_boolean(name, default, help, flag_values=<absl.flags._flagvalues.FlagValues object>, module_name=None, required=False, **args)[source]
Registers a boolean flag.
Such a boolean flag does not take an argument. If a user wants to specify a false value explicitly, the long option beginning with ‘no’ must be used: i.e. –noflag
This flag will have a value of None, True or False. None is possible if default=None and the user does not specify the flag on the command line.
- Parameters:
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.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__.
- Returns:
a handle to defined flag.
- absl.flags.DEFINE_enum(name, default, enum_values, help, flag_values=<absl.flags._flagvalues.FlagValues object>, module_name=None, required=False, **args)[source]
Registers a flag whose value can be any string from enum_values.
Instead of a string enum, prefer DEFINE_enum_class, which allows defining enums from an enum.Enum class.
- Parameters:
name – str, the flag name.
default – str|None, the default value of the flag.
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.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__.
- Returns:
a handle to defined flag.
- absl.flags.DEFINE_enum_class(name, default, enum_class, help, flag_values=<absl.flags._flagvalues.FlagValues object>, module_name=None, case_sensitive=False, required=False, **args)[source]
Registers a flag whose value can be the name of enum members.
- Parameters:
name – str, the flag name.
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.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__.
- Returns:
a handle to defined flag.
- absl.flags.DEFINE_flag(flag, flag_values=<absl.flags._flagvalues.FlagValues object>, module_name=None, required=False)[source]
Registers a
Flagobject with aFlagValuesobject.By default, the global
FLAGSFlagValueobject is used.Typical users will use one of the more specialized DEFINE_xxx functions, such as
DEFINE_string()orDEFINE_integer(). But developers who need to createFlagobjects themselves should use this function to register their flags.- Parameters:
flag –
Flag, a flag that is key to the module.flag_values –
FlagValues, theFlagValuesinstance 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.
- Returns:
a handle to defined flag.
- absl.flags.DEFINE_float(name, default, help, lower_bound=None, upper_bound=None, flag_values=<absl.flags._flagvalues.FlagValues object>, required=False, **args)[source]
Registers a flag whose value must be a float.
If
lower_boundorupper_boundare set, then this flag must be within the given range.- Parameters:
name – str, the flag name.
default – float|str|None, the default value of the flag.
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.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().
- Returns:
a handle to defined flag.
- absl.flags.DEFINE_integer(name, default, help, lower_bound=None, upper_bound=None, flag_values=<absl.flags._flagvalues.FlagValues object>, required=False, **args)[source]
Registers a flag whose value must be an integer.
If
lower_bound, orupper_boundare set, then this flag must be within the given range.- Parameters:
name – str, the flag name.
default – int|str|None, the default value of the flag.
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.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().
- Returns:
a handle to defined flag.
- absl.flags.DEFINE_list(name, default, help, flag_values=<absl.flags._flagvalues.FlagValues object>, required=False, **args)[source]
Registers a flag whose value is a comma-separated list of strings.
The flag value is parsed with a CSV parser.
- Parameters:
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.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__.
- Returns:
a handle to defined flag.
- absl.flags.DEFINE_multi(parser, serializer, name, default, help, flag_values=<absl.flags._flagvalues.FlagValues object>, module_name=None, required=False, **args)[source]
Registers a generic MultiFlag that parses its args with a given parser.
Auxiliary function. Normal users should NOT use it directly.
Developers who need to create their own ‘Parser’ classes for options which can appear multiple times can call this module function to register their flags.
- Parameters:
parser – ArgumentParser, used to parse the flag arguments.
serializer – ArgumentSerializer, the flag serializer instance.
name – str, the flag name.
default – Union[Iterable[T], Text, None], the default value of the flag. If the value is text, it will be parsed as if it was provided from the command line. If the value is a non-string iterable, it will be iterated 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.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__.
- Returns:
a handle to defined flag.
- absl.flags.DEFINE_multi_enum(name, default, enum_values, help, flag_values=<absl.flags._flagvalues.FlagValues object>, case_sensitive=True, required=False, **args)[source]
Registers a flag whose value can be a list strings from enum_values.
Use the flag on the command line multiple times to place multiple enum values into the list. The ‘default’ may be a single string (which will be converted into a single-element list) or a list of strings.
- Parameters:
name – str, the flag name.
default – Union[Iterable[Text], Text, None], the default value of the flag; see DEFINE_multi.
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.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__.
- Returns:
a handle to defined flag.
- absl.flags.DEFINE_multi_enum_class(name, default, enum_class, help, flag_values=<absl.flags._flagvalues.FlagValues object>, module_name=None, case_sensitive=False, required=False, **args)[source]
Registers a flag whose value can be a list of enum members.
Use the flag on the command line multiple times to place multiple enum values into the list.
- Parameters:
name – str, the flag name.
default – Union[Iterable[Enum], Iterable[Text], Enum, Text, None], the default value of the flag; see DEFINE_multi; only differences are documented here. If the value is a single Enum, it is treated as a single-item list of that Enum value. If it is an iterable, text values 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.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__.
- Returns:
a handle to defined flag.
- absl.flags.DEFINE_multi_float(name, default, help, lower_bound=None, upper_bound=None, flag_values=<absl.flags._flagvalues.FlagValues object>, required=False, **args)[source]
Registers a flag whose value can be a list of arbitrary floats.
Use the flag on the command line multiple times to place multiple float values into the list. The ‘default’ may be a single float (which will be converted into a single-element list) or a list of floats.
- Parameters:
name – str, the flag name.
default – Union[Iterable[float], Text, None], the default value of the flag; see DEFINE_multi.
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.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__.
- Returns:
a handle to defined flag.
- absl.flags.DEFINE_multi_integer(name, default, help, lower_bound=None, upper_bound=None, flag_values=<absl.flags._flagvalues.FlagValues object>, required=False, **args)[source]
Registers a flag whose value can be a list of arbitrary integers.
Use the flag on the command line multiple times to place multiple integer values into the list. The ‘default’ may be a single integer (which will be converted into a single-element list) or a list of integers.
- Parameters:
name – str, the flag name.
default – Union[Iterable[int], Text, None], the default value of the flag; see DEFINE_multi.
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.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__.
- Returns:
a handle to defined flag.
- absl.flags.DEFINE_multi_string(name, default, help, flag_values=<absl.flags._flagvalues.FlagValues object>, required=False, **args)[source]
Registers a flag whose value can be a list of any strings.
Use the flag on the command line multiple times to place multiple string values into the list. The ‘default’ may be a single string (which will be converted into a single-element list) or a list of strings.
- Parameters:
name – str, the flag name.
default – Union[Iterable[Text], Text, None], the default value of the flag; see
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.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__.
- Returns:
a handle to defined flag.
- absl.flags.DEFINE_spaceseplist(name, default, help, comma_compat=False, flag_values=<absl.flags._flagvalues.FlagValues object>, required=False, **args)[source]
Registers a flag whose value is a whitespace-separated list of strings.
Any whitespace can be used as a separator.
- Parameters:
name – str, the flag name.
default – list|str|None, the default value of the flag.
help – str, the help message.
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.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__.
- Returns:
a handle to defined flag.
- absl.flags.DEFINE_string(name, default, help, flag_values=<absl.flags._flagvalues.FlagValues object>, required=False, **args)[source]
Registers a flag whose value can be any string.
- exception absl.flags.DuplicateFlagError[source]
Bases:
ErrorRaised if there is a flag naming conflict.
- classmethod from_flag(flagname, flag_values, other_flag_values=None)[source]
Creates a DuplicateFlagError by providing flag name and values.
- Parameters:
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.
- Returns:
An instance of DuplicateFlagError.
- class absl.flags.EnumClassFlag(name: str, default: _ET | None | str, help: str | None, enum_class: Type[_ET], short_name: str | None = None, case_sensitive: bool = False, **args)[source]
Bases:
Flag[_ET]Basic enum flag; its value is an enum class’s member.
- class absl.flags.EnumClassListSerializer(list_sep: str, **kwargs)[source]
Bases:
ListSerializer[_ET]A serializer for
MultiEnumClassflags.This serializer simply joins the output of EnumClassSerializer using a provided separator.
- class absl.flags.EnumClassParser(*args, **kwargs)[source]
Bases:
ArgumentParser[_ET]Parser of an Enum class member.
- parse(argument: _ET | str) _ET[source]
Determines validity of argument and returns the correct element of enum.
- Parameters:
argument – str or Enum class member, the supplied flag value.
- Returns:
The first matching Enum class member in Enum class.
- Raises:
ValueError – Raised when argument didn’t match anything in enum.
- class absl.flags.EnumClassSerializer(lowercase: bool)[source]
Bases:
ArgumentSerializerClass for generating string representations of an enum class flag value.
- class absl.flags.EnumFlag(name: str, default: str | None, help: str | None, enum_values: Iterable[str], short_name: str | None = None, case_sensitive: bool = True, **args)[source]
-
Basic enum flag; its value can be any string from list of enum_values.
- class absl.flags.EnumParser(*args, **kwargs)[source]
Bases:
ArgumentParser[str]Parser of a string enum value (a string value from a given set).
- parse(argument: str) str[source]
Determines validity of argument and returns the correct element of enum.
- Parameters:
argument – str, the supplied flag value.
- Returns:
The first matching element from enum_values.
- Raises:
ValueError – Raised when argument didn’t match anything in enum.
- absl.flags.FLAGS = <absl.flags._flagvalues.FlagValues object>
The global FlagValues instance.
- class absl.flags.Flag(parser: ArgumentParser[_T], serializer: ArgumentSerializer[_T] | None, name: str, default: _T | None | str, help_string: str | None, short_name: str | None = None, boolean: bool = False, allow_override: bool = False, allow_override_cpp: bool = False, allow_hide_cpp: bool = False, allow_overwrite: bool = True, allow_using_method_names: bool = False)[source]
Bases:
Generic[_T]Information about a command-line flag.
- name
the name for this flag
- default
the default value for this flag
- Type:
absl.flags._flag._T | None
- 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
ArgumentParserobject
- 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
Flagobject isparse(), but it is typically only called by aFlagValuesobject. Theparse()method is a thin wrapper around theArgumentParser.parse()method. The parsed value is saved in.value, and the.presentattribute 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.valueattribute. This enables other python modules to safely use flags even if the__main__module neglects to parse the command line arguments. The.presentattribute is cleared after__init__parsing. If the default value is set toNone, then the__init__parsing step is skipped and the.valueattribute is initialized to None.Note: The default value is also presented to the user in the help string, so it is important that it be a legal value for this flag.
- flag_type() str[source]
Returns a str that describes the type of the flag.
NOTE: we use strings, and not the types.*Type constants because our flags can have more exotic types, e.g., ‘comma separated list of strings’, ‘whitespace separated list of strings’, etc.
- class absl.flags.FlagHolder(flag_values: FlagValues, flag: Flag[_T], ensure_non_none_value: bool = False)[source]
Bases:
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)
since the name of the flag appears only once in the source code.
- property default: _T
Returns the default value of the flag.
- property value: _T
Returns the value of the flag.
If
_ensure_non_none_valueisTrue, then return value is notNone.- Raises:
UnparsedFlagAccessError – if flag parsing has not finished.
IllegalFlagValueError – if value is None unexpectedly.
- exception absl.flags.FlagNameConflictsWithMethodError[source]
Bases:
ErrorRaised when a flag name conflicts with
FlagValuesmethods.
- class absl.flags.FlagValues[source]
Bases:
objectRegistry of
Flagobjects.A
FlagValuescan 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 oneFlagValuesobject is needed by an application:FLAGS.This class is heavily overloaded:
Flagobjects are registered via__setitem__:FLAGS['longname'] = x # register a new flag
The
.valueattribute of the registeredFlagobjects can be accessed as attributes of thisFlagValuesobject, through__getattr__. Both the long and short name of the originalFlagobjects 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
Flagobjects through the__call__method. Unparsed arguments, includingargv[0](e.g. the program name) are returned:argv = FLAGS(sys.argv) # scan command line arguments
The original registered
Flagobjects can be retrieved through the use of the dictionary-like operator,__getitem__:x = FLAGS['longname'] # access the registered Flag object
The
str()operator of aabsl.flags.FlagValuesobject provides help for all of the registeredFlagobjects.- append_flag_values(flag_values: FlagValues) None[source]
Appends flags registered in another FlagValues instance.
- Parameters:
flag_values – FlagValues, the FlagValues instance from which to copy flags.
- append_flags_into_file(filename: str) None[source]
Appends all flags assignments from this FlagInfo object to a file.
Output will be in the format of a flagfile.
NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile from https://github.com/gflags/gflags.
- Parameters:
filename – str, name of the file.
- find_module_defining_flag(flagname: str, default: _T | None = None) str | _T | None[source]
Return the name of the module defining this flag, or default.
- Parameters:
flagname – str, name of the flag to lookup.
default – Value to return if flagname is not defined. Defaults to None.
- Returns:
The name of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default.
- find_module_id_defining_flag(flagname: str, default: _T | None = None) int | _T | None[source]
Return the ID of the module defining this flag, or default.
- Parameters:
flagname – str, name of the flag to lookup.
default – Value to return if flagname is not defined. Defaults to None.
- Returns:
The ID of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default.
- flag_values_dict() Dict[str, Any][source]
Returns a dictionary that maps flag names to flag values.
- flags_by_module_dict() Dict[str, List[Flag]][source]
Returns the dictionary of module_name -> list of defined flags.
- Returns:
A dictionary. Its keys are module names (strings). Its values are lists of Flag objects.
- flags_by_module_id_dict() Dict[int, List[Flag]][source]
Returns the dictionary of module_id -> list of defined flags.
- Returns:
A dictionary. Its keys are module IDs (ints). Its values are lists of Flag objects.
- flags_into_string() str[source]
Returns a string with the flags assignments from this FlagValues object.
This function ignores flags whose value is None. Each flag assignment is separated by a newline.
NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString from https://github.com/gflags/gflags.
- Returns:
str, the string with the flags assignments from this FlagValues object. The flags are ordered by (module_name, flag_name).
- get_flag_value(name: str, default: Any) Any[source]
Returns the value of a flag (if not None) or a default value.
- Parameters:
name – str, the name of a flag.
default – Default value to use if the flag value is None.
- Returns:
Requested flag value or default.
- get_flags_for_module(module: str | Any) List[Flag][source]
Returns the list of flags defined by a module.
- Parameters:
module – module|str, the module to get flags from.
- Returns:
[Flag], a new list of Flag instances. Caller may update this list as desired: none of those changes will affect the internals of this FlagValue instance.
- get_help(prefix: str = '', include_special_flags: bool = True) str[source]
Returns a help string for all known flags.
- Parameters:
prefix – str, per-line output prefix.
include_special_flags – bool, whether to include description of SPECIAL_FLAGS, i.e. –flagfile and –undefok.
- Returns:
str, formatted help message.
- get_key_flags_for_module(module: str | Any) List[Flag][source]
Returns the list of key flags for a module.
- Parameters:
module – module|str, the module to get key flags from.
- Returns:
[Flag], a new list of Flag instances. Caller may update this list as desired: none of those changes will affect the internals of this FlagValue instance.
- key_flags_by_module_dict() Dict[str, List[Flag]][source]
Returns the dictionary of module_name -> list of key flags.
- Returns:
A dictionary. Its keys are module names (strings). Its values are lists of Flag objects.
- main_module_help() str[source]
Describes the key flags of the main module.
- Returns:
str, describing the key flags of the main module.
- mark_as_parsed() None[source]
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 use by things like appcommands which do additional command like parsing.
- module_help(module: Any) str[source]
Describes the key flags of a module.
- Parameters:
module – module|str, the module to describe the key flags for.
- Returns:
str, describing the key flags of a module.
- read_flags_from_files(argv: Sequence[str], force_gnu: bool = True) List[str][source]
Processes command line args, but also allow args to be read from file.
- Parameters:
argv – [str], a list of strings, usually sys.argv[1:], which may contain one or more flagfile directives of the form –flagfile=”./filename”. Note that the name of the program (sys.argv[0]) should be omitted.
force_gnu – bool, if False, –flagfile parsing obeys the FLAGS.is_gnu_getopt() value. If True, ignore the value and always follow gnu_getopt semantics.
- Returns:
A new list which has the original list combined with what we read from any flagfile(s).
- Raises:
IllegalFlagValueError – Raised when –flagfile is provided with no argument.
This function is called by FLAGS(argv). It scans the input list for a flag that looks like: –flagfile=<somefile>. Then it opens <somefile>, reads all valid key and value pairs and inserts them into the input list in exactly the place where the –flagfile arg is found.
Note that your application’s flags are still defined the usual way 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”
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.
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.
- register_flag_by_module(module_name: str, flag: Flag) None[source]
Records the module that defines a specific flag.
We keep track of which flag is defined by which module so that we can later sort the flags by module.
- Parameters:
module_name – str, the name of a Python module.
flag – Flag, the Flag instance that is key to the module.
- register_flag_by_module_id(module_id: int, flag: Flag) None[source]
Records the module that defines a specific flag.
- Parameters:
module_id – int, the ID of the Python module.
flag – Flag, the Flag instance that is key to the module.
- register_key_flag_for_module(module_name: str, flag: Flag) None[source]
Specifies that a flag is a key flag for a module.
- Parameters:
module_name – str, the name of a Python module.
flag – Flag, the Flag instance that is key to the module.
- remove_flag_values(flag_values: FlagValues | Iterable[str]) None[source]
Remove flags that were previously appended from another FlagValues.
- Parameters:
flag_values – FlagValues, the FlagValues instance containing flags to remove.
- set_default(name: str, value: Any) None[source]
Changes the default value of the named flag object.
The flag’s current value is also updated if the flag is currently using the default value, i.e. not specified in the command line, and not set by FLAGS.name = value.
- Parameters:
name – str, the name of the flag to modify.
value – The new default value.
- Raises:
UnrecognizedFlagError – Raised when there is no registered flag named name.
IllegalFlagValueError – Raised when value is not valid.
- set_gnu_getopt(gnu_getopt: bool = True) None[source]
Sets whether or not to use GNU style scanning.
GNU style allows mixing of flag and non-flag arguments. See http://docs.python.org/library/getopt.html#getopt.gnu_getopt
- Parameters:
gnu_getopt – bool, whether or not to use GNU style scanning.
- validate_all_flags() None[source]
Verifies whether all flags pass validation.
- Raises:
AttributeError – Raised if validators work with a non-existing flag.
IllegalFlagValueError – Raised if validation fails for at least one validator.
- write_help_in_xml_format(outfile: TextIO | None = None) None[source]
Outputs flag documentation in XML format.
NOTE: We use element names that are consistent with those used by the C++ command-line flag library, from https://github.com/gflags/gflags. We also use a few new elements (e.g., <key>), but we do not interfere / overlap with existing XML elements used by the C++ library. Please maintain this consistency.
- Parameters:
outfile – File object we write to. Default None means sys.stdout.
- class absl.flags.FloatParser(*args, **kwargs)[source]
Bases:
NumericParser[float]Parser of floating point values.
Parsed value may be bounded to a given upper and lower bound.
- number_article = 'a'
- number_name = 'number'
- exception absl.flags.IllegalFlagValueError[source]
Bases:
ErrorRaised when the flag command line argument is illegal.
- class absl.flags.IntegerParser(*args, **kwargs)[source]
Bases:
NumericParser[int]Parser of an integer value.
Parsed value may be bounded to a given upper and lower bound.
- number_article = 'an'
- number_name = 'integer'
- class absl.flags.ListParser(*args, **kwargs)[source]
Bases:
BaseListParserParser for a comma-separated list of strings.
- class absl.flags.ListSerializer(list_sep: str)[source]
Bases:
Generic[_T],ArgumentSerializer[List[_T]]
- class absl.flags.MultiEnumClassFlag(name: str, default: None | Iterable[_ET] | _ET | Iterable[str] | str, help_string: str, enum_class: Type[_ET], case_sensitive: bool = False, **args)[source]
Bases:
MultiFlag[_ET]A multi_enum_class flag.
See the __doc__ for MultiFlag for most behaviors of this class. In addition, this class knows how to handle enum.Enum instances as values for this flag type.
- class absl.flags.MultiFlag(*args, **kwargs)[source]
Bases:
Generic[_T],Flag[List[_T]]A flag that can appear multiple time on the command-line.
The value of such a flag is a list that contains the individual values from all the appearances of that flag on the command-line.
See the __doc__ for Flag for most behavior of this class. Only differences in behavior are described here:
The default value may be either a single value or an iterable of values. A single value is transformed into a single-item list of that value.
The value of the flag is always a list, even if the option was only supplied once, and even if the default value is a single value
- exception absl.flags.UnparsedFlagAccessError[source]
Bases:
ErrorRaised when accessing the flag value from unparsed
FlagValues.
- exception absl.flags.UnrecognizedFlagError(flagname, flagvalue='', suggestions=None)[source]
Bases:
ErrorRaised when a flag is unrecognized.
- flagname
str, the name of the unrecognized flag.
- flagvalue
The value of the flag, empty if the flag is not defined.
- exception absl.flags.ValidationError[source]
Bases:
ErrorRaised when flag validator constraint is not satisfied.
- class absl.flags.WhitespaceSeparatedListParser(*args, **kwargs)[source]
Bases:
BaseListParserParser for a whitespace-separated list of strings.
- absl.flags.adopt_module_key_flags(module: ~typing.Any, flag_values: ~absl.flags._flagvalues.FlagValues = <absl.flags._flagvalues.FlagValues object>) None[source]
Declares that all flags key to a module are key to the current module.
- Parameters:
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.
- Raises:
Error – Raised when given an argument that is a module name (a string), instead of a module object.
- absl.flags.declare_key_flag(flag_name: str | ~absl.flags._flagvalues.FlagHolder, flag_values: ~absl.flags._flagvalues.FlagValues = <absl.flags._flagvalues.FlagValues object>) None[source]
Declares one flag as key to the current module.
Key flags are flags that are deemed really important for a module. They are important when listing help messages; e.g., if the –helpshort command-line flag is used, then only the key flags of the main module are listed (instead of all flags, as in the case of –helpfull).
Sample usage:
flags.declare_key_flag('flag_1')
- Parameters:
flag_name – str |
FlagHolder, the name or holder of an already declared flag. (Redeclaring flags as key, including flags implicitly key because they were declared in this module, is a no-op.) Positional-only parameter.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.
- Raises:
ValueError – Raised if flag_name not defined as a Python flag.
- absl.flags.disclaim_key_flags() None[source]
Declares that the current module will not define any more key flags.
Normally, the module that calls the DEFINE_xxx functions claims the flag to be its key flag. This is undesirable for modules that define additional DEFINE_yyy functions with its own flag parsers and serializers, since that module will accidentally claim flags defined by DEFINE_yyy as its key flags. After calling this function, the module disclaims flag definitions thereafter, so the key flags will be correctly attributed to the caller of DEFINE_yyy.
After calling this function, the module will not be able to define any more flags. This function will affect all FlagValues objects.
- absl.flags.flag_dict_to_args(flag_map: Dict[str, Any], multi_flags: Set[str] | None = None) Iterable[str][source]
Convert a dict of values into process call parameters.
This method is used to convert a dictionary into a sequence of parameters for a binary that parses arguments using this module.
- Parameters:
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=valueis emitted.If value is a collection, this will emit
--name=value1,value2,value3, unless the flag name is inmulti_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:
sequence of string suitable for a subprocess execution.
- absl.flags.get_help_width() int[source]
Returns the integer width of help lines that is used in TextWrap.
- absl.flags.mark_bool_flags_as_mutual_exclusive(flag_names, required=False, flag_values=<absl.flags._flagvalues.FlagValues object>)[source]
Ensures that only one flag among flag_names is True.
- Parameters:
flag_names – [str | FlagHolder], names or holders of flags. Positional-only parameter.
required – bool. If true, exactly one flag must be True. Otherwise, at most one flag can be True, and it is valid for all flags to be False.
flag_values – flags.FlagValues, optional FlagValues instance where the flags are defined.
- Raises:
ValueError – Raised when multiple FlagValues are used in the same invocation. This can occur when FlagHolders have different _flagvalues or when str-type flag_names entries are present and the flag_values argument does not match that of provided FlagHolder(s).
- absl.flags.mark_flag_as_required(flag_name, flag_values=<absl.flags._flagvalues.FlagValues object>)[source]
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-
Nonevalue, such asFalse,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:
if __name__ == '__main__': flags.mark_flag_as_required('your_flag_name') app.run()
- Parameters:
flag_name – str | FlagHolder, name or holder of the flag. Positional-only parameter.
flag_values – flags.FlagValues, optional
FlagValuesinstance where the flag is defined.
- Raises:
AttributeError – Raised when flag_name is not registered as a valid flag name.
ValueError – Raised when flag_values is non-default and does not match the FlagValues of the provided FlagHolder instance.
- absl.flags.mark_flags_as_mutual_exclusive(flag_names, required=False, flag_values=<absl.flags._flagvalues.FlagValues object>)[source]
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 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.- Parameters:
flag_names – [str | FlagHolder], names or holders of flags. Positional-only parameter.
required – bool. If true, exactly one of the flags must have a value other than None. Otherwise, at most one of the flags can have a value other than None, and it is valid for all of the flags to be None.
flag_values – flags.FlagValues, optional FlagValues instance where the flags are defined.
- Raises:
ValueError – Raised when multiple FlagValues are used in the same invocation. This can occur when FlagHolders have different _flagvalues or when str-type flag_names entries are present and the flag_values argument does not match that of provided FlagHolder(s).
- absl.flags.mark_flags_as_required(flag_names, flag_values=<absl.flags._flagvalues.FlagValues object>)[source]
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:
if __name__ == '__main__': flags.mark_flags_as_required(['flag1', 'flag2', 'flag3']) app.run()
- Parameters:
flag_names – Sequence[str | FlagHolder], names or holders of the flags.
flag_values – flags.FlagValues, optional FlagValues instance where the flags are defined.
- Raises:
AttributeError – If any of flag name has not already been defined as a flag.
- absl.flags.multi_flags_validator(flag_names, message='Flag validation failed', flag_values=<absl.flags._flagvalues.FlagValues object>)[source]
A function decorator for defining a multi-flag validator.
Registers the decorated function as a validator for flag_names, e.g.:
@flags.multi_flags_validator(['foo', 'bar']) def _CheckFooBar(flags_dict): ...
See
register_multi_flags_validator()for the specification of checker function.- Parameters:
flag_names – [str | FlagHolder], a list of the flag names or holders to be checked. Positional-only parameter.
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.
- Returns:
A function decorator that registers its function argument as a validator.
- Raises:
AttributeError – Raised when a flag is not registered as a valid flag name.
- absl.flags.register_multi_flags_validator(flag_names, multi_flags_checker, message='Flags validation failed', flag_values=<absl.flags._flagvalues.FlagValues object>)[source]
Adds a constraint to multiple flags.
The constraint is validated when flags are initially parsed, and after each change of the corresponding flag’s value.
- Parameters:
flag_names – [str | FlagHolder], a list of the flag names or holders to be checked. Positional-only parameter.
multi_flags_checker –
callable, a function to validate the flag.
- 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.
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.
flag_values – flags.FlagValues, optional FlagValues instance to validate against.
- Raises:
AttributeError – Raised when a flag is not registered as a valid flag name.
ValueError – Raised when multiple FlagValues are used in the same invocation. This can occur when FlagHolders have different _flagvalues or when str-type flag_names entries are present and the flag_values argument does not match that of provided FlagHolder(s).
- absl.flags.register_validator(flag_name, checker, message='Flag validation failed', flag_values=<absl.flags._flagvalues.FlagValues object>)[source]
Adds a constraint, which will be enforced during program execution.
The constraint is validated when flags are initially parsed, and after each change of the corresponding flag’s value.
- Parameters:
flag_name – str | FlagHolder, name or holder of the flag to be checked. Positional-only parameter.
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 Falseorraise 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.
ValueError – Raised when flag_values is non-default and does not match the FlagValues of the provided FlagHolder instance.
- absl.flags.set_default(flag_holder: FlagHolder[_T], value: _T) None[source]
Changes the default value of the provided flag object.
The flag’s current value is also updated if the flag is currently using the default value, i.e. not specified in the command line, and not set by FLAGS.name = value.
- Parameters:
flag_holder – FlagHolder, the flag to modify.
value – The new default value.
- Raises:
IllegalFlagValueError – Raised when value is not valid.
- absl.flags.text_wrap(text: str, length: int | None = None, indent: str = '', firstline_indent: str | None = None) str[source]
Wraps a given text to a maximum line length and returns it.
It turns lines that only contain whitespace into empty lines, keeps new lines, and expands tabs using 4 spaces.
- Parameters:
text – str, text to wrap.
length – int, maximum length of a line, includes indentation. If this is None then use get_help_width()
indent – str, indent for all but first line.
firstline_indent – str, indent for first line; if None, fall back to indent.
- Returns:
str, the wrapped text.
- Raises:
ValueError – Raised if indent or firstline_indent not shorter than length.
- absl.flags.validator(flag_name, message='Flag validation failed', flag_values=<absl.flags._flagvalues.FlagValues object>)[source]
A function decorator for defining a flag validator.
Registers the decorated function as a validator for flag_name, e.g.:
@flags.validator('foo') def _CheckFoo(foo): ...
See
register_validator()for the specification of checker function.- Parameters:
flag_name – str | FlagHolder, name or holder of the flag to be checked. Positional-only parameter.
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.
- Returns:
A function decorator that registers its function argument as a validator.
- Raises:
AttributeError – Raised when flag_name is not registered as a valid flag name.