How to check if a python module has been imported?

后端 未结 5 1545
余生分开走
余生分开走 2020-12-01 04:06

How do I check if I imported a module somewhere in the code?

 if not has_imported(\"somemodule\"):
     print(\'you have not imported somemodule\')
         


        
相关标签:
5条回答
  • 2020-12-01 04:28

    sys.modules contains all modules used anywhere in the current instance of the interpreter and so shows up if imported in any other Python module.

    dir() checks whether the name was defined in the current namespace.

    The combination of the 2 is more safe than each separate and works as long you didn't define a copy yourself.

    if ('copy' in sys.modules) and ('copy' in dir()):
    
    0 讨论(0)
  • 2020-12-01 04:31

    Test for the module name in the sys.modules dictionary:

    import sys
    
    modulename = 'datetime'
    if modulename not in sys.modules:
        print 'You have not imported the {} module'.format(modulename)
    

    From the documenation:

    This is a dictionary that maps module names to modules which have already been loaded.

    Note that an import statement does two things:

    1. if the module has never been imported before (== not present in sys.modules), then it is loaded and added to sys.modules.
    2. Bind 1 or more names in the current namespace that reference the module object or to objects that are members of the module namespace.

    The expression modulename not in sys.modules tests if step 1 has taken place. Testing for the result of step 2 requires knowing what exact import statement was used as they set different names to reference different objects:

    • import modulename sets modulename = sys.modules['modulename']
    • import packagename.nestedmodule sets packagename = sys.modules['packagename'] (no matter how many addional levels you add)
    • import modulename as altname sets altname = sys.module['modulename']
    • import packagename.nestedmodule as altname sets altname = sys.modules['packagename.nestedmodule']
    • from somemodule import objectname sets objectname = sys.modules['somemodule'].objectname
    • from packagename import nestedmodulename sets nestedmodulename = sys.modules['packagename.nestedmodulename'] (only when there was no object named nestedmodulename in the packagename namespace before this import, an additional name for the nested module is added to the parent package namespace at this point)
    • from somemodule import objectname as altname sets altname = sys.modules['somemodule'].objectname
    • from packagename import nestedmodulename as altname sets altname = sys.modules['packagename.nestedmodulename'] (only when there was no object named nestedmodulename in the packagename namespace before this import, an additional name for the nested module is added to the parent package namespace at this point)

    You can test if the name to which the imported object was bound exists in a given namespace:

    # is this name visible in the current scope:
    'importedname' in dir()
    
    # or, is this a name in the globals of the current module:
    'importedname' in globals()
    
    # or, does the name exist in the namespace of another module:
    'importedname' in globals(sys.modules['somemodule'])
    

    This only tells you of the name exists (has been bound), not if it refers to a specific module or object from that module. You could further introspect that object or test if it’s the same object as what’s available in sys.modules, if you need to rule out that the name has been set to something else entirely since then.

    0 讨论(0)
  • 2020-12-01 04:44

    To the sys.modules answers accepted, I'd add one caveat to be careful about renaming modules on import:

    >>> import sys
    >>> import datetime as dt
    >>> 'dt' in sys.modules
    False
    >>> 'datetime' in sys.modules
    True
    
    0 讨论(0)
  • 2020-12-01 04:47

    use sys.modules to test if a module has been imported (I'm using unicodedata as an example):

    >>> import sys
    >>> 'unicodedata' in sys.modules
    False
    >>> import unicodedata
    >>> 'unicodedata' in sys.modules
    True
    
    0 讨论(0)
  • 2020-12-01 04:50
    if "sys" not in dir():
      print("sys not imported!")
    
    0 讨论(0)
提交回复
热议问题