I have created a singleton wrapper for the selenium webdriver.
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Driver(metaclass=Singleton):
"""Ensures theres only 1 Driver open at any time.
If the driver is closed, tries to quit the previous
instance, and recreates a new one"""
def __init__(self):
self._driver = self.load_selenium_driver()
@staticmethod
def load_selenium_driver():
_chrome_driver_locn = CHROME_DRIVER_LOCATION
_driver = webdriver.Chrome(_chrome_driver_locn)
return _driver
@property
def driver(self):
"""Creates a new driver if the previous one is closed,
and quits the instance of the chrome driver."""
if self._web_browser_is_open():
return self._driver
else:
try:
self._driver.quit()
finally:
self._driver = self.load_selenium_driver()
return self._driver
def _web_browser_is_open(self):
try:
self._driver.title
return True
except WebDriverException:
return False
Running a = Driver()
I want to access the Driver.driver
methods, in a
, so that I don't need to do a.driver.get('google.com')
, but a.get('google.com')
.
The question:
How do I make an instance of Driver, return the driver
object (found in the property Driver.driver
), rather than the instance of the Driver
?