Skip to content

S7 and a new := named-bind operator #7801

Description

@hadley

The dev version of the S7 package introduces a new := operator:

`:=` <- function(lhs, rhs) {
  cl <- sys.call()
  if (!is.symbol(cl[[2L]])) {
    stop2("Left-hand side of `:=` must be a symbol.")
  }
  if (!is.call(cl[[3L]])) {
    stop2("Right-hand side of `:=` must be a function call.")
  }
  if ("name" %in% names(cl[[3L]])) {
    stop2("Right-hand side of `:=` must not already supply a `name` argument.")
  }

  cl[[1L]] <- quote(`<-`)
  cl[[3L]]$name <- as.character(cl[[2L]])

  # Can't use eval because it introduces a new frame
  invisible(.Call(S7_eval_bare_, cl, parent.frame()))
}

This is designed to support creating new classes and generics (and various more exotic objects) where you want to give an object a name and bind it to that name.

# with <-
foo <- new_class("foo")
bar <- new_generic("bar")

# with :=
foo := new_class()
bar := new_generic()

This feels like a useful and general tool and @lawremi thinks there's some chance it will make it to base R.

The downside is that it conflicts with the existing definitions of := in data.table and rlang which both error to suggest to the user they've done something wrong. (It doesn't actually affect the operation of these packages since both data.table and rlang override the meaning of := via NSE.)

We don't have any solutions to this problem yet (although we're experimenting with a .onLoad hook approach for rlang that we can share when it's done), but I wanted to give y'all a heads up that we're seriously exploring it and give you an opportunity to give feedback to the S7 team.

(cc @t-kalinowski)

Activity

  1. aitap commented on Jun 24, 2026

    @aitap
    Member
  2. hadley commented on Jun 24, 2026

    @hadley
    ContributorAuthor

    It will be added to S7 in the near release, with the hope (pending approval by R core) of being added to base at some point in the future.

    Or maybe a new package that just contains this operator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions