Skip to content

Commit 2a6f290

Browse files
authored
Add automatic code formatting to Requests (#6095)
1 parent 2d55176 commit 2a6f290

39 files changed

+2830
-2399
lines changed

.coveragerc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
[run]
2-
omit = requests/packages/*
2+
omit = requests/packages/*

.github/ISSUE_TEMPLATE.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,4 @@ import requests
2525

2626
This command is only available on Requests v2.16.4 and greater. Otherwise,
2727
please provide some basic information about your system (Python version,
28-
operating system, &c).
28+
operating system, &c).

.github/workflows/codeql-analysis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ jobs:
4242
with:
4343
languages: "python"
4444
# If you wish to specify custom queries, you can do so here or in a config file.
45-
# By default, queries listed here will override any specified in a config file.
45+
# By default, queries listed here will override any specified in a config file.
4646
# Prefix the list here with "+" to use these queries and those in the config file.
4747
# queries: ./path/to/local/query, your-org/your-repo/queries@main
4848

.pre-commit-config.yaml

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
exclude: 'docs/|ext/'
2+
3+
repos:
4+
- repo: https://github.com/pre-commit/pre-commit-hooks
5+
rev: v4.0.1
6+
hooks:
7+
- id: check-yaml
8+
- id: debug-statements
9+
- id: end-of-file-fixer
10+
- id: trailing-whitespace
11+
- repo: https://github.com/PyCQA/isort
12+
rev: 5.10.1
13+
hooks:
14+
- id: isort
15+
- repo: https://github.com/psf/black
16+
rev: 22.3.0
17+
hooks:
18+
- id: black
19+
exclude: tests/test_lowlevel.py
20+
- repo: https://github.com/asottile/pyupgrade
21+
rev: v2.31.1
22+
hooks:
23+
- id: pyupgrade
24+
args: [--py37-plus]
25+
- repo: https://gitlab.com/pycqa/flake8
26+
rev: 4.0.1
27+
hooks:
28+
- id: flake8

docs/dev/contributing.rst

Lines changed: 15 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,21 @@ event that you object to the code review feedback, you should make your case
9393
clearly and calmly. If, after doing so, the feedback is judged to still apply,
9494
you must either apply the feedback or withdraw your contribution.
9595

96+
Code Style
97+
~~~~~~~~~~
98+
99+
Requests uses a collection of tools to ensure the code base has a consistent
100+
style as it grows. We have these orchestrated using a tool called
101+
`pre-commit`_. This can be installed locally and run over your changes prior
102+
to opening a PR, and will also be run as part of the CI approval process
103+
before a change is merged.
104+
105+
You can find the full list of formatting requirements specified in the
106+
`.pre-commit-config.yaml`_ at the top level directory of Requests.
107+
108+
.. _pre-commit: https://pre-commit.com/
109+
.. _.pre-commit-config.yaml: https://github.com/psf/requests/blob/main/.pre-commit-config.yaml
110+
96111
New Contributors
97112
~~~~~~~~~~~~~~~~
98113

@@ -103,62 +118,6 @@ asking for help.
103118

104119
Please also check the :ref:`early-feedback` section.
105120

106-
Kenneth Reitz's Code Style™
107-
~~~~~~~~~~~~~~~~~~~~~~~~~~~
108-
109-
The Requests codebase uses the `PEP 8`_ code style.
110-
111-
In addition to the standards outlined in PEP 8, we have a few guidelines:
112-
113-
- Line-length can exceed 79 characters, to 100, when convenient.
114-
- Line-length can exceed 100 characters, when doing otherwise would be *terribly* inconvenient.
115-
- Always use single-quoted strings (e.g. ``'#flatearth'``), unless a single-quote occurs within the string.
116-
117-
Additionally, one of the styles that PEP8 recommends for `line continuations`_
118-
completely lacks all sense of taste, and is not to be permitted within
119-
the Requests codebase::
120-
121-
# Aligned with opening delimiter.
122-
foo = long_function_name(var_one, var_two,
123-
var_three, var_four)
124-
125-
No. Just don't. Please. This is much better::
126-
127-
foo = long_function_name(
128-
var_one,
129-
var_two,
130-
var_three,
131-
var_four,
132-
)
133-
134-
Docstrings are to follow the following syntaxes::
135-
136-
def the_earth_is_flat():
137-
"""NASA divided up the seas into thirty-three degrees."""
138-
pass
139-
140-
::
141-
142-
def fibonacci_spiral_tool():
143-
"""With my feet upon the ground I lose myself / between the sounds
144-
and open wide to suck it in. / I feel it move across my skin. / I'm
145-
reaching up and reaching out. / I'm reaching for the random or
146-
whatever will bewilder me. / Whatever will bewilder me. / And
147-
following our will and wind we may just go where no one's been. /
148-
We'll ride the spiral to the end and may just go where no one's
149-
been.
150-
151-
Spiral out. Keep going...
152-
"""
153-
pass
154-
155-
All functions, methods, and classes are to contain docstrings. Object data
156-
model methods (e.g. ``__repr__``) are typically the exception to this rule.
157-
158-
Thanks for helping to make the world a better place!
159-
160-
.. _PEP 8: https://pep8.org/
161-
.. _line continuations: https://www.python.org/dev/peps/pep-0008/#indentation
162121

163122
Documentation Contributions
164123
---------------------------

pyproject.toml

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
[tool.isort]
2+
profile = "black"
3+
src_paths = ["requests", "test"]
4+
honor_noqa = true
5+
6+
[tool.pytest.ini_options]
7+
addopts = "-p no:warnings --doctest-modules"
8+
doctest_optionflags = "NORMALIZE_WHITESPACE ELLIPSIS"
9+
minversion = "6.2"
10+
testpaths = [
11+
"requests",
12+
"tests",
13+
]

pytest.ini

Lines changed: 0 additions & 3 deletions
This file was deleted.

requests/__init__.py

Lines changed: 59 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# -*- coding: utf-8 -*-
2-
31
# __
42
# /__) _ _ _ _ _/ _
53
# / ( (- (/ (/ (- _) / _)
@@ -40,8 +38,10 @@
4038
:license: Apache 2.0, see LICENSE for more details.
4139
"""
4240

43-
import urllib3
4441
import warnings
42+
43+
import urllib3
44+
4545
from .exceptions import RequestsDependencyWarning
4646

4747
try:
@@ -54,13 +54,14 @@
5454
except ImportError:
5555
chardet_version = None
5656

57+
5758
def check_compatibility(urllib3_version, chardet_version, charset_normalizer_version):
58-
urllib3_version = urllib3_version.split('.')
59-
assert urllib3_version != ['dev'] # Verify urllib3 isn't installed from git.
59+
urllib3_version = urllib3_version.split(".")
60+
assert urllib3_version != ["dev"] # Verify urllib3 isn't installed from git.
6061

6162
# Sometimes, urllib3 only reports its version as 16.1.
6263
if len(urllib3_version) == 2:
63-
urllib3_version.append('0')
64+
urllib3_version.append("0")
6465

6566
# Check urllib3 for compatibility.
6667
major, minor, patch = urllib3_version # noqa: F811
@@ -72,36 +73,46 @@ def check_compatibility(urllib3_version, chardet_version, charset_normalizer_ver
7273

7374
# Check charset_normalizer for compatibility.
7475
if chardet_version:
75-
major, minor, patch = chardet_version.split('.')[:3]
76+
major, minor, patch = chardet_version.split(".")[:3]
7677
major, minor, patch = int(major), int(minor), int(patch)
7778
# chardet_version >= 3.0.2, < 5.0.0
7879
assert (3, 0, 2) <= (major, minor, patch) < (5, 0, 0)
7980
elif charset_normalizer_version:
80-
major, minor, patch = charset_normalizer_version.split('.')[:3]
81+
major, minor, patch = charset_normalizer_version.split(".")[:3]
8182
major, minor, patch = int(major), int(minor), int(patch)
8283
# charset_normalizer >= 2.0.0 < 3.0.0
8384
assert (2, 0, 0) <= (major, minor, patch) < (3, 0, 0)
8485
else:
8586
raise Exception("You need either charset_normalizer or chardet installed")
8687

88+
8789
def _check_cryptography(cryptography_version):
8890
# cryptography < 1.3.4
8991
try:
90-
cryptography_version = list(map(int, cryptography_version.split('.')))
92+
cryptography_version = list(map(int, cryptography_version.split(".")))
9193
except ValueError:
9294
return
9395

9496
if cryptography_version < [1, 3, 4]:
95-
warning = 'Old version of cryptography ({}) may cause slowdown.'.format(cryptography_version)
97+
warning = "Old version of cryptography ({}) may cause slowdown.".format(
98+
cryptography_version
99+
)
96100
warnings.warn(warning, RequestsDependencyWarning)
97101

102+
98103
# Check imported dependencies for compatibility.
99104
try:
100-
check_compatibility(urllib3.__version__, chardet_version, charset_normalizer_version)
105+
check_compatibility(
106+
urllib3.__version__, chardet_version, charset_normalizer_version
107+
)
101108
except (AssertionError, ValueError):
102-
warnings.warn("urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported "
103-
"version!".format(urllib3.__version__, chardet_version, charset_normalizer_version),
104-
RequestsDependencyWarning)
109+
warnings.warn(
110+
"urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported "
111+
"version!".format(
112+
urllib3.__version__, chardet_version, charset_normalizer_version
113+
),
114+
RequestsDependencyWarning,
115+
)
105116

106117
# Attempt to enable urllib3's fallback for SNI support
107118
# if the standard library doesn't support SNI or the
@@ -114,39 +125,56 @@ def _check_cryptography(cryptography_version):
114125

115126
if not getattr(ssl, "HAS_SNI", False):
116127
from urllib3.contrib import pyopenssl
128+
117129
pyopenssl.inject_into_urllib3()
118130

119131
# Check cryptography version
120132
from cryptography import __version__ as cryptography_version
133+
121134
_check_cryptography(cryptography_version)
122135
except ImportError:
123136
pass
124137

125138
# urllib3's DependencyWarnings should be silenced.
126139
from urllib3.exceptions import DependencyWarning
127-
warnings.simplefilter('ignore', DependencyWarning)
128140

129-
from .__version__ import __title__, __description__, __url__, __version__
130-
from .__version__ import __build__, __author__, __author_email__, __license__
131-
from .__version__ import __copyright__, __cake__
132-
133-
from . import utils
134-
from . import packages
135-
from .models import Request, Response, PreparedRequest
136-
from .api import request, get, head, post, patch, put, delete, options
137-
from .sessions import session, Session
138-
from .status_codes import codes
139-
from .exceptions import (
140-
RequestException, Timeout, URLRequired,
141-
TooManyRedirects, HTTPError, ConnectionError,
142-
FileModeWarning, ConnectTimeout, ReadTimeout, JSONDecodeError
143-
)
141+
warnings.simplefilter("ignore", DependencyWarning)
144142

145143
# Set default logging handler to avoid "No handler found" warnings.
146144
import logging
147145
from logging import NullHandler
148146

147+
from . import packages, utils
148+
from .__version__ import (
149+
__author__,
150+
__author_email__,
151+
__build__,
152+
__cake__,
153+
__copyright__,
154+
__description__,
155+
__license__,
156+
__title__,
157+
__url__,
158+
__version__,
159+
)
160+
from .api import delete, get, head, options, patch, post, put, request
161+
from .exceptions import (
162+
ConnectionError,
163+
ConnectTimeout,
164+
FileModeWarning,
165+
HTTPError,
166+
JSONDecodeError,
167+
ReadTimeout,
168+
RequestException,
169+
Timeout,
170+
TooManyRedirects,
171+
URLRequired,
172+
)
173+
from .models import PreparedRequest, Request, Response
174+
from .sessions import Session, session
175+
from .status_codes import codes
176+
149177
logging.getLogger(__name__).addHandler(NullHandler())
150178

151179
# FileModeWarnings go off per the default.
152-
warnings.simplefilter('default', FileModeWarning, append=True)
180+
warnings.simplefilter("default", FileModeWarning, append=True)

requests/__version__.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22
# |( |- |.| | | |- `-. | `-.
33
# ' ' `-' `-`.`-' `-' `-' ' `-'
44

5-
__title__ = 'requests'
6-
__description__ = 'Python HTTP for Humans.'
7-
__url__ = 'https://requests.readthedocs.io'
8-
__version__ = '2.27.1'
5+
__title__ = "requests"
6+
__description__ = "Python HTTP for Humans."
7+
__url__ = "https://requests.readthedocs.io"
8+
__version__ = "2.27.1"
99
__build__ = 0x022701
10-
__author__ = 'Kenneth Reitz'
11-
__author_email__ = '[email protected]'
12-
__license__ = 'Apache 2.0'
13-
__copyright__ = 'Copyright 2022 Kenneth Reitz'
14-
__cake__ = u'\u2728 \U0001f370 \u2728'
10+
__author__ = "Kenneth Reitz"
11+
__author_email__ = "[email protected]"
12+
__license__ = "Apache 2.0"
13+
__copyright__ = "Copyright 2022 Kenneth Reitz"
14+
__cake__ = "\u2728 \U0001f370 \u2728"

requests/_internal_utils.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# -*- coding: utf-8 -*-
2-
31
"""
42
requests._internal_utils
53
~~~~~~~~~~~~~~
@@ -11,7 +9,7 @@
119
from .compat import builtin_str
1210

1311

14-
def to_native_string(string, encoding='ascii'):
12+
def to_native_string(string, encoding="ascii"):
1513
"""Given a string object, regardless of type, returns a representation of
1614
that string in the native string type, encoding and decoding where
1715
necessary. This assumes ASCII unless told otherwise.
@@ -33,7 +31,7 @@ def unicode_is_ascii(u_string):
3331
"""
3432
assert isinstance(u_string, str)
3533
try:
36-
u_string.encode('ascii')
34+
u_string.encode("ascii")
3735
return True
3836
except UnicodeEncodeError:
3937
return False

0 commit comments

Comments
 (0)