Get source file from a Python module

2

How can I assign a method to a module in Python or even access the source file of this module? I tried using the __file__ attribute, as shown below, but returned the error saying that the module does not have such an 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__'
    
asked by anonymous 18.02.2017 / 01:59

3 answers

3

You can not understand what you mean by "assigning a method to a module", but to get the source file, the way you did it is valid, along with several others, such as using the module inspect :

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

Why does not it work with the math module?

Because the math module, along with some others, is not written in Python, but in C, already compiled into a file referring to the operating system. The same happens with the datetime module, 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. Within the Modules directory you will find the source files in C.

If you want to extend the functionality 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 do not think that makes sense at all. If so, explain your problem better so we can discuss better solutions.

    
18.02.2017 / 02:53
2

You can not print the path of the module math, at least as far as I know, but you can with others as with the

>> import os
>> print(os.__file__)
C:\Python27\lib\os.pyc
    
18.02.2017 / 02:54
1

You can create a class and make an extend

ex:

import nomeModule

class MyOwnClass(nomeModule.MethodModule):
#AsTuasFuncoesAqui
    
18.02.2017 / 02:58