How to use the pytype.pytd.pytd_utils.Print function in pytype

To help you get started, weā€™ve selected a few pytype 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 / pytype / pytype / pytd / parse / parser_test_base.py View on Github external
def ApplyVisitorToString(self, data, visitor):
    tree = self.Parse(data)
    new_tree = tree.Visit(visitor)
    return pytd_utils.Print(new_tree)
github google / pytype / pytype / convert_structural.py View on Github external
def match_call_record(self, matcher, solver, call_record, complete):
    """Match the record of a method call against the formal signature."""
    assert is_partial(call_record)
    assert is_complete(complete)
    formula = (
        matcher.match_Function_against_Function(call_record, complete, {}))
    if formula is booleq.FALSE:
      cartesian = call_record.Visit(visitors.ExpandSignatures())
      for signature in cartesian.signatures:
        formula = matcher.match_Signature_against_Function(
            signature, complete, {})
        if formula is booleq.FALSE:
          faulty_signature = pytd_utils.Print(signature)
          break
      else:
        faulty_signature = ""
      raise FlawedQuery("Bad call\n%s%s\nagainst:\n%s" % (
          type_match.unpack_name_of_partial(call_record.name),
          faulty_signature, pytd_utils.Print(complete)))
    solver.always_true(formula)
github google / pytype / pytype / pytd / serialize_ast.py View on Github external
loader: A load_pytd.Loader instance.

  Returns:
    A pytd.TypeDeclUnit representing the supplied AST as it would look after
    being written to a file and parsed.
  """
  # This is a workaround for functionality which crept into places it doesn't
  # belong. Ideally this would call some transformation Visitors on ast to
  # transform it into the same ast we get after parsing and loading (compare
  # load_pytd.Loader.load_file). Unfortunately parsing has some special cases,
  # e.g. '__init__' return type and '__new__' being a 'staticmethod', which
  # need to be moved to visitors before we can do this. Printing an ast also
  # applies transformations,
  # e.g. visitors.PrintVisitor._FormatContainerContents, which need to move to
  # their own visitors so they can be applied without printing.
  src = pytd_utils.Print(ast)
  ast = parser.parse_string(src=src, name=module_name,
                            python_version=python_version)
  ast = ast.Visit(visitors.LookupBuiltins(loader.builtins, full_names=False))
  ast = ast.Visit(visitors.ExpandCompatibleBuiltins(loader.builtins))
  ast = ast.Visit(visitors.LookupLocalTypes())
  ast = ast.Visit(visitors.AdjustTypeParameters())
  ast = ast.Visit(visitors.NamedTypeToClassType())
  ast = ast.Visit(visitors.FillInLocalPointers({"": ast, module_name: ast}))
  ast = ast.Visit(visitors.ClassTypeToLateType(
      ignore=[module_name + ".", "__builtin__.", "typing."]))
  return ast
github google / pytype / pytype / io.py View on Github external
UsageError: If the input filepath is invalid.
  """
  options = options or config.Options.create(input_filename)
  with config.verbosity_from(options):
    errorlog, (mod, builtins) = _call(
        analyze.infer_types, input_filename, options, loader)
    mod.Visit(visitors.VerifyVisitor())
    mod = optimize.Optimize(mod,
                            builtins,
                            # TODO(kramm): Add FLAGs for these
                            lossy=False,
                            use_abcs=False,
                            max_union=7,
                            remove_mutable=False)
    mod = pytd_utils.CanonicalOrdering(mod, sort_signatures=True)
    result = pytd_utils.Print(mod)
    log.info("=========== pyi optimized =============")
    log.info("\n%s", result)
    log.info("========================================")

  result += "\n"
  if options.quick:
    result = "# (generated with --quick)\n\n" + result
  return errorlog, result, mod
