Hướng dẫn python typeddict enum - python typeddict enum

Mô tả lỗi

Nếu

************* Module test
test.py:30:11: E1136: Value 'value3' is unsubscriptable (unsubscriptable-object)
test.py:33:11: E1136: Value 'value4' is unsubscriptable (unsubscriptable-object)
0 có
************* Module test
test.py:30:11: E1136: Value 'value3' is unsubscriptable (unsubscriptable-object)
test.py:33:11: E1136: Value 'value4' is unsubscriptable (unsubscriptable-object)
1 dưới dạng pylint giá trị cho thấy dương tính giả cho "đối tượng không thể mô tả". Tuy nhiên, điều này được phát hiện chính xác bởi, ví dụ, MYPY và phần mở rộng Python trong VSCode. Sau này thậm chí còn cung cấp hoàn thành Intellisense cho tên đăng ký.

# pylint: disable=missing-class-docstring, missing-module-docstring, missing-function-docstring, invalid-name
from enum import Enum
from typing import TypedDict


class TypedDictionary(TypedDict):
    name: str


class Enumerations(Enum):
    KEY1: TypedDictionary = {"name": "from enum"}


def return_enum_value() -> TypedDictionary:
    return Enumerations.KEY1.value


def return_typed_dict() -> TypedDictionary:
    return {"name": "from function"}


if __name__ == "__main__":
    value1: TypedDictionary = {"name": "flat"}
    assert value1["name"] == "flat"

    value2 = return_typed_dict()
    assert value2["name"] == "from function"

    value3 = Enumerations.KEY1.value
    assert value3["name"] == "from enum"

    value4 = return_enum_value()
    assert value4["name"] == "from enum"

Cấu hình

Không phản hồi

Lệnh được sử dụng

Đầu ra pylint

************* Module test
test.py:30:11: E1136: Value 'value3' is unsubscriptable (unsubscriptable-object)
test.py:33:11: E1136: Value 'value4' is unsubscriptable (unsubscriptable-object)

Hành vi mong đợi

************* Module test
test.py:30:11: E1136: Value 'value3' is unsubscriptable (unsubscriptable-object)
test.py:33:11: E1136: Value 'value4' is unsubscriptable (unsubscriptable-object)
2 và
************* Module test
test.py:30:11: E1136: Value 'value3' is unsubscriptable (unsubscriptable-object)
test.py:33:11: E1136: Value 'value4' is unsubscriptable (unsubscriptable-object)
3 không nên được hiển thị là không thể mô tả.

Phiên bản pylint

pylint 2.14.5
astroid 2.11.7
Python 3.10.5 (main, Jun 23 2022, 17:14:57) [Clang 13.1.6 (clang-1316.0.21.2.5)]

Hệ điều hành / môi trường

MacOS 12,5 ZSH 5.8.1 (x86_64-apple-darwin21.0) VSCODE 1.70.0 (Universal) với Python Extension V2022.12.0
zsh 5.8.1 (x86_64-apple-darwin21.0)
VSCode 1.70.0 (Universal) with Python extension v2022.12.0

Phụ thuộc bổ sung

Không phản hồi

Jukkal đã thêm một cam kết tham chiếu vấn đề này

Ngày 4 tháng 5 năm 2021

Hướng dẫn python typeddict enum - python typeddict enum

A union of enum literals was merged back to the enum type, which broke
type narrowing. Disable merging in this case to work around the
issue.

The fix feels a bit ad hoc. However, I'd rather not spend a lot of
time figuring out a general fix, since this seems like a pretty rare
edge case.

Fixes #10414.

Jukkal đã thêm một cam kết tham chiếu vấn đề này

Ngày 4 tháng 5 năm 2021

A union of enum literals was merged back to the enum type, which broke
type narrowing. Disable merging in this case to work around the
issue.

The fix feels a bit ad hoc. However, I'd rather not spend a lot of
time figuring out a general fix, since this seems like a pretty rare
edge case.

Fixes #10414.

Mặc dù điều này không trả lời câu hỏi như được hỏi, tôi nghĩ bạn cũng có thể xem xét lại lý do tại sao bạn sử dụng

