1

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?

user1561108
  • 2,666
  • 9
  • 44
  • 69

3 Answers3

4

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.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
  • Interesting. Why does my math module have a `.file` attribute and yours doesn't? – Mark Feb 03 '13 at 16:03
  • @Mark Probably on Mac OS X the `math` module is not statically linked to the interpreter. (I guess is OSX by the `lib-dynload` in the path) It probably has to do with [this](http://stackoverflow.com/questions/2339679/what-are-the-differences-between-so-and-dylib-on-osx) – Bakuriu Feb 03 '13 at 16:08
  • I'm on linux, so I don't get the .file attr. Anyway to check this? Then again I guess this means I'm probably loading the correct one. – user1561108 Feb 03 '13 at 16:11
  • If the module has not `__file__` attribute then you are loading the module from the standard library. Whether it's the correct one depends on which one you wanted to import. – Bakuriu Feb 03 '13 at 16:14
  • I'm actually on Linux - Fedora 14. – Mark Feb 03 '13 at 17:25
  • @Mark Then I have no idea. Did you install it with `yum` or in some other way? – Bakuriu Feb 03 '13 at 19:48
  • It was the Python included with the base install. After some Googling, the best I can come up with is that `built-in` modules (like sys or thread) do not have the attribute. Which Linux distro are you running? – Mark Feb 03 '13 at 20:22
  • Kubuntu 12.04. The documentation explicitly says that C modules statically linked to the interpreter do not have the attribute. Why `math` is sometimes statically linked and sometimes not I really have no idea. – Bakuriu Feb 03 '13 at 20:23
  • Yes, sorry, you are correct about, by `built-in`, they mean they are directly in libpython. – Mark Feb 03 '13 at 20:25
1

Check themodule.__file__.

import urllib
print urllib.__file__
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
1
>>> import math
>>> math.__file__
'/usr/lib/python2.7/lib-dynload/math.so'
Mark
  • 106,305
  • 20
  • 172
  • 230