-1

I have a script define many functions. Now I want to execute some of them in a batch.

eg:

def foo_fun1():
   xxx

def foo_fun2():
   xxx

...

def bar_funx():
   yyy

I now want to loop all function and pickup some of them if the function name contains "foo", how to archive that ?

for fun in dir():
    if 'foo' in fun:
         #
         # the fun is string
         # how to call the string as function here??

Thanks!

6
  • You could try globals()[fun]() to call the function, with no arguments. Commented Jul 1, 2019 at 4:50
  • but how about if I need arguments? fun(arg1,arg2) Commented Jul 1, 2019 at 4:53
  • @TomKarzes It's better to avoid using globals() unless you have no other choice, and generally there are better choices. Commented Jul 1, 2019 at 4:55
  • You could put your functions into a dict, with the function name as the key. Also, a function stores its name as an attribute. In your loop you can do name = fun.__name__ Commented Jul 1, 2019 at 4:57
  • @PM2Ring Yes, it's not how I would do it, but I was directly addressing what OP was asking. Commented Jul 1, 2019 at 5:24

1 Answer 1

0

You need to use globals() function, which returns a dict of every global object

def say_hey():
    print('hey')

def say_hi():
    print('hi')

def main():
    for name, func in globals().items():
        if 'say_' in name and callable(func):
            func()

if __name__ == '__main__':
    main()

which outputs

hey
hi

https://docs.python.org/3/library/functions.html#globals

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.