Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

Python - how to create changeable return variable?

I want to predefine the return value of a function and change it's elements during my function. So, i.e. let us define

def myFunc()
    properties = ["value","num", "comment"]
    elements = []
    parts = {"properties":properties, "elements":elements}    
    error = 0
    errorMsg = ""
    result = [parts, error, errorMsg]
    
    .... # do all the stuff

    return result

In case something goes wrong, I would like to change error to an error code and add an error message. If everything went well, elements will contain some elements.

I understand, why this will always return error=0. It is because in result there is not stored a reference to error, there is stored the same reference, that error has had in the moment when result was created.

So how can I achieve, that the return value will also be changed, when chaning it's elements? I know, that

error = [0]
errorMsg = [""]

together with

error[0]=1
errorMsg[0]="error"

works, but in this case, the return value res[1] is a list and not the value itself.

question from:https://stackoverflow.com/questions/65941189/python-how-to-create-changeable-return-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You might be able to try a try except statement, I'm not sure if this is what you're looking for but it may work:

try:
    return result
except Exception as e:
    errorMsg = e + " has gone wrong!"
    return errorMsg

This uses errorMsg as a string and not a list like you had it, but I believe this should work


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...