Skip to content Skip to sidebar Skip to footer

Importing External Package Once In My Module Without It Being Added To The Namespace

I apologize for not being able to phrase my question more easily. I am writing a large package that makes extensive use of pandas in almost every function. My first instinct, natur

Solution 1:

...by importing pandas from the __init__.py call I can define some pandas' options there (like pandas.options.display.expand_frame_repr) and it will be valid throughout the module.

They will be anyway. The module is only loaded the first time you call import pandas. At that point a reference to the module is stored in a module dictionary accessible via sys.modules. Any subsequent calls to import pandas in any other module will re-use the same reference from sys.modules, so any options you changed will also apply.

Furthermore, re-importing the same package from scratch seems to me that takes longer, but I'm not sure it that is correct.

It should actually be marginally faster, since it doesn't have to resolve relative paths. Once the module has been loaded, subsequent calls work like...

import pandas          # pandas = sys.modules['pandas']
import pandas as pd    # pd = sys.modules['pandas']

Post a Comment for "Importing External Package Once In My Module Without It Being Added To The Namespace"