`Packet.fields_desc` type annotation is inconsistent with runtime behavior
Brief description
Packet.fields_desc supports Packet / Packet_metaclass but typed as List[AnyField]
Scapy version
2.7.0
Python version
3.14
Operating system
Windows11
Additional environment information
No response
How to reproduce
The type annotation for fields_desc on Packet classes is declared as List[AnyField]:
# scapy/packet.py, line 108
fields_desc = [] # type: List[AnyField]
However, at runtime, the Packet_metaclass.__new__ method explicitly handles the case where elements in fields_desc are Packet metaclass instances (i.e., references to other Packet subclasses), not just Field instances:
# scapy/base_classes.py, lines 371-380
if "fields_desc" in dct: # perform resolution of references to other packets # noqa: E501
current_fld = dct["fields_desc"] # type: List[Union[scapy.fields.Field[Any, Any], Packet_metaclass]] # noqa: E501
resolved_fld = [] # type: List[scapy.fields.Field[Any, Any]]
for fld_or_pkt in current_fld:
if isinstance(fld_or_pkt, Packet_metaclass):
# reference to another fields_desc
for pkt_fld in fld_or_pkt.fields_desc:
resolved_fld.append(pkt_fld)
else:
resolved_fld.append(fld_or_pkt)
This means fields_desc can contain:
Fieldinstances — the documented/typed behaviorPacketclasses (metaclass instances) — which get inlined/expanded by flattening theirfields_desc
Actual result
No response
Expected result
The type should be updated to something like:
fields_desc = [] # type: List[Union[AnyField, Type[Packet]]]
Related resources
No response
I'd like to work on this issue. I'll align Packet.fields_desc type annotation with Packet_metaclass resolution behavior (allow Type[Packet] references at class definition time).
Hi! I'd be glad to pick this up if it's still available — align the annotation with the runtime behavior and check that nothing relies on the current typing. Let me know!
I'd like to work on this — the fix is widening the annotation to match what the metaclass already accepts. PR incoming.
As annoying as that issue is, it's very hard to fix. Because that value is changed by a metaclass, there isn't really a good fix. Sadly I would advise to either use a fake cast() or put a type: ignore in your definition :( Sorry about that. This might change with Scapy 4.0.