Skip to content

"auto" return type #727

Closed
Closed
@kshpytsya

Description

@kshpytsya

I am unsure if this issue should go here or rather to mypy's tracker. I have looked through issues in both typing and mypy and couldn't find anything related.

Consider the following code:

import typing as tp


class A:
    x: int


def f1() -> A:
    return A()


def f2() -> tp.Any:
    return f1()


x = f1()
x.x = ""  # [1]

y = f2()
y.x = ""  # [2]

Upon checking with mypy, an expected Incompatible types in assignment (expression has type "str", variable has type "int") error is emited at [1], but not at [2]. This makes sense, as type of y is Any. However, e.g. jedi autocompletion library is smart enough to deduce that f2() -> A. While in the above degenerate example it would be trivial to just property annotate the f2, the real scenario has A and f1 defined in some library, and f2, which does something more useful than just calling f1 is defined in user-code. Specific class A is not intended to be directly instantiated by the user, moreover, it may be buried deeply inside module hierarchy, which may also change between library releases.

My suggestion is to introduce typing.Auto which, when used in return type annotation, would instruct type checker (mypy or any other) to infer return type from the type of expression in return statement. In case of multiple return statements, the pragmatical approach would probably be to infer the base-most class, possibly issuing an error or a warning if types are completely unrelated.

Another possibility is to optionally have mypy treat typing.Any return types in a manner suggested for the above-described typing.Auto but I suspect that this would be a breaking change.

P.S. typing.Auto should also be usable within typing.Tuple. I am not sure whether it would be desirable to allow inference of tuple in cases when return type is annotated as typing.Auto.

Metadata

Metadata

Assignees

No one assigned

    Labels

    resolution: duplicateThe idea/problem was already reportedtopic: featureDiscussions about new features for Python's type annotations

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions