[clang] [libclang/python] Fix some type errors, add type annotations (PR #98745)

Jannick Kremer via cfe-commits cfe-commits at lists.llvm.org
Sun Jul 21 04:37:57 PDT 2024


================
@@ -66,46 +66,77 @@
 
 import collections.abc
 import os
+import sys
 from enum import Enum
 
+from typing import (
+    Any,
+    Callable,
+    Generic,
+    Optional,
+    Type as TType,
+    TypeVar,
+    TYPE_CHECKING,
+    Union as TUnion,
+)
+from typing_extensions import Protocol, TypeAlias
+
+if TYPE_CHECKING:
+    from ctypes import _Pointer
+
+    StrPath: TypeAlias = TUnion[str, os.PathLike[str]]
+    LibFunc: TypeAlias = TUnion[
+        "tuple[str, Optional[list[Any]]]",
+        "tuple[str, Optional[list[Any]], Any]",
+        "tuple[str, Optional[list[Any]], Any, Callable[..., Any]]",
+    ]
+    CObjP: TypeAlias = _Pointer[Any]
+
+    TSeq = TypeVar("TSeq", covariant=True)
+
+    class NoSliceSequence(Protocol[TSeq]):
+        def __len__(self) -> int: ...
+        def __getitem__(self, key: int) -> TSeq: ...
+
 
 # Python 3 strings are unicode, translate them to/from utf8 for C-interop.
 class c_interop_string(c_char_p):
-    def __init__(self, p=None):
+    def __init__(self, p: str | bytes | None = None):
         if p is None:
             p = ""
         if isinstance(p, str):
             p = p.encode("utf8")
         super(c_char_p, self).__init__(p)
 
-    def __str__(self):
-        return self.value
+    def __str__(self) -> str:
+        return self.value or ""
----------------
DeinAlptraum wrote:

I just checked the `c_interop_string` usage again, and this type is apparently only used for converting strings that are fed _into_ the C interface functions, never returned. So no breaking change after all. Does make me wonder why it has a `__str__` though.

https://github.com/llvm/llvm-project/pull/98745


More information about the cfe-commits mailing list