Reputation: 16219
Given:
PICKLE_FILENAME_INSTRUCTION_IDS = 'pickled_instruction_ids.txt'
def compare_instruction_id_list_with_baseline(baselineidspicklefile):
baseline_ids = load_pickled_ids(baselineidspicklefile)
current_main_url_content = get_page_content(main_url_test)
root = lh.fromstring(current_main_url_content)
current_ids = get_instruction_ids(root)
diff = [id for id in current_ids if id not in baseline_ids]
return diff
where baselineidspicklefile
is the baseline of ids (a list
), pickled.
Later on in the code, I do a check of diff
, and if it's not empty, I do something with the new ids (current_ids
). Now though, I realise that if diff is non-empty, I also wish to overwrite the baseline ids with the new list of diffs via pickle, making it the new baseline.
current_ids
is local to this function though. So I can't just call pickle.dumps()
on it from the main section of the program. I'd rather not return both diff
and current_ids
from the function. And obviously I'd rather not make current_ids
global.
What are my options for accessing both variables?
Note: This is a general issue I have - I also encounter it when using urllib2 e.g in a function that does the following:
response = urllib2.urlopen(url)
content = response.read()
I typically return content
so I can do things like lxml.html.fromstring(content)
, but then I realise that a later point in the program will need to access response
, and I'm stuck because that's not what I've returned.
Upvotes: 1
Views: 32
Reputation: 20336
You can use the builtin locals()
function:
PICKLE_FILENAME_INSTRUCTION_IDS = 'pickled_instruction_ids.txt'
def compare_instruction_id_list_with_baseline(baselineidspicklefile):
baseline_ids = load_pickled_ids(baselineidspicklefile)
current_main_url_content = get_page_content(main_url_test)
root = lh.fromstring(current_main_url_content)
current_ids = get_instruction_ids(root)
diff = [id for id in current_ids if id not in baseline_ids]
return locals()
You can then use all variables defined in compare_instruction_id_list_with_baseline
by using the return value and then in brackets a string that defines the variable you want. For example, return_value = compare_instruction_id_list_with_baseline(...)
diff = return_value['diff']
.
Upvotes: 4