I want to perform sentiment analyses on various subreddits and consider both "new" and "hot" submissions. I'm able to do this in the following way:
# What I have
def new_submissions(sub):
subreddit = reddit.subreddit(sub).new(limit=100)
for submission in subreddit:
# Do stuff
return new_stuff
def hot_submissions(sub):
subreddit = reddit.subreddit(sub).hot(limit=100)
for submission in subreddit:
# Do stuff
return hot_stuff
new_submissions("subname")
hot_submissions("subname")
Here, "do stuff" involves 40 lines of identical code. I'd like to reference the "sort by" parameter for subreddits (e,g, .new(), .hot()) as a function argument as shown below:
# What I want
def submissions(sub, sortby):
subreddit = reddit.subreddit(sub).sortby(limit=100)
for submission in subreddit:
# Do stuff
return stuff
submissions("subname", new)
submissions("subname", hot)
I have not had success in getting this to work. How should I approach this?
What you could do is
def submissions(subreddit):
for submission in subreddit:
# Do stuff
return stuff
submissions(reddit.subreddit("subname").new(limit=100))
submissions(reddit.subreddit("subname").hot(limit=100))
or if you want to do as you were looking for you could do:
def submissions(sub, sortby):
method_to_call = getattr(reddit.subreddit(sub), sortby)
subreddit = method_to_call(limit=100)
for submission in subreddit:
# Do stuff
return stuff
# new and hot are strings to search for as attributes of the class
submissions("funnyvideos", 'new')
submissions("funnyvideos", 'hot')