python.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. """
  2. This module contains essential stuff that should've come with Python itself ;)
  3. """
  4. import gc
  5. import os
  6. import re
  7. import inspect
  8. import weakref
  9. import errno
  10. import six
  11. from functools import partial, wraps
  12. from itertools import chain
  13. import sys
  14. from scrapy.utils.decorators import deprecated
  15. def flatten(x):
  16. """flatten(sequence) -> list
  17. Returns a single, flat list which contains all elements retrieved
  18. from the sequence and all recursively contained sub-sequences
  19. (iterables).
  20. Examples:
  21. >>> [1, 2, [3,4], (5,6)]
  22. [1, 2, [3, 4], (5, 6)]
  23. >>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, (8,9,10)])
  24. [1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]
  25. >>> flatten(["foo", "bar"])
  26. ['foo', 'bar']
  27. >>> flatten(["foo", ["baz", 42], "bar"])
  28. ['foo', 'baz', 42, 'bar']
  29. """
  30. return list(iflatten(x))
  31. def iflatten(x):
  32. """iflatten(sequence) -> iterator
  33. Similar to ``.flatten()``, but returns iterator instead"""
  34. for el in x:
  35. if is_listlike(el):
  36. for el_ in iflatten(el):
  37. yield el_
  38. else:
  39. yield el
  40. def is_listlike(x):
  41. """
  42. >>> is_listlike("foo")
  43. False
  44. >>> is_listlike(5)
  45. False
  46. >>> is_listlike(b"foo")
  47. False
  48. >>> is_listlike([b"foo"])
  49. True
  50. >>> is_listlike((b"foo",))
  51. True
  52. >>> is_listlike({})
  53. True
  54. >>> is_listlike(set())
  55. True
  56. >>> is_listlike((x for x in range(3)))
  57. True
  58. >>> is_listlike(six.moves.xrange(5))
  59. True
  60. """
  61. return hasattr(x, "__iter__") and not isinstance(x, (six.text_type, bytes))
  62. def unique(list_, key=lambda x: x):
  63. """efficient function to uniquify a list preserving item order"""
  64. seen = set()
  65. result = []
  66. for item in list_:
  67. seenkey = key(item)
  68. if seenkey in seen:
  69. continue
  70. seen.add(seenkey)
  71. result.append(item)
  72. return result
  73. def to_unicode(text, encoding=None, errors='strict'):
  74. """Return the unicode representation of a bytes object ``text``. If
  75. ``text`` is already an unicode object, return it as-is."""
  76. if isinstance(text, six.text_type):
  77. return text
  78. if not isinstance(text, (bytes, six.text_type)):
  79. raise TypeError('to_unicode must receive a bytes, str or unicode '
  80. 'object, got %s' % type(text).__name__)
  81. if encoding is None:
  82. encoding = 'utf-8'
  83. return text.decode(encoding, errors)
  84. def to_bytes(text, encoding=None, errors='strict'):
  85. """Return the binary representation of ``text``. If ``text``
  86. is already a bytes object, return it as-is."""
  87. if isinstance(text, bytes):
  88. return text
  89. if not isinstance(text, six.string_types):
  90. raise TypeError('to_bytes must receive a unicode, str or bytes '
  91. 'object, got %s' % type(text).__name__)
  92. if encoding is None:
  93. encoding = 'utf-8'
  94. return text.encode(encoding, errors)
  95. def to_native_str(text, encoding=None, errors='strict'):
  96. """ Return str representation of ``text``
  97. (bytes in Python 2.x and unicode in Python 3.x). """
  98. if six.PY2:
  99. return to_bytes(text, encoding, errors)
  100. else:
  101. return to_unicode(text, encoding, errors)
  102. def re_rsearch(pattern, text, chunk_size=1024):
  103. """
  104. This function does a reverse search in a text using a regular expression
  105. given in the attribute 'pattern'.
  106. Since the re module does not provide this functionality, we have to find for
  107. the expression into chunks of text extracted from the end (for the sake of efficiency).
  108. At first, a chunk of 'chunk_size' kilobytes is extracted from the end, and searched for
  109. the pattern. If the pattern is not found, another chunk is extracted, and another
  110. search is performed.
  111. This process continues until a match is found, or until the whole file is read.
  112. In case the pattern wasn't found, None is returned, otherwise it returns a tuple containing
  113. the start position of the match, and the ending (regarding the entire text).
  114. """
  115. def _chunk_iter():
  116. offset = len(text)
  117. while True:
  118. offset -= (chunk_size * 1024)
  119. if offset <= 0:
  120. break
  121. yield (text[offset:], offset)
  122. yield (text, 0)
  123. if isinstance(pattern, six.string_types):
  124. pattern = re.compile(pattern)
  125. for chunk, offset in _chunk_iter():
  126. matches = [match for match in pattern.finditer(chunk)]
  127. if matches:
  128. start, end = matches[-1].span()
  129. return offset + start, offset + end
  130. return None
  131. def memoizemethod_noargs(method):
  132. """Decorator to cache the result of a method (without arguments) using a
  133. weak reference to its object
  134. """
  135. cache = weakref.WeakKeyDictionary()
  136. @wraps(method)
  137. def new_method(self, *args, **kwargs):
  138. if self not in cache:
  139. cache[self] = method(self, *args, **kwargs)
  140. return cache[self]
  141. return new_method
  142. _BINARYCHARS = {six.b(chr(i)) for i in range(32)} - {b"\0", b"\t", b"\n", b"\r"}
  143. _BINARYCHARS |= {ord(ch) for ch in _BINARYCHARS}
  144. @deprecated("scrapy.utils.python.binary_is_text")
  145. def isbinarytext(text):
  146. """ This function is deprecated.
  147. Please use scrapy.utils.python.binary_is_text, which was created to be more
  148. clear about the functions behavior: it is behaving inverted to this one. """
  149. return not binary_is_text(text)
  150. def binary_is_text(data):
  151. """ Returns ``True`` if the given ``data`` argument (a ``bytes`` object)
  152. does not contain unprintable control characters.
  153. """
  154. if not isinstance(data, bytes):
  155. raise TypeError("data must be bytes, got '%s'" % type(data).__name__)
  156. return all(c not in _BINARYCHARS for c in data)
  157. def _getargspec_py23(func):
  158. """_getargspec_py23(function) -> named tuple ArgSpec(args, varargs, keywords,
  159. defaults)
  160. Identical to inspect.getargspec() in python2, but uses
  161. inspect.getfullargspec() for python3 behind the scenes to avoid
  162. DeprecationWarning.
  163. >>> def f(a, b=2, *ar, **kw):
  164. ... pass
  165. >>> _getargspec_py23(f)
  166. ArgSpec(args=['a', 'b'], varargs='ar', keywords='kw', defaults=(2,))
  167. """
  168. if six.PY2:
  169. return inspect.getargspec(func)
  170. return inspect.ArgSpec(*inspect.getfullargspec(func)[:4])
  171. def get_func_args(func, stripself=False):
  172. """Return the argument name list of a callable"""
  173. if inspect.isfunction(func):
  174. func_args, _, _, _ = _getargspec_py23(func)
  175. elif inspect.isclass(func):
  176. return get_func_args(func.__init__, True)
  177. elif inspect.ismethod(func):
  178. return get_func_args(func.__func__, True)
  179. elif inspect.ismethoddescriptor(func):
  180. return []
  181. elif isinstance(func, partial):
  182. return [x for x in get_func_args(func.func)[len(func.args):]
  183. if not (func.keywords and x in func.keywords)]
  184. elif hasattr(func, '__call__'):
  185. if inspect.isroutine(func):
  186. return []
  187. elif getattr(func, '__name__', None) == '__call__':
  188. return []
  189. else:
  190. return get_func_args(func.__call__, True)
  191. else:
  192. raise TypeError('%s is not callable' % type(func))
  193. if stripself:
  194. func_args.pop(0)
  195. return func_args
  196. def get_spec(func):
  197. """Returns (args, kwargs) tuple for a function
  198. >>> import re
  199. >>> get_spec(re.match)
  200. (['pattern', 'string'], {'flags': 0})
  201. >>> class Test(object):
  202. ... def __call__(self, val):
  203. ... pass
  204. ... def method(self, val, flags=0):
  205. ... pass
  206. >>> get_spec(Test)
  207. (['self', 'val'], {})
  208. >>> get_spec(Test.method)
  209. (['self', 'val'], {'flags': 0})
  210. >>> get_spec(Test().method)
  211. (['self', 'val'], {'flags': 0})
  212. """
  213. if inspect.isfunction(func) or inspect.ismethod(func):
  214. spec = _getargspec_py23(func)
  215. elif hasattr(func, '__call__'):
  216. spec = _getargspec_py23(func.__call__)
  217. else:
  218. raise TypeError('%s is not callable' % type(func))
  219. defaults = spec.defaults or []
  220. firstdefault = len(spec.args) - len(defaults)
  221. args = spec.args[:firstdefault]
  222. kwargs = dict(zip(spec.args[firstdefault:], defaults))
  223. return args, kwargs
  224. def equal_attributes(obj1, obj2, attributes):
  225. """Compare two objects attributes"""
  226. # not attributes given return False by default
  227. if not attributes:
  228. return False
  229. temp1, temp2 = object(), object()
  230. for attr in attributes:
  231. # support callables like itemgetter
  232. if callable(attr):
  233. if attr(obj1) != attr(obj2):
  234. return False
  235. elif getattr(obj1, attr, temp1) != getattr(obj2, attr, temp2):
  236. return False
  237. # all attributes equal
  238. return True
  239. class WeakKeyCache(object):
  240. def __init__(self, default_factory):
  241. self.default_factory = default_factory
  242. self._weakdict = weakref.WeakKeyDictionary()
  243. def __getitem__(self, key):
  244. if key not in self._weakdict:
  245. self._weakdict[key] = self.default_factory(key)
  246. return self._weakdict[key]
  247. @deprecated
  248. def stringify_dict(dct_or_tuples, encoding='utf-8', keys_only=True):
  249. """Return a (new) dict with unicode keys (and values when "keys_only" is
  250. False) of the given dict converted to strings. ``dct_or_tuples`` can be a
  251. dict or a list of tuples, like any dict constructor supports.
  252. """
  253. d = {}
  254. for k, v in six.iteritems(dict(dct_or_tuples)):
  255. k = k.encode(encoding) if isinstance(k, six.text_type) else k
  256. if not keys_only:
  257. v = v.encode(encoding) if isinstance(v, six.text_type) else v
  258. d[k] = v
  259. return d
  260. @deprecated
  261. def is_writable(path):
  262. """Return True if the given path can be written (if it exists) or created
  263. (if it doesn't exist)
  264. """
  265. if os.path.exists(path):
  266. return os.access(path, os.W_OK)
  267. else:
  268. return os.access(os.path.dirname(path), os.W_OK)
  269. @deprecated
  270. def setattr_default(obj, name, value):
  271. """Set attribute value, but only if it's not already set. Similar to
  272. setdefault() for dicts.
  273. """
  274. if not hasattr(obj, name):
  275. setattr(obj, name, value)
  276. def retry_on_eintr(function, *args, **kw):
  277. """Run a function and retry it while getting EINTR errors"""
  278. while True:
  279. try:
  280. return function(*args, **kw)
  281. except IOError as e:
  282. if e.errno != errno.EINTR:
  283. raise
  284. def without_none_values(iterable):
  285. """Return a copy of ``iterable`` with all ``None`` entries removed.
  286. If ``iterable`` is a mapping, return a dictionary where all pairs that have
  287. value ``None`` have been removed.
  288. """
  289. try:
  290. return {k: v for k, v in six.iteritems(iterable) if v is not None}
  291. except AttributeError:
  292. return type(iterable)((v for v in iterable if v is not None))
  293. def global_object_name(obj):
  294. """
  295. Return full name of a global object.
  296. >>> from scrapy import Request
  297. >>> global_object_name(Request)
  298. 'scrapy.http.request.Request'
  299. """
  300. return "%s.%s" % (obj.__module__, obj.__name__)
  301. if hasattr(sys, "pypy_version_info"):
  302. def garbage_collect():
  303. # Collecting weakreferences can take two collections on PyPy.
  304. gc.collect()
  305. gc.collect()
  306. else:
  307. def garbage_collect():
  308. gc.collect()
  309. class MutableChain(object):
  310. """
  311. Thin wrapper around itertools.chain, allowing to add iterables "in-place"
  312. """
  313. def __init__(self, *args):
  314. self.data = chain(*args)
  315. def extend(self, *iterables):
  316. self.data = chain(self.data, *iterables)
  317. def __iter__(self):
  318. return self.data.__iter__()
  319. def __next__(self):
  320. return next(self.data)
  321. next = __next__