0

I need to create multiple functions using a for loop so I can have similar functions with different names.

rss = ['food', 'wood', 'stone', 'iron', 'gold']

for resource in rss:
    def resource(account):
        with open('accountdetails.py', 'r') as file:
            accdets = json.load(file)
        rss_value = accdets[account][resource]
        print(rss_value)

food('account_3')

This code doesn't work, but I expected it to create 5 different functions, and the [resource] being replaced depending on which function is called. Instead, I get NameError: name 'food' is not defined

B Food
  • 115
  • 2
  • 10

1 Answers1

0

You can not create functions like this - however, you can reuse the same function and simply provide the "resource-name" as additional input to it:

def resource(account, res):
    """Prints the resource 'res' from acccount 'account'"""
    with open('accountdetails.py', 'r') as file:
        accdets = json.load(file)
    rss_value = accdets[account][res]
    print(rss_value)


rss = ['food', 'wood', 'stone', 'iron', 'gold']
for what in rss:
    resource("account_3", what) # this will print it 

The disadvantage is:

  • you load the file 5 times
  • you create the json 5 times

It would be better to do the loading and object-creation just once:

# not sure if it warrants its own function
def print_resource(data, account, res):
    print(data[account][res]) 

# load json from file and create object from it 
with open('accountdetails.py', 'r') as file:
    accdets = json.load(file)

rss = ['food', 'wood', 'stone', 'iron', 'gold']
for what in rss:
    print_resource(accdets, "account_3", what)   
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69