-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!

petezurich
  • 9,280
  • 9
  • 43
  • 57
Niuya
  • 428
  • 1
  • 5
  • 14
  • You could try `globals()[fun]()` to call the function, with no arguments. – Tom Karzes Jul 01 '19 at 04:50
  • but how about if I need arguments? fun(arg1,arg2) – Niuya Jul 01 '19 at 04:53
  • @TomKarzes It's better to avoid using `globals()` unless you have no other choice, and generally there are better choices. – PM 2Ring Jul 01 '19 at 04: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__` – PM 2Ring Jul 01 '19 at 04:57
  • @PM2Ring Yes, it's not how I would do it, but I was directly addressing what OP was asking. – Tom Karzes Jul 01 '19 at 05:24
  • Also see https://stackoverflow.com/questions/9205081/is-there-a-way-to-store-a-function-in-a-list-or-dictionary-so-that-when-the-inde and the linked questions there. – PM 2Ring Jul 01 '19 at 05:47

1 Answers1

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

abdusco
  • 9,700
  • 2
  • 27
  • 44