Transform an "exec ()" of python into str

3

I'm doing some experiments in python, I was wondering if it's possible to transform a exec() into a string, example:

def prueba():
    print("hola mundo")
var = exec("prueba()")

The idea is that the variable "var" has the value "hello world", the truth is that I do not think it is even possible but I hope to be wrong.

    
asked by binario_newbie 29.09.2018 в 23:03
source

1 answer

3

It is not possible directly for a very simple reason, prueba does not return "nothing" , the function is limited to printing the string by the standard output and returning None (all function / method returns None by default). Just like if you do:

>>> var = prueba()

var is None , which is what the function returns and not "hola mundo" .

On the other hand, exec always returns None , discarding any return resulting from executing the received code, but you can make an assignment in the chain that you pass without problems, as long as it is code Python valid exec does the "magic", very dark and dangerous indeed ...:)

def prueba():
    return("hola mundo")
exec("var = prueba()")

print(var)

or use eval , which only allows an expression (if what is passed is a string) unlike exec but, on the other hand, returns the result of its evaluation:

def prueba():
    return("hola mundo")
var = eval("prueba()")

print(var)
    
answered by 29.09.2018 / 23:09
source