Asserting something is a valid function in Python

Viewed 3144

Suppose I have the following code which takes in a distance function and two points, and spits out the distance:

def distance(dist_fun, p1, p2):
    ## SOME ASSERTION HERE on dist_fun ##

    ## Suppose, just for this post, we've already checked p1 and p2 are 
    ## n-tuples of integers.

    assert (len(p1) == len(p2)), "Coordinates are different dimensions."
    dist = dist_fun(p1, p2)
    assert (dist>=0), "Negative distance is not possible."
    return dist

def euclid(p1, p2):  #as an example dist function.
    return pow(reduce(lambda x,y: x+y, [pow((p1[i] - p2[i]), 2) for i in range(len(p1))]),0.5)

I'd like to be able to check that if a user uses a particular distance function that it is, first and foremost, actually a function. After this, I can check other things, but my main question is: how do I assert that dist_fun is actually a function?

If there is no easy way to do this, or if there's an alternative way to do this kind of thing, let me know. I've done a bit of testing before in Python, but never ran across this problem until now. I've seen that the "type" of a function is "function", but Python does not allow me to use this as a type? Would it be easier just to go back to try-except here?

4 Answers
Related