Python利用字符串导模块的完美的方法

需求:利字符串导入模块的方法,
注意:此代码来源Tornado源码
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from typing import Any

def import_object(name: str) -> Any:
    """字符串导入模块方法"""
    if name.count(".") == 0:
        return __import__(name)

    parts = name.split(".")

    obj = __import__(".".join(parts[:-1]), fromlist=[parts[-1]])
    try:
        return getattr(obj, parts[-1])
    except AttributeError:
        raise ImportError("No module named %s" % parts[-1])

if __name__ == '__main__':
    from math import sqrt

    sqrt_obj = import_object('math.sqrt')
    print(sqrt_obj(9))

 

上一篇:Three Parts of the Array (简单题)


下一篇:725. Split Linked List in Parts