开发者

Go through a number of functions in Python

开发者 https://www.devze.com 2022-12-30 05:03 出处:网络
I have an unknown number of functions in开发者_高级运维 my python script (well, it is known, but not constant) that start with site_...

I have an unknown number of functions in开发者_高级运维 my python script (well, it is known, but not constant) that start with site_... I was wondering if there's a way to go through all of these functions in some main function that calls for them. something like:

foreach function_that_has_site_ as coolfunc
   if coolfunc(blabla,yada) == true:
      return coolfunc(blabla,yada)

so it would go through them all until it gets something that's true.

thanks!


The inspect module, already mentioned in other answers, is especially handy because you get to easily filter the names and values of objects you care about. inspect.getmembers takes two arguments: the object whose members you're exploring, and a predicate (a function returning bool) which will accept (return True for) only the objects you care about.

To get "the object that is this module" you need the following well-known idiom:

import sys
this_module = sys.modules[__name__]

In your predicate, you want to select only objects which are functions and have names that start with site_:

import inspect
def function_that_has_site(f):
    return inspect.isfunction(f) and f.__name__.startswith('site_')

With these two items in hand, your loop becomes:

for n, coolfunc in inspect.getmembers(this_module, function_that_has_site):
   result = coolfunc(blabla, yada)
   if result: return result

I have also split the loop body so that each function is called only once (which both saves time and is a safer approach, avoiding possible side effects)... as well as rewording it in Python;-)


Have you tried using the inspect module?

http://docs.python.org/library/inspect.html

The following will return the methods:

inspect.getmembers

Then you could invoke with:

methodobjToInvoke = getattr(classObj, methodName) 
methodobj("arguments") 


This method goes through all properties of the current module and executes all functions it finds with a name starting with site_:

import sys
import types
for elm in dir():
    f = getattr(sys.modules[__name__], elm)
    if isinstance(f, types.FunctionType) and f.__name__[:5] == "site_":
        f()

The function-type check is unnecessary if only functions are have names starting with site_.


def run():
    for f_name, f in globals().iteritems():
        if not f_name.startswith('site_'):
            continue
        x = f()
        if x:
            return x


It's best to use a decorator to enumerate the functions you care about:

_funcs = []

def enumfunc(func):
  _funcs.append(func)
  return func

@enumfunc
def a():
  print 'foo'

@enumfunc
def b():
  print 'bar'

@enumfunc
def c():
  print 'baz'

if __name__ == '__main__':
  for f in _funcs:
    f()


Try dir(), globals() or locals(). Or inspect module (as mentioned above).

def site_foo():
  pass

def site_bar():
  pass

for name, f in globals().items():
  if name.startswith("site_"):
    print name, f()
0

精彩评论

暂无评论...
验证码 换一张
取 消