Type field declared in multiple flows as common base

Open
#5,111 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Feature
Clarity
Needs clarification
Activity status
Stale
Tech stack
python
Domain
devtools

Research direction

The issue names no files, tests, or entry points. Start by reviewing the conditional-assignment examples and the requested common-base inference, then determine the intended typing behavior for optional and related model types. Done means the desired inference is defined and supported without requiring either explicit annotation form.

Written by the indexing model from the issue text.

Description

feature topic-type-narrowing

In this code:

if condition:
  s = get_str()
else:
  s = get_optional_str()

we currently need to add hints, i.e. (a)

if condition:
  s: Optional[str] = get_str()
else:
  s = get_optional_str()

or (b)

s: Optional[str]
if condition:
  s = get_str()
else:
  s = get_optional_str()

Both (a) and (b) seem overly verbose to me, for what seems like a common pattern. If the optionality of s serves a problem for the code that's to follow, that's what mypy should alert us about.

Perhaps optionality is actually somewhat of a special case. A more natural application of this logic would allow for:

if condition:
   model = get_foo_model()  # FooModel
else:
   model = get_bar_model()  # BarModel
# model is Model
Dominant language
Python
Stars
20.6k
Forks
3.3k
Avg merge
1d 18h
Merged PRs (30d)
54

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.

More from python/mypy

All issues in python/mypy

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.