dr. Sybren
dr. Sybren

Reputation: 855

Type declaration for returning a class, gives error in PyCharm

I'm trying to use type annotations to improve my code clarity. The following code gives an error in PyCharm Community Edition 2016.3.3:

#!python
import typing


class MyClass:
    def __init__(self, name: str) -> None:
        self.name = name


backends: typing.Mapping[str, typing.Type[MyClass]] = {
    'local': MyClass
}


def get_backend(backend_name: str) -> typing.Type[MyClass]:
    return backends[backend_name]


def create_instance(name) -> MyClass:
    backend_cls = get_backend('local')

    # Here PyCharm highlights "backend_cls(name)" as in error:
    return backend_cls(name)


if __name__ == '__main__':
    instance = create_instance('hey')
    print(f'Name is: {instance.name}')

The error is higlighted by PyCharm at the backend_cls(name) expression, and reads 'Type' object is not callable. However, the code runs fine, and even mypy thisexample.py shows no error what so ever.

Is there a way to let PyCharm enhance its calm and understand that everything is fine? Or do I misunderstand something and is mypy giving a false positive?

This is using Python 3.6.0 and mypy-0.501 on Ubuntu 16.10.

Upvotes: 1

Views: 275

Answers (1)

Ernst
Ernst

Reputation: 572

typing.Type support will be added in PyCharm 2017.1, which will be released this week. You can get a pre-release version here: https://www.jetbrains.com/pycharm/nextversion/

Upvotes: 3

Related Questions