m2m模型翻译
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.

1138 lines
40 KiB

6 months ago
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2013-2017 Vinay Sajip.
  4. # Licensed to the Python Software Foundation under a contributor agreement.
  5. # See LICENSE.txt and CONTRIBUTORS.txt.
  6. #
  7. from __future__ import absolute_import
  8. import os
  9. import re
  10. import shutil
  11. import sys
  12. try:
  13. import ssl
  14. except ImportError: # pragma: no cover
  15. ssl = None
  16. if sys.version_info[0] < 3: # pragma: no cover
  17. from StringIO import StringIO
  18. string_types = basestring,
  19. text_type = unicode
  20. from types import FileType as file_type
  21. import __builtin__ as builtins
  22. import ConfigParser as configparser
  23. from urlparse import urlparse, urlunparse, urljoin, urlsplit, urlunsplit
  24. from urllib import (urlretrieve, quote as _quote, unquote, url2pathname,
  25. pathname2url, ContentTooShortError, splittype)
  26. def quote(s):
  27. if isinstance(s, unicode):
  28. s = s.encode('utf-8')
  29. return _quote(s)
  30. import urllib2
  31. from urllib2 import (Request, urlopen, URLError, HTTPError,
  32. HTTPBasicAuthHandler, HTTPPasswordMgr, HTTPHandler,
  33. HTTPRedirectHandler, build_opener)
  34. if ssl:
  35. from urllib2 import HTTPSHandler
  36. import httplib
  37. import xmlrpclib
  38. import Queue as queue
  39. from HTMLParser import HTMLParser
  40. import htmlentitydefs
  41. raw_input = raw_input
  42. from itertools import ifilter as filter
  43. from itertools import ifilterfalse as filterfalse
  44. # Leaving this around for now, in case it needs resurrecting in some way
  45. # _userprog = None
  46. # def splituser(host):
  47. # """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
  48. # global _userprog
  49. # if _userprog is None:
  50. # import re
  51. # _userprog = re.compile('^(.*)@(.*)$')
  52. # match = _userprog.match(host)
  53. # if match: return match.group(1, 2)
  54. # return None, host
  55. else: # pragma: no cover
  56. from io import StringIO
  57. string_types = str,
  58. text_type = str
  59. from io import TextIOWrapper as file_type
  60. import builtins
  61. import configparser
  62. from urllib.parse import (urlparse, urlunparse, urljoin, quote, unquote,
  63. urlsplit, urlunsplit, splittype)
  64. from urllib.request import (urlopen, urlretrieve, Request, url2pathname,
  65. pathname2url, HTTPBasicAuthHandler,
  66. HTTPPasswordMgr, HTTPHandler,
  67. HTTPRedirectHandler, build_opener)
  68. if ssl:
  69. from urllib.request import HTTPSHandler
  70. from urllib.error import HTTPError, URLError, ContentTooShortError
  71. import http.client as httplib
  72. import urllib.request as urllib2
  73. import xmlrpc.client as xmlrpclib
  74. import queue
  75. from html.parser import HTMLParser
  76. import html.entities as htmlentitydefs
  77. raw_input = input
  78. from itertools import filterfalse
  79. filter = filter
  80. try:
  81. from ssl import match_hostname, CertificateError
  82. except ImportError: # pragma: no cover
  83. class CertificateError(ValueError):
  84. pass
  85. def _dnsname_match(dn, hostname, max_wildcards=1):
  86. """Matching according to RFC 6125, section 6.4.3
  87. http://tools.ietf.org/html/rfc6125#section-6.4.3
  88. """
  89. pats = []
  90. if not dn:
  91. return False
  92. parts = dn.split('.')
  93. leftmost, remainder = parts[0], parts[1:]
  94. wildcards = leftmost.count('*')
  95. if wildcards > max_wildcards:
  96. # Issue #17980: avoid denials of service by refusing more
  97. # than one wildcard per fragment. A survey of established
  98. # policy among SSL implementations showed it to be a
  99. # reasonable choice.
  100. raise CertificateError(
  101. "too many wildcards in certificate DNS name: " + repr(dn))
  102. # speed up common case w/o wildcards
  103. if not wildcards:
  104. return dn.lower() == hostname.lower()
  105. # RFC 6125, section 6.4.3, subitem 1.
  106. # The client SHOULD NOT attempt to match a presented identifier in which
  107. # the wildcard character comprises a label other than the left-most label.
  108. if leftmost == '*':
  109. # When '*' is a fragment by itself, it matches a non-empty dotless
  110. # fragment.
  111. pats.append('[^.]+')
  112. elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
  113. # RFC 6125, section 6.4.3, subitem 3.
  114. # The client SHOULD NOT attempt to match a presented identifier
  115. # where the wildcard character is embedded within an A-label or
  116. # U-label of an internationalized domain name.
  117. pats.append(re.escape(leftmost))
  118. else:
  119. # Otherwise, '*' matches any dotless string, e.g. www*
  120. pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
  121. # add the remaining fragments, ignore any wildcards
  122. for frag in remainder:
  123. pats.append(re.escape(frag))
  124. pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
  125. return pat.match(hostname)
  126. def match_hostname(cert, hostname):
  127. """Verify that *cert* (in decoded format as returned by
  128. SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
  129. rules are followed, but IP addresses are not accepted for *hostname*.
  130. CertificateError is raised on failure. On success, the function
  131. returns nothing.
  132. """
  133. if not cert:
  134. raise ValueError("empty or no certificate, match_hostname needs a "
  135. "SSL socket or SSL context with either "
  136. "CERT_OPTIONAL or CERT_REQUIRED")
  137. dnsnames = []
  138. san = cert.get('subjectAltName', ())
  139. for key, value in san:
  140. if key == 'DNS':
  141. if _dnsname_match(value, hostname):
  142. return
  143. dnsnames.append(value)
  144. if not dnsnames:
  145. # The subject is only checked when there is no dNSName entry
  146. # in subjectAltName
  147. for sub in cert.get('subject', ()):
  148. for key, value in sub:
  149. # XXX according to RFC 2818, the most specific Common Name
  150. # must be used.
  151. if key == 'commonName':
  152. if _dnsname_match(value, hostname):
  153. return
  154. dnsnames.append(value)
  155. if len(dnsnames) > 1:
  156. raise CertificateError("hostname %r "
  157. "doesn't match either of %s" %
  158. (hostname, ', '.join(map(repr, dnsnames))))
  159. elif len(dnsnames) == 1:
  160. raise CertificateError("hostname %r "
  161. "doesn't match %r" %
  162. (hostname, dnsnames[0]))
  163. else:
  164. raise CertificateError("no appropriate commonName or "
  165. "subjectAltName fields were found")
  166. try:
  167. from types import SimpleNamespace as Container
  168. except ImportError: # pragma: no cover
  169. class Container(object):
  170. """
  171. A generic container for when multiple values need to be returned
  172. """
  173. def __init__(self, **kwargs):
  174. self.__dict__.update(kwargs)
  175. try:
  176. from shutil import which
  177. except ImportError: # pragma: no cover
  178. # Implementation from Python 3.3
  179. def which(cmd, mode=os.F_OK | os.X_OK, path=None):
  180. """Given a command, mode, and a PATH string, return the path which
  181. conforms to the given mode on the PATH, or None if there is no such
  182. file.
  183. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
  184. of os.environ.get("PATH"), or can be overridden with a custom search
  185. path.
  186. """
  187. # Check that a given file can be accessed with the correct mode.
  188. # Additionally check that `file` is not a directory, as on Windows
  189. # directories pass the os.access check.
  190. def _access_check(fn, mode):
  191. return (os.path.exists(fn) and os.access(fn, mode)
  192. and not os.path.isdir(fn))
  193. # If we're given a path with a directory part, look it up directly rather
  194. # than referring to PATH directories. This includes checking relative to the
  195. # current directory, e.g. ./script
  196. if os.path.dirname(cmd):
  197. if _access_check(cmd, mode):
  198. return cmd
  199. return None
  200. if path is None:
  201. path = os.environ.get("PATH", os.defpath)
  202. if not path:
  203. return None
  204. path = path.split(os.pathsep)
  205. if sys.platform == "win32":
  206. # The current directory takes precedence on Windows.
  207. if os.curdir not in path:
  208. path.insert(0, os.curdir)
  209. # PATHEXT is necessary to check on Windows.
  210. pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
  211. # See if the given file matches any of the expected path extensions.
  212. # This will allow us to short circuit when given "python.exe".
  213. # If it does match, only test that one, otherwise we have to try
  214. # others.
  215. if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
  216. files = [cmd]
  217. else:
  218. files = [cmd + ext for ext in pathext]
  219. else:
  220. # On other platforms you don't have things like PATHEXT to tell you
  221. # what file suffixes are executable, so just pass on cmd as-is.
  222. files = [cmd]
  223. seen = set()
  224. for dir in path:
  225. normdir = os.path.normcase(dir)
  226. if normdir not in seen:
  227. seen.add(normdir)
  228. for thefile in files:
  229. name = os.path.join(dir, thefile)
  230. if _access_check(name, mode):
  231. return name
  232. return None
  233. # ZipFile is a context manager in 2.7, but not in 2.6
  234. from zipfile import ZipFile as BaseZipFile
  235. if hasattr(BaseZipFile, '__enter__'): # pragma: no cover
  236. ZipFile = BaseZipFile
  237. else: # pragma: no cover
  238. from zipfile import ZipExtFile as BaseZipExtFile
  239. class ZipExtFile(BaseZipExtFile):
  240. def __init__(self, base):
  241. self.__dict__.update(base.__dict__)
  242. def __enter__(self):
  243. return self
  244. def __exit__(self, *exc_info):
  245. self.close()
  246. # return None, so if an exception occurred, it will propagate
  247. class ZipFile(BaseZipFile):
  248. def __enter__(self):
  249. return self
  250. def __exit__(self, *exc_info):
  251. self.close()
  252. # return None, so if an exception occurred, it will propagate
  253. def open(self, *args, **kwargs):
  254. base = BaseZipFile.open(self, *args, **kwargs)
  255. return ZipExtFile(base)
  256. try:
  257. from platform import python_implementation
  258. except ImportError: # pragma: no cover
  259. def python_implementation():
  260. """Return a string identifying the Python implementation."""
  261. if 'PyPy' in sys.version:
  262. return 'PyPy'
  263. if os.name == 'java':
  264. return 'Jython'
  265. if sys.version.startswith('IronPython'):
  266. return 'IronPython'
  267. return 'CPython'
  268. import sysconfig
  269. try:
  270. callable = callable
  271. except NameError: # pragma: no cover
  272. from collections.abc import Callable
  273. def callable(obj):
  274. return isinstance(obj, Callable)
  275. try:
  276. fsencode = os.fsencode
  277. fsdecode = os.fsdecode
  278. except AttributeError: # pragma: no cover
  279. # Issue #99: on some systems (e.g. containerised),
  280. # sys.getfilesystemencoding() returns None, and we need a real value,
  281. # so fall back to utf-8. From the CPython 2.7 docs relating to Unix and
  282. # sys.getfilesystemencoding(): the return value is "the user’s preference
  283. # according to the result of nl_langinfo(CODESET), or None if the
  284. # nl_langinfo(CODESET) failed."
  285. _fsencoding = sys.getfilesystemencoding() or 'utf-8'
  286. if _fsencoding == 'mbcs':
  287. _fserrors = 'strict'
  288. else:
  289. _fserrors = 'surrogateescape'
  290. def fsencode(filename):
  291. if isinstance(filename, bytes):
  292. return filename
  293. elif isinstance(filename, text_type):
  294. return filename.encode(_fsencoding, _fserrors)
  295. else:
  296. raise TypeError("expect bytes or str, not %s" %
  297. type(filename).__name__)
  298. def fsdecode(filename):
  299. if isinstance(filename, text_type):
  300. return filename
  301. elif isinstance(filename, bytes):
  302. return filename.decode(_fsencoding, _fserrors)
  303. else:
  304. raise TypeError("expect bytes or str, not %s" %
  305. type(filename).__name__)
  306. try:
  307. from tokenize import detect_encoding
  308. except ImportError: # pragma: no cover
  309. from codecs import BOM_UTF8, lookup
  310. cookie_re = re.compile(r"coding[:=]\s*([-\w.]+)")
  311. def _get_normal_name(orig_enc):
  312. """Imitates get_normal_name in tokenizer.c."""
  313. # Only care about the first 12 characters.
  314. enc = orig_enc[:12].lower().replace("_", "-")
  315. if enc == "utf-8" or enc.startswith("utf-8-"):
  316. return "utf-8"
  317. if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
  318. enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
  319. return "iso-8859-1"
  320. return orig_enc
  321. def detect_encoding(readline):
  322. """
  323. The detect_encoding() function is used to detect the encoding that should
  324. be used to decode a Python source file. It requires one argument, readline,
  325. in the same way as the tokenize() generator.
  326. It will call readline a maximum of twice, and return the encoding used
  327. (as a string) and a list of any lines (left as bytes) it has read in.
  328. It detects the encoding from the presence of a utf-8 bom or an encoding
  329. cookie as specified in pep-0263. If both a bom and a cookie are present,
  330. but disagree, a SyntaxError will be raised. If the encoding cookie is an
  331. invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
  332. 'utf-8-sig' is returned.
  333. If no encoding is specified, then the default of 'utf-8' will be returned.
  334. """
  335. try:
  336. filename = readline.__self__.name
  337. except AttributeError:
  338. filename = None
  339. bom_found = False
  340. encoding = None
  341. default = 'utf-8'
  342. def read_or_stop():
  343. try:
  344. return readline()
  345. except StopIteration:
  346. return b''
  347. def find_cookie(line):
  348. try:
  349. # Decode as UTF-8. Either the line is an encoding declaration,
  350. # in which case it should be pure ASCII, or it must be UTF-8
  351. # per default encoding.
  352. line_string = line.decode('utf-8')
  353. except UnicodeDecodeError:
  354. msg = "invalid or missing encoding declaration"
  355. if filename is not None:
  356. msg = '{} for {!r}'.format(msg, filename)
  357. raise SyntaxError(msg)
  358. matches = cookie_re.findall(line_string)
  359. if not matches:
  360. return None
  361. encoding = _get_normal_name(matches[0])
  362. try:
  363. codec = lookup(encoding)
  364. except LookupError:
  365. # This behaviour mimics the Python interpreter
  366. if filename is None:
  367. msg = "unknown encoding: " + encoding
  368. else:
  369. msg = "unknown encoding for {!r}: {}".format(
  370. filename, encoding)
  371. raise SyntaxError(msg)
  372. if bom_found:
  373. if codec.name != 'utf-8':
  374. # This behaviour mimics the Python interpreter
  375. if filename is None:
  376. msg = 'encoding problem: utf-8'
  377. else:
  378. msg = 'encoding problem for {!r}: utf-8'.format(
  379. filename)
  380. raise SyntaxError(msg)
  381. encoding += '-sig'
  382. return encoding
  383. first = read_or_stop()
  384. if first.startswith(BOM_UTF8):
  385. bom_found = True
  386. first = first[3:]
  387. default = 'utf-8-sig'
  388. if not first:
  389. return default, []
  390. encoding = find_cookie(first)
  391. if encoding:
  392. return encoding, [first]
  393. second = read_or_stop()
  394. if not second:
  395. return default, [first]
  396. encoding = find_cookie(second)
  397. if encoding:
  398. return encoding, [first, second]
  399. return default, [first, second]
  400. # For converting & <-> &amp; etc.
  401. try:
  402. from html import escape
  403. except ImportError:
  404. from cgi import escape
  405. if sys.version_info[:2] < (3, 4):
  406. unescape = HTMLParser().unescape
  407. else:
  408. from html import unescape
  409. try:
  410. from collections import ChainMap
  411. except ImportError: # pragma: no cover
  412. from collections import MutableMapping
  413. try:
  414. from reprlib import recursive_repr as _recursive_repr
  415. except ImportError:
  416. def _recursive_repr(fillvalue='...'):
  417. '''
  418. Decorator to make a repr function return fillvalue for a recursive
  419. call
  420. '''
  421. def decorating_function(user_function):
  422. repr_running = set()
  423. def wrapper(self):
  424. key = id(self), get_ident()
  425. if key in repr_running:
  426. return fillvalue
  427. repr_running.add(key)
  428. try:
  429. result = user_function(self)
  430. finally:
  431. repr_running.discard(key)
  432. return result
  433. # Can't use functools.wraps() here because of bootstrap issues
  434. wrapper.__module__ = getattr(user_function, '__module__')
  435. wrapper.__doc__ = getattr(user_function, '__doc__')
  436. wrapper.__name__ = getattr(user_function, '__name__')
  437. wrapper.__annotations__ = getattr(user_function,
  438. '__annotations__', {})
  439. return wrapper
  440. return decorating_function
  441. class ChainMap(MutableMapping):
  442. '''
  443. A ChainMap groups multiple dicts (or other mappings) together
  444. to create a single, updateable view.
  445. The underlying mappings are stored in a list. That list is public and can
  446. accessed or updated using the *maps* attribute. There is no other state.
  447. Lookups search the underlying mappings successively until a key is found.
  448. In contrast, writes, updates, and deletions only operate on the first
  449. mapping.
  450. '''
  451. def __init__(self, *maps):
  452. '''Initialize a ChainMap by setting *maps* to the given mappings.
  453. If no mappings are provided, a single empty dictionary is used.
  454. '''
  455. self.maps = list(maps) or [{}] # always at least one map
  456. def __missing__(self, key):
  457. raise KeyError(key)
  458. def __getitem__(self, key):
  459. for mapping in self.maps:
  460. try:
  461. return mapping[
  462. key] # can't use 'key in mapping' with defaultdict
  463. except KeyError:
  464. pass
  465. return self.__missing__(
  466. key) # support subclasses that define __missing__
  467. def get(self, key, default=None):
  468. return self[key] if key in self else default
  469. def __len__(self):
  470. return len(set().union(
  471. *self.maps)) # reuses stored hash values if possible
  472. def __iter__(self):
  473. return iter(set().union(*self.maps))
  474. def __contains__(self, key):
  475. return any(key in m for m in self.maps)
  476. def __bool__(self):
  477. return any(self.maps)
  478. @_recursive_repr()
  479. def __repr__(self):
  480. return '{0.__class__.__name__}({1})'.format(
  481. self, ', '.join(map(repr, self.maps)))
  482. @classmethod
  483. def fromkeys(cls, iterable, *args):
  484. 'Create a ChainMap with a single dict created from the iterable.'
  485. return cls(dict.fromkeys(iterable, *args))
  486. def copy(self):
  487. 'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
  488. return self.__class__(self.maps[0].copy(), *self.maps[1:])
  489. __copy__ = copy
  490. def new_child(self): # like Django's Context.push()
  491. 'New ChainMap with a new dict followed by all previous maps.'
  492. return self.__class__({}, *self.maps)
  493. @property
  494. def parents(self): # like Django's Context.pop()
  495. 'New ChainMap from maps[1:].'
  496. return self.__class__(*self.maps[1:])
  497. def __setitem__(self, key, value):
  498. self.maps[0][key] = value
  499. def __delitem__(self, key):
  500. try:
  501. del self.maps[0][key]
  502. except KeyError:
  503. raise KeyError(
  504. 'Key not found in the first mapping: {!r}'.format(key))
  505. def popitem(self):
  506. 'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.'
  507. try:
  508. return self.maps[0].popitem()
  509. except KeyError:
  510. raise KeyError('No keys found in the first mapping.')
  511. def pop(self, key, *args):
  512. 'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
  513. try:
  514. return self.maps[0].pop(key, *args)
  515. except KeyError:
  516. raise KeyError(
  517. 'Key not found in the first mapping: {!r}'.format(key))
  518. def clear(self):
  519. 'Clear maps[0], leaving maps[1:] intact.'
  520. self.maps[0].clear()
  521. try:
  522. from importlib.util import cache_from_source # Python >= 3.4
  523. except ImportError: # pragma: no cover
  524. def cache_from_source(path, debug_override=None):
  525. assert path.endswith('.py')
  526. if debug_override is None:
  527. debug_override = __debug__
  528. if debug_override:
  529. suffix = 'c'
  530. else:
  531. suffix = 'o'
  532. return path + suffix
  533. try:
  534. from collections import OrderedDict
  535. except ImportError: # pragma: no cover
  536. # {{{ http://code.activestate.com/recipes/576693/ (r9)
  537. # Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
  538. # Passes Python2.7's test suite and incorporates all the latest updates.
  539. try:
  540. from thread import get_ident as _get_ident
  541. except ImportError:
  542. from dummy_thread import get_ident as _get_ident
  543. try:
  544. from _abcoll import KeysView, ValuesView, ItemsView
  545. except ImportError:
  546. pass
  547. class OrderedDict(dict):
  548. 'Dictionary that remembers insertion order'
  549. # An inherited dict maps keys to values.
  550. # The inherited dict provides __getitem__, __len__, __contains__, and get.
  551. # The remaining methods are order-aware.
  552. # Big-O running times for all methods are the same as for regular dictionaries.
  553. # The internal self.__map dictionary maps keys to links in a doubly linked list.
  554. # The circular doubly linked list starts and ends with a sentinel element.
  555. # The sentinel element never gets deleted (this simplifies the algorithm).
  556. # Each link is stored as a list of length three: [PREV, NEXT, KEY].
  557. def __init__(self, *args, **kwds):
  558. '''Initialize an ordered dictionary. Signature is the same as for
  559. regular dictionaries, but keyword arguments are not recommended
  560. because their insertion order is arbitrary.
  561. '''
  562. if len(args) > 1:
  563. raise TypeError('expected at most 1 arguments, got %d' %
  564. len(args))
  565. try:
  566. self.__root
  567. except AttributeError:
  568. self.__root = root = [] # sentinel node
  569. root[:] = [root, root, None]
  570. self.__map = {}
  571. self.__update(*args, **kwds)
  572. def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
  573. 'od.__setitem__(i, y) <==> od[i]=y'
  574. # Setting a new item creates a new link which goes at the end of the linked
  575. # list, and the inherited dictionary is updated with the new key/value pair.
  576. if key not in self:
  577. root = self.__root
  578. last = root[0]
  579. last[1] = root[0] = self.__map[key] = [last, root, key]
  580. dict_setitem(self, key, value)
  581. def __delitem__(self, key, dict_delitem=dict.__delitem__):
  582. 'od.__delitem__(y) <==> del od[y]'
  583. # Deleting an existing item uses self.__map to find the link which is
  584. # then removed by updating the links in the predecessor and successor nodes.
  585. dict_delitem(self, key)
  586. link_prev, link_next, key = self.__map.pop(key)
  587. link_prev[1] = link_next
  588. link_next[0] = link_prev
  589. def __iter__(self):
  590. 'od.__iter__() <==> iter(od)'
  591. root = self.__root
  592. curr = root[1]
  593. while curr is not root:
  594. yield curr[2]
  595. curr = curr[1]
  596. def __reversed__(self):
  597. 'od.__reversed__() <==> reversed(od)'
  598. root = self.__root
  599. curr = root[0]
  600. while curr is not root:
  601. yield curr[2]
  602. curr = curr[0]
  603. def clear(self):
  604. 'od.clear() -> None. Remove all items from od.'
  605. try:
  606. for node in self.__map.itervalues():
  607. del node[:]
  608. root = self.__root
  609. root[:] = [root, root, None]
  610. self.__map.clear()
  611. except AttributeError:
  612. pass
  613. dict.clear(self)
  614. def popitem(self, last=True):
  615. '''od.popitem() -> (k, v), return and remove a (key, value) pair.
  616. Pairs are returned in LIFO order if last is true or FIFO order if false.
  617. '''
  618. if not self:
  619. raise KeyError('dictionary is empty')
  620. root = self.__root
  621. if last:
  622. link = root[0]
  623. link_prev = link[0]
  624. link_prev[1] = root
  625. root[0] = link_prev
  626. else:
  627. link = root[1]
  628. link_next = link[1]
  629. root[1] = link_next
  630. link_next[0] = root
  631. key = link[2]
  632. del self.__map[key]
  633. value = dict.pop(self, key)
  634. return key, value
  635. # -- the following methods do not depend on the internal structure --
  636. def keys(self):
  637. 'od.keys() -> list of keys in od'
  638. return list(self)
  639. def values(self):
  640. 'od.values() -> list of values in od'
  641. return [self[key] for key in self]
  642. def items(self):
  643. 'od.items() -> list of (key, value) pairs in od'
  644. return [(key, self[key]) for key in self]
  645. def iterkeys(self):
  646. 'od.iterkeys() -> an iterator over the keys in od'
  647. return iter(self)
  648. def itervalues(self):
  649. 'od.itervalues -> an iterator over the values in od'
  650. for k in self:
  651. yield self[k]
  652. def iteritems(self):
  653. 'od.iteritems -> an iterator over the (key, value) items in od'
  654. for k in self:
  655. yield (k, self[k])
  656. def update(*args, **kwds):
  657. '''od.update(E, **F) -> None. Update od from dict/iterable E and F.
  658. If E is a dict instance, does: for k in E: od[k] = E[k]
  659. If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
  660. Or if E is an iterable of items, does: for k, v in E: od[k] = v
  661. In either case, this is followed by: for k, v in F.items(): od[k] = v
  662. '''
  663. if len(args) > 2:
  664. raise TypeError('update() takes at most 2 positional '
  665. 'arguments (%d given)' % (len(args), ))
  666. elif not args:
  667. raise TypeError('update() takes at least 1 argument (0 given)')
  668. self = args[0]
  669. # Make progressively weaker assumptions about "other"
  670. other = ()
  671. if len(args) == 2:
  672. other = args[1]
  673. if isinstance(other, dict):
  674. for key in other:
  675. self[key] = other[key]
  676. elif hasattr(other, 'keys'):
  677. for key in other.keys():
  678. self[key] = other[key]
  679. else:
  680. for key, value in other:
  681. self[key] = value
  682. for key, value in kwds.items():
  683. self[key] = value
  684. __update = update # let subclasses override update without breaking __init__
  685. __marker = object()
  686. def pop(self, key, default=__marker):
  687. '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  688. If key is not found, d is returned if given, otherwise KeyError is raised.
  689. '''
  690. if key in self:
  691. result = self[key]
  692. del self[key]
  693. return result
  694. if default is self.__marker:
  695. raise KeyError(key)
  696. return default
  697. def setdefault(self, key, default=None):
  698. 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
  699. if key in self:
  700. return self[key]
  701. self[key] = default
  702. return default
  703. def __repr__(self, _repr_running=None):
  704. 'od.__repr__() <==> repr(od)'
  705. if not _repr_running:
  706. _repr_running = {}
  707. call_key = id(self), _get_ident()
  708. if call_key in _repr_running:
  709. return '...'
  710. _repr_running[call_key] = 1
  711. try:
  712. if not self:
  713. return '%s()' % (self.__class__.__name__, )
  714. return '%s(%r)' % (self.__class__.__name__, self.items())
  715. finally:
  716. del _repr_running[call_key]
  717. def __reduce__(self):
  718. 'Return state information for pickling'
  719. items = [[k, self[k]] for k in self]
  720. inst_dict = vars(self).copy()
  721. for k in vars(OrderedDict()):
  722. inst_dict.pop(k, None)
  723. if inst_dict:
  724. return (self.__class__, (items, ), inst_dict)
  725. return self.__class__, (items, )
  726. def copy(self):
  727. 'od.copy() -> a shallow copy of od'
  728. return self.__class__(self)
  729. @classmethod
  730. def fromkeys(cls, iterable, value=None):
  731. '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
  732. and values equal to v (which defaults to None).
  733. '''
  734. d = cls()
  735. for key in iterable:
  736. d[key] = value
  737. return d
  738. def __eq__(self, other):
  739. '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
  740. while comparison to a regular mapping is order-insensitive.
  741. '''
  742. if isinstance(other, OrderedDict):
  743. return len(self) == len(
  744. other) and self.items() == other.items()
  745. return dict.__eq__(self, other)
  746. def __ne__(self, other):
  747. return not self == other
  748. # -- the following methods are only used in Python 2.7 --
  749. def viewkeys(self):
  750. "od.viewkeys() -> a set-like object providing a view on od's keys"
  751. return KeysView(self)
  752. def viewvalues(self):
  753. "od.viewvalues() -> an object providing a view on od's values"
  754. return ValuesView(self)
  755. def viewitems(self):
  756. "od.viewitems() -> a set-like object providing a view on od's items"
  757. return ItemsView(self)
  758. try:
  759. from logging.config import BaseConfigurator, valid_ident
  760. except ImportError: # pragma: no cover
  761. IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)
  762. def valid_ident(s):
  763. m = IDENTIFIER.match(s)
  764. if not m:
  765. raise ValueError('Not a valid Python identifier: %r' % s)
  766. return True
  767. # The ConvertingXXX classes are wrappers around standard Python containers,
  768. # and they serve to convert any suitable values in the container. The
  769. # conversion converts base dicts, lists and tuples to their wrapped
  770. # equivalents, whereas strings which match a conversion format are converted
  771. # appropriately.
  772. #
  773. # Each wrapper should have a configurator attribute holding the actual
  774. # configurator to use for conversion.
  775. class ConvertingDict(dict):
  776. """A converting dictionary wrapper."""
  777. def __getitem__(self, key):
  778. value = dict.__getitem__(self, key)
  779. result = self.configurator.convert(value)
  780. # If the converted value is different, save for next time
  781. if value is not result:
  782. self[key] = result
  783. if type(result) in (ConvertingDict, ConvertingList,
  784. ConvertingTuple):
  785. result.parent = self
  786. result.key = key
  787. return result
  788. def get(self, key, default=None):
  789. value = dict.get(self, key, default)
  790. result = self.configurator.convert(value)
  791. # If the converted value is different, save for next time
  792. if value is not result:
  793. self[key] = result
  794. if type(result) in (ConvertingDict, ConvertingList,
  795. ConvertingTuple):
  796. result.parent = self
  797. result.key = key
  798. return result
  799. def pop(self, key, default=None):
  800. value = dict.pop(self, key, default)
  801. result = self.configurator.convert(value)
  802. if value is not result:
  803. if type(result) in (ConvertingDict, ConvertingList,
  804. ConvertingTuple):
  805. result.parent = self
  806. result.key = key
  807. return result
  808. class ConvertingList(list):
  809. """A converting list wrapper."""
  810. def __getitem__(self, key):
  811. value = list.__getitem__(self, key)
  812. result = self.configurator.convert(value)
  813. # If the converted value is different, save for next time
  814. if value is not result:
  815. self[key] = result
  816. if type(result) in (ConvertingDict, ConvertingList,
  817. ConvertingTuple):
  818. result.parent = self
  819. result.key = key
  820. return result
  821. def pop(self, idx=-1):
  822. value = list.pop(self, idx)
  823. result = self.configurator.convert(value)
  824. if value is not result:
  825. if type(result) in (ConvertingDict, ConvertingList,
  826. ConvertingTuple):
  827. result.parent = self
  828. return result
  829. class ConvertingTuple(tuple):
  830. """A converting tuple wrapper."""
  831. def __getitem__(self, key):
  832. value = tuple.__getitem__(self, key)
  833. result = self.configurator.convert(value)
  834. if value is not result:
  835. if type(result) in (ConvertingDict, ConvertingList,
  836. ConvertingTuple):
  837. result.parent = self
  838. result.key = key
  839. return result
  840. class BaseConfigurator(object):
  841. """
  842. The configurator base class which defines some useful defaults.
  843. """
  844. CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$')
  845. WORD_PATTERN = re.compile(r'^\s*(\w+)\s*')
  846. DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*')
  847. INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*')
  848. DIGIT_PATTERN = re.compile(r'^\d+$')
  849. value_converters = {
  850. 'ext': 'ext_convert',
  851. 'cfg': 'cfg_convert',
  852. }
  853. # We might want to use a different one, e.g. importlib
  854. importer = staticmethod(__import__)
  855. def __init__(self, config):
  856. self.config = ConvertingDict(config)
  857. self.config.configurator = self
  858. def resolve(self, s):
  859. """
  860. Resolve strings to objects using standard import and attribute
  861. syntax.
  862. """
  863. name = s.split('.')
  864. used = name.pop(0)
  865. try:
  866. found = self.importer(used)
  867. for frag in name:
  868. used += '.' + frag
  869. try:
  870. found = getattr(found, frag)
  871. except AttributeError:
  872. self.importer(used)
  873. found = getattr(found, frag)
  874. return found
  875. except ImportError:
  876. e, tb = sys.exc_info()[1:]
  877. v = ValueError('Cannot resolve %r: %s' % (s, e))
  878. v.__cause__, v.__traceback__ = e, tb
  879. raise v
  880. def ext_convert(self, value):
  881. """Default converter for the ext:// protocol."""
  882. return self.resolve(value)
  883. def cfg_convert(self, value):
  884. """Default converter for the cfg:// protocol."""
  885. rest = value
  886. m = self.WORD_PATTERN.match(rest)
  887. if m is None:
  888. raise ValueError("Unable to convert %r" % value)
  889. else:
  890. rest = rest[m.end():]
  891. d = self.config[m.groups()[0]]
  892. while rest:
  893. m = self.DOT_PATTERN.match(rest)
  894. if m:
  895. d = d[m.groups()[0]]
  896. else:
  897. m = self.INDEX_PATTERN.match(rest)
  898. if m:
  899. idx = m.groups()[0]
  900. if not self.DIGIT_PATTERN.match(idx):
  901. d = d[idx]
  902. else:
  903. try:
  904. n = int(
  905. idx
  906. ) # try as number first (most likely)
  907. d = d[n]
  908. except TypeError:
  909. d = d[idx]
  910. if m:
  911. rest = rest[m.end():]
  912. else:
  913. raise ValueError('Unable to convert '
  914. '%r at %r' % (value, rest))
  915. # rest should be empty
  916. return d
  917. def convert(self, value):
  918. """
  919. Convert values to an appropriate type. dicts, lists and tuples are
  920. replaced by their converting alternatives. Strings are checked to
  921. see if they have a conversion format and are converted if they do.
  922. """
  923. if not isinstance(value, ConvertingDict) and isinstance(
  924. value, dict):
  925. value = ConvertingDict(value)
  926. value.configurator = self
  927. elif not isinstance(value, ConvertingList) and isinstance(
  928. value, list):
  929. value = ConvertingList(value)
  930. value.configurator = self
  931. elif not isinstance(value, ConvertingTuple) and isinstance(value, tuple):
  932. value = ConvertingTuple(value)
  933. value.configurator = self
  934. elif isinstance(value, string_types):
  935. m = self.CONVERT_PATTERN.match(value)
  936. if m:
  937. d = m.groupdict()
  938. prefix = d['prefix']
  939. converter = self.value_converters.get(prefix, None)
  940. if converter:
  941. suffix = d['suffix']
  942. converter = getattr(self, converter)
  943. value = converter(suffix)
  944. return value
  945. def configure_custom(self, config):
  946. """Configure an object with a user-supplied factory."""
  947. c = config.pop('()')
  948. if not callable(c):
  949. c = self.resolve(c)
  950. props = config.pop('.', None)
  951. # Check for valid identifiers
  952. kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
  953. result = c(**kwargs)
  954. if props:
  955. for name, value in props.items():
  956. setattr(result, name, value)
  957. return result
  958. def as_tuple(self, value):
  959. """Utility function which converts lists to tuples."""
  960. if isinstance(value, list):
  961. value = tuple(value)
  962. return value