Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can you create a function that has custom code via parameters in python?

What I mean by the title is this for ex:

def write_to_file(*params):
    with open(path, 'r+', encoding="utf-8") as file:
        content = file.read()
        file.seek(0) 

        # custom code via func parameters to be executed
        # for example *params will be ["file.write("test" + '\n')", "]
        # and here will be like for loop that goes through the params ?
        # for code in params:
            #code.execute() ?
    
        file.truncate() 

Hopefully I explained it well, just wondering if you can do any of this.

// Edit (better explanation): I want to convert string into a code executable, "print(x)" -> print(x) that will be called in a function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you just need to execute code from a string (reading the contents of a file with .read() also returns them in form of a single or multiline string), then you might simply use eval() function for the purpose.

eval() is a built-in Python function that can evaluate any expression given in it, and any errors in expressions are also thrown on console accordingly. This function just evaluates the given single-line expression, and does not support assignment and other related operators.
For other purposes, you may also want to use exec() Python function.

I initially wanted to comment it, but I lack 2 reputation score for it at the time of posting it, so have to post it as an answer here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading