I should clarify that what I said is opinionated (my opinion in
particular!) so it's possible others disagree. Certainly there is a
lot of code in SymPy that doesn't follow the advice above.

If we want a cached_property decorator then we can add this somewhere
in sympy/utilities or perhaps sympy/core/cache:

from functools import wraps

def cached_property(propfunc):

    attrname = '_' + propfunc.__name__
    sentinel = object()

    @wraps(propfunc)
    def accessor(self):
        val = getattr(self, attrname, sentinel)
        if val is sentinel:
            val = propfunc(self)
            setattr(self, attrname, val)
        return val

    return property(accessor)

class A:
    @cached_property
    def g(self):
        print('foo')
        return 'bar'

>From the SymPy codebase though most instances of storing attributes
outside of args not for this kind of caching. I think it's usually the
author deliberately trying to keep the attribute out of args. That
could be because the arg is unsympifiable or it could be because there
is too much code that relies on a particular args layout so the author
wants to emulate that. The latter reason is why it is best to have a
layer above args that defines properties (one and another in the
examples above) so other code doesn't need to access args directly.

Oscar

On Sun, 8 Sep 2019 at 14:56, Rybalka Denys <rybalka.de...@gmail.com> wrote:
>
> Great, that is exactly what I've been trying to find!
>
> By the way, there is caching property decorator called `@cached_property`,
> that does exactly what you suggested. It is, however, not in the standard
> library (https://pypi.org/project/cached-property/). Maybe it would be
> beneficial to add it to the standard sympy package? Unfortunately¸
> I have no idea how these things are done.
>
> Do you think it is worthwhile to create a page with the "coding guidelines",
> so that other authors can use this information? If yes, where?
>
> Denys
>
> --
> You received this message because you are subscribed to the Google Groups 
> "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to sympy+unsubscr...@googlegroups.com.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/sympy/a78f21b0-63c6-4b78-8b4d-e21a3e95968d%40googlegroups.com.

-- 
You received this message because you are subscribed to the Google Groups 
"sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sympy+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sympy/CAHVvXxSQOva21Pkeq5sVWHYTPzC8uz4x_w1f1NR4W3c3umvw0w%40mail.gmail.com.

Reply via email to