Search code examples
pythonlistmethodsattributesinstapy

Randomly choose one method? attribute error - Python


Using instapy, I am using both a following and unfollowing method. In an attempt to halve the time needed for the program to run, I'm trying to have the program only follow or unfollow each time I run it. Instead of having to manually comment out one method or the other, I tried put both in a list, and use random.choice() to pick one or the other to run.

account_list = ['dji_official' , 'drone', 'dronenerds', 'dronepals']
first = session.follow_likers([random.sample(account_list, 2)], photos_grab_amount = 2, follow_likers_per_photo = 15, randomize=True, sleep_delay=25, interact=False)
# unfollow
second = session.unfollow_users(amount=40, allFollowing=True, style="FIFO", unfollow_after=12*60*60, sleep_delay=15)

action_list = [first, second]
random.choice(action_list)

This code returned an error "'list' object has no attribute 'replace'" Not sure where/why it is throwing this error. Is there an easy fix? or would I be better off trying a function(s)?


Solution

  • This looks like a great use for an if. You could structure your code like this:

    account_list = ['dji_official' , 'drone', 'dronenerds', 'dronepals']
    action_list = [1, 2]
    option = random.choice(action_list)
    if option == 1:
        session.follow_likers([random.sample(account_list, 2)], photos_grab_amount = 2, follow_likers_per_photo = 15, randomize=True, sleep_delay=25, interact=False)
    elif option == 2:
        session.unfollow_users(amount=40, allFollowing=True, style="FIFO", unfollow_after=12*60*60, sleep_delay=15)
    

    Notice that, as was pointed out above, you need to store the result of running random.choice in a variable (I called it option) so you can do something with it, like check it in an if.