PyWriter

Overview

PyWriter is a utility class that aids in writing Python code along with abstract syntax tree (AST) nodes. It is designed to write or modify Python code using directives from code objects. It provides capabilities to create and update Python modules, among other functions. To use PyWriter, supply an instance of PyReader to PyWriter when it is instantiated.

‘PyWriter.ModuleNotFound’ is an exception raised when a module is not found in the module dictionary.

Example

This documentation provides an excerpt from a test of PyWriter functionality. The purpose is to show how to instantiate and use the PyWriter:

# MockCodeGenerator is a hypothetical class and its instance generates the source code for testing PyWriter
from automata.tests.unit.test_py_writer import PyWriter, MockCodeGenerator
from automata.code_handling.py.reader import PyReader
import os

py_writer = PyWriter(PyReader())
mock_generator = MockCodeGenerator(
    has_class=True, has_class_docstring=True, has_function=True, has_function_docstring=True
)
source_code = mock_generator.generate_code()
py_writer.create_new_module("sample_modules.sample_module_write", source_code, do_write=True)

assert os.path.exists("sample_module_write.py")

mock_generator_2 = MockCodeGenerator(
    has_class=True, has_class_docstring=True, has_function=True, has_function_docstring=True
)
source_code_2 = mock_generator_2.generate_code()

py_writer.update_existing_module(
    source_code=source_code_2,
    module_dotpath="sample_modules.sample_module_write",
    do_write=True,
)

To comprehend this example fully, note that an object called MockCodeGenerator() is utilized. This is likely a mock unit used in testing to replace a more complex code generator class. If you’re attempting this in a non-testing scenario, replace this with the appropriate mechanism to generate or retrieve your source code.

Limitations

Source code must in be in the correct format as expected by the PyWriter when creating or updating a Python code file. Any errors in the source code will likely result in faulty Python files. Another limitation is that this tool assumes Python AST node objects—it may not be compatible with customized AST node objects or AST node objects generated by code parsers other than Python’s built-in.

Follow-up Questions:

  • How can PyWriter handle additional exception cases for not found entities other than modules?

  • Are there any constraints when using PyWriter in terms of Python versions compatibility or code structure?

  • What happens if PyWriter tries to edit an existing Python file which is in read-only mode?