Developing a code generator library
In this section, let’s look at developing a code generator that will be used to generate code for all the base classes – CarSpecs
, CarMake
, CarCatalogue
, BodyStyle
, and SaleType
. The detailed steps are as follows:
- Let’s create a file named
codegenerator.py
and start by defining a class namedCodeGenerator
:class CodeGenerator:
- Let’s define a method that imports the
ast
library and adds ameta_template
attribute that has the string format of theCarSpecs
class as a value. Themeta_template
attribute is further parsed and unparsed into class code:def generate_meta(self): ast = __import__('ast') meta_template = ''' from abc import ABC, abstractmethod, ABCMeta class CarSpecs(type, metaclass = ABCMeta): def __new__(classitself, classname, baseclasses, attributes): ...