suggestions for functional style (singleton pattern?)

Ian Kelly ian.g.kelly at gmail.com
Mon Mar 2 11:51:45 EST 2015


On Mon, Mar 2, 2015 at 8:59 AM, Michael Torrie <torriem at gmail.com> wrote:
> Now I don't know of any way of implementing class-style properties on a
> module as you can do in a class, but if that were needed you would write
> a standard class and instantiate a singleton inside the module itself
> perhaps.

This works, although I'm not sure that I would do it in real code.

>>> class PropertyModule(types.ModuleType):
...     @property
...     def parrot(self):
...         return "Norwegian Blue"
...
>>> sys.modules['parrot_sketch'] = PropertyModule('parrot_sketch')
>>> import parrot_sketch
>>> parrot_sketch.parrot
'Norwegian Blue'

Note that if the user does "from parrot_sketch import parrot", then
the property is evaluated at import time and any changes won't be
reflected in the local binding, which might cause some surprises.

Also, this isn't really a singleton any longer since the user might
just create another instance of the class, but you can hide the class
and present just the module as the API.



More information about the Python-list mailing list