“预期类型‘Union[str, bytearray]’改为‘int’”写入方法中的警告

问题描述 投票:0回答:3

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

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

但是当删除除法时

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

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

警告消失

这里到底发生了什么?

谢谢

python python-2.7 pycharm
3个回答
46
投票

忽略此警告。 IDE 正在(根据有限的信息)对运行时的数据类型进行最佳猜测,但它的猜测是错误的。也就是说,如果您不知道某个东西实际上是什么,则可以相当合理地预期某个东西乘以

int
将得到
int

如果您确实想解决这个问题,请通过为您的类编写文档字符串(或使用注释来提供类型提示)来告诉 IDE 您的期望

chunk.pattern

例如。

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

对于较新版本的 python,首选语法是:

class DedupChunk:
    def __init__(self,
            chunk_pattern: str,
            # ... more args
    ):
        self._chunk_pattern = chunk_pattern
        ... # rest of class

对于局部变量或类变量,您可以对变量进行注释。

# given f() has an unknown return type

foo: str = f()  # annotate as type str and initalise
bar: str        # only annotate as type str, but leave uninitialised

class MyClass:
    foo: str = f()
    bar: str

10
投票

要忽略内联警告,请将此注释添加到导致警告的行上方

# noinspection PyTypeChecker

0
投票

我遇到这个问题是因为我使用了

x=int|list[int]
而不是
x:int|list[int]

© www.soinside.com 2019 - 2024. All rights reserved.