Skip to content

Commit 5595b2b

Browse files
committed
Fix typing of Parser's unbound methods
All credit due to "Finite State Machine" on the typing gitter, they're the one who had the idea of trying to type `self` in case that would make mypy happy. Which it absolutely does. This does make that use pattern easier to recommend, as it's fully typed as well.
1 parent b9f74ec commit 5595b2b

2 files changed

Lines changed: 14 additions & 8 deletions

File tree

src/ua_parser/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -93,25 +93,25 @@ def __call__(self, ua: str, domains: Domain, /) -> PartialParseResult:
9393
"""
9494
return self.resolver(ua, domains)
9595

96-
def parse(self, ua: str) -> ParseResult:
96+
def parse(self: Resolver, ua: str) -> ParseResult:
9797
"""Convenience method for parsing all domains, and falling back to
9898
default values for all failures.
9999
"""
100100
return self(ua, Domain.ALL).complete()
101101

102-
def parse_user_agent(self, ua: str) -> Optional[UserAgent]:
102+
def parse_user_agent(self: Resolver, ua: str) -> Optional[UserAgent]:
103103
"""Convenience method for parsing the :class:`UserAgent` domain,
104104
falling back to the default value in case of failure.
105105
"""
106106
return self(ua, Domain.USER_AGENT).user_agent
107107

108-
def parse_os(self, ua: str) -> Optional[OS]:
108+
def parse_os(self: Resolver, ua: str) -> Optional[OS]:
109109
"""Convenience method for parsing the :class:`OS` domain, falling back
110110
to the default value in case of failure.
111111
"""
112112
return self(ua, Domain.OS).os
113113

114-
def parse_device(self, ua: str) -> Optional[Device]:
114+
def parse_device(self: Resolver, ua: str) -> Optional[Device]:
115115
"""Convenience method for parsing the :class:`Device` domain, falling
116116
back to the default value in case of failure.
117117
"""

tests/test_convenience_parser.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
1-
from ua_parser import Parser, ParseResult, PartialParseResult
1+
from ua_parser import Domain, Parser, ParseResult, PartialParseResult
2+
3+
4+
def resolver(s: str, d: Domain) -> PartialParseResult:
5+
return PartialParseResult(d, None, None, None, s)
26

37

48
def test_parser_utility() -> None:
59
"""Tests that ``Parser``'s methods to behave as procedural
610
helpers, for users who may not wish to instantiate a parser or
711
something.
812
9-
Sadly the typing doesn't really play nicely with that.
10-
1113
"""
12-
r = Parser.parse(lambda s, d: PartialParseResult(d, None, None, None, s), "a") # type: ignore
14+
15+
r = Parser.parse(resolver, "a")
1316
assert r == ParseResult(None, None, None, "a")
17+
18+
os = Parser.parse_os(resolver, "a")
19+
assert os is None

0 commit comments

Comments
 (0)