DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • OpenCV Integration With Live 360 Video for Robotics
  • Application-Level Tracing: The Good, the Bad, and the Alternative
  • Building a Dynamic Chat Application: Setting up ChatGPT in FastAPI and Displaying Conversations in ReactJS
  • Effective Prompt Engineering Principles for Generative AI Application

Trending

  • Build Your First AI Model in Python: A Beginner's Guide (1 of 3)
  • Unlocking AI Coding Assistants: Generate Unit Tests
  • MySQL to PostgreSQL Database Migration: A Practical Case Study
  • Understanding and Mitigating IP Spoofing Attacks
  1. DZone
  2. Coding
  3. Languages
  4. A Simple Code Generator Using a Cool Python Feature

A Simple Code Generator Using a Cool Python Feature

By 
Bipin Patwardhan user avatar
Bipin Patwardhan
·
Mar. 20, 22 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
7.7K Views

Join the DZone community and get the full member experience.

Join For Free

For my most recent project, I wrote a couple of code generators - three variants of a Python/Spark application generator and at least four variants of an Airflow DAG generator. Different variants were needed as the requirements and the complexity of the output evolved over a period of time. Using this experience, I will show how you can get started on your journey of writing a code generator using a cool feature of Python.

For the purpose of this article, I will use a Python program that generates a basic Python/Spark application to get and display 10 rows of the specified table. The application to be generated is as below

Python
 
import os
import sys
import pyspark
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql import SparkSession

spark_session = SparkSession.builder.appName("generator").getOrCreate()
try:
    df = spark_session.sql("select * from user_names")
    df.show(10, False)
except Exception as e:
    print("Got an error {er}".format(er=str(e)))
spark_session.stop()

Version 1

The simplest method for generating this application is to make use of print statements as below

Python
 
import os
import sys

print("import os")
print("import sys")
print("import pyspark")
print("from pyspark import SparkContext")
print("from pyspark.sql import SQLContext")
print("from pyspark.sql import SparkSession")
print("")
print("spark_session = SparkSession.builder.appName(\"generator\").getOrCreate()")
print("try:")
print("    df = spark_session.sql(\"select * from user_names\")")
print("    df.show(10, False)")
print("except Exception as e:")
print("    print(\"Got an error {er}\".format(er=str(e)))")
print("")

Version 2

What if we want to allow the user to provide the name of the application and the name of the table, so that these can be incorporated in the application? Let us accept the name of the application and the name of the table as command line arguments when the generator is executed. Our code generator has to be modified as below

Python
 
import os
import sys

app_name = sys.argv[1]
table_name = sys.argv[2]

print("import os")
print("import sys")
print("import pyspark")
print("from pyspark import SparkContext")
print("from pyspark.sql import SQLContext")
print("from pyspark.sql import SparkSession")
print("")
print("spark_session = SparkSession.builder.appName(\"" + app_name + "\").getOrCreate()")
print("try:")
print("    df = spark_session.sql(\"select * from " + table_name + "\")")
print("    df.show(10, False)")
print("except Exception as e:")
print("    print(\"Got an error {er}\".format(er=str(e)))")
print("")

Version 3

In version 2, can you make out which part of the code is the code generator and which part of the code is the generated code? It is quite difficult to separate out the two. Imagine what the code will look like if we have to generate a very large and complex program. As you can imagine, the code generator will not be easy to maintain.

Let us simplify the code generator. Python allows us to define blocks of text inside triple double quotes or triple single quotes. The text can not only span multiple rows, but can also contain variable place-holders. What are variable place-holders? These are elements that are substituted by the actual value at the time the block of text is evaluated. And when is a block of text evaluated? When it is used in a print statement.

How does our code generator look like?

Python
 
import os
import sys

template_application = """ # note the triple quotes that indicate start of block
import os
import sys
import pyspark
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql import SparkSession

spark_session = SparkSession.builder.appName("{app_name}").getOrCreate()
try:
    df = spark_session.sql("select * from {table_name}")
    df.show(10, False)
except Exception as e:
    print("Got an error {{er}}".format(er=str(e)))
spark_session.stop()
""" # note the triple quote that indicate end of block

app_name = sys.argv[1]
table_name = sys.argv[2]
print(template_application.format(app_name=app_name, table_name=table_name))

We are defining all our code in the variable named 'template_application'. The variable also contains variable place-holders for application name (app_name) and table name (table_name). We have to take care to provide values for these variables. We do that in the print statement, where we provide the actual values using the format keyword.

Important Note:

You will note that we have enclosed the 'er' variable inside double curly brackets. This is because we want the variable to remain a variable in the generated code. By using double curly brackets, Python will remove one set of curly brackets during evaluation of the format statement, but will retain the second set. The second set then appears as a variable in the generated code.

Happy coding!!!

Python (language) application

Opinions expressed by DZone contributors are their own.

Related

  • OpenCV Integration With Live 360 Video for Robotics
  • Application-Level Tracing: The Good, the Bad, and the Alternative
  • Building a Dynamic Chat Application: Setting up ChatGPT in FastAPI and Displaying Conversations in ReactJS
  • Effective Prompt Engineering Principles for Generative AI Application

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!