1# Copyright 2021 The TensorFlow Authors. All Rights Reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# ============================================================================== 15"""Utilities for accessing Python generic type annotations (typing.*).""" 16 17import collections.abc 18import typing 19 20 21def is_generic_union(tp): 22 """Returns true if `tp` is a parameterized typing.Union value.""" 23 return (tp is not typing.Union and 24 getattr(tp, '__origin__', None) is typing.Union) 25 26 27def is_generic_tuple(tp): 28 """Returns true if `tp` is a parameterized typing.Tuple value.""" 29 return (tp not in (tuple, typing.Tuple) and 30 getattr(tp, '__origin__', None) in (tuple, typing.Tuple)) 31 32 33def is_generic_list(tp): 34 """Returns true if `tp` is a parameterized typing.List value.""" 35 return (tp not in (list, typing.List) and 36 getattr(tp, '__origin__', None) in (list, typing.List)) 37 38 39def is_generic_mapping(tp): 40 """Returns true if `tp` is a parameterized typing.Mapping value.""" 41 return (tp not in (collections.abc.Mapping, typing.Mapping) and getattr( 42 tp, '__origin__', None) in (collections.abc.Mapping, typing.Mapping)) 43 44 45def is_forward_ref(tp): 46 """Returns true if `tp` is a typing forward reference.""" 47 if hasattr(typing, 'ForwardRef'): 48 return isinstance(tp, typing.ForwardRef) 49 elif hasattr(typing, '_ForwardRef'): 50 return isinstance(tp, typing._ForwardRef) # pylint: disable=protected-access 51 else: 52 return False 53 54 55# Note: typing.get_args was added in Python 3.8. 56if hasattr(typing, 'get_args'): 57 get_generic_type_args = typing.get_args 58else: 59 get_generic_type_args = lambda tp: tp.__args__ 60