5

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

Darren Christopher
  • 3,893
  • 4
  • 20
  • 37

2 Answers2

8

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

longemen3000
  • 1,273
  • 5
  • 14
  • 1
    Thanks! I saw `fieldnames`, but didn't realize it took `::DataTypes` as the argument instead of an object. – Darren Christopher Oct 18 '19 at 03:50
  • 4
    In Julia version >= 1.2 there are two functions, `hasproperty` and `hasfield`. The implementation you have written here seems to be more appropriately named `hasfield`. Properties can be fields, but they can also be 'virtual fields' that are not actually stored. On version 1.0 you could implement `hasproperty` in terms of `propertynames`, instead of `fieldnames`. – DNF Oct 18 '19 at 07:48
5

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

Jun Tian
  • 1,340
  • 7
  • 12