|
5 | 5 | import enum |
6 | 6 | import re |
7 | 7 | 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 | + |
9 | 10 | 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 |
10 | 13 | try: |
| 14 | + # Python 3.6+ should have Collection in the typing module |
11 | 15 | from typing import Collection |
12 | 16 | 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 |
27 | 54 |
|
28 | 55 |
|
29 | 56 | ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m') |
|
0 commit comments