Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve pyright support #1108

Merged
merged 12 commits into from
Apr 9, 2022
1 change: 1 addition & 0 deletions changes/1108.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improved pyright support by ignoring all errors that go against the design patterns of hikari.
4 changes: 2 additions & 2 deletions hikari/events/typing_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,12 @@ def user_id(self) -> snowflakes.Snowflake:
# <<inherited docstring from TypingEvent>>.
return self.member.id

async def fetch_channel(self) -> typing.Union[channels.TextableGuildChannel]:
async def fetch_channel(self) -> channels.TextableGuildChannel:
"""Perform an API call to fetch an up-to-date image of this channel.

Returns
-------
typing.Union[hikari.channels.TextableGuildChannel]
hikari.channels.TextableGuildChannel
The channel.
"""
channel = await super().fetch_channel()
Expand Down
2 changes: 1 addition & 1 deletion hikari/impl/buckets.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@ def do_gc_pass(self, expire_after: float) -> None:
`RESTBucketManager.start` and `RESTBucketManager.close` to control
this instead.
"""
buckets_to_purge = []
buckets_to_purge: typing.List[str] = []

now = time.monotonic()

Expand Down
9 changes: 4 additions & 5 deletions hikari/impl/entity_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,7 @@ def deserialize_implicit_token(self, query: data_binding.Query) -> application_m
def _deserialize_audit_log_change_roles(
self, payload: data_binding.JSONArray
) -> typing.Mapping[snowflakes.Snowflake, guild_models.PartialRole]:
roles = {}
roles: typing.Dict[snowflakes.Snowflake, guild_models.PartialRole] = {}
for role_payload in payload:
role = guild_models.PartialRole(
app=self._app, id=snowflakes.Snowflake(role_payload["id"]), name=role_payload["name"]
Expand Down Expand Up @@ -710,7 +710,7 @@ def deserialize_audit_log(self, payload: data_binding.JSONObject) -> audit_log_m
for entry_payload in payload["audit_log_entries"]:
entry_id = snowflakes.Snowflake(entry_payload["id"])

changes = []
changes: typing.List[audit_log_models.AuditLogChange] = []
if (change_payloads := entry_payload.get("changes")) is not None:
for change_payload in change_payloads:
key: typing.Union[audit_log_models.AuditLogChangeKey, str] = audit_log_models.AuditLogChangeKey(
Expand Down Expand Up @@ -1375,10 +1375,9 @@ def deserialize_member(
time.iso8601_datetime_string_to_datetime(raw_premium_since) if raw_premium_since is not None else None
)

communication_disabled_until: typing.Optional[datetime.datetime] = None
if raw_communication_disabled_until := payload.get("communication_disabled_until"):
communication_disabled_until = time.iso8601_datetime_string_to_datetime(raw_communication_disabled_until)
thesadru marked this conversation as resolved.
Show resolved Hide resolved
else:
communication_disabled_until = None

return guild_models.Member(
user=user,
Expand Down Expand Up @@ -2622,7 +2621,7 @@ def deserialize_member_presence( # noqa: CFQ001 - Max function length
*,
guild_id: undefined.UndefinedOr[snowflakes.Snowflake] = undefined.UNDEFINED,
) -> presence_models.MemberPresence:
activities = []
activities: typing.List[presence_models.RichActivity] = []
for activity_payload in payload["activities"]:
timestamps: typing.Optional[presence_models.ActivityTimestamps] = None
if "timestamps" in activity_payload:
Expand Down
9 changes: 5 additions & 4 deletions hikari/impl/event_manager_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
typing.List[event_manager_.CallbackT[base_events.EventT]],
]
_WaiterT = typing.Tuple[
typing.Optional[event_manager_.PredicateT[base_events.EventT]], asyncio.Future[base_events.EventT]
typing.Optional[event_manager_.PredicateT[base_events.EventT]], "asyncio.Future[base_events.EventT]"
davfsa marked this conversation as resolved.
Show resolved Hide resolved
]
_WaiterMapT = typing.Dict[typing.Type[base_events.EventT], typing.Set[_WaiterT[base_events.EventT]]]

Expand Down Expand Up @@ -103,8 +103,8 @@ def __events_bitmask__(self) -> int:

def _generate_weak_listener(
reference: weakref.WeakMethod[typing.Any],
) -> typing.Callable[[base_events.EventT], typing.Coroutine[typing.Any, typing.Any, None]]:
async def call_weak_method(event: base_events.EventT) -> None:
) -> typing.Callable[[base_events.Event], typing.Coroutine[typing.Any, typing.Any, None]]:
async def call_weak_method(event: base_events.Event) -> None:
davfsa marked this conversation as resolved.
Show resolved Hide resolved
method = reference()
if method is None:
raise TypeError(
Expand Down Expand Up @@ -555,7 +555,7 @@ def decorator(

return decorator

def dispatch(self, event: base_events.EventT) -> asyncio.Future[typing.Any]:
def dispatch(self, event: base_events.Event) -> asyncio.Future[typing.Any]:
if not isinstance(event, base_events.Event):
raise TypeError(f"Events must be subclasses of {base_events.Event.__name__}, not {type(event).__name__}")

Expand Down Expand Up @@ -613,6 +613,7 @@ async def wait_for(

future: asyncio.Future[base_events.EventT] = asyncio.get_running_loop().create_future()

waiter_set: typing.MutableSet[_WaiterT[base_events.Event]]
try:
waiter_set = self._waiters[event_type]
except KeyError:
Expand Down
2 changes: 1 addition & 1 deletion hikari/impl/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -762,7 +762,7 @@ async def _request(
)

if trace_logging_enabled:
time_taken = (time.monotonic() - start) * 1_000
time_taken = (time.monotonic() - start) * 1_000 # pyright: ignore[reportUnboundVariable]
_LOGGER.log(
ux.TRACE,
"%s %s %s in %sms\n%s",
Expand Down
6 changes: 3 additions & 3 deletions hikari/internal/attr_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def invalidate_deep_copy_cache() -> None:


def get_fields_definition(
cls: typing.Type[ModelT],
cls: type,
) -> typing.Tuple[
typing.Sequence[typing.Tuple[attr.Attribute[typing.Any], str]], typing.Sequence[attr.Attribute[typing.Any]]
]:
Expand All @@ -76,8 +76,8 @@ def get_fields_definition(
typing.Sequence[typing.Tuple[builtins.str, builtins.str]]
A sequence of tuples of string attribute names to string key-word names.
"""
init_results = []
non_init_results = []
init_results: typing.List[typing.Tuple[attr.Attribute[typing.Any], str]] = []
non_init_results: typing.List[attr.Attribute[typing.Any]] = []

