Reputation: 337
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[definition.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?
Upvotes: 1
Views: 240
Reputation: 25436
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.
Upvotes: 0
Reputation: 127527
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.
Upvotes: 2