Twice instanciation

Manuel Garcia news at manuelmgarcia.com
Thu Jun 12 16:30:20 EDT 2003


On Thu, 12 Jun 2003 22:14:35 +0200, Salvatore <artyprog at wanadoo.fr>
wrote:

>In fact that is not exactly what I want.
>I don't want a unique instance of a class, but i want
>to avoid a same name of an instance being used twice.

You may have to use a 'try' statement.

    print "1st time, create name 'G'"

    try:
        G
    except NameError:
        G = 'whatever'
    else:
        print "name 'G' already in use"

    print "2nd time, recognize already using 'G'"

    try:
        G
    except NameError:
        G = 'whatever'
    else:
        print "name 'G' already in use"

If you want this behavior as part of your class, you will have to do
some very tricky programming with 'sys._getframe()' and 'inspect' in
your '__init__'. 'sys._getframe(1).f_locals' and
'sys._getframe(1).f_globals' so you can see the names already in use,
to see if perhaps any are an instance of your class, and then
'inspect' to take a peek at the line of code with the assignment.

If, in fact, this is what you want, may I ask what the exact purpose
is?  What are you trying to avoid, and why is it important to avoid
it?  The code for the procedure very roughly sketched out in the
preceeding paragraph would be difficult to write, and very difficult
to be made robust.

Manuel




More information about the Python-list mailing list