Tokaalmighty Tokaalmighty - 23 days ago 8
Python Question

Python function used 3 times, but only returned once

I'm trying to create a function that returns a dictionary and use it 3 times, then join the returned dictionaries into 1. Then assign that dictionary as value to a key in another dictionary. But print(all_dict) only returns 1 dictionary. If I try to print(get_dict(f1)), I get the Traceback below. If instead of calling the same function 3 times, I define each function separately with the same commands in each function, I can get what I want. But I hope to find a more concise way to write code.

You can find HTML of the table here: https://github.com/Tokaalmighty/topmover_table_html/blob/master/html

Traceback (most recent call last):
File "week4_1.py", line 55, in <module>
print(get_dict(f1))
File "week4_1.py", line 23, in get_dict
bold=topmovers.find_all('b')
AttributeError: 'NoneType' object has no attribute 'find_all'


Here is the code of my function and how I tried to join 3 dictionaries into 1:

def get_dict(f1):

soup=bs(f1,'html.parser')
topmovers=soup.find('table'{'class':'topmovers'})
bold=topmovers.find_all('b')


return final

all_dict={}
result = {**get_dict(f1), **get_dict(f2), **get_dict(f3)}
all_dict['result']=result
print(all_dict)
print(get_dict(f1))

lvc lvc
Answer Source

You don't show your original definition of f1, f2 and f3, but I suspect it looks something like:

f1 = open(...)

What's going on, then, is that repeated reads from files start from where the last one left off. If you've read the whole file (like by getting bs to parse it), that will be at the end and subsequent reads come back empty. bs now can't find a table of the appropriate class in the empty file, so it returns None.

To fix this, you can reset the files internal pointer back to the start by calling

f1.seek(0)

Before you use it the second time; or you could avoid duplicating work by capturing the result of the first get_dict call in a variable.