About 'use a_module, only: a_subroutine' - fortran

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
[3] http://www.fortran90.org/src/best-practices.html

Related

Why should I use "use, only" in Fortran

In python a statement like this:
from module import function354
makes sense, because Python is an interpreter language and I don't want python to load all 353 other functions.
Fortran has a similar construct:
use module, only : function354
Why would I use this? The compiler creates a *.mod file anyway, compiling all function. Is there any performance advantage (in compile or run time) if I specify an only-statement?
I can see that it might be helpful to avoid naming conflict, but other than that I don't really see the point.
Two main reasons
To avoid name conflicts, as you mention but seem to think unimportant. In a large, complex code anything that helps maintainability is a bonus, so use, only is a useful addition to aid this
It automatically documents where an entity comes from. Given a large, complex code to read for the first time I can almost guarantee you'll be spending time working out what comes from which module, so use, only is a nice feature to aid code readability
You don't just want fast code - as important is maintainability, and more important is correctness!
Disclaimer:
Some people has pointed (correctly) in the comments that use rename => name can be used independently of use, only. Like this:
use module, f354 => function354
I am keeping the answer because it could be useful as complementary information on the use statement for someone that lands here.
Original Answer:
Just for completeness, there is another feature that use, only provides, that is the ability to rename imported names with locally-bound names (only is not needed for this, see disclaimer above).
Like this:
use module, only: f354 => function354
That has proven useful for me in several different scenarios:
Resolve specific name ambiguities when two used modules provide types or functions with the same name.
Example:
use module1, only: m1_init => initialize
use module2, only: m2_init => initialize
Use short names when the original name is too long, too cryptic or when it is used very often in your program.
Example (from fgsl and lapack):
use fgsl, only: stride => fgsl_aux_vector_double_stride ! too long
use lapack, only: solve => dgesvx ! too cryptic
use iso_c_binding, only: i32 => c_int32_t, i64 => c_int64_t ! too frequent
Make it easier to refactor or use conditional compilation / templating:
Example (from Fortran-lang/stdlib):
use iso_fortran_env, only: sp => real32, dp => real64, qp => real128
! If we decide later to use iso_c_binding instead of iso_fortran_env:
! use iso_c_binding, only: sp => c_float, dp => c_double, qp => c_float128

How should I name modules? They often conflict with local variables

I'm starting my first large python project, and I'm running into a common issue. I'll have some file response.py that is purely functional and has no classes. I often end up doing this:
from my_cookbook.util import response
...
def foo():
response = bar.get_response()
response.baz(response)
The reponse module operates on the response variable, which of course conflicts. PEP8 says package and module names should be lowercase, as should local variables.
Question: Is there a way I can mitigate the amount of naming conflicts I get without sacrificing readability of both module and variable names?

How do I specify runtime constants in (modern) Fortran?

I'm working on a Fortran 2008 project in which I read some parameters (including both scalars and arrays) from an input file using read statements. I would like to enforce that these parameters not be modified after they are read in. How can I achieve this?
Module variables can be given the PROTECTED attribute, which prevents code USE'ing the relevant module from modifying the module variable through the name of the variable.
However this does not prevent modifications to the variable from within the defining module or its descendant submodules, or modifications to the variable through means other than the use associated name (e.g. through a pointer associated with the same thing), or stop non-conforming Fortran code from modifying the variable (e.g. by the use associated name being used as an actual argument to a procedure with implicit interface that modifies the corresponding dummy).
In fortran 90, You can define a module that has those variables as private member. Let the module define only the function to read your variables from file, and getter functions that return their values. And no other function in the module.
I do not use the OO capability offer by fortran 2003 an fortran 2008, but the scenario will be similar.

What happened to ifilter?

In comparing documentation for itertools between Python 2 and 3, I noticed ifilter, imap, izip are missing from Python 3. I suspect this is because many builtin keywords have been converted to generators and replaced former keywords, but it is unclear in this case.
Is it true ifilter, imap, izip are now equivalent to filter, map, zip in Python 3? If not, where can I find rationales for why certain methods were removed from current itertools?
Python 2.3 introduced the itertools module, which defined variants of the global zip(), map(), and filter() functions that returned iterators instead of lists. In Python 3, those global functions return iterators, so those functions in the itertools module have been eliminated.
Instead of itertools.izip(), just use the global zip() function.
Instead of itertools.imap(), just use map().
itertools.ifilter() becomes filter().
The itertools module still exists in Python 3, it just doesn’t have the functions that have migrated to the global namespace. The 2to3 script is smart enough to remove the specific imports that no longer exist, while leaving other imports intact.
Read more here

What is the opposite of PyMODINIT_FUNC in Python 2.x C extension modules?

I need to import one of the core modules (datetime) inside my C extension module since I want to return a datetime.date from some functions of my module.
It appears that Python C extension modules have no complement for the PyMODINIT_FUNC upon destruction.
Question: What can I do short of importing the required module time and time again in every call inside my C extension module and then dereferencing it at the end of the call(s) again?
Rationale: Basically I fear that this (importing it over and over again) creates an unnecessary overhead, because from my understanding of the documentation dereferencing it means that the garbage collector can come around and collect it, so next time PyImport_ImportModule would have to be called again.
Somewhat related questions:
Import and use standard Python module from inside Python C extension
Making a C extension to Python that requires another extension