Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty printer of objects in Julia

Tags:

julia

I want to write a function in Julia that can take any composite type and pretty-print the names of the nested members, their types and their values, and I want to put this function in a package for the community to use.

Imagine a user has the following structs:

struct House
    value::Int32
    rooms::Int32
    number::Int32
end

struct Street
    name::String
    houses::AbstractArray{House}
end

struct Town
    name::String
    streets::AbstractArray{Street}
end

town = Town(<initialization code here>)

This user can call PrettyPrinter.print(town), which should output something like

town::Town
    name::String = "London"
    streets[1]::Street
        name::String = "Downing Street"
        houses[1]::House
            value::Int32 = 100000
            rooms::Int32 = 5
            number::Int32 = 10
        houses[2]::House
            value::Int32 = 300000
            rooms::Int32 = 6
            number::Int32 = 40210

But of course, the PrettyPrinter package can not parse the struct implementation, it has to do its job by low level Julia trickery. My problem is not with the recursive programming.

Question: How do I access the member names, their types and their values?

like image 696
TradingDerivatives.eu Avatar asked Sep 20 '25 13:09

TradingDerivatives.eu


1 Answers

This functionality is already built-in into dump function:

julia> t = Town("London", [Street("Downing Street",[House(100000,5,10),House(300000,6,40210)])])
Town("London", Street[Street("Downing Street", House[House(100000, 5, 10), House(300000, 6, 40210)])]);

julia> dump(t)
Town
  name: String "London"
  streets: Array{Street}((1,))
    1: Street
      name: String "Downing Street"
      houses: Array{House}((2,))
        1: House
          value: Int32 100000
          rooms: Int32 5
          number: Int32 10
        2: House
          value: Int32 300000
          rooms: Int32 6
          number: Int32 40210

However, if you want query the data, you can use the fieldnames function:

julia> fieldnames(typeof(t))
(:name, :streets)

julia> getfield(t, :name)
"London"
like image 148
Przemyslaw Szufel Avatar answered Sep 23 '25 13:09

Przemyslaw Szufel