# Buggy code
def __getitem__(self, key):
    return type(self)(self.array[key])


# Traceback (TypeError)
import xarray as xr
xr.__version__
'0.9.1'

ds = xr.open_dataset('lgm2co2.nc')
ds
<xarray.Dataset>
Dimensions:            (lat_aux_grid: 105, moc_comp: 1, moc_z: 26, time: 2204, transport_reg: 2)
Coordinates:
* time               (time) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...
* lat_aux_grid       (lat_aux_grid) float32 -80.2602 -78.7338 -77.2176 ...
* moc_z              (moc_z) float32 0.0 800.0 1644.05 2573.71 3627.36 ...
moc_components     (moc_comp) |S512 b'Eulerian Mean'
transport_regions  (transport_reg) |S512 b'Global Ocean - Marginal Seas' ...
Dimensions without coordinates: moc_comp, transport_reg
Data variables:
MOC                (time, transport_reg, moc_comp, moc_z, lat_aux_grid) float64 0.0 ...


moc = ds.MOC.isel(transport_reg=1,moc_comp=0)
moc

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/Users/Yefee/miniconda3/lib/python3.6/site-packages/IPython/core/formatters.py in __call__(self, obj)
670                 type_pprinters=self.type_printers,
671                 deferred_pprinters=self.deferred_printers)
--> 672             printer.pretty(obj)
673             printer.flush()
674             return stream.getvalue()

/Users/Yefee/miniconda3/lib/python3.6/site-packages/IPython/lib/pretty.py in pretty(self, obj)
381                             if callable(meth):
382                                 return meth(obj, self, cycle)
--> 383             return _default_pprint(obj, self, cycle)
384         finally:
385             self.end_group()

/Users/Yefee/miniconda3/lib/python3.6/site-packages/IPython/lib/pretty.py in _default_pprint(obj, p, cycle)
501     if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
502         # A user-provided repr. Find newlines and replace them with p.break_()
--> 503         _repr_pprint(obj, p, cycle)
504         return
505     p.begin_group(1, '<')

/Users/Yefee/miniconda3/lib/python3.6/site-packages/IPython/lib/pretty.py in _repr_pprint(obj, p, cycle)
699     """A pprint that just redirects to the normal repr function."""
700     # Find newlines and replace them with p.break_()
--> 701     output = repr(obj)
702     for idx,output_line in enumerate(output.splitlines()):
703         if idx:

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/common.py in __repr__(self)
152
153     def __repr__(self):
--> 154         return formatting.array_repr(self)
155
156     def _iter(self):

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/formatting.py in array_repr(arr)
380     if hasattr(arr, 'coords'):
381         if arr.coords:
--> 382             summary.append(repr(arr.coords))
383
384         unindexed_dims_str = unindexed_dims_repr(arr.dims, arr.coords)

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/formatting.py in __repr__(self)
58     """Mixin that defines __repr__ for a class that already has __unicode__."""
59     def __repr__(self):
---> 60         return ensure_valid_repr(self.__unicode__())
61
62

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/coordinates.py in __unicode__(self)
44
45     def __unicode__(self):
---> 46         return formatting.coords_repr(self)
47
48     @property

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/formatting.py in coords_repr(coords, col_width)
309         col_width = _calculate_col_width(_get_col_items(coords))
310     return _mapping_repr(coords, title=u'Coordinates',
--> 311                          summarizer=summarize_coord, col_width=col_width)
312
313

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/formatting.py in _mapping_repr(mapping, title, summarizer, col_width)
291     summary = [u'%s:' % title]
292     if mapping:
--> 293         summary += [summarizer(k, v, col_width) for k, v in mapping.items()]
294     else:
295         summary += [EMPTY_REPR]

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/formatting.py in <listcomp>(.0)
291     summary = [u'%s:' % title]
292     if mapping:
--> 293         summary += [summarizer(k, v, col_width) for k, v in mapping.items()]
294     else:
295         summary += [EMPTY_REPR]

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/formatting.py in summarize_coord(name, var, col_width)
251                 [_summarize_coord_multiindex(coord, col_width, marker),
252                  _summarize_coord_levels(coord, col_width)])
--> 253     return _summarize_var_or_coord(name, var, col_width, show_values, marker)
254
255

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/formatting.py in _summarize_var_or_coord(name, var, col_width, show_values, marker, max_width)
205     front_str = u'%s%s%s ' % (first_col, dims_str, var.dtype)
206     if show_values:
--> 207         values_str = format_array_flat(var, max_width - len(front_str))
208     else:
209         values_str = u'...'

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/formatting.py in format_array_flat(items_ndarray, max_width)
178     # print at least one item
179     max_possibly_relevant = max(int(np.ceil(max_width / 2.0)), 1)
--> 180     relevant_items = first_n_items(items_ndarray, max_possibly_relevant)
181     pprint_items = format_items(relevant_items)
182

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/formatting.py in first_n_items(x, n_desired)
86     if n_desired < x.size:
87         indexer = _get_indexer_at_least_n_items(x.shape, n_desired)
---> 88         x = x[indexer]
89     return np.asarray(x).flat[:n_desired]
90

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/dataarray.py in __getitem__(self, key)
467         else:
468             # orthogonal array indexing
--> 469             return self.isel(**self._item_key_to_dict(key))
470
471     def __setitem__(self, key, value):

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/dataarray.py in isel(self, drop, **indexers)
655         DataArray.sel
656         """
--> 657         ds = self._to_temp_dataset().isel(drop=drop, **indexers)
658         return self._from_temp_dataset(ds)
659

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/dataset.py in isel(self, drop, **indexers)
1117         for name, var in iteritems(self._variables):
1118             var_indexers = dict((k, v) for k, v in indexers if k in var.dims)
-> 1119             new_var = var.isel(**var_indexers)
1120             if not (drop and name in var_indexers):
1121                 variables[name] = new_var

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/variable.py in isel(self, **indexers)
545             if dim in indexers:
546                 key[i] = indexers[dim]
--> 547         return self[tuple(key)]
548
549     def squeeze(self, dim=None):

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/variable.py in __getitem__(self, key)
375         dims = tuple(dim for k, dim in zip(key, self.dims)
376                      if not isinstance(k, (int, np.integer)))
--> 377         values = self._indexable_data[key]
378         # orthogonal indexing should ensure the dimensionality is consistent
379         if hasattr(values, 'ndim'):

/Users/Yefee/miniconda3/lib/python3.6/site-packages/xarray/core/indexing.py in __getitem__(self, key)
419
420     def __getitem__(self, key):
--> 421         return type(self)(self.array[key])
422
423     def __setitem__(self, key, value):

TypeError: byte indices must be integers or slices, not tuple

# Fixed code
def __getitem__(self, key):
    return type(self)(_wrap_numpy_scalars(self.array[key]))