github google / pytype / pytype / analyze.py View on Github external
ast.Lookup("__getattr__")
    except KeyError:
      ast = pytd_utils.Concat(
          ast, builtins.GetDefaultAst(options.python_version))
  # If merged with other if statement, triggers a ValueError: Unresolved class
  # when attempts to load from the protocols file
  if options.protocols:
    protocols_pytd = tracer.loader.import_name("protocols")
  else:
    protocols_pytd = None
  builtins_pytd = tracer.loader.concat_all()
  # Insert type parameters, where appropriate
  ast = ast.Visit(visitors.CreateTypeParametersForSignatures())
  if options.protocols:
    log.info("=========== PyTD to solve =============\n%s",
             pytd_utils.Print(ast))
    ast = convert_structural.convert_pytd(ast, builtins_pytd, protocols_pytd)
  elif not show_library_calls:
    log.info("Solving is turned off. Discarding call traces.")
    # Rename remaining "~unknown" to "?"
    ast = ast.Visit(visitors.RemoveUnknownClasses())
    # Remove "~list" etc.:
    ast = convert_structural.extract_local(ast)
  _maybe_output_debug(options, tracer.program)
  return ast, builtins_pytd
github google / pytype / pytype / function.py View on Github external
for formal in self.pytd_sig.params:
      actual = arg_dict[formal.name]
      arg = actual.data
      if (formal.mutated_type is not None and
          arg.isinstance_SimpleAbstractValue()):
        if (isinstance(formal.type, pytd.GenericType) and
            isinstance(formal.mutated_type, pytd.GenericType) and
            formal.type.base_type == formal.mutated_type.base_type and
            isinstance(formal.type.base_type, pytd.ClassType) and
            formal.type.base_type.cls):
          names_actuals = zip(formal.mutated_type.base_type.cls.template,
                              formal.mutated_type.parameters)
          for tparam, type_actual in names_actuals:
            log.info("Mutating %s to %s",
                     tparam.name,
                     pytd_utils.Print(type_actual))
            type_actual_val = self.vm.convert.constant_to_var(
                abstract_utils.AsInstance(type_actual), subst, node,
                discard_concrete_values=True)
            mutations.append(Mutation(arg, tparam.full_name, type_actual_val))
        else:
          log.error("Old: %s", pytd_utils.Print(formal.type))
          log.error("New: %s", pytd_utils.Print(formal.mutated_type))
          log.error("Actual: %r", actual)
          raise ValueError("Mutable parameters setting a type to a "
                           "different base type is not allowed.")
    return mutations
github google / pytype / pytype / pytd / visitors.py View on Github external
class X(object):
        def copy(self):
          return X()
    we should have left X alone. But it prevents a number of false
    positives by enabling us to infer correct types for common
    implementations of __new__ and __enter__.

    Args:
      sig: A pytd.Signature.

    Returns:
      True if the signature needs a class param, False otherwise.
    """
    if self.class_name and self.function_name and sig.params:
      # Printing the class name escapes illegal characters.
      safe_class_name = pytd_utils.Print(pytd.NamedType(self.class_name))
      return (pytd_utils.Print(sig.return_type) == safe_class_name and
              pytd_utils.Print(sig.params[0].type) in (
                  "Type[%s]" % safe_class_name, safe_class_name))
    return False
github google / pytype / pytype / pytd / visitors.py View on Github external
def copy(self):
          return X()
    we should have left X alone. But it prevents a number of false
    positives by enabling us to infer correct types for common
    implementations of __new__ and __enter__.

    Args:
      sig: A pytd.Signature.

    Returns:
      True if the signature needs a class param, False otherwise.
    """
    if self.class_name and self.function_name and sig.params:
      # Printing the class name escapes illegal characters.
      safe_class_name = pytd_utils.Print(pytd.NamedType(self.class_name))
      return (pytd_utils.Print(sig.return_type) == safe_class_name and
              pytd_utils.Print(sig.params[0].type) in (
                  "Type[%s]" % safe_class_name, safe_class_name))
    return False
github google / pytype / pytype / function.py View on Github external
def _print(t):
  return pytd_utils.Print(t.get_instance_type())