Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

type_debug: Remove type_debug.

Zixuan James Li965ed728e11c
diff --git a/docs/testing/mypy.md b/docs/testing/mypy.md
index e4d73e3469c..221c3145d60 100644
--- a/docs/testing/mypy.md
+++ b/docs/testing/mypy.md
@@ -114,44 +114,6 @@ everything in the third-party module as an `Any`, which is the right
model (one certainly wouldn't want to need stubs for everything just
to use `mypy`!), but means the code can't be fully type-checked.
-## `type_debug.py`
-
-`zerver/lib/type_debug.py` has a useful decorator `print_types`. It
-prints the types of the parameters of the decorated function and the
-return type whenever that function is called. This can help find out
-what parameter types a function is supposed to accept, or if
-parameters with the wrong types are being passed to a function.
-
-Here is an example using the interactive console:
-
-```pycon
->>> from zerver.lib.type_debug import print_types
->>>
->>> @print_types
-... def func(x, y):
-... return x + y
-...
->>> func(1.0, 2)
-func(float, int) -> float
-3.0
->>> func('a', 'b')
-func(str, str) -> str
-'ab'
->>> func((1, 2), (3,))
-func((int, int), (int,)) -> (int, int, int)
-(1, 2, 3)
->>> func([1, 2, 3], [4, 5, 6, 7])
-func([int, ...], [int, ...]) -> [int, ...]
-[1, 2, 3, 4, 5, 6, 7]
-```
-
-`print_all` prints the type of the first item of lists. So `[int, ...]` represents
-a list whose first element's type is `int`. Types of all items are not printed
-because a list can have many elements, which would make the output too large.
-
-Similarly in dicts, one key's type and the corresponding value's type are printed.
-So `{1: 'a', 2: 'b', 3: 'c'}` will be printed as `{int: str, ...}`.
-
## Using @overload to accurately describe variations
Sometimes, a function's type is most precisely expressed as a few
diff --git a/zerver/lib/type_debug.py b/zerver/lib/type_debug.py
deleted file mode 100644
index 24071d7bd3e..00000000000
--- a/zerver/lib/type_debug.py
+++ /dev/null
@@ -1,92 +0,0 @@
-import functools
-import sys
-from typing import IO, Any, Callable, Mapping, Sequence, TypeVar, cast
-
-
-def get_mapping_type_str(x: Mapping[Any, Any]) -> str:
- container_type = type(x).__name__
- if not x:
- if container_type == "dict":
- return "{}"
- else:
- return container_type + "([])"
- key = next(iter(x))
- key_type = get_type_str(key)
- value_type = get_type_str(x[key])
- if container_type == "dict":
- if len(x) == 1:
- return f"{{{key_type}: {value_type}}}"
- else:
- return f"{{{key_type}: {value_type}, ...}}"
- else:
- if len(x) == 1:
- return f"{container_type}([({key_type}, {value_type})])"
- else:
- return f"{container_type}([({key_type}, {value_type}), ...])"
-
-
-def get_sequence_type_str(x: Sequence[Any]) -> str:
- container_type = type(x).__name__
- if not x:
- if container_type == "list":
- return "[]"
- else:
- return container_type + "([])"
- elem_type = get_type_str(x[0])
- if container_type == "list":
- if len(x) == 1:
- return "[" + elem_type + "]"
- else:
- return "[" + elem_type + ", ...]"
- else:
- if len(x) == 1:
- return f"{container_type}([{elem_type}])"
- else:
- return f"{container_type}([{elem_type}, ...])"
-
-
-expansion_blacklist = (str, bytes)
-
-
-def get_type_str(x: Any) -> str:
- if x is None:
- return "None"
- elif isinstance(x, tuple):
- types = []
- for v in x:
- types.append(get_type_str(v))
- if len(x) == 1:
- return "(" + types[0] + ",)"
- else:
- return "(" + ", ".join(types) + ")"
- elif isinstance(x, Mapping):
- return get_mapping_type_str(x)
- elif isinstance(x, Sequence) and not isinstance(x, expansion_blacklist):
- return get_sequence_type_str(x)
- else:
- return type(x).__name__
-
-
-FuncT = TypeVar("FuncT", bound=Callable[..., object])
-
-
-def print_types_to(file_obj: IO[str]) -> Callable[[FuncT], FuncT]:
- def decorator(func: FuncT) -> FuncT:
- @functools.wraps(func)
- def wrapper(*args: object, **kwargs: object) -> object:
- arg_types = [get_type_str(arg) for arg in args]
- kwarg_types = [key + "=" + get_type_str(value) for key, value in kwargs.items()]
- ret_val = func(*args, **kwargs)
- output = "{}({}) -> {}".format(
- func.__name__, ", ".join(arg_types + kwarg_types), get_type_str(ret_val)
- )
- print(output, file=file_obj)
- return ret_val
-
- return cast(FuncT, wrapper) # https://github.com/python/mypy/issues/1927
-
- return decorator
-
-
-def print_types(func: FuncT) -> FuncT:
- return print_types_to(sys.stdout)(func)
diff --git a/zerver/tests/test_type_debug.py b/zerver/tests/test_type_debug.py
deleted file mode 100644
index 527c9a3cab5..00000000000
--- a/zerver/tests/test_type_debug.py
+++ /dev/null
@@ -1,131 +0,0 @@
-import sys
-from io import StringIO
-from typing import Any, Callable, Dict, Iterable, List, Tuple, TypeVar
-
-from zerver.lib.test_classes import ZulipTestCase
-from zerver.lib.type_debug import print_types
-
-T = TypeVar("T")
-
-
-def add(x: Any = 0, y: Any = 0) -> Any:
- return x + y
-
-
-def to_dict(v: Iterable[Tuple[Any, Any]] = []) -> Dict[Any, Any]:
- return dict(v)
-
-
-class TypesPrintTest(ZulipTestCase):
-
- # These 2 methods are needed to run tests with our custom test-runner
- def _pre_setup(self) -> None:
- pass
-
- def _post_teardown(self) -> None:
- pass
-
- def check_signature(
- self, signature: str, retval: T, func: Callable[..., T], *args: Any, **kwargs: Any
- ) -> None:
- """
- Checks if print_types outputs `signature` when func is called with *args and **kwargs.
- Do not decorate func with print_types before passing into this function.
- func will be decorated with print_types within this function.
- """
- try:
- original_stdout = sys.stdout
- sys.stdout = StringIO()
- self.assertEqual(retval, print_types(func)(*args, **kwargs))
- self.assertEqual(sys.stdout.getvalue().strip(), signature)
- finally:
- sys.stdout = original_stdout
-
- def test_empty(self) -> None:
- def empty_func() -> None:
- pass
-
- self.check_signature("empty_func() -> None", None, empty_func)
- self.check_signature("<lambda>() -> None", None, (lambda: None))
-
- def test_basic(self) -> None:
- self.check_signature("add(float, int) -> float", 5.0, add, 2.0, 3)
- self.check_signature("add(float, y=int) -> float", 5.0, add, 2.0, y=3)
- self.check_signature("add(x=int) -> int", 2, add, x=2)
- self.check_signature("add() -> int", 0, add)
-
- def test_list(self) -> None:
- self.check_signature("add([], [str]) -> [str]", ["two"], add, [], ["two"])
- self.check_signature("add([int], [str]) -> [int, ...]", [2, "two"], add, [2], ["two"])
- self.check_signature(
- "add([int, ...], y=[]) -> [int, ...]", [2, "two"], add, [2, "two"], y=[]
- )
-
- def test_dict(self) -> None:
- self.check_signature("to_dict() -> {}", {}, to_dict)
- self.check_signature(
- "to_dict([(int, str)]) -> {int: str}", {2: "two"}, to_dict, [(2, "two")]
- )
- self.check_signature(
- "to_dict(((int, str),)) -> {int: str}", {2: "two"}, to_dict, ((2, "two"),)
- )
- self.check_signature(
- "to_dict([(int, str), ...]) -> {int: str, ...}",
- {1: "one", 2: "two"},
- to_dict,
- [(1, "one"), (2, "two")],
- )
-
- def test_tuple(self) -> None:
- self.check_signature("add((), ()) -> ()", (), add, (), ())
- self.check_signature("add((int,), (str,)) -> (int, str)", (1, "one"), add, (1,), ("one",))
- self.check_signature("add(((),), ((),)) -> ((), ())", ((), ()), add, ((),), ((),))
-
- def test_class(self) -> None:
- class A:
- pass
-
- class B(str):
- pass
-
- self.check_signature("<lambda>(A) -> str", "A", (lambda x: x.__class__.__name__), A())
- self.check_signature("<lambda>(B) -> int", 5, (lambda x: len(x)), B("hello"))
-
- def test_sequence(self) -> None:
- class A(List[Any]):
- pass
-
- class B(List[Any]):
- pass
-
- self.check_signature("add(A([]), B([str])) -> [str]", ["two"], add, A([]), B(["two"]))
- self.check_signature(
- "add(A([int]), B([str])) -> [int, ...]", [2, "two"], add, A([2]), B(["two"])
- )
- self.check_signature(
- "add(A([int, ...]), y=B([])) -> [int, ...]", [2, "two"], add, A([2, "two"]), y=B([])
- )
-
- def test_mapping(self) -> None:
- class A(Dict[Any, Any]):
- pass
-
- def to_A(v: Iterable[Tuple[Any, Any]] = []) -> A:
- return A(v)
-
- self.check_signature("to_A() -> A([])", A(()), to_A)
- self.check_signature(
- "to_A([(int, str)]) -> A([(int, str)])", {2: "two"}, to_A, [(2, "two")]
- )
- self.check_signature(
- "to_A([(int, str), ...]) -> A([(int, str), ...])",
- {1: "one", 2: "two"},
- to_A,
- [(1, "one"), (2, "two")],
- )
- self.check_signature(
- "to_A(((int, str), (int, str))) -> A([(int, str), ...])",
- {1: "one", 2: "two"},
- to_A,
- ((1, "one"), (2, "two")),
- )