'How to prevent exception and class name conflict in R?

It just came to my attention that if in R I were to write something like this

tryCatch({
    myfunc()
  }, NotCoverged = function(e) {}
)

Some issues would arise if myfunc() has the following scenario:

myfunc <- function() {
     package1::operation()
     package2::another_operation()
}

now imagine that both package1 and package2 have a condition called NotConverged, with the exact same name. Obviously, package1::operation stops with its own package1 NotConverged, and package2::another_operation stops with its own package2 NotConverged. I would not be able to differentiate if the first call or the second call has raised it. Resolution is only done by name, and the tryCatch handler would be called regardless, and would not be able to differentiate.

Similar situation may occur with class names in S3 resolution: if I have two packages defining the same class name. e.g. package1 defines:

create_obj <- function() {
    obj <- new.env()
    class(obj) <- c("whatever")
}

and a completely unrelated package2 also defines

create_obj <- function() {
    obj <- new.env()
    class(obj) <- c("whatever")
}

if each package defines print.whatever as an S3 method, what happens if I call, in my code that uses both package1 and package2, print(package1::create_obj()) vs print(package2::create_obj())? It is my understanding it's "whoever got imported first" so you might end up calling the S3 method for the package1 whatever passing a package2 whatever object, which would likely be very bad, as they are completely unrelated with the exception of the name collision.

Are there any rules or code practice that namespaces conditions and class names in packages so that collisions between unrelated packages cannot occur?

r


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source