Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch from flake8 to ruff #414

Merged
merged 6 commits into from
May 29, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 0 additions & 16 deletions .flake8

This file was deleted.

11 changes: 3 additions & 8 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ permissions:
contents: read

env:
FORCE_COLOR: 1
PIP_DISABLE_PIP_VERSION_CHECK: 1

concurrency:
Expand Down Expand Up @@ -99,16 +100,10 @@ jobs:
python-version: "3"
cache: "pip"
cache-dependency-path: "test-requirements.txt"

- name: Install dependencies
run: |
pip install -r test-requirements.txt
# not included in test-requirements.txt as it depends on typing-extensions,
# so it's a pain to have it installed locally
pip install flake8-noqa

run: pip install -r test-requirements.txt
- name: Lint implementation
run: flake8 --color always
run: ruff check

create-issue-on-failure:
name: Create an issue if daily tests failed
Expand Down
3 changes: 2 additions & 1 deletion doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@

import os.path
import sys
from sphinx.writers.html5 import HTML5Translator

from docutils.nodes import Element
from sphinx.writers.html5 import HTML5Translator

sys.path.insert(0, os.path.abspath('.'))

Expand Down
37 changes: 37 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,40 @@ email = "[email protected]"
[tool.flit.sdist]
include = ["CHANGELOG.md", "README.md", "tox.ini", "*/*test*.py"]
exclude = []

[tool.ruff]
line-length = 90
target-version = "py38"
fix = true
AlexWaygood marked this conversation as resolved.
Show resolved Hide resolved

[tool.ruff.lint]
select = [
"B",
"C4",
"E",
"F",
"I",
"ISC001",
"PGH004",
"RUF",
"SIM201",
"SIM202",
"UP",
"W",
]

[tool.ruff.lint.per-file-ignores]
"!src/typing_extensions.py" = [
"B018",
"B024",
"C4",
"E302",
"E306",
"E501",
"E701",
"UP",
]

[tool.ruff.lint.isort]
extra-standard-library = ["tomllib"]
known-first-party = ["typing_extensions", "_typed_dict_test_helper"]
3 changes: 2 additions & 1 deletion src/_typed_dict_test_helper.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from __future__ import annotations

from typing import Generic, Optional, T
from typing_extensions import TypedDict, Annotated, Required

from typing_extensions import Annotated, Required, TypedDict


# this class must not be imported into test_typing_extensions.py at top level, otherwise
Expand Down
106 changes: 82 additions & 24 deletions src/test_typing_extensions.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,97 @@
import sys
import abc
import gc
import io
import contextlib
import collections
from collections import defaultdict
import collections.abc
import contextlib
import copy
from functools import lru_cache
import gc
import importlib
import inspect
import io
import pickle
import re
import subprocess
import sys
import tempfile
import textwrap
import types
from pathlib import Path
from unittest import TestCase, main, skipUnless, skipIf
from unittest.mock import patch
import typing
import warnings
from collections import defaultdict
from functools import lru_cache
from pathlib import Path
from unittest import TestCase, main, skipIf, skipUnless
from unittest.mock import patch

import typing_extensions
from typing_extensions import NoReturn, Any, ClassVar, Final, IntVar, Literal, Type, NewType, TypedDict, Self
from typing_extensions import TypeAlias, ParamSpec, Concatenate, ParamSpecArgs, ParamSpecKwargs, TypeGuard
from typing_extensions import Awaitable, AsyncIterator, AsyncContextManager, Required, NotRequired, ReadOnly
from typing_extensions import Protocol, runtime, runtime_checkable, Annotated, final, is_typeddict
from typing_extensions import TypeVarTuple, Unpack, dataclass_transform, reveal_type, Never, assert_never, LiteralString
from typing_extensions import assert_type, get_type_hints, get_origin, get_args, get_original_bases
from typing_extensions import clear_overloads, get_overloads, overload, Iterator
from typing_extensions import NamedTuple, TypeIs, no_type_check, Dict
from typing_extensions import override, deprecated, Buffer, TypeAliasType, TypeVar, get_protocol_members, is_protocol
from typing_extensions import Doc, NoDefault, List, Union, AnyStr, Iterable, Generic, Optional, Set, Tuple, Callable
from _typed_dict_test_helper import Foo, FooGeneric, VeryAnnotated
from typing_extensions import (
Annotated,
Any,
AnyStr,
AsyncContextManager,
AsyncIterator,
Awaitable,
Buffer,
Callable,
ClassVar,
Concatenate,
Dict,
Doc,
Final,
Generic,
IntVar,
Iterable,
Iterator,
List,
Literal,
LiteralString,
NamedTuple,
Never,
NewType,
NoDefault,
NoReturn,
NotRequired,
Optional,
ParamSpec,
ParamSpecArgs,
ParamSpecKwargs,
Protocol,
ReadOnly,
Required,
Self,
Set,
Tuple,
Type,
TypeAlias,
TypeAliasType,
TypedDict,
TypeGuard,
TypeIs,
TypeVar,
TypeVarTuple,
Union,
Unpack,
assert_never,
assert_type,
clear_overloads,
dataclass_transform,
deprecated,
final,
get_args,
get_origin,
get_original_bases,
get_overloads,
get_protocol_members,
get_type_hints,
is_protocol,
is_typeddict,
no_type_check,
overload,
override,
reveal_type,
runtime,
runtime_checkable,
)

