1

How do I deal with common dependencies within a project?

Lets say I make a package, pack, with some modules, mod1 and mod2. All of the modules need to use some common external modules. For example:

mod1.py: import sys import numpy # define stuff mod2.py: import numpy # define more stuff 

I also want to use the same external modules in my main code:

main.py: import sys import numpy import pack # do the stuff 

In this situation I appear to have multiple copies of numpy and sys loaded i.e.:

numpy pack.mod1.numpy pack.mod2.numpy 

This seems bad. Do I really have multiple numpys or do I have one numpy with three names? Is there a way to avoid this sort of thing? What is the best practice in this case?

1 Answer 1

2

No need to worry, the code in the modules get executed only once when it is imported by your first module. When you import it in the second module, you just get a 'pointer' to the already cached module.

Quick demonstration:

# mod1.py print 'starting mod1' import mod3 print 'finished mod1' # mod2.py print 'starting mod2' import mod3 print 'finished mod2' # mod3.py print 'in mod3' 

Result:

In [2]: import mod1 starting mod1 in mod3 finished mod1 In [3]: import mod2 starting mod2 finished mod2 
Sign up to request clarification or add additional context in comments.

1 Comment

Additionally, I believe the multiple module references only become significant if you start reloading modules. In many ways, Python module imports are similar to import in Java or using in C#.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.