1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Caching derived properties of NamedTuple

Discussão em 'Python' iniciado por Stack, Novembro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I've got a NamedTuple:

    from typing import NamedTuple
    from functools import cached_property

    class NT(NamedTuple):
    a: int
    b: int

    @property
    def primefactors_a(self):
    n = self.a
    if n < 2:
    return []
    factors = []
    d = 2
    while d <= n:
    while n % d == 0:
    factors.append(d)
    n //= d
    d += 1
    return factors

    @cached_property
    def cached_primefactors(self):
    return self.primefactors_a

    @property
    def man_cached_primefactors(self):
    if hasattr(self, "pf_cache"):
    return getattr(self, "pf_cache")
    pf = self.primefactors_a
    setattr(self, "pf_cache", pf)
    return pf


    Assume my derived property is just a costly computation on immutable values of my tuple. For illustrations, I tried to provide the most naive implementation of the prime factor decomposition of self.a.

    1. Usage of @functools.cached_property fails: TypeError: Cannot use cached_property instance without calling __set_name__ on it.
    2. Usage of if not hasattr(...): setattr(...) fails: AttributeError: 'NT' object has no attribute 'pf_cache'

    Can it be done with a NamedTuple?

    Adding a regular property

    ...
    internal_cache = {}


    does not count. If unpacking the tuple, it should only contain the real properties, no derived properties or helpers.

    This is question about: "Is it at all possible to do it. Can I add a cached derived property to an NamedTuple" - not a question: "Should I rather use some normal (data)class for this use case".

    Continue reading...

Compartilhe esta Página