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.pyand start by defining a class namedCodeGenerator:class CodeGenerator:
- Let’s define a method that imports the
astlibrary and adds ameta_templateattribute that has the string format of theCarSpecsclass as a value. Themeta_templateattribute 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):Â ...