开发者

Pylons: free module-level variables?

开发者 https://www.devze.com 2022-12-18 10:36 出处:网络
Not even sure if module-level is correct here, but... I have a Pylons project and within the model component I have a global variable, doc, in __init__.py that I want to use from different Query obje

Not even sure if module-level is correct here, but...

I have a Pylons project and within the model component I have a global variable, doc, in __init__.py that I want to use from different Query objects. (doc is a Document handle on an XML file that I am using as a fake DB.) My question is, when does __init__.py's scope end? Currently I am not freeing the Document with doc.unlink() and I am not sure where to put that.

The alternative design I was thinking about deals with making the consuming object (Query) have a class-level variable of this doc (i.e. make it a single开发者_开发百科ton). But it appears that the life of my Query object is such that doc always gets reallocated a new Document handle.

class Query(object):
    doc = None 

    def __init__(self, content=None):
        self.content = content
        if self.doc == None:                        
            self.doc = parse(os.path.join(config['app_conf']['xmldb'], "sample_search_result.xml"))

I can tell because the address of the elements within the Document keep changing.

Anyone want to help a noobie out?


Objects only stop existing when 1) no references to them exist, or 2) the interpreter ends. A module/package keeps a reference to all module-level names in its private dict; deleting all references to the module in all other modules as well as in sys.modules, and all references to any objects within it will release the module.


Have you considered putting the doc object in globals? Since it's an immutable object it shall be the perfect place to store it. Than you can reference globals from any controller and pass it to a Query object (during __init__ or explicitly when calling a method on the object)

You can also try to store the doc object in the controller's session (if per session reads required)

0

精彩评论

暂无评论...
验证码 换一张
取 消