def add_with_port_collision_retry(client, unit_name, **kw):
 ultimate_ports = []
 def add():
  ultimate_ports[:] = tentative_ports = list(((port.set(external_port=find_free_port()[1]) if (port.external_port == 0) else port) for port in kw['ports']))
  tentative_kw = kw.copy()
  tentative_kw['ports'] = tentative_ports
  return client.add(unit_name, **tentative_kw)
 def cleanup():
  return client.remove(unit_name)
 if ('ports' in kw):
  trying = add()
  trying.addErrback(_retry_on_port_collision, add, cleanup)
  result = trying
 else:
  result = client.add(unit_name, **kw)
 result.addCallback((lambda app: (app, ultimate_ports)))
 return result

def add_with_port_collision_retry ( client , unit_name , ** kw ) : ultimate_ports = [ ] def add ( ) : ultimate_ports [ : ] = tentative_ports = list ( ( ( port . set ( external_port = find_free_port ( ) [ 1 ] ) if ( port . external_port == 0 ) else port ) for port in kw [ 'ports' ] ) ) tentative_kw = kw . copy ( ) tentative_kw [ 'ports' ] = tentative_ports return client . add ( unit_name , ** tentative_kw ) def cleanup ( ) : return client . remove ( unit_name ) if ( 'ports' in kw ) : trying = add ( ) trying . addErrback ( _retry_on_port_collision , add , cleanup ) result = trying else : result = client . add ( unit_name , ** kw ) result . addCallback ( ( lambda app : ( app , ultimate_ports ) ) ) return result
add a container .