Skip to content

Commit

Permalink
chore: migrate to ruff code formatter (#2230)
Browse files Browse the repository at this point in the history
* chore: migrate to `ruff` code formatter

* chore: update falcon/inspect.py per @CaselIT's suggestion

Co-authored-by: Federico Caselli <cfederico87@gmail.com>

* chore: fix spelling

* chore(ruff): use parentheses to prevent too sparse layout

---------

Co-authored-by: Federico Caselli <cfederico87@gmail.com>
  • Loading branch information
vytas7 and CaselIT committed Apr 17, 2024
1 parent 33e0bb3 commit e619c39
Show file tree
Hide file tree
Showing 47 changed files with 71 additions and 102 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/tests.yaml
Expand Up @@ -23,9 +23,9 @@ jobs:
- "ubuntu-latest"
toxenv:
- "pep8"
- "blue"
- "pep8-examples"
- "pep8-docstrings"
- "pep8-examples"
- "ruff"
- "mypy"
- "mypy_tests"
- "py312"
Expand Down
8 changes: 4 additions & 4 deletions CONTRIBUTING.md
Expand Up @@ -28,13 +28,13 @@ Please note that all contributors and maintainers of this project are subject to

Before submitting a pull request, please ensure you have added or updated tests as appropriate,
and that all existing tests still pass with your changes.
Please also ensure that your coding style follows PEP 8 and the ``blue`` formatting style.
Please also ensure that your coding style follows PEP 8 and the ``ruff`` formatting style.

In order to reformat your code with ``blue``, simply issue:
In order to reformat your code with ``ruff``, simply issue:

```bash
$ pip install -U blue
$ blue .
$ pip install -U ruff
$ ruff format
```

You can check all this by running ``tox`` from within the Falcon project directory. Your environment must be based on CPython 3.8, 3.10, 3.11 or 3.12:
Expand Down
5 changes: 1 addition & 4 deletions README.rst
Expand Up @@ -8,7 +8,7 @@
>
</a>

|Build Status| |Docs| |codecov.io| |Blue|
|Build Status| |Docs| |codecov.io|

The Falcon Web Framework
========================
Expand Down Expand Up @@ -1049,6 +1049,3 @@ limitations under the License.
:target: https://github.com/falconry/falcon/actions?query=workflow%3A%22Run+tests%22
.. |codecov.io| image:: https://codecov.io/gh/falconry/falcon/branch/master/graphs/badge.svg
:target: http://codecov.io/gh/falconry/falcon
.. |Blue| image:: https://img.shields.io/badge/code%20style-blue-blue.svg
:target: https://blue.readthedocs.io/
:alt: code style: blue
1 change: 0 additions & 1 deletion examples/look/look/images.py
Expand Up @@ -31,7 +31,6 @@ def on_post(self, req, resp):


class ImageStore:

_CHUNK_SIZE_BYTES = 4096

# Note the use of dependency injection for standard library
Expand Down
1 change: 0 additions & 1 deletion examples/things_advanced.py
Expand Up @@ -26,7 +26,6 @@ def handle(ex, req, resp, params):


class SinkAdapter:

engines = {
'ddg': 'https://duckduckgo.com',
'y': 'https://search.yahoo.com/search',
Expand Down
1 change: 0 additions & 1 deletion examples/things_advanced_asgi.py
Expand Up @@ -26,7 +26,6 @@ async def handle(ex, req, resp, params):


class SinkAdapter:

engines = {
'ddg': 'https://duckduckgo.com',
'y': 'https://search.yahoo.com/search',
Expand Down
1 change: 0 additions & 1 deletion falcon/asgi/request.py
Expand Up @@ -384,7 +384,6 @@ class Request(request.Request):
_wsgi_errors = None

def __init__(self, scope, receive, first_event=None, options=None):

# =====================================================================
# Prepare headers
# =====================================================================
Expand Down
1 change: 0 additions & 1 deletion falcon/bench/nuts/nuts/app.py
Expand Up @@ -8,7 +8,6 @@ def create():


def setup_app(config):

return make_app(
config.app.root,
static_root=config.app.static_root,
Expand Down
2 changes: 1 addition & 1 deletion falcon/cmd/inspect_app.py
Expand Up @@ -15,6 +15,7 @@
"""
Script that prints out the routes of an App instance.
"""

import argparse
import importlib
import os
Expand Down Expand Up @@ -59,7 +60,6 @@ def make_parser():


def load_app(parser, args):

try:
module, instance = args.app_module.split(':', 1)
except ValueError:
Expand Down
6 changes: 4 additions & 2 deletions falcon/inspect.py
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

"""Inspect utilities for falcon applications."""

from functools import partial
import inspect
from typing import Callable # NOQA: F401
Expand Down Expand Up @@ -89,8 +90,9 @@ def inspect_my_router(router):
def wraps(fn):
if router_class in _supported_routers:
raise ValueError(
'Another function is already registered'
' for the router {}'.format(router_class)
'Another function is already registered for the router {}'.format(
router_class
)
)
_supported_routers[router_class] = fn
return fn
Expand Down
2 changes: 0 additions & 2 deletions falcon/media/multipart.py
Expand Up @@ -272,7 +272,6 @@ def content_type(self):
@property
def filename(self):
if self._filename is None:

if self._content_disposition is None:
value = self._headers.get(b'content-disposition', b'')
self._content_disposition = parse_header(value.decode())
Expand Down Expand Up @@ -308,7 +307,6 @@ def secure_filename(self):
@property
def name(self):
if self._name is None:

if self._content_disposition is None:
value = self._headers.get(b'content-disposition', b'')
self._content_disposition = parse_header(value.decode())
Expand Down
1 change: 0 additions & 1 deletion falcon/middleware.py
Expand Up @@ -108,7 +108,6 @@ def process_response(self, req: Request, resp: Response, resource, req_succeeded
and req.method == 'OPTIONS'
and req.get_header('Access-Control-Request-Method')
):

# NOTE(kgriffs): This is a CORS preflight request. Patch the
# response accordingly.

Expand Down
2 changes: 1 addition & 1 deletion falcon/request_helpers.py
Expand Up @@ -30,7 +30,7 @@
# (see also: https://www.python.org/dev/peps/pep-3333/#unicode-issues)
#
_COOKIE_NAME_RESERVED_CHARS = re.compile(
'[\x00-\x1F\x7F-\xFF()<>@,;:\\\\"/[\\]?={} \x09]'
'[\x00-\x1f\x7f-\xff()<>@,;:\\\\"/[\\]?={} \x09]'
)

# NOTE(kgriffs): strictly speaking, the weakness indicator is
Expand Down
3 changes: 1 addition & 2 deletions falcon/routing/compiled.py
Expand Up @@ -651,8 +651,7 @@ def _compile(self):

src_lines.append(
# PERF(kgriffs): Explicit return of None is faster than implicit
_TAB_STR
+ 'return None'
_TAB_STR + 'return None'
)

self._finder_src = '\n'.join(src_lines)
Expand Down
1 change: 0 additions & 1 deletion falcon/routing/static.py
Expand Up @@ -173,7 +173,6 @@ def __call__(self, req, resp):
or '//' in without_prefix
or len(without_prefix) > self._MAX_NON_PREFIXED_LEN
):

raise falcon.HTTPNotFound()

normalized = os.path.normpath(without_prefix)
Expand Down
2 changes: 0 additions & 2 deletions falcon/testing/client.py
Expand Up @@ -452,7 +452,6 @@ def simulate_request(
asgi_chunk_size=4096,
asgi_disconnect_ttl=300,
) -> _ResultBase:

"""Simulate a request to a WSGI or ASGI application.
Performs a request against a WSGI or ASGI application. In the case of
Expand Down Expand Up @@ -671,7 +670,6 @@ async def _simulate_request_asgi(
_one_shot=True,
_stream_result=False,
) -> _ResultBase:

"""Simulate a request to an ASGI application.
Keyword Args:
Expand Down
3 changes: 0 additions & 3 deletions falcon/testing/helpers.py
Expand Up @@ -864,7 +864,6 @@ def create_scope(
include_server=True,
cookies=None,
) -> Dict[str, Any]:

"""Create a mock ASGI scope ``dict`` for simulating HTTP requests.
Keyword Args:
Expand Down Expand Up @@ -1002,7 +1001,6 @@ def create_scope_ws(
subprotocols=None,
spec_version='2.1',
) -> Dict[str, Any]:

"""Create a mock ASGI scope ``dict`` for simulating WebSocket requests.
Keyword Args:
Expand Down Expand Up @@ -1089,7 +1087,6 @@ def create_environ(
root_path=None,
cookies=None,
) -> Dict[str, Any]:

"""Create a mock PEP-3333 environ ``dict`` for simulating WSGI requests.
Keyword Args:
Expand Down
1 change: 0 additions & 1 deletion falcon/util/deprecation.py
Expand Up @@ -66,7 +66,6 @@ def deprecated(
"""

def decorator(func: Callable[..., Any]) -> Callable[[Callable[..., Any]], Any]:

object_name = 'property' if is_property else 'function'
post_name = '' if is_property else '(...)'
message = 'Call to deprecated {} {}{}. {}'.format(
Expand Down
1 change: 1 addition & 0 deletions falcon/util/misc.py
Expand Up @@ -22,6 +22,7 @@
now = falcon.http_now()
"""

import datetime
import functools
import http
Expand Down
2 changes: 1 addition & 1 deletion falcon/util/reader.py
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

"""Buffered stream reader."""

from __future__ import annotations

import functools
Expand Down Expand Up @@ -189,7 +190,6 @@ def _finalize_read_until(
next_chunk: Optional[bytes] = None,
next_chunk_len: int = 0,
) -> bytes:

if delimiter_pos < 0 and delimiter is not None:
delimiter_pos = self._buffer.find(delimiter, self._buffer_pos)

Expand Down
11 changes: 4 additions & 7 deletions falcon/util/structures.py
Expand Up @@ -25,6 +25,7 @@
things = falcon.CaseInsensitiveDict()
"""

from __future__ import annotations

from collections.abc import Mapping
Expand Down Expand Up @@ -146,14 +147,11 @@ class Context:
# merely to let mypy know this is a namespace object.
if TYPE_CHECKING:

def __getattr__(self, name: str) -> Any:
...
def __getattr__(self, name: str) -> Any: ...

def __setattr__(self, name: str, value: Any) -> None:
...
def __setattr__(self, name: str, value: Any) -> None: ...

def __delattr__(self, name: str) -> None:
...
def __delattr__(self, name: str) -> None: ...

def __contains__(self, key: str) -> bool:
return self.__dict__.__contains__(key)
Expand Down Expand Up @@ -217,7 +215,6 @@ def pop(self, key: str, default: Optional[Any] = None) -> Optional[Any]:
return self.__dict__.pop(key, default)

def popitem(self) -> Tuple[str, Any]:

return self.__dict__.popitem()

def setdefault(
Expand Down
2 changes: 1 addition & 1 deletion falcon/util/sync.py
Expand Up @@ -198,7 +198,7 @@ def _should_wrap_non_coroutines() -> bool:


def _wrap_non_coroutine_unsafe(
func: Optional[Callable[..., Any]]
func: Optional[Callable[..., Any]],
) -> Union[Callable[..., Awaitable[Any]], Callable[..., Any], None]:
"""Wrap a coroutine using ``wrap_sync_to_async_unsafe()`` for internal test cases.
Expand Down
3 changes: 1 addition & 2 deletions falcon/util/uri.py
Expand Up @@ -22,6 +22,7 @@
name, port = uri.parse_host('example.org:8080')
"""

from typing import Callable
from typing import Dict
from typing import List
Expand Down Expand Up @@ -57,7 +58,6 @@


def _create_char_encoder(allowed_chars: str) -> Callable[[int], str]:

lookup = {}

for code_point in range(256):
Expand All @@ -74,7 +74,6 @@ def _create_char_encoder(allowed_chars: str) -> Callable[[int], str]:
def _create_str_encoder(
is_value: bool, check_is_escaped: bool = False
) -> Callable[[str], str]:

allowed_chars = _UNRESERVED if is_value else _ALL_ALLOWED
allowed_chars_plus_percent = allowed_chars + '%'
encode_char = _create_char_encoder(allowed_chars)
Expand Down
9 changes: 9 additions & 0 deletions pyproject.toml
Expand Up @@ -82,10 +82,19 @@
extend-exclude = "falcon/vendor"

[tool.blue]
# NOTE(vytas): Before switching to Ruff, Falcon used the Blue formatter.
# With the below settings, accidentally running blue should yield
# only minor cosmetic changes in a handful of files.
target-version = ["py37"]
line-length = 88
extend-exclude = "falcon/vendor"

[tool.ruff]
target-version = "py37"
format.quote-style = "single"
line-length = 88
extend-exclude = ["falcon/vendor"]

[tool.pytest.ini_options]
filterwarnings = [
"ignore:Unknown REQUEST_METHOD. '(CONNECT|DELETE|GET|HEAD|OPTIONS|PATCH|POST|PUT|TRACE|CHECKIN|CHECKOUT|COPY|LOCK|MKCOL|MOVE|PROPFIND|PROPPATCH|REPORT|UNCHECKIN|UNLOCK|UPDATE|VERSION-CONTROL)':wsgiref.validate.WSGIWarning",
Expand Down
1 change: 0 additions & 1 deletion setup.py
Expand Up @@ -139,7 +139,6 @@ def load_description():

# NOTE(kgriffs): PyPI does not support the raw directive
for readme_line in io.open('README.rst', 'r', encoding='utf-8'):

# NOTE(vytas): The patron list largely builds upon raw sections
if readme_line.startswith('.. Patron list starts'):
in_patron_list = True
Expand Down
8 changes: 4 additions & 4 deletions tests/asgi/test_boundedstream_asgi.py
Expand Up @@ -11,9 +11,9 @@
[
b'',
b'\x00',
b'\x00\xFF',
b'\x00\xff',
b'catsup',
b'\xDE\xAD\xBE\xEF' * 512,
b'\xde\xad\xbe\xef' * 512,
testing.rand_string(1, 2048),
os.urandom(100 * 2**20),
],
Expand Down Expand Up @@ -193,9 +193,9 @@ async def receive():
[
b'',
b'\x00',
b'\x00\xFF',
b'\x00\xff',
b'catsup',
b'\xDE\xAD\xBE\xEF' * 512,
b'\xde\xad\xbe\xef' * 512,
testing.rand_string(1, 2048).encode(),
],
ids=['empty', 'null', 'null-ff', 'normal', 'long', 'random'],
Expand Down
1 change: 0 additions & 1 deletion tests/asgi/test_example_asgi.py
Expand Up @@ -27,7 +27,6 @@ async def handle(ex, req, resp, params):


class SinkAdapter:

engines = {
'ddg': 'https://duckduckgo.com',
'y': 'https://search.yahoo.com/search',
Expand Down
2 changes: 0 additions & 2 deletions tests/asgi/test_request_context_asgi.py
Expand Up @@ -20,7 +20,6 @@ def test_default_request_context(
assert req.context.get('note') == req.context['note']

def test_custom_request_context(self):

# Define a Request-alike with a custom context type
class MyCustomContextType:
pass
Expand All @@ -32,7 +31,6 @@ class MyCustomRequest(Request):
assert isinstance(req.context, MyCustomContextType)

def test_custom_request_context_failure(self):

# Define a Request-alike with a non-callable custom context type
class MyCustomRequest(Request):
context_type = False
Expand Down

0 comments on commit e619c39

Please sign in to comment.