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

re's Match does not support indexing: "Value of type "Optional[Match[str]]" is not indexable" #3010

Closed
blueyed opened this issue May 26, 2019 · 5 comments

Comments

@blueyed
Copy link
Contributor

blueyed commented May 26, 2019

The following is valid, but mypy complains about it:

import re

m = re.search(".", "foo")
print(m[0])

t-mypy.py:4: error: Value of type "Optional[Match[str]]" is not indexable

Seems to be similar to #2751 (#2753).

mypy 0.710+dev.5f08ccf029aa3046b15e1afc60743ba692e4758d.dirty (dirty due to using latest typshed master (53500c8)

@JelleZijlstra
Copy link
Member

That's because of the Optional part. It's telling you that if there is no match, this code will break. Mypy will show no errors if you first check that m is not None.

@blueyed
Copy link
Contributor Author

blueyed commented May 26, 2019

@JelleZijlstra
Thanks - figured this out with something else already (forgot to report back here).
assert m also works.

@dongweiming
Copy link

dongweiming commented Jan 7, 2020

@JelleZijlstra if use Assignment expressions will throw an error:

❯ cat a.py 
import re

if (m := re.search(".", "foo")):
    print(m[0])

❯ mypy a.py 
a.py:4: error: Value of type "Optional[Match[str]]" is not indexable
        print(m[0])
              ^
Found 1 error in 1 file (checked 1 source file)

@srittau
Copy link
Collaborator

srittau commented Jan 7, 2020

This is a mypy problem:

from typing import Optional

def foo() -> Optional[str]:
    pass

x = foo()
if x:
    x.lower()  # no error
    
if (y := foo()):
    y.lower()  # error: Item "None" of "Optional[str]" has no attribute "lower"

(mypy 0.761 with Python 3.8.0)

@JelleZijlstra
Copy link
Member

Yes, python/mypy#7316.

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

No branches or pull requests

4 participants