[Python-ideas] Better Type Hinting

Andrew Barnert abarnert at yahoo.com
Fri Jun 5 10:38:32 CEST 2015

On Jun 5, 2015, at 00:21, Thomas Güttler <guettliml at thomas-guettler.de> wrote:
>> Am 05.06.2015 um 08:19 schrieb Stephen Hansen:
>>> On Thu, Jun 4, 2015, at 11:01 PM, Andrew Barnert via Python-ideas wrote:
>>> On Jun 4, 2015, at 22:36, Thomas Güttler <guettliml at thomas-guettler.de>
>>> wrote:
>>>> It would be great to have better type hinting in IDEs.
>>> Is PEP 484 not sufficient for this purpose?
>> It's really not.
>> For one thing, PEP 484 isn't going to result in the standard library
>> being hinted all up (though I assume someone may make stubs). But
>> really, the specific issue that the OP is running into is because of the
>> signature of logging.warn --  msg, *args, **kwargs.
> I am using logger.warn() not logging.warn().
> The question is: How to know which kind of duck "logger" is?

That is _exactly_ what PEP 484 addresses.

If `logging.getLogger` is annotated or stubbed to specify that it returns a `logging.Logger` (which it will be), then a static type checker (whether MyPy or a competing checker or custom code in the IDE) can trivially infer that `logger` is a `logging.Logger`.

If you needed to annotate exactly which subclass of `Logger` was returned (unlikely, but not impossible--maybe you conditionally do a `logging.set_logger_class`, and _you_ know what the type is going to be even though a static analyzer can't infer it, and your subclass has a different API than the base class), then you can use a variable type comment.

As Stephen Hansen argues, that may still not solve all of your problems. But it definitely does solve the "how to know which kind of duck" problem you're asking about.

> "logger" was created by "logging.getLogger(__name__)"
> It is not the question how to implement better guessing in the IDE.
> The basics needs to be solved. Everything else is "toilet paper programming"

Have you read PEP 484? What part of the basics do you think it's not solving? Because it sounds an awful lot like you're just demanding that someone write something exactly like PEP 484.

More information about the Python-ideas mailing list