2

In Julia, is there any function like isdynamic() to show whether a given variable is of "dynamic" or "static" type? For example, I assume that a and b in the following code are dynamic and static variables, respectively, where I mean by "dynamic" that the variable can represent any data type. If I run @code_warntype, a and b are shown to be Any and Int64, respectively, but I am wondering whether it is possible to display the actual internal representation with some function. Is this not possible because the determination of the internal representation depends on the whole function (plus, the type of actual arguments when the variable depends on it) rather than the code up to the invocation of isdynamic( a )?

function test()
    a = 1
    b::Int = 1
    @show typeof( a )    # Int64
    @show typeof( b )    # Int64

    a = 3.0
    b = 3.0
    @show typeof( a )   # Float64
    @show typeof( b )   # Int64

    a = 3.2      # okay
    # b = 3.2    # InexactError
end

test()
# @code_warntype test()   # after eliminating @show... statements
roygvib
  • 7,218
  • 2
  • 19
  • 36

1 Answers1

3

OK, try to put the following code in test function body:

function test()
:
:
    vinfo = code_lowered(test,())[1].args[2][1]
    aind = findfirst(x->x[1]==:a,vinfo)
    bind = findfirst(x->x[1]==:b,vinfo)
    if aind > 0
        println("inference-type of a = $(vinfo[aind][2])")
    end
    if bind > 0
        println("inference-type of b = $(vinfo[bind][2])")
    end
end

and run test(). This should show the difference between the variables as the inference engine computes it and stores it internally. Patched this by looking around the code, so perhaps someone who is more of an internals expert has a better answer.

For an isdynamic function like the OP asked about, we can have:

function isdynamic(f,args,symbol)
    vi=code_lowered(f,args)[1].args[2][1]
    (ind=findfirst(x->x[1]==symbol,vi))>0 ? vi[ind][2]==:Any : false
end
isdynamic(test,(),:a) # true
isdynamic(test,(),:b) # false
Dan Getz
  • 17,002
  • 2
  • 23
  • 41
  • of course, the extra code can be run anywhere (from the REPL also), when the function is already compiled. – Dan Getz Oct 18 '15 at 21:50
  • 1
    Very interesting, thanks very much :) I have played around with code_lowered() for a while. Although the net information obtained may be the same as @code_warntype, I think it is interesting to be able to know internal types from within the function. I tried adding an argument like `test( s )`, defining a with s, and calling the above isdynamic() as `isdynamic( test, (typeof(s),), :a )` from inside test(), then it gives true. So one can "embed" the checking code inside a routine :) – roygvib Oct 18 '15 at 22:28