for field in attr.fields(cls):
if field.init:
Expand Down
2 changes: 1 addition & 1 deletion hikari/internal/reflect.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def resolve_signature(func: typing.Callable[..., typing.Any]) -> inspect.Signatu

signature = inspect.signature(func)
resolved_typehints = typing.get_type_hints(func)
params = []
params: typing.List[inspect.Parameter] = []

none_type = type(None)
for name, param in signature.parameters.items():
Expand Down
4 changes: 2 additions & 2 deletions hikari/snowflakes.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def min(cls) -> Snowflake:
return cls.___MIN___

except AttributeError:
cls.___MIN___ = Snowflake(0)
cls.___MIN___ = Snowflake(0) # pyright: ignore[reportConstantRedefinition]
return cls.___MIN___

@classmethod
Expand All @@ -103,7 +103,7 @@ def max(cls) -> Snowflake:
return cls.___MAX___

except AttributeError:
cls.___MAX___ = Snowflake((1 << 63) - 1)
cls.___MAX___ = Snowflake((1 << 63) - 1) # pyright: ignore[reportConstantRedefinition]
return cls.___MAX___

@classmethod
Expand Down
19 changes: 18 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,27 @@ exclude_lines = [
]

[tool.pyright]
include = ["examples", "hikari"]
thesadru marked this conversation as resolved.
Show resolved Hide resolved
include = ["hikari", "examples"]
exclude = ["examples/simple_dashboard.py", "**/__init__.py", "hikari/internal/enums.py", "hikari/internal/fast_protocol.py"]
thesadru marked this conversation as resolved.
Show resolved Hide resolved
pythonVersion = "3.8"
typeCheckingMode = "strict"

reportUnnecessaryTypeIgnoreComment = "error"
reportMissingTypeStubs = "none"
reportImportCycles = "none" # Doesn't account for TYPE_CHECKING
reportIncompatibleMethodOverride = "none" # This relies on ordering for keyword-only arguments
reportOverlappingOverload = "none" # Type-Vars in last overloads may interfere
reportIncompatibleVariableOverride = "none" # Cannot overwrite abstract properties using attrs
thesadru marked this conversation as resolved.
Show resolved Hide resolved

# Attrs validators will always be unknown
reportUnknownMemberType = "warning"
reportUntypedFunctionDecorator = "warning"
reportOptionalMemberAccess = "warning"

# for mypy
reportUnnecessaryIsInstance = "none"
thesadru marked this conversation as resolved.
Show resolved Hide resolved


[tool.pytest.ini_options]
asyncio_mode = "strict"
xfail_strict = true
Expand Down