Skip to content

Commit 3bb755d

Browse files
authored
Merge pull request #247 from pytest-dev/remove-typing-any
Remove usages of `typing.Any`
2 parents 892bb79 + 3627e88 commit 3bb755d

File tree

4 files changed

+52
-41
lines changed

4 files changed

+52
-41
lines changed

src/pytest_factoryboy/fixture.py

Lines changed: 36 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from dataclasses import dataclass
1111
from inspect import signature
1212
from types import MethodType
13-
from typing import TYPE_CHECKING, Any, Callable, Generic, TypeVar, cast, overload
13+
from typing import TYPE_CHECKING, Callable, Generic, TypeVar, cast, overload
1414

1515
import factory
1616
import factory.enums
@@ -45,13 +45,13 @@
4545

4646

4747
@dataclass(eq=False)
48-
class DeferredFunction(Generic[T]):
48+
class DeferredFunction(Generic[T, U]):
4949
name: str
5050
factory: type[Factory[T]]
5151
is_related: bool
52-
function: Callable[[SubRequest], Any]
52+
function: Callable[[SubRequest], U]
5353

54-
def __call__(self, request: SubRequest) -> Any:
54+
def __call__(self, request: SubRequest) -> U:
5555
return self.function(request)
5656

5757

@@ -76,21 +76,33 @@ def named_model(model_cls: type[T], name: str) -> type[T]:
7676
# @register
7777
# class AuthorFactory(Factory): ...
7878
@overload
79-
def register(factory_class: type[Factory[T]], _name: str | None = None, **kwargs: Any) -> type[Factory[T]]: ...
79+
def register(
80+
factory_class: type[Factory[T]],
81+
_name: str | None = ...,
82+
*,
83+
_caller_locals: Box[dict[str, object]] | None = ...,
84+
**kwargs: object,
85+
) -> type[Factory[T]]: ...
8086

8187

8288
# @register(...)
8389
# class AuthorFactory(Factory): ...
8490
@overload
85-
def register(*, _name: str | None = None, **kwargs: Any) -> Callable[[type[Factory[T]]], type[Factory[T]]]: ...
91+
def register(
92+
factory_class: None,
93+
_name: str | None = ...,
94+
*,
95+
_caller_locals: Box[dict[str, object]] | None = ...,
96+
**kwargs: object,
97+
) -> Callable[[type[Factory[T]]], type[Factory[T]]]: ...
8698

8799

