Just want to find an analogue of this answer: Python check if function exists without running it
You can check with isdefined
.
isdefined(ModuleName, :function_name)
Example:
using Statistics
julia> isdefined(Statistics, :std)
true
julia> isdefined(Base, :std)
false
To make sure it is a function, Julia allows you to check its type too:
julia> isdefined(Main, :sin)
true
julia> isdefined(Main, :Int)
true
julia> isdefined(Main, :sin) && getproperty(Main, :sin) isa Function
true
julia> isdefined(Main, :Int) && getproperty(Main, :Int) isa Function
false
julia> import Dates
julia> isdefined(Dates, :month) && getproperty(Dates, :month) isa Function
true
Relatedly, once you know something is a function, you can also check whether it applies to a particular set of argument types.
This is important in Julia, as a given function can have several methods implementing it for different sets of argument types. hasmethod
allows you to make sure that the function applies to your particular set of argument types.
julia> hasmethod(+, Tuple{Int, Float64})
true
julia> hasmethod(+, Tuple{Int, String})
false
julia> #can check keyword arguments too
hasmethod(range, Tuple{Int}, (:stop, :step))
true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With