Conditional import of modules in Python

后端 未结 3 518
北恋
北恋 2020-12-07 14:15

In my program I want to import simplejson or json based on whether the OS the user is on is Windows or Linux. I take the OS name as input from the user. Now, is it correct t

3条回答
  •  误落风尘
    2020-12-07 14:54

    To answer the question in your title but not the particular case you provide, it's perfectly correct, tons of packages do this. It's probably better to figure out the OS yourself instead of relying on the user; here's pySerial doing it as an example.

    serial/__init__.py

    import sys
    
    if sys.platform == 'cli':
        from serial.serialcli import Serial
    else:
        import os
        # chose an implementation, depending on os
        if os.name == 'nt':  # sys.platform == 'win32':
            from serial.serialwin32 import Serial
        elif os.name == 'posix':
            from serial.serialposix import Serial, PosixPollSerial, VTIMESerial  # noqa
        elif os.name == 'java':
            from serial.serialjava import Serial
        else:
            raise ImportError(
                "Sorry: no implementation for your platform ('{}') available".format(
                    os.name
                )
            )
    

    This should be only used in cases where you're assuming and need a strong guarantee that certain interfaces/features will be there: e.g. a 'file' called /dev/ttyX. In your case: dealing with JSON, there's nothing that is actually OS-specific and you are only checking if the package exists or not. In that case, just try to import it, and fall-back with an except if it fails:

    try:
        import some_specific_json_module as json
    except ImportError:
        import json
    

提交回复
热议问题