Skip to content

mypy not checking if calling passing a value of type Any to a function expecting some other type #16563

Closed as not planned

Description

@gjcarneiro

Bug Report

(A clear and concise description of what the bug is.)

To Reproduce

from typing import Any

class Foo:
    pass

def func(foo: Foo) -> None:
    pass


def main() -> None:
    x: Any = 1
    func(x)

Expected Behavior

I would expect that mypy would complain when calling func() with a parameter of type Any while func expects Foo.

Actual Behavior

$ mypy --version
mypy 1.7.1 (compiled: yes)
$ mypy --strict test.py 
Success: no issues found in 1 source file
$ 

Your Environment

  • Mypy version used:
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used:

Activity

  1. erictraut commented on Nov 25, 2023

    @erictraut

    Mypy is doing the right thing here. This is how Any works in the Python static type system. It's literally compatible with any other type. When you use Any, you're effectively telling the type checker "don't emit any type violations here, I know what I'm doing". For more details, refer to this section in PEP 484.

  2. gjcarneiro commented on Nov 25, 2023

    @gjcarneiro
    Author

    That is unfortunate, because the Any comes from a sqlalchemy model. I wish we had a different kind of type similar to Any, like Unknown, to annotate when we don't know what is the type of something.

    But OK, thanks for indulging my question anyway. I have to investigate how to deal with this. Maybe the nuclear option disallow_any_expr is the way to go :/

  3. AlexWaygood commented on Nov 25, 2023

    @AlexWaygood
    Member

    If you have a variable that is inferred asAny, but you'd like to enforce strict typechecking on that variable until the type of the variable has been manually narrowed, consider using typing.cast to convert the type of the variable to object, e.g.

    import json
    import typing
    
    x = json.loads('{"foo": "bar"}')  # oh no, inferred by type checker as having type 'Any'
    y = typing.cast(object, x)  # y refers to the same object but has type 'object'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions