turning a string into an object name

Alex Martelli aleax at aleax.it
Thu Apr 4 06:56:24 EST 2002


A. Jones wrote:
        ...
> I'll probably get blasted for this by Python gurus... but, I've used

*BLAST*!  No, seriously.  Don't do that.  You'll get hurt if you do.

> it with some success.  You can do
> 
> exec(myObjc + " = " + value)

You can do it without the parentheses, too (and that makes it
clearer what you're doing, because exec is a statement, while
you make it look as if it was a function).


> or, if it's a class instance you want to create
> 
> exec(myObjc + " = " + bar + "()").
> 
> Toss whatever variables you want sent on to the instance inside "("
> and ")" and you're homefree.
> 
> Unless there's some problem with that that an old-timer spots that I
> haven't yet.

The problem is basically exactly the specs as expressed: "please
help me trample all over my namespace by dirtying it with names
that I cannot control".  These specs are wrong and you are
guaranteed no end of grief if you do match them.

Suppose you do:

def wrongHeaded(name, value):
    exec name+'='+repr(value)
    print vars()

Seems fine, no?  Can hardly be simpler, right?

wrongHeaded('a', 23)

does indeed emit:
{'a': 23, 'name': 'a', 'value': 23}

proving it's done just what we expected.  BUT -- what if we
call it like...:

wrongHeaded('vars', 24)

OOPS!  Now it dies:

Traceback (most recent call last):
  File "d.py", line 6, in ?
    wrongHeaded('vars', 24)
  File "d.py", line 3, in wrongHeaded
    print vars()
TypeError: 'int' object is not callable

What's it taling about?  Answer: it's talking about 'vars'.
We just set it to 24, so we can't call it any more.

This comes to apply to ALL identifiers WITHOUT EXCEPTION.

You cannot use ANY identifier safely after that exec
statement, as you have no idea any more what the
identifier can refer to.  As a bonus, your code crawls,
since the Python compiler knows it does not know, and
therefore executes a full identifier look-up at runtime
rather than recognizing local variables at compile time.

What kind of useful code can you write without being
able to use ANY identifier safely?  WHY would you ever
WANT to trample all over your namespace to ensure every
identifier becomes an utter and total mystery?  Beats me.


WHATEVER the problem may be that you THINK you need to
solve by wilfully destroying your namespace, I ensure
you, it *ISN'T*.  There is ALWAYS a better approach,
whatever your application's exact needs might be.


Alex




More information about the Python-list mailing list