The R Project SVN R

Rev

Rev 71366 | Rev 88914 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
42333 ripley 1
% File src/library/methods/man/setGeneric.Rd
68948 ripley 2
% Part of the R package, https://www.R-project.org
71228 maechler 3
% Copyright 1995-2016 R Core Team
42333 ripley 4
% Distributed under GPL 2 or later
5
 
15357 jmc 6
\name{setGeneric}
56186 murdoch 7
\alias{setGeneric}
71366 jmc 8
\title{Create a Generic Version of a Function}
15357 jmc 9
\description{
71366 jmc 10
  Create a generic version of the named function so that methods may
11
  be defined for it.  A call to \code{\link{setMethod}} will call
12
  \code{setGeneric} automatically if applied to a non-generic
13
  function.
14
 
15
  An explicit call to \code{setGeneric} is usually not required, but
16
  doesn't hurt and makes explicit that methods are being defined for a
17
  non-generic function.
18
 
19
  Standard calls will be of the form:
20
 
21
  \code{setGeneric(name)}
22
 
23
  where \code{name} specifies an existing function, possibly in another
24
  package.  An alternative when creating a new generic function in this package is:
25
 
26
  \code{setGeneric(name, def)}
27
 
71388 ripley 28
  where the function definition \code{def} specifies the formal
71366 jmc 29
  arguments and becomes the default method.
30
 
15357 jmc 31
}
32
\usage{
44243 ripley 33
setGeneric(name, def= , group=list(), valueClass=character(),
34
           where= , package= , signature= , useAsDefault= ,
46546 jmc 35
           genericFunction= , simpleInheritanceOnly = )
15357 jmc 36
}
37
\arguments{
45824 jmc 38
  \item{name}{ The character string name of the generic function.
15571 ripley 39
  }
71366 jmc 40
  \item{def}{An optional function object, defining the non-generic
41
      version, to become the default method.  This is equivalent in
42
      effect to assigning \code{def} as the function and then using
43
      the one-argument call to \code{setGeneric}.
26530 maechler 44
 
71366 jmc 45
      \emph{The following arguments are specialized, optionally used
46
        when creating a new generic function with non-standard
47
        features. They should not be used when the non-generic is in
48
        another package.}
58136 jmc 49
 
15357 jmc 50
  }
71366 jmc 51
  \item{group}{ The name of the group
69538 ripley 52
    generic function to which this function belongs.  See
71366 jmc 53
    \link{Methods_Details} for details of group generic functions in method
71388 ripley 54
    selection and \link{S4groupGeneric} for existing groups.
15571 ripley 55
  }
71366 jmc 56
  \item{valueClass}{ A character vector specifying one or more class
50786 maechler 57
    names.  The value returned by the generic function must
42679 ripley 58
    have (or extend) this class, or one of the classes; otherwise,
45824 jmc 59
    an error is generated.
42679 ripley 60
  }
21345 jmc 61
  \item{signature}{
71366 jmc 62
    The vector of names from among the formal arguments to
63
    the function, that will be allowed in the signature of methods for this
64
    function, in calls to \code{\link{setMethod}}.  By default and
65
    usually, this will be all formal arguments except \code{\dots}.
66
 
67
    A non-standard signature for the generic function may be
68
    used to exclude arguments that take advantage of lazy evaluation;
69
    in particular, if the argument may \emph{not} be evaluated then it
70
    cannot be part of the signature.
71
 
72
    While \code{\dots} cannot be used as part of a general signature,
73
    it is possible to have this as the \emph{only} element of the
74
    signature.
75
    Methods will then be selected if their signature matches
69538 ripley 76
    all the \code{\dots} arguments.  See the documentation for topic
71366 jmc 77
    \link{dotsMethods} for details.  It is not
78
    possible to mix \code{\dots} and other arguments in the signature.
46314 jmc 79
 
71366 jmc 80
    It's usually a mistake to omit arguments from the signature in the
81
    belief that this improves efficiency.  For method selection, the
82
    arguments that are used in the signatures for the \emph{methods}
83
    are what counts, and then only seriously on the first call to the
84
    function with that combination of classes.
15571 ripley 85
  }
46546 jmc 86
  \item{simpleInheritanceOnly}{
50786 maechler 87
    Supply this argument as \code{TRUE} to require that methods selected
88
    be inherited through simple inheritance only; that is, from
89
    superclasses specified in the \code{contains=} argument to
90
    \code{\link{setClass}}, or by simple inheritance to a class union or
91
    other virtual class.  Generic functions should require simple
92
    inheritance if they need to be assured that they get the complete
93
    original object, not one that has been transformed.  Examples of
94
    functions requiring simple inheritance are \code{\link{initialize}},
95
    because by definition it must return an object from the same class
96
    as its argument, and \code{\link{show}}, because it claims to give a
97
    full description of the object provided as its argument.
71366 jmc 98
 
46546 jmc 99
  }
71366 jmc 100
  \item{useAsDefault}{
101
    Override the usual default method mechanism.  Only relevant when
102
    defining a nonstandard generic function.
103
    See the section \sQuote{Specialized Local Generics}.
18558 jmc 104
 
71366 jmc 105
    \emph{The remaining arguments are obsolete for normal applications.}
42679 ripley 106
  }
71366 jmc 107
  \item{package}{ The name of the package with which this function is
108
    associated.  Should be determined automatically from the
109
    non-generic version.
110
 
111
  }
112
  \item{where}{ Where to store the resulting objects as side effects.
113
      The default, to store in the package's namespace, is the only
114
      safe choice.
115
  }
116
  \item{genericFunction}{Obsolete.}
15357 jmc 117
}
45824 jmc 118
\section{Basic Use}{
15357 jmc 119
  The \code{setGeneric} function is called to initialize a generic
50786 maechler 120
  function as preparation for defining some methods for that function.
15357 jmc 121
 
71366 jmc 122
  The simplest and most common situation is that \code{name} specifies
123
  an existing function, usually in another package. You now want to
124
  define methods for this function.  In this case you should
50786 maechler 125
  supply only \code{name}, for example:
16764 jmc 126
 
45824 jmc 127
    \code{setGeneric("colSums")}
128
 
71366 jmc 129
  There must be an existing function of this name (in this case in
130
  package \code{"base"}).  The non-generic function can be in the same
131
  package as the call, typically the case when you are creating a new
132
  function plus methods for it. When the function is in
133
  another package, it must be available by name, for
134
  example through an \code{importFrom()} directive in this package's
135
  \code{NAMESPACE} file. Not required for functions in \code{"base"},
136
  which are implicitly imported.
137
 
138
  A generic version of
139
  the function will be created in the current package.  The existing function
50786 maechler 140
  becomes the default method, and the package slot of the new generic
141
  function is set to the location of the original function
71366 jmc 142
  (\code{"base"} in the example).  
45824 jmc 143
 
71366 jmc 144
  Two special types of non-generic should be noted.
145
  Functions that dispatch S3 methods by calling
146
  \code{\link{UseMethod}} are ordinary functions, not objects from the
147
  \code{"genericFunction"} class.  They are made generic like any
148
  other function, but some special considerations apply to ensure that
149
  S4 and S3 method dispatch is consistent (see \link{Methods_for_S3}).
45824 jmc 150
 
71366 jmc 151
  Primitive functions are handled in C code and don't exist as normal
152
  functions.
153
  A call to \code{setGeneric} is allowed in the simple form, but no
154
  actual generic function object is created.  Method dispatch will
155
  take place in the C code. See the section on Primitive Functions for
156
  more details.
45824 jmc 157
 
71366 jmc 158
  It's an important feature that the
159
  identical generic function definition is created in every package that
160
  uses the same \code{setGeneric()} call.
161
  When any of these packages is loaded into an \R session, this
162
  function will be added to a table of generic functions, and will
163
  contain a methods table of all the available methods for the
164
  function.
69636 lawrence 165
 
71366 jmc 166
  Calling \code{setGeneric()} is not strictly
167
  necessary before calling \code{setMethod()}.  If
168
  the function specified in the call to \code{setMethod} is not generic,
169
  \code{setMethod} will execute the call to \code{setGeneric} itself.
170
  In the case that the non-generic is in another package, does not
171
  dispatch S3 methods and is not a primitive, a message is printed noting the
172
  creation of the generic function the first time \code{setMethod} is called.
45824 jmc 173
 
50786 maechler 174
  The second common use of \code{setGeneric()} is to create a new
71366 jmc 175
  generic function, unrelated to any existing function.  See the
176
  \code{asRObject()} example below.
177
  This case can be handled just like the previous examples, with only
178
  the difference that the non-generic function exists in the
179
  current package.
180
  Again, the non-generic version becomes the default method.
181
  For clarity it's best for the assignment to immediately precede the
182
  call to \code{setGeneric()} in the source code.
18976 jmc 183
 
71366 jmc 184
  Exactly the same result can be obtained by supplying the default as
185
  the \code{def} argument instead of assigning it.
186
  In some applications, there will be no completely general default
187
  method. While there is a special mechanism for this (see the
188
  \sQuote{Specialized Local Generics} section), the recommendation is to provide a
189
  default method that signals an error, but with a message that
190
  explains as clearly as you can why a non-default method is needed.
18976 jmc 191
 
45824 jmc 192
}
71366 jmc 193
\section{Specialized Local Generics}{
58136 jmc 194
  The great majority of calls to \code{setGeneric()} should either
195
  have one argument to ensure that an existing function can have
196
  methods, or arguments \code{name} and \code{def} to create a new
71366 jmc 197
  generic function and optionally a default method.
58136 jmc 198
 
71366 jmc 199
  It is possible to create generic functions with nonstandard
200
  signatures, or functions that do additional computations besides
201
  method dispatch or that belong to a group of generic functions.
202
 
203
  None of these mechanisms should be used with a non-generic function
204
  from a \emph{different} package, because the result is to create a
205
  generic function that may not be consistent from one package to another.
206
  When any such options are used,
207
  the new generic function will be assigned with a
50786 maechler 208
  package slot set to the \emph{current} package, not the one in which
71366 jmc 209
  the non-generic version of the function is found.
18976 jmc 210
 
71366 jmc 211
  There is a mechanism to define a specialized generic version of a
212
  non-generic function, the \code{\link{implicitGeneric}}
213
  construction.
214
  This defines the generic version, but then reverts the function to
215
  it non-generic form, saving the implicit generic in a table to be
216
  activated when methods are defined.
217
  However, the mechanism can only legitimately be used either for a non-generic
218
  in the same package or by the \code{"methods"} package itself.
219
  And in the first case, there is no compelling reason not to simply
220
  make the function generic, with the non-generic as the default
221
  method.
222
  See \code{\link{implicitGeneric}} for details.
223
 
50786 maechler 224
  The body of a generic function usually does nothing except for
225
  dispatching methods by a call to \code{standardGeneric}.  Under some
226
  circumstances you might just want to do some additional computation in
227
  the generic function itself.  As long as your function eventually
71366 jmc 228
  calls \code{standardGeneric} that is permissible.
229
  See the example \code{"authorNames"} below.
20676 jmc 230
 
71366 jmc 231
  In this case, the \code{def} argument will define the nonstandard
232
  generic, not the default method.
233
  An existing non-generic of the same name and calling sequence should
234
  be pre-assigned.  It will become the default method, as usual.
235
  (An alternative is the \code{useAsDefault} argument.)
236
 
42656 ripley 237
  By default, the generic function can return any object.  If
238
  \code{valueClass} is supplied, it should be a vector of class names;
239
  the value returned by a method is then required to satisfy
240
  \code{is(object, Class)} for one of the specified classes.  An empty
241
  (i.e., zero length) vector of classes means anything is allowed.  Note
242
  that more complicated requirements on the result can be specified
243
  explicitly, by defining a non-standard generic function.
18976 jmc 244
 
71366 jmc 245
  If the \code{def} argument calls \code{standardGeneric()} (with or
246
  without additional computations) and there is no existing
247
  non-generic version of the function, the generic is created without
248
  a default method.  This is not usually a good idea:  better to have a
249
    default method that signals an error with a message explaining why
250
    the default case is not defined.
45824 jmc 251
 
71366 jmc 252
  A new generic function can be created belonging to an existing group
253
  by including the \code{group} argument.  The argument list of the
254
  new generic must agree with that of the group. See
255
  \code{\link{setGroupGeneric}} for defining a new group generic.
256
   For the role of group generics in
257
  dispatching methods, see \link{GroupGenericFunctions} and section
258
  10.5 of the second reference.
45824 jmc 259
 
260
 
71366 jmc 261
}
45824 jmc 262
 
