Daniel Alarcon
Daniel Alarcon

Reputation: 149

How to Deal with Redundant/Repeated Imports in Python Modules?

I am writing a python module with multiple files, and files in sub-directories.

For example, lets say the base directory is ./package, sub-directory ./package/sub and files ./package/sub/file1.py and ./package/file2.py.

In ./package/sub/file1.py, I imported the following third-party modules:

import pickle
import numpy as np

In ./package/file2.py, I imported the same modules from earlier, as well as the module present in the sub folder like so:

import pickle
import numpy as np
import sub.file1 as sub

Now, it turns out that sub has its own version of pickle under sub.pickle, and then file1 and file2 has their own version of pickle. Is there any way to remove this kind of redundancy?

If it is not a problem, does anyone know if both pickle imports will refer to the same region of memory?

Is there a better way I could have designed my code around imports?

Upvotes: 8

Views: 2642

Answers (1)

nosklo
nosklo

Reputation: 222822

You don't have to do anything. Python import system uses a cache (in the sys.modules dictionary) to prevent a module from being imported twice. Calling import with the same name anywhere in your code will yield the same module object from the first time, thus making module objects kind of "singletons".

Upvotes: 13

Related Questions