Pass some functions in Python

I have an unknown number of functions in my python script (well, it’s known, but not always) that start from the site _... I was wondering if there is a way to go through all these functions in some kind of main function that them requires. sort of:

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

so that he goes through everything until something true comes out.

thank!

+3
source share
6 answers

inspect, , , , . inspect.getmembers : , , (, bool), (return True for) , .

", ", :

import sys
this_module = sys.modules[__name__]

, , , site_:

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

:

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

, ( , , )... Python; -)

+5

?

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

:

inspect.getmembers

:

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

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

, , site_.

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

, :

_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()
+1

dir(), globals() locals(). inspect ( ).

def site_foo():
  pass

def site_bar():
  pass

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

Source: https://habr.com/ru/post/1745618/


All Articles