modifying locals

Arnaud Delobelle arnodel at googlemail.com
Fri Oct 31 05:14:32 EDT 2008


On Oct 30, 9:21 pm, "John [H2O]" <washa... at gmail.com> 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]))
>
>     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.
>
> Bringing up another matter... is there a better way to do this that doesn't
> use exec?

What you're trying to do is hard to achieve but there's a reason for
that: it's a bad idea as it makes code really difficult to maintain.

You may want to define a class to contain all those variables that
need to be changed together:

class MyVars(object):
    def __init__(self, outfile, numcount, ...):
        self.outfile = outfile
        self.numcount = numcount
    def write_and_do_stuff(self):
        self.outfile.write(...)
        self.numcount += 1
        # do this, do that...

Then you can use this in your functions:

def myfunction():
     vars = MyVars(open('my.log', w), 0, ...)
     # Do some stuff
     vars.write_and_do_stuff()
     # Do more stuff

You may even consider making some of those functions into methods of
the class.

--
Arnaud




More information about the Python-list mailing list