Is using Python f-strings effective for generating Python code?Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?Convert bytes to a string?Does Python have a string 'contains' substring method?How do I lowercase a string in Python?Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?

What is the evidence on the danger of feeding whole blueberries and grapes to infants and toddlers?

How to translate 脑袋短路 into English?

How to avoid using System.String with Rfc2898DeriveBytes in C#

Does git delete empty folders?

Has any ancient or medieval Vedic scholar refuted the guna-based varna theory?

Why the color Red in Us, what is the significance?

Do predators tend to have vertical slit pupils versus horizontal for prey animals?

Metal that glows when near pieces of itself

Story that includes a description: "Two concentric circles, intersecting at three points"

How to think about joining a company whose business I do not understand?

Why didn’t Doctor Strange stay in the original winning timeline?

Unsolved Problems (Not Independent of ZFC) due to Lack of Computational Power

How does the Saturn V Dynamic Test Stand work?

E: Sub-process /usr/bin/dpkg returned an error code (1) - but how do I find the meaningful error messages in APT's output?

Chess software to analyze games

How can I train a replacement without letting my bosses and the replacement know?

Homogeneous Equations and Linear Algebra

Why do some academic journals requires a separate "summary" paragraph in addition to an abstract?

Can my Boyfriend, who lives in the UK and has a Polish passport, visit me in the USA?

Moons that can't see each other

How best to join tables, which have different lengths on the same column values which exist in both tables?

Can I submit a paper under an alias so as to avoid trouble in my country?

How can I override the serving of Media Files? (Implementing authentication for media items)

Do living authors still get paid royalties for their old work?



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


Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?Convert bytes to a string?Does Python have a string 'contains' substring method?How do I lowercase a string in Python?Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















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?










share|improve this question





















  • 3





    Why do you even need many scripts with (potentially) almost exactly the same source code, rather than a single script that accepts input from CLI arguments or conf files?

    – DeepSpace
    Mar 27 at 14:45












  • Irrelevant to the question, but you do realize that file_name will actually be overwritten on each of the expressions iterations, right? You'll end up with just the last value.

    – Matias Cicero
    Mar 27 at 14:46











  • @DeepSpace: The objective is to have specific indice calculators that can be easily used by people with little technical background. Like calculating an NDVI or NDSI and having only to pass the required and simplified arguments for the calculation.

    – Zachary Deziel
    Mar 27 at 14:52











  • @MatiasCicero: Yes, the program generates as many scripts as there are expressions.

    – Zachary Deziel
    Mar 27 at 14:54











  • @DeepSpace: To answer your questions more clearly, the script is based on gdal.org/gdal_calc.html. gdal_calc already provides a way to treat individual images in a general command line utility. The interest of my project is processing directories of images and having a more abstracted command line interface (having more explicit arguments than (A-B)/(A+B) for example).

    – Zachary Deziel
    Mar 27 at 15:08

















2















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?










share|improve this question





















  • 3





    Why do you even need many scripts with (potentially) almost exactly the same source code, rather than a single script that accepts input from CLI arguments or conf files?

    – DeepSpace
    Mar 27 at 14:45












  • Irrelevant to the question, but you do realize that file_name will actually be overwritten on each of the expressions iterations, right? You'll end up with just the last value.

    – Matias Cicero
    Mar 27 at 14:46











  • @DeepSpace: The objective is to have specific indice calculators that can be easily used by people with little technical background. Like calculating an NDVI or NDSI and having only to pass the required and simplified arguments for the calculation.

    – Zachary Deziel
    Mar 27 at 14:52











  • @MatiasCicero: Yes, the program generates as many scripts as there are expressions.

    – Zachary Deziel
    Mar 27 at 14:54











  • @DeepSpace: To answer your questions more clearly, the script is based on gdal.org/gdal_calc.html. gdal_calc already provides a way to treat individual images in a general command line utility. The interest of my project is processing directories of images and having a more abstracted command line interface (having more explicit arguments than (A-B)/(A+B) for example).

    – Zachary Deziel
    Mar 27 at 15:08













2












2








2


1






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?










share|improve this question
















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?







python python-3.x code-generation






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 4:02









Nathan Vērzemnieks

4,6981 gold badge6 silver badges18 bronze badges




4,6981 gold badge6 silver badges18 bronze badges










asked Mar 27 at 14:40









Zachary DezielZachary Deziel

114 bronze badges




