How to use the fire.inspectutils function in fire

To help you get started, we’ve selected a few fire examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github google / python-fire / fire / completion.py View on Github external
def Completions(component, verbose=False):
  """Gives possible Fire command completions for the component.

  A completion is a string that can be appended to a command to continue that
  command. These are used for TAB-completions in Bash for Fire CLIs.

  Args:
    component: The component whose completions to list.
    verbose: Whether to include all completions, even private members.
  Returns:
    A list of completions for a command that would so far return the component.
  """
  if inspect.isroutine(component) or inspect.isclass(component):
    spec = inspectutils.GetFullArgSpec(component)
    return _CompletionsFromArgs(spec.args + spec.kwonlyargs)

  if isinstance(component, (tuple, list)):
    return [str(index) for index in range(len(component))]

  if inspect.isgenerator(component):
    # TODO(dbieber): There are currently no commands available for generators.
    return []

  return [
      _FormatForCommand(member_name)
      for member_name, _ in VisibleMembers(component, verbose=verbose)
  ]
github google / python-fire / fire / helputils.py View on Github external
def UsageString(component, trace=None, verbose=False):
  """Returns a string showing how to use the component as a Fire command."""
  if trace:
    command = trace.GetCommand()
  else:
    command = None

  if command:
    command += ' '
  else:
    command = ''

  if inspect.isroutine(component) or inspect.isclass(component):
    spec = inspectutils.GetFullArgSpec(component)
    return _UsageStringFromFullArgSpec(command, spec)

  if isinstance(component, (list, tuple)):
    length = len(component)
    if length == 0:
      return command
    if length == 1:
      return command + '[0]'
    return command + '[0..{cap}]'.format(cap=length - 1)

  completions = completion.Completions(component, verbose)
  if command:
    completions = [''] + completions
  return '\n'.join(command + end for end in completions)
github google / python-fire / fire / core.py View on Github external
def _MakeParseFn(fn, metadata):
  """Creates a parse function for fn.

  Args:
    fn: The function or class to create the parse function for.
    metadata: Additional metadata about the component the parse function is for.
  Returns:
    A parse function for fn. The parse function accepts a list of arguments
    and returns (varargs, kwargs), remaining_args. The original function fn
    can then be called with fn(*varargs, **kwargs). The remaining_args are
    the leftover args from the arguments to the parse function.
  """
  fn_spec = inspectutils.GetFullArgSpec(fn)

  # Note: num_required_args is the number of positional arguments without
  # default values. All of these arguments are required.
  num_required_args = len(fn_spec.args) - len(fn_spec.defaults)
  required_kwonly = set(fn_spec.kwonlyargs) - set(fn_spec.kwonlydefaults)

  def _ParseFn(args):
    """Parses the list of `args` into (varargs, kwargs), remaining_args."""
    kwargs, remaining_kwargs, remaining_args = _ParseKeywordArgs(args, fn_spec)

    # Note: _ParseArgs modifies kwargs.
    parsed_args, kwargs, remaining_args, capacity = _ParseArgs(
        fn_spec.args, fn_spec.defaults, num_required_args, kwargs,
        remaining_args, metadata)

    if fn_spec.varargs or fn_spec.varkw:
github google / python-fire / fire / core.py View on Github external
component_trace.AddAccessedProperty(
            component, target, [target], filename, lineno)
      else:
        error = FireError('Cannot find key:', target)
        candidate_errors.append((error, initial_args))

    if not handled and remaining_args:
      # Object handler. We'll try to access a member of the component.
      try:
        target = remaining_args[0]

        component, consumed_args, remaining_args = _GetMember(
            component, remaining_args)
        handled = True

        filename, lineno = inspectutils.GetFileAndLine(component)

        component_trace.AddAccessedProperty(
            component, target, consumed_args, filename, lineno)

      except FireError as error:
        # Couldn't access member.
        candidate_errors.append((error, initial_args))

    if not handled and is_callable_object:
      # The component is a callable object; we'll try to call it.
      try:
        component, remaining_args = _CallAndUpdateTrace(
            component,
            remaining_args,
            component_trace,
            treatment='callable')
github google / python-fire / fire / core.py View on Github external
Args:
    component: The component to call
    args: Args for calling the component
    component_trace: FireTrace object that contains action trace
    treatment: Type of treatment used. Indicating whether we treat the component
        as a class, a routine, or a callable.
    target: Target in FireTrace element, default is None. If the value is None,
        the component itself will be used as target.
  Returns:
    component: The object that is the result of the callable call.
    remaining_args: The remaining args that haven't been consumed yet.
  """
  if not target:
    target = component
  filename, lineno = inspectutils.GetFileAndLine(component)
  metadata = decorators.GetMetadata(component)
  fn = component.__call__ if treatment == 'callable' else component
  parse = _MakeParseFn(fn, metadata)
  (varargs, kwargs), consumed_args, remaining_args, capacity = parse(args)
  component = fn(*varargs, **kwargs)

  if treatment == 'class':
    action = trace.INSTANTIATED_CLASS
  elif treatment == 'routine':
    action = trace.CALLED_ROUTINE
  else:
    action = trace.CALLED_CALLABLE
  component_trace.AddCalledComponent(
      component, target, consumed_args, filename, lineno, capacity,
      action=action)
github google / python-fire / fire / core.py View on Github external
used_separator = False
    if separator in remaining_args:
      # For the current component, only use arguments up to the separator.
      separator_index = remaining_args.index(separator)
      saved_args = remaining_args[separator_index + 1:]
      remaining_args = remaining_args[:separator_index]
      used_separator = True
    assert separator not in remaining_args

    handled = False
    candidate_errors = []

    is_callable = inspect.isclass(component) or inspect.isroutine(component)
    is_callable_object = callable(component) and not is_callable
    is_sequence = isinstance(component, (list, tuple))
    is_map = isinstance(component, dict) or inspectutils.IsNamedTuple(component)

    if not handled and is_callable:
      # The component is a class or a routine; we'll try to initialize it or
      # call it.
      is_class = inspect.isclass(component)

      try:
        component, remaining_args = _CallAndUpdateTrace(
            component,
            remaining_args,
            component_trace,
            treatment='class' if is_class else 'routine',
            target=component.__name__)
        handled = True
      except FireError as error:
        candidate_errors.append((error, initial_args))
github google / python-fire / fire / trace.py View on Github external
"""Returns whether a the trace need '--' before '--help'.

    '--' is needed when the component takes keyword arguments, when the value of
    flag matches one of the argument of the component, or the component takes in
    keyword-only arguments(e.g. argument with default value).

    Args:
      flag: the flag available for the trace

    Returns:
      True for needed '--', False otherwise.

    """
    element = self.GetLastHealthyElement()
    component = element.component
    spec = inspectutils.GetFullArgSpec(component)
    return (spec.varkw is not None
            or flag in spec.args
            or flag in spec.kwonlyargs)