search_type = str(input("Enter search paramiter. (type top for top of all time) (type hot for populour posts in the last 24 hours) (type new for the newest posts): "))
hot_apex = subred.search_type(limit=num)
I would like search_type to be from a user input so the user could write top and then search type = top and changes to
hot_apex = subred.top(limit=num)
However, I get this error message 'Subreddit' object has no attribute 'search_type' however top is a object of subreddit
search_type
is a variable defined as a string.
subred.search_type
tries to look for an attribute called "search_type"
in the subred
object. It doesn't resolve the variable search_type
and look for an attribute named by the value of that variable. To do that, you need to use the getattr()
function.
search_type = input("Enter type: ")
try:
func_to_call = getattr(subred, search_type)
results = func_to_call(limit=num)
except AttributeError:
print("Invalid input")
results = []
Alternatively, you could use an if..elif
ladder, but this can quickly get cumbersome if you have many possible valid inputs:
if search_type == "hot":
results = subred.hot(limit=num)
elif search_type == "top":
results = subred.top(limit=num)
else:
print("Invalid input")
results = []