質問

I've built a module in Python in one single file without using classes. I do this so that using some api module becomes easier. Basically like this:

the_module.py

from some_api_module import some_api_call, another_api_call

def method_one(a, b):
    return some_api_call(a + b)

def method_two(c, d, e):
    return another_api_call(c * d * e)

I now need to built many similar modules, for different api modules, but I want all of them to have the same basic set of methods so that I can import any of these modules and call a function knowing that this function will behave the same in all the modules I built. To ensure they are all the same, I want to use some kind of abstract base module to build upon. I would normally grab the Abstract Base Classes module, but since I don't use classes at all, this doesn't work.

Does anybody know how I can implement an abstract base module on which I can build several other modules without using classes? All tips are welcome!

役に立ちましたか?

解決

You are not using classes, but you could easily rewrite your code to do so. A class is basically a namespace which contains functions and variables, as is a module. Should not make a huge difference whether you call mymodule.method_one() or mymodule.myclass.method_one().

In python there is no such thing as interfaces which you might know from java. The paradigm in python is Duck typing, that means more or less that for a given module you can tell whether it implements your API if it provides the right methods. Python does this i.e. to determine what to do if you call myobject[i] on an instance of your class myclass. It looks whether the class has the method __getitem__ and if it does so, it replaces myobject[i] by myobject.__getitem__(i). Yout don't have to tell python that your class supports this kind of access, python just figures it out from the way you defined your class. The same way you should determine whether your module implements your API.

Maybe you want to look inside the hidden dictionary mymodule.__dict__ after import mymodulewhich contains all function names and pointers to them of your module. You could then check whether the right functions are present and raise an error otherwise

import my_module_4
#check if my_module_4 implements api
if all(func in my_module_4.__dict__ for func in ("method_one","method_two"):
  print "API implemented"
else:
  print "Warning: Not all API functions found in my_module_4"
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top