I want to raise an error if the user uses return launch and result().
def launch(returnOutput=False):
# Function
if returnOutput:
return "value"
else:
value = "value"
def result():
return value
I want it to say like:
Console > print(launch(True), result())
Error: "Can't get result if launched output."
Is there a way to do this?
I am dumb so i didn't think of this:
def result():
if value == None:
# Throw error
else:
return value
Related
I am running my script in Flask and to catch and print the errors on the server I have made functions that either return None if succeeded else return an error message.
The problem is I have many functions which runs one after another and uses global variable from earlier function, this makes the code unorganized. What can I do?
App.py
from flask import Flask
from main import *
app = Flask(__name__)
#app.route('/')
def main():
input = request.args.get('input')
first_response = function1(input)
if first_response is None:
second_response = function2() # no input from hereon
if second_response is None:
third_response = function3() # functions are imported from main.py
if third_response is None:
...
if ...
else ...
else:
return third_response
else:
return second_response
else:
return first_response
main.py
def function1(input):
global new_variable1
if input is valid:
new_variable1 = round(input,2)
else:
return "the value is not integer"
def function2():
global new_variable2
if new_variable1 > 8:
new_variable2 = new_variable1 / 8
else:
return "the division is not working, value is 0"
def function3():
...
This is just a demo of what's going on. The last function will return a value either side. So if everything goes right I would be able to see the right output as well as I will see error on any given function.
The code works fine, but I need better alternative to do this.
Thanks!
Ah...you have (correctly) determined that you have two things to do:
Process your data, and
Deal with errors.
So let's process the data replacing global with parameteters (and come back to the error handling in a bit). You want to do something like this.
main.py
def function1(some_number):
if some_number is valid:
return round(some_number, 2)
def function2(a_rounded_number):
if a_rounded_number > 8:
return a_rounded_number / 8
So each function should return the results of its work. Then the calling routine can just send the results of each function to the next function, like this:
app.py
# [code snipped]
result1 = function1(the_input_value)
result2 = function2(result1)
result3 = function3(result2)
But...how do we deal with unexpected or error conditions? We use exceptions, like this:
main.py
def function1(some_number):
if some_number is valid:
return round(some_number, 2)
else:
raise ValueError("some_number was not valid")
and then in the calling routine
app.py
try:
result1 = function1(some_input_value)
except (ValueError as some_exception):
return str(some_exception)
I have a class that handles changes in the DB with a couple of methods, In each method, I am doing some sort of validation to the data to check if it's acceptable, and if not it will return a jsonfiy response with an error and status code:
class ChangeData():
# more code...
def change_data(self, new_data):
if new_data not valid:
print({"error": "first name can only contain latters"})# will print if not valid
return jsonify({"error":
"can't change the data"}), 400
else:
#change the data
I was expecting that if the data is not valid it will return to the frontend the jsonfiy error message but although the print works the frontend isn't receiving the jsonfiy error its receiving the jsonfiy success message no matter if the data is valid or not.
#app.route("/change", methods=["POST"])
def change_user_data():
data = request.form
update_data = ChangeData()
new_data = data.get("new_data", None)
if new_data:
update_data.change_data(new_data)
return jsonfiy({"sucsees": "the data as been changed"}), 200
One way I can solve it is by returning False from the change_data method if the data is not valid and True if it is, and based on that return a jsonfiy from the "/change" route, but I don't like this solution, Thanks in advance!
Your calling code doesn't expect a return so your error is not being 'captured' on return from the function
if new_data:
update_data.change_data(new_data)
Even if your calling code expected a return value, you're not checking if an error occurred before returning an output to the client. Your code simply does
return jsonfiy({"success": "the data as been changed"}), 200
One possible solution is to put your calling code within a try except block and raise an exception from the callee. Something like this (this is a rough outline and you have to flesh it out)
class ChangeData():
def change_data(self, new_data):
if new_data not valid:
print({"error": "first name can only contain letters"})
raise Exception("first name can only contain letters")
#app.route("/change", methods=["POST"])
def change_user_data():
data = request.form
update_data = ChangeData()
new_data = data.get("new_data", None)
try:
if new_data:
update_data.change_data(new_data)
return jsonfiy({"sucsees": "the data as been changed"}), 200
except:
return jsonify({"error": "can't change the data"}), 400
The code below runs and prints out the values returned from the two functions test_value(address) and checkRepeatCount(address) when i try to add the two value returned i None as the result. Anyway to fix this?
def check(address):
## define point variables
pass_invalid_char = test_value(address)
pass_repeat_count = checkRepeatCount(address)
if pass_invalid_char == False:
return print("Invalid character")
else:
pass
total = pass_invalid_char+pass_repeat_count
print(total)
check("hello")
Function 1 test_value
def test_value(value):
return print(30)
Function 2 checkRepeatCount
def checkRepeatCount(value):
return print(20)
Thats how im returning the function values
In both functions was returning a print statement with value
def test_value(value):
return print(30)
I was supposed just to return the number on its own like so
def test_value(value):
return 30
Consider the following:
def funcA():
some process = dynamicVar
if dynamicVar == 1:
return dynamicVar
else:
print "no dynamicVar"
def main():
outcome = funcA()
If the 'some process' part results in a 1, the var dynamicVar is passed back as outcome to the main func. If dynamicVar is anything but 1, the routine fails as no arguments are being return.
I could wrap the outcome as a list:
def funcA():
outcomeList = []
some process = dynamicVar
if dynamicVar == 1:
outcomeList.append(dynamicVar)
return outcomeList
else:
print "no dynamicVar"
return outcomeList
def main():
outcome = funcA()
if outcome != []:
do something using dynamicVar
else:
do something else!
or maybe as a dictionary item. Each of the 2 solutions I can think of involve another set of processing in the main / requesting func.
Is this the 'correct' way to handle this eventuality? or is there a better way?
What is the proper way of dealing with this. I was particularly thinking about trying to catch try: / except: errors, so in that example the uses are reversed, so something along the lines of:
def funcA():
some process = dynamicVar
if dynamicVar == 1:
return
else:
outcome = "no dynamicVar"
return outcome
def main():
try:
funcA()
except:
outcome = funcA.dynamicVar
In Python, all function that do not return a value will implicitly return None. So you can just check if outcome is not None in main().
I believe when you write a function, it's return value should be clear and expected. You should return what you say you will return. That being said, you can use None as a meaningful return value to indicate that the operation failed or produced no results:
def doSomething():
"""
doSomething will return a string value
If there is no value available, None will be returned
"""
if check_something():
return "a string"
# this is being explicit. If you did not do this,
# None would still be returned. But it is nice
# to be verbose so it reads properly with intent.
return None
Or you can make sure to always return a default of the same type:
def doSomething():
"""
doSomething will return a string value
If there is no value available, and empty string
will be returned
"""
if check_something():
return "a string"
return ""
This handles the case with a bunch of complex conditional tests that eventually just fall through:
def doSomething():
if foo:
if bar:
if biz:
return "value"
return ""
While running this function to validate captcha key and value i am not able to return
it show error like this
"AttributeError: 'bool' object has no attribute 'status_code'"
def validate(request):
id=request.GET.get('id','')
key=request.GET.get('key','')
captchavalue = mc.get(str(id))
if captchavalue == key:
return True
else:
return False
By reading the code and the error, I assume that validate is a view. A view must always return a HttpResponse. So if you want to return a response indicating a boolean value, indicating if captchavalue == key, do:
from django.http import HttpResponse
def validate(request):
id=request.GET.get('id','')
key=request.GET.get('key','')
captchavalue = mc.get(str(id))
return HttpResponse(captchavalue == key)
I'm not 100% sure about the import line, but it's something very similar.
I don't know much Django, but it seems it expects you to return a response object instead of a bool value (True / False).
Maybe your code should like more like this:
if captchvalue == key:
return HttpResponse('HTML Page saying OK')
else:
return HttpResponse('HTML Page saying Error')