Access a hidden library function in Python?
Question: So when I was doing coding I came across this:

    
    
    from hidden_lib import train_classifier
    

Out of curiosity, is there a way to access the function using the terminal and
see what's inside there?


Answer: You can use "inspect" library to do that, but it will work only if you have
the source code of the "hidden_lib" somewhere on your machine:

    
    
    >>> import hidden_lib
    >>> import inspect
    >>> print inspect.getsource(hidden_lib.train_classifier)
    

Otherwise library will throw the exception:

    
    
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Python27\lib\inspect.py", line 701, in getsource
        lines, lnum = getsourcelines(object)
      File "C:\Python27\lib\inspect.py", line 690, in getsourcelines
        lines, lnum = findsource(object)
      File "C:\Python27\lib\inspect.py", line 529, in findsource
        raise IOError('source code not available')
    IOError: source code not available
    

In such a case you need to decompile .pyc file first. To do that you need to
go to the:

    
    
    https://github.com/wibiti/uncompyle2 
    

then download the package, go to the package folder and install it:

    
    
    C:\package_location> C:\Python27\python.exe setup.py install
    

Now you can easily find location of the library by typing [1]:

    
    
    >>> hidden_lib.__file__
    

Then go to the pointed directory and unpyc the file:

    
    
    >C:\Python27\python.exe C:\Python27\Scripts\uncompyle2 -o C:\path_pointed_by_[1]\hidden_lib.py C:\path_pointed_by_[1]\hidden_lib.pyc
    

Sources should be decompiled seccessfully:

    
    
    # 2016.05.07 17:47:36 Central European Daylight Time
    +++ okay decompyling hidden_lib.pyc
    # decompiled 1 files: 1 okay, 0 failed, 0 verify faile
    # 2016.05.07 17:47:36 Central European Daylight Time
    

And now you can display sources of functions exposed by hidden_lib in a way I
described at the beginning of the post. If you are using iPython you can use
also embedded function help(hidden_lib.train_classifier) to do exactly the
same.

IMPORTANT NOTE: uncompyle2 library (that I used) works only with Python 2.7,
if you want to do the same for Python 3.x you need to find other similar
library.

