'How should I write the hints of variable type when there are multiple variable types or classes accepted in python? [duplicate]
I want to make use of the hint (or maybe also called annotation?) of python to make easier my coding getting the functions of a class. Therefore I was using something like the following:
def convert_to_string(my_integer_number: int) -> str:
return str(my_integer_number)
But now I'm working with selenium and I have multiple classes that can be accepted for the same code, for example:
import webdriver
def get_driver(browser = DEFAULT_BROWSER, headless=False) -> \
webdriver.Chrome or webdriver.Firefox or webdriver.Edge:
"""
Returns a selenium webdriver:
* browser: Available options are 'chrome', 'edge' and 'firefox'
"""
if browser == 'chrome':
return webdriver.Chrome(
#....
)
if browser == 'firefox':
return webdriver.Firefox(
...
)
if browser == 'edge':
return webdriver.Edge(
...
)
And then in the functions where make use of one of the returned drivers:
def access_login_page(driver: webdriver.Chrome or webdriver.Firefox or webdriver.Edge) -> None:
"""
Access the login page using the header menu
"""
ELEMENT_ID = 'header-sign-in'
try:
element: WebElement = WebDriverWait(driver, timeout=30).until(
EC.element_to_be_clickable((By.ID, ELEMENT_ID))
)
This looks like a lot of overhead but at the same time I find really usefull to have this information. Is this the correct approach to do this?
Solution 1:[1]
Use the typing module:
from typing import Union
import webdriver
...
def get_driver(browser = DEFAULT_BROWSER, headless=False) -> \
Union[webdriver.Chrome, webdriver.Firefox, webdriver.Edge]:
...
The typing module contains thin wrappers for built-in types and also things like Optional[<type>] (which is basically Union[<type>, None]), Any, Callable, etc.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arseny |
