How to tell if Python module is a namespace module

Namespace packages have a __path__, and either __file__ set to None or no __file__ attribute. (__file__ is set to None on Python 3.7 and later; previously, it was unset.)

if hasattr(mod, __path__) and getattr(mod, '__file__', None) is None:
    print("It's a namespace package.")

In contrast, modules that aren't packages don't have a __path__, and packages that aren't namespace packages have __file__ set to the location of their __init__.py.


From the Python 3.8 documentation, __file__ is:

Name of the place from which the module is loaded, e.g. “builtin” for built-in modules and the filename for modules loaded from source. Normally “origin” should be set, but it may be None (the default) which indicates it is unspecified (e.g. for namespace packages).

Also, the correct answer should be:

is_namespace = (
    lambda module: hasattr(module, "__path__")
    and getattr(module, "__file__", None) is None
)