Skip to content

Commit 9bec6d2

Browse files
ajkeller34KristofferC
authored andcommitted
Add section on type piracy to style guide (#20967)
* Add section on type piracy. * Add examples of type piracy.
1 parent 75c2e72 commit 9bec6d2

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

doc/src/manual/style-guide.md

+31
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,37 @@ This would provide custom showing of vectors with a specific new element type. W
273273
this should be avoided. The trouble is that users will expect a well-known type like `Vector()`
274274
to behave in a certain way, and overly customizing its behavior can make it harder to work with.
275275

276+
## Avoid type piracy
277+
278+
"Type piracy" refers to the practice of extending or redefining methods in Base
279+
or other packages on types that you have not defined. In some cases, you can get away with
280+
type piracy with little ill effect. In extreme cases, however, you can even crash Julia
281+
(e.g. if your method extension or redefinition causes invalid input to be passed to a
282+
`ccall`). Type piracy can complicate reasoning about code, and may introduce
283+
incompatibilities that are hard to predict and diagnose.
284+
285+
As an example, suppose you wanted to define multiplication on symbols in a module:
286+
287+
```julia
288+
module A
289+
import Base.*
290+
*(x::Symbol, y::Symbol) = Symbol(x,y)
291+
end
292+
```
293+
294+
The problem is that now any other module that uses `Base.*` will also see this definition.
295+
Since `Symbol` is defined in Base and is used by other modules, this can change the
296+
behavior of unrelated code unexpectedly. There are several alternatives here, including
297+
using a different function name, or wrapping the `Symbol`s in another type that you define.
298+
299+
Sometimes, coupled packages may engage in type piracy to separate features from definitions,
300+
especially when the packages were designed by collaborating authors, and when the
301+
definitions are reusable. For example, one package might provide some types useful for
302+
working with colors; another package could define methods for those types that enable
303+
conversions between color spaces. Another example might be a package that acts as a thin
304+
wrapper for some C code, which another package might then pirate to implement a
305+
higher-level, Julia-friendly API.
306+
276307
## Be careful with type equality
277308

278309
You generally want to use [`isa()`](@ref) and `<:` ([`issubtype()`](@ref)) for testing types,

0 commit comments

Comments
 (0)