def DEFINE_flag(flag, flag_values=FLAGS, module_name=None): # pylint: disable=g-bad-name """Registers a 'Flag' object with a 'FlagValues' object. By default, the global 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. Args: flag: A Flag object, a flag that is key to the module. flag_values: FlagValues object with which the flag will be registered. 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. """ # copying the reference to flag_values prevents pychecker warnings fv = flag_values fv[flag.name] = flag # Tell flag_values who's defining the flag. if isinstance(flag_values, FlagValues): # Regarding the above isinstance test: some users pass funny # values of flag_values (e.g., {}) in order to avoid the flag # registration (in the past, there used to be a flag_values == # FLAGS test here) and redefine flags with the same name (e.g., # debug). To avoid breaking their code, we perform the # registration only if flag_values is a real FlagValues object. if module_name: module = sys.modules.get(module_name) else: module, module_name = _helpers.GetCallingModuleObjectAndName() # TODO(vrusinov): _RegisterFlagByModule* should be public. # pylint: disable=protected-access flag_values._RegisterFlagByModule(module_name, flag) flag_values._RegisterFlagByModuleId(id(module), flag)
def __setitem__(self, name, flag): """Registers a new flag variable.""" fl = self.FlagDict() if not isinstance(flag, _flag.Flag): raise exceptions.IllegalFlagValue(flag) if str is bytes and isinstance(name, unicode): # When using Python 2 with unicode_literals, allow it but encode it # into the bytes type we require. name = name.encode('utf-8') if not isinstance(name, type('')): raise exceptions.FlagsError('Flag name must be a string') if not name: raise exceptions.FlagsError('Flag name cannot be empty') if name in fl and not flag.allow_override and not fl[ name].allow_override: module, module_name = _helpers.GetCallingModuleObjectAndName() if (self.FindModuleDefiningFlag(name) == module_name and id(module) != self.FindModuleIdDefiningFlag(name)): # If the flag has already been defined by a module with the same name, # but a different ID, we can stop here because it indicates that the # module is simply being imported a subsequent time. return raise exceptions.DuplicateFlagError(name, self) short_name = flag.short_name if short_name is not None: if (short_name in fl and not flag.allow_override and not fl[short_name].allow_override): raise exceptions.DuplicateFlagError(short_name, self) fl[short_name] = flag if (name not in fl # new flag or fl[name].using_default_value or not flag.using_default_value): fl[name] = flag