19473 jmc 263
\section{Generic Functions and Primitive Functions}{
41161 maechler 264
  A number of the basic \R functions are specially implemented as
50786 maechler 265
  primitive functions, to be evaluated directly in the underlying C code
266
  rather than by evaluating an \R language definition.  Most have
42299 ripley 267
  implicit generics (see \code{\link{implicitGeneric}}), and become
268
  generic as soon as methods (including group methods) are defined on
269
  them.  Others cannot be made generic.
19473 jmc 270
 
71366 jmc 271
 
272
  Calling \code{setGeneric()} for
273
  the primitive functions in the base package differs in that it does not, in fact,
274
  generate an explicit generic function.
275
  Methods for primitives are selected and dispatched from
276
  the internal C code, to satisfy concerns for efficiency.
277
  The same is true for a few
278
  non-primitive functions that dispatch internally. These include
279
  \code{unlist} and \code{as.vector}.
280
 
281
  Note, that the implementation restrict methods for
50786 maechler 282
  primitive functions to signatures in which at least one of the classes
283
  in the signature is a formal S4 class.
71366 jmc 284
  Otherwise the internal C code will not look for methods.
285
  This is a desirable restriction in principle, since optional
286
  packages should not be allowed to change the behavior of basic R
287
  computations on existing data types.
45824 jmc 288
 
289
  To see the generic version of a primitive function, use
290
  \code{\link{getGeneric}(name)}.  The function
291
  \code{\link{isGeneric}} will tell you whether methods are defined
292
  for the function in the current session.
293
 
48062 jmc 294
  Note that S4 methods can only be set on those primitives which are
295
  \sQuote{\link{internal generic}}, plus \code{\%*\%}.
19473 jmc 296
}
71366 jmc 297
 
