Determine if a Python class is an Abstract Base Class or Concrete

后端 未结 3 1427
无人及你
无人及你 2020-12-16 09:58

My Python application contains many abstract classes and implementations. For example:

import abc
import datetime
         


        
3条回答
  •  Happy的楠姐
    2020-12-16 10:11

    You could do this with the _ast module. For example, if your example code were in foo.py you could invoked this function with "foo.py" and "FriendlyMessagePrinter" as arguments.

    def is_abstract(filepath, class_name):
        astnode = compile(open(filename).read(), filename, 'exec', _ast.PyCF_ONLY_AST)
        for node in astnode.body:
            if isinstance(node, _ast.ClassDef) and node.name == class_name:
                for funcdef in node.body:
                    if isinstance(funcdef, _ast.FunctionDef):
                        if any(not isinstance(n, _ast.Pass) for n in funcdef.body):
                            return False
                return True
        print 'class %s not found in file %s' %(class_name, filepath)
    

提交回复
热议问题