Python警告 - 预期类型'联盟[积分,切片]',得到' str'代替

时间:2017-06-10 15:32:57

标签: python dictionary types pycharm warnings

我在python下面的代码在线上给了我一个警告:

 some_new_object['someVar'] = cd['someVar']

警告是

Expected type 'Union[Integral, slice]', got 'str' instead

代码:

def some_object():
     return {
         'someId': 0,
         'someVar' : ''
     }

def warn_test(in_list):
     try:
         new_list = []
         some_new_object = some_object()

         for cd in in_list:
             if cd['someVar']:
                 new_list.append(cd)

         for cd in new_list:
             some_new_object['someVar'] = cd['someVar']
             in_list.append(some_new_object.copy())

         return in_list
     except Exception:
         print 'baaa'

 #Main Program
 new_obj =  some_object()
 new_obj['someId'] = 1
 new_obj['someVar'] = 'Next'

 new_obj2 =  some_object()
 new_obj2['someId'] = 1
 new_obj2['someVar'] = None

 new_list = []
 new_list.append(new_obj)
 new_list.append(new_obj2)

 out_list = warn_test(new_list)
 for obj in out_list:
     print obj

如果我将函数warn_test更改为:

def warn_test(in_list):
    try:
        new_list = []
        some_new_object = some_object()

        for cd in in_list:
            if cd['someVar']:
                some_new_object['someVar'] = cd['someVar']
                new_list.append(some_new_object.copy())

        for cd in new_list:
            in_list.append(cd)

        return in_list
    except Exception:
        print 'baaa'

它没有给我任何警告。

有人可以帮助我理解为什么我会收到警告,以及如何在第二次迭代中访问cd['someVar']而不会收到警告?

我知道这段代码很奇怪,我需要这个用于我正在处理的项目,我在这里分享了这个测试,但它给了我相同的警告,所以这个解决方案将在我的系统中修复它。 (没有警告是该系统必须的Haves之一)

1 个答案:

答案 0 :(得分:0)

迟到总比不到好。

总的来说,我发现如果变量/方法返回是强类型的,这些警告就会消失。