"once" assigment in Python

Alex Martelli aleax at mac.com
Fri Sep 14 17:22:52 CEST 2007


Lorenzo Di Gregorio <lorenzo.digregorio at gmail.com> wrote:

> When employing Python it's pretty straightforward to translate the
> instance to an object.
> 
> instance = Component(input=wire1,output=wire2)
> 
> Then you don't use "instance" *almost* anymore: it's an object which
> gets registered with the simulator kernel and gets called by reference
> and event-driven only by the simulator kernel.  We might reuse the
> name for calling some administrative methods related to the instance
> (e.g. for reporting) but that's a pretty safe thing to do.  Of course
> all this can be done during initialization, but there are some good
> reasons (see Verilog vs VHDL) why it's handy do be able to do it
> *anywhere*.  The annoying problem was that every time the program flow
> goes over the assignment, the object gets recreated.

If you originally set, e.g.,

  instance = None

then using in your later code:

  instance = instance or Component(...)

will stop the multiple creations.  Other possibilities include using a
compound name (say an.instance where 'an' is an instance of a suitable
container class) and overriding the __new__ method of class Component so
that it will not return multiple distinct objects with identical
attributes.  "Has this *plain* name ever been previously assigned to
anything at all" is simply not a particularly good condition to test for
(you COULD probably write a decorator that ensures that all
uninitialized local variables of a function are instead initialized to
None, but I'd DEFINITELY advise against such "black magic").


Alex



More information about the Python-list mailing list