"预期类型' Union [str,bytearray]'得到了' int'代替"写入方法中的警告

时间:2015-10-27 18:11:28

标签: python python-2.7 pycharm

我的脚本使用预生成的数据模式按块写入文件块:

# DedupChunk class CTOR:
class DedupChunk:
    def __init__(self, chunk_size, chunk_pattern, chunk_position=0, state=DedupChunkStates.PENDING):
        self._chunk_size = chunk_size  # chunk size in bytes
        self._chunk_pattern = chunk_pattern
        self._chunk_position = chunk_position
        self._state = state
        self.mapping = None

    @property
    def size(self):
        return self._chunk_size

    @property
    def pattern(self):
        return self._chunk_pattern

    @property
    def position(self):
        return self._chunk_position

    @property
    def state(self):
        return self._state

...

# Here Chunk object is being initialized (inside other class's CTOR):
chunk_size = random.randint(64, 192) * 1024  # in bytes
        while (position + chunk_size) < self.file_size:  # generating random chunks number
            self.chunks.append(DedupChunk(chunk_size, DedupChunkPattern.get_random_chunk_pattern(), position))

...

# Actual writing
    with open(self.path, 'rb+') as f:
        for chunk in self.chunks:
            f.write(chunk.pattern * (chunk.size // 8))

...

PyCharm

Expected type 'Union[str, bytearray]' got 'int' instead显示&#34; f.write(chunk.pattern * chunk.size)&#34;写入方法中的警告

但在删除分区时 chunk.size //= 8 f.write(chunk.pattern * chunk.size) ,或在外面做分工:

{{1}}

警告消失

这里到底发生了什么?

由于

1 个答案:

答案 0 :(得分:23)

忽略此警告。 IDE正在最好地猜测(来自有限的信息)关于数据类型在运行时将是什么,但它猜错了。也就是说,如果你不知道实际上是什么东西,那么期望乘以int的东西会产生int是相当合理的。

如果您真的想要解决这个问题,请通过为您的班级编写文档字符串(或使用注释提供类型提示)告诉IDE您期望chunk.pattern的内容。

例如

class DedupChunk:
    """
    :type _chunk_pattern: str
    ... other fields
    """
    ... # rest of class