2

I am trying to use a static type checking tool to check for wrong assignment to a variable. E.g., assign a string to an int variable.

I tried pytype and mypy. Both didn't give me any warnings.

class A: def __init__(self): self.x : int = None if __name__ == '__main__': a = A() a.x = 'abc' print(a.x) 

I expect a static type checking tool can give me a warning on the above line:

a.x = 'abc' 

Do I need to use some options or other helper tools to detect this kind of assignment statement?

1
  • Hey there. Which IDE environment are you using? Commented Aug 13, 2019 at 4:14

2 Answers 2

1

So when I copy your code and check it with mypy, I get the following result:

project\scratch.py:7: error: Incompatible types in assignment (expression has type "str", variable has type "int") 

I found this by executing mypy path/to/file.py.

Internally, within Visual Studio Code, selecting mypy as the linter underlines the a variable and overlays the mypy error.

So I'm getting the warning error codes displayed correctly; maybe your IDE isn't set up to handle them.

Note: executing python path/to/file.py will not display the mypy error, most likely to keep the typing 'soft' - so that the code will still execute, and typing is more to 'hint', rather than stop the code:

You can always use a Python interpreter to run your statically typed programs, even if they have type errors: $ python3 PROGRAM

From the documentation.

Sign up to request clarification or add additional context in comments.

Comments

0

I can't speak for other IDEs, but for Visual Studio Code (using Python 3.8.5)...

  1. Install pylance (Microsoft's Python language server extension)

  2. Add these two lines to settings.json:

    "python.languageServer":"Pylance", "python.analysis.typeCheckingMode" :"strict" 
  3. Note the following problems reported:

    (variable) x: None Cannot assign member "x" for type "A" Expression of type "None" cannot be assigned to member "x" of class "A" Type "None" cannot be assigned to type "int"Pylance (reportGeneralTypeIssues) [3, 14] (variable) x: Literal['abc'] Cannot assign member "x" for type "A" Expression of type "Literal['abc']" cannot be assigned to member "x" of class "A" "Literal['abc']" is incompatible with "int"Pylance (reportGeneralTypeIssues) [7, 7] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.