altunyurt
altunyurt

Reputation: 2936

Forcing imported method to use local variables

I have a module 'b' importing a method from module "a", where method "a.method" uses a variable defined in "a" must be overriden in "b". simply, in codes:

module a.py:

local_var = 1
def method():
    print local_var

module b.py:

from a import method
local_var = 2
print method()

running python b.py prints 1, instead of 2. In my scenario imported method is a django method so i can't modify the module, nor i want to copy the method to my module and modify it.

How can i override a local variable of another module and mkae the imported method use new variable?

Upvotes: 2

Views: 3724

Answers (2)

warvariuc
warvariuc

Reputation: 59604

I suggest you better don't use such an approach. Pass the variable as the function argument, or use a class to encapsulate the value inside it.

If you insist:

Try the built-in exec function:

In all cases, if the optional parts are omitted, the code is executed in the current scope. If only the first expression after in is specified, it should be a dictionary, which will be used for both the global and the local variables. If two expressions are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object.

A working code:

a.py:

local_var = 1
def method():
    print local_var

b.py:

from a import method
import inspect

code = inspect.getsource(method)
local_var = 2
method()
print code
exec code
method()

python b.py:

vic@ubuntu:~/Desktop$ python b.py
1
def method():
    print local_var

2
vic@ubuntu:~/Desktop$ 

Upvotes: 1

Emil Ivanov
Emil Ivanov

Reputation: 37633

You can't. This is by design. Each module has its own namespace.

You can, however, save the current value of var, assign a new value, call the method and restore the original value.

# module a.py:

local_var = 1
def method():
    print local_var

# module b.py:

import a
old_local_var = a.local_var
a.local_var = 2
print method()
a.local_var = old_local_var

As jyore pointed out in the comment - this method should be used with care. It is more-or-less a hack. The only valid uses for this I can think of are testing or last resort measure, when everything else (including Chuck Norris) has failed.

Upvotes: 1

Related Questions