Dmytro Striletskyi
Dmytro Striletskyi

Reputation: 71

Is there a way for mypy to warn about missing explicit typing when declaring a variable?

I'm trying to setup mypy to warn me about all my mistakes in typing, but I have not been able to figure out the right config to get warnings/errors when I forget to add explicit typing when declaring a variable.

For example:

a = min([3, 5, 2, 4]) 

should warn me that I forgot typing in that line.

And this:

a: int = min([3, 5, 2, 4])

should say 'Success: no issues found'.

I would like this to happen every time and not only when mypy cannot infer the type on its own.

Is there a flag for this?

Upvotes: 5

Views: 4510

Answers (2)

Sunil
Sunil

Reputation: 141

@SamMason , --disallow-untyped-defs & --disallow-incomplete-defs mypy arguments can address this problem now. you can refer their document for more details.

https://mypy.readthedocs.io/en/latest/command_line.html#untyped-definitions-and-calls I have added this in my vscode settings and tested , its working enter image description here

I not passed the type hint for the second argument , it throws an error enter image description here

Hope it could help addressing this problem

Upvotes: 2

Michael0x2a
Michael0x2a

Reputation: 63978

There is no way to make mypy report an error if you don't include a type hint on every variable annotation. That kind of thing is considered an anti-pattern and so is explicitly not supported by mypy.

I'm a bit less familiar with how configurable linting tools such as flake8 are, but AFAIK they also don't support this kind of check. So if you want to mandate this sort of style, I'm afraid the only option left is for you to write your own linter.

I recommend that you instead focus on enabling the following categories of mypy command line flags/config values:

The following flags may also be useful:

Both disallowing dynamic typing and making mypy more aggressive about making sure code does not go unchecked should help your ultimate goal of making sure everything has a precise type.

Note that most of the flags I mentioned above are not enabled by default when using --strict.

Upvotes: 4

Related Questions