Stein
Stein

Reputation: 3277

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.

Upvotes: 17

Views: 9644

Answers (2)

Rodrigo Rodrigues
Rodrigo Rodrigues

Reputation: 8566

Disclaimer:

Someone has already 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:

  1. 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
    
  2. 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
    
  3. 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
    

Upvotes: 6

Ian Bush
Ian Bush

Reputation: 7432

Two main reasons

  1. 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
  2. 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!

Upvotes: 23

Related Questions