python / python/mypy

Refactor parial types to avoid code duplication

Open
#8,043 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Currently there is some duplication around partial types:

  • Logic in try_infer_partial_generic_type_from_assignment() essentially duplicates the logic inlined in check_assignment() for None partial types. These two probably can be refactored to the same method if we also update handle_partial_var_type() to not special-case partial None types, and instead consistently return a partial type in lvalue context.
  • Logic in try_infer_partial_type_from_indexed_assignment() duplicates that in try_infer_partial_type() (there is already a TODO item). This one can be refactored by either pushing the latter a bit down the call stack (closer to check_call()), or by generating a synthetic CallExpr with __setitem__ and passing it to try_infer_partial_type().

The second item may be something to watch out when implementing support for these:

a = defaultdict(list)
a[0].append('yes')

b = {}
b.setdefault(0, []).append('yes')

c = defaultdict(set)
c[0].add('yes')

d = {}
d.setdefault(0, set()).add('yes')

@JukkaL this is probably not something important, but maybe it makes sense to fix this while we are at 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

Start by locating try_infer_partial_generic_type_from_assignment(), check_assignment(), handle_partial_var_type(), try_infer_partial_type_from_indexed_assignment(), and try_infer_partial_type(). Compare their partial-type handling, then evaluate the defaultdict and setdefault examples as regression cases; done means the duplicated logic is unified without breaking those inference scenarios.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.