114 bronze badges










  • 3





    Why do you even need many scripts with (potentially) almost exactly the same source code, rather than a single script that accepts input from CLI arguments or conf files?

    – DeepSpace
    Mar 27 at 14:45












  • Irrelevant to the question, but you do realize that file_name will actually be overwritten on each of the expressions iterations, right? You'll end up with just the last value.

    – Matias Cicero
    Mar 27 at 14:46











  • @DeepSpace: The objective is to have specific indice calculators that can be easily used by people with little technical background. Like calculating an NDVI or NDSI and having only to pass the required and simplified arguments for the calculation.

    – Zachary Deziel
    Mar 27 at 14:52











  • @MatiasCicero: Yes, the program generates as many scripts as there are expressions.

    – Zachary Deziel
    Mar 27 at 14:54











  • @DeepSpace: To answer your questions more clearly, the script is based on gdal.org/gdal_calc.html. gdal_calc already provides a way to treat individual images in a general command line utility. The interest of my project is processing directories of images and having a more abstracted command line interface (having more explicit arguments than (A-B)/(A+B) for example).

    – Zachary Deziel
    Mar 27 at 15:08












  • 3





    Why do you even need many scripts with (potentially) almost exactly the same source code, rather than a single script that accepts input from CLI arguments or conf files?

    – DeepSpace
    Mar 27 at 14:45












  • Irrelevant to the question, but you do realize that file_name will actually be overwritten on each of the expressions iterations, right? You'll end up with just the last value.

    – Matias Cicero
    Mar 27 at 14:46











  • @DeepSpace: The objective is to have specific indice calculators that can be easily used by people with little technical background. Like calculating an NDVI or NDSI and having only to pass the required and simplified arguments for the calculation.

    – Zachary Deziel
    Mar 27 at 14:52











  • @MatiasCicero: Yes, the program generates as many scripts as there are expressions.

    – Zachary Deziel
    Mar 27 at 14:54











  • @DeepSpace: To answer your questions more clearly, the script is based on gdal.org/gdal_calc.html. gdal_calc already provides a way to treat individual images in a general command line utility. The interest of my project is processing directories of images and having a more abstracted command line interface (having more explicit arguments than (A-B)/(A+B) for example).

    – Zachary Deziel
    Mar 27 at 15:08







3




3





Why do you even need many scripts with (potentially) almost exactly the same source code, rather than a single script that accepts input from CLI arguments or conf files?

– DeepSpace
Mar 27 at 14:45






Why do you even need many scripts with (potentially) almost exactly the same source code, rather than a single script that accepts input from CLI arguments or conf files?

– DeepSpace
Mar 27 at 14:45














Irrelevant to the question, but you do realize that file_name will actually be overwritten on each of the expressions iterations, right? You'll end up with just the last value.

– Matias Cicero
Mar 27 at 14:46





Irrelevant to the question, but you do realize that file_name will actually be overwritten on each of the expressions iterations, right? You'll end up with just the last value.

– Matias Cicero
Mar 27 at 14:46













@DeepSpace: The objective is to have specific indice calculators that can be easily used by people with little technical background. Like calculating an NDVI or NDSI and having only to pass the required and simplified arguments for the calculation.

– Zachary Deziel
Mar 27 at 14:52





@DeepSpace: The objective is to have specific indice calculators that can be easily used by people with little technical background. Like calculating an NDVI or NDSI and having only to pass the required and simplified arguments for the calculation.

– Zachary Deziel
Mar 27 at 14:52













@MatiasCicero: Yes, the program generates as many scripts as there are expressions.

– Zachary Deziel
Mar 27 at 14:54





@MatiasCicero: Yes, the program generates as many scripts as there are expressions.

– Zachary Deziel
Mar 27 at 14:54













@DeepSpace: To answer your questions more clearly, the script is based on gdal.org/gdal_calc.html. gdal_calc already provides a way to treat individual images in a general command line utility. The interest of my project is processing directories of images and having a more abstracted command line interface (having more explicit arguments than (A-B)/(A+B) for example).

– Zachary Deziel
Mar 27 at 15:08





@DeepSpace: To answer your questions more clearly, the script is based on gdal.org/gdal_calc.html. gdal_calc already provides a way to treat individual images in a general command line utility. The interest of my project is processing directories of images and having a more abstracted command line interface (having more explicit arguments than (A-B)/(A+B) for example).

– Zachary Deziel
Mar 27 at 15:08












1 Answer
1






active

oldest

votes


















0














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.






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55379934%2fis-using-python-f-strings-effective-for-generating-python-code%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    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.






    share|improve this answer





























      0














      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.






      share|improve this answer



























        0












        0








        0







        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 27 at 16:37









        Zachary DezielZachary Deziel

        114 bronze badges




        114 bronze badges





















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55379934%2fis-using-python-f-strings-effective-for-generating-python-code%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해