The code below calls the parse_config()
function which populates the global variables user
, passwd
and host
which are later used in main()
function:
#!/usr/bin/env python3
import sys
import configparser
def parse_config(cfg):
"""
Read the configuration file.
"""
global user, passwd, host
if cfg.has_option('login', 'username'):
user = cfg['login']['username']
else:
sys.exit(1)
if cfg.has_option('login', 'password'):
passwd = cfg['login']['password']
else:
sys.exit(1)
if cfg.has_option('server', 'host'):
host = cfg['server']['host']
else:
host = 'localhost'
def main():
config = configparser.ConfigParser()
with open('conf.ini', encoding='utf-8') as conf_f:
config.read_file(conf_f)
parse_config(config)
print(f'username: {user}, password: {passwd}, host: {host}')
if __name__ == '__main__':
main()
As using the global variables is not encouraged, then how should one rewrite this script? Perhaps by returning the local variables from the parse_config()
function? Like this:
#!/usr/bin/env python3
import sys
import configparser
def parse_config(cfg):
"""
Read the configuration options.
"""
if cfg.has_option('login', 'username'):
user = cfg['login']['username']
else:
sys.exit(1)
if cfg.has_option('login', 'password'):
passwd = cfg['login']['password']
else:
sys.exit(1)
if cfg.has_option('server', 'host'):
host = cfg['server']['host']
else:
host = 'localhost'
return user, passwd, host
def main():
config = configparser.ConfigParser()
with open('conf.ini', encoding='utf-8') as conf_f:
config.read_file(conf_f)
user, passwd, host = parse_config(config)
print(f'username: {user}, password: {passwd}, host: {host}')
if __name__ == '__main__':
main()
Or perhaps it's fine to use global variables in this case?