|
4 | 4 | from threading import local as threadlocal |
5 | 5 | from typing import AnyStr, Tuple, Optional |
6 | 6 | import warnings |
| 7 | +import sys |
7 | 8 | import copy |
8 | 9 | import logging |
9 | 10 | from datetime import datetime, timedelta |
@@ -422,14 +423,13 @@ def remove_query_from_url(url: AnyStr) -> Optional[AnyStr]: |
422 | 423 | # milliseconds precision |
423 | 424 | # Python can do this natively from version 3.6, but we need to include a |
424 | 425 | # fallback implementation for Python 3.5 |
425 | | -try: |
426 | | - # this will raise if 'timespec' isn't supported |
427 | | - datetime.utcnow().isoformat(timespec='milliseconds') # type: ignore |
428 | | - |
| 426 | +if sys.version_info >= (3, 6): |
| 427 | + # Python 3.6+ has a built-in method for this |
429 | 428 | def to_rfc3339(dt: datetime) -> str: |
430 | 429 | return dt.isoformat(timespec='milliseconds') # type: ignore |
431 | 430 |
|
432 | | -except Exception: |
| 431 | +else: |
| 432 | + # Python 3.5 fallback implementation |
433 | 433 | def _get_timezone_offset(dt: datetime) -> str: |
434 | 434 | if dt.tzinfo is None: |
435 | 435 | return '' |
@@ -464,17 +464,16 @@ def to_rfc3339(dt: datetime) -> str: |
464 | 464 |
|
465 | 465 |
|
466 | 466 | def get_package_version(package_name: str) -> Optional[str]: |
467 | | - try: |
468 | | - from importlib import metadata |
469 | | - |
470 | | - return metadata.version(package_name) # type: ignore |
471 | | - except ImportError: |
| 467 | + if sys.version_info >= (3, 8): |
472 | 468 | try: |
473 | | - import pkg_resources |
474 | | - except ImportError: |
| 469 | + from importlib import metadata |
| 470 | + return metadata.version(package_name) # type: ignore |
| 471 | + except metadata.PackageNotFoundError: |
475 | 472 | return None |
476 | | - |
| 473 | + else: |
477 | 474 | try: |
478 | | - return pkg_resources.get_distribution(package_name).version |
479 | | - except pkg_resources.DistributionNotFound: |
| 475 | + import pkg_resources # type: ignore |
| 476 | + return pkg_resources.get_distribution( |
| 477 | + package_name).version # type: ignore |
| 478 | + except (ImportError, pkg_resources.DistributionNotFound): |
480 | 479 | return None |
0 commit comments