Search code examples
pythonmoduleinternalspython-internals

Determining if a given Python module is a built-in module


I am doing some parsing and introspection of various modules, but I don't want to parse built-in modules. Now, there is no special type for built-in modules like there is a types.BuiltinFunctionType, so how do I do this?

>>> import CornedBeef
>>> CornedBeef
<module 'CornedBeef' from '/meatish/CornedBeef.pyc'>
>>> CornedBeef.__file__
'/meatish/CornedBeef.pyc'
>>> del CornedBeef.__file__
>>> CornedBeef
<module 'CornedBeef' (built-in)>

According to Python, a module is apparently built-in if it doesn't have a __file__ attribute. Does this mean that hasattr(SomeModule, '__file__') is the way to check if a module is built in? Surely, it isn't exactly common to del SomeModule.__file__, but is there a more solid way to determine if a module is built-in?


Solution

  • sys.builtin_module_names

    A tuple of strings giving the names of all modules that are compiled into this Python interpreter. (This information is not available in any other way — modules.keys() only lists the imported modules.)