Skip to content

Commit 5876497

Browse files
authored
chore: fixed some Python types and Dicts (microsoft#14)
Fixes microsoft#3
1 parent 6001f1a commit 5876497

15 files changed

+89
-31
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@ dist/
1010
env/
1111
htmlcov/
1212
.coverage
13+
.DS_Store

README.md

+5
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,11 @@ python ./build_package.py
6363
python ./upload_package.py
6464
```
6565

66+
Checking for typing errors
67+
```sh
68+
mypy playwright_web
69+
```
70+
6671
# Contributing
6772

6873
This project welcomes contributions and suggestions. Most contributions require you to agree to a

local-requirements.txt

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1-
pytest
2-
pytest-asyncio
3-
pytest-cov
1+
pytest==5.4.3
2+
pytest-asyncio==0.14.0
3+
pytest-cov==2.10.0
4+
mypy==0.782

playwright_web/browser_context.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@
1818
from playwright_web.network import Request, Response, Route
1919
from playwright_web.page import BindingCall, Page
2020
from types import SimpleNamespace
21-
from typing import Any, Callable, Dict, List, Optional, Union
21+
from typing import Any, Callable, Dict, List, Optional, Union, TYPE_CHECKING
22+
23+
if TYPE_CHECKING:
24+
from playwright_web.browser import Browser
2225

2326
class BrowserContext(ChannelOwner):
2427

@@ -83,8 +86,6 @@ async def newPage(self) -> Page:
8386
async def cookies(self, urls: Union[str, List[str]]) -> List[Cookie]:
8487
if urls == None:
8588
urls = list()
86-
if urls and isinstance(urls, list):
87-
urls = [ urls ]
8889
return await self._channel.send('cookies', dict(urls=urls))
8990

9091
async def addCookies(self, cookies: List[Cookie]) -> None:

playwright_web/connection.py

-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
from playwright_web.helper import parse_error
1717
from playwright_web.transport import Transport
1818
from pyee import BaseEventEmitter
19-
from types import SimpleNamespace
2019
from typing import Any, Awaitable, Dict, List, Optional
2120

2221

playwright_web/download.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,4 @@ async def failure(self) -> Optional[str]:
3535
return await self._channel.send('failure')
3636

3737
async def path(self) -> Optional[str]:
38-
await self._channel.send('path')
38+
return await self._channel.send('path')

playwright_web/element_handle.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,10 @@
1616
from playwright_web.connection import Channel, ChannelOwner, ConnectionScope, from_nullable_channel
1717
from playwright_web.helper import ConsoleMessageLocation, FilePayload, SelectOption, locals_to_params
1818
from playwright_web.js_handle import parse_result, serialize_argument, JSHandle
19-
from typing import Any, Dict, List, Optional, Union
19+
from typing import Any, Dict, List, Optional, Union, TYPE_CHECKING
20+
21+
if TYPE_CHECKING:
22+
from playwright_web.frame import Frame
2023

2124
class ElementHandle(JSHandle):
2225

playwright_web/file_chooser.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,12 @@
1313
# limitations under the License.
1414

1515
from playwright_web.helper import FilePayload
16-
from typing import Dict, List, Union
16+
17+
from typing import Dict, List, Union, TYPE_CHECKING
18+
19+
if TYPE_CHECKING:
20+
from playwright_web.page import Page
21+
from playwright_web.element_handle import ElementHandle
1722

1823
class FileChooser():
1924

playwright_web/frame.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@
1818
from playwright_web.helper import ConsoleMessageLocation, FilePayload, SelectOption, is_function_body, locals_to_params
1919
from playwright_web.js_handle import JSHandle, parse_result, serialize_argument
2020
from playwright_web.network import Request, Response, Route
21-
from typing import Any, Awaitable, Dict, List, Optional, Union
21+
from typing import Any, Awaitable, Dict, List, Optional, Union, TYPE_CHECKING
22+
23+
if TYPE_CHECKING:
24+
from playwright_web.page import Page
2225

2326
class Frame(ChannelOwner):
2427

playwright_web/helper.py

+39-9
Original file line numberDiff line numberDiff line change
@@ -17,20 +17,50 @@
1717
import fnmatch
1818
import re
1919

20-
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
21-
# from typing import TypedDict
20+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union, TYPE_CHECKING
21+
22+
import sys
23+
24+
if sys.version_info >= (3, 8):
25+
from typing import TypedDict # pylint: disable=no-name-in-module
26+
else:
27+
from typing_extensions import TypedDict
28+
29+
30+
if TYPE_CHECKING:
31+
from playwright_web.network import Route, Request
2232

2333
Cookie = List[Dict[str, Union[str, int, bool]]]
2434
URLMatch = Union[str, Callable[[str], bool]]
25-
FilePayload = Dict # TypedDict('FilePayload', name=str, mimeType=str, buffer=bytes)
26-
FrameMatch = Dict # TypedDict('FrameMatch', url=URLMatch, name=str)
27-
PendingWaitEvent = Dict # TypedDict('PendingWaitEvent', event=str, future=asyncio.Future)
2835
RouteHandler = Callable[['Route', 'Request'], None]
29-
RouteHandlerEntry = Dict # TypedDict('RouteHandlerEntry', matcher=URLMatcher, handler=RouteHandler)
30-
SelectOption = Dict # TypedDict('SelectOption', value=Optional[str], label=Optional[str], index=Optional[str])
31-
ConsoleMessageLocation = Dict #TypedDict('ConsoleMessageLocation', url=Optional[str], lineNumber=Optional[int], columnNumber=Optional[int])
3236
FunctionWithSource = Callable[[Dict], Any]
33-
ErrorPayload = Dict # TypedDict('ErrorPayload', message=str, name=str, stack=str, value=Any)
37+
class FilePayload(TypedDict):
38+
name: str
39+
mimeType: str
40+
buffer: bytes
41+
class FrameMatch(TypedDict):
42+
url: URLMatch
43+
name: str
44+
class PendingWaitEvent(TypedDict):
45+
event: str
46+
future: asyncio.Future
47+
48+
class RouteHandlerEntry(TypedDict):
49+
matcher: "URLMatcher"
50+
handler: RouteHandler
51+
class SelectOption(TypedDict):
52+
value: Optional[str]
53+
label: Optional[str]
54+
index: Optional[str]
55+
class ConsoleMessageLocation(TypedDict):
56+
url: Optional[str]
57+
lineNumber: Optional[int]
58+
columnNumber: Optional[int]
59+
class ErrorPayload(TypedDict):
60+
message: str
61+
name: str
62+
stack: str
63+
value: Any
3464

3565
class URLMatcher:
3666
def __init__(self, match: URLMatch):

playwright_web/js_handle.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@
1717
from datetime import datetime
1818
from playwright_web.connection import Channel, ChannelOwner, ConnectionScope, from_channel
1919
from playwright_web.helper import ConsoleMessageLocation, Error, is_function_body
20-
from typing import Any, Dict, List, Optional
20+
from typing import Any, Dict, List, Optional, TYPE_CHECKING
21+
22+
if TYPE_CHECKING:
23+
from playwright_web.element_handle import ElementHandle
2124

2225
class JSHandle(ChannelOwner):
2326

playwright_web/network.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,10 @@
1616
import json
1717
from playwright_web.connection import Channel, ChannelOwner, ConnectionScope, from_nullable_channel, from_channel
1818
from playwright_web.helper import Error
19-
from typing import Awaitable, Dict, List, Optional, Union
19+
from typing import Awaitable, Dict, List, Optional, Union, TYPE_CHECKING
20+
21+
if TYPE_CHECKING:
22+
from playwright_web.frame import Frame
2023

2124
class Request(ChannelOwner):
2225

@@ -69,7 +72,7 @@ def redirectedTo(self) -> Optional['Request']:
6972
return self._redirected_to
7073

7174
@property
72-
def failure(self) -> Optional[str]:
75+
def failure(self) -> Optional[str]:
7376
return self._failure_text
7477

7578

playwright_web/page.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,10 @@
2929
from playwright_web.network import Request, Response, Route
3030
from playwright_web.worker import Worker
3131
from types import SimpleNamespace
32-
from typing import Any, Awaitable, Callable, Dict, List, Union
32+
from typing import Any, Awaitable, Callable, Dict, List, Union, TYPE_CHECKING
33+
34+
if TYPE_CHECKING:
35+
from playwright_web.browser_context import BrowserContext
3336

3437
class Page(ChannelOwner):
3538

@@ -296,7 +299,7 @@ def predicate(request: Request):
296299

297300
async def waitForResponse(self, urlOrPredicate: Union[str, Callable[[Request], bool]]) -> Optional[Response]:
298301
matcher = URLMatcher(urlOrPredicate) if isinstance(urlOrPredicate, str) else None
299-
def predicate(request: Request):
302+
def predicate(request: Request):
300303
if matcher:
301304
return matcher.matches(request.url())
302305
return urlOrPredicate(request)
@@ -498,7 +501,7 @@ async def waitForFunction(self,
498501
if not is_function_body(expression):
499502
force_expr = True
500503
return await self._main_frame.waitForFunction(**locals_to_params(locals()))
501-
504+
502505
def workers(self) -> List[Worker]:
503506
return self._workers.copy()
504507

playwright_web/transport.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@
2222
class Transport:
2323
def __init__(self, input: asyncio.StreamReader, output: asyncio.StreamWriter, loop: asyncio.AbstractEventLoop) -> None:
2424
super().__init__()
25-
self._input = input
26-
self._output = output
27-
self.loop = loop
25+
self._input: asyncio.StreamReader = input
26+
self._output: asyncio.StreamWriter = output
27+
self.loop: asyncio.AbstractEventLoop = loop
2828
self.on_message = lambda _: None
2929
loop.create_task(self._run())
3030

@@ -50,11 +50,11 @@ async def _run(self) -> None:
5050
if 'DEBUG' in os.environ:
5151
print('\x1b[33mRECV>\x1b[0m', obj.get('method'))
5252
self.on_message(obj)
53-
except asyncio.streams.IncompleteReadError:
53+
except asyncio.IncompleteReadError:
5454
break
5555
await asyncio.sleep(0)
5656

57-
def send(self, message: Dict) -> Awaitable:
57+
def send(self, message: Dict) -> None:
5858
msg = json.dumps(message)
5959
if 'DEBUGP' in os.environ:
6060
print('\x1b[32mSEND>\x1b[0m', json.dumps(message, indent=2))

setup.py

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
include_package_data=True,
3131
install_requires=[
3232
'pyee',
33+
'typing-extensions',
3334
],
3435
classifiers=[
3536
'Programming Language :: Python :: 3',

0 commit comments

Comments
 (0)