Header Ads

change import pattern in python



Sometimes we want to provide selected packages and classes import in a certain way and not using the path it is actually implemented. One of the example is Pandas package in python.

when we want to create a Dataframe in pandas we import pandas and do something like


1
2
import pandas as pd
df=pd.DataFrame()

but when we see source code of pandas library, DataFrame code is actually in pandas/core/Frame.py.

Lets see how pandas allows user to access dataframe class using pandas module in place of actual path pandas.core.Frame.DataFrame.

Pandas package has __init__.py files which contains import code like


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#pandas/__init_.py

from pandas.core.api import (

...

...

Dataframe

..)

This init code actually imports DataFrame from pandas/core/api.py


1
2
3
#pandas/core/api.py

from pandas.core.frame import DataFrame

now we can easily access DataFrame from pandas package.
This pattern is used frequently to give user friendly api along with modular design.

No comments

Powered by Blogger.