try to assign a wrong-typed value and
catch the error)
Let’s say you want to check
myvar - you assume it is defined in
Main and has type
myvar::Int64 = 1 function checkglobal() :myvar in names(Main) && # or hasproperty(Main, :myvar) Base.return_types(() -> getproperty(Main, :myvar)) == Int64 end #true println(checkglobal())
Another option (this only checks for global typed quality - without doing an explicit type test):
using Test @inferred (() -> Main.:myvar)() # or @inferred (() -> getproperty(Main, :myvar))()
The above will fail if
myvar is not a global typed defined in
Not sure how you want to treat the
const scenario (you can have a typed global, which is also declared as
const). However, you can add the following on the mix - depending on your end-goal:
# false - in the above snippet context isconst(Main, :myvar)
@algunion thank you.
Do I understand it correctly that Base.return_types is not in the public API?
Also, I have tried to modify your function as to accept the variable name as argument - but it doesn’t work. Why?
myvar::Int64 = 1 function checkglobal(x) x in names(Main) && Base.return_types(v -> getproperty(Main, v)) == Int64 end # false - why? checkglobal(:myvar)
I can see the
return_types used in the manual here.
I don’t know why it doesn’t appear when searching the docs. The function is not used much in the Julia codebase but is well-represented (and useful) in the tests.
It seems to me that it is treated as being part of the public API, but somehow it doesn’t show (or is not properly exported in the docs). I’ll look into it.
As for your question related to why doesn’t work when you use the variable as an argument - I don’t have an answer right away, I’ll need to test/check that and come back with an answer later.
You don’t need the workaround via
return_types here, there’s an internal function
Core.get_binding_type(:: Module, ::Symbol) that should do what you want
@simeonschaub thank you, it works.
But shouldn’t be there some public API way to get this information, similar to