r-lib / R6

Encapsulated object-oriented programming for R
https://R6.r-lib.org
Other
403 stars 56 forks source link

[Question] Is there a hook function that runs when an instance is cloned? #204

Open dipterix opened 4 years ago

dipterix commented 4 years ago

Is there any way to register a function "clone_hook" so that it automatically runs every time an instance is cloned?

Right now I have to do things like

a <- b$clone()
modify_finalizer(a, ...)

Maybe it could be better if I can put a hook in class definition which runs before/after an instance is cloned.

wch commented 4 years ago

Sorry, there currently isn't a way to add a hook to run after cloning. But that is an interesting possibility. Can you provide a realistic example of how you would want to use it?

dipterix commented 4 years ago

For example, in my case, if there are multiple instances linking to a shared file, you probably want to register a shared finalizer that only runs once all the registered instances are "gc"ed. If using default finalize method, the file will be removed upon the first instance gets "gc"ed. At current stage, if I want to clone an object, I have to manually register for shared garbage collection, but that's not user-friendly:

# A copy of e1
e2 <- e1$clone()

# unfortunately, we have to manually register finalizer
shared_finalizer(e2, key = e2$file_path)

I think there could be multiple other examples as long as they are related to external connections: database, http requests etc. In the hook function, one can also define what's "deep copy" or "shallow copy" on something that R6 cannot control (like externalptr, or connections).