Circumventing `Name "_" already defined` mypy error
See original GitHub issueMypy really hates the pattern of naming every test like def _():
and errors on every Ward test with the message Name "_" already defined on line 79 [no-redef]
.
Type checking tests still often makes sense, so we should come up with a good way to circumvent the error and document that. Best would perhaps be if mypy had a configuration option to disable this specific error only, and only disable it in a test directory. That doesn’t seem to be possible though.
Adding a # type: ignore[no-redef]
after each @test
decorator line works but is a bit laborious. Maybe make an auto-formatter (supporting pre-commit framework) that adds these ignore comments? Or even better, maybe there’s a way to make a mypy plugin that tricks mypy into thinking these comments are in place, even if they really aren’t (less clutter in the codebase).
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (4 by maintainers)
Top GitHub Comments
As a temporary solution I’ve found out that configuring
works well.
Unfortunately it seems that it can not be configured on a per module basis, so it will disable
no-redef
checks globally outside the test directory as well. One way to get around this limitation is using a separate command line invocation for tests and then using the CLI argument instead of configuration file:Alternatively, if using
pre-commit
to runmypy
, it is possible to configure two separate mypy invocations in.pre-commit-config.yaml
as well.This was recently fixed in mypy master:
A quick loosely related question (happy to move it to a separate issue):
Do you have plans for allowing strict type-checking of tests using the default argument syntax? The issue I see here is that the parameter should be annotated with the type of the value injected into the test, but the default argument has the type of the fixture that provides the value. It seems analogous to how dataclasses.field works, and would probably require a mypy plugin as well?