Thursday, 19 September 2013

How can I convert a python string to an attribute or symbol for assignment?

How can I convert a python string to an attribute or symbol for assignment?

So basically, I'm attempting to mock by cheating with eval(). But it
doesn't seem to be syntactically viable. Curious if there is any other
way? (I'm well aware of mocking libraries for python, please don't suggest
that, although any 1-5 line techniques they use, to solve this, would be
awesome!)
>>> import os
>>> def func(*args, **kwargs):
... print "Who knows?"
...
>>> to_assign = 'os.getcwd'
>>> os.getcwd
<built-in function getcwd>
>>> eval('os.getcwd')
<built-in function getcwd>
>>> os.getcwd = func
>>> os.getcwd()
Who knows?
>>> eval('os.getcwd') = func
File "<stdin>", line 1
SyntaxError: can't assign to function call
As illustrated above, os.getcwd and eval('os.getcwd') should evaluate to
the same thing, but I can't get the assignment to happen if the eval is on
the destination side of the statement.
Also, I cannot use exec because I'm using this in a nested function with
closures.
A solution for Python 2 is preferable, but also would be good to know a
solution for Python 3 if one exists.
Thanks, Chenz

No comments:

Post a Comment