Python Type Checking - Mypy

Mypy is a Python type checker that can help decrease errors and enhance the quality of code. These tools detect problems and provide warnings for possible errors by examining code flow and type annotations. 

Mypy :

Using Mypy can be done from the command line, as a stand-alone application, or as a component of an integrated linter in an editor or IDE. It is directly compatible because it is integrated into many editors and IDEs, including the Python extension for Visual Studio Code. When Mypy is run, it produces reports that emphasize consistency in the code by using the type information that is supplied.


Most of Mypy's code checks will not be performed if type annotations are absent from the code. This way, if you are gradually annotating a codebase, Mypy will not waste time checking code that you are not attempting to type-check. On the other hand, Mypy can be used to manually flag unannotated code in different levels of strictness to meet specific needs.


The "strict" option is useful for those starting with a new codebase and wanting an aggressively preemptive linting strategy to prevent any untyped code. On the other hand, more relaxed options, such as "disallow-untyped-defs" can prevent only untyped function definitions while allowing other untyped code, which is better for legacy codebases with fewer type definitions. Additionally, you can use inline comments like "# type: ignore" to prevent individual lines from being flagged

How to use Mypy, a static type checker for Python ?

def greet(name: str) -> str:

    return "Hello, " + name

def square(x: int) -> int:

    return x * x

def sum_list(numbers: list[int]) -> int:

    return sum(numbers)

def multiply(x: int, y: int) -> int:

    return x * y

# Call the functions with appropriate arguments

print(greet("Alice"))

print(square(5))

print(sum_list([1, 2, 3, 4, 5]))

print(multiply(3, 4))

Conclusion

run by mypy script.py

If there are any type errors or inconsistencies in your code, Mypy will report them. For example, if you were to call the greet function with an integer instead of a string, Mypy would detect this and raise a type error.


Comments