繁体   English   中英

Python函数针对非空列表返回None

[英]Python function returns None for non emptylist

我编写了一个递归函数来对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)

(我在这里跳过了数据库构造)

运行此代码将给出:

['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

调试打印显示出的列表完全符合我的预期,但是在函数外打印时以及事先分配给变量后,我都得到None。

我正在编写此代码,以便在具有python 2.6的CentOS 6服务器上运行它。 我可以在virtualenv中运行它,这是万不得已的方法,但是如果可能的话,我会避免使用它

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM