logankilpatrick
logankilpatrick

Reputation: 14551

Get all object attributes in Julia?

I am trying to see the methods, attributes, etc. that a specific object has in Julia. I know some options that may get me part of this are things like fieldnames() or hasproperty() but is there an option which will give me all of the attributes (similar to the dir function in python)?

Upvotes: 5

Views: 3617

Answers (2)

Fernando Conde-Pumpido
Fernando Conde-Pumpido

Reputation: 118

Retrieving all attributes from a Type

Suppose you have a Type T.

To see all methods that accept an object of type T as an argument, you can do:

methodswith(T)

To see all fields (i.e.: type's "properties"):

fieldnames(T)

If you want to combine all info into a function, you can do one yourself, like this:

function allinfo(type)
   display(fieldnames(type))
   methodswith(type)
end

Retrieving all attributes from an object

If instead of having a Type, you have an object a, the procedure is the same, but substituting T and type above by typeof(a):

# See all methods
methodswith(typeof(a))

# See all fields
methodswith(typeof(a))

# Function combining both
function allinfo(a)
   type = typeof(a)
   display(fieldnames(type))
   methodswith(type)
end

Retrieving all attributes regardless of its nature

Using multiple dispatch, you can define a function with three methods that gets you all info regardless of what you pass as argument.

The third case is needed in case you want to inspect methods that accept Type objects as arguments.

# Gets all info when argument is a Type
function allinfo(type::Type)
   display(fieldnames(type))
   methodswith(type)
end

# Gets all info when the argument is an object
function allinfo(a)
   type = typeof(a)
   display(fieldnames(type))
   methodswith(type)
end

# Gets all info when the argument is a parametric type of Type
function allinfo(a::Type{T}) where T <: Type
   methodswith(a)
end

Upvotes: 6

MarcMush
MarcMush

Reputation: 1488

not exactly what you're asking for, but dump is pretty handy

julia> struct A
           a
           b
       end

julia> dump(A((1,2),"abc"))
A
  a: Tuple{Int64, Int64}
    1: Int64 1
    2: Int64 2
  b: String "abc"

Upvotes: 5

Related Questions