Replies: 1 comment 1 reply
|
Feel free to submit one or more PRs. |
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
This is something that was partially discussed in:
#2459
When reviewing the v3.14 changelog I noticed:
#2951
To me, it would seem that by typing
registersaslist[int], two things happen:listhas functions that allow mutating that list, likereverse, making this and other functions prone to similar logic issueslist, which is mutable, that the function has ownership and thus permission to perform this mutation.If the object was instead typed as a
Sequence(slicing is used internally) we would flip that:In this way, we leverage the typing system to narrow the safe operations that are allowed on that object as these types of things are very easy to miss in code review and functional tests.
Using the older version of the now fixed function as an example, if I change the type:
We see the following:
(The bytearray stuff is unrelated, but likely due to object promotion that is deprecated in v2 python/mypy#15313)
This could be useful for public methods where we want to enforce this contractual agreement. Maybe there are some public functions where there is an expectation that these items get mutated on purpose, but maybe those should be specialized functions or return values.
I realize API contracts are difficult, especially when they could break compatibility, but widening the types usually eases that burden to some degree and follows the typing guidance from https://typing.python.org/en/latest/reference/best_practices.html#arguments-and-return-types. It does, however have a slight performance cost for any functions that expect to mutate objects in place vs making mutated copies so something that has to be balanced.
Anyway, figured I'd bring this up as an idea in case it seemed useful.
All reactions