对于非空列表,Python函数返回None

时间:2015-12-16 15:32:56

标签: python function

我编写了一个递归函数来对Racktables数据库进行查询,并跟踪对象之间的连接并将它们放在一个列表中。

所有结果都会附加并扩展到我作为参数提供的列表中。 该函数最多可以使用return语句,但列表在返回后会显示None

我在函数中添加了一些print语句进行调试,列表中包含了我需要的数据:

def plink(Objid, PortId, mylist):

    if len(mylist) < 2:                         #If this is the first run put he initial data in the list
        mylist.append(Objid)
        mylist.append(PortId)

    res = rt.GetLink(PortId)                    #check if port is connected 

    if res == (False, False):
        print 'exiting because not connected'   #debug
        return mylist                           #If not connected return list

    nextObj = rt.GetPortObjid(res[1])
    mylist.extend(res)
    mylist.append(nextObj)

    ispatch = rt.CheckObjType(nextObj, 50080)
    if ispatch[0][0] == 0:                      #If connected to a non-patch-unit, add data to list and exit
        print "exiting because next object {0} is not a patchunit, mylist is {1}".format(nextObj, mylist)  #debug
        return mylist

    patchPorts = rt.GetAllPorts(nextObj)

    if len(patchPorts) != 2:                    #check if the patchunit has the right number of ports
        mylist.append("Error, patch-unit must have exactly two ports")
        return mylist

    if patchPorts[0][2] == res[1]:              #check which port is unseen and call the function again
        print mylist
        plink(nextObj, patchPorts[1][2], mylist)
    else:
        print mylist
        plink(nextObj, patchPorts[0][2], mylist)

results = ['Initial data']
allconn = plink(159, 947, results)
print "The full connection is {0}".format(allconn)

(我在这里跳过了DB结构)

运行此代码会给出:

['Initial data', 159, 947, 'C150303-056', 4882, 1591L]
['Initial data', 159, 947, 'C150303-056', 4882, 1591L, 'C140917-056', 4689, 727L]
exiting because next object 1114 is not a patchunit, mylist is ['Initial data', 159, 947, 'C150303-056', 4882, 1591L, 'C140917-056', 4689, 727L, 'C140908-001', 3842, 1114L]
The full connection is None

调试打印显示正好按照预期填充列表,但是当在函数外部打印时,在预先分配给变量之后,我得到无。

我写这篇文章是为了在运行python 2.6的CentOS 6服务器上运行它。我可以在virtualenv中运行它,作为最后的手段,但如果可能的话我会避免它

1 个答案:

答案 0 :(得分:1)

if patchPorts[0][2] == res[1]:              #check which port is unseen and call the function again
    print mylist
    plink(nextObj, patchPorts[1][2], mylist)
else:
    print mylist
    plink(nextObj, patchPorts[0][2], mylist)

递归调用函数不会自动使内部调用将返回值传递给外部调用。您仍然需要明确return

if patchPorts[0][2] == res[1]:              #check which port is unseen and call the function again
    print mylist
    return plink(nextObj, patchPorts[1][2], mylist)
else:
    print mylist
    return plink(nextObj, patchPorts[0][2], mylist)