Skip to content

Invalid type after function with side-effect on instance variable? #8157

Answered by erictraut
franjurinec asked this question in Q&A
Discussion options

You must be logged in to vote

Static type checkers narrow the type of expressions locally within an execution context (e.g. within a function body or within the module's global scope). They do not track side effects by other execution contexts. In your example, the set_x method has a side effect that happens to change the value of the local expression t.x. You'll see the same behavior in other Python type checkers like mypy as well as type checkers in other languages like TypeScript.

In general, it's best to avoid writing methods that have side effects like this, especially when they potentially affect subsequent code in the caller's execution context.

I don't know enough about your real use case to suggest a concrete…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by franjurinec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants