Python 3.11 Changes
In [Packaging] Support Python 3.11 by bebound · Pull Request #26923 · Azure/azure-cli (github.com) , I bumped azure-cli to use Python 3.11. We’ve bump the dependency in other PRs, I thought it should be a small PR, but in the end, a lot of changes are made.
args.getargspec
getargspec is dropped in 3.11. You can easily replaced it with getfullargspec . It returns FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations) instead of ArgSpec(args, varargs, keywords, defaults) So args, _, kw, _ = inspect.getargspec(fn) can be replaced by args, _, kw, *_ = inspect.getfullargspec(fn) However, getfullargspec is retained primarily for use in code that needs to maintain compatibility with the Python 2 inspect module API.
Note that
signature()and Signature Object provide the recommended API for callable introspection, and support additional behaviours (like positional-only arguments) that are sometimes encountered in extension module APIs. This function is retained primarily for use in code that needs to maintain compatibility with the Python 2inspectmodule API. –inspect — Inspect live objects — Python 3.11.4 documentation
The modern signature function provides the similar result but needs more modification:
| |
| |
Enum __format__ change
There is some custom classes in azure-cli, which makes Foo.BAR=‘bar’. In 3.11, the [[https://docs.python.org/3/whatsnew/3.11.html#enum][Enum]] =__format__() changes, it returns the enum and member name (ex: Color.RED). (The __str__ method is the same as Python 3.10)
Changed
Enum.__format__()(the default forformat(),str.format()and f-strings) to always produce the same result asEnum.__str__(): for enums inheriting fromReprEnumit will be the member’s value; for all other enums it will be the enum and member name (e.g.Color.RED). –What’s New In Python 3.11
| |
The standard way to replace Foo class is StrEnum
| |
If you also use Bar(int, Enum), you can replace it with ReprEnum: Bar(int, ReprEnum).
unittest.Mock
The unittest module replace unittest.mock._importer with pkgutil.resolve_name in bpo-44686 replace unittest.mock._importer with pkgutil.resolve_name by graingert · Pull Request #18544 · python/cpython (github.com), which also introduces some changes.
Previously, it use __import__ to import the patch target, which does not check the module name. But pkgutil.resolve_name will check name first, thus mock.patch fails if the target is not a valid Python module name. For example, this statement fails in 3.11:
| |
as 2020_09_01_hybrid is not a valid variable name in Python.
| |
As a workaround, mock.patch.object works.
| |
The ultimate solution is fix module name.
argparse.ArgumentError
bpo-39716: Raise on conflicting subparser names. by anntzer · Pull Request #18605 · python/cpython (github.com) Raise an ArgumentError when the same subparser name is added twice.
| |
The above code works on 3.10 but raises this error in 3.11:
| |