Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use reveal_type in mypy

I have read that I can reveal the type of variables by using a function called reveal_type, but I can't find how to use it or from where to import it.

like image 749
Yuval Pruss Avatar asked Jun 19 '17 08:06

Yuval Pruss


People also ask

How do I use type ignore?

You can use the form # type: ignore[<code>] to only ignore specific errors on the line. This way you are less likely to silence unexpected errors that are not safe to ignore, and this will also document what the purpose of the comment is.

How do you use type hints in Python?

Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.

Why should I use MYPY?

Mypy supports most Python features and idioms, and many large Python projects are using mypy successfully. Code that uses complex introspection or metaprogramming may be impractical to type check, but it should still be possible to use static typing in other parts of a codebase that are less dynamic.

What is MYPY Python?

“Mypy is an optional static type checker for Python that aims to combine the benefits of dynamic (or 'duck') typing and static typing. Mypy combines the expressive power and convenience of Python with a powerful type system and compile-time type checking.” A little background on the Mypy project.


1 Answers

I found out in the end how to use it: You should just put and use the reveal_type in the code, and run it with the mypy program. Then, it will log a message that look like this:

Revealed type is 'builtins.str*' 

From the mypy documentation:

reveal_type is only understood by mypy and doesn’t exist in Python, if you try to run your program. You’ll have to remove any reveal_type calls before you can run your code. reveal_type is always available and you don’t need to import it.

For more reading: here.

like image 78
Yuval Pruss Avatar answered Sep 30 '22 17:09

Yuval Pruss