How to check if a python module has been imported?

后端 未结 5 1564
余生分开走
余生分开走 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: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
    

提交回复
热议问题