Skip to content

Commit

Permalink
TYP: use from __future__ import annotations more (pandas-dev#41892)
Browse files Browse the repository at this point in the history
  • Loading branch information
simonjayhawkins authored Jun 9, 2021
1 parent 384f414 commit ce3bac9
Show file tree
Hide file tree
Showing 9 changed files with 82 additions and 104 deletions.
50 changes: 24 additions & 26 deletions pandas/io/json/_json.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from abc import (
ABC,
abstractmethod,
Expand All @@ -10,10 +12,6 @@
Any,
Callable,
Mapping,
Optional,
Tuple,
Type,
Union,
)

import numpy as np
Expand Down Expand Up @@ -78,12 +76,12 @@
def to_json(
path_or_buf,
obj: NDFrame,
orient: Optional[str] = None,
orient: str | None = None,
date_format: str = "epoch",
double_precision: int = 10,
force_ascii: bool = True,
date_unit: str = "ms",
default_handler: Optional[Callable[[Any], JSONSerializable]] = None,
default_handler: Callable[[Any], JSONSerializable] | None = None,
lines: bool = False,
compression: CompressionOptions = "infer",
index: bool = True,
Expand All @@ -102,7 +100,7 @@ def to_json(
if orient == "table" and isinstance(obj, Series):
obj = obj.to_frame(name=obj.name or "values")

writer: Type[Writer]
writer: type[Writer]
if orient == "table" and isinstance(obj, DataFrame):
writer = JSONTableWriter
elif isinstance(obj, Series):
Expand Down Expand Up @@ -143,13 +141,13 @@ class Writer(ABC):
def __init__(
self,
obj,
orient: Optional[str],
orient: str | None,
date_format: str,
double_precision: int,
ensure_ascii: bool,
date_unit: str,
index: bool,
default_handler: Optional[Callable[[Any], JSONSerializable]] = None,
default_handler: Callable[[Any], JSONSerializable] | None = None,
indent: int = 0,
):
self.obj = obj
Expand Down Expand Up @@ -187,7 +185,7 @@ def write(self):

@property
@abstractmethod
def obj_to_write(self) -> Union[NDFrame, Mapping[IndexLabel, Any]]:
def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
"""Object to write in JSON format."""
pass

Expand All @@ -196,7 +194,7 @@ class SeriesWriter(Writer):
_default_orient = "index"

@property
def obj_to_write(self) -> Union[NDFrame, Mapping[IndexLabel, Any]]:
def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
if not self.index and self.orient == "split":
return {"name": self.obj.name, "data": self.obj.values}
else:
Expand All @@ -211,7 +209,7 @@ class FrameWriter(Writer):
_default_orient = "columns"

@property
def obj_to_write(self) -> Union[NDFrame, Mapping[IndexLabel, Any]]:
def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
if not self.index and self.orient == "split":
obj_to_write = self.obj.to_dict(orient="split")
del obj_to_write["index"]
Expand Down Expand Up @@ -243,13 +241,13 @@ class JSONTableWriter(FrameWriter):
def __init__(
self,
obj,
orient: Optional[str],
orient: str | None,
date_format: str,
double_precision: int,
ensure_ascii: bool,
date_unit: str,
index: bool,
default_handler: Optional[Callable[[Any], JSONSerializable]] = None,
default_handler: Callable[[Any], JSONSerializable] | None = None,
indent: int = 0,
):
"""
Expand Down Expand Up @@ -313,7 +311,7 @@ def __init__(
self.index = index

@property
def obj_to_write(self) -> Union[NDFrame, Mapping[IndexLabel, Any]]:
def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
return {"schema": self.schema, "data": self.obj}


Expand All @@ -326,19 +324,19 @@ def read_json(
path_or_buf=None,
orient=None,
typ="frame",
dtype: Optional[DtypeArg] = None,
dtype: DtypeArg | None = None,
convert_axes=None,
convert_dates=True,
keep_default_dates: bool = True,
numpy: bool = False,
precise_float: bool = False,
date_unit=None,
encoding=None,
encoding_errors: Optional[str] = "strict",
encoding_errors: str | None = "strict",
lines: bool = False,
chunksize: Optional[int] = None,
chunksize: int | None = None,
compression: CompressionOptions = "infer",
nrows: Optional[int] = None,
nrows: int | None = None,
storage_options: StorageOptions = None,
):
"""
Expand Down Expand Up @@ -639,11 +637,11 @@ def __init__(
date_unit,
encoding,
lines: bool,
chunksize: Optional[int],
chunksize: int | None,
compression: CompressionOptions,
nrows: Optional[int],
nrows: int | None,
storage_options: StorageOptions = None,
encoding_errors: Optional[str] = "strict",
encoding_errors: str | None = "strict",
):

self.orient = orient
Expand All @@ -663,7 +661,7 @@ def __init__(
self.nrows_seen = 0
self.nrows = nrows
self.encoding_errors = encoding_errors
self.handles: Optional[IOHandles] = None
self.handles: IOHandles | None = None

if self.chunksize is not None:
self.chunksize = validate_integer("chunksize", self.chunksize, 1)
Expand Down Expand Up @@ -816,7 +814,7 @@ def __exit__(self, exc_type, exc_value, traceback):


class Parser:
_split_keys: Tuple[str, ...]
_split_keys: tuple[str, ...]
_default_orient: str

_STAMP_UNITS = ("s", "ms", "us", "ns")
Expand All @@ -831,7 +829,7 @@ def __init__(
self,
json,
orient,
dtype: Optional[DtypeArg] = None,
dtype: DtypeArg | None = None,
convert_axes=True,
convert_dates=True,
keep_default_dates=False,
Expand Down Expand Up @@ -865,7 +863,7 @@ def __init__(
self.convert_dates = convert_dates
self.date_unit = date_unit
self.keep_default_dates = keep_default_dates
self.obj: Optional[FrameOrSeriesUnion] = None
self.obj: FrameOrSeriesUnion | None = None

def check_keys_split(self, decoded):
"""
Expand Down
22 changes: 9 additions & 13 deletions pandas/plotting/_matplotlib/converter.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import contextlib
import datetime as pydt
from datetime import (
Expand All @@ -6,13 +8,7 @@
tzinfo,
)
import functools
from typing import (
Any,
Dict,
List,
Optional,
Tuple,
)
from typing import Any

from dateutil.relativedelta import relativedelta
import matplotlib.dates as dates
Expand Down Expand Up @@ -169,7 +165,7 @@ def convert(value, unit, axis):
return value

@staticmethod
def axisinfo(unit, axis) -> Optional[units.AxisInfo]:
def axisinfo(unit, axis) -> units.AxisInfo | None:
if unit != "time":
return None

Expand Down Expand Up @@ -319,7 +315,7 @@ def try_parse(values):
return values

@staticmethod
def axisinfo(unit: Optional[tzinfo], axis) -> units.AxisInfo:
def axisinfo(unit: tzinfo | None, axis) -> units.AxisInfo:
"""
Return the :class:`~matplotlib.units.AxisInfo` for *unit*.
Expand Down Expand Up @@ -447,7 +443,7 @@ def autoscale(self):
return self.nonsingular(vmin, vmax)


def _from_ordinal(x, tz: Optional[tzinfo] = None) -> datetime:
def _from_ordinal(x, tz: tzinfo | None = None) -> datetime:
ix = int(x)
dt = datetime.fromordinal(ix)
remainder = float(x) - ix
Expand Down Expand Up @@ -476,7 +472,7 @@ def _from_ordinal(x, tz: Optional[tzinfo] = None) -> datetime:
# -------------------------------------------------------------------------


def _get_default_annual_spacing(nyears) -> Tuple[int, int]:
def _get_default_annual_spacing(nyears) -> tuple[int, int]:
"""
Returns a default spacing between consecutive ticks for annual data.
"""
Expand Down Expand Up @@ -1027,8 +1023,8 @@ def __init__(
freq = to_offset(freq)
self.format = None
self.freq = freq
self.locs: List[Any] = [] # unused, for matplotlib compat
self.formatdict: Optional[Dict[Any, Any]] = None
self.locs: list[Any] = [] # unused, for matplotlib compat
self.formatdict: dict[Any, Any] | None = None
self.isminor = minor_locator
self.isdynamic = dynamic_mode
self.offset = 0
Expand Down
13 changes: 5 additions & 8 deletions pandas/tests/extension/base/ops.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
from typing import (
Optional,
Type,
)
from __future__ import annotations

import pytest

Expand Down Expand Up @@ -67,10 +64,10 @@ class BaseArithmeticOpsTests(BaseOpsUtil):
* divmod_exc = TypeError
"""

series_scalar_exc: Optional[Type[TypeError]] = TypeError
frame_scalar_exc: Optional[Type[TypeError]] = TypeError
series_array_exc: Optional[Type[TypeError]] = TypeError
divmod_exc: Optional[Type[TypeError]] = TypeError
series_scalar_exc: type[TypeError] | None = TypeError
frame_scalar_exc: type[TypeError] | None = TypeError
series_array_exc: type[TypeError] | None = TypeError
divmod_exc: type[TypeError] | None = TypeError

def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
# series & scalar
Expand Down
10 changes: 4 additions & 6 deletions pandas/tests/io/parser/conftest.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from __future__ import annotations

import os
from typing import (
List,
Optional,
)

import pytest

Expand All @@ -13,9 +11,9 @@


class BaseParser:
engine: Optional[str] = None
engine: str | None = None
low_memory = True
float_precision_choices: List[Optional[str]] = []
float_precision_choices: list[str | None] = []

def update_kwargs(self, kwargs):
kwargs = kwargs.copy()
Expand Down
8 changes: 3 additions & 5 deletions pandas/tests/tseries/offsets/common.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
"""
Assertion helpers and base class for offsets tests
"""
from __future__ import annotations

from datetime import datetime
from typing import (
Optional,
Type,
)

from dateutil.tz.tz import tzlocal
import pytest
Expand Down Expand Up @@ -61,7 +59,7 @@ class WeekDay:


class Base:
_offset: Optional[Type[DateOffset]] = None
_offset: type[DateOffset] | None = None
d = Timestamp(datetime(2008, 1, 2))

timezones = [
Expand Down
Loading

0 comments on commit ce3bac9

Please sign in to comment.