Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@ accessor for attributes from non-S4 objects #207

Closed
jimhester opened this issue Jul 10, 2017 · 5 comments
Closed

@ accessor for attributes from non-S4 objects #207

jimhester opened this issue Jul 10, 2017 · 5 comments
Labels

Comments

@jimhester
Copy link
Member

It would be nice to provide the @ accessor for non-S4 objects, like you can with S4 slots (which are implemented as attributes anyway). A simple R implementation

`@` <- function(x, which) {
  if (isS4(x)) {
    base::`@`(x, which)
  } else {
    attr(x, deparse(substitute(which)), exact = TRUE)
  }
}

`@<-` <- function(x, which, value) {
  if (isS4(x)) {
    base::`@<-`(x, which, value)
  } else {
    `attr<-`(x, deparse(substitute(which)), value)
  }
}

x <- 1
x@a <- 2
x@a
#> [1] 2
x@b
#> NULL

Some thoughts on this

  1. Currently rlang does not mask any functions from base R. We could define this on-load to avoid the warning about masking @ if we wanted.
  2. The real implementation might be better off in C.
  3. I think using exact = TRUE is probably best, but it is a departure to how $ works in base R.
  4. Do we want to return NULL for missing attributes, or an error?

I think it would be nice to have this in rlang so we could start using it today, but alternatively we could propose the change to R-devel instead.

cc/ @hadley

@hadley
Copy link
Member

hadley commented Jul 10, 2017

Ideally, we should propose to R-devel, and provide a backport in rlang.

I agree that exact = TRUE is the desired behaviour.

@lionel- lionel- added the obj label Mar 9, 2018
@lionel-
Copy link
Member

lionel- commented Sep 28, 2018

In the meantime I have added a replacement variant of %@%.

@hadley
Copy link
Member

hadley commented Sep 28, 2018

It feels a bit weird that %@%<- doesn't require quotes, but %@% does

@lionel-
Copy link
Member

lionel- commented Sep 28, 2018

oh I hadn't realised that that %@% wasn't a quoting function. It feels like it should be?

@lionel-
Copy link
Member

lionel- commented Sep 28, 2018

Maybe I should also add Jim's S4 handling, then it's easy to override @ in the globalenv or in a namespace with

`@` <- rlang::`%@%`
`@<-` <- rlang::`%@%<-`

@lionel- lionel- reopened this Sep 28, 2018
lionel- added a commit that referenced this issue Oct 1, 2018
@lionel- lionel- closed this as completed in 1191202 Oct 1, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants