Reputation: 5504
I am serializing objects with the serialize
function.
For example
serialize_object <- serialize(some_object, NULL)
Now I have an issue with closures. For example:
closure <- function(){
member <- NULL
list(init=function(val){member <<- val})
}
closure_serialized <- serialize(closure(), NULL)
This raw object closure_serialized
is huge: some 200MB. I am quite sure that also the environment in which it is made is serialized. But I don't need its environment. I only need the closure and its contents.
Am I doing something wrong? Am I initializing or defining the closure in a wrong way? How can I make it only to serialize the closure and not the rest of the environment? Serializing closures from some packages do not have this effect, and I can not find the culprit.
Upvotes: 2
Views: 262
Reputation: 5504
This is mainly because the definition of the closure is within a function.
fn <- function(){
# make big variables
closure <- function(){
member <- NULL
list(init=function(val){member <<- val})
}
closure_serialized <- serialize(closure(), NULL)
}
# serialize will copy the environment within the function in closure_serialized
fn()
The serialize
function will in that case copy the environment also. A "workaround" is to place the definition of the closure in the global environment.
closure <- function(){
member <- NULL
list(init=function(val){member <<- val})
}
fn <- function(){
# make big variables
closure_serialized <- serialize(closure(), NULL)
}
# serialize will not copy the global environment.
fn()
The serialize
doesn't copy .GlobalEnv
environment. See also here for a related topic.
Upvotes: 2