Merge pull request #3429 from nateprewitt/docstring_cleanup
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Docstring cleanup
authored by Kenneth Reitz · committed by GitHub · parents 4285bac, b7809ac · Browse files · 22 files·+130 added−108 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
22 files+130 added−108 removed
- tests:+30 added−26 removed
- other:+100 added−82 removed
Provenance
- Commit
fb01456- Tree
b1f81b2- Author
Kenneth Reitz <me@kennethreitz.org>- Committer
GitHub <noreply@github.com>- Parent 1
4285bac- Parent 2
b7809ac
22 files changed+130 added−108 removed
modified:requests/__init__.py-1 removed
36 unmodified lines37 is at <http://python-requests.org>.38 39 :copyright: (c) 2016 by Kenneth Reitz.40 :license: Apache 2.0, see LICENSE for more details.41-41 """42 43 __title__ = 'requests'44 __version__ = '2.10.0'42 unmodified linesmodified:requests/api.py-1 removed
6 unmodified lines7 This module implements the Requests API.8 9 :copyright: (c) 2012 by Kenneth Reitz.10 :license: Apache2, see LICENSE for more details.11-11 """12 13 from . import sessions14 134 unmodified linesmodified:requests/certs.py+2 added-2 removed
1 #!/usr/bin/env python2 # -*- coding: utf-8 -*-3 4 """5-certs.py6-~~~~~~~~5+requests.certs6+~~~~~~~~~~~~~~7 8 This module returns the preferred default CA certificate bundle.9 10 If you are packaging Requests, e.g., for a Linux distribution or a managed15 unmodified linesmodified:requests/compat.py+5 added-1 removed
1 # -*- coding: utf-8 -*-2 3 """4-pythoncompat4+requests.compat5+~~~~~~~~~~~~~~~6+7+This module handles import compatibility issues between Python 2 and8+Python 3.9 """10 11 from .packages import chardet12 54 unmodified linesmodified:requests/cookies.py+65 added-27 removed
1 # -*- coding: utf-8 -*-2 3 """4+requests.cookies5+~~~~~~~~~~~~~~~~6+7 Compatibility code to be able to use `cookielib.CookieJar` with requests.8 9 requests.utils imports from here, so be careful with imports.10 """149 unmodified lines160 161 162 class CookieConflictError(RuntimeError):163 """There are two cookies that meet the criteria specified in the cookie jar.161- Use .get and .set and include domain and path args in order to be more specific."""164+ Use .get and .set and include domain and path args in order to be more specific.165+ """166 167 168 class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):169 """Compatibility class; is a cookielib.CookieJar, but exposes a dict17 unmodified lines187 """Dict-like get() that also supports optional domain and path args in188 order to resolve naming collisions from using one cookie jar over189 multiple domains.190 187- .. warning:: operation is O(n), not O(1)."""191+ .. warning:: operation is O(n), not O(1).192+ """193 try:194 return self._find_no_duplicates(name, domain, path)195 except KeyError:196 return default197 198 def set(self, name, value, **kwargs):199 """Dict-like set() that also supports optional domain and path args in200 order to resolve naming collisions from using one cookie jar over196- multiple domains."""201+ multiple domains.202+ """203 # support client code that unsets cookies by assignment of a None value:204 if value is None:205 remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))206 return6 unmodified lines213 return c214 215 def iterkeys(self):216 """Dict-like iterkeys() that returns an iterator of names of cookies211- from the jar. See itervalues() and iteritems()."""217+ from the jar.218+219+ .. seealso:: itervalues() and iteritems().220+ """221 for cookie in iter(self):222 yield cookie.name223 224 def keys(self):225 """Dict-like keys() that returns a list of names of cookies from the217- jar. See values() and items()."""226+ jar.227+228+ .. seealso:: values() and items().229+ """230 return list(self.iterkeys())231 232 def itervalues(self):233 """Dict-like itervalues() that returns an iterator of values of cookies222- from the jar. See iterkeys() and iteritems()."""234+ from the jar.235+236+ .. seealso:: iterkeys() and iteritems().237+ """238 for cookie in iter(self):239 yield cookie.value240 241 def values(self):242 """Dict-like values() that returns a list of values of cookies from the228- jar. See keys() and items()."""243+ jar.244+245+ .. seealso:: keys() and items().246+ """247 return list(self.itervalues())248 249 def iteritems(self):250 """Dict-like iteritems() that returns an iterator of name-value tuples233- from the jar. See iterkeys() and itervalues()."""251+ from the jar.252+253+ .. seealso:: iterkeys() and itervalues().254+ """255 for cookie in iter(self):256 yield cookie.name, cookie.value257 258 def items(self):259 """Dict-like items() that returns a list of name-value tuples from the239- jar. See keys() and values(). Allows client-code to call240- ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value241- pairs."""260+ jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a261+ vanilla python dict of key value pairs.262+263+ .. seealso:: keys() and values().264+ """265 return list(self.iteritems())266 267 def list_domains(self):268 """Utility method to list all the domains in the jar."""12 unmodified lines281 return paths282 283 def multiple_domains(self):284 """Returns True if there are multiple domains in the jar.262- Returns False otherwise."""285+ Returns False otherwise.286+ """287 domains = []288 for cookie in iter(self):289 if cookie.domain is not None and cookie.domain in domains:290 return True2 unmodified lines293 294 def get_dict(self, domain=None, path=None):295 """Takes as an argument an optional domain and path and returns a plain296 old Python dict of name-value pairs of cookies that meet the273- requirements."""297+ requirements.298+ """299 dictionary = {}300 for cookie in iter(self):301 if (domain is None or cookie.domain == domain) and (path is None302 or cookie.path == path):10 unmodified lines313 """Dict-like __getitem__() for compatibility with client code. Throws314 exception if there are more than one cookie with name. In that case,315 use the more explicit get() method instead.316 292- .. warning:: operation is O(n), not O(1)."""293-317+ .. warning:: operation is O(n), not O(1).318+ """319 return self._find_no_duplicates(name)320 321 def __setitem__(self, name, value):322 """Dict-like __setitem__ for compatibility with client code. Throws323 exception if there is already a cookie of that name in the jar. In that299- case, use the more explicit set() method instead."""300-324+ case, use the more explicit set() method instead.325+ """326 self.set(name, value)327 328 def __delitem__(self, name):329 """Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s305- ``remove_cookie_by_name()``."""330+ ``remove_cookie_by_name()``.331+ """332 remove_cookie_by_name(self, name)333 334 def set_cookie(self, cookie, *args, **kwargs):335 if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):8 unmodified lines344 else:345 super(RequestsCookieJar, self).update(other)346 347 def _find(self, name, domain=None, path=None):322- """Requests uses this method internally to get cookie values. Takes as323- args name and optional domain and path. Returns a cookie.value. If324- there are conflicting cookies, _find arbitrarily chooses one. See325- _find_no_duplicates if you want an exception thrown if there are326- conflicting cookies."""348+ """Requests uses this method internally to get cookie values.349+350+ If there are conflicting cookies, _find arbitrarily chooses one.351+ See _find_no_duplicates if you want an exception thrown if there are352+ conflicting cookies.353+354+ :param name: a string containing name of cookie355+ :param domain: (optional) string containing domain of cookie356+ :param path: (optional) string containing path of cookie357+ :return: cookie.value358+ """359 for cookie in iter(self):360 if cookie.name == name:361 if domain is None or cookie.domain == domain:362 if path is None or cookie.path == path:2 unmodified lines365 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))366 367 def _find_no_duplicates(self, name, domain=None, path=None):368 """Both ``__get_item__`` and ``get`` call this function: it's never337- used elsewhere in Requests. Takes as args name and optional domain and338- path. Returns a cookie.value. Throws KeyError if cookie is not found339- and CookieConflictError if there are multiple cookies that match name340- and optionally domain and path."""369+ used elsewhere in Requests.370+371+ :param name: a string containing name of cookie372+ :param domain: (optional) string containing domain of cookie373+ :param path: (optional) string containing path of cookie374+ :raises KeyError: if cookie is not found375+ :raises CookieConflictError: if there are multiple cookies376+ that match name and optionally domain and path377+ :return: cookie.value378+ """379 toReturn = None380 for cookie in iter(self):381 if cookie.name == name:382 if domain is None or cookie.domain == domain:150 unmodified linesmodified:requests/exceptions.py+4 added-8 removed
3 unmodified lines4 requests.exceptions5 ~~~~~~~~~~~~~~~~~~~6 7 This module contains the set of Requests' exceptions.8-8 """9 from .packages.urllib3.exceptions import HTTPError as BaseHTTPError10 11 12 class RequestException(IOError):13 """There was an ambiguous exception that occurred while handling your15- request."""14+ request.15+ """16 17 def __init__(self, *args, **kwargs):18- """19- Initialize RequestException with `request` and `response` objects.20- """18+ """Initialize RequestException with `request` and `response` objects."""19 response = kwargs.pop('response', None)20 self.response = response21 self.request = kwargs.pop('request', None)22 if (response is not None and not self.request and86 unmodified lines109 pass110 111 112 class FileModeWarning(RequestsWarning, DeprecationWarning):115- """116- A file was opened in text mode, but Requests determined its binary length.117- """113+ """A file was opened in text mode, but Requests determined its binary length."""114 passmodified:requests/hooks.py-1 removed
8 unmodified lines9 Available hooks:10 11 ``response``:12 The response generated from a Request.13-13 """14 HOOKS = ['response']15 16 18 unmodified linesmodified:requests/models.py+2 added-5 removed
106 unmodified lines107 tuples. Order is retained if data is a list of tuples but arbitrary108 if parameters are supplied as a dict.109 The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)110 or 4-tuples (filename, fileobj, contentype, custom_headers).111-111 """112 if (not files):113 raise ValueError("Files must be provided.")114 elif isinstance(data, basestring):90 unmodified lines205 >>> import requests206 >>> req = requests.Request('GET', 'http://httpbin.org/get')207 >>> req.prepare()208 <PreparedRequest [GET]>210-209 """210 211 def __init__(self, method=None, url=None, headers=None, files=None,212 data=None, params=None, auth=None, cookies=None, hooks=None, json=None):55 unmodified lines268 269 >>> s = requests.Session()270 >>> s.send(r)271 <Response [200]>274-272 """273 274 def __init__(self):275 #: HTTP verb to send to the server.237 unmodified lines513 will not be regenerated if it already exists, meaning this function514 can only be called once for the life of the515 :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls516 to ``prepare_cookies`` will have no actual effect, unless the "Cookie"520- header is removed beforehand."""521-517+ header is removed beforehand.518+ """519 if isinstance(cookies, cookielib.CookieJar):520 self._cookies = cookies521 else:522 self._cookies = cookiejar_from_dict(cookies)351 unmodified linesmodified:requests/sessions.py+7 added-12 removed
4 unmodified lines5 ~~~~~~~~~~~~~~~~6 7 This module provides a Session object to manage and persist settings across8 requests (cookies, auth, proxies).9-9 """10 import os11 from collections import Mapping12 from datetime import datetime25 unmodified lines38 REDIRECT_CACHE_SIZE = 100039 40 41 def merge_setting(request_setting, session_setting, dict_class=OrderedDict):43- """44- Determines appropriate setting for a given request, taking into account the45- explicit setting on that request, and the setting in the session. If a42+ """Determines appropriate setting for a given request, taking into account43+ the explicit setting on that request, and the setting in the session. If a44 setting is a dictionary, they will be merged together using `dict_class`45 """46 47 if session_setting is None:21 unmodified lines69 return merged_setting70 71 72 def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):75- """76- Properly merges both requests and session hooks.73+ """Properly merges both requests and session hooks.74 75 This is necessary because when request_hooks == {'response': []}, the76 merge breaks Session hooks entirely.77 """103 unmodified lines181 i += 1182 yield resp183 184 def rebuild_auth(self, prepared_request, response):188- """189- When being redirected we may want to strip authentication from the185+ """When being redirected we may want to strip authentication from the186 request to avoid leaking credentials. This method intelligently removes187 and reapplies authentication where possible to avoid credential loss.188 """189 headers = prepared_request.headers15 unmodified lines205 206 return207 208 def rebuild_proxies(self, prepared_request, proxies):213- """214- This method re-evaluates the proxy configuration by considering the209+ """This method re-evaluates the proxy configuration by considering the210 environment variables. If we are redirected to a URL covered by211 NO_PROXY, we strip the proxy configuration. Otherwise, we set missing212 proxy keys for this URL (in case they were stripped by a previous213 redirect).441 unmodified lines655 656 def mount(self, prefix, adapter):657 """Registers a connection adapter to a prefix.658 664- Adapters are sorted in descending order by key length."""665-659+ Adapters are sorted in descending order by key length.660+ """661 self.adapters[prefix] = adapter662 keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]663 664 for key in keys_to_move:21 unmodified linesmodified:requests/structures.py+1 added-4 removed
3 unmodified lines4 requests.structures5 ~~~~~~~~~~~~~~~~~~~6 7 Data structures that power Requests.8-8 """9 10 import collections11 12 from .compat import OrderedDict13 14 15 class CaseInsensitiveDict(collections.MutableMapping):17- """18- A case-insensitive ``dict``-like object.16+ """A case-insensitive ``dict``-like object.17 18 Implements all methods and operations of19 ``collections.MutableMapping`` as well as dict's ``copy``. Also20 provides ``lower_items``.15 unmodified lines36 37 If the constructor, ``.update``, or equality comparison38 operations are given keys that have equal ``.lower()``s, the39 behavior is undefined.42-40 """41 42 def __init__(self, data=None, **kwargs):43 self._store = OrderedDict()62 unmodified linesmodified:requests/utils.py+14 added-20 removed
4 unmodified lines5 ~~~~~~~~~~~~~~6 7 This module provides utility functions that are used within Requests8 that are also useful for external consumption.9-9 """10 11 import cgi12 import codecs385 unmodified lines398 Tried:399 400 1. charset from content-type401 2. fall back and replace all unicode characters403-402 """403 warnings.warn((404 'In requests 3.0, get_unicode_from_response will be removed. For '405 'more information, please see the discussion on issue #2266. (This'66 unmodified lines472 return quote(uri, safe=safe_without_percent)473 474 475 def address_in_network(ip, net):478- """479- This function allows you to check if on IP belongs to a network subnet476+ """This function allows you to check if on IP belongs to a network subnet477+478 Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24479 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24480 """481 ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]3 unmodified lines485 return (ipaddr & netmask) == (network & netmask)486 487 488 def dotted_netmask(mask):491- """492- Converts mask from /xx format to xxx.xxx.xxx.xxx489+ """Converts mask from /xx format to xxx.xxx.xxx.xxx490+491 Example: if mask is 24 function returns 255.255.255.0492 """493 bits = 0xffffffff ^ (1 << 32 - mask) - 1494 return socket.inet_ntoa(struct.pack('>I', bits))27 unmodified lines522 return True523 524 525 def should_bypass_proxies(url):528- """529- Returns whether we should bypass proxies or not.530- """526+ """Returns whether we should bypass proxies or not."""527 get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())528 529 # First check whether no_proxy is defined. If it is, check that the URL530 # we're getting isn't in the no_proxy list.92 unmodified lines623 def parse_header_links(value):624 """Return a dict of parsed link headers proxies.625 626 i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"631-627 """628 629 links = []630 56 unmodified lines687 688 689 def prepend_scheme_if_needed(url, new_scheme):690 """Given a URL that may or may not have a scheme, prepend the given scheme.696- Does not replace a present scheme with the one provided as an argument."""691+ Does not replace a present scheme with the one provided as an argument.692+ """693 scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)694 695 # urlparse is a finicky beast, and sometimes decides that there isn't a696 # netloc present. Assume that it's being over-cautious, and switch netloc5 unmodified lines702 703 704 def get_auth_from_url(url):705 """Given a url with authentication components, extract them into a tuple of710- username,password."""706+ username,password.707+ """708 parsed = urlparse(url)709 710 try:711 auth = (unquote(parsed.username), unquote(parsed.password))3 unmodified lines715 return auth716 717 718 def to_native_string(string, encoding='ascii'):719+ """Given a string object, regardless of type, returns a representation of720+ that string in the native string type, encoding and decoding where721+ necessary. This assumes ASCII unless told otherwise.722 """723- Given a string object, regardless of type, returns a representation of that724- string in the native string type, encoding and decoding where necessary.725- This assumes ASCII unless told otherwise.726- """723 if isinstance(string, builtin_str):724 out = string725 else:726 if is_py2:8 unmodified lines735 _CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$')736 _CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')737 738 def check_header_validity(header):743- """Verifies that header value is a string which doesn't contain 739+ """Verifies that header value is a string which doesn't contain740 leading whitespace or return characters. This prevents unintended741 header injection.742 743 :param header: tuple, in the format (name, value).12 unmodified lines756 "not %s" % (value, type(value)))757 758 759 def urldefragauth(url):764- """765- Given a url remove the fragment and the authentication part766- """760+ """Given a url remove the fragment and the authentication part"""761 scheme, netloc, path, params, query, fragment = urlparse(url)762 763 # see func:`prepend_scheme_if_needed`764 if not netloc:5 unmodified linesmodified:tests/testserver/server.py+2 added
1+# -*- coding: utf-8 -*-2+3 import threading4 import socket5 import select6 121 unmodified linesmodified:tests/__init__.py+1 added-1 removed
1-# coding: utf-81+# -*- coding: utf-8 -*-2 3 """Requests test package initialisation."""4 5 import warnings17 unmodified linesmodified:tests/compat.py+2 added-1 removed
1-# coding: utf-81+# -*- coding: utf-8 -*-2+3 from requests.compat import is_py34 5 6 try:15 unmodified linesmodified:tests/conftest.py+2 added-1 removed
1-# coding: utf-81+# -*- coding: utf-8 -*-2+3 import pytest4 from requests.compat import urljoin5 6 18 unmodified linesmodified:tests/test_hooks.py+2 added-1 removed
1-# coding: utf-81+# -*- coding: utf-8 -*-2+3 import pytest4 5 from requests import hooks6 17 unmodified linesmodified:tests/test_lowlevel.py+2 added
1+# -*- coding: utf-8 -*-2+3 import os4 import pytest5 import threading6 import requests52 unmodified linesmodified:tests/test_requests.py+3 added-6 removed
953 unmodified lines954 assert next(iter(r))955 io.close()956 957 def test_response_decode_unicode(self):958- """959- When called with decode_unicode, Response.iter_content should always958+ """When called with decode_unicode, Response.iter_content should always959 return unicode.960 """961 r = requests.Response()962 r._content_consumed = True82 unmodified lines1045 r = s.send(r.prepare())1046 assert r.status_code == 2001047 1048 def test_fixes_1329(self, httpbin):1050- """1051- Ensure that header updates are done case-insensitively.1052- """1049+ """Ensure that header updates are done case-insensitively."""1050 s = requests.Session()1051 s.headers.update({'ACCEPT': 'BOGUS'})1052 s.headers.update({'accept': 'application/json'})1053 r = s.get(httpbin('get'))520 unmodified lines1574 requests.get(httpbin('get'), timeout=timeout)1575 assert error_text in str(e)1576 1577 def test_none_timeout(self, httpbin):1581- """ Check that you can set None as a valid timeout value.1578+ """Check that you can set None as a valid timeout value.1579 1580 To actually test this behavior, we'd want to check that setting the1581 timeout to None actually lets the request block past the system default1582 timeout. However, this would make the test suite unbearably slow.200 unmodified linesmodified:tests/test_structures.py+4 added-7 removed
1-# coding: utf-81+# -*- coding: utf-8 -*-2+3 import pytest4 5 from requests.structures import CaseInsensitiveDict, LookupDict6 1 unmodified line8 class TestCaseInsensitiveDict:9 10 @pytest.fixture(autouse=True)11 def setup(self):11- """12- CaseInsensitiveDict instance with "Accept" header.13- """12+ """CaseInsensitiveDict instance with "Accept" header."""13 self.case_insensitive_dict = CaseInsensitiveDict()14 self.case_insensitive_dict['Accept'] = 'application/json'15 16 def test_list(self):35 unmodified lines52 class TestLookupDict:53 54 @pytest.fixture(autouse=True)55 def setup(self):57- """58- LookupDict instance with "bad_gateway" attribute.59- """56+ """LookupDict instance with "bad_gateway" attribute."""57 self.lookup_dict = LookupDict('test')58 self.lookup_dict.bad_gateway = 50259 60 def test_repr(self):16 unmodified linesmodified:tests/test_testserver.py+2 added
1+# -*- coding: utf-8 -*-2+3 import threading4 import socket5 import time6 158 unmodified linesmodified:tests/test_utils.py+8 added-9 removed
1-# coding: utf-81+# -*- coding: utf-8 -*-2+3 from io import BytesIO4 5 import pytest6 from requests import compat33 unmodified lines40 assert super_len(s) == 041 42 @pytest.mark.parametrize('error', [IOError, OSError])43 def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):43- """44- If tell() raises errors, assume the cursor is at position zero.45- """44+ """If tell() raises errors, assume the cursor is at position zero."""45 class BoomFile(object):46 def __len__(self):47 return 548 53 unmodified lines102 103 104 class TestGetEnvironProxies:105 """Ensures that IP addresses are correctly matches with ranges107- in no_proxy variable."""106+ in no_proxy variable.107+ """108 109 @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])110 def no_proxy(self, request, monkeypatch):111 monkeypatch.setenv(request.param, '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')175 unmodified lines287 'http://example.com/fiz?buz=%25ppicture',288 ),289 ))290 def test_requote_uri_with_unquoted_percents(uri, expected):291- """See: https://github.com/kennethreitz/requests/issues/2356292- """291+ """See: https://github.com/kennethreitz/requests/issues/2356"""292 assert requote_uri(uri) == expected293 294 295 @pytest.mark.parametrize(162 unmodified lines458 ('http://172.16.1.12:5000/', False),459 ('http://google.com:5000/v1.0/', False),460 ))461 def test_should_bypass_proxies(url, expected, monkeypatch):462+ """Tests for function should_bypass_proxies to check if proxy463+ can be bypassed or not464 """464- Tests for function should_bypass_proxies to check if proxy can be bypassed or not465- """465 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')466 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')467 assert should_bypass_proxies(url) == expectedmodified:tests/utils.py+2 added
1+# -*- coding: utf-8 -*-2+3 import contextlib4 import os5 6 13 unmodified lines