ClementWalter
ClementWalter

Reputation: 5324

Export all hidden functions from a package

Is there a way to automatically import all hidden functions from a package, ie functions accessible only with package:::fun ?

Indeed I have brought some modifications to a given function which uses quite a lot of internal functions and I want to avoid retyping package::: everywhere.

I looked at loadNamespace base function but it does not attach the non exported ones.

Upvotes: 10

Views: 3032

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 546083

I don’t think dumping non-exported names from a package into the current environment is ever a good idea:1 there’s a reason why these functions are not exported, and at the point where you find yourself accessing them in bulk you should stop and rethink your approach.

Given your specific use-case (edit a function from a package that needs to use non-exported names internally), a better solution would be to assign the package namespace as the function’s environment:

the_edited_function = function (…) { … }
environment(the_edited_function) = asNamespace('the_package')

… of course it goes without saying that this is also a horrible hack and should rarely be necessary.


1 It can be done with a single expression:

list2env(as.list(asNamespace('the_package'), all.names = TRUE), envir = environment())

… but, really, don’t do this.

Upvotes: 3

ClementWalter
ClementWalter

Reputation: 5324

Ok I finally found sort of a hack using this related post and eval:

# get all the function names of the given package "mypack"
r <- unclass(lsf.str(envir = asNamespace("mypack"), all = T))

# filter weird names
r <- r[-grep("\\[", r)]
r <- r[-grep("<-", r)]

# create functions in the Global Env. with the same name
for(name in r) eval(parse(text=paste0(name, '<-mypack:::', name)))

I would have thought there were some prebuilt function to do this anyway.

Upvotes: 10

Related Questions