Skip to content

Commit

Permalink
Fix compatibility with Python 3.11
Browse files Browse the repository at this point in the history
Code objects have some new attributes. Those are related
to the enhanced exceptions with code highlighting.
  • Loading branch information
frenzymadness committed Mar 17, 2022
1 parent 9a0013e commit c9d6749
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 25 deletions.
18 changes: 17 additions & 1 deletion cloudpickle/cloudpickle_fast.py
Expand Up @@ -244,7 +244,23 @@ def _enum_getstate(obj):

def _code_reduce(obj):
"""codeobject reducer"""
if hasattr(obj, "co_linetable"): # pragma: no branch
# If you are not sure about the order of arguments, take a look at help
# of the specific type from types, for example:
# >>> from types import CodeType
# >>> help(CodeType)
if hasattr(obj, "co_columntable"): # pragma: no branch
# Python 3.11 and later: there are some new attributes
# related to the enhanced exceptions.
args = (
obj.co_argcount, obj.co_posonlyargcount,
obj.co_kwonlyargcount, obj.co_nlocals, obj.co_stacksize,
obj.co_flags, obj.co_code, obj.co_consts, obj.co_names,
obj.co_varnames, obj.co_filename, obj.co_name, obj.co_qualname,
obj.co_firstlineno, obj.co_linetable, obj.co_endlinetable,
obj.co_columntable, obj.co_exceptiontable, obj.co_freevars,
obj.co_cellvars,
)
elif hasattr(obj, "co_linetable"): # pragma: no branch
# Python 3.10 and later: obj.co_lnotab is deprecated and constructor
# expects obj.co_linetable instead.
args = (
Expand Down
30 changes: 7 additions & 23 deletions tests/cloudpickle_test.py
Expand Up @@ -2386,29 +2386,13 @@ def method(self, arg: type_) -> type_:

def check_annotations(obj, expected_type, expected_type_str):
assert obj.__annotations__["attribute"] == expected_type
if sys.version_info >= (3, 11):
# In Python 3.11, type annotations are stored as strings.
# See PEP 563 for more details:
# https://www.python.org/dev/peps/pep-0563/
# Originaly scheduled for 3.10, then postponed.
# See this for more details:
# https://mail.python.org/archives/list/python-dev@python.org/thread/CLVXXPQ2T2LQ5MP2Y53VVQFCXYWQJHKZ/
assert (
obj.method.__annotations__["arg"]
== expected_type_str
)
assert (
obj.method.__annotations__["return"]
== expected_type_str
)
else:
assert (
obj.method.__annotations__["arg"] == expected_type
)
assert (
obj.method.__annotations__["return"]
== expected_type
)
assert (
obj.method.__annotations__["arg"] == expected_type
)
assert (
obj.method.__annotations__["return"]
== expected_type
)
return "ok"

obj = MyClass()
Expand Down
2 changes: 1 addition & 1 deletion tox.ini
@@ -1,5 +1,5 @@
[tox]
envlist = py35, py36, py37, py38, py39, py310, pypy3
envlist = py35, py36, py37, py38, py39, py310, py311, pypy3

[testenv]
deps = -rdev-requirements.txt
Expand Down

0 comments on commit c9d6749

Please sign in to comment.