************* Module test
test.py:30:11: E1136: Value 'value3' is unsubscriptable (unsubscriptable-object)
test.py:33:11: E1136: Value 'value4' is unsubscriptable (unsubscriptable-object)
1 với một chuỗi thay vì một lớp thích hợp để giữ enum (thay vì
************* Module test
test.py:30:11: E1136: Value 'value3' is unsubscriptable (unsubscriptable-object)
test.py:33:11: E1136: Value 'value4' is unsubscriptable (unsubscriptable-object)
5, vì
************* Module test
test.py:30:11: E1136: Value 'value3' is unsubscriptable (unsubscriptable-object)
test.py:33:11: E1136: Value 'value4' is unsubscriptable (unsubscriptable-object)
6 thực sự có vẻ như là một enum ), và sau đó có thể sử dụng một số logic tuần tự hóa tùy chỉnh.

Ví dụ:

import dataclasses as dc
import json
from enum import Enum


class Transaction(Enum):
    DISBURSEMENT = "disbursement"
    REFUND = "refund"
    ROLLBACK = "rollback"

    def __str__(self):
        return self.value


@dc.dataclass
class Disbursement:
    transaction: Transaction
    id_: str
    amount: float

    def __str__(self):
        return json.dumps(dc.asdict(self), default=str)


if __name__ == "__main__":
    disbursement = Disbursement(
        Transaction.REFUND,
        "1",
        4400.24,
    )
    print(disbursement)
$ mypy example.py
Success: no issues found in 1 source file
$ python3 example.py
{"transaction": "refund", "id_": "1", "amount": 4400.24}

Ngoài ra, bạn có thể có ENUM kế thừa từ

************* Module test
test.py:30:11: E1136: Value 'value3' is unsubscriptable (unsubscriptable-object)
test.py:33:11: E1136: Value 'value4' is unsubscriptable (unsubscriptable-object)
5 và đơn giản hóa một vài điều:

import dataclasses as dc
import json
from enum import Enum


class Transaction(str, Enum):
    DISBURSEMENT = "disbursement"
    REFUND = "refund"
    ROLLBACK = "rollback"


@dc.dataclass
class Disbursement:
    transaction: Transaction
    id_: str
    amount: float

    def __str__(self):
        return json.dumps(dc.asdict(self))


if __name__ == "__main__":
    disbursement = Disbursement(
        Transaction.REFUND,
        "1",
        4400.24,
    )
    print(disbursement)

Những ý kiến ​​khác:

  • Python 3.11 sẽ có
    ************* Module test
    test.py:30:11: E1136: Value 'value3' is unsubscriptable (unsubscriptable-object)
    test.py:33:11: E1136: Value 'value4' is unsubscriptable (unsubscriptable-object)
    8: https://docs.python.org/3.11/howto/enum.html#strenum
  • Ghi chú về lớp con enum: https://docs.python.org/3/l Library/enum.html#others
  • So sánh bình đẳng với các chuỗi có lẽ nên tránh: https://www.cosmicpython.com/blog/2020-10-27-I-hate-enums.html (thích
    ************* Module test
    test.py:30:11: E1136: Value 'value3' is unsubscriptable (unsubscriptable-object)
    test.py:33:11: E1136: Value 'value4' is unsubscriptable (unsubscriptable-object)
    9 đến
    pylint 2.14.5
    astroid 2.11.7
    Python 3.10.5 (main, Jun 23 2022, 17:14:57) [Clang 13.1.6 (clang-1316.0.21.2.5)]
    0 hoặc
    pylint 2.14.5
    astroid 2.11.7
    Python 3.10.5 (main, Jun 23 2022, 17:14:57) [Clang 13.1.6 (clang-1316.0.21.2.5)]
    1
  • Kế thừa từ
    pylint 2.14.5
    astroid 2.11.7
    Python 3.10.5 (main, Jun 23 2022, 17:14:57) [Clang 13.1.6 (clang-1316.0.21.2.5)]
    2 có thể có một số nhược điểm: Làm thế nào để giảm bớt sự liệt kê với biểu diễn chuỗi?

Cuối cùng, tôi muốn lưu ý rằng việc xác định

