python / python/mypy

Assignment to Any doesn't make it more precise

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

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

documentation needs discussion
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ả

  • Are you reporting a bug, or opening a feature request?

Bug report.

  • Please insert below the code you are checking with mypy,
    or a mock-up repro if the source is private. We would appreciate
    if you try to simplify your case to a minimal repro.
from typing import Any, Optional


def foo(baz: Any) -> int:
    return 1


def bar1(baz: Any = 0) -> int:
    reveal_type(baz)
    baz = foo(baz)
    reveal_type(baz)
    return baz


def bar2(baz: Optional[Any] = 0) -> int:
    reveal_type(baz)
    baz = foo(baz)
    reveal_type(baz)
    return baz
  • What is the actual behavior/output?
main.py:9: note: Revealed type is 'Any'
main.py:11: note: Revealed type is 'Any'
main.py:12: error: Returning Any from function declared to return "int"
main.py:16: note: Revealed type is 'Union[Any, None]'
main.py:18: note: Revealed type is 'builtins.int'
Found 1 error in 1 file (checked 1 source file)
  • What is the behavior/output you expect?

After baz = foo(baz) the type of baz should be int. Redefinition should not be a problem here since this assignment makes the type of baz more precise.

By trial-and-error I found that annotating bar as a Union of Any and anything else (here Optional[Any] == Union[Any, None]) fixes this behavior.

  • What are the versions of mypy and Python you are using?
    Do you see the same issue after installing mypy from Git master?

mypy: 0.780 / 0.790+dev.95eff27adb1fae7b1ec4a7315524ebfdcebf6e2b
python: 3.6.9

  • What are the mypy flags you are using? (For example --strict-optional)

--warn-return-any

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 với trình tái hiện tối thiểu được thể hiện dưới dạng main.py và chạy mypy với --warn-return-any; so sánh đầu ra của reveal_type trước và sau baz = foo(baz). Được xem là hoàn tất khi phép gán được xử lý như việc thu hẹp baz thành int và lỗi return-any không còn được báo cáo, đồng thời hành vi hiện có của Optional[Any] vẫn được hiểu rõ.

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
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
35/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.