compat.py 41 KB

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