Rev 71388 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
% File src/library/methods/man/Methods.Rd% Part of the R package, https://www.R-project.org% Copyright 1995-2016 R Core Team% Distributed under GPL 2 or later\name{Methods_Details}\alias{Methods_Details}\title{General Information on Methods}\description{This documentation covers some general topics on how methodswork and how the \pkg{methods} package interacts with the rest of \R. Theinformation is usually not needed to get started with methods andclasses, but may be helpful for moderately ambitious projects, or whensomething doesn't work as expected.For additional information see documentation forthe important steps: (\code{\link{setMethod}()},\code{\link{setClass}()} and \code{\link{setGeneric}()}). Also\code{\link{Methods_for_Nongenerics}} on defining formal methods forfunctions that are not currently generic functions;\link{Methods_for_S3} for the relation to S3 classes and methods;\code{\link{Classes_Details}} for class definitions andChapters 9 and 10 of the reference.}\section{How Methods Work}{A call to a generic function selects a method matching the actualarguments in the call. The body of the method is evaluated in theframe of the call to the generic function.A generic function is identified by its name and by the package towhich it correspond. Unlike ordinary functions, the generic has aslot that specifies its package.In an \R session, there is one version of each such generic,regardless of where the call to that generic originated, andthe generic function has a table of all the methods currentlyavailable for it; that is, all the methodsin packages currently loaded into the session.Methods are frequently defined for functions that are non-generic intheir original package,.for example, for function \code{plot()} inpackage \pkg{graphics}.An identical version of the corresponding generic function may existin several packages. All methods will be dispatched consistentlyfrom the \R session.Each \R package with a call to \code{\link{setMethod}} in its source codewill include a methods metadata object for that generic.When the package is loaded into an \R session, the methods for eachgeneric function are \emph{cached}, that is, added to theenvironment of the generic function. This merged table of methods is used todispatch or select methods from the generic, using class inheritanceand possibly group generic functions (see\code{\link{GroupGenericFunctions}}) to find an applicable method.See the \dQuote{Method Selection and Dispatch} section below.The caching computations ensure that only one version of eachgeneric function is visible globally; although different attachedpackages may contain a copy of the generic function, these behaveidentically with respect to method selection.In contrast, it is possible for the same function name to refer tomore than one generic function, when these have different\code{package} slots. In the latter case, \R considers thefunctions unrelated: A generic function is defined by thecombination of name and package. See the \dQuote{Generic Functions}section below.The methods for a generic are stored according to thecorresponding \code{signature} in the call to \code{\link{setMethod}}that defined the method. The signature associates oneclass name with each of a subset of the formal arguments to thegeneric function. Which formal arguments are available, and theorder in which they appear, are determined by the \code{"signature"}slot of the generic function itself. By default, the signature of thegeneric consists of all the formal arguments except \dots, in theorder they appear in the function definition.Trailing arguments in the signature of the generic will be \emph{inactive} if nomethod has yet been specified that included those arguments in its signature.Inactive arguments are not needed or used in labeling the cachedmethods. (The distinction does not change which methods aredispatched, but ignoring inactive arguments improves theefficiency of dispatch.)All arguments in the signature of the generic function will be evaluated when thefunction is called, rather than using lazyevaluation. Therefore, it's important to \emph{exclude}from the signature any arguments that need to be dealt withsymbolically (such as the \code{expr} argument to function\code{\link{with}}). Note that only actual arguments areevaluated, not default expressions.A missing argument enters into the method selection as class\code{"missing"}.The cached methods are stored in anenvironment object. The names used for assignment are aconcatenation of the class names for the active arguments in the method signature.}\section{Method Selection: Details}{When a call to a generic function is evaluated, a method is selected correspondingto the classes of the actual arguments in the signature.First, the cached methods table is searched for an exact match;that is, a method stored under the signature defined bythe string value of \code{class(x)} for each non-missingargument, and \code{"missing"} for each missing argument.If no method is found directly for the actual arguments in a call to ageneric function, an attempt is made to match the available methods tothe arguments by using the superclass information about the actualclasses.A method found by this search is cachedin the generic function so that future calls with the same argument classes willnot require repeating the search. In any likely application, thesearch for inherited methods will be a negligible overhead.Each class definition may include a list of one or more direct\emph{superclasses} of the new class.The simplest and most common specification is by the \code{contains=} argument inthe call to \code{\link{setClass}}.Each class named in this argument is a superclass of the new class.A class will also have as a direct superclass any class union to whichit is a member.Class unions are created bya call to \code{\link{setClassUnion}}.Additional members can be added to the union by a simple call to\code{\link{setIs}}.Superclasses specified by either mechanism are the \emph{direct} superclasses.Inheritance specified in either of these forms is \emph{simple} in thesense that all the information needed for the superclass is assertedto be directly available from the object.\R inherited from S a more general form of inheritance in whichinheritance may require some transformation or be conditional on atest.This more general form has not proved to be useful in generalpractical situations. Since it also adds some computational costsnon-simple inheritance is not recommended. See \code{\link{setIs}}for the general version.The direct superclasses themselves mayhave direct superclasses andsimilarly through further generations. Putting all this information together producesthe full list of superclasses for this class.The superclass list is included in the definition of the class that iscached during the \R session.The \emph{distance} between the two classes is defined to be thenumber of generations:\code{1} for direct superclasses (regardless of which mechanismdefined them), then \code{2} for the direct superclasses of thoseclasses, and so on.To see all the superclasses, with their distance, print the classdefinition by calling \code{\link{getClass}}.In addition, any class implicitly has class \code{"ANY"} as a superclass. Thedistance to \code{"ANY"} is treated as larger than the distance to anyactual class.The special class \code{"missing"} corresponding to missing argumentshas only \code{"ANY"} as a superclass, while \code{"ANY"} has nosuperclasses.When a method is to be selected by inheritance, a search is made inthe table for all methods corresponding to a combination ofeither the direct class or one of its superclasses, for each argumentin the active signature.For an example, suppose there is only one argument in the signature and that the class ofthe corresponding object was \code{"dgeMatrix"} (from the recommended package\code{Matrix}).This class has (currently) three direct superclasses and through theseadditional superclasses at distances 2 through 4.A method that had been defined for any of these classes or for class\code{"ANY"} (the default method) would be eligible.Methods for the shortest difference are preferred.If there is only one best method in this sense, method selection is unambiguous.When there are multiple arguments in the signature, each argument willgenerate a similar list of inherited classes.The possible matches are now all the combinations of classes from eachargument (think of the function \code{outer} generating an array ofall possible combinations).The search now finds all the methods matching any of this combinationof classes.For each argument, the distance to the superclass defines whichmethod(s) are preferred for that argument.A method is considered best for selection if it is among the best(i.e., has the least distance) foreach argument.The end result is that zero, one or more methods may be \dQuote{best}.If one, this method is selected and cached in the table of methods.If there is more than one best match, the selection is ambiguous and a message isprinted noting which method was selected (the first methodlexicographically in the ordering) and what other methods could havebeen selected.Since the ambiguity is usually nothing the end user could control,this is not a warning.Package authors should examine their package for possible ambiguousinheritance by calling \code{\link{testInheritedMethods}}.Cached inherited selections arenot themselves used in future inheritance searches, since that could resultin invalid selections.If you want inheritance computations to be done again (for example,because a newly loaded package has a more direct method than onethat has already been used in this session), call\code{\link{resetGeneric}}. Because classes and methods involvingthem tend to come from the same package, the current implementationdoes not reset all generics every time a new package is loaded.Besides being initiated through calls to the generic function, methodselection can be done explicitly by calling the function\code{\link{selectMethod}}.Note that some computations may use this function directly, withoptional arguments.The prime example is the use of \code{\link{coerce}()} methods byfunction \code{\link{as}()}.There has been some confusion from comparing coerce methods to a callto \code{\link{selectMethod}} with other options.}\section{Method Evaluation: Details}{Once a method has been selected, the evaluator creates a new contextin which a call to the method is evaluated.The context is initialized with the arguments from the call to thegeneric function.These arguments are not rematched. All the arguments in the signatureof the generic will have been evaluated (including any that arecurrently inactive); arguments that are not in the signature will obeythe usual lazy evaluation rules of the language.If an argument was missing in the call, its default expression if anywill \emph{not} have been evaluated, since method dispatch always usesclass \code{missing} for such arguments.A call to a generic function therefore has two contexts: one for thefunction and a second for the method.The argument objects will be copied to the second context, but not anylocal objects created in a nonstandard generic function.The other important distinction is that the parent(\dQuote{enclosing}) environment of the second context is the environmentof the method as a function, so that all \R programming techniquesusing such environments apply to method definitions as ordinary functions.For further discussion of method selection and dispatch, see thereferences in the sections indicated.}\section{Generic Functions}{In principle, a generic function could be any function that evaluatesa call to \code{standardGeneric()}, the internal function that selectsa method and evaluates a call to the selected method. In practice,generic functions are special objects that in addition to being from asubclass of class \code{"function"} also extend the class\code{\linkS4class{genericFunction}}. Such objects have slots to defineinformation needed to deal with their methods. They also havespecialized environments, containing the tables used in methodselection.The slots \code{"generic"} and \code{"package"} in the object are thecharacter string names of the generic function itself and of thepackage from which the function is defined.As with classes, generic functions are uniquely defined in \R by thecombination of the two names.There can be generic functions of the same name associated withdifferent packages (although inevitably keeping such functions cleanlydistinguished is not always easy).On the other hand, \R will enforce that only one definition of ageneric function can be associated with a particular combination offunction and package name, in the current session or other activeversion of \R.Tables of methods for a particular generic function, in this sense,will often be spread over several other packages.The total set of methods for a given generic function may changeduring a session, as additional packages are loaded.Each table must be consistent in the signature assumed for the genericfunction.\R distinguishes \emph{standard} and \emph{nonstandard} genericfunctions, with the former having a function body that does nothingbut dispatch a method.For the most part, the distinction is just one of simplicity: knowingthat a generic function only dispatches a method call allows someefficiencies and also removes some uncertainties.In most cases, the generic function is the visible functioncorresponding to that name, in the corresponding package.There are two exceptions, \emph{implicit} genericfunctions and the special computations required to deal with \R's\emph{primitive} functions.Packages can contain a table of implicit generic versions of functionsin the package, if the package wishes to leave a function non-genericbut to constrain what the function would be like if it were generic.Such implicit generic functions are created during the installation ofthe package, essentially by defining the generic function andpossibly methods for it, and then reverting the function to itsnon-generic form. (See \link{implicitGeneric} for how this is done.)The mechanism is mainly used for functions in the older packages in\R, which may prefer to ignore S4 methods.Even in this case, the actual mechanism is only needed if somethingspecial has to be specified.All functions have a corresponding implicit generic version definedautomatically (an implicit, implicit generic function one might say).This function is a standard generic with the same arguments as thenon-generic function, with the non-generic version as the default (and only)method, and with the generic signature being all the formal argumentsexcept \dots.The implicit generic mechanism is needed only to override some aspectof the default definition.One reason to do so would be to remove some arguments from thesignature.Arguments that may need to be interpreted literally, or for which thelazy evaluation mechanism of the language is needed, must \emph{not}be included in the signature of the generic function, since allarguments in the signature will be evaluated in order to select amethod.For example, the argument \code{expr} to the function\code{\link{with}} is treated literally and must therefore be excludedfrom the signature.One would also need to define an implicit generic if the existingnon-generic function were not suitable as the default method.Perhaps the function only applies to some classes of objects, and thepackage designer prefers to have no general default method.In the other direction, the package designer might have some ideasabout suitable methods for some classes, if the function were generic.With reasonably modern packages, the simple approach in all thesecases is just to define the function as a generic.The implicit generic mechanism is mainly attractive for older packagesthat do not want to require the methods package to be available.Generic functions will also be defined but not obviously visible forfunctions implemented as \emph{primitive} functions in the basepackage.Primitive functions look like ordinary functions when printed but arein fact not function objects but objects of two types interpreted bythe \R evaluator to call underlying C code directly.Since their entire justification is efficiency, \R refuses to hideprimitives behind a generic function object.Methods may be defined for most primitives, and corresponding metadataobjects will be created to store them.Calls to the primitive still go directly to the C code, which willsometimes check for applicable methods.The definition of \dQuote{sometimes} is that methods must have beendetected for the function in some package loaded in the session and\code{isS4(x)} is \code{TRUE} for the first argument (or for thesecond argument, in the case of binary operators).You can test whether methods have been detected by calling\code{\link{isGeneric}} for the relevant function and you can examinethe generic function by calling \code{\link{getGeneric}}, whether ornot methods have been detected.For more on generic functions, see the references and also section 2of the \emph{R Internals} document supplied with \R.}\section{Method Definitions}{All method definitions are stored as objects from the\code{\linkS4class{MethodDefinition}} class.Like the class of generic functions, this class extends ordinary \Rfunctions with some additional slots: \code{"generic"}, containing thename and package of the generic function, and two signature slots,\code{"defined"} and \code{"target"}, the first being the signature supplied whenthe method was defined by a call to \code{\link{setMethod}}.The \code{"target"} slot starts off equal to the \code{"defined"}slot. When an inherited method is cached after being selected, asdescribed above, a copy is made with the appropriate \code{"target"} signature.Output from \code{\link{showMethods}}, for example, includes bothsignatures.Method definitions are required to have the same formal arguments asthe generic function, since the method dispatch mechanism does notrematch arguments, for reasons of both efficiency and consistency.}\references{Chambers, John M. (2016)\emph{Extending R},Chapman & Hall.(Chapters 9 and 10.)Chambers, John M. (2008)\emph{Software for Data Analysis: Programming with R}Springer. (Section 10.5 for some details.)}\seealso{For more specific information, see\code{\link{setGeneric}}, \code{\link{setMethod}}, and\code{\link{setClass}}.For the use of \dots in methods, see \link{dotsMethods}.}\keyword{programming}\keyword{classes}\keyword{methods}