0

Scenario:

I am working with python to execute some functions in cycle... over and over again.

How I do it:

I create a list with all the functions I want to execute, and then I do so.

# Define the functions before using 'em
def this_f:
    pass

def the_other:
    pass

....

# List of f() I want to run
funciones_escrapeadoras = [
    this_f,
    the_other,
    ...
    ]

# Call them all, cyclically
while True:
    for funcion_escrapeadora in funciones_escrapeadoras:
        funcion_escrapeadora()

Question:

If I prefixed all the functions I want to be part of the list, is there a way to automatically identify them and put them into that list?

Example:

I define the functions:

autorun_lalaa, hello_world, autorun_lololo, ...

And only autorun_lalaa and autorun_lololo and autorun_* will be part of the list.

Purpose:

To add in the functions I want to run, without needing to update the list.

Álvaro N. Franz
  • 1,188
  • 3
  • 17
  • 39

2 Answers2

2

Use the builtin locals() or globals():

for name, obj in locals().iteritems():
    if name.startswith('autorun_'):
        obj()

You could also make a Decorator which is described here: https://wiki.python.org/moin/PythonDecorators - then the functions don't need a name prefix, you could instead have the decorator add the function to a list.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1

To list the names of all the functions and variables of a module you can use:

funcs_n_vars = dir(modulename)

Then you can iterate over it to filter the list:

filtered_funcs = [func for func in funcs_n_vars if ('filter' in func)]

Finally, to call the methods from the list, you can do:

for func in filtered_funcs
    method_to_call = getattr(modulename, func)
    result = method_to_call()
otorrillas
  • 4,357
  • 1
  • 21
  • 34
  • 1
    Thank you too, but I will go with John's answer. I don't need the functions from a module but from current file, and locals() is the approach I was looking for. – Álvaro N. Franz Jul 17 '17 at 11:57