Search code examples
pythonpython-3.xcode-generation

Is using Python f-strings effective for generating Python code?


I have not found any related questions or examples of Python code using f-strings to generate Python code. Is there an underlying problem that I should know about? f-strings are really convenient and seem to be rather efficient for my needs.

I am generating some python scripts that can be used in the command line for automatically processing folders with remote sensing images. I was going to manually write some files by hand but realized is was relatively easy to automate the process by externalizing metadata regarding the expressions.

Program logic:

  • Extract expressions containing information on the different types of calculations that could be performed on the images (any sort of remote sensing indice)
  • Iterate through expressions
  • Create file with expression name (and other standards)
  • Insert expression information into f-strings
  • Write f-string to create file

I will also generate some tests automatically once settled on the method to be used. Is there a limit from which f-strings will not handle the code efficiently?

Some people have discussed using Python templates like Jinja2. However, if f-strings are sufficient I do not wish to integrate another external dependency.

from expressions_meta import expressions

for key in expressions.keys():
    file_name = '_'.join([key, 'dir', 'cl.py'])

    with open(file_name, 'w') as f:

        f.write(f"""
import sys
import getopt

from gdal_dir_calc import GDALDirCalc

expression = {expressions[key]}

band_meta = {{}}

[...]

gdal_dir_obj.main()
""")

I might just be overly cautious but I think the topic could address other applications as well.

Any other tips regarding the use of f-strings for Python code generation or another tool?


Solution

  • If you are coming across this question, be sure to review the design of your program.

    Most likely you are trying to implement a solution in which you violate DRY principles.

    For command line applications:

    Instead of generating many specific commands, look into to passing a name argument which in turn can be used with a selection of arguments.

    From the standard library, some tools that may be helpful are configparser, shlex, cmd, getopt and argparse. See the standard library documentation on these tools.

    Click is an interesting third party package.

    Thanks @SergeBallesta for your helpful comments.