Search code examples
pythonplaywrightpython-typing

Playwright typing annotation


Despite being for informational use, I am trying to setup typing annotations on my script, as it helps me to debug it later.

I am trying to set up Playwright's browser and context as the return of the following code, but I am not being successful:

import asyncio
from playwright.async_api import async_playwright

async def run_browser() : 
    p = await async_playwright().start()
    browser = await p.chromium.launch(headless=False)
    context = await browser.new_context(java_script_enabled=True,locale='pt-br')
    return context, p

What would I have to set on the -> type?


Solution

  • This Playwright 1.40.0 code passes Pyright 1.1.343 on Python 3.10.12:

    import asyncio
    from playwright.async_api import async_playwright, BrowserContext, Playwright
    
    
    async def run_browser() -> tuple[BrowserContext, Playwright]:
        p = await async_playwright().start()
        browser = await p.chromium.launch(headless=False)
        context = await browser.new_context(java_script_enabled=True, locale="pt-br")
        return context, p
    

    See also Automatically generating Python type annotations?.