1# Copyright 2017 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"""Symbol naming utilities.""" 16 17from __future__ import absolute_import 18from __future__ import division 19from __future__ import print_function 20 21from tensorflow.python.autograph.pyct import qual_names 22 23 24class Namer(object): 25 """Symbol name generator.""" 26 27 def __init__(self, global_namespace): 28 self.global_namespace = global_namespace 29 self.generated_names = set() 30 31 def new_symbol(self, name_root, reserved_locals): 32 """See control_flow.SymbolNamer.new_symbol.""" 33 # reserved_locals may contain QNs. 34 all_reserved_locals = set() 35 for s in reserved_locals: 36 if isinstance(s, qual_names.QN): 37 all_reserved_locals.update(s.qn) 38 elif isinstance(s, str): 39 all_reserved_locals.add(s) 40 else: 41 raise ValueError('Unexpected symbol type "%s"' % type(s)) 42 43 pieces = name_root.split('_') 44 if pieces[-1].isdigit(): 45 name_root = '_'.join(pieces[:-1]) 46 n = int(pieces[-1]) 47 else: 48 n = 0 49 new_name = name_root 50 51 while (new_name in self.global_namespace or 52 new_name in all_reserved_locals or new_name in self.generated_names): 53 n += 1 54 new_name = '%s_%d' % (name_root, n) 55 56 self.generated_names.add(new_name) 57 return new_name 58