【问题标题】:Return statement in recursive function with try-except structure not executed / returns NoneType未执行 try-except 结构的递归函数中的返回语句/返回 NoneType
【发布时间】:2020-12-10 13:29:04
【问题描述】:

为了测试一个函数是否适用于多个参数之一,我创建了一个带有 try-except 结构的递归函数。 函数递归后返回return语句,输出正确,但是return语句返回一个NoneType对象,就好像没有return语句一样。

from datetime import datetime, timedelta
import datetime as dt

# Bombard function with different tryinputs untill it works or all options are tested.
def tryexcept(function, tryinputs, *args, **kwargs):
    try:
        if True:#contains_explicit_return(function):
            output = function(tryinputs[0],*args,**kwargs)
            if type(output) == dt.date:
                print(output)
                return output
            else:
                raise ValueError("Output didn't return datetime.date object.")
        else:
            function(tryinputs[0],*args,**kwargs)
    except:
        if len(tryinputs) > 1:
            tryexcept(function,tryinputs[1:],*args,**kwargs)
        else:
            raise ValueError("WARNING: All tried inputs failed.")


# Date Conversion Functions
def stringtotime(stringformat,string):
    output = datetime.strptime(str(string),stringformat).date()
    return output


# Execution part

tryinputs = ['%d/%m/%Y %H:%M', '%d/%m/%Y %I:%M %p', '%m/%d/%Y %H:%M', '%m/%d/%Y %I:%M %p',
             '%d/%m/%Y  %H:%M:%S', '%d/%m/%Y  %I:%M:%S %p', '%m/%d/%Y  %H:%M:%S',
             '%m/%d/%Y  %I:%M:%S %p']
test = '29/9/2020  13:02:00'

output = tryexcept(stringtotime, tryinputs, test)

之后会打印以下内容:

2020-09-29

但变量“输出”包含一个 NoneType 对象:

In [176]: type(output)
Out[176]: NoneType

我不知道为什么会这样,也找不到任何遇到相同问题的帖子。有谁知道为什么会这样?

谢谢!

【问题讨论】:

    标签: python-3.x


    【解决方案1】:
      1 from datetime import datetime
      2 import datetime as dt
      3 
      4 # Bombard function with different tryinputs untill it works or all options are tested.
      5 def tryexcept(function, tryinputs, *args, **kwargs):
      6     try:
      7         if True:#contains_explicit_return(function):
      8             output = function(tryinputs[0],*args,**kwargs)
      9             if type(output) == dt.date:
     10                 return output
     11             else:
     12                 raise ValueError("Output didn't return datetime.date object.")
     13     except:
     14         if len(tryinputs) > 1:
     15             output=tryexcept(function,tryinputs[1:],*args,**kwargs)
     16         else:
     17             raise ValueError("WARNING: All tried inputs failed.")
     18     return output
     19 
     20 # Date Conversion Functions
     21 def stringtotime(stringformat,string):
     22     output = datetime.strptime(str(string),stringformat).date()
     23     return output
     24 
     25 
     26 # Execution part
     27 
     28 tryinputs = ['%d/%m/%Y %H:%M', '%d/%m/%Y %I:%M %p', '%m/%d/%Y %H:%M', '%m/%d/%Y %I:%M %p',
     29              '%d/%m/%Y  %H:%M:%S', '%d/%m/%Y  %I:%M:%S %p', '%m/%d/%Y  %H:%M:%S',
     30              '%m/%d/%Y  %I:%M:%S %p']
     31 test = '29/9/2020  13:02:00'
     32 
     33 output = tryexcept(stringtotime, tryinputs, test)
     34 print(output)
     35 print(type(output))
    

    您的程序有一个相当小的问题。您确实返回了一个值,但没有返回到主程序;而是将其返回到上一个函数调用的范围。当您在第 15 行从 tryexcept 的递归调用返回时,您没有接受成功调用返回的输出。一旦你回到顶层调用 try except,它会运行到函数的末尾,你不返回任何东西,所以函数隐式返回 None

    通过让第 15 行设置 output 并在第 18 行 tryexcept 的最后返回 output,您的返回值可以从函数中传递到主程序。

    【讨论】:

    • 啊,这真的很有意义。非常感谢! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 2020-02-09
    • 2010-10-30
    相关资源
    最近更新 更多