15357 jmc 298
\value{
19029 hornik 299
  The \code{setGeneric} function exists for its side effect: saving the
300
  generic function to allow methods to be specified later.  It returns
301
  \code{name}.
15357 jmc 302
}
303
\references{
71366 jmc 304
 Chambers, John M. (2016)
305
 \emph{Extending R},
306
  Chapman & Hall.
307
(Chapters 9 and 10.)
308
 
45824 jmc 309
 Chambers, John M. (2008)
310
 \emph{Software for Data Analysis: Programming with R}
71366 jmc 311
  Springer. (Section 10.5 for some details.)
15357 jmc 312
 
313
}
20676 jmc 314
\examples{
315
 
71366 jmc 316
## Specify that this package will define methods for plot()
317
setGeneric("plot")
318
 
45824 jmc 319
## create a new generic function, with a default method
58136 jmc 320
setGeneric("props", function(object) attributes(object))
45824 jmc 321
 
20676 jmc 322
###   A non-standard generic function.  It insists that the methods
323
###   return a non-empty character vector (a stronger requirement than
324
###    valueClass = "character" in the call to setGeneric)
325
 
26530 maechler 326
setGeneric("authorNames",
20676 jmc 327
    function(text) {
328
      value <- standardGeneric("authorNames")
329
      if(!(is(value, "character") && any(nchar(value)>0)))
330
        stop("authorNames methods must return non-empty strings")
331
      value
332
      })
333
 
71366 jmc 334
## the asRObject generic function, from package XR
335
## Its default method just returns object
336
## See the reference, Chapter 12 for methods
337
 
338
setGeneric("asRObject", function(object, evaluator) {
339
        object
340
})
341
 
342
 
26000 ripley 343
\dontshow{
20676 jmc 344
setMethod("authorNames", "character", function(text)text)
345
 
49727 maechler 346
tryIt <- function(expr) tryCatch(expr, error = function(e) e)
39651 maechler 347
stopifnot(identical(authorNames(c("me", "you")), c("me", "you")),
49727 maechler 348
          is(tryIt(authorNames(character())), "error"), # empty value
349
          is(tryIt(authorNames(NULL)), "error"))        # no default method
20676 jmc 350
}
26000 ripley 351
\dontshow{
20676 jmc 352
removeGeneric("authorNames")
45824 jmc 353
removeGeneric("props")
71366 jmc 354
removeGeneric("asRObject")
19474 jmc 355
}
356
}
15571 ripley 357
\seealso{
71366 jmc 358
  \code{\link{Methods_Details}} and the links there for a general discussion,
46314 jmc 359
  \code{\link{dotsMethods}} for methods that dispatch on
69538 ripley 360
  \code{\dots}, and \code{\link{setMethod}} for method definitions.
15571 ripley 361
}
362
\keyword{ programming }
363
\keyword{ methods }
71366 jmc 364
 
365
 
366
  % The description above is the effect when the package that owns the
367
  % non-generic function has not created an implicit generic version.
368
  % Otherwise, it is this implicit generic function that is used. See the
369
  % section on Implicit Generic Functions below.  Either way, the
370
  % essential result is that the \emph{same} version of the generic
371
  % function will be created each time.
372
 
373
  % The \code{useAsDefault} argument controls the default method for the
374
  % new generic.  If not told otherwise, \code{setGeneric} will try to
375
  % find a non-generic version of the function to use as a default.  So,
376
  % if you do have a suitable default method, it is often simpler to first
377
  % set this up as a non-generic function, and then use the one-argument
378
  % call to \code{setGeneric} at the beginning of this section.  See the
379
  % first example in the Examples section below.
380
 
381
  % If you \emph{don't} want the existing function to be taken as default,
382
  % supply the argument \code{useAsDefault}.  That argument can be the
383
  % function you want to be the default method, or \code{FALSE} to force
384
  % no default (i.e., to cause an error if there is no direct or inherited
385
  % method selected for a call to the function).