Skip to content

Pass optional message to assert #116

Closed
@milancurcic

Description

@milancurcic

Problem

Current implementation of assert in stdlib_experimental_error always prints the same message on failure:

subroutine assert(condition, code)
  logical, intent(in) :: condition
  integer, intent(in), optional :: code
  if (.not. condition) call error_stop("Assert failed.", code)
end subroutine

As is, if asserts fail, they tell you that they failed, but nothing more.

It's quite useful to be able to pass a custom message to assert. For example:

call assert(x < 3, "Error: x must be < 3")

would tell you why the assertion failed. This approach is especially useful during development, but could also be useful in production, for example to validate user inputs.

This is equivalent to Python's:

assert x < 3, "Error: x must be < 3"

Solution

This implementation would allow the user to optionally pass a custom message:

use stdlib_experimental_optval, only: optval

subroutine assert(condition, msg, code)
  logical, intent(in) :: condition
  character(*), intent(in), optional :: msg
  integer, intent(in), optional :: code
  if (.not. condition) call error_stop(optval(msg, "Assert failed."), code)
end subroutine

The solution is straightforward and backward compatible, assuming any existing code passed the optional code as a keyword argument.

I'd like to get support here before writing up a spec and a PR (both will be quite straightforward).

@certik @nncarlson @jvdp1 @ivan-pi @rweed What do you think? Anything I missed?

This issue is related to #72.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ideaProposition of an idea and opening an issue to discuss ittopic: utilitiescontainers, strings, files, OS/environment integration, unit testing, assertions, logging, ...

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions