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 r_policy
10
11
12def _r_policy_extract(self, t):
13    """Extract the user-defined replacement policy.
14
15    This method allows to extract a reference to the user-defined replacement policy (UDRP) stored within this
16    :class:`~pygmo.r_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 UDRP:
18
19    * if the type of the UDRP is *t*, then a reference to the UDRP will be returned
20      (this mirrors the behaviour of the corresponding C++ method
21      :cpp:func:`pagmo::r_policy::extract()`),
22    * if *t* is :class:`object` and the UDRP is a Python object (as opposed to an
23      :ref:`exposed C++ replacement policy <r_policies_cpp>`), then a reference to the
24      UDRP will be returned (this allows to extract a Python UDRP without knowing its type),
25    * otherwise, :data:`None` will be returned.
26
27    Args:
28        t (:class:`type`): the type of the user-defined replacement policy to extract
29
30    Returns:
31        a reference to the internal user-defined replacement 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_r_policy"):
40        return self._cpp_extract(t())
41    return self._py_extract(t)
42
43
44def _r_policy_is(self, t):
45    """Check the type of the user-defined replacement policy.
46
47    This method returns :data:`False` if :func:`extract(t) <pygmo.r_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 UDRP
52
53    Returns:
54        bool: whether the UDRP is of type *t* or not
55
56    Raises:
57        unspecified: any exception thrown by :func:`~pygmo.r_policy.extract()`
58
59    """
60    return not self.extract(t) is None
61
62
63# Do the actual patching.
64setattr(r_policy, "extract", _r_policy_extract)
65setattr(r_policy, "is_", _r_policy_is)
66