Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22462

Python Morsels: How I made a dataclass remover

$
0
0

My journey creating a dataclass converter by using abstract syntax trees, match-case, the dedent utility and more. You may learn something new along the way.

How does this undataclass.py script work?

Essentially the undaclass.py script:

  1. Parses the contents of a Python file into an abstract syntax tree (using the ast module)
  2. Identifies dataclass-related AST nodes representing dataclasses, dataclass fields, and __post_init__ methods
  3. Builds up strings representing Python code for the various equivalent non-dataclass methods
  4. Parses those strings into AST nodes and injects them into the was-a-dataclass node
  5. Converts all the AST nodes back into Python code

I used some tricks I don't usually get to use in Python. I used:

  1. Many very hairy match-case blocks which replaced even hairier if-elif blocks
  2. A sentinel object to keep track of a location that needed replacing
  3. Python's textwrap.dedent utility, which I feel should be more widely known & used
  4. slice assignment to inject one list into another
  5. The ast module's unparse function to convert an abstract syntax tree into Python code

Let's take a look at some of the code.

Structural pattern matching

Python's structural pattern matching can …

Read the full article: https://www.pythonmorsels.com/making-a-dataclass-remover/


Viewing all articles
Browse latest Browse all 22462

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>