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

Provide infix operators for active and delayed assignment? #424

Closed
hadley opened this issue Feb 28, 2018 · 2 comments
Closed

Provide infix operators for active and delayed assignment? #424

hadley opened this issue Feb 28, 2018 · 2 comments

Comments

@hadley
Copy link
Member

hadley commented Feb 28, 2018

Like %<a-% and %<d-% from pryr.

Or are those too specialised?

@lionel-
Copy link
Member

lionel- commented Feb 28, 2018

I think this is too specialised. Also IMO operators should only be added sparingly because they tend to make R code more difficult to read so the payoff has to be important.

@hadley hadley closed this as completed Feb 28, 2018
@t-kalinowski
Copy link
Member

I just came across this thread while looking for an active assignment operator. I see that rlang has %<~% for delayed assignment. Maybe it makes sense now to add a companion for active bindings? Maybe something like %<+%?

Motivation: in keras, we export %<-active% as a convenient way to create the equivalent of python decorated @property class methods. I was looking at moving some of the python class generating routines to reticulate, but would rather avoid adding symbols to reticulate that are not strictly python related, like %<-active% would be.

It's just a simple:

`%<-active%` <- function(sym, value) {
  makeActiveBinding(substitute(sym), value, parent.frame())
  invisible(value)
}

With intended usage like:

library(keras)

MyClass %py_class% {
  initialize <- function(x) {
    print("Hi from MyClass$initialize()!")
    self$x <- x
  }
  my_property %<-active% function(x = NULL) {
    if(is.null(x))
      cat("my_property accessed\n")
    else 
      cat("my_property assigned value:", x, "\n")
  }
}

inst <- MyClass("foo")
#> [1] "Hi from MyClass$initialize()!"
inst$x
#> [1] "foo"
inst$my_property
#> my_property accessed
#> NULL
inst$my_property <- "bar"
#> my_property assigned value: bar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants