MCPcopy Index your code
hub / github.com/python/mypy / TypeFormatter

Class TypeFormatter

mypy/suggestions.py:831–910  ·  view source on GitHub ↗

Visitor used to format types

Source from the content-addressed store, hash-verified

829
830
831class TypeFormatter(TypeStrVisitor):
832 """Visitor used to format types"""
833
834 # TODO: Probably a lot
835 def __init__(self, module: str | None, graph: Graph, options: Options) -> None:
836 super().__init__(options=options)
837 self.module = module
838 self.graph = graph
839
840 def visit_any(self, t: AnyType) -> str:
841 if t.missing_import_name:
842 return t.missing_import_name
843 else:
844 return "Any"
845
846 def visit_instance(self, t: Instance) -> str:
847 s = t.type.fullname or t.type.name or None
848 if s is None:
849 return "<???>"
850
851 mod_obj = split_target(self.graph, s)
852 assert mod_obj
853 mod, obj = mod_obj
854
855 # If a class is imported into the current module, rewrite the reference
856 # to point to the current module. This helps the annotation tool avoid
857 # inserting redundant imports when a type has been reexported.
858 if self.module:
859 parts = obj.split(".") # need to split the object part if it is a nested class
860 tree = self.graph[self.module].tree
861 if tree and parts[0] in tree.names and mod not in tree.names:
862 mod = self.module
863
864 if (mod, obj) == ("builtins", "tuple"):
865 mod, obj = "typing", "Tuple[" + t.args[0].accept(self) + ", ...]"
866 elif t.args:
867 obj += f"[{self.list_str(t.args)}]"
868
869 if mod_obj == ("builtins", "unicode"):
870 return "Text"
871 elif mod == "builtins":
872 return obj
873 else:
874 delim = "." if "." not in obj else ":"
875 return mod + delim + obj
876
877 def visit_tuple_type(self, t: TupleType) -> str:
878 if t.partial_fallback and t.partial_fallback.type:
879 fallback_name = t.partial_fallback.type.fullname
880 if fallback_name != "builtins.tuple":
881 return t.partial_fallback.accept(self)
882 s = self.list_str(t.items)
883 return f"Tuple[{s}]"
884
885 def visit_uninhabited_type(self, t: UninhabitedType) -> str:
886 return "Any"
887
888 def visit_typeddict_type(self, t: TypedDictType) -> str:

Callers 1

format_typeMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…