Internals of the MolMod package

molmod.utils – Read-only objects and cached attributes

class molmod.utils.cached(fn)

A decorator that will turn a method into a caching descriptor

When an attribute is requested for the first time, the original method will be called and its return value is cached. Subsequent access to the attribute will just return the cached value.

Usage:

class Foo(object):
    @cached
    def some_property(self):
        return self.x*self.y

There are a few limitations on the cached decorator. Once the result is computed and cached, it can not be erased. This means that the values on which the result depends have to be read-only parameters that can not be changed afterwards. This is facilitated by deriving from the ReadOnly object. See molmod.molecules.Molecule for an example.

class molmod.utils.ReadOnly

A base class for read-only objects

An object that has nothing but read-only attributes. If an attribute is not assigned yet, it is writable. Some attributes are cached, i.e. they are computed from other attributes upon request.

If you want to modify a ReadOnly object, just create a modified one from scratch. This is greatly facilitated by the method copy_with().

copy_with(**kwargs)

Return a copy with (a few) changed attributes

The keyword arguments are the attributes to be replaced by new values. All other attributes are copied (or referenced) from the original object. This only works if the constructor takes all (read-only) attributes as arguments.