Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a module name is part of python standard library

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.

like image 268
Yohai Devir Avatar asked Sep 27 '17 07:09

Yohai Devir


People also ask

What are Python standard modules?

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.

How do I identify a Python module?

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 .

How many modules are in Python standard library?

The Python standard library contains well over 200 modules, although the exact number varies between distributions.


1 Answers

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')
like image 51
Guillaume Avatar answered Oct 28 '22 10:10

Guillaume