importastfromtypingimportCallabledef_get_normalized_sources_from_ast(code_ast:ast.AST,/):""" :param code_ast: abstract syntax tree to convert to source code :return: noramlized source code string """statements=[]fornodeincode_ast.body:statements.append(ast.unparse(node))return("\n".join(statements)).strip()
[docs]classScript(Callable):""" A script object represents a small python script that can be executed in a controlled environment. For example, it will hold your scripts defined in rules. """
[docs]def__init__(self,source:ast.AST|str=None,/,*,filename=None):self._filename=filenameorf"<{type(self).__name__.lower()}:{id(self)}>"self._source=NoneifsourceisNone:raiseValueError("Code or AST must be provided.")ifisinstance(source,str):source=ast.parse(source)self._code=compile(source,filename=self._filename,mode="exec")self._source=_get_normalized_sources_from_ast(source)
[docs]@classmethoddeffrom_file(cls,filename:str):"""Constructor from a file content, by filename."""withopen(filename)asf:returncls(f.read(),filename=filename)