Question

My application reads the python script:

a = MyObject("a")
b = MyObject("b")

my_objects = [a, b]

The following code loads the file and gets my_objects (exceptions in case of parsing error are omitted):

_config = __import__(file_name)
if hasattr(_config, "my_objects"):
    v = getattr(_config, "my_objects")

It works but i want MyObject to have access to another object during file parsing. The only way I found was to declare a global variable in a separate python (globs.py) file to avoid cyclic import error:

_cached_instance

And then the code of my object is:

import globs

class MyObject(Object):
    def __init__(self):
        self.cache_instance = globs._cached_instance

It works... but is is not very elegant. The use of a global variable makes testing difficult (and with strange border effect). I'm looking for a more elegant way to "inject" the _cached_instance during the loading of the python script and make it only available in the script. Any ideas ?

Was it helpful?

Solution

Best I could come up with was using an initialization function, but this does of course not run during parsing but shortly after:

test.py

my_objects = None

def update(foo):
    globals()['my_objects'] = [foo, foo+1]

test2.py

_config = __import__("test")
_config.update(2) 
print _config.my_objects

There are quite a lot of ideas floating around, but most of them involve messing with the imported module after import, not during parsing.

One way of making the variable available doing it is changing the calling module's (test2) __builtin__ before calling the import, but that seems like a pretty big hack to me. See the accepted answer in this discussion: Python: How to make a cross-module variable?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top