Re: [PhillyPUG] Python hackery, any better ideas?

From: Thomas E J.
Sent on: Thursday, January 12, 2012 1:02 PM


On Thu, Jan 12, 2012 at 12:49, Kevin Hill <[address removed]> wrote:
On 01/12/[masked]:31 PM, Mat Schaffer wrote:
> Thanks Erik and Thomas, but I think both of those solutions would
> require prepending `vars.` to all the local variable references in the
> code which is a frightening prospect. It's about 250 lines with lots of
> cross referencing of values and oddly placed list comprensions :(
>
> I updated https://gist.github.com/1601533#file_uglycode.py to point out
> where that line is (currently 12) that I don't want to touch anything
> below. It's possible that what I have is as good as it gets, but the
> warning on first run (I suspect the compilation process) is concerning.
>
> -Mat

Instead of calling the functions directly, you could use "exec" and pass
in a dictionary of variables.

Something like this:

my_vals = locals()

# override the ones you need
my_vals['foo'] = 'bar'

# call the function with exec and pass in variables
exec(my_func(), my_vals)

This would allow you to override whatever you need.

- khill

Something based on the above might be more what you are looking for, but just to give another option.

You can leave the hairy function in a module with it referencing all of the module-level (global) vars and just import that module as a variable and manipulate those module level vars to override them.

So if you have a hairy.py with:

frob = 42
other = 23

def somefunc():
    return frob + other

You can then do the below:

>>> hairy_mod = __import__('hairy')
>>> hairy_mod.somefunc()
65
>>> hairy_mod.frob = 88
>>> hairy_mod.somefunc()
111

Thomas

Our Sponsors

People in this
Meetup are also in:

Sign up

Meetup members, Log in

By clicking "Sign up" or "Sign up using Facebook", you confirm that you accept our Terms of Service & Privacy Policy