Chris Rackauckas
Chris Rackauckas

Reputation: 19142

How to check a type for mutability

Is there a way to check if a type is mutable or immutable? Can this check be done at compile-time (i.e. have branches if ismutable(T) compile away to just use the codepath for either mutability or immutability)?

Upvotes: 9

Views: 1169

Answers (2)

Clemens Cords
Clemens Cords

Reputation: 226

As of julia 1.7 there is a new standard library function ismutabletype. If your really want ismutable to work on types, you can add another method for it like so:

function ismutable(t::Type) ::Bool
    return ismutabletype(t)
end

Usage:

mutable struct MutableType end
struct ImmutableType end

mutable_instance = MutableType()
immutable_instance = ImmutableType()

ismutable(mutable_instance) # true
ismutable(typeof(mutable_instance)) # true
ismutable(immutable_instance) # false
ismutable(typeof(immutable_instance)) # false

I would just recommend using Base.ismutabletype to begin with, adding methods to standard library functions isn't recommended in most scenarios

Upvotes: 2

HarmonicaMuse
HarmonicaMuse

Reputation: 7893

DataTypes have a mutable field, so you can define is_mutable and is_immutable using that, since doing that instead of accessing that field directly is more Julian.

Using Julia version 0.5.0:

               _
   _       _ _(_)_     |  By greedy hackers for greedy hackers.
  (_)     | (_) (_)    |  Documentation: http://docs.julialang.org
   _ _   _| |_  __ _   |  Type "?help" for help.
  | | | | | | |/ _' |  |
  | | |_| | | | (_| |  |  Version 0.5.0 (2016-09-19 18:14 UTC)
 _/ |\__'_|_|_|\__'_|  |  Official http://julialang.org/ release
|__/                   |  x86_64-w64-mingw32

julia> DataType.    # <TAB> to auto complete
abstract         hastypevars       instance          layout            llvm::StructType  name              parameters        super             uid
depth            haswildcard       isleaftype        llvm::DIType      mutable           ninitialized      size              types

julia> is_mutable(x::DataType) = x.mutable
is_mutable (generic function with 1 method)

julia> is_mutable(x) = is_mutable(typeof(x))
is_mutable (generic function with 2 methods)

julia> is_immutable(x) = !is_mutable(x)
is_immutable (generic function with 1 method)

Create a type and an immutable and instances for both of them:

julia> type Foo end

julia> f = Foo()
Foo()

julia> immutable Bar end

julia> b = Bar()
Bar()

Check for mutability:

julia> is_mutable(Foo), is_mutable(f)
(true,true)

julia> is_mutable(Bar), is_mutable(b)
(false,false)

Check for immutability:

julia> is_immutable(Foo), is_immutable(f)
(false,false)

julia> is_immutable(Bar), is_immutable(b)
(true,true)

For performance, also consider declaring these functions as @pure:

Base.@pure is_mutable(x::DataType) = x.mutable

Upvotes: 10

Related Questions