2

I'm working on a verification framework, in which I'd like to do something along the lines of (pseudo below - just an example):

class VerificationBase
{
    criticisms = set()
    AddCriticism( *FuncRef* ): criticisms.add(FuncRef)
    Execute(): for f in criticisms: [call f]
}

def CriticizeDatabaseConnections(): { //do stuff }
def CriticizeDatabaseSchemas(): { //do stuff }
def CriticizeNetworkSettings(): { //do stuff}

...

VerificationBase.AddCriticism(CriticizeDatabaseConnections())
VerificationBase.AddCriticism(CriticizeDatabaseSchemas())
VerificationBase.AddCriticism(CriticizeNetworkSettings())

VerificationBase.Execute()

What is this style called? I'm sure there are detailed docs around this, but I'm not even sure what to google other than 'call function by reference' -- even that doesn't produce the most helpful results.

How can I correctly accomplish the above example?

MrDuk
  • 16,578
  • 18
  • 74
  • 133
  • http://stackoverflow.com/questions/1349332/python-passing-a-function-into-another-function – NightShadeQueen Jul 15 '15 at 17:08
  • 1
    `VerificationBase.AddCriticism(())` will execute the function add pass in the functions return into that function. `VerificationBase.AddCriticism()` will simply pass in the function itself. – James Mertz Jul 15 '15 at 17:10
  • 1
    what is your overall goal here? It looks like your trying to setup a testing script/module? Am I reading into this correctly? – James Mertz Jul 15 '15 at 17:12
  • @KronoS - yes, exactly. Is there something well established already available? – MrDuk Jul 15 '15 at 17:13
  • Python already has built-in [unit testing functionality](https://docs.python.org/2/library/test.html). I would look there first. You might also [find this](http://docs.python-guide.org/en/latest/writing/tests/) interesting. – James Mertz Jul 15 '15 at 19:23
  • Thanks, but this isn't so much unit testing. It's moreso a module to handle server verification prior to deploying packages. So it's external verification, not internal. – MrDuk Jul 15 '15 at 20:22

1 Answers1

2

Function is just like any other name in python, you can store the function reference in a list (or set, or another variable, etc) and then iterate over them using a for loop, and call them using the name you use in for loop.

A Simple Example -

>>> def a():
...     print('a')
...
>>> def b():
...     print('b')
...
>>> l = [a,b]
>>>
>>> for i in l:
...     i()
...
a
b

Or a set (as in your pseudo-code) -

>>> s = set()
>>> s.add(a)
>>> s.add(b)
>>> for i in s:
...     i()
...
a
b

Also, in your pseudo-code , when you are adding the functions, you need to pass in (add) the function reference, not the result of calling the function. Example for a function a -

>>> def a():
...     print('a')
...

a() calls the function, whereas the name a refers to the function. Example -

>>> a()
a
>>> a
<function a at 0x022262B8>
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176