Jon Jon - 2 years ago 155
Python Question

Python: How to check if an imported module/package/class is from standard library

Is there a possibility to verify if an import comes from the standard library or not?

For example:

from math import sin #from the standard library.
from my_module import MyClass #not from the standard library.

Answer Source

There is no simple way to do this, as the Python standard library is not implemented in a special way - to Python, there is no distinction between the standard library and other modules.

At best, you could use the inspect module to try and find some indicators, for example, using inspect.getsourcefile() to find where the source file is located, then using that to check if it's a core library. This won't work particularly well, however, as any modules in C will return a TypeError as they are builtins - but you can't presume they are from the standard library, as any C extension module will do the same thing.

If you really have to do this, my suggestion would be to keep a list of standard library module names and do it that way - it's not a great solution, but it's likely to be more stable than any alternative.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download