Check if a parameter is a Python module?

后端 未结 6 522
野性不改
野性不改 2021-02-04 23:54

How can I (pythonically) check if a parameter is a Python module? There\'s no type like module or package.

>>> os


        
相关标签:
6条回答
  • 2021-02-05 00:32

    A mix of @Greg Hewgill and @Lennart Regebro answers:

    >>> from types import ModuleType
    >>> import os
    >>> type(os) is ModuleType
    True
    
    0 讨论(0)
  • 2021-02-05 00:40
    from types import ModuleType
    
    isinstance(obj, ModuleType)
    
    0 讨论(0)
  • 2021-02-05 00:40
    >>> import inspect, os
    >>> inspect.ismodule(os)
    True
    
    0 讨论(0)
  • 2021-02-05 00:42

    This seems a bit hacky, but:

    >>> import sys
    >>> import os
    >>> type(os) is type(sys)
    True
    
    0 讨论(0)
  • 2021-02-05 00:44

    Two ways,you could not import any modules:

    • type(os) is type(__builtins__)
    • str(type(os)).find('module')>-1
    0 讨论(0)
  • 2021-02-05 00:52

    Flatten the module to a string and check if it starts with '<module '

    import matplotlib
    foobarbaz = "some string"
    print(str(matplotlib).startswith("<module "))     #prints True
    print(str(foobarbaz).startswith("<module "))      #prints False
    

    Drawback being this could collide with a python string that starts with the text '<module' You could try to classify it more strongly with a regex.

    0 讨论(0)
提交回复
热议问题