Search code examples
pythonpycharm

How to find the real type of an object in Python


How to find the real return type of a method in Python?

For example, I want to enable type hinting in Pycharm so that autocompletion works, but it is surprisingly not easy to find the exact object type even while in the debugger, and even after looking at the method bodies.

I expected type(someObject) to return something meaningful for objects but for most objects it returns <type 'instance'> which is hardly of any use.

For example, how can I find out what is the type of the response object returned by a call to urllib2.urlopen(url) so that I can mark the local variable using a Pycharm type hint to make autocompletion work?

I realize that everything is dynamic in Python, and that programming to an interface is not a widely used Python paradigm, but at least I would like to know how far can we go in terms of type inference, specifically for comfortable IDE support and 'lazy' programming with autocompletion.


Solution

  • As of Python 3.11 you can use reveal_type. For example in your case:

    reveal_type(urllib.request.urlopen(url))
    

    Prints in the REPL:

    Runtime type is 'HTTPResponse'
    

    Note that there is a backport of this feature from typing_extensions import reveal_type