1
votes

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?

2
Your code doesn't make much sense. get_keys is an instance method, you're supposed to call it on an instance of the class. But there is nowhere in your code that accepts a dict, so it's my clear where the keys are supposed to be coming from. - Daniel Roseman
get_key() is a method - it would normally be called on an instance of TestClass, NOT Testclass itself. It would take no parameters other than the implicit self passed to all methods, so I have no idea what that dict you're passing is supposed to do. - jasonharper

2 Answers

3
votes

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.

-1
votes

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).