def state_logic(state):
    # Only consider states which are in the same container
    in_same_container = filter(lambda s: s.container == state.container, states.get_states())

    other = iterator.find(
        lambda s: s.source == state.source and s.options['replace'] == True,
        in_same_container
    )

    if other:
        states.remove(other, wipeout_buffer=False)
        state.uid = other.uid
        state.buff = other.buff
        state.source = other.source
        return state, other

    other = iterator.find(
        lambda s: s.source != state.source and s.options['replace'] == True,
        in_same_container,
    )

    if other:
        states.remove(other, wipeout_buffer=False)
        state.uid = other.uid
        state.buff = other.buff
        state.source.populate_candidates()
        ui.set_buffer_contents(state.buff, state.source.formatted_candidates())
        return state, other

    other = iterator.find(lambda s: s.source == state.source, in_same_container)
    if other:
        state.source = other.source
    else:
        state.source.populate_candidates()
    return state, None
State create/replace/reuse logic. The function name is not very good :(
dataset/ETHPy150Open azure-satellite/pyunite/pyunite/core.py/state_logic