Skip to content

Commit 46b3e24

Browse files
committed
Fix Collection type definition so it works on all versions of Python
1 parent 45851d1 commit 46b3e24

File tree

1 file changed

+42
-15
lines changed

1 file changed

+42
-15
lines changed

TableFormatter.py

Lines changed: 42 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,52 @@
55
import enum
66
import re
77
import textwrap as textw
8-
from typing import List, Union, Tuple, Iterable, Sized, Container, Generic, TypeVar
8+
from typing import List, Iterable, Tuple, Union
9+
910
from wcwidth import wcswidth
11+
12+
# This whole try/except exists to make sure a Collection type exists for use with optional type hinting and isinstance
1013
try:
14+
# Python 3.6+ should have Collection in the typing module
1115
from typing import Collection
1216
except ImportError:
13-
# noinspection PyAbstractClass
14-
class Collection(Generic[TypeVar('T_co', covariant=True)], Container, Sized, Iterable):
15-
"""hack to enable Collection typing"""
16-
__slots__ = ()
17-
18-
# noinspection PyPep8Naming
19-
@classmethod
20-
def __subclasshook__(cls, C):
21-
if cls is Collection:
22-
if any("__len__" in B.__dict__ for B in C.__mro__) and \
23-
any("__iter__" in B.__dict__ for B in C.__mro__) and \
24-
any("__contains__" in B.__dict__ for B in C.__mro__):
25-
return True
26-
return NotImplemented
17+
from typing import Container, Sized
18+
import sys
19+
20+
# Unfortunately need slightly different solutions for Python 3.4 vs 3.5
21+
if sys.version_info < (3, 5):
22+
# Python 3.4
23+
# noinspection PyAbstractClass
24+
class Collection(Container, Sized, Iterable):
25+
"""hack to enable Collection typing"""
26+
__slots__ = ()
27+
28+
# noinspection PyPep8Naming
29+
@classmethod
30+
def __subclasshook__(cls, C):
31+
if cls is Collection:
32+
if any("__len__" in B.__dict__ for B in C.__mro__) and \
33+
any("__iter__" in B.__dict__ for B in C.__mro__) and \
34+
any("__contains__" in B.__dict__ for B in C.__mro__):
35+
return True
36+
return NotImplemented
37+
else:
38+
# Python 3.5
39+
# noinspection PyAbstractClass
40+
from typing import Generic, TypeVar
41+
class Collection(Generic[TypeVar('T_co', covariant=True)], Container, Sized, Iterable):
42+
"""hack to enable Collection typing"""
43+
__slots__ = ()
44+
45+
# noinspection PyPep8Naming
46+
@classmethod
47+
def __subclasshook__(cls, C):
48+
if cls is Collection:
49+
if any("__len__" in B.__dict__ for B in C.__mro__) and \
50+
any("__iter__" in B.__dict__ for B in C.__mro__) and \
51+
any("__contains__" in B.__dict__ for B in C.__mro__):
52+
return True
53+
return NotImplemented
2754

2855

2956
ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m')

0 commit comments

Comments
 (0)