I'm using rpy2
to wrap R libraries (modules in Python speak) within python, through the importr
function provided by this module.
The issue is that importr
can be very expensive at runtime (it does a number of things when invoked) and I'd like to have it called just once (for each importr
call I have several functions using its result, and at the same time I can't just put everything on top of the module, or it would slow import time significantly).
Currently, for each module where I use importr
I do:
myrlib = None
def do_stuff_with_r(param):
global myrlib
if myrlib is None:
myrlib = importr(myrlib)
I'd like to generalize it since I do this kind of operation in many different modules and thus these lines are duplicated all over.
However I'm not sure how to do this: this solution returns None after the first invocation, which is not really what I'd like to do. Assuming this is doable, how do I ensure importr()
for a specific argument is called just once?