Reputation: 965
I am refactoring a python function in a large codebase. Currently, it looks like:
def GetEvents(file_path):
...
return events #a list of Event objects
A bunch of code depends on this function returning a list object already. However, I want to refactor it so it returns:
def GetEvents(file_path):
...
return (events, event_header)
Where event_header is a little description of this group of events. However, this will badly break all code that currently expects a list, not a tuple to be returned. In any other language, I would pass the event_header by reference, but I do not think I can do that in Python. I could also declare another function, GetEventsAndHeader(), but that awkwardly duplicates functionality.
Suggestions?
Upvotes: 2
Views: 983
Reputation: 6272
If you don't absolutely need to return a tuple, just add an attribute to your returned list:
class EventList(list):
pass
def GetEvents(file_path):
...
events = EventList(events)
events.event_header = some_header
return events
Upvotes: 6
Reputation: 49826
Well, as noted, if this takes no arguments, then it probably shouldn't be a function. I'd add that it's probably part of an object, and if not, it should be.
That way, you can have:
class EventGroup(object):
def GetEvents(): # note camelcase is not pep8 compliant
return dat_list
def EventGroupInfo():
return some_info
def fact_about_events1():
return fact1
def fact_about_events2():
return fact2
I've used no-argument methods to parallel your code, but I don't necessarily recommend it.
An alternative design choice would be to return an object which respects the full list protocol, and carries metadata about the group of events also.
Upvotes: 0
Reputation: 1121724
Rename the function to GetEventsAndHeader()
, and add a new function GetEvents()
:
def GetEvents(*args, **kw):
return GetEventsAndHeader(*args, **kw)[0]
or just bite the bullet and update all code that calls GetEvents()
and adjust that code to either use the returnvalue indexed to [0]
or make use of the headers as well.
Upvotes: 8