开发者

In python, what is contained in the info property of a module object?

I'm looking into creating a Plugin structure for a program and making it so even the core library is treated as plugins. in my research I came across this code that is dynamically importing modules.

def __initialize_def(self, module):
    """Attempt to load the definition"""

    # Import works the same for py files and package modules so strip!
    if module.endswith(".py"):
        name = module [:-3]
    else:
        name = module

    # Do the actual import
    __import__(name)
    definition = sys.modules[name]

    # Add the definition only if the class is available
    if hasattr(definition, definition.info["class"]):
        self.definitions[definit开发者_运维问答ion.info["name"]] = definition
        logging.info("Loaded %s" % name)

I have tried to understand what this code is doing and I've succeeded to a point. However, I simply can't understand the latter part of the code, specifically these two lines:

if hasattr(definition, definition.info["class"]):
    self.definitions[definition.info["name"]] = definition

I can't figure out what definition.info["<key>"] is referring to.

What is this .info[] dictionary and what does it hold? Is it common to all Python objects or only module objects? What is it useful for?


py> import sys,os
py> sys.modules["os"].info["class"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'info'

So this info attribute must be specific to modules that can be used as plugins in this program.


Reserved names in Python generally begin with two underscores. You just stumbled on some piece of a larger codebase, that gives info module-scope values a special meaning. I don't think its authors chose a particularly good name for these, anyway; $FRAMEWORK_MODULE_INFO would be more explicit.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