A simple way to find out a Python module's location on your drive.

Edited 3 Years Ago by vegaseat

''' module_origin1.py
Where does a given module come from?
You could use module.__path__
but not all modules have a .pth file
tested with Python27 and Python33  by  vegaseat  22oct2013
'''

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk
import os

print(os.path.dirname(tk.__file__))

''' 
result (Python27) ...
c:\python27\lib\lib-tk
result (Python33) ...
c:\python33\lib\tkinter
'''

You can also get the location from help(module) under FILE ...

import collections
help(collections)

Edited 1 Year Ago by vegaseat

Get more detail this way ...

''' inspect101.py
explore Python module inspect
'''

import inspect
import glob

# check if there is a file glob.py
try:
    print(inspect.getsourcefile(glob))
except TypeError:
    print("source file not found")

print('-'*60)

# retrieve the source code of glob.py
try:
    print(inspect.getsource(glob))
except IOError:
    print("source code not found")

print('-'*60)

# check if an object is built in or give file location
import json
object = json
try:
    file_path = inspect.getfile(object)
    print(file_path)
    if "__init__.py" in file_path:
        print("This is a package")
except TypeError:
    print("{} is a built-in module, class, or function".format(object))

print('-'*60)

# check if an object is built in or give file location
object = str
try:
    file_path = inspect.getfile(object)
    print(file_path)
    if "__init__.py" in file_path:
        print("This is a package")
except TypeError:
    print("{} is a built-in module, class, or function".format(object))

# where is the function getmodule() of module inspect located
print('-'*60)
print(inspect.getmodule(inspect.getmodule))

Edited 1 Year Ago by vegaseat

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.