“预期类型 'Union[str, bytearray]' 改为 'int'"写入方法中的警告 [英] "Expected type 'Union[str, bytearray]' got 'int' instead" warning in write method

查看:31
本文介绍了“预期类型 'Union[str, bytearray]' 改为 'int'"写入方法中的警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My script writes to file chunk by chunk, using pre-generated data patterns:

#  Data pattern generator    
def get_random_chunk_pattern():
            return ''.join(random.choice(ascii_uppercase + digits + ascii_lowercase) for _ in range(8))

....

# 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"警告

PyCharm displays "Expected type 'Union[str, bytearray]' got 'int' instead" warning in write method

但是在删除除法时f.write(chunk.pattern * chunk.size),或者在外面做除法:

But when removing the division in f.write(chunk.pattern * chunk.size), or doing division outside:

chunk.size //= 8
f.write(chunk.pattern * chunk.size)

警告消失

这里到底发生了什么?

谢谢

推荐答案

忽略此警告.IDE 正在对运行时的数据类型做出最佳猜测(根据有限的信息),但猜测是错误的.也就是说,如果你不知道某个东西实际上是什么,那么期望乘以 int 的东西会产生一个 int 是相当合理的.

Ignore this warning. The IDE is making a best guess (from limited information) as to what the data type will be at runtime, but it is guessing wrong. That is, it is fairly reasonable to expect that something multiplied by an int will result in an int if you don't know what that something actually is.

如果你真的想解决这个问题,那么通过为你的类编写一个文档字符串(或使用注释来提供类型提示)告诉 IDE 你期望 chunk.pattern 是什么.

If you really want to solve this then tell the IDE what you expect chunk.pattern to be by writing a doc string for your class (or using annotations to provide type hinting).

例如.

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

这篇关于“预期类型 'Union[str, bytearray]' 改为 'int'"写入方法中的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