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

Time:01-14

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.

CodePudding user response:

pass the function itself:

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

def func():
    print("foo")

write_to_file(func)

CodePudding user response:

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.

  •  Tags:  
  • Related