By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,190 Members | 765 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,190 IT Pros & Developers. It's quick & easy.

Re: modifying locals

P: n/a
John [H2O] wrote:
I would like to write a function to write variables to a file and modify a
few 'counters'. This is to replace multiple instances of identical code in a
module I am writing.

This is my approach:

def write_vars(D):
""" pass D=locals() to this function... """
for key in D.keys():
exec("%s = %s" % (key,D[key]))
Note that this code will likely fail to execute if D[key] is some object
whose str() method does not return a valid Python expression.
numcount += 1
do this, do that...

the issue is that at the end, I want to return outfile, numcount, etc... but
I would prefer to not return them explicitly, that is, I would just like
that the modified values are reflected in the script. How do I do this?
Using global? But that seems a bit dangerous since I am using exec.
Return them as a tuple, using an unpacking assignment to bind the
different elements to different names.
Bringing up another matter... is there a better way to do this that doesn't
use exec?
It's not really obvious why you are trying to replicate the caller's
namespace inside this function. Perhaps you could explain a little more
what you are trying to achieve.

Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC

Oct 30 '08 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.