fluid.unique_name

generate

paddle.fluid.unique_name.generate(key)[source]

Generate unique name with prefix key. Currently, Paddle distinguishes the names of the same key by numbering it from zero. For example, when key=fc, it continuously generates fc_0, fc_1, fc_2, etc.

Parameters

key (str) – The prefix of generated name.

Returns

A unique string with the prefix key.

Return type

str

Examples

import paddle.fluid as fluid
name1 = fluid.unique_name.generate('fc')
name2 = fluid.unique_name.generate('fc')
print(name1, name2) # fc_0, fc_1

guard

paddle.fluid.unique_name.guard(new_generator=None)[source]

Change the namespace of unique name with with statement. After calling it, a new namespace in the context of with will be created, and it will number names from zero again when calling generate() with same key.

Parameters

new_generator (str|bytes, optional) – New name of global namespace. Note that str in Python2 was spilted into str and bytes in Python3, so here are two types. Default is None. If not None, new_generator will be added into the prefix of unique name generated by generate().

Returns

None.

Examples

import paddle.fluid as fluid
with fluid.unique_name.guard():
  name_1 = fluid.unique_name.generate('fc')
with fluid.unique_name.guard():
  name_2 = fluid.unique_name.generate('fc')
print(name_1, name_2) # fc_0, fc_0

with fluid.unique_name.guard('A'):
  name_1 = fluid.unique_name.generate('fc')
with fluid.unique_name.guard('B'):
  name_2 = fluid.unique_name.generate('fc')
print(name_1, name_2) # Afc_0, Bfc_0

switch

paddle.fluid.unique_name.switch(new_generator=None)[source]

Switch the namespace of in current context to a new namespace. Though switch() and guard() can both change namespace, guard() is recommended since it can manage the context better together with with statement.

Parameters

new_generator (UniqueNameGenerator, optional) – A new UniqueNameGenerator, not required normally. Default is None, which means switch to a new anonymous namespace.

Returns

The previous UniqueNameGenerator.

Return type

UniqueNameGenerator

Examples

import paddle.fluid as fluid
name1 = fluid.unique_name.generate('fc')
name2 = fluid.unique_name.generate('fc')
print(name1, name2) # fc_0, fc_1

pre_generator = fluid.unique_name.switch() # switch to a new anonymous namespace.
name2 = fluid.unique_name.generate('fc')
print(name2) # fc_0

fluid.unique_name.switch(pre_generator) # switch back to pre_generator.
name3 = fluid.unique_name.generate('fc')
print(name3) # fc_2, since pre_generator has generated fc_0, fc_1.