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

Issue 3265: Add WPS476 SneakyTypeVarWithDefaultViolation #3314

Open
wants to merge 20 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
e4c5c98
Resolve #3265: add WPS476 TypeVarTupleFollowsTypeVarWithDefaultViolat…
Tapeline Feb 10, 2025
632171d
Refactoring: split classes.py into submodules. Change naming
Tapeline Feb 20, 2025
8b2c65a
Merge branch 'master' into issue-3265
Tapeline Feb 20, 2025
4f3bd91
Transfer changes from classes.py to classes/methods.py
Tapeline Feb 20, 2025
c48d615
Update CHANGELOG.md
Tapeline Feb 20, 2025
57530d2
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Feb 20, 2025
48ce42e
Fix WPS linting and CI build issues
Tapeline Feb 20, 2025
f016624
Merge remote-tracking branch 'origin/issue-3265' into issue-3265
Tapeline Feb 20, 2025
5a03e99
Fix WPS linting and CI build issues
Tapeline Feb 20, 2025
990c9de
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Feb 20, 2025
e12ae40
Fix CI build issues and compatibility issues
Tapeline Feb 20, 2025
3061b70
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Feb 20, 2025
3f6e072
Fix CI build issues and compatibility issues
Tapeline Feb 20, 2025
41c7e05
Merge remote-tracking branch 'origin/issue-3265' into issue-3265
Tapeline Feb 20, 2025
b31d45a
Change rule behaviour: support only 3.13+ typevars. Change tests
Tapeline Feb 27, 2025
06b55b4
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Feb 27, 2025
cc68e6b
Add python versioning conditions on tests
Tapeline Feb 27, 2025
f5b0eea
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Feb 27, 2025
ef34b32
Adjust test skipping
Tapeline Feb 27, 2025
082b819
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Feb 27, 2025
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ Semantic versioning in our case means:

## 1.1.0 WIP

### Rules

- Adds `WPS476`: do not allow `TypeVarTuple` after a `TypeVar` with a default #3265

### Command line utility

This version introduces `wps` CLI tool.
Expand Down
14 changes: 14 additions & 0 deletions tests/fixtures/noqa/noqa.py
Original file line number Diff line number Diff line change
Expand Up @@ -747,3 +747,17 @@ def my_function():

def pos_only_problem(first_argpm=0, second_argpm=1, /): # noqa: WPS475
my_print(first_argpm, second_argpm)


TypeVarDefault = TypeVar("T", default=int)
FollowingTuple = TypeVarTuple("Ts")


class NewStyleGenerics[TypeVarDefault, *FollowingTuple]: # noqa: WPS476
...


class OldStyleGenerics(
Generic[TypeVarDefault, *FollowingTuple] # noqa: WPS476
):
...
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
from typing import Final

import pytest

from wemake_python_styleguide.violations.best_practices import (
SneakyTypeVarWithDefaultViolation,
)
from wemake_python_styleguide.visitors.ast.classes.classdef import (
ConsecutiveDefaultTypeVarsVisitor,
)

class_header_formats: Final[list[str]] = ['Class[{0}]', 'Class(Generic[{0}])']
various_code: Final[str] = (
'pi = 3.14\n'
'a = obj.method_call()\n'
'w, h = get_size()\n'
'obj.field = function_call()\n'
'AlmostTypeVar = NotReallyATypeVar()\n'
"NonDefault = TypeVar('NonDefault')\n"
)
classes_with_various_bases: Final[str] = (
'class SimpleBase(object): ...\n'
'class NotANameSubscript(Some.Class[object]): ...\n'
'class NotAGenericBase(NotAGeneric[T]): ...\n'
'class GenericButNotMultiple(Generic[T]): ...\n'
)


@pytest.mark.parametrize(
'class_header_format',
class_header_formats,
)
def test_sneaky_type_var_with_default(
assert_errors,
parse_ast_tree,
default_options,
class_header_format,
):
"""Test that WPS476 works correctly."""
class_header = class_header_format.format('T, *Ts')
src = (
f'{various_code}\n'
f'{classes_with_various_bases}\n'
"T = TypeVar('T', default=int)\n"
"Ts = TypeVarTuple('Ts')\n"
'\n'
f'class {class_header}:\n'
' ...'
)

tree = parse_ast_tree(src)

visitor = ConsecutiveDefaultTypeVarsVisitor(default_options, tree=tree)
visitor.run()

