scalar references

Fredrik Lundh fredrik at
Wed Nov 19 08:47:57 CET 2003

John Hunter wrote:

> I don't really have a problem with this approach, but am wondering if
> this is the best (most pythonic!) way to share a mutable scalar value
> among several objects.

Wrapping individual scalars is usually not the best way to design things
in any language; a better approach is to attach the scalar to a class that
represents a more abstract (higher-level) concept than just the individual

In this case, you can get better performance and eliminate a lot of code
by using an ordinary class with a "dpi" attribute.  Create a shared instance
of that class and add it to the components.  Instead of writing "self.dpi.get()"
every time you need to access the current setting, write "self.context.dpi"
or, better:

    dpi = self.context.dpi
    ... calculations that depend on the dpi ...

The next step is to factor out common subexpressions that involve the DPI
from the individual components and move them into the context object, via
precalculated attributes or helper methods.  Use a setdpi() method or
descriptors to make sure all attributes are updated when the DPI is changed
(Should individual parts even have to know about the current DPI, by the
way?  Shouldn't they work in the "plot value domain" or the "actual size
domain"?  Maybe you should route all drawing operations through the new
context class? Can you think of any other methods that belong to the
context class?  Refactor!).


More information about the Python-list mailing list