Skip to main content
 首页 » 编程设计

python之函数定义后的 Import 语句——如何让它更像 pythonic

2025年05月04日12虾米姐

我写了下面的一段代码,我认为它很蹩脚:

def findfile1(wildcard): 
    """Returns path of the first matched file. Using win32file. 
    >>> findfile1("D:\\Python26\\*.exe") 
    'D:\\Python26\\python.exe' 
    """ 
    return filepath 
 
def findfile2(wildcard): 
    "Same as above, but using glob." 
    return filepath 
 
try: 
    import win32file 
    findfile = findfile1 
except ImportError: 
    import glob 
    findfile = findfile2 
 
if __name__ == '__main__': 
    f = findfile('D:\\Python26\\*.exe') 

函数是在导入所需模块之前定义的,整体结构对我来说有点奇怪。

这类问题的常见做法是什么?我怎样才能让它更像 pythonic?

请您参考如下方法:

try: 
    import win32file 
except ImportError: 
    win32file = None 
    import glob 
 
if win32file: 
    def findfile(wildcard): 
        """Returns path of the first matched file. Using win32file.""" 
        ... 
        return filepath 
else: 
    def findfile(wildcard): 
        """Returns path of the first matched file. Using glob.""" 
        ... 
        return filepath