给定完整模块路径动态导入可调用对象?

发布于 2024-08-20 01:39:54 字数 198 浏览 2 评论 0原文

>>> import_path('os.path.join')
<function join at 0x22d4050>

编写 import_path (在 Python 2.6 及更高版本中)的最简单方法是什么?假设最后组件始终是模块/包中的可调用组件。

>>> import_path('os.path.join')
<function join at 0x22d4050>

What is the simplest way to write import_path (in Python 2.6 and above)? Assume that the last component is always a callable in a module/package.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一刻暧昧 2024-08-27 01:39:54

这似乎就是您想要的:

def import_path(name):
    modname, _, attr = name.rpartition('.')
    if not modname:
        # name was just a single module name
        return __import__(attr)
    m = __import__(modname, fromlist=[attr])
    return getattr(m, attr)

要使其与 Python 2.5 及更早版本一起使用,其中 __import__ 不接受关键字参数,您将需要使用:

m = __import__(modname, {}, globals(), [attr])

This seems to be what you want:

def import_path(name):
    modname, _, attr = name.rpartition('.')
    if not modname:
        # name was just a single module name
        return __import__(attr)
    m = __import__(modname, fromlist=[attr])
    return getattr(m, attr)

To make it work with Python 2.5 and earlier, where __import__ doesn't take keyword arguments, you will need to use:

m = __import__(modname, {}, globals(), [attr])
萌辣 2024-08-27 01:39:54

显然有以下工作:

>>> p = 'os.path.join'
>>> a, b = p.rsplit('.', 1)
>>> getattr(__import__(a, fromlist=True), b)
<function join at 0x7f8799865230>

Apparently the following works:

>>> p = 'os.path.join'
>>> a, b = p.rsplit('.', 1)
>>> getattr(__import__(a, fromlist=True), b)
<function join at 0x7f8799865230>
旧时模样 2024-08-27 01:39:54

尝试一下有效

def import_path(name):
  (mod,mem) = name.rsplit('.',1)
  m = __import__(mod, fromlist=[mem])
  return getattr(m, mem)

至少

>>> import_path('os.walk')
<function walk at 0x7f23c24f8848>

现在

>>> import_path('os.path.join')
<function join at 0x7f7fc7728a28>

Try

def import_path(name):
  (mod,mem) = name.rsplit('.',1)
  m = __import__(mod, fromlist=[mem])
  return getattr(m, mem)

Works at least for

>>> import_path('os.walk')
<function walk at 0x7f23c24f8848>

and now

>>> import_path('os.path.join')
<function join at 0x7f7fc7728a28>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文