pylint 2.14.5
astroid 2.11.7
Python 3.10.5 (main, Jun 23 2022, 17:14:57) [Clang 13.1.6 (clang-1316.0.21.2.5)]
3 trên enum của tôi đã không làm những gì tôi mong đợi nó sẽ làm bằng cách sử dụng ví dụ
************* Module test
test.py:30:11: E1136: Value 'value3' is unsubscriptable (unsubscriptable-object)
test.py:33:11: E1136: Value 'value4' is unsubscriptable (unsubscriptable-object)
1 của bạn ở trên; Đó là bởi vì str (mydict) gọi
pylint 2.14.5
astroid 2.11.7
Python 3.10.5 (main, Jun 23 2022, 17:14:57) [Clang 13.1.6 (clang-1316.0.21.2.5)]
5 để cung cấp mỗi
pylint 2.14.5
astroid 2.11.7
Python 3.10.5 (main, Jun 23 2022, 17:14:57) [Clang 13.1.6 (clang-1316.0.21.2.5)]
6:

class Example:
    def __repr__(self):
        print("I called repr!")
        return "from repr"

    def __str__(self):
        print("I called str!")
        return "from str"


if __name__ == "__main__":
    print(f"example: {Example()}\n")

    d = {"example": Example()}
    print(f"in a dict: {d}")
$ python3 foo.py
I called str!
example: from str

I called repr!
in a dict: {'example': from repr}

Ngoài ra, bạn không thể thêm các phương thức tùy chỉnh vào

************* Module test
test.py:30:11: E1136: Value 'value3' is unsubscriptable (unsubscriptable-object)
test.py:33:11: E1136: Value 'value4' is unsubscriptable (unsubscriptable-object)
1; Nếu bạn thay đổi
pylint 2.14.5
astroid 2.11.7
Python 3.10.5 (main, Jun 23 2022, 17:14:57) [Clang 13.1.6 (clang-1316.0.21.2.5)]
8 thành kế thừa từ
************* Module test
test.py:30:11: E1136: Value 'value3' is unsubscriptable (unsubscriptable-object)
test.py:33:11: E1136: Value 'value4' is unsubscriptable (unsubscriptable-object)
1 và chạy lại ví dụ cuối cùng đó, bạn sẽ không thấy rằng
A union of enum literals was merged back to the enum type, which broke
type narrowing. Disable merging in this case to work around the
issue.

The fix feels a bit ad hoc. However, I'd rather not spend a lot of
time figuring out a general fix, since this seems like a pretty rare
edge case.

Fixes #10414.
0 và
pylint 2.14.5
astroid 2.11.7
Python 3.10.5 (main, Jun 23 2022, 17:14:57) [Clang 13.1.6 (clang-1316.0.21.2.5)]
3 đều không được gọi và thật không may, cũng không có lỗi thời gian chạy (
A union of enum literals was merged back to the enum type, which broke
type narrowing. Disable merging in this case to work around the
issue.

The fix feels a bit ad hoc. However, I'd rather not spend a lot of
time figuring out a general fix, since this seems like a pretty rare
edge case.

Fixes #10414.
2 cảnh báo một cách hữu ích
A union of enum literals was merged back to the enum type, which broke
type narrowing. Disable merging in this case to work around the
issue.

The fix feels a bit ad hoc. However, I'd rather not spend a lot of
time figuring out a general fix, since this seems like a pretty rare
edge case.

Fixes #10414.
3). Bởi vì logic tuần tự hóa dường như thuộc về
A union of enum literals was merged back to the enum type, which broke
type narrowing. Disable merging in this case to work around the
issue.

The fix feels a bit ad hoc. However, I'd rather not spend a lot of
time figuring out a general fix, since this seems like a pretty rare
edge case.

Fixes #10414.
4, tôi đã thay đổi nó thành một lớp có phần tương tự cho phép tôi tùy chỉnh
pylint 2.14.5
astroid 2.11.7
Python 3.10.5 (main, Jun 23 2022, 17:14:57) [Clang 13.1.6 (clang-1316.0.21.2.5)]
3 của nó: một DataClass.