enforce_types: Enforced typing in R *[Experimental]*

View source: R/typing.R

enforce_typesR Documentation

Enforced typing in R [Experimental]

Description

This function allows for simple type enforcement in R inspired by C++ and other compiled languages. There are currently six primitive types which the function handles:

Usage

enforce_types(level = c("error", "warn", "none"))

Arguments

level

Should type failures error, warn, or be skipped (none)?

Details

  • int(): An integer specified with the L syntax (i.e., '1L“)

  • chr(): A string or character

  • lgl(): A boolean TRUE/FALSE

  • dbl(): A double or numeric value

  • tbl(): A data frame or tibble (types within the data frame are not checked)

You can also provide default arguments within the parenthesis of the type. This is shown in the example below. You can provide new arguments as well. The function has knowledge of the function declaration when it runs. Note: types are checked at runtime not when the function is declared.

Examples

foo <- function(
  x = int(1L),
  y = chr("Hello!"),
  z = lgl(TRUE),
  a = dbl(1.1),
  b = tbl(mtcars),
  c = NULL # This argument will not be checked
) {

  # Simply place enforce_types() in your function header!
  dataclass::enforce_types()

  # Function logic ...
}

# This run the function with the type defaults
foo()

# This will check types but for new arguments
foo(2L, "Hi!", FALSE, 1.2, mtcars)

# This would fail because types are incorrect!
# foo(1.1, FALSE, NULL, "Hi", list())

# This function will only warn when there are type failures
bar <- function(x = int(1)) {
  dataclass::enforce_types("warn")
}

dataclass documentation built on Sept. 24, 2024, 5:07 p.m.