Python - import in if

后端 未结 4 1814
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 16:18

I wrote little wrapper for urllib (python3). Is it proper and safe to import module in if?

if self.response_encodi         


        
4条回答
  •  不知归路
    2020-12-15 16:47

    This is a reasonably common idiom actually. You'll sometimes see it to pick between different modules:

    if system == 'linux':
       import linuxdeps as deps
    elif system == 'win32':
       import win32deps as deps
    

    Then, assuming both linuxdeps and win32deps have the same functions, you can just use it:

    deps.func()
    

    This is even used to get os.path in the standard library (some of the source code for os follows):

    if 'posix' in _names:
        name = 'posix'
        linesep = '\n'
        from posix import *
        try:
            from posix import _exit
        except ImportError:
            pass
        import posixpath as path
    
        import posix
        __all__.extend(_get_exports_list(posix))
        del posix
    
    elif 'nt' in _names:
        name = 'nt'
        linesep = '\r\n'
        from nt import *
        try:
            from nt import _exit
        except ImportError:
            pass
        import ntpath as path
    
        import nt
        __all__.extend(_get_exports_list(nt))
        del nt
    

提交回复
热议问题