TRam
TRam

Reputation: 43

Python scope/namespace across modules

I have a question related to scoping in python. Below is the code snippet:

file: settings.py

#module settings
fruit = 'banana'

def set_fruit(val):
    global fruit
    print 'Setting fruit ', fruit, ' to ', val
    fruit = val

file: helper.py

#module helper
from settings import fruit

class Helper(object):
    def __init__(self):
        print 'Inside Helper fruit = ', fruit

file: controller.py

#module controller
import settings
import helper

class Controller(object):
    def __init__(self):
        settings.set_fruit('apple')
        print 'Controller: settings.fruit = ', settings.fruit

Controller()
print 'fruit = ', settings.fruit
helper.Helper()

settings.py has global settings that are used by various modules. Some of these settings needs to be changed during start up by controller. I want to know why the settings changed by controller is not visible to others, in this case to helper module.

Here is the output that I get:

$ python controller.py
Setting fruit  banana  to  apple
Controller: settings.fruit =  apple
fruit =  apple
Inside Helper fruit =  banana

Upvotes: 1

Views: 64

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121484

The moment you do from settings import fruit you created a new fruit name in your helper module that is separate from the settings.fruit name. It merely references the same object.

Your settings.set_fruit() method then rebinds the settings.fruit to point it to a new object, but the helper.fruit reference cannot follow suit; it is separate after all.

All this is no different from creating two separate local variables that reference a value:

fruit = 'banana'
another_fruit = fruit
fruit = 'apple'
print another_fruit

The work-around is to do what you did in the controller module; only reference names within settings as attributes on the module. That way you'll always use just the one reference, it is the reference to the settings module that is shared across your other modules then.

Upvotes: 1

Related Questions