コード例 #1
0
def _internal_declare_key_flags(
    flag_names, flag_values=_flagvalues.FLAGS, key_flag_values=None):
  """Declares a flag as key for the calling module.

  Internal function.  User code should call declare_key_flag or
  adopt_module_key_flags instead.

  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 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.
  """
  key_flag_values = key_flag_values or flag_values

  module = _helpers.get_calling_module()

  for flag_name in flag_names:
    flag = flag_values[flag_name]
    key_flag_values.register_key_flag_for_module(module, flag)
コード例 #2
0
def _internal_declare_key_flags(flag_names,
                                flag_values=_flagvalues.FLAGS,
                                key_flag_values=None):
    """Declares a flag as key for the calling module.

  Internal function.  User code should call declare_key_flag or
  adopt_module_key_flags instead.

  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 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.
  """
    key_flag_values = key_flag_values or flag_values

    module = _helpers.get_calling_module()

    for flag_name in flag_names:
        flag = flag_values[flag_name]
        key_flag_values.register_key_flag_for_module(module, flag)
コード例 #3
0
    def from_flag(cls, flagname, flag_values, other_flag_values=None):
        """Creates a DuplicateFlagError by providing flag name and values.

    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.

    Returns:
      An instance of DuplicateFlagError.
    """
        first_module = flag_values.find_module_defining_flag(
            flagname, default='<unknown>')
        if other_flag_values is None:
            second_module = _helpers.get_calling_module()
        else:
            second_module = other_flag_values.find_module_defining_flag(
                flagname, default='<unknown>')
        flag_summary = flag_values[flagname].help
        msg = (
            "The flag '%s' is defined twice. First from %s, Second from %s.  "
            'Description from first occurrence: %s') % (
                flagname, first_module, second_module, flag_summary)
        return cls(msg)
コード例 #4
0
ファイル: _exceptions.py プロジェクト: bazelbuild/bazel
  def from_flag(cls, flagname, flag_values, other_flag_values=None):
    """Creates a DuplicateFlagError by providing flag name and values.

    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.

    Returns:
      An instance of DuplicateFlagError.
    """
    first_module = flag_values.find_module_defining_flag(
        flagname, default='<unknown>')
    if other_flag_values is None:
      second_module = _helpers.get_calling_module()
    else:
      second_module = other_flag_values.find_module_defining_flag(
          flagname, default='<unknown>')
    flag_summary = flag_values[flagname].help
    msg = ("The flag '%s' is defined twice. First from %s, Second from %s.  "
           "Description from first occurrence: %s") % (
               flagname, first_module, second_module, flag_summary)
    return cls(msg)
コード例 #5
0
def get_module_name():
  """Uses get_calling_module() to return the name of this module.

  For checking that _get_calling_module works as expected.

  Returns:
    A string, the name of this module.
  """
  return _helpers.get_calling_module()
コード例 #6
0
    def test_get_calling_module(self):
        self.assertEqual(_helpers.get_calling_module(), sys.argv[0])
        self.assertEqual(module_foo.get_module_name(),
                         'absl.flags.tests.module_foo')
        self.assertEqual(module_bar.get_module_name(),
                         'absl.flags.tests.module_bar')

        # We execute the following exec statements for their side-effect
        # (i.e., not raising an error).  They emphasize the case that not
        # all code resides in one of the imported modules: Python is a
        # really dynamic language, where we can dynamically construct some
        # code and execute it.
        code = ('from absl.flags import _helpers\n'
                'module_name = _helpers.get_calling_module()')
        exec(code)  # pylint: disable=exec-used

        # Next two exec statements executes code with a global environment
        # that is different from the global environment of any imported
        # module.
        exec(code, {})  # pylint: disable=exec-used
        # vars(self) returns a dictionary corresponding to the symbol
        # table of the self object.  dict(...) makes a distinct copy of
        # this dictionary, such that any new symbol definition by the
        # exec-ed code (e.g., import flags, module_name = ...) does not
        # affect the symbol table of self.
        exec(code, dict(vars(self)))  # pylint: disable=exec-used

        # Next test is actually more involved: it checks not only that
        # get_calling_module does not crash inside exec code, it also checks
        # that it returns the expected value: the code executed via exec
        # code is treated as being executed by the current module.  We
        # check it twice: first time by executing exec from the main
        # module, second time by executing it from module_bar.
        global_dict = {}
        exec(code, global_dict)  # pylint: disable=exec-used
        self.assertEqual(global_dict['module_name'], sys.argv[0])

        global_dict = {}
        module_bar.execute_code(code, global_dict)
        self.assertEqual(global_dict['module_name'],
                         'absl.flags.tests.module_bar')
コード例 #7
0
    def test_get_calling_module_with_iteritems_error(self):
        # This test checks that get_calling_module is using
        # sys.modules.items(), instead of .iteritems().
        orig_sys_modules = sys.modules

        # Mock sys.modules: simulates error produced by importing a module
        # in paralel with our iteration over sys.modules.iteritems().
        class SysModulesMock(dict):
            def __init__(self, original_content):
                dict.__init__(self, original_content)

            def iteritems(self):
                # Any dictionary method is fine, but not .iteritems().
                raise RuntimeError('dictionary changed size during iteration')

        sys.modules = SysModulesMock(orig_sys_modules)
        try:
            # _get_calling_module should still work as expected:
            self.assertEqual(_helpers.get_calling_module(), sys.argv[0])
            self.assertEqual(module_foo.get_module_name(),
                             'absl.flags.tests.module_foo')
        finally:
            sys.modules = orig_sys_modules