2
\$\begingroup\$

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)
    driver.set_page_load_timeout(timeout)
    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?

\$\endgroup\$
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – Peilonrayz Jan 22 '18 at 17:15
  • \$\begingroup\$ Peilonrayz, thank you for your comment. I have added my actual code. \$\endgroup\$ – x42ov Jan 23 '18 at 7:45
1
\$\begingroup\$

A global flag would be clear and simple:

_LOGGED_DRIVER = False

def init_chromedriver(path, timeout=30):
    driver = webdriver.Chrome(executable_path=path)
    driver.set_page_load_timeout(timeout)
    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)
    driver.set_page_load_timeout(timeout)
    return driver

def init_chromedriver(path, timeout=30):
    driver = _init_chromedriver(path, timeout)
    logger = logging.getLogger('driver')
    for k, v in driver.capabilities.items():
        logger.log(logging.INFO, f"{k}: {v}")
    global init_chromedriver
    init_chromedriver = _init_chromedriver
    return driver

But I think the global flag would be clearer.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.