Generate a new object each time a name is imported

Steven D'Aprano steve at
Sun Aug 2 09:35:08 CEST 2009

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.


More information about the Python-list mailing list