Hi.
I have a function that should return the result of a query.
It works, but my question is related to what is the best practise.
The return value in this case is a response object from an API, that contains a value which indicate whether the query failed or not. The first question then is, should I have my function return the result of the query as it is?
For the cases where the return object says nothing about how the execution of the function went, should it also return a boolean to indicate if things went as it should?
And lastly, if I would need to return more than one variable, should they be returned as a tuple, a dictionary, or in some other way?
I haven't been programming with Python for long. I know a bit, but I lack a lot of knowledge about how to write good/nice code.
Top comments (5)
I dont know much about python, but when building graphql api, after long trial and error we went with structure like this:
Errors is empty when there are no errors, and populated when something went wrong. We found out that it is easier to handle both cases when return values are consistent.
Hi, and thanks for the reply :)
Yeah, I was thinking of using a dictionary in a similar fashion, where one key-value pair is used to indicate if there was any trouble or not.
Having a key
error
seems like a nice way to create the necessary feed back in a standardized way.this is preferable
In most cases, the 'de-facto' standard for Python is:
True
).For complex return values:
Regardless, the most important thing here is to make your code consistent. Pick an approach and stick to it. I would encourage you to look at some of the bigger projects written in Python for ideas on this though.
Thank you for such a in depth reply :D
I'll have to read this a few times, and look up some things I have not encountered in Python before :)
Looking forward to testing out what you have suggested, and I will try to stay consistent in my projects to come.