python / python/mypy

Flow-sensitive typing ignores dictionary key mutation

Đang mở
#10,185 1 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

bug topic-type-narrowing
Ngôn ngữ chính
Python
Star
20.6k
Fork
3.3k
Chỉ số merge pull request
Chỉ số pull request đang chờ

Mô tả

Bug Report

mypy allows runtime type checks for dictionary items. However it ignores subsequent dictionary mutations. This leads to mypy accepting code that fails at runtime.

To Reproduce

from typing import Dict, Optional

foo_dict: Dict[str, Optional[str]] = {'bar': 'baz'}

if foo_dict['bar'] is not None:
    foo_dict['bar'] = None
    foo_dict['bar'].upper()

Expected Behavior

mypy reports .upper() call as error. This is similar to what already happens with object attributes:

from dataclasses import dataclass
from typing import Optional

@dataclass
class Foo:
    bar: Optional[str]

foo = Foo(bar='baz')

if foo.bar is not None:
    foo.bar = None
    foo.bar.upper()

For such code mypy outputs the following error: "None" has no attribute "upper".

Actual Behavior

mypy reports no error.

Your Environment

  • Mypy version used: 0.812
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.6.8
  • Operating system and version: Windows 8.1

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu bằng cách chạy bản tái hiện Python với mypy --strict và so sánh nó với ví dụ thuộc tính dataclass, xác nhận rằng trường hợp dictionary được chấp nhận trong khi trường hợp thuộc tính bị từ chối. Truy vết logic narrowing phụ thuộc vào luồng đối với các biểu thức phần tử dictionary và bổ sung coverage cho mutation; hoàn tất khi mypy báo lời gọi .upper() là một lỗi.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
python
Lĩnh vực
compilers, devtools
Loại issue
Lỗi
Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Khá rõ ràng
Mức phù hợp với người mới
45/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.