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.match().group() fails despite if check #7503

Closed
jamesmcm opened this issue Sep 12, 2019 · 5 comments
Closed

re.match().group() fails despite if check #7503

jamesmcm opened this issue Sep 12, 2019 · 5 comments

Comments

@jamesmcm
Copy link

The following code fails the mypy check:

   df.loc[:, "col"] = df.loc[:, "col"].apply(
          lambda x: r.match(x).group(1) if r.match(x) else "0"
      )

With error:

error: Item "None" of "Optional[Match[str]]" has no attribute "group"

Despite the explicit check for r.match(x) that means .group() will never be called for None.

How can I work around this?

@srittau
Copy link
Contributor

srittau commented Sep 12, 2019

r.match() is called twice. mypy has no way of knowing that it returns the same value both times. The solution is to assign the result of r.match() to a variable and check that. Of course, this does not work in a lambda.

@msullivan
Copy link
Collaborator

In Python 3.8 you'll be able to use assignment expressions which should work with mypy and be more efficient, but until then try a cast or a type ignore.

@Bidek56
Copy link

Bidek56 commented Nov 21, 2019

mypy with Python 3.8 still has the same issue with the example code:

import re

advertisement = '10% discount'
discount = 0.0
if (mo := re.search(r'(\d+)% discount', advertisement)):
    discount = float(mo.group(1)) / 100.0

results in: error: Item "None" of "Optional[Match[str]]" has no attribute "group"
Any ideas would be appreciated. Thanks

@JelleZijlstra
Copy link
Member

This is #7316.

@zachliu

This comment has been minimized.

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

6 participants