88100
def register(
89101
factory_class: type[Factory[T]] | None = None,
90102
_name: str | None = None,
91103
*,
92-
_caller_locals: Box[dict[str, Any]] | None = None,
93-
**kwargs: Any,
104+
_caller_locals: Box[dict[str, object]] | None = None,
105+
**kwargs: object,
94106
) -> type[Factory[T]] | Callable[[type[Factory[T]]], type[Factory[T]]]:
95107
r"""Register fixtures for the factory class.
96108
@@ -141,9 +153,9 @@ def generate_fixtures(
141153
factory_class: type[Factory[T]],
142154
model_name: str,
143155
factory_name: str,
144-
overrides: Mapping[str, Any],
145-
caller_locals: Box[Mapping[str, Any]],
146-
) -> Iterable[tuple[str, Callable[..., Any]]]:
156+
overrides: Mapping[str, object],
157+
caller_locals: Box[Mapping[str, object]],
158+
) -> Iterable[tuple[str, Callable[..., object]]]:
147159
"""Generate all the FixtureDefs for the given factory class."""
148160

149161
related: list[str] = []
@@ -199,10 +211,10 @@ def create_fixture_with_related(
199211

200212
def make_declaration_fixturedef(
201213
attr_name: str,
202-
value: Any,
214+
value: object,
203215
factory_class: type[Factory[T]],
204216
related: list[str],
205-
) -> Callable[..., Any]:
217+
) -> Callable[[SubRequest], object]:
206218
"""Create the FixtureDef for a factory declaration."""
207219
if isinstance(value, (SubFactory, RelatedFactory)):
208220
subfactory_class: type[Factory[object]] = value.get_factory()
@@ -246,7 +258,7 @@ def make_declaration_fixturedef(
246258
)
247259

248260

249-
def inject_into_caller(name: str, function: Callable[..., Any], locals_: Box[dict[str, Any]]) -> None:
261+
def inject_into_caller(name: str, function: Callable[..., object], locals_: Box[dict[str, object]]) -> None:
250262
"""Inject a function into the caller's locals, making sure that the function will work also within classes."""
251263
# We need to check if the caller frame is a class, since in that case the first argument is the class itself.
252264
# In that case, we can apply the staticmethod() decorator to the injected function, so that the first param
@@ -302,7 +314,7 @@ def get_deps(
302314
model_name = get_model_name(factory_class) if model_name is None else model_name
303315
parent_model_name = get_model_name(parent_factory_class) if parent_factory_class is not None else None
304316

305-
def is_dep(value: Any) -> bool:
317+
def is_dep(value: object) -> bool:
306318
if isinstance(value, RelatedFactory):
307319
return False
308320
if isinstance(value, SubFactory):
@@ -325,7 +337,7 @@ def evaluate(request: SubRequest, value: LazyFixture[T] | T) -> T:
325337
return value.evaluate(request) if isinstance(value, LazyFixture) else value
326338

327339

328-
def noop(*args: Any, **kwargs: Any) -> None:
340+
def noop(*args: object, **kwargs: object) -> None:
329341
"""No-op function."""
330342
pass
331343

@@ -388,7 +400,7 @@ def model_fixture(request: SubRequest, factory_name: str) -> object:
388400
request._fixture_defs[fixture_name] = request._fixturedef
389401

390402
# Defer post-generation declarations
391-
deferred: list[DeferredFunction[object]] = []
403+
deferred: list[DeferredFunction[object, object]] = []
392404

393405
for attr in factory_class._meta.post_declarations.sorted():
394406
decl = factory_class._meta.post_declarations.declarations[attr]
@@ -427,7 +439,7 @@ def model_fixture(request: SubRequest, factory_name: str) -> object:
427439
return instance
428440

429441

430-
def make_deferred_related(factory: type[Factory[T]], fixture: str, attr: str) -> DeferredFunction[T]:
442+
def make_deferred_related(factory: type[Factory[T]], fixture: str, attr: str) -> DeferredFunction[T, object]:
431443
"""Make deferred function for the related factory declaration.
432444
433445
:param factory: Factory class.
@@ -438,7 +450,7 @@ def make_deferred_related(factory: type[Factory[T]], fixture: str, attr: str) ->
438450
"""
439451
name = SEPARATOR.join((fixture, attr))
440452

441-
def deferred_impl(request: SubRequest) -> Any:
453+
def deferred_impl(request: SubRequest) -> object:
442454
return request.getfixturevalue(name)
443455

444456
return DeferredFunction(
@@ -453,11 +465,11 @@ def make_deferred_postgen(
453465
step: BuildStep,
454466
factory_class: type[Factory[T]],
455467
fixture: str,
456-
instance: Any,
468+
instance: T,
457469
attr: str,
458470
declaration: PostGenerationDeclaration,
459471
context: PostGenerationContext,
460-
) -> DeferredFunction[T]:
472+
) -> DeferredFunction[T, object]:
461473
"""Make deferred function for the post-generation declaration.
462474
463475
:param step: factory_boy builder step.
@@ -472,7 +484,7 @@ def make_deferred_postgen(
472484
"""
473485
name = SEPARATOR.join((fixture, attr))
474486

475-
def deferred_impl(request: SubRequest) -> Any:
487+
def deferred_impl(request: SubRequest) -> object:
476488
return declaration.call(instance, step, context)
477489

478490
return DeferredFunction(
@@ -493,13 +505,13 @@ def attr_fixture(request: SubRequest, value: T) -> T:
493505
return value
494506

495507

496-
def subfactory_fixture(request: SubRequest, factory_class: type[Factory[object]]) -> Any:
508+
def subfactory_fixture(request: SubRequest, factory_class: type[Factory[object]]) -> object:
497509
"""SubFactory/RelatedFactory fixture implementation."""
498510
fixture = inflection.underscore(factory_class._meta.model.__name__)
499511
return request.getfixturevalue(fixture)
500512

501513

502-
def get_caller_locals(depth: int = 0) -> dict[str, Any]:
514+
def get_caller_locals(depth: int = 0) -> dict[str, object]:
503515
"""Get the local namespace of the caller frame."""
504516
return sys._getframe(depth + 2).f_locals
505517

src/pytest_factoryboy/plugin.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
from __future__ import annotations
44

55
from collections import defaultdict
6-
from typing import Any
76

87
import pytest
98
from _pytest.config import PytestPluginManager
@@ -25,12 +24,12 @@ class Request:
2524

2625
def __init__(self) -> None:
2726
"""Create pytest_factoryboy request."""
28-
self.deferred: list[list[DeferredFunction[object]]] = []
29-
self.results: dict[str, dict[str, Any]] = defaultdict(dict)
27+
self.deferred: list[list[DeferredFunction[object, object]]] = []
28+
self.results: dict[str, dict[str, object]] = defaultdict(dict)
3029
self.model_factories: dict[str, type[Factory[object]]] = {}
31-
self.in_progress: set[DeferredFunction[object]] = set()
30+
self.in_progress: set[DeferredFunction[object, object]] = set()
3231

33-
def defer(self, functions: list[DeferredFunction[object]]) -> None:
32+
def defer(self, functions: list[DeferredFunction[object, object]]) -> None:
3433
"""Defer post-generation declaration execution until the end of the test setup.
3534
3635
:param functions: Functions to be deferred.
@@ -65,7 +64,10 @@ def get_current_deps(self, request: FixtureRequest | SubRequest) -> set[str]:
6564
return deps
6665

6766
def execute(
68-
self, request: SubRequest, function: DeferredFunction[object], deferred: list[DeferredFunction[object]]
67+
self,
68+
request: SubRequest,
69+
function: DeferredFunction[object, object],
70+
deferred: list[DeferredFunction[object, object]],
6971
) -> None:
7072
"""Execute deferred function and store the result."""
7173
if function in self.in_progress:

tests/test_factory_fixtures.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,6 @@
1212
from pytest_factoryboy import LazyFixture, register
1313

1414
if TYPE_CHECKING:
15-
from typing import Any
16-
1715
from factory.declarations import LazyAttribute
1816

1917

@@ -77,7 +75,7 @@ class Meta:
7775
register_user__password = "qwerty" # Make sure fixture is generated
7876

7977
@factory.post_generation
80-
def register_user(author: Author, create: bool, username: str | None, **kwargs: Any) -> None:
78+
def register_user(author: Author, create: bool, username: str | None, **kwargs: object) -> None:
8179
"""Register author as a user in the system."""
8280
if username is not None:
8381
author.user = UserFactory(username=username, **kwargs)

tests/test_postgen_dependencies.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
from collections.abc import Mapping
56
from dataclasses import dataclass, field
67
from typing import TYPE_CHECKING
78

@@ -12,8 +13,6 @@
1213
from pytest_factoryboy import register
1314

1415
if TYPE_CHECKING:
15-
from typing import Any
16-
1716
from pytest_factoryboy.plugin import Request
1817

1918

@@ -34,7 +33,7 @@ def set_number(self, new_number: int = 987) -> None:
3433

3534
# NOTE: following attributes are used internally only for assertions
3635
_create: bool | None = None
37-
_postgeneration_results: dict[str, Any] = field(default_factory=dict)
36+
_postgeneration_results: dict[str, object] = field(default_factory=dict)
3837

3938

4039
@dataclass
@@ -70,7 +69,7 @@ class Meta:
7069
number = factory.PostGenerationMethodCall("set_number")
7170

7271
@factory.post_generation
73-
def set1(foo: Foo, create: bool, value: Any, **kwargs: Any) -> str:
72+
def set1(foo: Foo, create: bool, value: object, **kwargs: object) -> str:
7473
foo.value = 1
7574
return "set to 1"
7675

@@ -82,7 +81,7 @@ def set2(foo, create, value, **kwargs):
8281
foo.value = value
8382

8483
@classmethod
85-
def _after_postgeneration(cls, obj: Foo, create: bool, results: dict[str, Any] | None = None) -> None:
84+
def _after_postgeneration(cls, obj: Foo, create: bool, results: Mapping[str, object] | None = None) -> None:
8685
obj._postgeneration_results = results or {}
8786
obj._create = create
8887

@@ -190,7 +189,7 @@ class Meta:
190189

191190
@classmethod
192191
def _after_postgeneration(
193-
cls, obj: dict[str, Any], create: bool, results: dict[str, Any] | None = None
192+
cls, obj: Mapping[str, object], create: bool, results: Mapping[str, object] | None = None
194193
) -> None:
195194
obj.setdefault("_after_postgeneration_calls", []).append((obj, create, results))
196195

@@ -218,11 +217,11 @@ class Meta:
218217
model = Ordered
219218

220219
@factory.post_generation
221-
def zzz(obj: Ordered, create: bool, val: Any, **kwargs: Any) -> None:
220+
def zzz(obj: Ordered, create: bool, val: object, **kwargs: object) -> None:
222221
obj.value = "zzz"
223222

224223
@factory.post_generation
225-
def aaa(obj: Ordered, create: bool, val: Any, **kwargs: Any) -> None:
224+
def aaa(obj: Ordered, create: bool, val: object, **kwargs: object) -> None:
226225
obj.value = "aaa"
227226

228227

0 commit comments

Comments
 (0)