Debian Codegraph @

src/_pytest/assertion/_guards.py

raw
1 from __future__ import annotations
2
3 import collections.abc
4 from collections.abc import Mapping
5 import dataclasses
6 from typing import TypeGuard
7
8
9 def issequence(x: object) -> TypeGuard[collections.abc.Sequence[object]]:
10 return isinstance(x, collections.abc.Sequence) and not isinstance(x, str)
11
12
13 def istext(x: object) -> TypeGuard[str]:
14 return isinstance(x, str)
15
16
17 def ismapping(x: object) -> TypeGuard[Mapping[object, object]]:
18 return isinstance(x, Mapping)
19
20
21 def isset(x: object) -> TypeGuard[set[object] | frozenset[object]]:
22 return isinstance(x, set | frozenset)
23
24
25 def isnamedtuple(obj: object) -> bool:
26 return isinstance(obj, tuple) and getattr(obj, "_fields", None) is not None
27
28
29 isdatacls = dataclasses.is_dataclass
30
31
32 def isattrs(obj: object) -> bool:
33 return getattr(obj, "__attrs_attrs__", None) is not None
34
35
36 def isiterable(obj: object) -> TypeGuard[collections.abc.Iterable[object]]:
37 try:
38 iter(obj) # type: ignore[call-overload]
39 return not istext(obj)
40 except Exception:
41 return False
42
43
44 def has_default_eq(obj: object) -> bool:
45 """Check if an instance of an object contains the default eq
46
47 First, we check if the object's __eq__ attribute has __code__,
48 if so, we check the equally of the method code filename (__code__.co_filename)
49 to the default one generated by the dataclass and attr module
50 for dataclasses the default co_filename is <string>, for attrs class, the __eq__ should contain "attrs eq generated"
51 """
52 # inspired from https://github.com/willmcgugan/rich/blob/07d51ffc1aee6f16bd2e5a25b4e82850fb9ed778/rich/pretty.py#L68
53 if hasattr(obj.__eq__, "__code__") and hasattr(obj.__eq__.__code__, "co_filename"):
54 code_filename = obj.__eq__.__code__.co_filename
55
56 if isattrs(obj):
57 return "attrs generated " in code_filename
58
59 return code_filename == "<string>" # data class
60 return True