NoneType = type(None)
T = TypeVar("T")
Expand Down Expand Up @@ -179,14 +237,14 @@ def g_bad_ann():
class BaseTestCase(TestCase):
def assertIsSubclass(self, cls, class_or_tuple, msg=None):
if not issubclass(cls, class_or_tuple):
message = f'{cls!r} is not a subclass of {repr(class_or_tuple)}'
message = f'{cls!r} is not a subclass of {class_or_tuple!r}'
if msg is not None:
message += f' : {msg}'
raise self.failureException(message)

def assertNotIsSubclass(self, cls, class_or_tuple, msg=None):
if issubclass(cls, class_or_tuple):
message = f'{cls!r} is a subclass of {repr(class_or_tuple)}'
message = f'{cls!r} is a subclass of {class_or_tuple!r}'
if msg is not None:
message += f' : {msg}'
raise self.failureException(message)
Expand Down Expand Up @@ -2988,7 +3046,7 @@ class NonP(P):
class NonPR(PR): pass
class C(metaclass=abc.ABCMeta):
x = 1
class D(metaclass=abc.ABCMeta): # noqa: B024
class D(metaclass=abc.ABCMeta):
def meth(self): pass # noqa: B027
self.assertNotIsInstance(C(), NonP)
self.assertNotIsInstance(D(), NonPR)
Expand Down Expand Up @@ -6312,8 +6370,8 @@ def test_or(self):
X = TypeVar('X')
# use a string because str doesn't implement
# __or__/__ror__ itself
self.assertEqual(X | "x", Union[X, "x"]) # noqa: F821
self.assertEqual("x" | X, Union["x", X]) # noqa: F821
self.assertEqual(X | "x", Union[X, "x"])
self.assertEqual("x" | X, Union["x", X])
# make sure the order is correct
self.assertEqual(get_args(X | "x"), (X, typing.ForwardRef("x")))
self.assertEqual(get_args("x" | X), (typing.ForwardRef("x"), X))
Expand Down
16 changes: 8 additions & 8 deletions src/typing_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,12 +413,12 @@ def clear_overloads():
OrderedDict = typing.OrderedDict
Counter = typing.Counter
ChainMap = typing.ChainMap
Text = typing.Text
Text = typing.Text # noqa: UP019
AlexWaygood marked this conversation as resolved.
Show resolved Hide resolved
TYPE_CHECKING = typing.TYPE_CHECKING


if sys.version_info >= (3, 13, 0, "beta"):
from typing import ContextManager, AsyncContextManager, Generator, AsyncGenerator
from typing import AsyncContextManager, AsyncGenerator, ContextManager, Generator
else:
def _is_dunder(attr):
return attr.startswith('__') and attr.endswith('__')
Expand Down Expand Up @@ -739,8 +739,8 @@ def close(self): ...
not their type signatures!
"""
if not issubclass(cls, typing.Generic) or not getattr(cls, '_is_protocol', False):
raise TypeError('@runtime_checkable can be only applied to protocol classes,'
' got %r' % cls)
raise TypeError(f'@runtime_checkable can be only applied to protocol classes,'
f' got {cls!r}')
cls._is_runtime_protocol = True

# typing.Protocol classes on <=3.11 break if we execute this block,
Expand Down Expand Up @@ -1271,7 +1271,7 @@ def __repr__(self):

def __reduce__(self):
return operator.getitem, (
Annotated, (self.__origin__,) + self.__metadata__
Annotated, (self.__origin__, *self.__metadata__)
)

def __eq__(self, other):
Expand Down Expand Up @@ -1397,7 +1397,7 @@ def get_args(tp):
get_args(Callable[[], T][int]) == ([], int)
"""
if isinstance(tp, _AnnotatedAlias):
return (tp.__origin__,) + tp.__metadata__
return (tp.__origin__, *tp.__metadata__)
if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):
if getattr(tp, "_special", False):
return ()
Expand Down Expand Up @@ -1811,7 +1811,7 @@ def _concatenate_getitem(self, parameters):
# 3.10+
if hasattr(typing, 'Concatenate'):
Concatenate = typing.Concatenate
_ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa: F811
_ConcatenateGenericAlias = typing._ConcatenateGenericAlias
# 3.9
elif sys.version_info[:2] >= (3, 9):
@_ExtensionsSpecialForm
Expand Down Expand Up @@ -3248,7 +3248,7 @@ class Employee(NamedTuple):
if hasattr(collections.abc, "Buffer"):
Buffer = collections.abc.Buffer
else:
class Buffer(abc.ABC):
class Buffer(abc.ABC): # noqa: B024
"""Base class for classes that implement the buffer protocol.

The buffer protocol allows Python objects to expose a low-level
Expand Down
3 changes: 1 addition & 2 deletions test-requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
flake8
flake8-bugbear
ruff==0.4.5
Loading