r/pythonhelp • • May 25 '22

random.sample throws a warning with the counts parameter

Hi,

I am using random.sample with the counts parameter in my code and PyCharm throws a warning : Expected type 'Iterable[str] | None' (matched generic type 'Iterable[_T] | None'), got 'list[int]' instead

The code itself works fine, but I am losing my mind trying to get rid of the warning. Why does it do that? Here is an example of the code:

from random import sample

a, b, c = sample(["A", "B"], counts=[1, 2], k=3)

print(a, b, c)

Results = B B A , A B B , B A B

2 Upvotes

4 comments sorted by

2

u/Goobyalus May 25 '22

It's because random.pyi (the python interface file) declares sample like this:

if sys.version_info >= (3, 9):
    def sample(population: Union[Sequence[_T], Set[_T]], k: int, *, counts: Optional[Iterable[_T]] = ...) -> list[_T]: ...

Which I think erroneously implies that population and counts contain the same type of data.

If you change your population to [1, 2], the warning goes away, right?

2

u/Satiivas1 May 25 '22

Yes, thank you! I do need to use strings though in my code, so what is the best practice here? Just leave it be or silence the warning somehow?

2

u/Goobyalus May 25 '22

Yeah per https://www.jetbrains.com/help/pycharm/disabling-and-enabling-inspections.html#suppress-inspections

I think you want a comment like # noinspection (name of inspection) for that line

edit

# noinspection PyTypeChecker
a, b, c = sample(["A", "B"], counts=[1, 2], k=3)

The lightbulb gives you "suppress for a statement" that adds the comment

2

u/Satiivas1 May 25 '22

Thank you very much!