nmh nmh - 24 days ago 8
Python Question

Python- re-assigning object variables within script multiple times- good practice?

Say for example, I have a function 'artistsearch' in class 'Scraper()' that takes the arguments 'website', 'artist', 'keyword' and 'rangenum', and I want to use this function multiple times in a script for different values. Is it the usual practice to simply reassign the variables like in the example below, or is there a more pythonesque way of doing this?

# Set values for first instantiation

website="https://www.examplewebsitenumber1.com/"
artist="Da Vinci"
keyword="painting"
rangenum=7

# instantiate to object devinci
devinci=Scraper()

# run function
devinci.artistsearch(website, artist, keyword, rangenum)

# Set values for second instantiation

website="https://www.examplewebsitenumber2.com/"
artist="Gaudi"
keyword="sculpture"
rangenum=9
# instantiate to object gaudi
gaudi=Scraper()

# run function again with different values
gaudi.artistsearch(website, artist, keyword, rangenum)

and so on.........

Answer Source

It's perfectly okay to reuse a variable (you're just reassigning the name to something else), but in your case, you seem to need a loop & a list of dictionaries to pass as keyword arguments

arglist = [{website:"https://www.examplewebsitenumber1.com/",
artist:"Da Vinci",
keyword:"painting",
rangenum:7},
{website:"https://www.examplewebsitenumber2.com/",
artist:"Gaudi",
keyword:"sculpture",
rangenum:9}
]

for args in arglist:
    devinci=Scraper()
    devinci.artistsearch(**args)

I'm of course not sure of the argument names in artistsearch, but you get the idea (at worst, create a list of lists instead and pass arguments as positional, artistsearch(*args) in that case)