Generate a new object each time a name is imported

Peter Otten __peter__ at web.de
Sun Aug 2 06:33:03 EDT 2009


Steven D'Aprano wrote:

> I would like to generate a new object each time I import a name from a
> module, rather than getting the same object each time. For example,
> currently I might do something like this:
> 
> # Module
> count = 0
> def factory():
>     # Generate a unique object each time this is called
>     global count
>     count += 1
>     return "Object #%d" % count
> 
> 
> # Calling module
> from Module import factory
> a = factory()  # a == "Object #1"
> b = factory()  # b == "Object #2"
> del factory
> 
> 
> I'm looking for a way to hide the generation of objects from the caller,
> so I could do something like this:
> 
> from Module import factory() as a  # a == "Object #1"
> from Module import factory() as b  # b == "Object #2"
> 
> except of course that syntax is illegal.

How about

>>> class A(object):
...     def __init__(self):
...             self._n = 0
...     @property
...     def a(self):
...             try:
...                     return self._n
...             finally:
...                     self._n += 1
...
>>> import sys
>>> sys.modules["yadda"] = A()
>>> from yadda import a
>>> from yadda import a as b
>>> a, b
(0, 1)

Peter




More information about the Python-list mailing list