Skip to content

Commit ba1b18f

Browse files
authored
fix importing typing under if TYPE_CHECKING: (enthought#448)
1 parent 11410ce commit ba1b18f

10 files changed

+127
-166
lines changed

comtypes/__init__.py

+33-55
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import atexit
55
from ctypes import *
6-
from ctypes import _SimpleCData
6+
from ctypes import _Pointer, _SimpleCData
77

88
try:
99
from _ctypes import COMError
@@ -22,6 +22,36 @@
2222
import sys
2323
import types
2424

25+
# fmt: off
26+
from typing import (
27+
Any, ClassVar, overload, TYPE_CHECKING, TypeVar,
28+
# instead of `builtins`. see PEP585
29+
Dict, List, Tuple, Type,
30+
# instead of `collections.abc`. see PEP585
31+
Callable, Iterable, Iterator,
32+
# instead of `A | B` and `None | A`. see PEP604
33+
Optional, Union as _UnionT, # avoiding confusion with `ctypes.Union`
34+
)
35+
# fmt: on
36+
if TYPE_CHECKING:
37+
from ctypes import _CData # only in `typeshed`, private in runtime
38+
from comtypes import hints as hints # type: ignore
39+
else:
40+
_CData = _SimpleCData.__mro__[:-1][-1]
41+
42+
from comtypes.GUID import GUID
43+
from comtypes import patcher
44+
from comtypes._npsupport import interop as npsupport
45+
from comtypes._memberspec import (
46+
ComMemberGenerator,
47+
_ComMemberSpec,
48+
DispMemberGenerator,
49+
_DispMemberSpec,
50+
_encode_idl,
51+
_resolve_argspec,
52+
)
53+
54+
2555
################################################################
2656

2757
# fmt: off
@@ -63,59 +93,6 @@ def wrapper(cls):
6393
return wrapper
6494
# fmt: on
6595

66-
################################################################
67-
68-
# type hinting symbols
69-
#
70-
# `if TYPE_CHECKING:` code block must not be executed because `TYPE_CHECKING`
71-
# is always `False` in runtime.
72-
# see https://peps.python.org/pep-0484/#runtime-or-type-checking
73-
#
74-
if sys.version_info >= (3, 5):
75-
from typing import TYPE_CHECKING
76-
else: # typehints in this package don't support Py<3.5 due to importing symbols.
77-
TYPE_CHECKING = False
78-
#
79-
# Annotations must be placed in a `# type:` comment in according to PEP484.
80-
# see https://peps.python.org/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code
81-
# - `NameError` never raises by using those symbols.
82-
# - It is not able to use any runtime introspections, such as
83-
# `typing.get_type_hints` or `typing.get_origin`.
84-
#
85-
if TYPE_CHECKING:
86-
from ctypes import _CData # only in `typeshed`, private in runtime
87-
88-
# _CData = _SimpleCData.__mro__[:-1][-1] # defining in runtime
89-
from ctypes import _Pointer
90-
from typing import Any, ClassVar, overload, TypeVar
91-
92-
# XXX: symbols for backward compatibility.
93-
# instead of `builtins`. see PEP585.
94-
from typing import Dict, List, Tuple, Type
95-
96-
# instead of `collections.abc`. see PEP585.
97-
from typing import Callable, Iterable, Iterator
98-
99-
# instead of `A | B` and `None | A`. see PEP604.
100-
from typing import Union as _UnionT # avoiding confusion with `ctypes.Union`
101-
from typing import Optional
102-
103-
# utilities or workarounds for annotations.
104-
from comtypes import hints as hints
105-
106-
################################################################
107-
108-
from comtypes.GUID import GUID
109-
from comtypes import patcher
110-
from comtypes._npsupport import interop as npsupport
111-
from comtypes._memberspec import (
112-
ComMemberGenerator,
113-
_ComMemberSpec,
114-
DispMemberGenerator,
115-
_DispMemberSpec,
116-
_encode_idl,
117-
_resolve_argspec,
118-
)
11996

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

829+
_T_IUnknown = TypeVar("_T_IUnknown", bound="IUnknown")
830+
852831
if TYPE_CHECKING:
853-
_T_IUnknown = TypeVar("_T_IUnknown", bound="IUnknown")
854832

855833
class _IUnknown_Base(c_void_p):
856834
"""This is workaround to avoid false-positive of static type checking.

comtypes/_memberspec.py

+21-23
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,26 @@
11
import ctypes
2-
2+
from typing import (
3+
Any,
4+
Callable,
5+
Dict,
6+
Iterator,
7+
List,
8+
Optional,
9+
Tuple,
10+
Type,
11+
Union as _UnionT,
12+
)
13+
14+
from comtypes import _CData
315
import comtypes
4-
from comtypes import TYPE_CHECKING
5-
6-
if TYPE_CHECKING:
7-
from comtypes import _CData
8-
from typing import (
9-
Any,
10-
Callable,
11-
Dict,
12-
Iterator,
13-
List,
14-
Optional,
15-
Tuple,
16-
Type,
17-
Union as _UnionT,
18-
)
19-
20-
PositionalParamFlagType = Tuple[int, Optional[str]]
21-
OptionalParamFlagType = Tuple[int, Optional[str], Any]
22-
ParamFlagType = _UnionT[PositionalParamFlagType, OptionalParamFlagType]
23-
PositionalArgSpecElmType = Tuple[List[str], Type[_CData], str]
24-
OptionalArgSpecElmType = Tuple[List[str], Type[_CData], str, Any]
25-
ArgSpecElmType = _UnionT[PositionalArgSpecElmType, OptionalArgSpecElmType]
16+
17+
18+
PositionalParamFlagType = Tuple[int, Optional[str]]
19+
OptionalParamFlagType = Tuple[int, Optional[str], Any]
20+
ParamFlagType = _UnionT[PositionalParamFlagType, OptionalParamFlagType]
21+
PositionalArgSpecElmType = Tuple[List[str], Type[_CData], str]
22+
OptionalArgSpecElmType = Tuple[List[str], Type[_CData], str, Any]
23+
ArgSpecElmType = _UnionT[PositionalArgSpecElmType, OptionalArgSpecElmType]
2624

2725

2826
_PARAMFLAGS = {

comtypes/automation.py

+14-24
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,29 @@
33
import datetime
44
import decimal
55
import sys
6-
76
from ctypes import *
87
from ctypes import _Pointer
98
from _ctypes import CopyComPointer
10-
from comtypes import (
11-
BSTR,
12-
COMError,
13-
COMMETHOD,
14-
GUID,
15-
IID,
16-
IUnknown,
17-
STDMETHOD,
9+
from ctypes.wintypes import DWORD, LONG, UINT, VARIANT_BOOL, WCHAR, WORD
10+
from typing import (
11+
Any,
12+
Callable,
13+
ClassVar,
14+
List,
15+
Optional,
1816
TYPE_CHECKING,
17+
Tuple,
18+
Union as _UnionT,
1919
)
20+
21+
from comtypes import BSTR, COMError, COMMETHOD, GUID, IID, IUnknown, STDMETHOD
2022
from comtypes.hresult import *
2123
import comtypes.patcher
2224
import comtypes
2325

26+
if TYPE_CHECKING:
27+
from comtypes import hints # type: ignore
28+
2429
try:
2530
from comtypes import _safearray
2631
except (ImportError, AttributeError):
@@ -29,21 +34,6 @@ class _safearray(object):
2934
tagSAFEARRAY = None
3035

3136

32-
from ctypes.wintypes import DWORD, LONG, UINT, VARIANT_BOOL, WCHAR, WORD
33-
34-
if TYPE_CHECKING:
35-
from typing import (
36-
Any,
37-
Callable,
38-
ClassVar,
39-
List,
40-
Optional,
41-
Tuple,
42-
Union as _UnionT,
43-
)
44-
from comtypes import hints
45-
46-
4737
if sys.version_info >= (3, 0):
4838
int_types = (int,)
4939
str_types = (str,)

comtypes/client/__init__.py

+14-7
Original file line numberDiff line numberDiff line change
@@ -12,28 +12,35 @@
1212
import logging
1313
import os
1414
import sys
15+
from typing import (
16+
Any,
17+
Optional,
18+
overload,
19+
Type,
20+
TYPE_CHECKING,
21+
TypeVar,
22+
Union as _UnionT,
23+
)
1524

1625
import comtypes
1726
from comtypes.hresult import *
18-
from comtypes import automation, CoClass, GUID, IUnknown, TYPE_CHECKING, typeinfo
27+
from comtypes import automation, CoClass, GUID, IUnknown, typeinfo
1928
import comtypes.client.dynamic
2029
from comtypes.client._constants import Constants
2130
from comtypes.client._events import GetEvents, ShowEvents, PumpEvents
2231
from comtypes.client._generate import GetModule
2332
from comtypes.client._code_cache import _find_gen_dir
2433

34+
if TYPE_CHECKING:
35+
from comtypes import hints # type: ignore
36+
2537
gen_dir = _find_gen_dir()
2638
import comtypes.gen
2739

2840
### for testing
2941
##gen_dir = None
3042

31-
if TYPE_CHECKING:
32-
from typing import Any, Optional, overload, Type, TypeVar, Union as _UnionT
33-
from comtypes import hints
34-
35-
_T_IUnknown = TypeVar("_T_IUnknown", bound=IUnknown)
36-
43+
_T_IUnknown = TypeVar("_T_IUnknown", bound=IUnknown)
3744
logger = logging.getLogger(__name__)
3845

3946

comtypes/client/_generate.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import os
66
import sys
77
import types
8+
from typing import Any, Tuple, List, Optional, Dict, Union as _UnionT
89

910
if sys.version_info >= (3, 0):
1011
base_text_type = str
@@ -13,13 +14,10 @@
1314
base_text_type = basestring
1415
import _winreg as winreg
1516

16-
from comtypes import GUID, TYPE_CHECKING, typeinfo
17+
from comtypes import GUID, typeinfo
1718
import comtypes.client
1819
from comtypes.tools import codegenerator, tlbparser
1920

20-
if TYPE_CHECKING:
21-
from typing import Any, Tuple, List, Optional, Dict, Union as _UnionT
22-
2321

2422
logger = logging.getLogger(__name__)
2523

comtypes/tools/codegenerator.py

+2-12
Original file line numberDiff line numberDiff line change
@@ -7,27 +7,17 @@
77
import os
88
import sys
99
import textwrap
10+
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union as _UnionT
1011

1112
if sys.version_info >= (3, 0):
1213
import io
1314
else:
1415
import cStringIO as io
1516

1617
import comtypes
17-
from comtypes import TYPE_CHECKING, typeinfo
18+
from comtypes import typeinfo
1819
from comtypes.tools import tlbparser, typedesc
1920

20-
if TYPE_CHECKING:
21-
from typing import (
22-
Any,
23-
Dict,
24-
Iterator,
25-
List,
26-
Optional,
27-
Tuple,
28-
Union as _UnionT,
29-
)
30-
3121

3222
version = comtypes.__version__
3323

comtypes/tools/tlbparser.py

+14-16
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,24 @@
11
from __future__ import print_function
22
import os
33
import sys
4-
from ctypes import alignment, c_void_p, sizeof, windll
4+
from typing import (
5+
Any,
6+
Callable,
7+
Dict,
8+
List,
9+
Optional,
10+
Type,
11+
TYPE_CHECKING,
12+
TypeVar,
13+
Tuple,
14+
Union as _UnionT,
15+
)
16+
from ctypes import alignment, c_void_p, _Pointer, sizeof, windll
517

6-
from comtypes import automation, COMError, TYPE_CHECKING, typeinfo
18+
from comtypes import automation, _CData, COMError, typeinfo
719
from comtypes.tools import typedesc
820
from comtypes.client._code_cache import _get_module_filename
921

10-
if TYPE_CHECKING:
11-
from typing import (
12-
Any,
13-
Callable,
14-
Dict,
15-
List,
16-
Optional,
17-
Type,
18-
TypeVar,
19-
Tuple,
20-
Union as _UnionT,
21-
)
22-
from ctypes import _CData, _Pointer
23-
2422

2523
# Is the process 64-bit?
2624
is_64bits = sys.maxsize > 2**32

comtypes/tools/typedesc.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,11 @@
22
# in typedesc_base
33

44
import ctypes
5-
from comtypes import TYPE_CHECKING
5+
from typing import Any, List, Optional, Tuple, Union as _UnionT
6+
67
from comtypes.typeinfo import ITypeLib, TLIBATTR
78
from comtypes.tools.typedesc_base import *
89

9-
if TYPE_CHECKING:
10-
from typing import Any, List, Optional, Tuple, Union as _UnionT
11-
1210

1311
class TypeLib(object):
1412
def __init__(self, name, guid, major, minor, doc=None):

0 commit comments

Comments
 (0)