Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get fields of a Julia object

Given a Julia object of composite type, how can one determine its fields?

I know one solution if you're working in the REPL: First you figure out the type of the object via a call to typeof, then enter help mode (?), and then look up the type. Is there a more programmatic way to achieve the same thing?

like image 234
Yly Avatar asked Jan 17 '17 00:01

Yly


2 Answers

For v0.7+

Use fieldnames(x), where x is a DataType. For example, use fieldnames(Date), instead of fieldnames(today()), or else use fieldnames(typeof(today())).

This returns Vector{Symbol} listing the field names in order.

If a field name is myfield, then to retrieve the values in that field use either getfield(x, :myfield), or the shortcut syntax x.myfield.

Another useful and related function to play around with is dump(x).

Before v0.7

Use fieldnames(x), where x is either an instance of the composite type you are interested in, or else a DataType. That is, fieldnames(today()) and fieldnames(Date) are equally valid and have the same output.

like image 176
Colin T Bowers Avatar answered Oct 22 '22 12:10

Colin T Bowers


suppose the object is obj,

you can get all the information of its fields with following code snippet:

T = typeof(obj)
for (name, typ) in zip(fieldnames(T), T.types)
    println("type of the fieldname $name is $typ")
end

Here, fieldnames(T) returns the vector of field names and T.types returns the corresponding vector of type of the fields.

like image 25
novatena Avatar answered Oct 22 '22 12:10

novatena