Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if Julia object is callable

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
like image 281
Yly Avatar asked Jan 15 '17 07:01

Yly


People also ask

How do you know if an object is callable?

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.

What is :: In Julia?

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 .

Is function callable object?

Functions and classes are both callables, but you can actually invent your own callable objects too.

Is callable in Python?

Python callable() FunctionThe callable() function returns True if the specified object is callable, otherwise it returns False.


2 Answers

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.

like image 119
Isaiah Norton Avatar answered Sep 27 '22 01:09

Isaiah Norton


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?

like image 24
David P. Sanders Avatar answered Sep 25 '22 01:09

David P. Sanders