Generate a new object each time a name is imported

Hrvoje Niksic hniksic at xemacs.org
Sun Aug 2 10:23:51 CEST 2009


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:

> 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.

That sounds reasonable (zen quotes aside), but it's just not possible in
current Python.  It would require for any use of "a" in subsequent code
to not only refer to an object, but also to automagically call it.  I
know of no mechanism to do that.  While Python allows intricate
customization of access to objects, simply referring to a name remains
fixed in meaning, probably intentionally.

(The "cell" mechanism used to implement closures sounds like it could
help, but a cell only stores a single value, not a factory, and it
doesn't apply to global variables anyway.)



More information about the Python-list mailing list