I have a module name as a string (e.g. 'logging') that was given by querying the module attribute of an object.
How can I differentiate between modules that are part of my project and modules that are part of python standard library?
I know that I can check if this module was installed by pip using pip.get_installed_distributions(), but these are not related to the standard library
Note: I'm working on python 2.7 so solutions that are valid only in python 3.x are less relevant.
Unlike the answer here, I was looking for a solution that can be run in O(1) and will not require holding an array of results nor having to scan the directory for every query.
Thanks.
The Python Standard Library is a collection of script modules accessible to a Python program to simplify the programming process and removing the need to rewrite commonly used commands.
Get the location of a particular module in Python using the OS module. For a pure Python module, we can locate its source by module_name. __file__. This will return the location where the module's .
The Python standard library contains well over 200 modules, although the exact number varies between distributions.
Quick 'n dirty solution, using the standard module imp:
import imp
import os.path
import sys
python_path = os.path.dirname(sys.executable)
my_mod_name = 'logging'
module_path = imp.find_module(my_mod_name)[1]
if 'site-packages' in module_path or python_path in module_path or not imp.is_builtin(my_mod_name):
print('module', my_mod_name, 'is not included in standard python library')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With