Skip to content

Instantly share code, notes, and snippets.

@shoyer
Last active November 21, 2017 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shoyer/0c2fa6c4535209df966210930849de58 to your computer and use it in GitHub Desktop.
Save shoyer/0c2fa6c4535209df966210930849de58 to your computer and use it in GitHub Desktop.
# Copyright 2017 Google LLC.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Generic, TypeVar, Type, Union
# toy version of the NumPy type hierarchy
class generic(object):
pass
class floating(generic):
pass
class float64(floating):
pass
class float32(floating):
pass
D = TypeVar('D', bound=generic)
# toy version of np.dtype
class DType(Generic[D]):
def __init__(self, type_: 'Union[Type[D], DType[D]]') -> None:
if isinstance(type_, DType):
type_ = type_.type
self._type = type_
@property
def type(self) -> Type[D]:
return self._type
DTypeLike = Union[Type[D], DType[D]]
# toy version of np.ndarray
class NDArray(Generic[D]):
def __init__(self, dtype: DTypeLike) -> None:
self._dtype = DType(dtype)
@property
def dtype(self) -> DType[D]:
return self._dtype
def empty_flexible(dtype: DTypeLike[D]) -> NDArray[D]:
return NDArray(dtype)
def empty_dtype_only(dtype: DType[D]) -> NDArray[D]:
return NDArray(dtype)
def empty_generic_only(dtype: Type[D]) -> NDArray[D]:
return NDArray(dtype)
# Tests
# All these typing errors should be caught by mypy
def invalid_convert(array: NDArray[float32]) -> NDArray[float64]:
return array
def invalid_create_dtype_only() -> NDArray[float64]:
return empty_dtype_only(DType(float32))
def invalid_create_flexible_dtype() -> NDArray[float64]:
return empty_flexible(DType(float32))
def invalid_create_flexible_generic() -> NDArray[float64]:
return empty_flexible(float32) # mypy DOES NOT catch this
def invalid_create_generic_only() -> NDArray[float64]:
return empty_generic_only(float32)
# These errors should pass
def valid_create_dtype_only() -> NDArray[float64]:
return empty_dtype_only(DType(float64))
def valid_create_flexible_generic() -> NDArray[float64]:
return empty_flexible(float64)
def valid_create_flexible_dtype() -> NDArray[float64]:
return empty_flexible(DType(float64))
def valid_create_generic_only() -> NDArray[float64]:
return empty_generic_only(float64)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment