liveBook · Manning

Module

As explained in Julia as a Second Language

A module is a Julia namespace that groups related functions, types, constants, and other definitions.

A module groups related Julia functions, types, and constants in a namespace. That namespace lets two projects use the same function name without making those functions interchangeable. Define one with `module Name ... end`; definitions made at the REPL instead belong to `Main` unless placed in a named module. section 16.1.2 section 9.3.2

Listing 4.1 Calculating arithmetic mean
average(A) = sum(A) / length(A)

Defining `Cylinder.volume` and `Cone.volume` in separate modules gives each calculation its own name. Call the one you want with a qualified name, such as `Cylinder.volume(2.5, 3)`. section 16.1.2

Use a ready-made module

At the REPL, run `using Statistics`, then try `mean([1, 2, 3])` or `std([3, 3, 3])`. For an overview of available names, type `Statistics.` and press Tab twice. Type `?Statistics` to open its documentation. section 4.4

A module is not the same thing as a package. A package bundles source code, resources, and metadata; it defines a module that Julia loads when you use the package. For a growing package, keep the module definition in one file and call `include` there to evaluate definitions from other source files inside that module. section 16.1.2 section 16.2.2

using Statistics

The ToyGeometry module includes separate volume and trigonometry files. Their functions become part of the same module without crowding its definition file. section 16.2.2

Module boundaries also matter when extending an existing function. Before adding angle-specific methods to Julia’s `+`, write `import Base: +`. Without the import, defining `+` creates a separate function in `Main` that can shadow `Base.+`; even `3 + 4` may then fail. To make a module function available by name, Julia uses `export sphere_volume`, not a `public` keyword before its definition. section 9.3.2 section 16.4

How Julia as a Second Language covers it

How deep it goes
Defines modules and works through loading, namespace separation, multi-file organization, and function shadowing.
Examples
Uses Statistics functions, separate volume calculations, a multi-file geometry package, and an angle-arithmetic shadowing error.
What it assumes
Assumes familiarity with functions and REPL definitions while introducing the `module` keyword through small examples.
What you can do after
Build it from scratch with `module` and `include`, and import existing functions before extending them.
How it connects
Connects modules to packages, namespaces, imports, exports, and included source files.

Also explained in

Compare how 35 books explain module →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.