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))

 

posted @ 2020-11-22 22:55  小粉优化大师  阅读(111)  评论(0编辑  收藏  举报