python / python/mypy

When using`--disallow-any-expr`, silence complaints about Any where object would work

Open
#9,153 23 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic-disallow-any
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Problem

Using Any is not type safe, therefore Mypy provides options to disallow Any. However, there are many uses of Any from third-party and stdlib, so these options tend to result in a lot of errors even when they are not relevant.

I'm finding many situations where I get an error about Any, but the code would be deemed safe if it was object.

Examples

This produces errors about Any on both lines even though the value is not used:

type_hints = typing.get_type_hints(...)  # Dict[str, Any]
if k in type_hints:
    ...

This produces errors as well, but object would not produce errors, as Mypy can infer everything necessary here to be type safe.

origin = typing.get_origin(...)  # Any
if origin is Literal:
    ...
elif origin is list:
    ...

Solution

Add an option, or change the behaviour of the current disallow Any options, such that Any is treated like object. Then, rather than producing errors when Any is present, just show normal errors with Any (as if it was object) in them (e.g. 'Any has no attribute foo').

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the two examples with --disallow-any-expr and compare their diagnostics with equivalent object annotations. Review the existing handling of the disallow-Any options, then define tests for treating Any like object while retaining ordinary errors such as missing attributes.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.