You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

629 lines
18KB

  1. # util/compat.py
  2. # Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. """Handle Python version/platform incompatibilities."""
  8. import collections
  9. import contextlib
  10. import inspect
  11. import operator
  12. import platform
  13. import sys
  14. py310 = sys.version_info >= (3, 10)
  15. py38 = sys.version_info >= (3, 8)
  16. py37 = sys.version_info >= (3, 7)
  17. py3k = sys.version_info >= (3, 0)
  18. py2k = sys.version_info < (3, 0)
  19. pypy = platform.python_implementation() == "PyPy"
  20. cpython = platform.python_implementation() == "CPython"
  21. win32 = sys.platform.startswith("win")
  22. osx = sys.platform.startswith("darwin")
  23. arm = "aarch" in platform.machine().lower()
  24. has_refcount_gc = bool(cpython)
  25. contextmanager = contextlib.contextmanager
  26. dottedgetter = operator.attrgetter
  27. namedtuple = collections.namedtuple
  28. next = next # noqa
  29. FullArgSpec = collections.namedtuple(
  30. "FullArgSpec",
  31. [
  32. "args",
  33. "varargs",
  34. "varkw",
  35. "defaults",
  36. "kwonlyargs",
  37. "kwonlydefaults",
  38. "annotations",
  39. ],
  40. )
  41. class nullcontext(object):
  42. """Context manager that does no additional processing.
  43. Vendored from Python 3.7.
  44. """
  45. def __init__(self, enter_result=None):
  46. self.enter_result = enter_result
  47. def __enter__(self):
  48. return self.enter_result
  49. def __exit__(self, *excinfo):
  50. pass
  51. try:
  52. import threading
  53. except ImportError:
  54. import dummy_threading as threading # noqa
  55. def inspect_getfullargspec(func):
  56. """Fully vendored version of getfullargspec from Python 3.3."""
  57. if inspect.ismethod(func):
  58. func = func.__func__
  59. if not inspect.isfunction(func):
  60. raise TypeError("{!r} is not a Python function".format(func))
  61. co = func.__code__
  62. if not inspect.iscode(co):
  63. raise TypeError("{!r} is not a code object".format(co))
  64. nargs = co.co_argcount
  65. names = co.co_varnames
  66. nkwargs = co.co_kwonlyargcount if py3k else 0
  67. args = list(names[:nargs])
  68. kwonlyargs = list(names[nargs : nargs + nkwargs])
  69. nargs += nkwargs
  70. varargs = None
  71. if co.co_flags & inspect.CO_VARARGS:
  72. varargs = co.co_varnames[nargs]
  73. nargs = nargs + 1
  74. varkw = None
  75. if co.co_flags & inspect.CO_VARKEYWORDS:
  76. varkw = co.co_varnames[nargs]
  77. return FullArgSpec(
  78. args,
  79. varargs,
  80. varkw,
  81. func.__defaults__,
  82. kwonlyargs,
  83. func.__kwdefaults__ if py3k else None,
  84. func.__annotations__ if py3k else {},
  85. )
  86. if py38:
  87. from importlib import metadata as importlib_metadata
  88. else:
  89. import importlib_metadata # noqa
  90. def importlib_metadata_get(group):
  91. ep = importlib_metadata.entry_points()
  92. if hasattr(ep, "select"):
  93. return ep.select(group=group)
  94. else:
  95. return ep.get(group, ())
  96. if py3k:
  97. import base64
  98. import builtins
  99. import configparser
  100. import itertools
  101. import pickle
  102. from functools import reduce
  103. from io import BytesIO as byte_buffer
  104. from io import StringIO
  105. from itertools import zip_longest
  106. from time import perf_counter
  107. from urllib.parse import (
  108. quote_plus,
  109. unquote_plus,
  110. parse_qsl,
  111. quote,
  112. unquote,
  113. )
  114. string_types = (str,)
  115. binary_types = (bytes,)
  116. binary_type = bytes
  117. text_type = str
  118. int_types = (int,)
  119. iterbytes = iter
  120. long_type = int
  121. itertools_filterfalse = itertools.filterfalse
  122. itertools_filter = filter
  123. itertools_imap = map
  124. exec_ = getattr(builtins, "exec")
  125. import_ = getattr(builtins, "__import__")
  126. print_ = getattr(builtins, "print")
  127. def b(s):
  128. return s.encode("latin-1")
  129. def b64decode(x):
  130. return base64.b64decode(x.encode("ascii"))
  131. def b64encode(x):
  132. return base64.b64encode(x).decode("ascii")
  133. def decode_backslashreplace(text, encoding):
  134. return text.decode(encoding, errors="backslashreplace")
  135. def cmp(a, b):
  136. return (a > b) - (a < b)
  137. def raise_(
  138. exception, with_traceback=None, replace_context=None, from_=False
  139. ):
  140. r"""implement "raise" with cause support.
  141. :param exception: exception to raise
  142. :param with_traceback: will call exception.with_traceback()
  143. :param replace_context: an as-yet-unsupported feature. This is
  144. an exception object which we are "replacing", e.g., it's our
  145. "cause" but we don't want it printed. Basically just what
  146. ``__suppress_context__`` does but we don't want to suppress
  147. the enclosing context, if any. So for now we make it the
  148. cause.
  149. :param from\_: the cause. this actually sets the cause and doesn't
  150. hope to hide it someday.
  151. """
  152. if with_traceback is not None:
  153. exception = exception.with_traceback(with_traceback)
  154. if from_ is not False:
  155. exception.__cause__ = from_
  156. elif replace_context is not None:
  157. # no good solution here, we would like to have the exception
  158. # have only the context of replace_context.__context__ so that the
  159. # intermediary exception does not change, but we can't figure
  160. # that out.
  161. exception.__cause__ = replace_context
  162. try:
  163. raise exception
  164. finally:
  165. # credit to
  166. # https://cosmicpercolator.com/2016/01/13/exception-leaks-in-python-2-and-3/
  167. # as the __traceback__ object creates a cycle
  168. del exception, replace_context, from_, with_traceback
  169. def u(s):
  170. return s
  171. def ue(s):
  172. return s
  173. from typing import TYPE_CHECKING
  174. # Unused. Kept for backwards compatibility.
  175. callable = callable # noqa
  176. from abc import ABC
  177. def _qualname(fn):
  178. return fn.__qualname__
  179. else:
  180. import base64
  181. import ConfigParser as configparser # noqa
  182. import itertools
  183. from StringIO import StringIO # noqa
  184. from cStringIO import StringIO as byte_buffer # noqa
  185. from itertools import izip_longest as zip_longest # noqa
  186. from time import clock as perf_counter # noqa
  187. from urllib import quote # noqa
  188. from urllib import quote_plus # noqa
  189. from urllib import unquote # noqa
  190. from urllib import unquote_plus # noqa
  191. from urlparse import parse_qsl # noqa
  192. from abc import ABCMeta
  193. class ABC(object):
  194. __metaclass__ = ABCMeta
  195. try:
  196. import cPickle as pickle
  197. except ImportError:
  198. import pickle # noqa
  199. string_types = (basestring,) # noqa
  200. binary_types = (bytes,)
  201. binary_type = str
  202. text_type = unicode # noqa
  203. int_types = int, long # noqa
  204. long_type = long # noqa
  205. callable = callable # noqa
  206. cmp = cmp # noqa
  207. reduce = reduce # noqa
  208. b64encode = base64.b64encode
  209. b64decode = base64.b64decode
  210. itertools_filterfalse = itertools.ifilterfalse
  211. itertools_filter = itertools.ifilter
  212. itertools_imap = itertools.imap
  213. def b(s):
  214. return s
  215. def exec_(func_text, globals_, lcl=None):
  216. if lcl is None:
  217. exec("exec func_text in globals_")
  218. else:
  219. exec("exec func_text in globals_, lcl")
  220. def iterbytes(buf):
  221. return (ord(byte) for byte in buf)
  222. def import_(*args):
  223. if len(args) == 4:
  224. args = args[0:3] + ([str(arg) for arg in args[3]],)
  225. return __import__(*args)
  226. def print_(*args, **kwargs):
  227. fp = kwargs.pop("file", sys.stdout)
  228. if fp is None:
  229. return
  230. for arg in enumerate(args):
  231. if not isinstance(arg, basestring): # noqa
  232. arg = str(arg)
  233. fp.write(arg)
  234. def u(s):
  235. # this differs from what six does, which doesn't support non-ASCII
  236. # strings - we only use u() with
  237. # literal source strings, and all our source files with non-ascii
  238. # in them (all are tests) are utf-8 encoded.
  239. return unicode(s, "utf-8") # noqa
  240. def ue(s):
  241. return unicode(s, "unicode_escape") # noqa
  242. def decode_backslashreplace(text, encoding):
  243. try:
  244. return text.decode(encoding)
  245. except UnicodeDecodeError:
  246. # regular "backslashreplace" for an incompatible encoding raises:
  247. # "TypeError: don't know how to handle UnicodeDecodeError in
  248. # error callback"
  249. return repr(text)[1:-1].decode()
  250. def safe_bytestring(text):
  251. # py2k only
  252. if not isinstance(text, string_types):
  253. return unicode(text).encode( # noqa: F821
  254. "ascii", errors="backslashreplace"
  255. )
  256. elif isinstance(text, unicode): # noqa: F821
  257. return text.encode("ascii", errors="backslashreplace")
  258. else:
  259. return text
  260. exec(
  261. "def raise_(exception, with_traceback=None, replace_context=None, "
  262. "from_=False):\n"
  263. " if with_traceback:\n"
  264. " raise type(exception), exception, with_traceback\n"
  265. " else:\n"
  266. " raise exception\n"
  267. )
  268. TYPE_CHECKING = False
  269. def _qualname(meth):
  270. """return __qualname__ equivalent for a method on a class"""
  271. for cls in meth.im_class.__mro__:
  272. if meth.__name__ in cls.__dict__:
  273. break
  274. else:
  275. return meth.__name__
  276. return "%s.%s" % (cls.__name__, meth.__name__)
  277. if py3k:
  278. def _formatannotation(annotation, base_module=None):
  279. """vendored from python 3.7"""
  280. if getattr(annotation, "__module__", None) == "typing":
  281. return repr(annotation).replace("typing.", "")
  282. if isinstance(annotation, type):
  283. if annotation.__module__ in ("builtins", base_module):
  284. return annotation.__qualname__
  285. return annotation.__module__ + "." + annotation.__qualname__
  286. return repr(annotation)
  287. def inspect_formatargspec(
  288. args,
  289. varargs=None,
  290. varkw=None,
  291. defaults=None,
  292. kwonlyargs=(),
  293. kwonlydefaults={},
  294. annotations={},
  295. formatarg=str,
  296. formatvarargs=lambda name: "*" + name,
  297. formatvarkw=lambda name: "**" + name,
  298. formatvalue=lambda value: "=" + repr(value),
  299. formatreturns=lambda text: " -> " + text,
  300. formatannotation=_formatannotation,
  301. ):
  302. """Copy formatargspec from python 3.7 standard library.
  303. Python 3 has deprecated formatargspec and requested that Signature
  304. be used instead, however this requires a full reimplementation
  305. of formatargspec() in terms of creating Parameter objects and such.
  306. Instead of introducing all the object-creation overhead and having
  307. to reinvent from scratch, just copy their compatibility routine.
  308. Ultimately we would need to rewrite our "decorator" routine completely
  309. which is not really worth it right now, until all Python 2.x support
  310. is dropped.
  311. """
  312. def formatargandannotation(arg):
  313. result = formatarg(arg)
  314. if arg in annotations:
  315. result += ": " + formatannotation(annotations[arg])
  316. return result
  317. specs = []
  318. if defaults:
  319. firstdefault = len(args) - len(defaults)
  320. for i, arg in enumerate(args):
  321. spec = formatargandannotation(arg)
  322. if defaults and i >= firstdefault:
  323. spec = spec + formatvalue(defaults[i - firstdefault])
  324. specs.append(spec)
  325. if varargs is not None:
  326. specs.append(formatvarargs(formatargandannotation(varargs)))
  327. else:
  328. if kwonlyargs:
  329. specs.append("*")
  330. if kwonlyargs:
  331. for kwonlyarg in kwonlyargs:
  332. spec = formatargandannotation(kwonlyarg)
  333. if kwonlydefaults and kwonlyarg in kwonlydefaults:
  334. spec += formatvalue(kwonlydefaults[kwonlyarg])
  335. specs.append(spec)
  336. if varkw is not None:
  337. specs.append(formatvarkw(formatargandannotation(varkw)))
  338. result = "(" + ", ".join(specs) + ")"
  339. if "return" in annotations:
  340. result += formatreturns(formatannotation(annotations["return"]))
  341. return result
  342. else:
  343. from inspect import formatargspec as _inspect_formatargspec
  344. def inspect_formatargspec(*spec, **kw):
  345. # convert for a potential FullArgSpec from compat.getfullargspec()
  346. return _inspect_formatargspec(*spec[0:4], **kw) # noqa
  347. # Fix deprecation of accessing ABCs straight from collections module
  348. # (which will stop working in 3.8).
  349. if py3k:
  350. import collections.abc as collections_abc
  351. else:
  352. import collections as collections_abc # noqa
  353. if py37:
  354. import dataclasses
  355. def dataclass_fields(cls):
  356. """Return a sequence of all dataclasses.Field objects associated
  357. with a class."""
  358. if dataclasses.is_dataclass(cls):
  359. return dataclasses.fields(cls)
  360. else:
  361. return []
  362. def local_dataclass_fields(cls):
  363. """Return a sequence of all dataclasses.Field objects associated with
  364. a class, excluding those that originate from a superclass."""
  365. if dataclasses.is_dataclass(cls):
  366. super_fields = set()
  367. for sup in cls.__bases__:
  368. super_fields.update(dataclass_fields(sup))
  369. return [
  370. f for f in dataclasses.fields(cls) if f not in super_fields
  371. ]
  372. else:
  373. return []
  374. else:
  375. def dataclass_fields(cls):
  376. return []
  377. def local_dataclass_fields(cls):
  378. return []
  379. def raise_from_cause(exception, exc_info=None):
  380. r"""legacy. use raise\_()"""
  381. if exc_info is None:
  382. exc_info = sys.exc_info()
  383. exc_type, exc_value, exc_tb = exc_info
  384. cause = exc_value if exc_value is not exception else None
  385. reraise(type(exception), exception, tb=exc_tb, cause=cause)
  386. def reraise(tp, value, tb=None, cause=None):
  387. r"""legacy. use raise\_()"""
  388. raise_(value, with_traceback=tb, from_=cause)
  389. def with_metaclass(meta, *bases, **kw):
  390. """Create a base class with a metaclass.
  391. Drops the middle class upon creation.
  392. Source: http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/
  393. """
  394. class metaclass(meta):
  395. __call__ = type.__call__
  396. __init__ = type.__init__
  397. def __new__(cls, name, this_bases, d):
  398. if this_bases is None:
  399. cls = type.__new__(cls, name, (), d)
  400. else:
  401. cls = meta(name, bases, d)
  402. if hasattr(cls, "__init_subclass__") and hasattr(
  403. cls.__init_subclass__, "__func__"
  404. ):
  405. cls.__init_subclass__.__func__(cls, **kw)
  406. return cls
  407. return metaclass("temporary_class", None, {})
  408. if py3k:
  409. from datetime import timezone
  410. else:
  411. from datetime import datetime
  412. from datetime import timedelta
  413. from datetime import tzinfo
  414. class timezone(tzinfo):
  415. """Minimal port of python 3 timezone object"""
  416. __slots__ = "_offset"
  417. def __init__(self, offset):
  418. if not isinstance(offset, timedelta):
  419. raise TypeError("offset must be a timedelta")
  420. if not self._minoffset <= offset <= self._maxoffset:
  421. raise ValueError(
  422. "offset must be a timedelta "
  423. "strictly between -timedelta(hours=24) and "
  424. "timedelta(hours=24)."
  425. )
  426. self._offset = offset
  427. def __eq__(self, other):
  428. if type(other) != timezone:
  429. return False
  430. return self._offset == other._offset
  431. def __hash__(self):
  432. return hash(self._offset)
  433. def __repr__(self):
  434. return "sqlalchemy.util.%s(%r)" % (
  435. self.__class__.__name__,
  436. self._offset,
  437. )
  438. def __str__(self):
  439. return self.tzname(None)
  440. def utcoffset(self, dt):
  441. return self._offset
  442. def tzname(self, dt):
  443. return self._name_from_offset(self._offset)
  444. def dst(self, dt):
  445. return None
  446. def fromutc(self, dt):
  447. if isinstance(dt, datetime):
  448. if dt.tzinfo is not self:
  449. raise ValueError("fromutc: dt.tzinfo " "is not self")
  450. return dt + self._offset
  451. raise TypeError(
  452. "fromutc() argument must be a datetime instance" " or None"
  453. )
  454. @staticmethod
  455. def _timedelta_to_microseconds(timedelta):
  456. """backport of timedelta._to_microseconds()"""
  457. return (
  458. timedelta.days * (24 * 3600) + timedelta.seconds
  459. ) * 1000000 + timedelta.microseconds
  460. @staticmethod
  461. def _divmod_timedeltas(a, b):
  462. """backport of timedelta.__divmod__"""
  463. q, r = divmod(
  464. timezone._timedelta_to_microseconds(a),
  465. timezone._timedelta_to_microseconds(b),
  466. )
  467. return q, timedelta(0, 0, r)
  468. @staticmethod
  469. def _name_from_offset(delta):
  470. if not delta:
  471. return "UTC"
  472. if delta < timedelta(0):
  473. sign = "-"
  474. delta = -delta
  475. else:
  476. sign = "+"
  477. hours, rest = timezone._divmod_timedeltas(
  478. delta, timedelta(hours=1)
  479. )
  480. minutes, rest = timezone._divmod_timedeltas(
  481. rest, timedelta(minutes=1)
  482. )
  483. result = "UTC%s%02d:%02d" % (sign, hours, minutes)
  484. if rest.seconds:
  485. result += ":%02d" % (rest.seconds,)
  486. if rest.microseconds:
  487. result += ".%06d" % (rest.microseconds,)
  488. return result
  489. _maxoffset = timedelta(hours=23, minutes=59)
  490. _minoffset = -_maxoffset
  491. timezone.utc = timezone(timedelta(0))