"vscode:/vscode.git/clone" did not exist on "8bc154893b0db64a31b4f1d03b3662562083625f"
Unverified Commit 6493f496 authored by Ralf W. Grosse-Kunstleve's avatar Ralf W. Grosse-Kunstleve Committed by GitHub
Browse files

Python 2 removal part 1: tests (C++ code is intentionally ~untouched) (#3688)



* `#error BYE_BYE_GOLDEN_SNAKE`

* Removing everything related to 2.7 from ci.yml

* Commenting-out Centos7

* Removing `PYTHON: 27` from .appveyor.yml

* "PY2" removal, mainly from tests. C++ code is not touched.

* Systematic removal of `u` prefix from `u"..."` and `u'...'` literals. Collateral cleanup of a couple minor other things.

* Cleaning up around case-insensitive hits for `[^a-z]py.*2` in tests/.

* Removing obsolete Python 2 mention in compiling.rst

* Proper `#error` for Python 2.

* Using PY_VERSION_HEX to guard `#error "PYTHON 2 IS NO LONGER SUPPORTED.`

* chore: bump pre-commit

* style: run pre-commit for pyupgrade 3+

* tests: use sys.version_info, not PY

* chore: more Python 2 removal

* Uncommenting Centos7 block (PR #3691 showed that it is working again).

* Update pre-commit hooks

* Fix pre-commit hook

* refactor: remove Python 2 from CMake

* refactor: remove Python 2 from setup code

* refactor: simplify, better static typing

* feat: fail with nice messages

* refactor: drop Python 2 C++ code

* docs: cleanup for Python 3

* revert: intree

revert: intree

* docs: minor touchup to py2 statement
Co-authored-by: default avatarHenry Schreiner <henryschreineriii@gmail.com>
Co-authored-by: default avatarAaron Gokaslan <skylion.aaron@gmail.com>
parent 46dcd9bc
# -*- coding: utf-8 -*-
import pytest
from pybind11_tests import ConstructorStats, UserType
......@@ -40,7 +39,7 @@ def test_pointers(msg):
1. (arg0: capsule) -> int
Invoked with: [1, 2, 3]
""" # noqa: E501 line too long
"""
)
assert m.return_null_str() is None
......
# -*- coding: utf-8 -*-
import pytest
import env
from pybind11_tests import ConstructorStats
from pybind11_tests import operators as m
......@@ -151,5 +149,4 @@ def test_overriding_eq_reset_hash():
def test_return_set_of_unhashable():
with pytest.raises(TypeError) as excinfo:
m.get_unhashable_HashMe_set()
if not env.PY2:
assert str(excinfo.value.__cause__).startswith("unhashable type:")
assert str(excinfo.value.__cause__).startswith("unhashable type:")
# -*- coding: utf-8 -*-
import pickle
import pytest
import env
from pybind11_tests import pickling as m
try:
import cPickle as pickle # Use cPickle on Python 2.7
except ImportError:
import pickle
@pytest.mark.parametrize("cls_name", ["Pickleable", "PickleableNew"])
def test_roundtrip(cls_name):
......
......@@ -87,7 +87,6 @@ TEST_SUBMODULE(pytypes, m) {
m.def("tuple_size_t", []() { return py::tuple{(py::size_t) 0}; });
m.def("get_tuple", []() { return py::make_tuple(42, py::none(), "spam"); });
#if PY_VERSION_HEX >= 0x03030000
// test_simple_namespace
m.def("get_simple_namespace", []() {
auto ns = py::module_::import("types").attr("SimpleNamespace")(
......@@ -96,7 +95,6 @@ TEST_SUBMODULE(pytypes, m) {
py::setattr(ns, "right", py::int_(2));
return ns;
});
#endif
// test_str
m.def("str_from_char_ssize_t", []() { return py::str{"red", (py::ssize_t) 3}; });
......@@ -423,12 +421,10 @@ TEST_SUBMODULE(pytypes, m) {
return py::memoryview::from_buffer(static_cast<void *>(nullptr), 1, "B", {}, {});
});
#if PY_MAJOR_VERSION >= 3
m.def("test_memoryview_from_memory", []() {
const char *buf = "\xff\xe1\xab\x37";
return py::memoryview::from_memory(buf, static_cast<py::ssize_t>(strlen(buf)));
});
#endif
// test_builtin_functions
m.def("get_len", [](py::handle h) { return py::len(h); });
......
# -*- coding: utf-8 -*-
from __future__ import division
import sys
import pytest
import env
import env # noqa: F401
from pybind11_tests import debug_enabled
from pybind11_tests import pytypes as m
......@@ -123,7 +120,6 @@ def test_tuple():
assert m.get_tuple() == (42, None, "spam")
@pytest.mark.skipif("env.PY2")
def test_simple_namespace():
ns = m.get_simple_namespace()
assert ns.attr == 42
......@@ -140,7 +136,7 @@ def test_str(doc):
assert doc(m.str_from_bytes) == "str_from_bytes() -> str"
class A(object):
class A:
def __str__(self):
return "this is a str"
......@@ -158,24 +154,14 @@ def test_str(doc):
malformed_utf8 = b"\x80"
if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
assert m.str_from_object(malformed_utf8) is malformed_utf8
elif env.PY2:
with pytest.raises(UnicodeDecodeError):
m.str_from_object(malformed_utf8)
else:
assert m.str_from_object(malformed_utf8) == "b'\\x80'"
if env.PY2:
with pytest.raises(UnicodeDecodeError):
m.str_from_handle(malformed_utf8)
else:
assert m.str_from_handle(malformed_utf8) == "b'\\x80'"
assert m.str_from_handle(malformed_utf8) == "b'\\x80'"
assert m.str_from_string_from_str("this is a str") == "this is a str"
ucs_surrogates_str = u"\udcc3"
if env.PY2:
assert u"\udcc3" == m.str_from_string_from_str(ucs_surrogates_str)
else:
with pytest.raises(UnicodeEncodeError):
m.str_from_string_from_str(ucs_surrogates_str)
ucs_surrogates_str = "\udcc3"
with pytest.raises(UnicodeEncodeError):
m.str_from_string_from_str(ucs_surrogates_str)
def test_bytes(doc):
......@@ -184,9 +170,7 @@ def test_bytes(doc):
assert m.bytes_from_string().decode() == "foo"
assert m.bytes_from_str().decode() == "bar"
assert doc(m.bytes_from_str) == "bytes_from_str() -> {}".format(
"str" if env.PY2 else "bytes"
)
assert doc(m.bytes_from_str) == "bytes_from_str() -> bytes"
def test_bytearray(doc):
......@@ -278,11 +262,6 @@ def test_constructors():
"""C++ default and converting constructors are equivalent to type calls in Python"""
types = [bytes, bytearray, str, bool, int, float, tuple, list, dict, set]
expected = {t.__name__: t() for t in types}
if env.PY2:
# Note that bytes.__name__ == 'str' in Python 2.
# pybind11::str is unicode even under Python 2.
expected["bytes"] = bytes()
expected["str"] = unicode() # noqa: F821
assert m.default_constructors() == expected
data = {
......@@ -300,11 +279,6 @@ def test_constructors():
}
inputs = {k.__name__: v for k, v in data.items()}
expected = {k.__name__: k(v) for k, v in data.items()}
if env.PY2: # Similar to the above. See comments above.
inputs["bytes"] = b"41"
inputs["str"] = 42
expected["bytes"] = b"41"
expected["str"] = u"42"
assert m.converting_constructors(inputs) == expected
assert m.cast_functions(inputs) == expected
......@@ -340,46 +314,39 @@ def test_non_converting_constructors():
def test_pybind11_str_raw_str():
# specifically to exercise pybind11::str::raw_str
cvt = m.convert_to_pybind11_str
assert cvt(u"Str") == u"Str"
assert cvt(b"Bytes") == u"Bytes" if env.PY2 else "b'Bytes'"
assert cvt(None) == u"None"
assert cvt(False) == u"False"
assert cvt(True) == u"True"
assert cvt(42) == u"42"
assert cvt(2 ** 65) == u"36893488147419103232"
assert cvt(-1.50) == u"-1.5"
assert cvt(()) == u"()"
assert cvt((18,)) == u"(18,)"
assert cvt([]) == u"[]"
assert cvt([28]) == u"[28]"
assert cvt({}) == u"{}"
assert cvt({3: 4}) == u"{3: 4}"
assert cvt(set()) == u"set([])" if env.PY2 else "set()"
assert cvt({3, 3}) == u"set([3])" if env.PY2 else "{3}"
valid_orig = u"DZ"
assert cvt("Str") == "Str"
assert cvt(b"Bytes") == "b'Bytes'"
assert cvt(None) == "None"
assert cvt(False) == "False"
assert cvt(True) == "True"
assert cvt(42) == "42"
assert cvt(2**65) == "36893488147419103232"
assert cvt(-1.50) == "-1.5"
assert cvt(()) == "()"
assert cvt((18,)) == "(18,)"
assert cvt([]) == "[]"
assert cvt([28]) == "[28]"
assert cvt({}) == "{}"
assert cvt({3: 4}) == "{3: 4}"
assert cvt(set()) == "set()"
assert cvt({3, 3}) == "{3}"
valid_orig = "DZ"
valid_utf8 = valid_orig.encode("utf-8")
valid_cvt = cvt(valid_utf8)
if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
assert valid_cvt is valid_utf8
else:
assert type(valid_cvt) is unicode if env.PY2 else str # noqa: F821
if env.PY2:
assert valid_cvt == valid_orig
else:
assert valid_cvt == "b'\\xc7\\xb1'"
assert type(valid_cvt) is str
assert valid_cvt == "b'\\xc7\\xb1'"
malformed_utf8 = b"\x80"
if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
assert cvt(malformed_utf8) is malformed_utf8
else:
if env.PY2:
with pytest.raises(UnicodeDecodeError):
cvt(malformed_utf8)
else:
malformed_cvt = cvt(malformed_utf8)
assert type(malformed_cvt) is str
assert malformed_cvt == "b'\\x80'"
malformed_cvt = cvt(malformed_utf8)
assert type(malformed_cvt) is str
assert malformed_cvt == "b'\\x80'"
def test_implicit_casting():
......@@ -428,14 +395,14 @@ def test_print(capture):
def test_hash():
class Hashable(object):
class Hashable:
def __init__(self, value):
self.value = value
def __hash__(self):
return self.value
class Unhashable(object):
class Unhashable:
__hash__ = None
assert m.hash_function(Hashable(42)) == 42
......@@ -493,12 +460,7 @@ def test_memoryview(method, args, fmt, expected_view):
view = method(*args)
assert isinstance(view, memoryview)
assert view.format == fmt
if isinstance(expected_view, bytes) or not env.PY2:
view_as_list = list(view)
else:
# Using max to pick non-zero byte (big-endian vs little-endian).
view_as_list = [max(ord(c) for c in s) for s in view]
assert view_as_list == list(expected_view)
assert list(view) == list(expected_view)
@pytest.mark.xfail("env.PYPY", reason="getrefcount is not available")
......@@ -522,12 +484,7 @@ def test_memoryview_from_buffer_empty_shape():
view = m.test_memoryview_from_buffer_empty_shape()
assert isinstance(view, memoryview)
assert view.format == "B"
if env.PY2:
# Python 2 behavior is weird, but Python 3 (the future) is fine.
# PyPy3 has <memoryview, while CPython 2 has <memory
assert bytes(view).startswith(b"<memory")
else:
assert bytes(view) == b""
assert bytes(view) == b""
def test_test_memoryview_from_buffer_invalid_strides():
......@@ -536,14 +493,10 @@ def test_test_memoryview_from_buffer_invalid_strides():
def test_test_memoryview_from_buffer_nullptr():
if env.PY2:
with pytest.raises(ValueError):
m.test_memoryview_from_buffer_nullptr()
else:
with pytest.raises(ValueError):
m.test_memoryview_from_buffer_nullptr()
@pytest.mark.skipif("env.PY2")
def test_memoryview_from_memory():
view = m.test_memoryview_from_memory()
assert isinstance(view, memoryview)
......@@ -563,9 +516,9 @@ def test_builtin_functions():
def test_isinstance_string_types():
assert m.isinstance_pybind11_bytes(b"")
assert not m.isinstance_pybind11_bytes(u"")
assert not m.isinstance_pybind11_bytes("")
assert m.isinstance_pybind11_str(u"")
assert m.isinstance_pybind11_str("")
if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
assert m.isinstance_pybind11_str(b"")
else:
......@@ -575,24 +528,21 @@ def test_isinstance_string_types():
def test_pass_bytes_or_unicode_to_string_types():
assert m.pass_to_pybind11_bytes(b"Bytes") == 5
with pytest.raises(TypeError):
m.pass_to_pybind11_bytes(u"Str")
m.pass_to_pybind11_bytes("Str")
if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE") or env.PY2:
if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
assert m.pass_to_pybind11_str(b"Bytes") == 5
else:
with pytest.raises(TypeError):
m.pass_to_pybind11_str(b"Bytes")
assert m.pass_to_pybind11_str(u"Str") == 3
assert m.pass_to_pybind11_str("Str") == 3
assert m.pass_to_std_string(b"Bytes") == 5
assert m.pass_to_std_string(u"Str") == 3
assert m.pass_to_std_string("Str") == 3
malformed_utf8 = b"\x80"
if hasattr(m, "PYBIND11_STR_LEGACY_PERMISSIVE"):
assert m.pass_to_pybind11_str(malformed_utf8) == 1
elif env.PY2:
with pytest.raises(UnicodeDecodeError):
m.pass_to_pybind11_str(malformed_utf8)
else:
with pytest.raises(TypeError):
m.pass_to_pybind11_str(malformed_utf8)
......@@ -609,12 +559,14 @@ def test_weakref(create_weakref, create_weakref_with_callback):
from weakref import getweakrefcount
# Apparently, you cannot weakly reference an object()
class WeaklyReferenced(object):
class WeaklyReferenced:
pass
callback_called = False
def callback(wr):
# No `nonlocal` in Python 2
callback.called = True
nonlocal callback_called
callback_called = True
obj = WeaklyReferenced()
assert getweakrefcount(obj) == 0
......@@ -623,13 +575,12 @@ def test_weakref(create_weakref, create_weakref_with_callback):
obj = WeaklyReferenced()
assert getweakrefcount(obj) == 0
callback.called = False
wr = create_weakref_with_callback(obj, callback) # noqa: F841
assert getweakrefcount(obj) == 1
assert not callback.called
assert not callback_called
del obj
pytest.gc_collect()
assert callback.called
assert callback_called
def test_cpp_iterators():
......
# -*- coding: utf-8 -*-
import pytest
from pybind11_tests import ConstructorStats
......
# -*- coding: utf-8 -*-
import pytest
m = pytest.importorskip("pybind11_tests.smart_ptr")
......
# -*- coding: utf-8 -*-
import pytest
from pybind11_tests import ConstructorStats, UserType
......@@ -283,7 +282,7 @@ def test_stl_pass_by_pointer(msg):
1. (v: List[int] = None) -> List[int]
Invoked with:
""" # noqa: E501 line too long
"""
)
with pytest.raises(TypeError) as excinfo:
......@@ -295,7 +294,7 @@ def test_stl_pass_by_pointer(msg):
1. (v: List[int] = None) -> List[int]
Invoked with: None
""" # noqa: E501 line too long
"""
)
assert m.stl_pass_by_pointer([1, 2, 3]) == [1, 2, 3]
......
# -*- coding: utf-8 -*-
import pytest
import env
from pybind11_tests import stl_binders as m
......@@ -74,18 +72,13 @@ def test_vector_buffer():
assert v[1] == 2
v[2] = 5
mv = memoryview(v) # We expose the buffer interface
if not env.PY2:
assert mv[2] == 5
mv[2] = 6
else:
assert mv[2] == "\x05"
mv[2] = "\x06"
assert mv[2] == 5
mv[2] = 6
assert v[2] == 6
if not env.PY2:
mv = memoryview(b)
v = m.VectorUChar(mv[::2])
assert v[1] == 3
mv = memoryview(b)
v = m.VectorUChar(mv[::2])
assert v[1] == 3
with pytest.raises(RuntimeError) as excinfo:
m.create_undeclstruct() # Undeclared struct contents, no buffer interface
......
# -*- coding: utf-8 -*-
from pybind11_tests import tagbased_polymorphic as m
......
# -*- coding: utf-8 -*-
import threading
from pybind11_tests import thread as m
......@@ -7,7 +5,7 @@ from pybind11_tests import thread as m
class Thread(threading.Thread):
def __init__(self, fn):
super(Thread, self).__init__()
super().__init__()
self.fn = fn
self.e = None
......@@ -19,7 +17,7 @@ class Thread(threading.Thread):
self.e = e
def join(self):
super(Thread, self).join()
super().join()
if self.e:
raise self.e
......
# -*- coding: utf-8 -*-
from pybind11_tests import union_ as m
......
# -*- coding: utf-8 -*-
import pytest
import env # noqa: F401
......@@ -10,12 +9,12 @@ from pybind11_tests import ConstructorStats # noqa: E402
def test_override(capture, msg):
class ExtendedExampleVirt(m.ExampleVirt):
def __init__(self, state):
super(ExtendedExampleVirt, self).__init__(state + 1)
super().__init__(state + 1)
self.data = "Hello world"
def run(self, value):
print("ExtendedExampleVirt::run(%i), calling parent.." % value)
return super(ExtendedExampleVirt, self).run(value + 1)
return super().run(value + 1)
def run_bool(self):
print("ExtendedExampleVirt::run_bool()")
......@@ -29,7 +28,7 @@ def test_override(capture, msg):
class ExtendedExampleVirt2(ExtendedExampleVirt):
def __init__(self, state):
super(ExtendedExampleVirt2, self).__init__(state + 1)
super().__init__(state + 1)
def get_string2(self):
return "override2"
......@@ -41,7 +40,7 @@ def test_override(capture, msg):
capture
== """
Original implementation of ExampleVirt::run(state=10, value=20, str1=default1, str2=default2)
""" # noqa: E501 line too long
"""
)
with pytest.raises(RuntimeError) as excinfo:
......@@ -59,7 +58,7 @@ def test_override(capture, msg):
== """
ExtendedExampleVirt::run(20), calling parent..
Original implementation of ExampleVirt::run(state=11, value=21, str1=override1, str2=default2)
""" # noqa: E501 line too long
"""
)
with capture:
assert m.runExampleVirtBool(ex12p) is False
......@@ -76,7 +75,7 @@ def test_override(capture, msg):
== """
ExtendedExampleVirt::run(50), calling parent..
Original implementation of ExampleVirt::run(state=17, value=51, str1=override1, str2=override2)
""" # noqa: E501 line too long
"""
)
cstats = ConstructorStats.get(m.ExampleVirt)
......@@ -97,7 +96,7 @@ def test_alias_delay_initialization1(capture):
class B(m.A):
def __init__(self):
super(B, self).__init__()
super().__init__()
def f(self):
print("In python f()")
......@@ -137,7 +136,7 @@ def test_alias_delay_initialization2(capture):
class B2(m.A2):
def __init__(self):
super(B2, self).__init__()
super().__init__()
def f(self):
print("In python B2.f()")
......@@ -245,7 +244,7 @@ def test_dispatch_issue(msg):
class PyClass2(m.DispatchIssue):
def dispatch(self):
with pytest.raises(RuntimeError) as excinfo:
super(PyClass2, self).dispatch()
super().dispatch()
assert (
msg(excinfo.value)
== 'Tried to call pure virtual function "Base::dispatch"'
......@@ -262,7 +261,7 @@ def test_recursive_dispatch_issue(msg):
class Data(m.Data):
def __init__(self, value):
super(Data, self).__init__()
super().__init__()
self.value = value
class Adder(m.Adder):
......
......@@ -92,7 +92,7 @@ endif()
# Use the Python interpreter to find the libs.
if(NOT PythonLibsNew_FIND_VERSION)
set(PythonLibsNew_FIND_VERSION "")
set(PythonLibsNew_FIND_VERSION "3.5")
endif()
find_package(PythonInterp ${PythonLibsNew_FIND_VERSION} ${_pythonlibs_required}
......
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import os
import sys
......
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
......
......@@ -8,7 +8,6 @@ Adds the following targets::
pybind11::lto - Link time optimizations (manual selection)
pybind11::thin_lto - Link time optimizations (manual selection)
pybind11::python_link_helper - Adds link to Python libraries
pybind11::python2_no_register - Avoid warning/error with Python 2 + C++14/7
pybind11::windows_extras - MSVC bigobj and mp for building multithreaded
pybind11::opt_size - avoid optimizations that increase code size
......@@ -66,31 +65,6 @@ set_property(
APPEND
PROPERTY INTERFACE_LINK_LIBRARIES pybind11::pybind11)
# ----------------------- no register ----------------------
# Workaround for Python 2.7 and C++17 (C++14 as a warning) incompatibility
# This adds the flags -Wno-register and -Wno-deprecated-register if the compiler
# is Clang 3.9+ or AppleClang and the compile language is CXX, or /wd5033 for MSVC (all languages,
# since MSVC didn't recognize COMPILE_LANGUAGE until CMake 3.11+).
add_library(pybind11::python2_no_register INTERFACE IMPORTED ${optional_global})
set(clang_4plus
"$<AND:$<CXX_COMPILER_ID:Clang>,$<NOT:$<VERSION_LESS:$<CXX_COMPILER_VERSION>,3.9>>>")
set(no_register "$<OR:${clang_4plus},$<CXX_COMPILER_ID:AppleClang>>")
if(MSVC AND CMAKE_VERSION VERSION_LESS 3.11)
set(cxx_no_register "${no_register}")
else()
set(cxx_no_register "$<AND:$<COMPILE_LANGUAGE:CXX>,${no_register}>")
endif()
set(msvc "$<CXX_COMPILER_ID:MSVC>")
set_property(
TARGET pybind11::python2_no_register
PROPERTY INTERFACE_COMPILE_OPTIONS
"$<${cxx_no_register}:-Wno-register;-Wno-deprecated-register>" "$<${msvc}:/wd5033>")
# --------------------------- link helper ---------------------------
add_library(pybind11::python_link_helper IMPORTED INTERFACE ${optional_global})
......
......@@ -51,8 +51,6 @@ complex applications, and they are available in all modes:
Python headers too.
``pybind11::python_link_helper``
Just the "linking" part of ``pybind11:module``, for CMake < 3.15.
``pybind11::python2_no_register``
Quiets the warning/error when mixing C++14+ and Python 2, also included in ``pybind11::module``.
``pybind11::thin_lto``
An alternative to ``INTERPROCEDURAL_OPTIMIZATION``.
``pybind11::lto``
......
......@@ -22,9 +22,7 @@ else()
set(_pybind11_quiet "")
endif()
if(NOT Python_FOUND
AND NOT Python3_FOUND
AND NOT Python2_FOUND)
if(NOT Python_FOUND AND NOT Python3_FOUND)
if(NOT DEFINED Python_FIND_IMPLEMENTATIONS)
set(Python_FIND_IMPLEMENTATIONS CPython PyPy)
endif()
......@@ -34,7 +32,7 @@ if(NOT Python_FOUND
set(Python_ROOT_DIR "$ENV{pythonLocation}")
endif()
find_package(Python REQUIRED COMPONENTS Interpreter Development ${_pybind11_quiet})
find_package(Python 3.5 REQUIRED COMPONENTS Interpreter Development ${_pybind11_quiet})
# If we are in submodule mode, export the Python targets to global targets.
# If this behavior is not desired, FindPython _before_ pybind11.
......@@ -51,19 +49,10 @@ if(Python_FOUND)
set(_Python
Python
CACHE INTERNAL "" FORCE)
elseif(Python3_FOUND AND NOT Python2_FOUND)
elseif(Python3_FOUND)
set(_Python
Python3
CACHE INTERNAL "" FORCE)
elseif(Python2_FOUND AND NOT Python3_FOUND)
set(_Python
Python2
CACHE INTERNAL "" FORCE)
else()
message(AUTHOR_WARNING "Python2 and Python3 both present, pybind11 in "
"PYBIND11_NOPYTHON mode (manually activate to silence warning)")
set(_pybind11_nopython ON)
return()
endif()
if(PYBIND11_MASTER_PROJECT)
......@@ -137,7 +126,7 @@ if(PYTHON_IS_DEBUG)
PROPERTY INTERFACE_COMPILE_DEFINITIONS Py_DEBUG)
endif()
# Check on every access - since Python2 and Python3 could have been used - do nothing in that case.
# Check on every access - since Python can change - do nothing in that case.
if(DEFINED ${_Python}_INCLUDE_DIRS)
# Only add Python for build - must be added during the import for config
......@@ -159,13 +148,6 @@ if(DEFINED ${_Python}_INCLUDE_DIRS)
CACHE INTERNAL "Directories where pybind11 and possibly Python headers are located")
endif()
if(DEFINED ${_Python}_VERSION AND ${_Python}_VERSION VERSION_LESS 3)
set_property(
TARGET pybind11::pybind11
APPEND
PROPERTY INTERFACE_LINK_LIBRARIES pybind11::python2_no_register)
endif()
# In CMake 3.18+, you can find these separately, so include an if
if(TARGET ${_Python}::Python)
set_property(
......@@ -205,8 +187,6 @@ function(pybind11_add_module target_name)
python_add_library(${target_name} ${lib_type} ${ARG_UNPARSED_ARGUMENTS})
elseif("${_Python}" STREQUAL "Python3")
python3_add_library(${target_name} ${lib_type} ${ARG_UNPARSED_ARGUMENTS})
elseif("${_Python}" STREQUAL "Python2")
python2_add_library(${target_name} ${lib_type} ${ARG_UNPARSED_ARGUMENTS})
else()
message(FATAL_ERROR "Cannot detect FindPython version: ${_Python}")
endif()
......@@ -223,10 +203,6 @@ function(pybind11_add_module target_name)
target_link_libraries(${target_name} PRIVATE pybind11::windows_extras)
endif()
if(DEFINED ${_Python}_VERSION AND ${_Python}_VERSION VERSION_LESS 3)
target_link_libraries(${target_name} PRIVATE pybind11::python2_no_register)
endif()
# -fvisibility=hidden is required to allow multiple modules compiled against
# different pybind versions to work properly, and for some features (e.g.
# py::module_local). We force it on everything inside the `pybind11`
......
......@@ -43,7 +43,7 @@ endif()
# A user can set versions manually too
set(Python_ADDITIONAL_VERSIONS
"3.11;3.10;3.9;3.8;3.7;3.6;3.5;3.4"
"3.11;3.10;3.9;3.8;3.7;3.6;3.5"
CACHE INTERNAL "")
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}")
......@@ -122,13 +122,6 @@ set_property(
INTERFACE_LINK_LIBRARIES pybind11::python_link_helper
"$<$<OR:$<PLATFORM_ID:Windows>,$<PLATFORM_ID:Cygwin>>:$<BUILD_INTERFACE:${PYTHON_LIBRARIES}>>")
if(PYTHON_VERSION VERSION_LESS 3)
set_property(
TARGET pybind11::pybind11
APPEND
PROPERTY INTERFACE_LINK_LIBRARIES pybind11::python2_no_register)
endif()
set_property(
TARGET pybind11::embed
APPEND
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment