Why is Pycharm giving me a warning when using the max function with ints and floats vars as arguments

Viewed 278

I tried using the max fuction with a couple of int vars and a couple of float vars and i got a warning that int was expected as the correct type but the program is running fine. Did i do something wrong?

2 Answers

The problem is probably introduced by you specifically designating types - something that can be done in Python and is supported by PyCharm as well, of course, but isn't required as part of the language.

For example:

i: int = 1
a: float = 0.1
print(max(i, a))

This will show a PyCharm warning on a in print(max(i, a)).

And because PyCharm can infer the type, this will show the same warning:

i = 1
a = 0.1
print(max(i, a))

This on the other hand won't:

items = [1, 0.1]
print(max(items))

The reason for this is that PyCharm knows that the max() built-in function of Python will fail if incompatible types are passed into it. For example, max(1, '2') will cause a TypeError at runtime. That's why you get a warning if you pass in several arguments of varying types, PyCharm knows it may become a problem and will give the warning on the first argument that doesn't match the types of the preceding ones.

The reason that the list doesn't give you the same problem is that PyCharm only looks at the types of the call's arguments (a single list in this case), but doesn't have the information that the max() function will of course return the max of the elements in the list - it cannot determine this from how the max() function is defined in the libraries, even though it may be obvious to you and me.

You can avoid the error if you know it's not a problem by wrapping the arguments in an iterable like a list or tuple, by casting the integers to a float, or by explicitly ignoring the warning. Or by taking a look at your code and deciding if you really should be comparing ints and floats.

i: int = 1
a: float = 0.1
print(max([i, a]))
print(max(float(i), a))
# noinspection PyTypeChecker
print(max(i, a))

Note that the final 'solution' will be specific to PyCharm, the rest should give you good results in any editor.

The definition of max() assumes that all of the inputs will have the same type, which is okay but it causes pycharm to show a warning because you're mixing types. You can either

  1. Use an iterable instead (e.g. max((1.4, 11, 17))

or

  1. Suppress the warning, because it's pretty inconsequential. You can do this in the pycharm GUI
Related