Skip to content

Change dict to mapping in writer.update_page_form_field_values #3453

@starspritechippy

Description

@starspritechippy

Explanation

Passing a variable of type dict[str, str] into the PdfWriter.update_page_form_field_values currently gives a pretty big error message when using Pylance regarding invariance, this message is left below. Since - from what I can tell - update_page_form_field_values does not write to the fields argument, its type annotation can be safely changed into collections.Mapping as the error suggests. Since I'm not entirely confident what the message means or what else the change might bring with it, I'm opening this as an issue rather than as a PR so I can get other people's input as well.

Pylance message:

Argument of type "dict[str, str]" cannot be assigned to parameter "fields" of type "dict[str, str | list[str] | tuple[str, str, float]]" in function "update_page_form_field_values"
  "dict[str, str]" is not assignable to "dict[str, str | list[str] | tuple[str, str, float]]"
    Type parameter "_VT@dict" is invariant, but "str" is not the same as "str | list[str] | tuple[str, str, float]"
    Consider switching from "dict" to "Mapping" which is covariant in the value typePylance(reportArgumentType)

Code Example

in https://github.com/py-pdf/pypdf/blob/main/pypdf/_writer.py#L1066 change

def update_page_form_field_values(
    self,
    page: Union[PageObject, list[PageObject], None],
    fields: dict[str, Union[str, list[str], tuple[str, str, float]]],
    flags: FA.FfBits = FFBITS_NUL,
    auto_regenerate: Optional[bool] = True,
    flatten: bool = False,
) -> None:
    ....

to

def update_page_form_field_values(
    self,
    page: Union[PageObject, list[PageObject], None],
    fields: Mapping[str, Union[str, list[str], tuple[str, str, float]]],
    flags: FA.FfBits = FFBITS_NUL,
    auto_regenerate: Optional[bool] = True,
    flatten: bool = False,
) -> None:
    ....

Metadata

Metadata

Assignees

No one assigned

    Labels

    PdfWriterThe PdfWriter component is affectedneeds-discussionThe PR/issue needs more discussion before we can continuetypingType hints are faulty

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions