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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
inspectmodule to try and find some indicators, for example, usinginspect.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.