开发者

Is there a way to get all modules 'under' a specific module in the hierarchy?

Is there a way of listing all python modules directly underneath a specified model in the hierarchy?

I开发者_Python百科've got a Django web-app that is slowly growing, and I've re-organised it based on this article:

http://paltman.com/2008/01/29/breaking-apart-models-in-django/

However, I'm trying to improve on his technique by making use of introspection in the module initialization file (__ init __.py) in order to auto-detect all instances of the Django model class in the subordinate jobs. I've got this sort of got this working, but it still needs a static list of modules in the tree above it to work.

In case people are interested, here's what my solution looks like:

from django.db.models.base import ModelBase
from sys import modules

moduleList = ['TechTree', 'PilotAbilities']
__all__ = []

for moduleName in moduleList:
  fullyQualifiedModuleName = '%s.%s' % (__name__, moduleName)
  moduleObj = __import__(fullyQualifiedModuleName)

  __all__ += [item for item in dir(moduleObj) if isinstance(getattr(moduleObj, item), ModelBase)]


Well, you can get os.path.dirname(parent.__file__), and then glob.glob() or os.walk() and look for other init.py files.


This is just an attempt, but it seems to work. I'm running python 2.7.1 and dir(somemodule) gives me all associated modules. Tested with the openpyxl and os modules.

def import_all(name):
    __import__(name)
    for i in dir(name):
        try:
            if type(i) == type(name):
                import_all(name+'.'+i)
        except:
            pass

Note: This is probably extremely unpythonic and discouraged, but it seems to work.

Note 2: That was because I accidentally had 'openpyxl' (a test I was using) instead of the list submodules. Sorry

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