Home > Enterprise >  Viewing the source code behind python modules such as Pandas and Random
Viewing the source code behind python modules such as Pandas and Random

Time:12-19

I would like to see how to view the code behind these modules, such as how randint from random works, etc.

import pandas
import random

For example:

print(pandas.file)
print(random.file)

CodePudding user response:

The source code for most built-in Python modules is located on GitHub, in the python/cpython repository.

The source code for third-party modules (which is what pandas is) can typically be found on a link on their PyPI page (https://pypi.org/project/<module name>).

For example:


Many modules, such as pandas, are actually a large collection of files, so there is not one file containing every function.

In some cases, however, you can use inspect.getsource (a Python built-in function) to return a string containing the source code for the object:

>>> import inspect
>>> import random
>>> print(inspect.getsource(random))
"""Random variable generators.

    bytes
    -----
           uniform bytes (values between 0 and 255)

    integers
    --------
           uniform within range

    sequences
    ---------
           pick random element
           pick random sample
           pick weighted random sample
           generate random permutation

.....

CodePudding user response:

This will print the file path on your machine where Python is importing those modules from.

import pandas
import random
print(pandas.__file__)
print(random.__file__)

Output:

C:\Users\xxxx\Anaconda3\lib\site-packages\pandas\__init__.py
C:\Users\xxxx\Anaconda3\lib\random.py

You can go to those files and view the source code.

  • Related