Get source file from a Python module

Asked

Viewed 212 times

2

How can I assign a method to a module in Python or even access its source file? I tried using the attribute __file__, as shown below, but returned me the error saying that the module does not have such attribute.

>>> import math
>>> Py.__file__ # Meu modulo
'/home/bezerk/Área de Trabalho/Py.py'
>>> math.__file__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__file__'

3 answers

3


I could not understand well what you want with "assign a method to a module", but to search the source file, the way you did it is valid, along with several other, such as using the module inspect:

>>> import inspect
>>> import os
>>> inspect.getfile(os)
'/usr/lib/python2.7/os.pyc'

Why doesn’t it work with the module math?

Because the module math, along with some others, it is not written in Python, but in C, already compiled for a file referring to the operating system. The same happens with the module datetime, for example.

If you want to access the source code as a way to study what actually happens in the language, you can directly access the Python repository, version 2.7 or version 3.3, for example. Inside the directory Modules find the source files in C.

If you want to extend the functionalities of a class present in the module, make use of object-oriented programming, such as inheritance. If you just want to add a function to namespace, I believe that it doesn’t even make sense. If this is the case, explain your problem better we can discuss better solutions.

2

You can’t print module Math’s path, at least as far as I know, but you can with others like

>> import os
>> print(os.__file__)
C:\\Python27\\lib\\os.pyc

1

You can create a class and extend

ex:

import nomeModule

class MyOwnClass(nomeModule.MethodModule):
#AsTuasFuncoesAqui
  • Try to centralize the content of your answer in just one place. Posting multiple short answers only pollutes the community. Just below each answer has the edit button to make the necessary changes.

  • I only put in multiple answers because they are two very different answers, but thank you for the warning

  • Also try to describe the solution better. Explain what you’re doing, why it works, or why it doesn’t, whether it should work or not. The more detailed the answer, the better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.