Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow error codes to be disabled inline #9989

Closed
allanlewis opened this issue Jan 28, 2021 · 5 comments
Closed

Allow error codes to be disabled inline #9989

allanlewis opened this issue Jan 28, 2021 · 5 comments
Labels

Comments

@allanlewis
Copy link

allanlewis commented Jan 28, 2021

Feature

I have some code like this:

flag = True
if flag:
    var: str = 'foo'
else:
    var: str = 'bar'

mypy complains about the redefinition of var:

foo.py:5: error: Name 'var' already defined on line 3

I would like mypy to not complain about this as long as the types are the same, or "compatible" by some definition.

Needless to say, the code within my if..else blocks is more complex than assigning a literal - in one case each branch has a try..except block, so I can't just use a ternary.

Pitch

The project I'm currently working on is a web app that uses feature flags. We therefore often have code blocks like the one above, and we would like mypy to not complain about this type of structure.

@JelleZijlstra
Copy link
Member

As a workaround, you can put var: str above the if-else.

@allanlewis
Copy link
Author

Thanks, @JelleZijlstra - that works for me.

@PeterJCLaw
Copy link
Contributor

PeterJCLaw commented Jan 31, 2021

You can also skip the annotation on the second assignment:

flag = True
if flag:
    var: str = 'foo'
else:
    var = 'bar'

@terencehonles
Copy link
Contributor

terencehonles commented Feb 3, 2021

This seems to be a dupe of #6233 unless you want to describe how error codes should be disabled inline.

If you are not aware you can use # type: ignore and run with --show-error-codes in order to be more specific `# type: ignore[error-code]. You should also read what disabling the type checking does https://mypy.readthedocs.io/en/stable/common_issues.html#spurious-errors-and-locally-silencing-the-checker

@AlexWaygood
Copy link
Member

This seems to be a dupe of #6233 unless you want to describe how error codes should be disabled inline.

I agree. I'm not sure exactly what's being proposed here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants