Sometimes I want to include a module in some other subroutine but I only need several subroutines from that module. What is the difference between
use a_module, only: a_subroutine
or simply
use a_module
?
Sometimes I want to include a module in some other subroutine but I only need several subroutines from that module. What is the difference between
use a_module, only: a_subroutine
or simply
use a_module
?
Here is a complete answer, some of which has already been discussed in the comments.
From Metcalf et al. (2011) p.146 (a leading Fortran reference textbook), use a_module
provides (emphasis added):
access to all the public named data objects, derived types, interface blocks, procedures, generic identifiers, and namelist groups in the module named.
Conversely, use a_module, only an_entity
provides:
access to an entity in a module only if the entity ... is specified.
i.e. use a_module
is equivalent to the not-recommended (e.g. in [2]) python practice:
from a_module import *
while use a_module, only an_entity
is equivalent to the preferred python practice:
from a_module import an_entity
Unfortunately, the recommended python practice
import module [as name]
or
import module.submodule [as name]
is not available in Fortran since Fortran imports all entities into a global namespace rather than accessing entities from modules via the module's namespace as done in python, e.g.:
import numpy as np
array = np.array([1, 2, 3])
As noted in the comments and elsewhere (e.g. [3]), explicit imports (use a_module, only an_entity
) are preferred over implicit imports (use a_module
) for code clarity and to avoid namespace pollution / name clashes ("explicit is better than implicit").
Metcalf et al. (2011) also note that should you require two entities with the same name from different modules, name clashes can be avoided by renaming one (or both) of the clashing entities locally (i.e. within your program / module only), e.g.
use stats_lib, only sprod => prod
use maths_lib, only prod
where prod
from stats_lib
is accessed locally using the name sprod
, while prod
from maths_lib
is accessed locally using the name prod
.
Incidentally, Metcalf et al. (2011) also note:
A name clash is permitted if there is no reference to the name in the scoping unit.
i.e. you can successfully compile:
use stats_lib
use maths_lib
without problems provided neither module's prod
(or any other clashing name) is used in your program / module. However, for the reasons above, such practice is not recommended.
[1] Metcalf, M, Reid, J & Cohen, M. (2011) "Modern Fortran Explained" (Oxford University Press)
[2] https://www.tutorialspoint.com/python/python_modules.htm