modifying locals

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Oct 30 18:23:08 EDT 2008


On Thu, 30 Oct 2008 14:21:01 -0700, John [H2O] wrote:

> I would like to write a function to write variables to a file and modify
> a few 'counters'. 

Are you talking about a function to generate Python source code?


> This is to replace multiple instances of identical
> code in a module I am writing.


Surely the right way to do this is to factor out the identical code into 
a function, and then call the function.

 
> 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]))

That would be better written as:

for key,item in D.iteritems():
    exec "%s = %s" % (key, item)

exec is a statement, not a function, and doesn't require brackets.

 
>     outfile.write(...)
>     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.

What you are actually trying to do is unclear to me. Perhaps you could 
try explaining better with a more concrete example?

I wounder whether this might be what you are after?

# start of script (untested)
counter = 0  # define a counter in the module scope (global)
filename = 'foo.txt'

def make_vars():
    global outfile, numcount  # force names to be in module scope
    outfile = open(filename, 'w')
    numcount = 99

try:
    numcount
except NameError:
    print "numcount doesn't exist yet, making it"
    make_vars()

print numcount
# end script


But of course the above can be written much more concisely as:

# start of script (untested)
counter = 0
filename = 'foo.txt'
outfile = open(filename, 'w')
numcount = 99
print numcount
# end script

so I'm not really sure you're trying to do what you seem to be doing.




-- 
Steven



More information about the Python-list mailing list