# Mutable default argument usage

I have a function that returns a ChromeDriver instance and logs browser information only once in a session:

from selenium import webdriver
def init_chromedriver(path, timeout=30, _l=[]):
driver = webdriver.Chrome(executable_path=path)
if not _l:
_l.append(None)
logger = logging.getLogger('driver')
for k, v in driver.capabilities.items():
logger.log(logging.INFO, f"{k}: {v}")
return driver


Is it a good practice or should I use another method?

• Is this actually your code? Cause some_args isn't used, and I doubt you'd be using webdriver.Chrome(...). If it's not, then please include your actual code. – Peilonrayz Jan 22 '18 at 17:15
• Peilonrayz, thank you for your comment. I have added my actual code. – x42ov Jan 23 '18 at 7:45

A global flag would be clear and simple:

_LOGGED_DRIVER = False

def init_chromedriver(path, timeout=30):
driver = webdriver.Chrome(executable_path=path)
global _LOGGED_DRIVER
if not _LOGGED_DRIVER:
_LOGGED_DRIVER = True
logger = logging.getLogger('driver')
for k, v in driver.capabilities.items():
logger.log(logging.INFO, f"{k}: {v}")
return driver


Alternatively, you could replace the function after it has been called for the first time:

def _init_chromedriver(path, timeout=30):
driver = webdriver.Chrome(executable_path=path)