Pergunta

I have code running on a server with namedtuples:

Event = namedtuple("Event", ['attr1', 'attr2', 'attr3'])

The server is getting events from other servers, coming out of a queue.

I want to add a new feature to my code which needs a new attribute in the namedtuple. Is there a good way to do this and keep backwards compatibility? That is, I can stop and start the server, and change the code to:

Event = namedtuple("Event", ['attr1', 'attr2', 'attr3', 'attr4'])

But in the meantime there will be Events with the old signature queued up.

Anyone done this before?

Foi útil?

Solução

It would work as it is, only problem can occur is in your code when you are using the newly added attribute e.g.

from collections import namedtuple

Event1 = namedtuple("Event", ['attr1', 'attr2', 'attr3', 'attr4'])
Event2 = namedtuple("Event", ['attr1', 'attr2', 'attr3', 'attr4', 'attr5'])

def handle_event(event):
    print event.attr5

handle_event(Event2(1,2,3,4,5))
handle_event(Event1(1,2,3,4))

You will get error AttributeError: 'Event' object has no attribute 'attr5' so if you taken care of such thing in backward-compatible way, like checking if attr5 is there, it should work

Outras dicas

looking at how you defined your tuples it should work without any issue, as long as you don't change the ordering of the attributes.

Obviously in your code you shouldn't rely nowere on the fact that the tuple is of length 3 instead of 4.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top