Generate a new object each time a name is imported

Jean-Michel Pichavant jeanmichel at sequans.com
Mon Aug 3 10:38:43 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.
>
>
>   
Why making standard statements do what they're not meant to do ?

You could write
 >import Module
 >
 >a = factory()
 >b = factory()
But you already know that.


So what's the purpose of making

>from Module import factory as a
>from Module import factory as b

return 2 different objects ? If I had to write this code I would expect 'a is b' to return 'True'.

This is no "don't do that" answer, it's a sincere question: what  is the 
benefit of your /new/ syntax ?

JM



More information about the Python-list mailing list