[Commands Module] Improve usability of type hints #3410
No reviewers
Labels
No labels
Automated PR
Blocked
Blocked By: Damage Control
Blocked By: Dependency
Blocked By: Other PR
Breaking Change
Category: CI
Category: Cogs - Admin
Category: Cogs - Alias
Category: Cogs - Audio
Category: Cogs - Bank
Category: Cogs - Cleanup
Category: Cogs - CustomCommands
Category: Cogs - Dev
Category: Cogs - Downloader
Category: Cogs - Economy
Category: Cogs - Filter
Category: Cogs - General
Category: Cogs - Image
Category: Cogs - Mod
Category: Cogs - Modlog
Category: Cogs - Mutes
Category: Cogs - Permissions
Category: Cogs - Reports
Category: Cogs - Streams
Category: Cogs - Trivia
Category: Cogs - Trivia - Lists
Category: Cogs - Warnings
Category: Core - API - App Commands Package
Category: Core - API - Audio
Category: Core - API - Bank
Category: Core - API - Commands Package
Category: Core - API - Config
Category: Core - API - Other
Category: Core - API - Utils Package
Category: Core - Bot Class
Category: Core - Bot Commands
Category: Core - Command-line Interfaces
Category: Core - Downloader
Category: Core - Help
Category: Core - i18n
Category: Core - Modlog
Category: Core - Other Internals
Category: Core - RPC/ZMQ
Category: Docker
Category: Docs - Changelogs
Category: Docs - For Developers
Category: Docs - Install Guides
Category: Docs - Other
Category: Docs - User Guides
Category: Meta
Category: RPC/ZMQ methods
Category: Vendored Packages
Changelog Entry: Added
Changelog Entry: Pending
Changelog Entry: Skipped
Closed: Duplicate
Closed: External
Closed: Invalid
Closed: User Error
Closed: Won't Fix
Complex Issue
Docs-only
Feature Branch
Good First Issue
Help Wanted
High Priority
Needs Backport To stable-docs
No Activity
No Repro
QA: Bypassed
QA: Changes Requested
QA: Passed
Release Blocker
Status: Accepted
Status: Frozen
Status: In Progress
Status: Needs Discussion
Status: Needs Info
Status: Needs Triage
Status: PRs Welcome
Type: Bug
Type: Dependency Update
Type: Deprecation
Type: Enhancement
Type: Feature
Type: Informational
Type: Merge
Type: Optimisation
Type: Question
Type: Removal
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
Mrcoolgamer11/Red-DiscordBot!3410
Loading…
Reference in a new issue
No description provided.
Delete branch "typehint-improvements"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Type
Description of the changes
This does a few things, but this should be safe enough as is.
Lying to mypy while shadowing the commands module like this is proving to be problematic
We get a lot of benefits from type analysis if we can get this right, but we may need to not shadow discord.py's commands module anymore.
This should no longer be failing, and also not break anyone, but long term we need some more robust handling of this.And now we're looking at a breaking version anyhow...
So, the strain on cog creators for this is something we can hopefully avoid. I'm putting more effort into doing this in a way which may add marginally to our dep update process, but should be otherwise fine and gain in usability and maintainability.
I looked to see if there are any names that have disappeared after applying this changes and those would be the module names from discord.ext.commands:
bot,cog,cooldowns,core,viewWhile I think it's not that good to keep those here forever, it would technically be a breaking change, so we might want to keep them here for now and remove later when doing Red 3.3.
sigh okay will add those in later this evening.
Technically breaking again.
Scope of breakage is limited to people importing discord.py submodules (not classes/funcs/etc) from redbot.core and people directly using
PermissionState.TRANSITIONSandPermissionState.ALLOWED_STATES, and people declaring coroutines using the asyncio.coroutine decorator (we're python 3.8+, please don't be doing this) for use as command objectsFound few small problems with d.py reimplements and have few small questions.
Also not included in review comments, but do we want to privatize some parts of
redbot.core.commands.requiresto be able to avoid minor bump when the only changes are in internal stuff?@ -302,0 +309,4 @@else:def get_timedelta_converter(Why is this branch needed if type hints are exactly the same?
@ -302,0 +420,4 @@.. warning::This converter class is still provisional.Why is this branch needed if type hints are exactly the same?
Why is this not using dot notation?
Why is this not using dot notation?
Implementation in d.py seems to have this instead:
Implementation in d.py seems to have this instead:
This will make decorators stop working with generator-based coros (
@asyncio.coroutine).I'm completely fine with this, especially that they're deprecated since Python 3.8 but I think this is technically also a breaking change which should be mentioned as part of the warning just in case.
Intentional. Mypy doesn't appreciate dynamic access to attributes which aren't declared
@ -302,0 +309,4 @@else:def get_timedelta_converter(type hints are the same, but there's a dynamic class declaration inside which mypy doesn't allow. For the sake of people using this, making it not appear dynamic since external to the function, the typing is fine.
K, this is on hold till the discord.py version bump then, and we'll do a wrap up with anything we have ready around then.
rebased over other newer changes.
I didn't look much at
callbackdefinition, but this breaks:With traceback:
I can't get
commands.Literalto work, example code that doesn't work for me:All I get when using
[p]somecom fooisConverting to "Literal" failed for parameter "test".Edit: I was able to get this to work after subclassing
Literalclass fromcommands.Converter.Also, this will have an unexpected behavior when only one argument is passed to
Literal- you get a string not tuple passed to__class_getitem__then which means you're checking if passed arg is a substring.You only import the converter but didn't use it.
This hasn't been documented.
@ -254,7 +265,7 @@ class Context(commands.Context):return pattern.sub(f"@{me.display_name}", self.prefix)These 2 classes aren't documented (not specified in
framework_commands.rstfile and placed underif TYPE_CHECKING).@ -149,2 +170,4 @@.. warning::This will be removed in version 3.4."""This suggestion and the one below can only be applied together as I changed the order.
This suggestion and the one above can only be applied together as I changed the order.
Also, if
ignore_optional_for_conversiongets documented, this should be a proper reference to that option.This isn't documented because of the place it is in (under
if TYPE_CHECKING:)Now these are just me being picky, feel free to ignore those, but it's just a matter of merging suggestions.
@ -149,2 +170,4 @@.. warning::This will be removed in version 3.4."""Two more nitpicks, might as well add them to the list 😛
@ -149,2 +170,4 @@.. warning::This will be removed in version 3.4."""Soooo, there's a workaround for the issue with
RedOptionalandLiteralbeing exported incorrectly...Re-exporting when importing (
from typing import Optional as RedOptional) and usingif not TYPE_CHECKING:to define implementation at runtime would make it work properly.Just FYI, I reverted changes to
kickban.py, I didn't actually plan to do this for you but my tools betrayed me... Ekhm, anyhow, changes to that file don't really fit into this PR after it no longer is replaced withUserInputOptional+ #3437 will get rid of thecastthat I think you wanted to get rid of.Still planning to do the actual review tomorrow 😄
No worries, I left the PR editable intentionally, sound reversion if it simplifies things.
If you care about fixing
func.__requires*stuff in this PR, feel free to but I didn't find it important enough to put review comments on stuff that needssetattr()use as it's not important to have it in this PR.mypy screams about the redefinitions of those later in the code ("All conditional function variants must have identical signatures"), one possible solution for this would be putting those imports here under
if not TYPE_CHECKINGDo we want to define our own versions of those instead of just putting typed variants under
if TYPE_CHECKINGand re-exporting the ones from d.py?These ones aren't conditionally defined.
Conditional import is fine here. It may be ugly, but the point is for this to work for our users and devs, if a little bit more ugly importing in this module is needed for it, that's fine.
Aside from stuff I put in review comments, we also need to type hint decorators in
requires-bot_has_permissions,has_permissions,is_owner, ...And it would also be good to type-hint
@commands.command()/@commands.group()as even with d.py stubs we still end up with our own deco untyped. But I don't remember full story on why you removed the type hints from those in first place so I am probably missing something here.There are also some things that I want to ask about but that are gonna be easier to discuss in discord.
This needs cast or assert.
This needs cast or assert.
@ -263,3 +274,63 @@ class Context(commands.Context):return self.guild.me@ -138,17 +160,18 @@ class APIToken(discord.ext.commands.Converter):This will parse the input argument separating the key value pairs into a@ -162,140 +185,262 @@ class APIToken(discord.ext.commands.Converter):return resultNot part of PR but since I noticed it, figured I can mention it 🤷♂
Not part of PR but since I noticed it, figured I can mention it 🤷♂
Would be convenient to have this reference the option for ease of navigation. I checked and this will get referenced properly by sphinx without adding anything.
This type is supposed to represent both
commands.CommandandCallable[..., Awaitable[Any]]], otherwise developers are gonna run into issues when they use check decorators before@commands.command()so I think this shouldn't be left like that unless I'm missing something here.@ -248,13 +252,18 @@ PermState.TRANSITIONS = {PermState.ACTIVE_DENY: (False, PermState.ACTIVE_DENY),},Since this is supposed to be public, shouldn't it be added to
__all__?Since this is supposed to be public, shouldn't it be added to
__all__?Since this is supposed to be public, shouldn't it be added to
__all__?Resolved most of the remaining issues, some are small things that we can (and will) continue improving on. The commit has been rebased down to a single commit over V3/develop for sanity purposes with how many revisions this entailed.
@ -254,7 +265,7 @@ class Context(commands.Context):return pattern.sub(f"@{me.display_name}", self.prefix)I've put this back for now, but I'm not entirely sure we should be encouraging decorator orders which don't stack logically as these end up doing assignments to function objects which gets much more difficult to write good typing for.