Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pytest fails when using type hints for lists

If I provide exact typing:

def _get_options(self, property_options: list[dict]) -> list[OptionInput]:

pytest (v.6.2.5, Python 3.7.3) returns an error:

E TypeError: 'type' object is not subscriptable

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This happens for all types of lists: list[str], list[dict], etc.

but when I change the header to:

def _get_options(self, property_options: list) -> list:

It works. Same thing with literals:

  • fails: ACCOUNT_IDS: dict[str, str] = {"my_account": "123"}
  • works: ACCOUNT_IDS: dict = {"my_account": "123"}

Is there any option in the config that would allow such type hints like list[dict] etc? Thanks!

>Solution :

You’re looking for from __future__ import annotations; you can add this at the top of the module.

The caveat is this won’t work with direct assignment in Python versions earlier than 3.9, like CustomType = list[dict].


You can also read more on the PEP which introduces the __future__ import to Python 3.7+.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading