Skip to content

[ArrowStringArray] TYP: add annotations to str.replace #41603

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

Merged
merged 1 commit into from
May 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 19 additions & 12 deletions pandas/core/strings/accessor.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from __future__ import annotations

import codecs
from collections.abc import Callable # noqa: PDF001
Copy link
Member Author

@simonjayhawkins simonjayhawkins May 21, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should disable the custom pandas flake rule.

we should be importing Callable from collections.abc
https://docs.python.org/3/library/typing.html#callable

from functools import wraps
import re
from typing import (
TYPE_CHECKING,
Hashable,
Pattern,
Copy link
Member Author

@simonjayhawkins simonjayhawkins May 21, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should not be using Pattern from typing.

https://www.python.org/dev/peps/pep-0585/

Importing those from typing is deprecated

)
import warnings

Expand Down Expand Up @@ -1217,7 +1217,15 @@ def fullmatch(self, pat, case=True, flags=0, na=None):
return self._wrap_result(result, fill_value=na, returns_string=False)

@forbid_nonstring_types(["bytes"])
def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None):
def replace(
self,
pat: str | re.Pattern,
repl: str | Callable,
n: int = -1,
case: bool | None = None,
flags: int = 0,
regex: bool | None = None,
):
r"""
Replace each occurrence of pattern/regex in the Series/Index.

Expand Down Expand Up @@ -1358,14 +1366,10 @@ def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None):

is_compiled_re = is_re(pat)
if regex:
if is_compiled_re:
if (case is not None) or (flags != 0):
raise ValueError(
"case and flags cannot be set when pat is a compiled regex"
)
elif case is None:
# not a compiled regex, set default case
case = True
if is_compiled_re and (case is not None or flags != 0):
raise ValueError(
"case and flags cannot be set when pat is a compiled regex"
)

elif is_compiled_re:
raise ValueError(
Expand All @@ -1374,6 +1378,9 @@ def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None):
elif callable(repl):
raise ValueError("Cannot use a callable replacement when regex=False")

if case is None:
case = True
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed so that case is not optional on array methods. all validation is done here.


result = self._data.array._str_replace(
pat, repl, n=n, case=case, flags=flags, regex=regex
)
Expand Down Expand Up @@ -3044,14 +3051,14 @@ def _result_dtype(arr):
return object


def _get_single_group_name(regex: Pattern) -> Hashable:
def _get_single_group_name(regex: re.Pattern) -> Hashable:
if regex.groupindex:
return next(iter(regex.groupindex))
else:
return None


def _get_group_names(regex: Pattern) -> list[Hashable]:
def _get_group_names(regex: re.Pattern) -> list[Hashable]:
"""
Get named groups from compiled regex.

Expand Down
15 changes: 12 additions & 3 deletions pandas/core/strings/base.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from __future__ import annotations

import abc
from typing import Pattern
from collections.abc import Callable # noqa: PDF001
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

another reason to disable the flake rule. abc is imported.

import re

import numpy as np

Expand Down Expand Up @@ -51,7 +52,15 @@ def _str_endswith(self, pat, na=None):
pass

@abc.abstractmethod
def _str_replace(self, pat, repl, n=-1, case=None, flags=0, regex=True):
def _str_replace(
self,
pat: str | re.Pattern,
repl: str | Callable,
n: int = -1,
case: bool = True,
flags: int = 0,
regex: bool = True,
):
pass

@abc.abstractmethod
Expand All @@ -67,7 +76,7 @@ def _str_match(
@abc.abstractmethod
def _str_fullmatch(
self,
pat: str | Pattern,
pat: str | re.Pattern,
case: bool = True,
flags: int = 0,
na: Scalar = np.nan,
Expand Down
27 changes: 16 additions & 11 deletions pandas/core/strings/object_array.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from __future__ import annotations

from collections.abc import Callable # noqa: PDF001
import re
import textwrap
from typing import Pattern
import unicodedata

import numpy as np
Expand All @@ -15,10 +15,7 @@
Scalar,
)

from pandas.core.dtypes.common import (
is_re,
is_scalar,
)
from pandas.core.dtypes.common import is_scalar
from pandas.core.dtypes.missing import isna

from pandas.core.strings.base import BaseStringArrayMethods
Expand Down Expand Up @@ -135,15 +132,23 @@ def _str_endswith(self, pat, na=None):
f = lambda x: x.endswith(pat)
return self._str_map(f, na_value=na, dtype=np.dtype(bool))

def _str_replace(self, pat, repl, n=-1, case: bool = True, flags=0, regex=True):
is_compiled_re = is_re(pat)

def _str_replace(
self,
pat: str | re.Pattern,
repl: str | Callable,
n: int = -1,
case: bool = True,
flags: int = 0,
regex: bool = True,
):
if case is False:
# add case flag, if provided
flags |= re.IGNORECASE

if regex and (is_compiled_re or len(pat) > 1 or flags or callable(repl)):
if not is_compiled_re:
if regex and (
isinstance(pat, re.Pattern) or len(pat) > 1 or flags or callable(repl)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mypy cannot narrow types with is_compiled_re

):
if not isinstance(pat, re.Pattern):
pat = re.compile(pat, flags=flags)

n = n if n >= 0 else 0
Expand Down Expand Up @@ -195,7 +200,7 @@ def _str_match(

def _str_fullmatch(
self,
pat: str | Pattern,
pat: str | re.Pattern,
case: bool = True,
flags: int = 0,
na: Scalar = None,
Expand Down