Skip to content

future annotations #40785

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
Apr 13, 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
35 changes: 16 additions & 19 deletions pandas/_config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@

"""

from __future__ import annotations

from collections import namedtuple
from contextlib import (
ContextDecorator,
Expand All @@ -57,12 +59,7 @@
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
cast,
)
import warnings
Expand All @@ -73,16 +70,16 @@
RegisteredOption = namedtuple("RegisteredOption", "key defval doc validator cb")

# holds deprecated option metadata
_deprecated_options: Dict[str, DeprecatedOption] = {}
_deprecated_options: dict[str, DeprecatedOption] = {}

# holds registered option metadata
_registered_options: Dict[str, RegisteredOption] = {}
_registered_options: dict[str, RegisteredOption] = {}

# holds the current values for registered options
_global_config: Dict[str, Any] = {}
_global_config: dict[str, Any] = {}

# keys which have a special meaning
_reserved_keys: List[str] = ["all"]
_reserved_keys: list[str] = ["all"]


class OptionError(AttributeError, KeyError):
Expand Down Expand Up @@ -194,7 +191,7 @@ def get_default_val(pat: str):
class DictWrapper:
""" provide attribute-style access to a nested dict"""

def __init__(self, d: Dict[str, Any], prefix: str = ""):
def __init__(self, d: dict[str, Any], prefix: str = ""):
object.__setattr__(self, "d", d)
object.__setattr__(self, "prefix", prefix)

Expand Down Expand Up @@ -428,8 +425,8 @@ def register_option(
key: str,
defval: object,
doc: str = "",
validator: Optional[Callable[[Any], Any]] = None,
cb: Optional[Callable[[str], Any]] = None,
validator: Callable[[Any], Any] | None = None,
cb: Callable[[str], Any] | None = None,
) -> None:
"""
Register an option in the package-wide pandas config object
Expand Down Expand Up @@ -500,7 +497,7 @@ def register_option(


def deprecate_option(
key: str, msg: Optional[str] = None, rkey: Optional[str] = None, removal_ver=None
key: str, msg: str | None = None, rkey: str | None = None, removal_ver=None
) -> None:
"""
Mark option `key` as deprecated, if code attempts to access this option,
Expand Down Expand Up @@ -547,7 +544,7 @@ def deprecate_option(
# functions internal to the module


def _select_options(pat: str) -> List[str]:
def _select_options(pat: str) -> list[str]:
"""
returns a list of keys matching `pat`

Expand All @@ -565,7 +562,7 @@ def _select_options(pat: str) -> List[str]:
return [k for k in keys if re.search(pat, k, re.I)]


def _get_root(key: str) -> Tuple[Dict[str, Any], str]:
def _get_root(key: str) -> tuple[dict[str, Any], str]:
path = key.split(".")
cursor = _global_config
for p in path[:-1]:
Expand Down Expand Up @@ -674,7 +671,7 @@ def pp_options_list(keys: Iterable[str], width=80, _print: bool = False):
from itertools import groupby
from textwrap import wrap

def pp(name: str, ks: Iterable[str]) -> List[str]:
def pp(name: str, ks: Iterable[str]) -> list[str]:
pfx = "- " + name + ".[" if name else ""
ls = wrap(
", ".join(ks),
Expand All @@ -687,7 +684,7 @@ def pp(name: str, ks: Iterable[str]) -> List[str]:
ls[-1] = ls[-1] + "]"
return ls

ls: List[str] = []
ls: list[str] = []
singles = [x for x in sorted(keys) if x.find(".") < 0]
if singles:
ls += pp("", singles)
Expand Down Expand Up @@ -760,7 +757,7 @@ def inner(key: str, *args, **kwds):
# arg in register_option


def is_type_factory(_type: Type[Any]) -> Callable[[Any], None]:
def is_type_factory(_type: type[Any]) -> Callable[[Any], None]:
"""

Parameters
Expand Down Expand Up @@ -826,7 +823,7 @@ def inner(x) -> None:
return inner


def is_nonnegative_int(value: Optional[int]) -> None:
def is_nonnegative_int(value: int | None) -> None:
"""
Verify that value is None or a positive int.

Expand Down
5 changes: 3 additions & 2 deletions pandas/_config/display.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@
Unopinionated display configuration.
"""

from __future__ import annotations

import locale
import sys
from typing import Optional

from pandas._config import config as cf

# -----------------------------------------------------------------------------
# Global formatting options
_initial_defencoding: Optional[str] = None
_initial_defencoding: str | None = None


def detect_console_encoding() -> str:
Expand Down
14 changes: 6 additions & 8 deletions pandas/_testing/_io.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from __future__ import annotations

import bz2
from functools import wraps
import gzip
from typing import (
Any,
Callable,
Optional,
Tuple,
)
import zipfile

Expand Down Expand Up @@ -272,9 +272,7 @@ def can_connect(url, error_classes=None):
# File-IO


def round_trip_pickle(
obj: Any, path: Optional[FilePathOrBuffer] = None
) -> FrameOrSeries:
def round_trip_pickle(obj: Any, path: FilePathOrBuffer | None = None) -> FrameOrSeries:
"""
Pickle an object and then read it again.

Expand All @@ -298,7 +296,7 @@ def round_trip_pickle(
return pd.read_pickle(temp_path)


def round_trip_pathlib(writer, reader, path: Optional[str] = None):
def round_trip_pathlib(writer, reader, path: str | None = None):
"""
Write an object to file specified by a pathlib.Path and read it back

Expand Down Expand Up @@ -327,7 +325,7 @@ def round_trip_pathlib(writer, reader, path: Optional[str] = None):
return obj


def round_trip_localpath(writer, reader, path: Optional[str] = None):
def round_trip_localpath(writer, reader, path: str | None = None):
"""
Write an object to file specified by a py.path LocalPath and read it back.

Expand Down Expand Up @@ -375,7 +373,7 @@ def write_to_compressed(compression, path, data, dest="test"):
------
ValueError : An invalid compression value was passed in.
"""
args: Tuple[Any, ...] = (data,)
args: tuple[Any, ...] = (data,)
mode = "wb"
method = "write"
compress_method: Callable
Expand Down
16 changes: 8 additions & 8 deletions pandas/_testing/_warnings.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
from __future__ import annotations

from contextlib import contextmanager
import re
from typing import (
Optional,
Sequence,
Type,
Union,
cast,
)
import warnings


@contextmanager
def assert_produces_warning(
expected_warning: Optional[Union[Type[Warning], bool]] = Warning,
expected_warning: type[Warning] | bool | None = Warning,
filter_level="always",
check_stacklevel: bool = True,
raise_on_extra_warnings: bool = True,
match: Optional[str] = None,
match: str | None = None,
):
"""
Context manager for running code expected to either raise a specific
Expand Down Expand Up @@ -99,8 +99,8 @@ class for all warnings. To check that no warning is returned,
def _assert_caught_expected_warning(
*,
caught_warnings: Sequence[warnings.WarningMessage],
expected_warning: Type[Warning],
match: Optional[str],
expected_warning: type[Warning],
match: str | None,
check_stacklevel: bool,
) -> None:
"""Assert that there was the expected warning among the caught warnings."""
Expand Down Expand Up @@ -135,7 +135,7 @@ def _assert_caught_expected_warning(
def _assert_caught_no_extra_warnings(
*,
caught_warnings: Sequence[warnings.WarningMessage],
expected_warning: Optional[Union[Type[Warning], bool]],
expected_warning: type[Warning] | bool | None,
) -> None:
"""Assert that no extra warnings apart from the expected ones are caught."""
extra_warnings = []
Expand All @@ -157,7 +157,7 @@ def _assert_caught_no_extra_warnings(

def _is_unexpected_warning(
actual_warning: warnings.WarningMessage,
expected_warning: Optional[Union[Type[Warning], bool]],
expected_warning: type[Warning] | bool | None,
) -> bool:
"""Check if the actual warning issued is unexpected."""
if actual_warning and not expected_warning:
Expand Down
19 changes: 9 additions & 10 deletions pandas/_testing/asserters.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from typing import (
Union,
cast,
)
from __future__ import annotations

from typing import cast
import warnings

import numpy as np
Expand Down Expand Up @@ -56,8 +55,8 @@
def assert_almost_equal(
left,
right,
check_dtype: Union[bool, str] = "equiv",
check_less_precise: Union[bool, int, NoDefault] = no_default,
check_dtype: bool | str = "equiv",
check_less_precise: bool | int | NoDefault = no_default,
rtol: float = 1.0e-5,
atol: float = 1.0e-8,
**kwargs,
Expand Down Expand Up @@ -169,7 +168,7 @@ def assert_almost_equal(
)


def _get_tol_from_less_precise(check_less_precise: Union[bool, int]) -> float:
def _get_tol_from_less_precise(check_less_precise: bool | int) -> float:
"""
Return the tolerance equivalent to the deprecated `check_less_precise`
parameter.
Expand Down Expand Up @@ -247,9 +246,9 @@ def assert_dict_equal(left, right, compare_keys: bool = True):
def assert_index_equal(
left: Index,
right: Index,
exact: Union[bool, str] = "equiv",
exact: bool | str = "equiv",
check_names: bool = True,
check_less_precise: Union[bool, int, NoDefault] = no_default,
check_less_precise: bool | int | NoDefault = no_default,
check_exact: bool = True,
check_categorical: bool = True,
check_order: bool = True,
Expand Down Expand Up @@ -429,7 +428,7 @@ def _get_ilevel_values(index, level):
assert_categorical_equal(left._values, right._values, obj=f"{obj} category")


def assert_class_equal(left, right, exact: Union[bool, str] = True, obj="Input"):
def assert_class_equal(left, right, exact: bool | str = True, obj="Input"):
"""
Checks classes are equal.
"""
Expand Down
5 changes: 3 additions & 2 deletions pandas/_testing/contexts.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from contextlib import contextmanager
import os
from pathlib import Path
Expand All @@ -8,7 +10,6 @@
from typing import (
IO,
Any,
Union,
)

import numpy as np
Expand Down Expand Up @@ -111,7 +112,7 @@ def ensure_clean(filename=None, return_filelike: bool = False, **kwargs: Any):

path.touch()

handle_or_str: Union[str, IO] = str(path)
handle_or_str: str | IO = str(path)
if return_filelike:
kwargs.setdefault("mode", "w+b")
handle_or_str = open(path, **kwargs)
Expand Down
5 changes: 3 additions & 2 deletions pandas/compat/_optional.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from __future__ import annotations

import distutils.version
import importlib
import sys
import types
from typing import Optional
import warnings

# Update install.rst when updating versions!
Expand Down Expand Up @@ -63,7 +64,7 @@ def import_optional_dependency(
name: str,
extra: str = "",
errors: str = "raise",
min_version: Optional[str] = None,
min_version: str | None = None,
):
"""
Import an optional dependency.
Expand Down
17 changes: 7 additions & 10 deletions pandas/core/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,30 @@
that can be mixed into or pinned onto other pandas classes.

"""
from typing import (
FrozenSet,
List,
Set,
)
from __future__ import annotations

import warnings

from pandas.util._decorators import doc


class DirNamesMixin:
_accessors: Set[str] = set()
_hidden_attrs: FrozenSet[str] = frozenset()
_accessors: set[str] = set()
_hidden_attrs: frozenset[str] = frozenset()

def _dir_deletions(self) -> Set[str]:
def _dir_deletions(self) -> set[str]:
"""
Delete unwanted __dir__ for this object.
"""
return self._accessors | self._hidden_attrs

def _dir_additions(self) -> Set[str]:
def _dir_additions(self) -> set[str]:
"""
Add additional __dir__ for this object.
"""
return {accessor for accessor in self._accessors if hasattr(self, accessor)}

def __dir__(self) -> List[str]:
def __dir__(self) -> list[str]:
"""
Provide method name lookup and completion.

Expand Down
Loading