Skip to content

Instantly share code, notes, and snippets.

@kingspp
Created October 24, 2018 06:40
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 kingspp/558e1cf1d4cfdcd30db9ab49df6e80f8 to your computer and use it in GitHub Desktop.
Save kingspp/558e1cf1d4cfdcd30db9ab49df6e80f8 to your computer and use it in GitHub Desktop.
Tensorflow Fetch Operation Validation
import typing
import tensorflow as tf
def validate_fetch(fetch_ops: typing.Union[str, list, dict, tf.Tensor]):
if isinstance(fetch_ops, str):
if not len(fetch_ops) > 0:
raise Exception("Fetch Op is an empty string")
return fetch_ops
elif isinstance(fetch_ops, tf.Tensor):
return fetch_ops
elif isinstance(fetch_ops, list):
if len(fetch_ops) == 0:
raise Exception(
"Fetch operations is an empty list. Requires a list of str of Tensors. Given, fetch_ops: {}".format(
fetch_ops))
for fetch_op in fetch_ops:
validate_fetch(fetch_op)
return fetch_ops
elif isinstance(fetch_ops, dict):
if len(fetch_ops) == 0:
raise Exception("Fetch operations is an empty list. fetch_ops: {}".format(fetch_ops))
for k, v in fetch_ops.items():
if not isinstance(k, str) or len(k) == 0:
raise Exception(
'Key of Fetch Ops should be a string and len(key) should be > 0. Given, type:{}, value:{}'.format(type(k),k))
validate_fetch(v)
return fetch_ops
else:
raise Exception('Fetch Ops support one among [str, list, dict, tf.Tensor]. Given: {}'.format(type(fetch_ops)))
ops_false = (
'',
None,
[],
[[]],
['123', []],
{},
{1:2},
{'':3},
{'123':3},
{'123':[]},
{'123':[[123]]},
{'123':{}},
)
ops_true = (
'abc',
['123'],
[['123'], [[[[[[[[[['123']]]]]]]]]]],
{'123':'123'},
{'123':[['123']]},
)
print(validate_fetch(ops_true[0]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment