Reputation: 1080
I want to have a dispatcher dict{str: method} with methods in it. I want to iterate over the dispatcher keys and call the value as method, but when I run the Python script the methods get executed as soon as the dict is created:
from python.helper.my_client import Client
def deco_download(f):
def f_download(*args, **kwargs):
# some retry functionality here
return json_data
return f_download
class Downloader:
def __init__(self):
self.attribute = 'some_value'
@deco_download
def download_persons(self, client, *args, **kwargs):
return client.get_persons(*args, **kwargs)
@deco_download
def download_organizations(self, client, *args, **kwargs):
return client.get_organizations(*args, **kwargs)
def run(self):
dispatcher = {
'person': self.download_persons(client),
'organization': self.download_organizations(client)
}
for key in dispatcher:
print("Downlading data for: {0}".format(key)
dispatcher[key]
Unfortunately the methods are executed directly when the dispatcher dict is initialized before I call them in the for loop. I expect them to be called in the for loop and not during the construction of the dict however. What am I doing wrong here? Is it because of the decorator I am using?
Upvotes: 1
Views: 76
Reputation: 10782
Simply don't execute the function during the creation of the dict:
def run(self):
dispatcher = {
'person': self.download_persons,
'organization': self.download_organizations
}
for key in dispatcher:
print("Downlading data for: {0}".format(key)
dispatcher[key](client) # execute the function here
Upvotes: 1
Reputation: 600041
They're called because you call them. Don't do that; put the callables in the dict.
def run(self):
dispatcher = {
'person': self.download_persons,
'organization': self.download_organizations
}
for key in dispatcher:
print("Downlading data for: {0}".format(key)
dispatcher[key](client)
Upvotes: 4