In Julia, what's the best way to determine whether an object is callable? (E.g. is there an analog of python's callable
function?)
EDIT: Here's what one could wish for:
f() = println("Hi")
x = [1,2,3]
a = 'A'
callable(f) # => true
callable(x) # => false
callable(a) # => false
callable(sin) # => true
Use the builtin callable() : >>> callable(open) True >>> print(callable. __doc__) callable(object) -> bool Return whether the object is callable (i.e., some kind of function). Note that classes are callable, as are instances with a __call__() method.
A return type can be specified in the function declaration using the :: operator. This converts the return value to the specified type. This function will always return an Int8 regardless of the types of x and y .
Functions and classes are both callables, but you can actually invent your own callable objects too.
Python callable() FunctionThe callable() function returns True if the specified object is callable, otherwise it returns False.
iscallable(f) = !isempty(methods(f))
This is the method used in Base (see here).
But consider rethinking your problem. Custom dispatch like this will probably be slow.
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 to do (and I suspect not very efficient). What's the use case?
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