Julia - Check object has attribute

Viewed 1017

Suppose I have struct as below.

struct Foo
    attr1
    attr2
end

I can then instantiate and get the attr1 and attr2

julia> foo = Foo(1,2)

julia> foo.attr1
1

I'm just wondering if I can do any checking that my object foo has attr1?

For reference, python has hasattr which exactly what I'm looking for here, but I couldn't seem to find the equivalent in julia.

Any help would be appreciated.

EDIT: I'm in Julia 1.1.0

2 Answers

if you are in julia 1.1 or 1.0, you can define your own hasproperty:

hasproperty(x, s::Symbol) = s in fieldnames(typeof(x))

this is (almost) the same function that is in julia 1.2 base and above

For Julia v1.2 or above, it is documented here: hasproperty.

If you are using Julia 1.1.0, then I think you can use that function in Compat.jl

Related