MitAnaLIT
MitAnaLIT

Reputation: 59

Warning: Expected type [Class Name], got 'Dict[str, int]' instead

I'm building a class with methods that take dictionaries as inputs but Pycharm displays a warning.

''' Expected type 'TestClass', got 'Dict[str, int]' instead less... (⌘F1) Inspection info: This inspection detects type errors in function call expressions. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Types of function parameters can be specified in docstrings or in Python 3 function annotations '''

class TestClass:
    def __getitem__(self, index):
        return self[index]

    def get_keys(self):
        return list(self.keys())


dict_input = {'a':123, 'b':456}
TestClass.get_keys(dict_input)

So I get the warning here:

TestClass.get_keys(dict_input)

What does this warning mean and what's the approach to fix it?

Upvotes: 1

Views: 8451

Answers (2)

Enthus3d
Enthus3d

Reputation: 2165

To specifically answer your question about the Pycharm warning, the warning that you're currently encountering is a known problem caused by Pycharm checking for types in the code, as PyCharm is confused because it expects a TestClass object but gets a dictionary object instead.

One way to deal with this is to disable that particular warning type, as paraphrased from here

  1. Go to Settings/Preferences
  2. In the sidebar, click Inspections
  3. Expand the Python tab
  4. Scroll down to Incorrect Call Arguments and uncheck it
  5. If that does not work, you can uncheck Type Checker instead.

Another more elegant method, although I'm unsure if it will resolve this PyCharm warning, is to add a decorator to your function, to let PyCharm know that your return type is a dict. The tutorial is here, but your docstring will probably include this:

"""
:rtype: Dict [str,int]
"""

As an aside, you should probably use a @staticmethod decorator on your get_keys function, as mentioned by Jean, since it's taking in an object and returning its keys (and we don't want that object to access our TestClass data in the process).

Upvotes: 0

Jean Hominal
Jean Hominal

Reputation: 16796

A method such as the one you wrote is called an "instance method".

self, the receiver, should be an instance of TestClass (otherwise, many things could work wrong, such as super).

You could define get_keys as a static method, or use a simple function (without putting it in a class).

class TestClass:
    @staticmethod
    def get_keys(s):
        return list(s.keys())

You may want to read the Python documentation about classes for more details.

Upvotes: 3

Related Questions