49

In python how do you check if a function exists without actually running the function (i.e. using try)? I would be testing if it exists in a module.

1
  • Depend on the context, if is a class, if is global defined, you-ll have to extend the question to provide more elements.
    – Paulo Bu
    Jan 4, 2014 at 21:23

7 Answers 7

50

You can use dir to check if a name is in a module:

>>> import os
>>> "walk" in dir(os)
True
>>>

In the sample code above, we test for the os.walk function.

3
  • 10
    And then to see if it's actually a function, callable(getattr(os,'walk'))
    – Mattias
    Jan 4, 2014 at 21:30
  • 5
    What if I want to know if it exists at a global namespace (or from existing imports)?
    – Jonathan
    Jun 10, 2016 at 19:13
  • 1
    Use callable(getattr(os,'walk', None)) if you don't want to throw an exception
    – VoteCoffee
    Dec 4, 2020 at 19:39
30

You suggested try except. You could indeed use that:

try:
    variable
except NameError:
    print("Not in scope!")
else:
    print("In scope!")

This checks if variable is in scope (it doesn't call the function).

3
  • 1
    They specifically said without running the function and gave try as an example of what they don't want to do.
    – fun4jimmy
    Feb 12, 2015 at 11:29
  • 7
    @fun4jimmy This doesn't call the function - that would require variable(). It just checks if variable is defined.
    – rlms
    Feb 12, 2015 at 15:42
  • Oh I didn't realise you could do that. I don't seem to be able to remove the downvote unless you edit your answer. Can you change something minor so I can remove it?
    – fun4jimmy
    Feb 13, 2015 at 10:31
17
Solution1:
import inspect
if (hasattr(m, 'f') and inspect.isfunction(m.f))

Solution2:
import inspect
if ('f' in dir(m) and inspect.isfunction(m.f))

where:
m = module name
f = function defined in m

4

If you are checking if function exists in a package:

import pkg

print("method" in dir(pkg))

If you are checking if function exists in your script / namespace:

def hello():
    print("hello")

print("hello" in dir())
3

if you are looking for a function in your code, use global()

if "function" in globals():
  ...
1

Just wanted to add my solution here. It's 8 years late, and similar variant been suggested, but here is more capable version. Just for those, who find this as i did.

def check(fn):
    def c():pass
    for item in globals().keys():
        if type(globals()[item]) == type(c) and fn == item:
            return print(item, "is Function!")
        elif fn == item:
            return print(fn, "is", type(globals()[item]))
    return print("Can't find", fn)
0

If you are looking for the function in class, you can use a "__dict__" option. E.g to check if the function "some_function" in "some_class" do:

if "some_function" in list(some_class.__dict__.keys()):
    print('Function {} found'.format ("some_function"))
1
  • 1
    You should just use hasattr(some_class, "some_function") for more clarity and because sometimes dict is not used, although this still does not check whether you’re dealing with a function or not. Mar 16, 2020 at 12:17

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.