函数定义后的导入语句 - 如何使它更符合Python风格?

2024-04-20 11:18:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了下面这段代码,我觉得很蹩脚:

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

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

解决这些问题的常见方法是什么?我怎样才能让它更像Python?在


Tags: path代码importreturndefexeglobreturns
3条回答
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

把功能放在两个不同的模块里怎么样?在

module1

import win32file

def findfile(wildcard):
    """Returns path of the first matched file. Using win32file.
    >>> findfile1("D:\\Python26\\*.exe")
    'D:\\Python26\\python.exe'
    """
    return filepath

module2

^{pr2}$

主程序:

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

相关问题 更多 >