typing

How to properly annotate a ContextManager in PyCharm?

本秂侑毒 提交于 2020-06-23 06:44:25
问题 How can I annotate the yield type of a contextmanager in PyCharm so that it properly guesses the type of the value used in the with clauses - just as it guesses that the f created in with open(...) as f is a file? For example, I have a context manager like this: @contextlib.contextmanager def temp_borders_file(geometry: GEOSGeometry, name='borders.json'): with TemporaryDirectory() as temp_dir: borders_file = Path(dir) / name with borders_file.open('w+') as f: f.write(geometry.json) yield

How do I check if a value matches a type in python?

ε祈祈猫儿з 提交于 2020-06-21 09:49:51
问题 Let's say I have a python function whose single argument is a non-trivial type: from typing import List, Dict ArgType = List[Dict[str, int]] # this could be any non-trivial type def myfun(a: ArgType) -> None: ... ... and then I have a data structure that I have unpacked from a JSON source: import json data = json.loads(...) My question is: How can I check at runtime that data has the correct type to be used as an argument to myfun() before using it as an argument for myfun() ? if not

Can you specify variance in a Python type annotation?

怎甘沉沦 提交于 2020-06-16 07:07:46
问题 Can you spot the error in the code below? Mypy can't. from typing import Dict, Any def add_items(d: Dict[str, Any]) -> None: d['foo'] = 5 d: Dict[str, str] = {} add_items(d) for key, value in d.items(): print(f"{repr(key)}: {repr(value.lower())}") Python spots the error, of course, helpfully informing us that 'int' object has no attribute 'lower' . Too bad it can't tell us this until run time. As far as I can tell, mypy doesn't catch this error because it allows arguments to the d parameter

Can you specify variance in a Python type annotation?

a 夏天 提交于 2020-06-16 07:07:18
问题 Can you spot the error in the code below? Mypy can't. from typing import Dict, Any def add_items(d: Dict[str, Any]) -> None: d['foo'] = 5 d: Dict[str, str] = {} add_items(d) for key, value in d.items(): print(f"{repr(key)}: {repr(value.lower())}") Python spots the error, of course, helpfully informing us that 'int' object has no attribute 'lower' . Too bad it can't tell us this until run time. As far as I can tell, mypy doesn't catch this error because it allows arguments to the d parameter