Is there a way to convince JetBrains PyCharm to autocomplete field names when using annotated dataclasses?

  Kiến thức lập trình

I currently have a program that is translating a protocol with many different message types to Python, and have used annotated dataclasses to represent the messages. For example:

@dataclass()
class TriggerEvent:
    sequence_num: int = 0
    num_sub_messages: int = 0
    carryover: dict[bytes, Ledger] = field(default_factory=lambda: {}) # Note Ledger is another dataclass defined in a similar way
    qrs: list[int] = field(default_factory=lambda: [])
    trs: list[int] = field(default_factory=lambda: [])
    tss: list[int] = field(default_factory=lambda: [])
    last_tss: list[int] = field(default_factory=lambda: []) 
    observed: bool = False
    sub_messages: list[SubTriggerEvents] = field(default_factory=lambda: []) # Note SubTriggerEvents is another dataclass defined in a similar way

This is a relatively simple example, some of these message types have dozens of fields.

In the actual code, the “main loop” ends up looking something like this:

next_event = get_next_event()
if type(next_event) is TriggerEvent:
   ....

It would be lovely if I could get JetBrains’ code completion to automatically list fields when I hit . on a variable constrained to a type like next_event. within the ‘if’ statement above, or if a method has a type hint in the signature.

Is there any ways to convince the PyCharm to do this?

6

LEAVE A COMMENT