0

Is it possible to import global variables into an object's instance namespace?

In a structure like this:

./mypackage/module1.py
./config.py
./script1.py

If config.py has:

#config
MYSETTING=1

and script1.py has:

#SCRIPT1
from config import *
from mypackage.mymodule import MyClass as MC

obj=MC()

module1.py:

#Myclass
class MyClass(object):
    def test(self):
        print MYSETTING

will give error NameError: global name "MYSETTING" is not defined

Is there some way I can import variables from config.py into MyClass namespace as globals without doing enumerated "global x" on each of them?

Gnudiff
  • 4,297
  • 1
  • 24
  • 25

1 Answers1

0

This problem is a little confusing. There are three parts.

config: contains variables you want.

script: contains your logical code and variables imported from config.

module: contains functions' definition.

When you call MC.test, it will find MYSETTING in module's namespace, but what you want is to find in script's namespace. So in test function, what you real want is to access parent frame's global namespace.

In this case, you need to use inspect built-in module.

import inspect

print(inspect.current_frame().f_back.f_globals["MYSETTING"])

inspect.current_frame() will return current frame, and f_back refers to parent frame which is the frame calling this function, then f_globals refers to frame's globals()

Sraw
  • 18,892
  • 11
  • 54
  • 87