Josh Wood
Josh Wood

Reputation: 1696

Python check if function exists without running it

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.

Upvotes: 53

Views: 60204

Answers (8)

Muhammad Dyas Yaskur
Muhammad Dyas Yaskur

Reputation: 8098

I believe this work also and look simpler for me:

def newFunc():
    print("hello")

if newFunc:
    print("newFunc function is exist")
else:
    print("newFunc function is not exist")

Upvotes: 0

Dmitriy Solar
Dmitriy Solar

Reputation: 31

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)

Upvotes: 0

Zvi
Zvi

Reputation: 2424

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

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

Upvotes: 3

kenisam
kenisam

Reputation: 1

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"))

Upvotes: 0

openwonk
openwonk

Reputation: 15567

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())

Upvotes: 5

rlms
rlms

Reputation: 11060

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).

Upvotes: 31

Paula Cogeanu
Paula Cogeanu

Reputation: 231

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

Upvotes: 17

user2555451
user2555451

Reputation:

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.

Upvotes: 54

Related Questions