Is this a good approach for doing a list of operations on a data structure in Python?

I have a data dictionary, the key is the name of the file, and the value is another dictionary of its attribute values. Now I would like to pass this data structure to various functions, each of which performs some attribute test and returns True / False.

One approach would be to call each function one from the main code. However, I can do something like this:

#MYmodule.py
class Mymodule:
  def MYfunc1(self):
  ...
  def MYfunc2(self):
  ...

#main.py
import Mymodule
...
#fill the data structure
...
#Now call all the functions in Mymodule one by one
for funcs in dir(Mymodule):
   if funcs[:2]=='MY':
      result=Mymodule.__dict__.get(funcs)(dataStructure)

The advantage of this approach is that the implementation of the main class should not change when I add more logic / tests to MYmodule.

Is this a good way to solve the problem? Are there better alternatives to this solution?

+3
2

, Pythonic decorator, , :

class MyFunc(object):
    funcs = []
    def __init__(self, func):
        self.funcs.append(func)

@MyFunc
def foo():
    return 5

@MyFunc
def bar():
    return 10

def quux():
    # Not decorated, so will not be in MyFunc
    return 20

for func in MyFunc.funcs:
    print func()

:

5
10

, : , .

+6

Sridhar, , , , unittest.

, unittest.TestLoader ( /usr/lib/python 2.6/unittest.py):

def getTestCaseNames(self, testCaseClass):
    """Return a sorted sequence of method names found within testCaseClass
    """
    def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
        return attrname.startswith(prefix) and hasattr(getattr(testCaseClass, attrname), '__call__')
    testFnNames = filter(isTestMethod, dir(testCaseClass))
    if self.sortTestMethodsUsing:
        testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
    return testFnNames

, unittest dir testCaseClass , prefix ( 'test').

:

MYmodule.py, ()

import MYmodule

getattr .__dict__.get. , , Mymodule. , , getattr, , .

for funcs in dir(MYmodule.Mymodule):
   if funcs.startswith('MY'):
      result=getattr(MYmodule.Mymodule,funcs)(dataStructure)
+1

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


All Articles