I wrote a small package EnumX
that I want to introduce.
Julia has builtin support for enums with the @enum
macro, but such enums have some drawbacks, where the namespace/scope of the instances is the most annoying. This, and other problems with @enum
have been discussed a lot on this forum (for example here, here, and here). I decided to package some ideas from those threads into EnumX.jl
, to make enums nicer to work with.
EnumX
provides the @enumx
macro, which, on the surface, is similar to @enum
and have the same surface syntax, but with some nice improvements. Let’s look at an example: This defines an enum Fruit
with the two instances Apple
and Banana
:
julia> using EnumX
julia> @enumx Fruit Apple Banana
The instances are accessed using dot-syntax:
julia> Fruit.Apple
Fruit.Apple = 0
julia> Fruit.Banana
Fruit.Banana = 1
The secret sauce here is that Fruit
is a module, and the enum-type is instead defined as Fruit.T
(this name can be configured, see the README):
julia> Fruit.T
Enum type Fruit.T <: Enum{Int32} with 2 instances:
Fruit.Apple = 0
Fruit.Banana = 1
This solves the problem with scope – the only name that is occupied by this enum is the module name Fruit
, which means that it is possible to use “common names” for instances without polluting the namespace. It also means that it is possible to define another enum in the same namespace, with the same instance name(s), e.g.:
julia> @enumx AnotherFruit Apple Banana
@enumx
has some other niceties such as:
- Support for duplicate values, e.g.
@enumx Fruit Apple = 1 Banana = 1
) - Reusing previous instances for value initialization, e.g.
@enumx Fruit Apple = 3 Banana = Apple
) - Support for docstrings:
""" Documentation for Fruit enum. """ @enumx Fruit begin "Documentation for Fruit.Apple instance." Apple "Documentation for Fruit.Banana instance." Banana end
Other than that, @enumx
should be a drop-in replacement for @enum
, and should support the same syntax and the same features, see the README for more details.