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?
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
Then (more or less) you have two names,
fooandbar, for the exact same function. Now suppose you calldelete_function(foo)ordelete_function(bar). The exact same thing, namely a function object, is being passed todelete_function. But what you actually want to remove is the association between the namefooorbarand that object — and there’s no possible waydelete_function(however you define it) can know whether it’sfooorbaror 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_functionknow 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_functionnot 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.