manuel mourato manuel mourato - 2 months ago 16
Python Question

Why doesn't Pycharm show dictionary methods in this case?

I am trying to do a very simple service to collect and print data from a RESTfull API, in Python.
This is the code I have:

import requests
import json

response = requests.get("url")
data2 = response.json()
print type(data2)


Here is my issue: when I print data2 type, it tells me it's a dictionary, so when I do
data2.
(notice the dot) my IDE should give me a series of methods like len(), cmp(),str() for me to choose from. But nothing shows up.
The same thing happens to me using Atom.
To be clear, if I write
data2.len()
, it does not say it is an error, so it recognizes the methods. But it doesn't show them as a suggestion.

How should I solve this? Thank you so much.

Answer

PyCharm's inability to display the methods you mention indicate inability to infer the variable's type from the code alone. Which often indicates that the code might not be prepared to handle that variable's data properly in all cases (in many cases that means buggy code).

The fact that your code prints the type as dict in that particular execution doesn't mean it'll always be a dict (otherwise PyCharm would have been able to infer the type).

Making the code better prepared to deal with the variable's data in any situation - will make the type inferable, which will also allow PyCharm to fill in the data correctly.

For example, you could write your code like this:

response = requests.get("url")
data2 = response.json()
assert isinstance(data2, dict)
print type(data2)  # here data2's methods would be listed

or,

response = requests.get("url")
data2 = response.json()
if isinstance(data2, dict):
    print type(data2)  # here data2's methods would be listed
Comments