How to determine if a Julia object is callable

In Julia, what is the best way to determine if an object is callable? (For example, is there an analogue of the python function callable ?)

EDIT: Here, one would wish:

 f() = println("Hi") x = [1,2,3] a = 'A' callable(f) # => true callable(x) # => false callable(a) # => false callable(sin) # => true 
+5
source share
2 answers

iscallable(f) = !isempty(methods(f))

This is the method used in Base (see here ).

But think about rethinking your problem. Customs shipping is likely to be slow.

+2
source

How about this:

 julia> function iscallable(f) try f() return true catch MethodError return false end end iscallable (generic function with 1 method) julia> f() = 3 f (generic function with 1 method) julia> iscallable(f) true julia> x = [1,2] 2-element Array{Int64,1}: 1 2 julia> iscallable(x) false 

This is actually quite a pythonic thing (and I suspect that it is not very effective). What is the precedent?

+1
source

Source: https://habr.com/ru/post/1262829/


All Articles