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

Escape non-method members with I() #222

Open
lionel- opened this issue Dec 2, 2020 · 4 comments
Open

Escape non-method members with I() #222

lionel- opened this issue Dec 2, 2020 · 4 comments

Comments

@lionel-
Copy link
Member

lionel- commented Dec 2, 2020

So these would be equivalent:

R6::R6Class("class",
  public = list(
    x = I(my_function)
  )
)

R6::R6Class("class",
  public = list(
    initialize = function() self$x = my_function,
    x = NULL
  )
)

Context at r-lib/coro#30.

@gaborcsardi
Copy link
Member

So this would be up to the user that implements the R6 class, right? I am not sure how R6 would be able to tell the difference.

@lionel-
Copy link
Member Author

lionel- commented Dec 2, 2020

Right, I() would be syntax sugar for the user.

I guess in theory escaping non-methods could be done automatically for functions with a class or with a non-local environment. It'd probably be dangerous to introduce this behaviour now though.

@wch
Copy link
Member

wch commented Dec 2, 2020

@gabor This could work by having the generator look for functions with the AsIs class, and not reassigning the environment for those functions.

How often do you guys think this comes up? I personally haven't encountered a situation where I've wanted to do this. I have wanted Java-style static classes, though, where methods and values exist on the class itself. That could help cases where functions and values need to be shared among members.

For example, it might look something like this:

Foo <- R6Class("Foo",
  static = list(
    x_2 = function() self$x * 2
    x = 1
  ),
  public = list(
    ....
  )
)

Foo$x
#> 1
Foo$x_2()
#> 2

# Can still instantiate objects
a <- Foo$new()

But I think it might be too late to do that at this point, since it would require changing the internal structure of the generator object, but I suspect there's code out there that depends on the existing internal structure.

@iqis
Copy link

iqis commented Jan 19, 2021

Can the following work?

  • add a static argument to R6Class()
  • put whatever's in static into generator$static
  • make active bindings in the instance level that grabs from the generator$static

This is will inadvertently maintain a reference to the generator. Does this mean that every parent of the generator all the way up to global env will get captured when serializing an instance and is hence hazardous, as mentioned in #225 ?

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

4 participants