簡體   English   中英

為此,我如何提高 python 中的代碼可讀性?

[英]How can I increase code readability in python for this?

我在 Flask 中運行我的腳本,為了捕獲並打印服務器上的錯誤,我創建了一些函數,如果成功則返回None ,否則返回一條error message

問題是我有許多函數一個接一個地運行並使用早期 function 的全局變量,這使得代碼變得雜亂無章。 我能做什么?

應用程序.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

主程序

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():
...

這只是正在發生的事情的演示。 最后一個 function 將在任一側返回一個值。 因此,如果一切順利,我將能夠看到正確的 output,並且我將在任何給定的 function 上看到錯誤。

代碼工作正常,但我需要更好的選擇來做到這一點。

謝謝!

啊......你已經(正確地)確定你有兩件事要做:

  1. 處理您的數據,以及
  2. 處理錯誤。

因此,讓我們用參數替換全局數據來處理數據(稍后再回到錯誤處理)。 你想做這樣的事情。

主程序

    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

所以每個 function 應該返回它的工作結果。 然后調用例程可以將每個 function 的結果發送到下一個 function,如下所示:

應用程序.py


   # [code snipped]

   result1 = function1(the_input_value)
   result2 = function2(result1)
   result3 = function3(result2)

但是......我們如何處理意外或錯誤情況? 我們使用異常,像這樣:

主程序

    def function1(some_number):
        if some_number is valid:
            return round(some_number, 2)
        else:
            raise ValueError("some_number was not valid")
     

然后在調用程序中

應用程序.py


   try:
       result1 = function1(some_input_value)
   except (ValueError as some_exception):
       return str(some_exception)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM