Delete Function

python

Solution

Deleting a function isn't really something you do to the function itself; it's something you do to the namespace it lives in. (Just as removing the number 3 from a list isn't something you do to the number 3, it's something you do to the list.)

Suppose you say

def foo(x): return 1
bar = foo

Then (more or less) you have two names, `foo` and `bar`, for the exact same function. Now suppose you call `delete_function(foo)` or `delete_function(bar)`. The exact same thing, namely a function object, is being passed to `delete_function`. But what you actually want to remove is the association between the name `foo` or `bar` and that object -- and there's no possible way `delete_function` (however you define it) can know whether it's `foo` or `bar` or something else you're wanting to get rid of.

(Well ... Actually, there is. There are nasty hacky things you can do that would let the code in `delete_function` know more about how it was called. But don't even think about thinking about them.)

So. Your options are as follows. (1) Nasty hacky things, as just mentioned. Don't. (2) Pass `delete_function` not the function object but information about the name of the function and the thing you're trying to delete it from. This is ugly and ungainly. (3) Don't bother.

I strongly recommend #3, unless the only reason you're doing this is to learn more about how Python works. In the latter case, a good place to begin might be http://docs.python.org/reference/executionmodel.html.

Problem

I'm trying to create a function to delete another function. ``` def delete_function(func): del func ``` is what I have so far, but for some reason it doesn't work. ``` def foo(): print("foo") delete_function(foo) ``` doesn't seem to do the trick. I know one can do it easily, just ``` del(foo) ``` but I'm trying to do it a different way. How?

Original source