4

I have a composite type, MyType,

 struct MyType

 a::Float64
 b::Float64     

 end

When I do

 a = MyType(1,2)
 fieldnames(a)

I get an error

 MethodError: no method matching fieldnames(::MyType)

When I do

 fieldnames(MyType)

it returns

 (:a,:b)

as expected. It was my understanding that the former should work as well - am I doing something wrong?

Econ
  • 1,075
  • 1
  • 8
  • 13
  • 7
    The behavior was changed in Julia 1.0 and now `fieldnames` works only on data types. – Bogumił Kamiński Nov 29 '18 at 20:09
  • [Partial duplicate](https://stackoverflow.com/questions/41687418/how-to-get-fields-of-a-julia-object/41687640#41687640) – Colin T Bowers Nov 29 '18 at 21:28
  • 1
    I see. I could only find documentation that claimed it would work. Easy workaround is just `fieldnames(typeof(a))` – Econ Nov 29 '18 at 22:29
  • just a curiosity, where did you read about it? In general, you should consult resources dealing with Julia >= 1.0, everything before is prehistory... – Antonello Oct 18 '22 at 13:43

1 Answers1

1

fieldnames was changed with Julia 1.0 to accept only types as its argument. The NEWS.md for 0.7 (which was the 1.0-gateway version) mentions that:

fieldnames now operates only on types. To get the names of fields in an object, use fieldnames(typeof(x))

The reasoning is essentially two-fold: (1) if it accepts both objects and types, there's an ambiguity since types are also objects themselves (so there's an artificial distinction in the old behaviour) (2) the fields are semantically an attribute of the type, not of its individual instances, so it makes more sense to have fieldnames operate on types only.

Sundar R
  • 13,776
  • 6
  • 49
  • 76