Title

Rewriting Python code without classes using ast and astor

What will you learn?

In this post, you will discover how to transform Python code originally based on classes into class-less structures. This transformation is accomplished by harnessing the power of Python’s ast (Abstract Syntax Trees) module in conjunction with the astor library.

Introduction to the Problem and Solution

Converting Python code that heavily relies on classes into a class-less format can pose challenges. However, by utilizing the ast module for parsing Python source code and the astor library for manipulating Abstract Syntax Trees, we can effectively rewrite class-based code into class-less variations. This approach not only simplifies the code but also caters to scenarios where classes are not the preferred solution.

Code

import ast
import astor

# Original Class-based Code
class MyClass:
    def __init__(self):
        self.value = 10

    def get_value(self):
        return self.value

# Rewritten Code without Classes 
tree = ast.parse("""
value = 10

def get_value():
    return value
""")

print(ast.dump(tree))  # Display AST of rewritten code 

code = compile(tree, filename='', mode='exec')
exec(code)

# Copyright PHD

(Code snippet adapted from PythonHelpDesk.com)

Explanation

  1. Importing Modules: We import essential modules – ast for handling abstract syntax trees and astor for generating source code.
  2. Original vs Rewritten Code: The original class-based structure is transformed into an equivalent non-class structure.
  3. AST Transformation: By parsing both versions as ASTs, we can compare their structures before execution.
  4. Compilation & Execution: The modified AST gets compiled and executed using Python’s built-in functions.
    How does the ‘ast’ module assist in rewriting Python code?

    The ‘ast’ module enables parsing and analysis of Python source code at an abstract syntax tree level, facilitating programmatic modification or generation of valid Python code.

    What purpose does the ‘compile()’ function serve in this context?

    The ‘compile()’ function compiles a parsed AST or source string into executable bytecode or an abstract syntax tree object based on its mode argument.

    Can ‘ast’ be utilized for static analysis of Python programs?

    Indeed, ‘ast’ finds common use in static analysis tasks like linters, refactoring tools, and optimization utilities due to its accurate representation of syntactic structures.

    How does ‘astor’ complement the functionality provided by the ‘ast’ module?

    ‘astor’ simplifies handling AST nodes by offering convenient functions to pretty-print modified trees back into readable source-code form efficiently.

    Is frequent manipulation of Abstract Syntax Trees directly advisable?

    Directly altering ASTs should be approached cautiously as incorrect modifications might lead to invalid or unexpected program behavior during execution.

    Conclusion

    By embracing tools like ast and astsor, transitioning from traditional class-oriented programming towards simpler structuring without explicit classes becomes seamless in Python projects. Understanding these underlying mechanisms grants flexibility in adapting existing solutions while preserving readability and functionality across various project phases.

    Leave a Comment