compat.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. # util/compat.py
  2. # Copyright (C) 2005-2022 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: https://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. py39 = sys.version_info >= (3, 9)
  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. kwonlydefaults = kwonlydefaults or {}
  313. annotations = annotations or {}
  314. def formatargandannotation(arg):
  315. result = formatarg(arg)
  316. if arg in annotations:
  317. result += ": " + formatannotation(annotations[arg])
  318. return result
  319. specs = []
  320. if defaults:
  321. firstdefault = len(args) - len(defaults)
  322. for i, arg in enumerate(args):
  323. spec = formatargandannotation(arg)
  324. if defaults and i >= firstdefault:
  325. spec = spec + formatvalue(defaults[i - firstdefault])
  326. specs.append(spec)
  327. if varargs is not None:
  328. specs.append(formatvarargs(formatargandannotation(varargs)))
  329. else:
  330. if kwonlyargs:
  331. specs.append("*")
  332. if kwonlyargs:
  333. for kwonlyarg in kwonlyargs:
  334. spec = formatargandannotation(kwonlyarg)
  335. if kwonlydefaults and kwonlyarg in kwonlydefaults:
  336. spec += formatvalue(kwonlydefaults[kwonlyarg])
  337. specs.append(spec)
  338. if varkw is not None:
  339. specs.append(formatvarkw(formatargandannotation(varkw)))
  340. result = "(" + ", ".join(specs) + ")"
  341. if "return" in annotations:
  342. result += formatreturns(formatannotation(annotations["return"]))
  343. return result
  344. else:
  345. from inspect import formatargspec as _inspect_formatargspec
  346. def inspect_formatargspec(*spec, **kw):
  347. # convert for a potential FullArgSpec from compat.getfullargspec()
  348. return _inspect_formatargspec(*spec[0:4], **kw) # noqa
  349. # Fix deprecation of accessing ABCs straight from collections module
  350. # (which will stop working in 3.8).
  351. if py3k:
  352. import collections.abc as collections_abc
  353. else:
  354. import collections as collections_abc # noqa
  355. if py37:
  356. import dataclasses
  357. def dataclass_fields(cls):
  358. """Return a sequence of all dataclasses.Field objects associated
  359. with a class."""
  360. if dataclasses.is_dataclass(cls):
  361. return dataclasses.fields(cls)
  362. else:
  363. return []
  364. def local_dataclass_fields(cls):
  365. """Return a sequence of all dataclasses.Field objects associated with
  366. a class, excluding those that originate from a superclass."""
  367. if dataclasses.is_dataclass(cls):
  368. super_fields = set()
  369. for sup in cls.__bases__:
  370. super_fields.update(dataclass_fields(sup))
  371. return [
  372. f for f in dataclasses.fields(cls) if f not in super_fields
  373. ]
  374. else:
  375. return []
  376. else:
  377. def dataclass_fields(cls):
  378. return []
  379. def local_dataclass_fields(cls):
  380. return []
  381. def raise_from_cause(exception, exc_info=None):
  382. r"""legacy. use raise\_()"""
  383. if exc_info is None:
  384. exc_info = sys.exc_info()
  385. exc_type, exc_value, exc_tb = exc_info
  386. cause = exc_value if exc_value is not exception else None
  387. reraise(type(exception), exception, tb=exc_tb, cause=cause)
  388. def reraise(tp, value, tb=None, cause=None):
  389. r"""legacy. use raise\_()"""
  390. raise_(value, with_traceback=tb, from_=cause)
  391. def with_metaclass(meta, *bases, **kw):
  392. """Create a base class with a metaclass.
  393. Drops the middle class upon creation.
  394. Source: https://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/
  395. """
  396. class metaclass(meta):
  397. __call__ = type.__call__
  398. __init__ = type.__init__
  399. def __new__(cls, name, this_bases, d):
  400. if this_bases is None:
  401. cls = type.__new__(cls, name, (), d)
  402. else:
  403. cls = meta(name, bases, d)
  404. if hasattr(cls, "__init_subclass__") and hasattr(
  405. cls.__init_subclass__, "__func__"
  406. ):
  407. cls.__init_subclass__.__func__(cls, **kw)
  408. return cls
  409. return metaclass("temporary_class", None, {})
  410. if py3k:
  411. from datetime import timezone
  412. else:
  413. from datetime import datetime
  414. from datetime import timedelta
  415. from datetime import tzinfo
  416. class timezone(tzinfo):
  417. """Minimal port of python 3 timezone object"""
  418. __slots__ = "_offset"
  419. def __init__(self, offset):
  420. if not isinstance(offset, timedelta):
  421. raise TypeError("offset must be a timedelta")
  422. if not self._minoffset <= offset <= self._maxoffset:
  423. raise ValueError(
  424. "offset must be a timedelta "
  425. "strictly between -timedelta(hours=24) and "
  426. "timedelta(hours=24)."
  427. )
  428. self._offset = offset
  429. def __eq__(self, other):
  430. if type(other) != timezone:
  431. return False
  432. return self._offset == other._offset
  433. def __hash__(self):
  434. return hash(self._offset)
  435. def __repr__(self):
  436. return "sqlalchemy.util.%s(%r)" % (
  437. self.__class__.__name__,
  438. self._offset,
  439. )
  440. def __str__(self):
  441. return self.tzname(None)
  442. def utcoffset(self, dt):
  443. return self._offset
  444. def tzname(self, dt):
  445. return self._name_from_offset(self._offset)
  446. def dst(self, dt):
  447. return None
  448. def fromutc(self, dt):
  449. if isinstance(dt, datetime):
  450. if dt.tzinfo is not self:
  451. raise ValueError("fromutc: dt.tzinfo " "is not self")
  452. return dt + self._offset
  453. raise TypeError(
  454. "fromutc() argument must be a datetime instance" " or None"
  455. )
  456. @staticmethod
  457. def _timedelta_to_microseconds(timedelta):
  458. """backport of timedelta._to_microseconds()"""
  459. return (
  460. timedelta.days * (24 * 3600) + timedelta.seconds
  461. ) * 1000000 + timedelta.microseconds
  462. @staticmethod
  463. def _divmod_timedeltas(a, b):
  464. """backport of timedelta.__divmod__"""
  465. q, r = divmod(
  466. timezone._timedelta_to_microseconds(a),
  467. timezone._timedelta_to_microseconds(b),
  468. )
  469. return q, timedelta(0, 0, r)
  470. @staticmethod
  471. def _name_from_offset(delta):
  472. if not delta:
  473. return "UTC"
  474. if delta < timedelta(0):
  475. sign = "-"
  476. delta = -delta
  477. else:
  478. sign = "+"
  479. hours, rest = timezone._divmod_timedeltas(
  480. delta, timedelta(hours=1)
  481. )
  482. minutes, rest = timezone._divmod_timedeltas(
  483. rest, timedelta(minutes=1)
  484. )
  485. result = "UTC%s%02d:%02d" % (sign, hours, minutes)
  486. if rest.seconds:
  487. result += ":%02d" % (rest.seconds,)
  488. if rest.microseconds:
  489. result += ".%06d" % (rest.microseconds,)
  490. return result
  491. _maxoffset = timedelta(hours=23, minutes=59)
  492. _minoffset = -_maxoffset
  493. timezone.utc = timezone(timedelta(0))