user1561108
user1561108

Reputation: 2747

In python after I import a module is there a way of finding what physical file it was loaded from?

Something's acting up in my math package I think and I want to ensure I'm loading the correct module. How do I check the physical file location of loaded modules in python?

Upvotes: 1

Views: 159

Answers (3)

Bakuriu
Bakuriu

Reputation: 101929

Use the __file__ attribute:

>>> import numpy
>>> numpy.__file__
'/usr/lib/python2.7/dist-packages/numpy/__init__.pyc'

Note that built-in modules written in C and statically linked to the interpreter do not have this attribute:

>>> import math
>>> math.__file__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__file__'

An other way to obtain the path to the file is using inspect.getfile. It raises TypeError if the object passed is a built.in module, class or function.

On a side note, you should avoid using names that conflict with language built-ins or standard library modules. So, I'd suggest you to rename your math package to something else, or, if it is part of a package like mypackage.math, to avoid importing it directly and use mypackage.math instead.

Upvotes: 5

Mark
Mark

Reputation: 108522

>>> import math
>>> math.__file__
'/usr/lib/python2.7/lib-dynload/math.so'

Upvotes: 1

Pavel Anossov
Pavel Anossov

Reputation: 62908

Check themodule.__file__.

import urllib
print urllib.__file__

Upvotes: 1

Related Questions