Python functools - cached_property()


Python tip (>=3.8):

You can use cached_property from functools to cache the results of a class attribute for the life of the instance. It's useful if you have a property that is expensive to compute and doesn't need to change.

An example 👇

import io
import pathlib
from functools import cached_property

from pikepdf import Pdf


class PDF:
    def __init__(self, file_bytes):
        self.file_bytes = file_bytes

    @cached_property
    def number_of_pages(self):
        return len(Pdf.open(io.BytesIO(self.file_bytes)).pages)


pdf = PDF(pathlib.Path("file.pdf").read_bytes())
print(pdf.number_of_pages)