TomCho
TomCho

Reputation: 3517

Creating global variable from submodule available in entire module

Suppose I have three files inside a directory that is called mymod. The three files are __init__.py, sm1.py, sm2.py. The content of the modules are:

__init__.py

import sm1
import sm2
global _defaults

sm1.py

global _defaults
class get_defs:
    color='blue'
    number=10    
_defaults = get_defs()

sm2.py

def printdefs():
    print _defaults.color
    print _defaults.number

So, what I am trying to do is set a class inside submodule sm1 called _defaults that can be accessed from any other place in the module or submodules, so that submodule sm2 can also access and print that class. I thought this setting would work, but when I run

import mymod
mymod.sm2.printdefs()

I get this error:

NameError: global name '_defaults' is not defined

Any suggestions as how to do that (and why this isn't working?)

P.S.:

The reason I want a global variable instead of just setting some variable to be imported is that I want to be able for the user to do this:

>>> import mymod
>>> mymod.sm2.printdefs()
'blue'
10
>>> mymod._defaults.color='red'
>>> mymod.sm2.printdefs()
'red'
10

So, working with global variables is the only I thought I could work like this.

Thank you.

Upvotes: 3

Views: 1395

Answers (1)

Chad S.
Chad S.

Reputation: 6631

global is not how you do that. sm1 should just set the variable, then all the other modules should just import it.

sm1.py:

class get_defs:
    color='blue'
    number=10 
_defaults = get_defs()

sm2.py

import sm1
def printdefs():
    print sm1._defaults.color
    print sm1._defaults.number

But really I'm not sure why you have a global for this rather than some kind of factory method, or class. If you can give more details about the actual project that would be helpful.

Upvotes: 1

Related Questions