Shorter type hints for long types

Viewed 260

(Excuse the bad title, maybe someone can suggest a better one)

Just getting into typehinting/typechecking and wanted to add on for a function to which I'm passing a selenium webdriver object which shows:

In:  type(driver)
Out: selenium.webdriver.chrome.webdriver.WebDriver

Is there a way it can be made shorter without typing the whole thing? (no pun intended)

I found about about aliases and wanted to know if it is safe to use something like:

WebDriver = selenium.webdriver.chrome.webdriver.WebDriver
WebElement = selenium.webdriver.remote.webelement.WebElement

# Function definition follows:
def get_object(driver: WebDriver, ....) -> WebElement:
    ...

Two questions remain:

  • Do I need to manually create the aliases or is there an easier way to do it?
  • Notice the alias name and the last part of the type is kept the same for easy identification. Safe or no?
1 Answers

The pythononic-way to do this is changing the imports line:

from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement

# Function definition follows:
def get_object(driver: WebDriver, ....) -> WebElement:
Related