assert_errors(visitor, [SneakyTypeVarWithDefaultViolation])


@pytest.mark.parametrize(
'class_header_format',
class_header_formats,
)
def test_sneaky_type_var_without_default(
assert_errors,
parse_ast_tree,
default_options,
class_header_format,
):
"""Test that WPS476 ignores non-defaulted TypeVars."""
class_header = class_header_format.format('T, *Ts')
src = (
f'{various_code}\n'
f'{classes_with_various_bases}\n'
"T = TypeVar('T')\n"
"Ts = TypeVarTuple('Ts')\n"
'\n'
f'class {class_header}:\n'
' ...'
)

tree = parse_ast_tree(src)

visitor = ConsecutiveDefaultTypeVarsVisitor(default_options, tree=tree)
visitor.run()

assert_errors(visitor, [])
17 changes: 17 additions & 0 deletions wemake_python_styleguide/compat/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,20 @@ class TypeAlias(ast.stmt):
name: ast.Name
type_params: list[ast.stmt]
value: ast.expr # noqa: WPS110


if sys.version_info >= (3, 12): # pragma: >=3.12 cover
from ast import TypeVar as TypeVar
from ast import TypeVarTuple as TypeVarTuple
else: # pragma: <3.12 cover

class TypeVar(ast.AST):
"""Used to define `TypeVar` nodes from `python3.12+`."""

name: str
bound: ast.expr | None # noqa: WPS110

class TypeVarTuple(ast.AST):
"""Used to define `TypeVarTuple` nodes from `python3.12+`."""

name: str
19 changes: 19 additions & 0 deletions wemake_python_styleguide/presets/topics/classes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from typing import Final

from wemake_python_styleguide.visitors.ast.classes import (
attributes,
classdef,
methods,
)

#: Used to store all classes related visitors to be later passed to checker:
PRESET: Final = (
classdef.WrongClassDefVisitor,
classdef.WrongClassBodyVisitor,
attributes.ClassAttributeVisitor,
attributes.WrongSlotsVisitor,
methods.WrongMethodVisitor,
methods.ClassMethodOrderVisitor,
methods.BuggySuperCallVisitor,
classdef.ConsecutiveDefaultTypeVarsVisitor,
)
11 changes: 2 additions & 9 deletions wemake_python_styleguide/presets/types/tree.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
from typing import Final

from wemake_python_styleguide.presets.topics import complexity, naming
from wemake_python_styleguide.presets.topics import classes, complexity, naming
from wemake_python_styleguide.visitors.ast import ( # noqa: WPS235
blocks,
builtins,
classes,
compares,
conditions,
decorators,
Expand Down Expand Up @@ -70,13 +69,6 @@
conditions.MatchVisitor,
conditions.ChainedIsVisitor,
iterables.IterableUnpackingVisitor,
classes.WrongClassDefVisitor,
classes.WrongClassBodyVisitor,
classes.WrongMethodVisitor,
classes.WrongSlotsVisitor,
classes.ClassAttributeVisitor,
classes.ClassMethodOrderVisitor,
classes.BuggySuperCallVisitor,
blocks.AfterBlockVariablesVisitor,
subscripts.SubscriptVisitor,
subscripts.ImplicitDictGetVisitor,
Expand All @@ -91,4 +83,5 @@
# Topics:
*complexity.PRESET,
*naming.PRESET,
*classes.PRESET,
)
37 changes: 37 additions & 0 deletions wemake_python_styleguide/violations/best_practices.py
Original file line number Diff line number Diff line change
Expand Up @@ -2968,3 +2968,40 @@ def function(first=0, *args): ...

error_template = 'Found problematic function parameters'
code = 475


@final
class SneakyTypeVarWithDefaultViolation(ASTViolation):
"""
Forbid using TypeVarTuple after a TypeVar with default.

Reasoning:
Following a defaulted TypeVar with a TypeVarTuple is bad,
because you cannot specify the TypeVarTuple without
specifying TypeVar.

Solution:
Consider refactoring and getting rid of that pattern.

Example::

# Wrong:
T = TypeVar("T", default=int)
class Class[T, *Ts]:
...

# Correct (no default):
class Class[T, *Ts]:
...

# Correct (no tuple):
T = TypeVar("T", default=int)
class Class[T]:
...

.. versionadded:: 1.1.0

"""

error_template = 'Found a TypeVarTuple following a TypeVar with default'
code = 476
Loading
Loading