首页 > 解决方案 > 转换python2代码时如何比较python3中的无类型

问题描述

我被困在从 python2 到 python3 的迁移中,其中一部分脚本将旧值与新值进行比较。在 python2 中,您可以比较“无”类型,但在 python3 中,您不能。有关解决此问题的任何建议?

不幸的是,在下面的这个片段中reading可能是脏数据并且包含“None”或None而不是一个值。

这是代码片段(简化):

# Meta data

do_meta_write = False
meta_data = all_meta_data[reading['device_key']]

# All time high
if value1 in value2 and reading1 in value2[value1]['all_time_high']:
        channel_meta = value2[value1]

        if reading['device'].model.channels[reading['channel_num']]['sensor_class'].newest_wins_tie:
            if channel_meta['all_time_high'][reading1] <= reading['reading_value']:
                do_meta_write = True
                channel_meta['all_time_high'] = ujson.decode(
                    reading['reading_json'])
        else:
            if channel_meta['all_time_high'][reading1] < reading['reading_value']:
                do_meta_write = True
                channel_meta['all_time_high'] = ujson.decode(
                    reading['reading_json'])
else:
    do_meta_write = True

    if not value2.get(value1):
        value2[value1] = {}

    meta_data['channel_data'][str(
        reading['channel_num'])]['all_time_high'] = ujson.decode(reading['reading_json'])


错误:

[ERROR] TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'
channel_meta['all_time_high']['raw_values'][reading['reading_unit']] < reading['reading_value']_summarize)

标签: pythonpython-3.xcomparator

解决方案


在不允许None的上下文中使用它之前检查一个值是否存在。None例如,

do_meta_write = False
if reading['device_key'] is not None:
    meta_data = all_meta_data[reading['device_key']]
    
    # All time high
    if value1 in value2 and reading1 in value2[value1]['all_time_high']:
        channel_meta = value2[value1]

    ...

推荐阅读