Skip to content

Commit

Permalink
Fix doctests (#4408)
Browse files Browse the repository at this point in the history
* update the CFTimeIndex reprs

* update the variable reprs and fix a typo

* fix the examples in the datetime accessors

* make sure numpy.random is always seeded in doctests

* fix more doctests

* explain the seeding of numpy.random

* shorten the expected array reprs

* fix the failing conventions doctests

* attempt to fix the failing coding.strings doctest

* fix the failing save_mfdataset doctest

* fix the indexing doctests

* always use change to a temporary directory before executing a test

which makes manually removing paths unnecessary

* fix the filter_by_attrs doctests
  • Loading branch information
keewis authored Sep 11, 2020
1 parent f70c881 commit 23dc2fc
Show file tree
Hide file tree
Showing 23 changed files with 557 additions and 424 deletions.
8 changes: 7 additions & 1 deletion conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def pytest_runtest_setup(item):


@pytest.fixture(autouse=True)
def add_standard_imports(doctest_namespace):
def add_standard_imports(doctest_namespace, tmpdir):
import numpy as np
import pandas as pd

Expand All @@ -33,3 +33,9 @@ def add_standard_imports(doctest_namespace):
doctest_namespace["np"] = np
doctest_namespace["pd"] = pd
doctest_namespace["xr"] = xr

# always seed numpy.random to make the examples deterministic
np.random.seed(0)

# always switch to the temporary directory, so files get written there
tmpdir.chdir()
11 changes: 11 additions & 0 deletions xarray/backends/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1189,6 +1189,17 @@ def save_mfdataset(
Save a dataset into one netCDF per year of data:
>>> ds = xr.Dataset(
... {"a": ("time", np.linspace(0, 1, 48))},
... coords={"time": pd.date_range("2010-01-01", freq="M", periods=48)},
... )
>>> ds
<xarray.Dataset>
Dimensions: (time: 48)
Coordinates:
* time (time) datetime64[ns] 2010-01-31 2010-02-28 ... 2013-12-31
Data variables:
a (time) float64 0.0 0.02128 0.04255 0.06383 ... 0.9574 0.9787 1.0
>>> years, datasets = zip(*ds.groupby("time.year"))
>>> paths = ["%s.nc" % y for y in years]
>>> xr.save_mfdataset(datasets, paths)
Expand Down
2 changes: 1 addition & 1 deletion xarray/coding/cftime_offsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -939,7 +939,7 @@ def cftime_range(
>>> xr.cftime_range(start="2000", periods=6, freq="2MS", calendar="noleap")
CFTimeIndex([2000-01-01 00:00:00, 2000-03-01 00:00:00, 2000-05-01 00:00:00,
2000-07-01 00:00:00, 2000-09-01 00:00:00, 2000-11-01 00:00:00],
dtype='object')
dtype='object', length=6, calendar='noleap')
As in the standard pandas function, three of the ``start``, ``end``,
``periods``, or ``freq`` arguments must be specified at a given time, with
Expand Down
9 changes: 6 additions & 3 deletions xarray/coding/cftimeindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,9 +523,11 @@ def shift(self, n, freq):
--------
>>> index = xr.cftime_range("2000", periods=1, freq="M")
>>> index
CFTimeIndex([2000-01-31 00:00:00], dtype='object')
CFTimeIndex([2000-01-31 00:00:00],
dtype='object', length=1, calendar='gregorian')
>>> index.shift(1, "M")
CFTimeIndex([2000-02-29 00:00:00], dtype='object')
CFTimeIndex([2000-02-29 00:00:00],
dtype='object', length=1, calendar='gregorian')
"""
from .cftime_offsets import to_offset

Expand Down Expand Up @@ -611,7 +613,8 @@ def to_datetimeindex(self, unsafe=False):
>>> import xarray as xr
>>> times = xr.cftime_range("2000", periods=2, calendar="gregorian")
>>> times
CFTimeIndex([2000-01-01 00:00:00, 2000-01-02 00:00:00], dtype='object')
CFTimeIndex([2000-01-01 00:00:00, 2000-01-02 00:00:00],
dtype='object', length=2, calendar='gregorian')
>>> times.to_datetimeindex()
DatetimeIndex(['2000-01-01', '2000-01-02'], dtype='datetime64[ns]', freq=None)
"""
Expand Down
6 changes: 3 additions & 3 deletions xarray/coding/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,9 +199,9 @@ class StackedBytesArray(indexing.ExplicitlyIndexedNDArrayMixin):
"""Wrapper around array-like objects to create a new indexable object where
values, when accessed, are automatically stacked along the last dimension.
>>> StackedBytesArray(np.array(["a", "b", "c"]))[:]
array('abc',
dtype='|S3')
>>> indexer = indexing.BasicIndexer((slice(None),))
>>> StackedBytesArray(np.array(["a", "b", "c"], dtype="S1"))[indexer]
array(b'abc', dtype='|S3')
"""

def __init__(self, array):
Expand Down
10 changes: 6 additions & 4 deletions xarray/conventions.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,11 @@ class NativeEndiannessArray(indexing.ExplicitlyIndexedNDArrayMixin):
>>> x.dtype
dtype('>i2')
>>> NativeEndianArray(x).dtype
>>> NativeEndiannessArray(x).dtype
dtype('int16')
>>> NativeEndianArray(x)[:].dtype
>>> indexer = indexing.BasicIndexer((slice(None),))
>>> NativeEndiannessArray(x)[indexer].dtype
dtype('int16')
"""

Expand All @@ -53,12 +54,13 @@ class BoolTypeArray(indexing.ExplicitlyIndexedNDArrayMixin):
>>> x = np.array([1, 0, 1, 1, 0], dtype="i1")
>>> x.dtype
dtype('>i2')
dtype('int8')
>>> BoolTypeArray(x).dtype
dtype('bool')
>>> BoolTypeArray(x)[:].dtype
>>> indexer = indexing.BasicIndexer((slice(None),))
>>> BoolTypeArray(x)[indexer].dtype
dtype('bool')
"""

Expand Down
51 changes: 25 additions & 26 deletions xarray/core/accessor_dt.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,30 +249,30 @@ class DatetimeAccessor(Properties):
>>> ts
<xarray.DataArray (time: 10)>
array(['2000-01-01T00:00:00.000000000', '2000-01-02T00:00:00.000000000',
'2000-01-03T00:00:00.000000000', '2000-01-04T00:00:00.000000000',
'2000-01-05T00:00:00.000000000', '2000-01-06T00:00:00.000000000',
'2000-01-07T00:00:00.000000000', '2000-01-08T00:00:00.000000000',
'2000-01-09T00:00:00.000000000', '2000-01-10T00:00:00.000000000'],
dtype='datetime64[ns]')
'2000-01-03T00:00:00.000000000', '2000-01-04T00:00:00.000000000',
'2000-01-05T00:00:00.000000000', '2000-01-06T00:00:00.000000000',
'2000-01-07T00:00:00.000000000', '2000-01-08T00:00:00.000000000',
'2000-01-09T00:00:00.000000000', '2000-01-10T00:00:00.000000000'],
dtype='datetime64[ns]')
Coordinates:
* time (time) datetime64[ns] 2000-01-01 2000-01-02 ... 2000-01-10
>>> ts.dt
<xarray.core.accessor_dt.DatetimeAccessor object at 0x118b54d68>
* time (time) datetime64[ns] 2000-01-01 2000-01-02 ... 2000-01-10
>>> ts.dt # doctest: +ELLIPSIS
<xarray.core.accessor_dt.DatetimeAccessor object at 0x...>
>>> ts.dt.dayofyear
<xarray.DataArray 'dayofyear' (time: 10)>
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Coordinates:
* time (time) datetime64[ns] 2000-01-01 2000-01-02 ... 2000-01-10
* time (time) datetime64[ns] 2000-01-01 2000-01-02 ... 2000-01-10
>>> ts.dt.quarter
<xarray.DataArray 'quarter' (time: 10)>
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
Coordinates:
* time (time) datetime64[ns] 2000-01-01 2000-01-02 ... 2000-01-10
* time (time) datetime64[ns] 2000-01-01 2000-01-02 ... 2000-01-10
"""

def strftime(self, date_format):
'''
"""
Return an array of formatted strings specified by date_format, which
supports the same string format as the python standard library. Details
of the string format can be found in `python string format doc
Expand All @@ -290,13 +290,12 @@ def strftime(self, date_format):
Examples
--------
>>> import datetime
>>> rng = xr.Dataset({"time": datetime.datetime(2000, 1, 1)})
>>> rng["time"].dt.strftime("%B %d, %Y, %r")
<xarray.DataArray 'strftime' ()>
array('January 01, 2000, 12:00:00 AM', dtype=object)
"""
'''
obj_type = type(self._obj)

result = _strftime(self._obj.data, date_format)
Expand Down Expand Up @@ -398,32 +397,32 @@ class TimedeltaAccessor(Properties):
>>> ts
<xarray.DataArray (time: 20)>
array([ 86400000000000, 108000000000000, 129600000000000, 151200000000000,
172800000000000, 194400000000000, 216000000000000, 237600000000000,
259200000000000, 280800000000000, 302400000000000, 324000000000000,
345600000000000, 367200000000000, 388800000000000, 410400000000000,
432000000000000, 453600000000000, 475200000000000, 496800000000000],
dtype='timedelta64[ns]')
172800000000000, 194400000000000, 216000000000000, 237600000000000,
259200000000000, 280800000000000, 302400000000000, 324000000000000,
345600000000000, 367200000000000, 388800000000000, 410400000000000,
432000000000000, 453600000000000, 475200000000000, 496800000000000],
dtype='timedelta64[ns]')
Coordinates:
* time (time) timedelta64[ns] 1 days 00:00:00 ... 5 days 18:00:00
>>> ts.dt
<xarray.core.accessor_dt.TimedeltaAccessor object at 0x109a27d68>
* time (time) timedelta64[ns] 1 days 00:00:00 ... 5 days 18:00:00
>>> ts.dt # doctest: +ELLIPSIS
<xarray.core.accessor_dt.TimedeltaAccessor object at 0x...>
>>> ts.dt.days
<xarray.DataArray 'days' (time: 20)>
array([1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5])
Coordinates:
* time (time) timedelta64[ns] 1 days 00:00:00 ... 5 days 18:00:00
* time (time) timedelta64[ns] 1 days 00:00:00 ... 5 days 18:00:00
>>> ts.dt.microseconds
<xarray.DataArray 'microseconds' (time: 20)>
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
Coordinates:
* time (time) timedelta64[ns] 1 days 00:00:00 ... 5 days 18:00:00
* time (time) timedelta64[ns] 1 days 00:00:00 ... 5 days 18:00:00
>>> ts.dt.seconds
<xarray.DataArray 'seconds' (time: 20)>
array([ 0, 21600, 43200, 64800, 0, 21600, 43200, 64800, 0,
21600, 43200, 64800, 0, 21600, 43200, 64800, 0, 21600,
43200, 64800])
21600, 43200, 64800, 0, 21600, 43200, 64800, 0, 21600,
43200, 64800])
Coordinates:
* time (time) timedelta64[ns] 1 days 00:00:00 ... 5 days 18:00:00
* time (time) timedelta64[ns] 1 days 00:00:00 ... 5 days 18:00:00
"""

days = Properties._tslib_field_accessor(
Expand Down
2 changes: 1 addition & 1 deletion xarray/core/accessor_str.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class StringAccessor:
for applicable DataArrays.
>>> da = xr.DataArray(["some", "text", "in", "an", "array"])
>>> ds.str.len()
>>> da.str.len()
<xarray.DataArray (dim_0: 5)>
array([4, 4, 2, 2, 5])
Dimensions without coordinates: dim_0
Expand Down
Loading

0 comments on commit 23dc2fc

Please sign in to comment.