Python按文件夹模块导入 [英] Python imports by folder module

查看:116
本文介绍了Python按文件夹模块导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个目录结构:

example.py
templates/
    __init__.py
    a.py
    b.py

a。 py b.py 只有一个类,名称与文件相同(因为它们是猎豹模板)。出于纯粹的样式原因,我希望能够在 example.py 中导入和使用这些类,如下所示:

a.py and b.py have only one class, named the same as the file (because they are cheetah templates). For purely style reasons, I want to be able to import and use these classes in example.py like so:

import templates

t = templates.a()

现在我通过在模板文件夹的 __ init __。py 中这样做:

Right now I do that by having this in the template folder's __init__.py:

__all__ = ["a", "b"]
from . import *

然而,这看起来很差(也许是多余的),甚至不做什么我想,因为我必须使用这样的类:

However, this seems pretty poor (and maybe superfluous), and doesn't even do what I want, as I have to use the classes like this:

t = templates.a.a()

想法?

推荐答案

为避免从< whatever>重复 import * 25次,你需要一个循环,例如:

To avoid repeating from <whatever> import * 25 times, you need a loop, such as:

import sys

def _allimports(modnames)
  thismod = sys.modules[__name__]

  for modname in modnames:
    submodname = '%s.%s' % (thismod, modname)
    __import__(submodname)
    submod = sys.modules[submodname]
    thismod.__dict__.update(submod.__dict__)

_allimports('a b c d e'.split())  # or whatever

我将有意义的代码放在函数中因为( a)总是最好[[为了性能并避免污染模块的命名空间]],(b)在这种特殊情况下它也避免了事故(例如,某些子模块可能定义名称 thismod modnames ...因此,将我们在循环中使用的名称保留在函数的本地,不是模块非常重要全局,所以他们不会被意外践踏; - )。

I'm putting the meaningful code in a function because (a) it's always best [[for performance and to avoid polluting the module's namespace]], (b) in this particular case it also avoids accidents (e.g., some submodule might define a name thismod or modnames... so it's important to keep those names that we're using in the loop local to the function, not module globals, so they can't be accidentally trampled;-).

如果你想强制执行这个事实在名为 modname 的模块中,只有一个具有相同名称的类(或其他全局),将循环的最后一个语句更改为:

If you want to enforce the fact that a module named modname only has one class (or other global) with the same name, change the last statement of the loop to:

    setattr(thismod, modname, getattr(submod, modname))

这篇关于Python按文件夹模块导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