python / python/mypy

Mypy cannot infer types of initialized variables

Open
#8,493 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug priority-1-normal
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

I have the following code:

class Service:
    def __init__():
        self.another_service = Service()
     
    def my_method() -> None:
        return self.another_service.another_method_call()

Mypy should gives an error of incompatible types because another_method_call is not returnig None but it is not type checking because it cannot identify what is the type of another_service.

The only way to makes it gives an error is initializing another_service using:

self.another_service: Service = Service() 

I think mypy has enough static information to guess what is the type of another_service wihout needing to someone explicit type it.

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

No file or test is named in the issue. Start by reproducing the class example with and without the explicit Service annotation, then trace mypy's instance-variable type inference and related tests. Done means mypy infers the initialized attribute type and reports the incompatible return type without requiring the annotation.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.