Skip to content

Commit

Permalink
fix importing typing under if TYPE_CHECKING: (enthought#448)
Browse files Browse the repository at this point in the history
(cherry picked from commit ba1b18f)
  • Loading branch information
junkmd committed Feb 3, 2024
1 parent d9737d7 commit 4064086
Show file tree
Hide file tree
Showing 10 changed files with 127 additions and 166 deletions.
88 changes: 33 additions & 55 deletions comtypes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import atexit
from ctypes import *
from ctypes import _SimpleCData
from ctypes import _Pointer, _SimpleCData

try:
from _ctypes import COMError
Expand All @@ -22,6 +22,36 @@
import sys
import types

# fmt: off
from typing import (
Any, ClassVar, overload, TYPE_CHECKING, TypeVar,
# instead of `builtins`. see PEP585
Dict, List, Tuple, Type,
# instead of `collections.abc`. see PEP585
Callable, Iterable, Iterator,
# instead of `A | B` and `None | A`. see PEP604
Optional, Union as _UnionT, # avoiding confusion with `ctypes.Union`
)
# fmt: on
if TYPE_CHECKING:
from ctypes import _CData # only in `typeshed`, private in runtime
from comtypes import hints as hints # type: ignore
else:
_CData = _SimpleCData.__mro__[:-1][-1]

from comtypes.GUID import GUID
from comtypes import patcher
from comtypes._npsupport import interop as npsupport
from comtypes._memberspec import (
ComMemberGenerator,
_ComMemberSpec,
DispMemberGenerator,
_DispMemberSpec,
_encode_idl,
_resolve_argspec,
)


################################################################

# fmt: off
Expand Down Expand Up @@ -63,59 +93,6 @@ def wrapper(cls):
return wrapper
# fmt: on

################################################################

# type hinting symbols
#
# `if TYPE_CHECKING:` code block must not be executed because `TYPE_CHECKING`
# is always `False` in runtime.
# see https://peps.python.org/pep-0484/#runtime-or-type-checking
#
if sys.version_info >= (3, 5):
from typing import TYPE_CHECKING
else: # typehints in this package don't support Py<3.5 due to importing symbols.
TYPE_CHECKING = False
#
# Annotations must be placed in a `# type:` comment in according to PEP484.
# see https://peps.python.org/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code
# - `NameError` never raises by using those symbols.
# - It is not able to use any runtime introspections, such as
# `typing.get_type_hints` or `typing.get_origin`.
#
if TYPE_CHECKING:
from ctypes import _CData # only in `typeshed`, private in runtime

# _CData = _SimpleCData.__mro__[:-1][-1] # defining in runtime
from ctypes import _Pointer
from typing import Any, ClassVar, overload, TypeVar

# XXX: symbols for backward compatibility.
# instead of `builtins`. see PEP585.
from typing import Dict, List, Tuple, Type

# instead of `collections.abc`. see PEP585.
from typing import Callable, Iterable, Iterator

# instead of `A | B` and `None | A`. see PEP604.
from typing import Union as _UnionT # avoiding confusion with `ctypes.Union`
from typing import Optional

# utilities or workarounds for annotations.
from comtypes import hints as hints

################################################################

from comtypes.GUID import GUID
from comtypes import patcher
from comtypes._npsupport import interop as npsupport
from comtypes._memberspec import (
ComMemberGenerator,
_ComMemberSpec,
DispMemberGenerator,
_DispMemberSpec,
_encode_idl,
_resolve_argspec,
)

################################################################
if sys.version_info >= (3, 0):
Expand Down Expand Up @@ -849,8 +826,9 @@ def COMMETHOD(idlflags, restype, methodname, *argspec):
################################################################
# IUnknown, the root of all evil...

_T_IUnknown = TypeVar("_T_IUnknown", bound="IUnknown")

if TYPE_CHECKING:
_T_IUnknown = TypeVar("_T_IUnknown", bound="IUnknown")

class _IUnknown_Base(c_void_p):
"""This is workaround to avoid false-positive of static type checking.
Expand Down
44 changes: 21 additions & 23 deletions comtypes/_memberspec.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,26 @@
import ctypes

from typing import (
Any,
Callable,
Dict,
Iterator,
List,
Optional,
Tuple,
Type,
Union as _UnionT,
)

from comtypes import _CData
import comtypes
from comtypes import TYPE_CHECKING

if TYPE_CHECKING:
from comtypes import _CData
from typing import (
Any,
Callable,
Dict,
Iterator,
List,
Optional,
Tuple,
Type,
Union as _UnionT,
)

PositionalParamFlagType = Tuple[int, Optional[str]]
OptionalParamFlagType = Tuple[int, Optional[str], Any]
ParamFlagType = _UnionT[PositionalParamFlagType, OptionalParamFlagType]
PositionalArgSpecElmType = Tuple[List[str], Type[_CData], str]
OptionalArgSpecElmType = Tuple[List[str], Type[_CData], str, Any]
ArgSpecElmType = _UnionT[PositionalArgSpecElmType, OptionalArgSpecElmType]


PositionalParamFlagType = Tuple[int, Optional[str]]
OptionalParamFlagType = Tuple[int, Optional[str], Any]
ParamFlagType = _UnionT[PositionalParamFlagType, OptionalParamFlagType]
PositionalArgSpecElmType = Tuple[List[str], Type[_CData], str]
OptionalArgSpecElmType = Tuple[List[str], Type[_CData], str, Any]
ArgSpecElmType = _UnionT[PositionalArgSpecElmType, OptionalArgSpecElmType]


_PARAMFLAGS = {
Expand Down
38 changes: 14 additions & 24 deletions comtypes/automation.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,29 @@
import datetime
import decimal
import sys

from ctypes import *
from ctypes import _Pointer
from _ctypes import CopyComPointer
from comtypes import (
BSTR,
COMError,
COMMETHOD,
GUID,
IID,
IUnknown,
STDMETHOD,
from ctypes.wintypes import DWORD, LONG, UINT, VARIANT_BOOL, WCHAR, WORD
from typing import (
Any,
Callable,
ClassVar,
List,
Optional,
TYPE_CHECKING,
Tuple,
Union as _UnionT,
)

from comtypes import BSTR, COMError, COMMETHOD, GUID, IID, IUnknown, STDMETHOD
from comtypes.hresult import *
import comtypes.patcher
import comtypes

if TYPE_CHECKING:
from comtypes import hints # type: ignore

try:
from comtypes import _safearray
except (ImportError, AttributeError):
Expand All @@ -29,21 +34,6 @@ class _safearray(object):
tagSAFEARRAY = None


from ctypes.wintypes import DWORD, LONG, UINT, VARIANT_BOOL, WCHAR, WORD

if TYPE_CHECKING:
from typing import (
Any,
Callable,
ClassVar,
List,
Optional,
Tuple,
Union as _UnionT,
)
from comtypes import hints


if sys.version_info >= (3, 0):
int_types = (int,)
str_types = (str,)
Expand Down
21 changes: 14 additions & 7 deletions comtypes/client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,35 @@
import logging
import os
import sys
from typing import (
Any,
Optional,
overload,
Type,
TYPE_CHECKING,
TypeVar,
Union as _UnionT,
)

import comtypes
from comtypes.hresult import *
from comtypes import automation, CoClass, GUID, IUnknown, TYPE_CHECKING, typeinfo
from comtypes import automation, CoClass, GUID, IUnknown, typeinfo
import comtypes.client.dynamic
from comtypes.client._constants import Constants
from comtypes.client._events import GetEvents, ShowEvents, PumpEvents
from comtypes.client._generate import GetModule
from comtypes.client._code_cache import _find_gen_dir

if TYPE_CHECKING:
from comtypes import hints # type: ignore

gen_dir = _find_gen_dir()
import comtypes.gen

### for testing
##gen_dir = None

if TYPE_CHECKING:
from typing import Any, Optional, overload, Type, TypeVar, Union as _UnionT
from comtypes import hints

_T_IUnknown = TypeVar("_T_IUnknown", bound=IUnknown)

_T_IUnknown = TypeVar("_T_IUnknown", bound=IUnknown)
logger = logging.getLogger(__name__)


Expand Down
6 changes: 2 additions & 4 deletions comtypes/client/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import os
import sys
import types
from typing import Any, Tuple, List, Optional, Dict, Union as _UnionT

if sys.version_info >= (3, 0):
base_text_type = str
Expand All @@ -13,13 +14,10 @@
base_text_type = basestring
import _winreg as winreg

from comtypes import GUID, TYPE_CHECKING, typeinfo
from comtypes import GUID, typeinfo
import comtypes.client
from comtypes.tools import codegenerator, tlbparser

if TYPE_CHECKING:
from typing import Any, Tuple, List, Optional, Dict, Union as _UnionT


logger = logging.getLogger(__name__)

Expand Down
14 changes: 2 additions & 12 deletions comtypes/tools/codegenerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,17 @@
import os
import sys
import textwrap
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union as _UnionT

if sys.version_info >= (3, 0):
import io
else:
import cStringIO as io

import comtypes
from comtypes import TYPE_CHECKING, typeinfo
from comtypes import typeinfo
from comtypes.tools import tlbparser, typedesc

if TYPE_CHECKING:
from typing import (
Any,
Dict,
Iterator,
List,
Optional,
Tuple,
Union as _UnionT,
)


version = comtypes.__version__

Expand Down
30 changes: 14 additions & 16 deletions comtypes/tools/tlbparser.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,24 @@
from __future__ import print_function
import os
import sys
from ctypes import alignment, c_void_p, sizeof, windll
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Type,
TYPE_CHECKING,
TypeVar,
Tuple,
Union as _UnionT,
)
from ctypes import alignment, c_void_p, _Pointer, sizeof, windll

from comtypes import automation, COMError, TYPE_CHECKING, typeinfo
from comtypes import automation, _CData, COMError, typeinfo
from comtypes.tools import typedesc
from comtypes.client._code_cache import _get_module_filename

if TYPE_CHECKING:
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Type,
TypeVar,
Tuple,
Union as _UnionT,
)
from ctypes import _CData, _Pointer


# Is the process 64-bit?
is_64bits = sys.maxsize > 2**32
Expand Down
6 changes: 2 additions & 4 deletions comtypes/tools/typedesc.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,11 @@
# in typedesc_base

import ctypes
from comtypes import TYPE_CHECKING
from typing import Any, List, Optional, Tuple, Union as _UnionT

from comtypes.typeinfo import ITypeLib, TLIBATTR
from comtypes.tools.typedesc_base import *

if TYPE_CHECKING:
from typing import Any, List, Optional, Tuple, Union as _UnionT


class TypeLib(object):
def __init__(self, name, guid, major, minor, doc=None):
Expand Down
Loading

0 comments on commit 4064086

Please sign in to comment.