Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if function exists without running it in Julia?

Tags:

julia

Just want to find an analogue of this answer: Python check if function exists without running it

like image 647
Vladimir Mikheev Avatar asked Sep 05 '25 03:09

Vladimir Mikheev


2 Answers

You can check with isdefined.

isdefined(ModuleName, :function_name)

Example:

using Statistics

julia> isdefined(Statistics, :std)
true

julia> isdefined(Base, :std)
false
like image 83
AboAmmar Avatar answered Sep 07 '25 23:09

AboAmmar


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
like image 44
Sundar R Avatar answered Sep 07 '25 23:09

Sundar R