Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a "with" statement support type hinting?

Can you define the type hint for a variable defined with the with syntax?

with example() as x:     print(x) 

I would like to type hint the above to say that x is a str (as an example).

The only work around that I've found is to use an intermediate variable, but this feels hacky.

with example() as x:     y: str = x     print(y) 

I can't find an example in the typing documentation.

like image 859
Reactgular Avatar asked Feb 11 '20 13:02

Reactgular


People also ask

What version of Python supports type hints?

Type hinting is a formal solution to statically indicate the type of a value within your Python code. It was specified in PEP 484 and introduced in Python 3.5. The name: str syntax indicates the name argument should be of type str . The -> syntax indicates the greet() function will return a string.

What are reasons for using type hinting?

Introduction to Type Hints As the code base gets larger, type hints can help to debug and prevent some dumb mistakes. If you're using an IDE like PyCharm, you'll get a warning message whenever you've used the wrong data type, provided you're using type hints.

How does Python type hinting work?

Introduction to Python type hints It means that you need to declare types of variables, parameters, and return values of a function upfront. The predefined types allow the compilers to check the code before compiling and running the program.

Does Python enforce type hints?

The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc. This module provides runtime support for type hints. The most fundamental support consists of the types Any , Union , Callable , TypeVar , and Generic .


Video Answer


2 Answers

PEP 526, which has been implemented in Python 3.6, allows you to annotate variables. You can use, for example,

x: str with example() as x:     [...] 

or

with example() as x:     x: str     [...] 
like image 193
pschill Avatar answered Oct 04 '22 10:10

pschill


Usually type annotations are placed at the API boundaries. In this case the type should be inferred from example.__enter__. In case that function doesn't declare any types, the solution is to create a corresponding stub file in order to help the type checker infer that type.

Specifically this means creating a .pyi file with the same stem as the module from which Example was imported. Then the following code can be added:

class Example:     def __enter__(self) -> str: ...     def __exit__(self, exc_type, exc_value, exc_traceback) -> None: ... 
like image 35
a_guest Avatar answered Oct 04 '22 10:10

a_guest