Darren Christopher
Darren Christopher

Reputation: 4811

Julia - Check object has attribute

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

Upvotes: 5

Views: 2110

Answers (2)

longemen3000
longemen3000

Reputation: 1313

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

Upvotes: 8

Jun Tian
Jun Tian

Reputation: 1390

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

Upvotes: 7

Related Questions