Skip to content

IndirectObject gives a KeyError when using in operator #3154

@noamkush

Description

@noamkush

When using PdfReader, accessing the /Names and checking whether the file contains javascript, I get a KeyError which is unexpected as it has a __getitem__ and can be used as a mapping.

Environment

Which environment were you using when you encountered the problem?

$ python -m platform
Linux-5.15.153.1-microsoft-standard-WSL2-x86_64-with-glibc2.39

$ python -c "import pypdf;print(pypdf._debug_versions)"
pypdf==5.3.0, crypt_provider=('cryptography', '44.0.1'), PIL=11.0.0

Code + PDF

This is a minimal, complete example that shows the issue:

from pypdf import PdfWriter, PdfReader
from io import BytesIO

writer = PdfWriter()
writer.add_attachment("test.txt", b"content")
stream = BytesIO()
writer.write(stream)

reader = PdfReader(stream)
names = reader.root_object.get("/Names")
if names and "/JavaScript" in names:
    ...

Traceback

This is the complete traceback I see:

KeyError                                  Traceback (most recent call last)
Cell In[1], line 11
      9 reader = PdfReader(stream)
     10 names = reader.root_object.get("/Names")
---> 11 if names and "/JavaScript" in names:
     12     ...

File ~/.cache/pypoetry/virtualenvs/...-py3.13/lib/python3.13/site-packages/pypdf/generic/_base.py:393, in IndirectObject.__getitem__(self, key)
    391 def __getitem__(self, key: Any) -> Any:
    392     # items should be extracted from pointed Object
--> 393     return self._get_object_with_check()[key]

File ~/.cache/pypoetry/virtualenvs/...-py3.13/lib/python3.13/site-packages/pypdf/generic/_data_structures.py:479, in DictionaryObject.__getitem__(self, key)
    478 def __getitem__(self, key: Any) -> PdfObject:
--> 479     return dict.__getitem__(self, key).get_object()

KeyError: 0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions