1# Copyright 2020, 2021 PaGMO development team
2#
3# This file is part of the pygmo library.
4#
5# This Source Code Form is subject to the terms of the Mozilla
6# Public License v. 2.0. If a copy of the MPL was not distributed
7# with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
8
9from .core import s_policy
10
11
12def _s_policy_extract(self, t):
13    """Extract the user-defined selection policy.
14
15    This method allows to extract a reference to the user-defined selection policy (UDSP) stored within this
16    :class:`~pygmo.s_policy` instance. The behaviour of this function depends on the value
17    of *t* (which must be a :class:`type`) and on the type of the internal UDSP:
18
19    * if the type of the UDSP is *t*, then a reference to the UDSP will be returned
20      (this mirrors the behaviour of the corresponding C++ method
21      :cpp:func:`pagmo::s_policy::extract()`),
22    * if *t* is :class:`object` and the UDSP is a Python object (as opposed to an
23      :ref:`exposed C++ selection policy <s_policies_cpp>`), then a reference to the
24      UDSP will be returned (this allows to extract a Python UDSP without knowing its type),
25    * otherwise, :data:`None` will be returned.
26
27    Args:
28        t (:class:`type`): the type of the user-defined selection policy to extract
29
30    Returns:
31        a reference to the internal user-defined selection policy, or :data:`None` if the extraction fails
32
33    Raises:
34        TypeError: if *t* is not a :class:`type`
35
36    """
37    if not isinstance(t, type):
38        raise TypeError("the 't' parameter must be a type")
39    if hasattr(t, "_pygmo_cpp_s_policy"):
40        return self._cpp_extract(t())
41    return self._py_extract(t)
42
43
44def _s_policy_is(self, t):
45    """Check the type of the user-defined selection policy.
46
47    This method returns :data:`False` if :func:`extract(t) <pygmo.s_policy.extract>` returns
48    :data:`None`, and :data:`True` otherwise.
49
50    Args:
51        t (:class:`type`): the type that will be compared to the type of the UDSP
52
53    Returns:
54        bool: whether the UDSP is of type *t* or not
55
56    Raises:
57        unspecified: any exception thrown by :func:`~pygmo.s_policy.extract()`
58
59    """
60    return not self.extract(t) is None
61
62
63# Do the actual patching.
64setattr(s_policy, "extract", _s_policy_extract)
65setattr(s_policy, "is_", _s_policy_is)
66