I have 4 modules:
entry_point.pyutils.pyrunner.pyclient.py
I use argparse in utils.py and I want to be able to retrieve the value of one of those arguments in client.py.
Entry point module (the one that gets called from console):
import utils def main(): console_args = utils.parse_arguments() # Get command-line arguments runner.run(console_args) # The main function in the program if __name__ == '__main__': main()utils.pymodule:def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument( # Several arguments, one of which should be 'url' ) return parser.parse_args()runner.pymodule:import client def run(arguments): user = User.new(arguments.user_id) client.get_user_info(user)client.pymodule:def get_user_info(user): url = _compose_url('user_status') resp = requests.post(url, data=user.id) def _compose_url(method): # TODO: get base_url from console arguments # base_url = ? return base_url + str(method)
I don't want to pass url as a parameter to client.get_user_info() because I don't think it would be good to have it as a parameter for that function.
So I would like to be able to retrieve the argparse arguments I got from utils.parse_arguments() directly. Is there a way to do that?
Like the suggestion my comment and Mike Müller's answer, the below code sets a module-level variable.
To prevent argument parsing upon import, however, I set the variable only once
parse_argumentsis called. Since the variable is set toNonebefore that happens, I also only import the variable when needed.This way,
parse_argumentsis only run when you call it, not when you import the module. It is probably not needed in your specific case, but can be convenient when e.g. a module likeutilsis used in a package.utils.py:client.py: