Github messages for voidlinux
 help / color / mirror / Atom feed
* [PR PATCH] sagemath: use cython 3
@ 2023-09-02 22:32 tornaria
  2023-09-02 22:37 ` [PR PATCH] [Updated] " tornaria
                   ` (16 more replies)
  0 siblings, 17 replies; 18+ messages in thread
From: tornaria @ 2023-09-02 22:32 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 2437 bytes --]

There is a new pull request by tornaria against master on the void-packages repository

https://github.com/tornaria/void-packages sagemath-cython3
https://github.com/void-linux/void-packages/pull/45887

sagemath: use cython 3
#### Testing the changes
- I tested the changes in this PR: **briefly**

Since https://github.com/sagemath/sage/pull/36109 was merged upstream, it's now almost trivial to build sagemath with cython 3. This PR is pretty straightforward to understand:

 - commit 7f8e6514ffa54449a80e01fbae7f9355a7739a46 rebuilds `python3-pplpy` using cython 3. Nothing fancy here and this commit was already tested and only dropped since it turned out it had to be built with the same version of cython as sagemath itself.
 - commit df0d21871ce850efea3fc01f19a3d9e8c0d5f0d4 is just adding a few patches to sagemath, switching to cython 3, and bumping.

Description of added patches:
1. patch `36109-00pre.patch`: this is hand picked trivial patch that allows us to apply https://github.com/sagemath/sage/pull/36109 cleanly on 10.1 (since that PR is based on 10.1.beta0). All changes are comments!
2. patch `36109-prepare_for_cython_3.0.patch`: this is long, taken verbatim from https://github.com/sagemath/sage/pull/36109.diff, and is already merged.
3. patch `build-cython3.patch`: this is 2 lines changed plus 4 legacy build options added to cython setup.
4. patch `fix-doctest-cython3.patch`: this is a few fixes in doctests to accomodate minor changes in cython output (`__repr__` for cython classes, functions, and generators).

CC: @ahesford 

<!--
#### New package
- This new package conforms to the [package requirements](https://github.com/void-linux/void-packages/blob/master/CONTRIBUTING.md#package-requirements): **YES**|**NO**
-->

<!-- Note: If the build is likely to take more than 2 hours, please add ci skip tag as described in
https://github.com/void-linux/void-packages/blob/master/CONTRIBUTING.md#continuous-integration
and test at least one native build and, if supported, at least one cross build.
Ignore this section if this PR is not skipping CI.
-->
<!--
#### Local build testing
- I built this PR locally for my native architecture, (ARCH-LIBC)
- I built this PR locally for these architectures (if supported. mark crossbuilds):
  - aarch64-musl
  - armv7l
  - armv6l-musl
-->


A patch file from https://github.com/void-linux/void-packages/pull/45887.patch is attached

[-- Warning: decoded text below may be mangled, UTF-8 assumed --]
[-- Attachment #2: github-pr-sagemath-cython3-45887.patch --]
[-- Type: text/x-diff, Size: 464625 bytes --]

From 7f8e6514ffa54449a80e01fbae7f9355a7739a46 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gonzalo=20Tornar=C3=ADa?= <tornaria@cmat.edu.uy>
Date: Wed, 19 Jul 2023 21:04:33 -0300
Subject: [PATCH 1/2] python3-pplpy: patch and rebuild for Cython 3

---
 ...8537fa7ea061ebb8d5131b1e23673eaf741d.patch | 22 ++++++++++++++++++
 .../patches/cython3-legacy.patch              | 23 +++++++++++++++++++
 srcpkgs/python3-pplpy/template                |  2 +-
 3 files changed, 46 insertions(+), 1 deletion(-)
 create mode 100644 srcpkgs/python3-pplpy/patches/aaa28537fa7ea061ebb8d5131b1e23673eaf741d.patch
 create mode 100644 srcpkgs/python3-pplpy/patches/cython3-legacy.patch

diff --git a/srcpkgs/python3-pplpy/patches/aaa28537fa7ea061ebb8d5131b1e23673eaf741d.patch b/srcpkgs/python3-pplpy/patches/aaa28537fa7ea061ebb8d5131b1e23673eaf741d.patch
new file mode 100644
index 0000000000000..21bc2a5214df4
--- /dev/null
+++ b/srcpkgs/python3-pplpy/patches/aaa28537fa7ea061ebb8d5131b1e23673eaf741d.patch
@@ -0,0 +1,22 @@
+From aaa28537fa7ea061ebb8d5131b1e23673eaf741d Mon Sep 17 00:00:00 2001
+From: Matthias Koeppe <mkoeppe@math.ucdavis.edu>
+Date: Sun, 31 Jul 2022 12:39:34 -0700
+Subject: [PATCH] ppl/bit_arrays.pxd: Use relative cimport
+
+---
+ ppl/bit_arrays.pxd | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/ppl/bit_arrays.pxd b/ppl/bit_arrays.pxd
+index eb57434..145a978 100644
+--- a/ppl/bit_arrays.pxd
++++ b/ppl/bit_arrays.pxd
+@@ -1,4 +1,4 @@
+-from ppl_decl cimport *
++from .ppl_decl cimport *
+ 
+ cdef class Bit_Row(object):
+     cdef PPL_Bit_Row *thisptr
+-- 
+GitLab
+
diff --git a/srcpkgs/python3-pplpy/patches/cython3-legacy.patch b/srcpkgs/python3-pplpy/patches/cython3-legacy.patch
new file mode 100644
index 0000000000000..e00b99f8c5f2e
--- /dev/null
+++ b/srcpkgs/python3-pplpy/patches/cython3-legacy.patch
@@ -0,0 +1,23 @@
+commit e6f3e66154138ce3e31e803e74b8c71787c70acc
+Author: Gonzalo Tornaría <tornaria@cmat.edu.uy>
+Date:   Wed Jul 19 20:47:52 2023 -0300
+
+    cython3 support using legacy directives
+
+diff --git a/setup.py b/setup.py
+index 13d543b..55dcd34 100755
+--- a/setup.py
++++ b/setup.py
+@@ -38,7 +38,11 @@ class build_ext(_build_ext):
+         self.extensions[:] = cythonize(
+             self.extensions,
+             include_path=sys.path,
+-            compiler_directives={'embedsignature': True})
++            compiler_directives={
++                'embedsignature': True,
++                'legacy_implicit_noexcept': True,
++                'c_api_binop_methods': True,
++                })
+ 
+         _build_ext.run(self)
+ 
diff --git a/srcpkgs/python3-pplpy/template b/srcpkgs/python3-pplpy/template
index 6c1e83aa091c7..fe6b08dba40f2 100644
--- a/srcpkgs/python3-pplpy/template
+++ b/srcpkgs/python3-pplpy/template
@@ -1,7 +1,7 @@
 # Template file for 'python3-pplpy'
 pkgname=python3-pplpy
 version=0.8.7
-revision=3
+revision=4
 build_style=python3-module
 hostmakedepends="python3-setuptools python3-Cython0.29"
 makedepends="python3-cysignals python3-gmpy2 python3-devel gmp-devel

From df0d21871ce850efea3fc01f19a3d9e8c0d5f0d4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gonzalo=20Tornar=C3=ADa?= <tornaria@cmat.edu.uy>
Date: Tue, 29 Aug 2023 22:14:49 -0300
Subject: [PATCH 2/2] sagemath: use cython 3.0

---
 srcpkgs/sagemath/patches/36109-00pre.patch    |   50 +
 .../36109-prepare_for_cython_3.0.patch        | 9995 +++++++++++++++++
 srcpkgs/sagemath/patches/build-cython3.patch  |   44 +
 .../patches/fix-doctest-cython3.patch         |  207 +
 srcpkgs/sagemath/patches/get_patches          |    7 +-
 srcpkgs/sagemath/template                     |    6 +-
 6 files changed, 10304 insertions(+), 5 deletions(-)
 create mode 100644 srcpkgs/sagemath/patches/36109-00pre.patch
 create mode 100644 srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch
 create mode 100644 srcpkgs/sagemath/patches/build-cython3.patch
 create mode 100644 srcpkgs/sagemath/patches/fix-doctest-cython3.patch

diff --git a/srcpkgs/sagemath/patches/36109-00pre.patch b/srcpkgs/sagemath/patches/36109-00pre.patch
new file mode 100644
index 0000000000000..0a30d622f0f62
--- /dev/null
+++ b/srcpkgs/sagemath/patches/36109-00pre.patch
@@ -0,0 +1,50 @@
+Pre-patch so that PR #36109 applies cleanly on top of 10.1
+
+diff --git a/src/sage/categories/hopf_algebras_with_basis.py b/src/sage/categories/hopf_algebras_with_basis.py
+index ea401896ca0..29b6f48a86f 100644
+--- a/src/sage/categories/hopf_algebras_with_basis.py
++++ b/src/sage/categories/hopf_algebras_with_basis.py
+@@ -33,11 +33,11 @@ class HopfAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
+     We now show how to use a simple Hopf algebra, namely the group algebra of the dihedral group
+     (see also AlgebrasWithBasis)::
+ 
+-        sage: A = C.example(); A                                                        # optional - sage.groups
++        sage: A = C.example(); A                                                        # needs sage.groups
+         An example of Hopf algebra with basis: the group algebra of the
+          Dihedral group of order 6 as a permutation group over Rational Field
+-        sage: A.__custom_name = "A"                                                     # optional - sage.groups
+-        sage: A.category()                                                              # optional - sage.groups
++        sage: A.__custom_name = "A"                                                     # needs sage.groups
++        sage: A.category()                                                              # needs sage.groups
+         Category of finite dimensional hopf algebras with basis over Rational Field
+ 
+         sage: A.one_basis()                                                             # optional - sage.groups
+diff --git a/src/sage/categories/modules_with_basis.py b/src/sage/categories/modules_with_basis.py
+index 85a0d50239a..c0e29886b5f 100644
+--- a/src/sage/categories/modules_with_basis.py
++++ b/src/sage/categories/modules_with_basis.py
+@@ -66,9 +66,9 @@ class ModulesWithBasis(CategoryWithAxiom_over_base_ring):
+ 
+     Let `X` and `Y` be two modules with basis. We can build `Hom(X,Y)`::
+ 
+-        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.__custom_name = "X"             # optional - sage.modules
+-        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.__custom_name = "Y"             # optional - sage.modules
+-        sage: H = Hom(X, Y); H                                                          # optional - sage.modules
++        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.__custom_name = "X"             # needs sage.modules
++        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.__custom_name = "Y"             # needs sage.modules
++        sage: H = Hom(X, Y); H                                                          # needs sage.modules
+         Set of Morphisms from X to Y
+          in Category of finite dimensional vector spaces with basis over Rational Field
+ 
+diff --git a/src/sage/misc/cachefunc.pyx b/src/sage/misc/cachefunc.pyx
+index dac4c684f47..9b2916e547d 100644
+--- a/src/sage/misc/cachefunc.pyx
++++ b/src/sage/misc/cachefunc.pyx
+@@ -297,6 +297,7 @@ methods of extension classes, as long as they either support attribute assignmen
+ or have a public attribute of type ``<dict>`` called ``__cached_methods``. The
+ latter is easy::
+ 
++    sage: # needs sage.misc.cython
+     sage: cython_code = [
+     ....: "from sage.misc.cachefunc import cached_method",
+     ....: "cdef class MyClass:",
diff --git a/srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch b/srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch
new file mode 100644
index 0000000000000..93390f7eef992
--- /dev/null
+++ b/srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch
@@ -0,0 +1,9995 @@
+diff --git a/src/doc/en/thematic_tutorials/coercion_and_categories.rst b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+index 4efe68a2617..de2349a9a3f 100644
+--- a/src/doc/en/thematic_tutorials/coercion_and_categories.rst
++++ b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+@@ -106,7 +106,6 @@ This base class provides a lot more methods than a general parent::
+ 
+     sage: [p for p in dir(Field) if p not in dir(Parent)]
+     ['__fraction_field',
+-     '__ideal_monoid',
+      '__iter__',
+      '__len__',
+      '__rxor__',
+@@ -119,6 +118,7 @@ This base class provides a lot more methods than a general parent::
+      '_default_category',
+      '_gens',
+      '_ideal_class_',
++     '_ideal_monoid',
+      '_latex_names',
+      '_list',
+      '_one_element',
+diff --git a/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst b/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst
+index 51aec989810..553a946c4d8 100644
+--- a/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst
++++ b/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst
+@@ -298,7 +298,7 @@ http://docs.python.org/library/ for a complete list. ::
+         sage: el
+         bla
+         sage: el.__dict__
+-        {'__custom_name': 'bla', 'value': 42}
++        {'_SageObject__custom_name': 'bla', 'value': 42}
+ 
+     Lots of Sage objects are not Python objects but compiled Cython
+     objects. Python sees them as builtin objects and you do not have
+diff --git a/src/sage/algebras/letterplace/free_algebra_letterplace.pxd b/src/sage/algebras/letterplace/free_algebra_letterplace.pxd
+index d1d162c3b40..47a7275aba0 100644
+--- a/src/sage/algebras/letterplace/free_algebra_letterplace.pxd
++++ b/src/sage/algebras/letterplace/free_algebra_letterplace.pxd
+@@ -20,16 +20,15 @@ cdef class FreeAlgebra_letterplace_libsingular():
+     cdef ring* _lp_ring
+     cdef MPolynomialRing_libsingular _commutative_ring
+     cdef MPolynomialRing_libsingular _lp_ring_internal
+-    cdef object __ngens
++    cdef object _ngens
+ 
+ cdef class FreeAlgebra_letterplace(Algebra):
+     cdef MPolynomialRing_libsingular _commutative_ring
+     cdef MPolynomialRing_libsingular _current_ring
+     cdef int _degbound
+-    cdef int __ngens
++    cdef int _ngens
+     cdef int _nb_slackvars
+     cdef object __monoid
+-    cdef public object __custom_name
+     cdef str exponents_to_string(self, E)
+     cdef str exponents_to_latex(self, E)
+     cdef tuple _degrees
+diff --git a/src/sage/algebras/letterplace/free_algebra_letterplace.pyx b/src/sage/algebras/letterplace/free_algebra_letterplace.pyx
+index e9c70c9de29..53f0dfdea6d 100644
+--- a/src/sage/algebras/letterplace/free_algebra_letterplace.pyx
++++ b/src/sage/algebras/letterplace/free_algebra_letterplace.pyx
+@@ -255,7 +255,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+         """
+         if not isinstance(R, MPolynomialRing_libsingular):
+             raise TypeError("a letterplace algebra must be provided by a polynomial ring of type %s" % MPolynomialRing_libsingular)
+-        self.__ngens = R.ngens()
++        self._ngens = R.ngens()
+         if degrees is None:
+             varnames = R.variable_names()
+             self._nb_slackvars = 0
+@@ -269,12 +269,12 @@ cdef class FreeAlgebra_letterplace(Algebra):
+         self._current_ring = make_letterplace_ring(R, 1)
+         self._degbound = 1
+         if degrees is None:
+-            self._degrees = tuple([int(1)] * self.__ngens)
++            self._degrees = tuple([int(1)] * self._ngens)
+         else:
+             if (not isinstance(degrees, (tuple, list))) \
+-                    or len(degrees) != self.__ngens - self._nb_slackvars \
++                    or len(degrees) != self._ngens - self._nb_slackvars \
+                     or any(i <= 0 for i in degrees):
+-                raise TypeError("the generator degrees must be given by a list or tuple of %d positive integers" % (self.__ngens - 1))
++                raise TypeError("the generator degrees must be given by a list or tuple of %d positive integers" % (self._ngens - 1))
+             self._degrees = tuple([int(i) for i in degrees])
+             self.set_degbound(max(self._degrees))
+         self._populate_coercion_lists_(coerce_list=[base_ring])
+@@ -305,7 +305,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F.ngens()
+             3
+         """
+-        return self.__ngens - self._nb_slackvars
++        return self._ngens - self._nb_slackvars
+ 
+     def gen(self, i):
+         """
+@@ -327,17 +327,17 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F.gen(2)
+             c
+         """
+-        if i >= self.__ngens - self._nb_slackvars:
+-            raise ValueError("this free algebra only has %d generators" % (self.__ngens - self._nb_slackvars))
++        if i >= self._ngens - self._nb_slackvars:
++            raise ValueError("this free algebra only has %d generators" % (self._ngens - self._nb_slackvars))
+         if self._gens is not None:
+             return self._gens[i]
+         deg = self._degrees[i]
+         # self.set_degbound(deg)
+         p = self._current_ring.gen(i)
+         cdef int n
+-        cdef int j = self.__ngens - 1
++        cdef int j = self._ngens - 1
+         for n in range(1, deg):
+-            j += self.__ngens
++            j += self._ngens
+             p *= self._current_ring.gen(j)
+         return FreeAlgebraElement_letterplace(self, p)
+ 
+@@ -413,7 +413,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: FreeAlgebra(QQ, implementation='letterplace', names=['x']).is_commutative()
+             True
+         """
+-        return self.__ngens - self._nb_slackvars <= 1
++        return self._ngens - self._nb_slackvars <= 1
+ 
+     def is_field(self, proof=True):
+         """
+@@ -430,7 +430,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F.is_field()
+             False
+         """
+-        return (not (self.__ngens - self._nb_slackvars)) and self._base.is_field(proof=proof)
++        return (not (self._ngens - self._nb_slackvars)) and self._base.is_field(proof=proof)
+ 
+     def _repr_(self):
+         """
+@@ -446,7 +446,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F
+             Free Associative Unital Algebra on 3 generators (x, y, z) over Rational Field
+         """
+-        return "Free Associative Unital Algebra on %d generators %s over %s" % (self.__ngens - self._nb_slackvars, self.gens(), self._base)
++        return "Free Associative Unital Algebra on %d generators %s over %s" % (self._ngens - self._nb_slackvars, self.gens(), self._base)
+ 
+     def _latex_(self):
+         r"""
+@@ -586,7 +586,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+               generated free abelian monoid.
+               In principle, this is correct, but it is not implemented, yet.>
+         """
+-        cdef int ngens = self.__ngens
++        cdef int ngens = self._ngens
+         cdef int nblocks = len(E) // ngens
+         cdef int i, j, base, exp, var_ind
+         cdef list out = []
+@@ -618,7 +618,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: latex(-(a*b*(z+1)-c)^2)     # indirect doctest
+             \left(2 z + 1\right) a b a b + \left(z + 1\right) a b c + \left(z + 1\right) c a b - c c
+         """
+-        cdef int ngens = self.__ngens
++        cdef int ngens = self._ngens
+         cdef int nblocks = len(E) // ngens
+         cdef int i, j, base, exp, var_ind
+         cdef list out = []
+@@ -678,7 +678,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+         cdef list out = []
+         C = self.current_ring()
+         cdef FreeAlgebraElement_letterplace x
+-        ngens = self.__ngens
++        ngens = self._ngens
+         cdef list G = [C(x._poly) for x in g]
+         from sage.groups.perm_gps.permgroup_named import CyclicPermutationGroup
+         CG = CyclicPermutationGroup(C.ngens())
+@@ -811,7 +811,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             l = len(e)
+             break
+         cdef dict out = {}
+-        self.set_degbound(l // self.__ngens)
++        self.set_degbound(l // self._ngens)
+         cdef Py_ssize_t n = self._current_ring.ngens()
+         for e, c in D.iteritems():
+             out[tuple(e) + (0,) * (n - l)] = c
+@@ -896,7 +896,7 @@ cdef class FreeAlgebra_letterplace_libsingular():
+         self._commutative_ring = commutative_ring
+ 
+     def __init__(self, commutative_ring, degbound):
+-        self.__ngens = commutative_ring.ngens() * degbound
++        self._ngens = commutative_ring.ngens() * degbound
+ 
+     def __dealloc__(self):
+         r"""
+diff --git a/src/sage/algebras/quatalg/quaternion_algebra_element.pyx b/src/sage/algebras/quatalg/quaternion_algebra_element.pyx
+index f6e87440fe9..8cb7e848fd0 100644
+--- a/src/sage/algebras/quatalg/quaternion_algebra_element.pyx
++++ b/src/sage/algebras/quatalg/quaternion_algebra_element.pyx
+@@ -1700,15 +1700,15 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra
+             x, y, z, w = v
+         cdef NumberFieldElement a = <NumberFieldElement>(parent._base(parent._a))
+         cdef NumberFieldElement b = <NumberFieldElement>(parent._base(parent._b))
+-        fmpz_poly_set_ZZX(self.x, (<NumberFieldElement>x).__numerator)
+-        fmpz_poly_set_ZZX(self.y, (<NumberFieldElement>y).__numerator)
+-        fmpz_poly_set_ZZX(self.z, (<NumberFieldElement>z).__numerator)
+-        fmpz_poly_set_ZZX(self.w, (<NumberFieldElement>w).__numerator)
++        fmpz_poly_set_ZZX(self.x, (<NumberFieldElement>x)._numerator)
++        fmpz_poly_set_ZZX(self.y, (<NumberFieldElement>y)._numerator)
++        fmpz_poly_set_ZZX(self.z, (<NumberFieldElement>z)._numerator)
++        fmpz_poly_set_ZZX(self.w, (<NumberFieldElement>w)._numerator)
+ 
+-        ZZ_to_mpz(T1, &(<NumberFieldElement>x).__denominator)
+-        ZZ_to_mpz(T2, &(<NumberFieldElement>y).__denominator)
+-        ZZ_to_mpz(t3, &(<NumberFieldElement>z).__denominator)
+-        ZZ_to_mpz(t4, &(<NumberFieldElement>w).__denominator)
++        ZZ_to_mpz(T1, &(<NumberFieldElement>x)._denominator)
++        ZZ_to_mpz(T2, &(<NumberFieldElement>y)._denominator)
++        ZZ_to_mpz(t3, &(<NumberFieldElement>z)._denominator)
++        ZZ_to_mpz(t4, &(<NumberFieldElement>w)._denominator)
+ 
+         mpz_lcm(self.d, T1, T2)
+         mpz_lcm(self.d, self.d, t3)
+@@ -1724,10 +1724,10 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra
+         fmpz_poly_scalar_mul_mpz(self.z, self.z, t3)
+         fmpz_poly_scalar_mul_mpz(self.w, self.w, t4)
+ 
+-        fmpz_poly_set_ZZX(self.a, a.__numerator)     # we will assume that the denominator of a and b are 1
+-        fmpz_poly_set_ZZX(self.b, b.__numerator)
++        fmpz_poly_set_ZZX(self.a, a._numerator)     # we will assume that the denominator of a and b are 1
++        fmpz_poly_set_ZZX(self.b, b._numerator)
+ 
+-        fmpz_poly_set_ZZX(self.modulus, (<NumberFieldElement>x).__fld_numerator.x)  # and same for the modulus
++        fmpz_poly_set_ZZX(self.modulus, (<NumberFieldElement>x)._fld_numerator.x)  # and same for the modulus
+ 
+     def __getitem__(self, int i):
+         """
+@@ -1756,17 +1756,17 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra
+         cdef NumberFieldElement item = el._new()
+ 
+         if i == 0:
+-            fmpz_poly_get_ZZX(item.__numerator, self.x)
++            fmpz_poly_get_ZZX(item._numerator, self.x)
+         elif i == 1:
+-            fmpz_poly_get_ZZX(item.__numerator, self.y)
++            fmpz_poly_get_ZZX(item._numerator, self.y)
+         elif i == 2:
+-            fmpz_poly_get_ZZX(item.__numerator, self.z)
++            fmpz_poly_get_ZZX(item._numerator, self.z)
+         elif i == 3:
+-            fmpz_poly_get_ZZX(item.__numerator, self.w)
++            fmpz_poly_get_ZZX(item._numerator, self.w)
+         else:
+             raise IndexError("quaternion element index out of range")
+ 
+-        mpz_to_ZZ(&item.__denominator, self.d)
++        mpz_to_ZZ(&item._denominator, self.d)
+ 
+         return item
+ 
+diff --git a/src/sage/categories/hopf_algebras_with_basis.py b/src/sage/categories/hopf_algebras_with_basis.py
+index 1be964cb6c9..615fc4eae06 100644
+--- a/src/sage/categories/hopf_algebras_with_basis.py
++++ b/src/sage/categories/hopf_algebras_with_basis.py
+@@ -36,7 +36,7 @@ class HopfAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
+         sage: A = C.example(); A                                                        # needs sage.groups
+         An example of Hopf algebra with basis: the group algebra of the
+          Dihedral group of order 6 as a permutation group over Rational Field
+-        sage: A.__custom_name = "A"                                                     # needs sage.groups
++        sage: A.rename("A")                                                             # needs sage.groups
+         sage: A.category()                                                              # needs sage.groups
+         Category of finite dimensional hopf algebras with basis over Rational Field
+ 
+diff --git a/src/sage/categories/modules_with_basis.py b/src/sage/categories/modules_with_basis.py
+index 65fd47cb890..fc1857f0c8e 100644
+--- a/src/sage/categories/modules_with_basis.py
++++ b/src/sage/categories/modules_with_basis.py
+@@ -66,8 +66,8 @@ class ModulesWithBasis(CategoryWithAxiom_over_base_ring):
+ 
+     Let `X` and `Y` be two modules with basis. We can build `Hom(X,Y)`::
+ 
+-        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.__custom_name = "X"             # needs sage.modules
+-        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.__custom_name = "Y"             # needs sage.modules
++        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.rename("X")                     # needs sage.modules
++        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.rename("Y")                     # needs sage.modules
+         sage: H = Hom(X, Y); H                                                          # needs sage.modules
+         Set of Morphisms from X to Y
+          in Category of finite dimensional vector spaces with basis over Rational Field
+diff --git a/src/sage/combinat/cluster_complex.py b/src/sage/combinat/cluster_complex.py
+index edc4f235aeb..e263d983887 100644
+--- a/src/sage/combinat/cluster_complex.py
++++ b/src/sage/combinat/cluster_complex.py
+@@ -222,10 +222,6 @@ def __init__(self, W, k, coxeter_element, algorithm):
+         self._W = W
+         self._w0 = w
+         self._k = k
+-        if k == 1:
+-            self.__custom_name = 'Cluster complex'
+-        else:
+-            self.__custom_name = 'Multi-cluster complex'
+ 
+         self.set_immutable()
+ 
+@@ -271,7 +267,10 @@ def _repr_(self):
+             sage: ClusterComplex(['A', 2])._repr_()
+             "Cluster complex of type ['A', 2] with 5 vertices and 5 facets"
+         """
+-        name = self.__custom_name
++        if self._k == 1:
++            name = 'Cluster complex'
++        else:
++            name = 'Multi-cluster complex'
+         name += (' of type %s with %s vertices and %s facets'
+                  % (self.cartan_type(), len(self.vertices()),
+                     len(self._facets)))
+diff --git a/src/sage/combinat/integer_lists/base.pxd b/src/sage/combinat/integer_lists/base.pxd
+index ecb5550a9cf..3d373a64fe0 100644
+--- a/src/sage/combinat/integer_lists/base.pxd
++++ b/src/sage/combinat/integer_lists/base.pxd
+@@ -12,4 +12,4 @@ cdef class IntegerListsBackend():
+     cdef readonly min_part, max_part
+     cdef readonly min_slope, max_slope
+     cdef readonly Envelope floor, ceiling
+-    cdef public dict __cached_methods  # Support cached_method
++    cdef public dict _cached_methods  # Support cached_method
+diff --git a/src/sage/combinat/subword_complex.py b/src/sage/combinat/subword_complex.py
+index b7489bdf754..de7eefe946e 100644
+--- a/src/sage/combinat/subword_complex.py
++++ b/src/sage/combinat/subword_complex.py
+@@ -1131,7 +1131,6 @@ def __init__(self, Q, w, algorithm="inductive"):
+         SimplicialComplex.__init__(self, maximal_faces=Fs,
+                                    maximality_check=False,
+                                    category=cat)
+-        self.__custom_name = 'Subword complex'
+         self._W = W
+         try:
+             T = W.coxeter_matrix().coxeter_type()
+diff --git a/src/sage/cpython/cython_metaclass.h b/src/sage/cpython/cython_metaclass.h
+index da06ab75a6b..ecf7f973c3e 100644
+--- a/src/sage/cpython/cython_metaclass.h
++++ b/src/sage/cpython/cython_metaclass.h
+@@ -52,6 +52,16 @@ static CYTHON_INLINE int Sage_PyType_Ready(PyTypeObject* t)
+     if (r < 0)
+         return r;
+ 
++#if PY_VERSION_HEX >= 0x03050000
++    // Cython 3 sets Py_TPFLAGS_HEAPTYPE before calling PyType_Ready,
++    // and resets just after the call. We need to reset it earlier,
++    // since otherwise the call to metaclass.__init__ below may have
++    // illegal memory accesses.
++    // See also:
++    // https://github.com/cython/cython/issues/3603
++    t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE;
++#endif
++
+     /* Set or get metaclass (the type of t) */
+     PyTypeObject* metaclass;
+ 
+diff --git a/src/sage/cpython/cython_metaclass.pyx b/src/sage/cpython/cython_metaclass.pyx
+index a8fe853661d..a8fa92fc1a8 100644
+--- a/src/sage/cpython/cython_metaclass.pyx
++++ b/src/sage/cpython/cython_metaclass.pyx
+@@ -19,13 +19,16 @@ file if you are using one).
+ 
+ In the extension type (a.k.a. ``cdef class``) for which you want to
+ define a metaclass, define a method ``__getmetaclass__`` with a single
+-unused argument. This method should return a type to be used as
++unused argument, and turn off the Cython directive
++``always_allow_keywords``. This method should return a type to be used as
+ metaclass:
+ 
+ .. code-block:: cython
+ 
++    cimport cython
+     cimport sage.cpython.cython_metaclass
+     cdef class MyCustomType():
++        @cython.always_allow_keywords(False)
+         def __getmetaclass__(_):
+             from foo import MyMetaclass
+             return MyMetaclass
+@@ -63,8 +66,10 @@ EXAMPLES::
+ 
+     sage: cython(                                                                       # needs sage.misc.cython
+     ....: '''
++    ....: cimport cython
+     ....: cimport sage.cpython.cython_metaclass
+     ....: cdef class MyCustomType():
++    ....:     @cython.always_allow_keywords(False)
+     ....:     def __getmetaclass__(_):
+     ....:         class MyMetaclass(type):
+     ....:             def __init__(*args):
+@@ -101,8 +106,10 @@ returns a non-type::
+ 
+     sage: cython(                                                                       # needs sage.misc.cython
+     ....: '''
++    ....: cimport cython
+     ....: cimport sage.cpython.cython_metaclass
+     ....: cdef class MyCustomType():
++    ....:     @cython.always_allow_keywords(False)
+     ....:     def __getmetaclass__(_):
+     ....:         return 2
+     ....: ''')
+diff --git a/src/sage/cpython/getattr.pyx b/src/sage/cpython/getattr.pyx
+index 3f603b98040..16f649c083d 100644
+--- a/src/sage/cpython/getattr.pyx
++++ b/src/sage/cpython/getattr.pyx
+@@ -271,7 +271,7 @@ cpdef getattr_from_other_class(self, cls, name):
+ 
+     Caveat: lazy attributes work with extension types only
+     if they allow attribute assignment or have a public attribute
+-    ``__cached_methods`` of type ``<dict>``. This condition
++    ``_cached_methods`` of type ``<dict>``. This condition
+     is satisfied, e.g., by any class that is derived from
+     :class:`Parent`::
+ 
+diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd
+index bdd49225ff2..030c9defa45 100644
+--- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd
++++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd
+@@ -8,7 +8,7 @@ from .polyhedron_face_lattice           cimport PolyhedronFaceLattice
+ 
+ @cython.final
+ cdef class CombinatorialPolyhedron(SageObject):
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+     # Do not assume any of those attributes to be initialized, use the corresponding methods instead.
+     cdef tuple _Vrep                       # the names of VRep, if they exist
+diff --git a/src/sage/groups/perm_gps/permgroup_element.pxd b/src/sage/groups/perm_gps/permgroup_element.pxd
+index a2ac8f20eaa..0a584745f96 100644
+--- a/src/sage/groups/perm_gps/permgroup_element.pxd
++++ b/src/sage/groups/perm_gps/permgroup_element.pxd
+@@ -22,7 +22,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement):
+     cpdef PermutationGroupElement _generate_new_GAP(self, old)
+     cpdef _gap_list(self)
+     cpdef domain(self)
+-    cdef public __custom_name
++    cdef public _SageObject__custom_name
+     cpdef list _act_on_list_on_position(self, list x)
+     cpdef ClonableIntArray _act_on_array_on_position(self, ClonableIntArray x)
+     cpdef ETuple _act_on_etuple_on_position(self, ETuple x)
+diff --git a/src/sage/interfaces/interface.py b/src/sage/interfaces/interface.py
+index f8237d3ad94..3180113c9c7 100644
+--- a/src/sage/interfaces/interface.py
++++ b/src/sage/interfaces/interface.py
+@@ -1169,11 +1169,8 @@ def __repr__(self):
+             s = cr
+         else:
+             s = self._repr_()
+-        if self._name in s:
+-            try:
+-                s = s.replace(self._name, getattr(self, '__custom_name'))
+-            except AttributeError:
+-                pass
++        if self._name in s and self.get_custom_name() is not None:
++            s = s.replace(self._name, self.get_custom_name())
+         if cr:
+             self._cached_repr = s
+         return s
+diff --git a/src/sage/interfaces/singular.py b/src/sage/interfaces/singular.py
+index 4b5c76e2bfa..705fa6f66e1 100644
+--- a/src/sage/interfaces/singular.py
++++ b/src/sage/interfaces/singular.py
+@@ -1400,8 +1400,8 @@ def _repr_(self):
+         """
+         s = super(SingularElement, self)._repr_()
+         if self._name in s:
+-            if (not hasattr(self, "__custom_name")) and self.type() == 'matrix':
+-                s = self.parent().eval('pmat(%s,20)'%(self.name()))
++            if self.get_custom_name() is None and self.type() == 'matrix':
++                s = self.parent().eval('pmat(%s,20)' % (self.name()))
+         return s
+ 
+     def __copy__(self):
+diff --git a/src/sage/libs/arb/arith.pyx b/src/sage/libs/arb/arith.pyx
+index d885f97b238..3b32fe7e8ed 100644
+--- a/src/sage/libs/arb/arith.pyx
++++ b/src/sage/libs/arb/arith.pyx
+@@ -81,5 +81,5 @@ def hilbert_class_polynomial(D):
+     cdef long n = D
+     cdef Polynomial_integer_dense_flint poly
+     poly = PolynomialRing(ZZ, "x", implementation="FLINT")()
+-    acb_modular_hilbert_class_poly(poly.__poly, n)
++    acb_modular_hilbert_class_poly(poly._poly, n)
+     return poly
+diff --git a/src/sage/libs/coxeter3/coxeter.pxd b/src/sage/libs/coxeter3/coxeter.pxd
+index 9d5cb2a3f5d..dbd2b8a61c6 100644
+--- a/src/sage/libs/coxeter3/coxeter.pxd
++++ b/src/sage/libs/coxeter3/coxeter.pxd
+@@ -29,6 +29,3 @@ cdef class CoxGroupElement:
+     cdef CoxGroup _parent_group
+     cdef CoxGroupElement _new(self)
+     cpdef CoxGroup parent_group(self)
+-
+-cdef class CoxGraph:
+-    cdef c_CoxGraph x
+diff --git a/src/sage/libs/gap/element.pyx b/src/sage/libs/gap/element.pyx
+index 1dc53c81f67..478caf9f9d0 100644
+--- a/src/sage/libs/gap/element.pyx
++++ b/src/sage/libs/gap/element.pyx
+@@ -720,7 +720,7 @@ cdef class GapElement(RingElement):
+             ...
+             AttributeError: 'some_name' does not define a GAP function
+         """
+-        if name in ('__dict__', '_getAttributeNames', '__custom_name', 'keys'):
++        if name in ('__dict__', '_getAttributeNames', '_SageObject__custom_name', 'keys'):
+             raise AttributeError('Python special name, not a GAP function.')
+         try:
+             proxy = make_GapElement_MethodProxy\
+diff --git a/src/sage/libs/gap/gap_includes.pxd b/src/sage/libs/gap/gap_includes.pxd
+index 840b8a0042e..1ed4378a6c7 100644
+--- a/src/sage/libs/gap/gap_includes.pxd
++++ b/src/sage/libs/gap/gap_includes.pxd
+@@ -144,3 +144,18 @@ cdef extern from "gap/stringobj.h" nogil:
+     bint IS_STRING(Obj obj)
+     bint IsStringConv(Obj obj)
+     Obj NEW_STRING(Int)
++
++
++cdef extern from "<structmember.h>" nogil:
++    """
++    /* Hack: Cython 3.0 automatically includes <structmember.h>, which
++     * defines several macros that collides with enum definitions in
++     * gap/objects.h. We need to include the header explicitly and
++     * undefine these macros.
++     */
++    #undef T_INT
++    #undef T_STRING
++    #undef T_CHAR
++    #undef T_BOOL
++    """
++    pass
+diff --git a/src/sage/libs/lcalc/lcalc_Lfunction.pxd b/src/sage/libs/lcalc/lcalc_Lfunction.pxd
+index 5edf0844f3e..1d595180a6f 100644
+--- a/src/sage/libs/lcalc/lcalc_Lfunction.pxd
++++ b/src/sage/libs/lcalc/lcalc_Lfunction.pxd
+@@ -99,19 +99,19 @@ cdef extern from "lcalc_sage.h":
+ ################
+ 
+ # strange bug, I can't compile without this trick ???
+-# it's only used in __typedN
++# it's only used in _typedN
+ ctypedef double Double
+ 
+ cdef class Lfunction:
+     cdef void *thisptr
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r)
+-    cdef c_Complex __value(self,c_Complex s,int derivative)
+-    cdef c_Complex __hardy_z_function(self,c_Complex s)
+-    cdef int __compute_rank(self)
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r)
++    cdef c_Complex _value(self,c_Complex s,int derivative)
++    cdef c_Complex _hardy_z_function(self,c_Complex s)
++    cdef int _compute_rank(self)
+     #strange bug, replacing Double with double gives me a compile error
+-    cdef Double __typedN(self, double T)
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize,doublevec *result)
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec* result)
++    cdef Double _typedN(self, double T)
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize,doublevec *result)
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec* result)
+ 
+     cdef str _repr
+ 
+diff --git a/src/sage/libs/lcalc/lcalc_Lfunction.pyx b/src/sage/libs/lcalc/lcalc_Lfunction.pyx
+index 6e9005c502b..7b871ed049f 100644
+--- a/src/sage/libs/lcalc/lcalc_Lfunction.pyx
++++ b/src/sage/libs/lcalc/lcalc_Lfunction.pyx
+@@ -99,7 +99,7 @@ cdef class Lfunction:
+             tmpc=CCC(residue[i])
+             r[i+1] = new_Complex(mpfr_get_d(tmpc.__re, MPFR_RNDN), mpfr_get_d(tmpc.__im, MPFR_RNDN))
+ 
+-        self.__init_fun(NAME, what_type, dirichlet_coefficient, Period, q,  w,  A, g, l, n_poles, p, r)
++        self._init_fun(NAME, what_type, dirichlet_coefficient, Period, q,  w,  A, g, l, n_poles, p, r)
+ 
+         if name:
+             name += ': '
+@@ -180,7 +180,7 @@ cdef class Lfunction:
+         """
+         cdef ComplexNumber complexified_s = CCC(s)
+         cdef c_Complex z = new_Complex(mpfr_get_d(complexified_s.__re, MPFR_RNDN), mpfr_get_d(complexified_s.__im, MPFR_RNDN))
+-        cdef c_Complex result = self.__value(z, derivative)
++        cdef c_Complex result = self._value(z, derivative)
+         return CCC(result.real(),result.imag())
+ 
+     def hardy_z_function(self, s):
+@@ -223,7 +223,7 @@ cdef class Lfunction:
+         #This takes s -> .5 + I*s
+         cdef ComplexNumber complexified_s = CCC(0.5)+ CCC(0,1)*CCC(s)
+         cdef c_Complex z = new_Complex(mpfr_get_d(complexified_s.__re, MPFR_RNDN), mpfr_get_d(complexified_s.__im, MPFR_RNDN))
+-        cdef c_Complex result = self.__hardy_z_function(z)
++        cdef c_Complex result = self._hardy_z_function(z)
+         return CCC(result.real(),result.imag())
+ 
+ 
+@@ -249,9 +249,9 @@ cdef class Lfunction:
+             3
+ 
+         """
+-        return self.__compute_rank()
++        return self._compute_rank()
+ 
+-    def __N(self, T):
++    def _N(self, T):
+         """
+         Compute the number of zeroes upto height `T` using the formula for
+         `N(T)` with the error of `S(T)`. Please do not use this. It is only
+@@ -262,12 +262,12 @@ cdef class Lfunction:
+             sage: from sage.libs.lcalc.lcalc_Lfunction import *
+             sage: chi = DirichletGroup(5)[2] #This is a quadratic character
+             sage: L=Lfunction_from_character(chi, type="complex")
+-            sage: L.__N(10) # abs tol 1e-8
++            sage: L._N(10) # abs tol 1e-8
+             4.0
+         """
+         cdef RealNumber real_T=RRR(T)
+         cdef double double_T = mpfr_get_d(real_T.value, MPFR_RNDN)
+-        cdef double res_d = self.__typedN(double_T)
++        cdef double res_d = self._typedN(double_T)
+         return RRR(res_d)
+ 
+     def find_zeros(self, T1, T2, stepsize):
+@@ -323,7 +323,7 @@ cdef class Lfunction:
+         cdef RealNumber real_T2 = RRR(T2)
+         cdef RealNumber real_stepsize = RRR(stepsize)
+         sig_on()
+-        self.__find_zeros_v( mpfr_get_d(real_T1.value, MPFR_RNDN), mpfr_get_d(real_T2.value, MPFR_RNDN), mpfr_get_d(real_stepsize.value, MPFR_RNDN),&result)
++        self._find_zeros_v( mpfr_get_d(real_T1.value, MPFR_RNDN), mpfr_get_d(real_T2.value, MPFR_RNDN), mpfr_get_d(real_stepsize.value, MPFR_RNDN),&result)
+         sig_off()
+         i=result.size()
+         returnvalue = []
+@@ -399,7 +399,7 @@ cdef class Lfunction:
+         cdef const char* message_stamp = ""
+         cdef doublevec result
+         sig_on()
+-        self.__find_zeros(count, start, max_refine, rank, message_stamp, &result)
++        self._find_zeros(count, start, max_refine, rank, message_stamp, &result)
+         sig_off()
+         returnvalue = []
+         for i in range(result.size()):
+@@ -408,25 +408,25 @@ cdef class Lfunction:
+         return returnvalue
+ 
+     # Needs to be overriden
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         raise NotImplementedError
+ 
+-    cdef c_Complex __value(self,c_Complex s,int derivative):
++    cdef c_Complex _value(self,c_Complex s,int derivative):
+         raise NotImplementedError
+ 
+-    cdef c_Complex __hardy_z_function(self,c_Complex s):
++    cdef c_Complex _hardy_z_function(self,c_Complex s):
+         raise NotImplementedError
+ 
+-    cdef int __compute_rank(self):
++    cdef int _compute_rank(self):
+         raise NotImplementedError
+ 
+-    cdef double __typedN(self,double T):
++    cdef double _typedN(self,double T):
+         raise NotImplementedError
+ 
+-    cdef void __find_zeros_v(self,double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self,double T1, double T2, double stepsize, doublevec *result):
+         raise NotImplementedError
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         raise NotImplementedError
+ 
+ ##############################################################################
+@@ -497,7 +497,7 @@ cdef class Lfunction_I(Lfunction):
+         self._repr += " with integer Dirichlet coefficients"
+ 
+     # override
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         cdef int N = len(dirichlet_coeff)
+         cdef Integer tmpi
+         cdef int * coeffs = new_ints(N+1) #lcalc ignores 0the coefficient
+@@ -507,22 +507,22 @@ cdef class Lfunction_I(Lfunction):
+         self.thisptr=new_c_Lfunction_I(NAME, what_type,  N, coeffs, Period, q,  w,  A, g, l, n_poles, p, r)
+         del_ints(coeffs)
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_I *>(self.thisptr)).value(s, derivative, "pure")
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_I *>(self.thisptr)).value(s, 0, "rotated pure")
+ 
+-    cdef int __compute_rank(self):
++    cdef int _compute_rank(self):
+         return (<c_Lfunction_I *>(self.thisptr)).compute_rank()
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_I *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_I *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_I *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     # debug tools
+@@ -633,7 +633,7 @@ cdef class Lfunction_D(Lfunction):
+         self._repr += " with real Dirichlet coefficients"
+ 
+     # override
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         cdef int i
+         cdef RealNumber tmpr
+         cdef int N = len(dirichlet_coeff)
+@@ -644,23 +644,23 @@ cdef class Lfunction_D(Lfunction):
+         self.thisptr=new_c_Lfunction_D(NAME, what_type,  N, coeffs, Period, q,  w,  A, g, l, n_poles, p, r)
+         del_doubles(coeffs)
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_D *>(self.thisptr)).value(s, derivative, "pure")
+ 
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_D *>(self.thisptr)).value(s, 0, "rotated pure")
+ 
+-    cdef inline int __compute_rank(self):
++    cdef inline int _compute_rank(self):
+         return (<c_Lfunction_D *>(self.thisptr)).compute_rank()
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_D *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_D *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start,double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start,double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_D *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     # debug tools
+@@ -773,7 +773,7 @@ cdef class Lfunction_C:
+         self._repr += " with complex Dirichlet coefficients"
+ 
+     # override
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         cdef int i
+         cdef int N = len(dirichlet_coeff)
+         cdef ComplexNumber tmpc
+@@ -788,24 +788,24 @@ cdef class Lfunction_C:
+ 
+         del_Complexes(coeffs)
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_C *>(self.thisptr)).value(s, derivative, "pure")
+ 
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_C *>(self.thisptr)).value(s, 0,"rotated pure")
+ 
+-    cdef inline int __compute_rank(self):
++    cdef inline int _compute_rank(self):
+         return (<c_Lfunction_C *>(self.thisptr)).compute_rank()
+ 
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_C *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_C *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_C *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     # debug tools
+@@ -873,24 +873,24 @@ cdef class Lfunction_Zeta(Lfunction):
+         self.thisptr = new_c_Lfunction_Zeta()
+         self._repr = "The Riemann zeta function"
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_Zeta *>(self.thisptr)).value(s, derivative, "pure")
+ 
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_Zeta *>(self.thisptr)).value(s, 0, "rotated pure")
+ 
+-    cdef inline int __compute_rank(self):
++    cdef inline int _compute_rank(self):
+         return (<c_Lfunction_Zeta *>(self.thisptr)).compute_rank()
+ 
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_Zeta *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_Zeta *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_Zeta *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     def __dealloc__(self):
+diff --git a/src/sage/libs/linkages/padics/Polynomial_ram.pxi b/src/sage/libs/linkages/padics/Polynomial_ram.pxi
+index 1ac51f1211f..e0584ecb8ad 100644
+--- a/src/sage/libs/linkages/padics/Polynomial_ram.pxi
++++ b/src/sage/libs/linkages/padics/Polynomial_ram.pxi
+@@ -55,16 +55,16 @@ cdef inline bint creduce(celement out, celement a, long prec, PowComputer_ prime
+     """
+     cdef celement ared = a % prime_pow.modulus
+     if ared is a and out is not a:
+-        out.__coeffs = ared.__coeffs[:]
++        out._coeffs = ared._coeffs[:]
+     else:
+-        out.__coeffs = ared.__coeffs
++        out._coeffs = ared._coeffs
+     cdef long coeff_prec = prec / prime_pow.e + 1
+     cdef long break_pt = prec % prime_pow.e
+-    for i in range(len(out.__coeffs)):
++    for i in range(len(out._coeffs)):
+         if i == break_pt:
+             coeff_prec -= 1
+-        out.__coeffs[i] = out.__coeffs[i].add_bigoh(coeff_prec)
+-    out.__normalize()
++        out._coeffs[i] = out._coeffs[i].add_bigoh(coeff_prec)
++    out._normalize()
+     return out == 0
+ 
+ cdef inline bint creduce_small(celement out, celement a, long prec, PowComputer_ prime_pow) except -1:
+@@ -116,7 +116,7 @@ cdef inline long cvaluation(celement a, long prec, PowComputer_ prime_pow) excep
+     higher.
+ 
+     """
+-    C = a.__coeffs
++    C = a._coeffs
+     if not C:
+         return prec
+     cdef long ret = maxordp
+@@ -161,7 +161,7 @@ cdef inline int cshift(celement shifted, celement rem, celement a, long n, long
+         v = cvaluation(a, prec, prime_pow)
+         notrunc = (v >= -n)
+     if notrunc:
+-        rem.__coeffs = []
++        rem._coeffs = []
+         return cshift_notrunc(shifted, a, n, prec, prime_pow, reduce_afterward)
+     if v > 0:
+         b = prime_pow.poly_ring(0)
+@@ -185,7 +185,7 @@ cdef inline int cshift(celement shifted, celement rem, celement a, long n, long
+     if reduce_afterward:
+         creduce(shifted, a, prec, prime_pow)
+     else:
+-        shifted.__coeffs = a.__coeffs[:]
++        shifted._coeffs = a._coeffs[:]
+ 
+ cdef inline int cshift_notrunc(celement out, celement a, long n, long prec, PowComputer_ prime_pow, bint reduce_afterward) except -1:
+     r"""
+@@ -236,7 +236,7 @@ cdef inline int cshift_notrunc(celement out, celement a, long n, long prec, PowC
+     if reduce_afterward:
+         creduce(out, a, prec, prime_pow)
+     else:
+-        out.__coeffs = a.__coeffs[:]
++        out._coeffs = a._coeffs[:]
+ 
+ cdef inline int cinvert(celement out, celement a, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -253,7 +253,7 @@ cdef inline int cinvert(celement out, celement a, long prec, PowComputer_ prime_
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = prime_pow.invert(a, prec).__coeffs
++    out._coeffs = prime_pow.invert(a, prec)._coeffs
+     creduce(out, out, prec, prime_pow)
+ 
+ cdef inline int cdivunit(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+@@ -335,7 +335,7 @@ cdef inline cexpansion_next(celement value, expansion_mode mode, long curpower,
+     # the following is specific to the ramified over unramified case.
+     modp_rep, term = value[0]._modp_rep(mode == smallest_mode)
+     if term:
+-        value.__coeffs[0] -= modp_rep
++        value._coeffs[0] -= modp_rep
+     cshift_notrunc(value, value, -1, curpower, prime_pow, False)
+     return term
+ 
+@@ -354,10 +354,10 @@ cdef inline cexpansion_getitem(celement value, long m, PowComputer_ prime_pow):
+     while m >= 0:
+         modp_rep, term = value[0]._modp_rep()
+         if m:
+-            if len(value.__coeffs):
+-                value.__coeffs[0] -= modp_rep
++            if len(value._coeffs):
++                value._coeffs[0] -= modp_rep
+             else:
+-                value.__coeffs.append(-modp_rep)
++                value._coeffs.append(-modp_rep)
+             cshift_notrunc(value, value, -1, 1, prime_pow, False)
+         m -= 1
+     return term
+@@ -379,9 +379,9 @@ cdef int cteichmuller(celement out, celement value, long prec, PowComputer_ prim
+ 
+     """
+     if value[0].valuation() > 0:
+-        out.__coeffs = []
++        out._coeffs = []
+     else:
+-        out.__coeffs = [value[0].parent().teichmuller(value[0])]
++        out._coeffs = [value[0].parent().teichmuller(value[0])]
+ 
+ cdef list ccoefficients(celement x, long valshift, long prec, PowComputer_ prime_pow):
+     """
+diff --git a/src/sage/libs/linkages/padics/Polynomial_shared.pxi b/src/sage/libs/linkages/padics/Polynomial_shared.pxi
+index 495dc6b0848..367bbc2f33d 100644
+--- a/src/sage/libs/linkages/padics/Polynomial_shared.pxi
++++ b/src/sage/libs/linkages/padics/Polynomial_shared.pxi
+@@ -106,7 +106,7 @@ cdef inline int ccmp(celement a, celement b, long prec, bint reduce_a, bint redu
+     if not (reduce_a or reduce_b):
+         return 0 if a == b else 1
+     csub(prime_pow.tmp_ccmp_a, a, b, prec, prime_pow)
+-    coeffs = prime_pow.tmp_ccmp_a.__coeffs
++    coeffs = prime_pow.tmp_ccmp_a._coeffs
+     cdef long i, coeff_prec, break_pt
+     if prime_pow.e == 1:
+         for i in range(prime_pow.tmp_ccmp_a.degree()+1):
+@@ -186,9 +186,9 @@ cdef inline int cneg(celement out, celement a, long prec, PowComputer_ prime_pow
+     """
+     cdef celement ma = -a
+     if ma is a:
+-        out.__coeffs = ma.__coeffs[:]
++        out._coeffs = ma._coeffs[:]
+     else:
+-        out.__coeffs = ma.__coeffs
++        out._coeffs = ma._coeffs
+ 
+ cdef inline int cadd(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -211,9 +211,9 @@ cdef inline int cadd(celement out, celement a, celement b, long prec, PowCompute
+     """
+     cdef celement sm = a + b
+     if sm is a or sm is b:
+-        out.__coeffs = sm.__coeffs[:]
++        out._coeffs = sm._coeffs[:]
+     else:
+-        out.__coeffs = sm.__coeffs
++        out._coeffs = sm._coeffs
+ 
+ cdef inline int csub(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -236,9 +236,9 @@ cdef inline int csub(celement out, celement a, celement b, long prec, PowCompute
+     """
+     cdef celement df = a - b
+     if df is a or df is b:
+-        out.__coeffs = df.__coeffs[:]
++        out._coeffs = df._coeffs[:]
+     else:
+-        out.__coeffs = df.__coeffs
++        out._coeffs = df._coeffs
+ 
+ cdef inline int cmul(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -261,9 +261,9 @@ cdef inline int cmul(celement out, celement a, celement b, long prec, PowCompute
+     """
+     cdef celement pd = a*b
+     if pd is a or pd is b:
+-        out.__coeffs = pd.__coeffs[:]
++        out._coeffs = pd._coeffs[:]
+     else:
+-        out.__coeffs = pd.__coeffs
++        out._coeffs = pd._coeffs
+ 
+ cdef inline int csetone(celement out, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -276,7 +276,7 @@ cdef inline int csetone(celement out, PowComputer_ prime_pow) except -1:
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = [prime_pow.base_ring(1)]
++    out._coeffs = [prime_pow.base_ring(1)]
+ 
+ cdef inline int csetzero(celement out, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -289,7 +289,7 @@ cdef inline int csetzero(celement out, PowComputer_ prime_pow) except -1:
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = []
++    out._coeffs = []
+ 
+ cdef inline bint cisone(celement a, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -330,7 +330,7 @@ cdef inline int ccopy(celement out, celement a, PowComputer_ prime_pow) except -
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = a.__coeffs[:]
++    out._coeffs = a._coeffs[:]
+ 
+ cdef inline cpickle(celement a, PowComputer_ prime_pow):
+     r"""
+@@ -343,7 +343,7 @@ cdef inline cpickle(celement a, PowComputer_ prime_pow):
+     - ``prime_pow`` the ``PowComputer`` for the ring
+ 
+     """
+-    return a.__coeffs
++    return a._coeffs
+ 
+ cdef inline int cunpickle(celement out, x, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -358,7 +358,7 @@ cdef inline int cunpickle(celement out, x, PowComputer_ prime_pow) except -1:
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = x
++    out._coeffs = x
+ 
+ cdef inline long chash(celement a, long ordp, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -413,9 +413,9 @@ cdef int cconv(celement out, x, long prec, long valshift, PowComputer_ prime_pow
+     else:
+         xx = prime_pow.poly_ring(x)
+     if xx is x:
+-        out.__coeffs = xx.__coeffs[:]
++        out._coeffs = xx._coeffs[:]
+     else:
+-        out.__coeffs = xx.__coeffs
++        out._coeffs = xx._coeffs
+     if valshift > 0:
+         cshift_notrunc(out, out, -valshift, prec, prime_pow, True)
+     elif valshift == 0:
+@@ -458,12 +458,12 @@ cdef inline long cconv_mpz_t(celement out, mpz_t x, long prec, bint absolute, Po
+     mpz_set(n.value, x)
+ 
+     if n:
+-        out.__coeffs = [prime_pow.base_ring(n)]
++        out._coeffs = [prime_pow.base_ring(n)]
+         if not absolute:
+             valuation = cremove(out, out, prec, prime_pow)
+         creduce(out, out, prec, prime_pow)
+     else:
+-        out.__coeffs = []
++        out._coeffs = []
+ 
+     return valuation
+ 
+@@ -492,12 +492,12 @@ cdef inline int cconv_mpz_t_out(mpz_t out, celement x, long valshift, long prec,
+     else:
+         prime_pow.powhelper_cconv_out = x
+ 
+-    if len(prime_pow.powhelper_cconv_out.__coeffs) == 0:
++    if len(prime_pow.powhelper_cconv_out._coeffs) == 0:
+         mpz_set_ui(out, 0)
+-    elif len(prime_pow.powhelper_cconv_out.__coeffs) == 1:
++    elif len(prime_pow.powhelper_cconv_out._coeffs) == 1:
+         # recursively let the underlying polynomial convert the constant
+         # coefficient to an integer (if possible)
+-        n = ZZ(prime_pow.powhelper_cconv_out.__coeffs[0])
++        n = ZZ(prime_pow.powhelper_cconv_out._coeffs[0])
+         mpz_set(out, n.value)
+     else:
+         raise ValueError("cannot convert to integer")
+@@ -532,7 +532,7 @@ cdef inline long cconv_mpq_t(celement out, mpq_t x, long prec, bint absolute, Po
+     """
+     cdef Rational r = PY_NEW(Rational)
+     mpq_set(r.value, x)
+-    out.__coeffs = [prime_pow.base_ring(r)]
++    out._coeffs = [prime_pow.base_ring(r)]
+ 
+     if not absolute:
+         return cremove(out, out, prec, prime_pow)
+@@ -565,12 +565,12 @@ cdef inline int cconv_mpq_t_out(mpq_t out, celement x, long valshift, long prec,
+     else:
+         prime_pow.powhelper_cconv_out = x
+ 
+-    if len(prime_pow.powhelper_cconv_out.__coeffs) == 0:
++    if len(prime_pow.powhelper_cconv_out._coeffs) == 0:
+         mpq_set_ui(out, 0, 1)
+-    elif len(prime_pow.powhelper_cconv_out.__coeffs) == 1:
++    elif len(prime_pow.powhelper_cconv_out._coeffs) == 1:
+         # recursively let the underlying polynomial convert the constant
+         # coefficient to a rational (if possible)
+-        c = QQ(prime_pow.powhelper_cconv_out.__coeffs[0])
++        c = QQ(prime_pow.powhelper_cconv_out._coeffs[0])
+         mpq_set(out, c.value)
+     else:
+         raise ValueError("cannot convert to rational")
+diff --git a/src/sage/libs/ntl/ntl_lzz_p.pyx b/src/sage/libs/ntl/ntl_lzz_p.pyx
+index 161d0782bc2..af86b9bcf69 100644
+--- a/src/sage/libs/ntl/ntl_lzz_p.pyx
++++ b/src/sage/libs/ntl/ntl_lzz_p.pyx
+@@ -89,19 +89,19 @@ cdef class ntl_zz_p():
+         #self.c.restore_c()   ## This was done in __new__
+ 
+         if isinstance(a, IntegerMod_int):
+-            if (self.c.p == (<IntegerMod_int>a).__modulus.int32): ## this is slow
++            if (self.c.p == (<IntegerMod_int>a)._modulus.int32): ## this is slow
+                 self.x = (<IntegerMod_int>a).ivalue
+             else:
+                 raise ValueError("Mismatched modulus for converting to zz_p.")
+ 
+         elif isinstance(a, IntegerMod_int64):
+-            if (self.c.p == (<IntegerMod_int64>a).__modulus.int64): ## this is slow
++            if (self.c.p == (<IntegerMod_int64>a)._modulus.int64): ## this is slow
+                 self.x = (<IntegerMod_int64>a).ivalue
+             else:
+                 raise ValueError("Mismatched modulus for converting to zz_p.")
+ 
+         elif isinstance(a, IntegerMod_gmp):
+-            if (p_sage == (<IntegerMod_gmp>a).__modulus.sageInteger): ## this is slow
++            if (p_sage == (<IntegerMod_gmp>a)._modulus.sageInteger): ## this is slow
+                 self.x = mpz_get_si((<IntegerMod_gmp>a).value)
+             else:
+                 raise ValueError("Mismatched modulus for converting to zz_p.")
+diff --git a/src/sage/libs/ntl/ntl_lzz_pX.pyx b/src/sage/libs/ntl/ntl_lzz_pX.pyx
+index 24b503a9a62..7d19cc55e37 100644
+--- a/src/sage/libs/ntl/ntl_lzz_pX.pyx
++++ b/src/sage/libs/ntl/ntl_lzz_pX.pyx
+@@ -108,17 +108,17 @@ cdef class ntl_zz_pX():
+             a = ls[i]
+ 
+             if isinstance(a, IntegerMod_int):
+-                if (self.c.p == (<IntegerMod_int>a).__modulus.int32): ## this is slow
++                if (self.c.p == (<IntegerMod_int>a)._modulus.int32): ## this is slow
+                     zz_pX_SetCoeff_long(self.x, i, (<IntegerMod_int>a).ivalue)
+                 else:
+                     raise ValueError("Mismatched modulus for converting to zz_pX.")
+             elif isinstance(a, IntegerMod_int64):
+-                if (self.c.p == (<IntegerMod_int64>a).__modulus.int64): ## this is slow
++                if (self.c.p == (<IntegerMod_int64>a)._modulus.int64): ## this is slow
+                     zz_pX_SetCoeff_long(self.x, i, (<IntegerMod_int64>a).ivalue)
+                 else:
+                     raise ValueError("Mismatched modulus for converting to zz_pX.")
+             elif isinstance(a, IntegerMod_gmp):
+-                if (p_sage == (<IntegerMod_gmp>a).__modulus.sageInteger): ## this is slow
++                if (p_sage == (<IntegerMod_gmp>a)._modulus.sageInteger): ## this is slow
+                     zz_pX_SetCoeff_long(self.x, i, mpz_get_si((<IntegerMod_gmp>a).value))
+                 else:
+                     raise ValueError("Mismatched modulus for converting to zz_pX.")
+diff --git a/src/sage/matrix/matrix_complex_ball_dense.pyx b/src/sage/matrix/matrix_complex_ball_dense.pyx
+index 9e14079c6d4..47ca41070fa 100644
+--- a/src/sage/matrix/matrix_complex_ball_dense.pyx
++++ b/src/sage/matrix/matrix_complex_ball_dense.pyx
+@@ -664,7 +664,7 @@ cdef class Matrix_complex_ball_dense(Matrix_dense):
+         Pol = polynomial_ring_constructor._single_variate(self.base_ring(), var)
+         cdef Polynomial_complex_arb res = Polynomial_complex_arb(Pol)
+         sig_on()
+-        acb_mat_charpoly(res.__poly, self.value, prec(self))
++        acb_mat_charpoly(res._poly, self.value, prec(self))
+         sig_off()
+         return res
+ 
+diff --git a/src/sage/matrix/matrix_cyclo_dense.pyx b/src/sage/matrix/matrix_cyclo_dense.pyx
+index 15ff6394951..f1ed9af8403 100644
+--- a/src/sage/matrix/matrix_cyclo_dense.pyx
++++ b/src/sage/matrix/matrix_cyclo_dense.pyx
+@@ -396,11 +396,11 @@ cdef class Matrix_cyclo_dense(Matrix_dense):
+             # Now set k-th entry of x's numerator to tmp
+             fmpz_get_mpz(tmp, ftmp)
+             mpz_to_ZZ(&coeff, tmp)
+-            ZZX_SetCoeff(x.__numerator, k, coeff)
++            ZZX_SetCoeff(x._numerator, k, coeff)
+ 
+         # Set the denominator of x to denom.
+         fmpz_get_mpz(tmp, denom)
+-        mpz_to_ZZ(&x.__denominator, tmp)
++        mpz_to_ZZ(&x._denominator, tmp)
+         fmpz_clear(denom)
+         mpz_clear(tmp)
+         fmpz_clear(ftmp)
+diff --git a/src/sage/matrix/matrix_integer_dense.pyx b/src/sage/matrix/matrix_integer_dense.pyx
+index 9c509104967..8088350577c 100644
+--- a/src/sage/matrix/matrix_integer_dense.pyx
++++ b/src/sage/matrix/matrix_integer_dense.pyx
+@@ -1371,12 +1371,12 @@ cdef class Matrix_integer_dense(Matrix_dense):
+         if algorithm == 'flint':
+             g = (<Polynomial_integer_dense_flint> PolynomialRing(ZZ, names=var).gen())._new()
+             sig_on()
+-            fmpz_mat_charpoly(g.__poly, self._matrix)
++            fmpz_mat_charpoly(g._poly, self._matrix)
+             sig_off()
+         elif algorithm == 'linbox':
+             g = (<Polynomial_integer_dense_flint> PolynomialRing(ZZ, names=var).gen())._new()
+             sig_on()
+-            linbox_fmpz_mat_charpoly(g.__poly, self._matrix)
++            linbox_fmpz_mat_charpoly(g._poly, self._matrix)
+             sig_off()
+         elif algorithm == 'generic':
+             g = Matrix_dense.charpoly(self, var)
+@@ -1460,7 +1460,7 @@ cdef class Matrix_integer_dense(Matrix_dense):
+         if algorithm == 'linbox':
+             g = (<Polynomial_integer_dense_flint> PolynomialRing(ZZ, names=var).gen())._new()
+             sig_on()
+-            linbox_fmpz_mat_minpoly(g.__poly, self._matrix)
++            linbox_fmpz_mat_minpoly(g._poly, self._matrix)
+             sig_off()
+         elif algorithm == 'generic':
+             g = Matrix_dense.minpoly(self, var)
+diff --git a/src/sage/matrix/matrix_integer_sparse.pyx b/src/sage/matrix/matrix_integer_sparse.pyx
+index a41677c7b6a..83d5ee42fbe 100644
+--- a/src/sage/matrix/matrix_integer_sparse.pyx
++++ b/src/sage/matrix/matrix_integer_sparse.pyx
+@@ -869,10 +869,10 @@ cdef class Matrix_integer_sparse(Matrix_sparse):
+         sig_off()
+ 
+         cdef size_t i
+-        fmpz_poly_fit_length(g.__poly, p.size())
++        fmpz_poly_fit_length(g._poly, p.size())
+         for i in range(p.size()):
+-            fmpz_poly_set_coeff_mpz(g.__poly, i, p[0][i].get_mpz_const())
+-        _fmpz_poly_set_length(g.__poly, p.size())
++            fmpz_poly_set_coeff_mpz(g._poly, i, p[0][i].get_mpz_const())
++        _fmpz_poly_set_length(g._poly, p.size())
+ 
+         del M
+         del p
+@@ -968,10 +968,10 @@ cdef class Matrix_integer_sparse(Matrix_sparse):
+         sig_off()
+ 
+         cdef size_t i
+-        fmpz_poly_fit_length(g.__poly, p.size())
++        fmpz_poly_fit_length(g._poly, p.size())
+         for i in range(p.size()):
+-            fmpz_poly_set_coeff_mpz(g.__poly, i, p[0][i].get_mpz_const())
+-        _fmpz_poly_set_length(g.__poly, p.size())
++            fmpz_poly_set_coeff_mpz(g._poly, i, p[0][i].get_mpz_const())
++        _fmpz_poly_set_length(g._poly, p.size())
+ 
+         del M
+         del p
+diff --git a/src/sage/matroids/basis_exchange_matroid.pxd b/src/sage/matroids/basis_exchange_matroid.pxd
+index aec3bb54c42..28cc7ad868c 100644
+--- a/src/sage/matroids/basis_exchange_matroid.pxd
++++ b/src/sage/matroids/basis_exchange_matroid.pxd
+@@ -15,13 +15,13 @@ cdef class BasisExchangeMatroid(Matroid):
+     cdef _weak_invariant_var, _strong_invariant_var, _heuristic_invariant_var
+     cdef SetSystem _weak_partition_var, _strong_partition_var, _heuristic_partition_var
+ 
+-    cdef __relabel(self, l)
++    cdef _relabel(self, l)
+ 
+-    cdef __pack(self, bitset_t, X)
++    cdef _pack(self, bitset_t, X)
+     cdef __unpack(self, bitset_t)
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1
+-    cdef int __exchange(self, long x, long y) except -1
+-    cdef int __move(self, bitset_t X, bitset_t Y) except -1
++    cdef bint _is_exchange_pair(self, long x, long y) except -1
++    cdef int _exchange(self, long x, long y) except -1
++    cdef int _move(self, bitset_t X, bitset_t Y) except -1
+     cdef __fundamental_cocircuit(self, bitset_t, long x)
+     cdef __fundamental_circuit(self, bitset_t, long y)
+ 
+@@ -30,7 +30,7 @@ cdef class BasisExchangeMatroid(Matroid):
+     cdef __closure(self, bitset_t, bitset_t)
+     cdef __max_coindependent(self, bitset_t, bitset_t)
+     cdef __cocircuit(self, bitset_t, bitset_t)
+-    cdef __coclosure(self, bitset_t, bitset_t)
++    cdef _coclosure_internal(self, bitset_t, bitset_t)
+ 
+     cdef __augment(self, bitset_t, bitset_t, bitset_t)
+     cdef bint __is_independent(self, bitset_t F) except -1
+diff --git a/src/sage/matroids/basis_exchange_matroid.pyx b/src/sage/matroids/basis_exchange_matroid.pyx
+index 90d10842d46..015fa8b8df3 100644
+--- a/src/sage/matroids/basis_exchange_matroid.pyx
++++ b/src/sage/matroids/basis_exchange_matroid.pyx
+@@ -57,10 +57,10 @@ cdef class BasisExchangeMatroid(Matroid):
+ 
+     This base exchange graph is not stored as such, but should be provided
+     implicitly by the child class in the form of two methods
+-    ``__is_exchange_pair(x, y)`` and ``__exchange(x, y)``, as well as an
++    ``_is_exchange_pair(x, y)`` and ``_exchange(x, y)``, as well as an
+     initial basis. At any moment, BasisExchangeMatroid keeps a current basis
+-    `B`. The method ``__is_exchange_pair(x, y)`` should return a boolean
+-    indicating whether `B - x + y` is a basis. The method ``__exchange(x, y)``
++    `B`. The method ``_is_exchange_pair(x, y)`` should return a boolean
++    indicating whether `B - x + y` is a basis. The method ``_exchange(x, y)``
+     is called when the current basis `B` is replaced by said `B-x + y`. It is
+     up to the child class to update its internal data structure to make
+     information relative to the new basis more accessible. For instance, a
+@@ -81,16 +81,16 @@ cdef class BasisExchangeMatroid(Matroid):
+     - :class:`BasisMatroid <sage.matroids.basis_matroid.BasisMatroid>`: keeps
+       a list of all bases.
+ 
+-        - ``__is_exchange_pair(x, y)`` reduces to a query whether `B - x + y`
++        - ``_is_exchange_pair(x, y)`` reduces to a query whether `B - x + y`
+           is a basis.
+-        - ``__exchange(x, y)`` has no work to do.
++        - ``_exchange(x, y)`` has no work to do.
+ 
+     - :class:`LinearMatroid <sage.matroids.linear_matroid.LinearMatroid>`:
+       keeps a matrix representation `A` of the matroid so that `A[B] = I`.
+ 
+-        - ``__is_exchange_pair(x, y)`` reduces to testing whether `A[r, y]`
++        - ``_is_exchange_pair(x, y)`` reduces to testing whether `A[r, y]`
+           is nonzero, where `A[r, x]=1`.
+-        - ``__exchange(x, y)`` should modify the matrix so that `A[B - x + y]`
++        - ``_exchange(x, y)`` should modify the matrix so that `A[B - x + y]`
+           becomes `I`, which means pivoting on `A[r, y]`.
+ 
+     - ``TransversalMatroid`` (not yet implemented): If `A` is a set of subsets
+@@ -100,17 +100,17 @@ cdef class BasisExchangeMatroid(Matroid):
+       edge `(A_i,e)` if `e` is in the subset `A_i`. At any time you keep a
+       maximum matching `M` of `G` covering the current basis `B`.
+ 
+-        - ``__is_exchange_pair(x, y)`` checks for the existence of an
++        - ``_is_exchange_pair(x, y)`` checks for the existence of an
+           `M`-alternating path `P` from `y` to `x`.
+-        - ``__exchange(x, y)`` replaces `M` by the symmetric difference of
++        - ``_exchange(x, y)`` replaces `M` by the symmetric difference of
+           `M` and `E(P)`.
+ 
+     - ``AlgebraicMatroid`` (not yet implemented): keeps a list of polynomials
+       in variables `E - B + e` for each variable `e` in `B`.
+ 
+-        - ``__is_exchange_pair(x, y)`` checks whether the polynomial that
++        - ``_is_exchange_pair(x, y)`` checks whether the polynomial that
+           relates `y` to `E-B` uses `x`.
+-        - ``__exchange(x, y)`` make new list of polynomials by computing
++        - ``_exchange(x, y)`` make new list of polynomials by computing
+           resultants.
+ 
+     All but the first of the above matroids are algebraic, and all
+@@ -139,7 +139,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         This initializer sets up a correspondence between elements of
+         ``groundset`` and ``range(len(groundset))``. ``BasisExchangeMatroid``
+         uses this correspondence for encoding of subsets of the groundset as
+-        bitpacked sets of integers --- see ``__pack()`` and ``__unpack()``. In
++        bitpacked sets of integers --- see ``_pack()`` and ``__unpack()``. In
+         general, methods of ``BasisExchangeMatroid`` having a name starting
+         with two underscores deal with such encoded subsets.
+ 
+@@ -180,7 +180,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             self._idx[self._E[i]] = i
+ 
+         if basis is not None:
+-            self.__pack(self._current_basis, frozenset(basis))
++            self._pack(self._current_basis, frozenset(basis))
+ 
+     def __dealloc__(self):
+         bitset_free(self._current_basis)
+@@ -191,7 +191,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_free(self._output)
+         bitset_free(self._temp)
+ 
+-    cdef __relabel(self, l):
++    cdef _relabel(self, l):
+         """
+         Relabel each element `e` as `l[e]`, where `l` is a given injective map.
+ 
+@@ -231,7 +231,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             self._heuristic_partition_var._relabel(l)
+ 
+     # the engine
+-    cdef __pack(self, bitset_t I, F):
++    cdef _pack(self, bitset_t I, F):
+         """
+         Encode a subset F of the groundset into a bitpacked set of integers
+         """
+@@ -252,21 +252,21 @@ cdef class BasisExchangeMatroid(Matroid):
+         return frozenset(F)
+ 
+     # this method needs to be overridden by child class
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         """
+         Test if current_basis-x + y is a basis
+         """
+         raise NotImplementedError
+ 
+     # if this method is overridden by a child class, the child class needs to call this method
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         """
+         put current_basis <-- current_basis-x + y
+         """
+         bitset_discard(self._current_basis, x)
+         bitset_add(self._current_basis, y)
+ 
+-    cdef int __move(self, bitset_t X, bitset_t Y) except -1:
++    cdef int _move(self, bitset_t X, bitset_t Y) except -1:
+         """
+         Change current_basis to minimize intersection with ``X``, maximize intersection with ``Y``.
+         """
+@@ -275,8 +275,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         while x >= 0:
+             y = bitset_first(Y)
+             while y >= 0:
+-                if self.__is_exchange_pair(x, y):
+-                    self.__exchange(x, y)
++                if self._is_exchange_pair(x, y):
++                    self._exchange(x, y)
+                     bitset_discard(Y, y)
+                     bitset_discard(X, x)
+                     if bitset_isempty(Y):
+@@ -295,7 +295,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_complement(self._temp, self._current_basis)
+         y = bitset_first(self._temp)
+         while y >= 0:
+-            if self.__is_exchange_pair(x, y):
++            if self._is_exchange_pair(x, y):
+                 bitset_add(C, y)
+             y = bitset_next(self._temp, y + 1)
+         bitset_add(C, x)
+@@ -308,7 +308,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_clear(C)
+         x = bitset_first(self._current_basis)
+         while x >= 0:
+-            if self.__is_exchange_pair(x, y):
++            if self._is_exchange_pair(x, y):
+                 bitset_add(C, x)
+             x = bitset_next(self._current_basis, x + 1)
+         bitset_add(C, y)
+@@ -319,7 +319,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, F)
+         bitset_difference(self._outside, F, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_intersection(R, self._current_basis, F)
+ 
+     cdef __circuit(self, bitset_t R, bitset_t F):
+@@ -335,8 +335,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         while y >= 0:
+             x = bitset_first(self._inside)
+             while x >= 0:
+-                if self.__is_exchange_pair(x, y):
+-                    self.__exchange(x, y)
++                if self._is_exchange_pair(x, y):
++                    self._exchange(x, y)
+                     bitset_discard(self._outside, y)
+                     bitset_discard(self._inside, x)
+                     if bitset_isempty(self._outside):
+@@ -355,7 +355,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, F)
+         bitset_difference(self._outside, F, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_set_first_n(R, self._groundset_size)
+         cdef long x = bitset_first(self._inside)
+         while x >= 0:
+@@ -370,7 +370,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_difference(R, F, self._current_basis)
+ 
+     cdef __cocircuit(self, bitset_t R, bitset_t F):
+@@ -387,8 +387,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         while x >= 0:
+             y = bitset_first(self._outside)
+             while y >= 0:
+-                if self.__is_exchange_pair(x, y):
+-                    self.__exchange(x, y)
++                if self._is_exchange_pair(x, y):
++                    self._exchange(x, y)
+                     bitset_discard(self._outside, y)
+                     bitset_discard(self._inside, x)
+                     if bitset_isempty(self._inside):
+@@ -401,14 +401,14 @@ cdef class BasisExchangeMatroid(Matroid):
+                 return
+             x = bitset_next(self._inside, x + 1)
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``closure``.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_set_first_n(R, self._groundset_size)
+         cdef long y = bitset_first(self._outside)
+         while y >= 0:
+@@ -422,10 +422,10 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, X)
+         bitset_difference(self._outside, X, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_difference(self._inside, self._inside, Y)
+         bitset_difference(self._outside, Y, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_intersection(R, self._current_basis, Y)
+ 
+     cdef bint __is_independent(self, bitset_t F) except -1:
+@@ -434,7 +434,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, F)
+         bitset_difference(self._outside, F, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         return bitset_isempty(self._outside)
+ 
+     cdef __move_current_basis(self, bitset_t X, bitset_t Y):
+@@ -443,21 +443,21 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, X)
+         bitset_difference(self._outside, X, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_intersection(self._inside, self._current_basis, Y)
+         bitset_complement(self._outside, self._current_basis)
+         bitset_difference(self._outside, self._outside, Y)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+     # functions for derived classes and for parent class
+     cdef bint _set_current_basis(self, F):
+         """
+         Set _current_basis to subset of the groundset ``F``.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         bitset_difference(self._inside, self._current_basis, self._input)
+         bitset_difference(self._outside, self._input, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         return bitset_isempty(self._outside) and bitset_isempty(self._inside)
+ 
+     # groundset and full_rank
+@@ -630,8 +630,8 @@ cdef class BasisExchangeMatroid(Matroid):
+             ['b', 'c', 'e', 'f']
+ 
+         """
+-        self.__pack(self._input, X)
+-        self.__pack(self._input2, Y)
++        self._pack(self._input, X)
++        self._pack(self._input2, Y)
+         self.__move_current_basis(self._input, self._input2)
+ 
+     cpdef _max_independent(self, F):
+@@ -661,7 +661,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.max_independent>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_independent(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -692,7 +692,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.rank>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_independent(self._output, self._input)
+         return bitset_len(self._output)
+ 
+@@ -729,7 +729,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             the input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.circuit>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__circuit(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -754,7 +754,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             sage: sorted(M._fundamental_circuit('abcd', 'e'))
+             ['a', 'b', 'c', 'e']
+         """
+-        self.__pack(self._input, B)
++        self._pack(self._input, B)
+         bitset_clear(self._input2)
+         self.__move_current_basis(self._input, self._input2)
+         self.__fundamental_circuit(self._output, self._idx[e])
+@@ -787,7 +787,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             :meth:`<sage.matroids.matroid.Matroid.closure>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__closure(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -818,7 +818,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.max_coindependent>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_coindependent(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -848,7 +848,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.corank>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_coindependent(self._output, self._input)
+         return bitset_len(self._output)
+ 
+@@ -885,7 +885,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.cocircuit>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__cocircuit(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -910,7 +910,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             sage: sorted(M._fundamental_cocircuit('efgh', 'e'))
+             ['b', 'c', 'd', 'e']
+         """
+-        self.__pack(self._input, B)
++        self._pack(self._input, B)
+         bitset_clear(self._input2)
+         self.__move_current_basis(self._input, self._input2)
+         self.__fundamental_cocircuit(self._output, self._idx[e])
+@@ -943,8 +943,8 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.coclosure>`.
+ 
+         """
+-        self.__pack(self._input, F)
+-        self.__coclosure(self._output, self._input)
++        self._pack(self._input, F)
++        self._coclosure_internal(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+     cpdef _augment(self, X, Y):
+@@ -973,8 +973,8 @@ cdef class BasisExchangeMatroid(Matroid):
+             ['e', 'f', 'g']
+ 
+         """
+-        self.__pack(self._input, X)
+-        self.__pack(self._input2, Y)
++        self._pack(self._input, X)
++        self._pack(self._input2, Y)
+         self.__augment(self._output, self._input, self._input2)
+         return self.__unpack(self._output)
+ 
+@@ -1006,7 +1006,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             the input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.is_independent>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         return self.__is_independent(self._input)
+ 
+     # connectivity
+@@ -1142,8 +1142,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         cdef bitset_t SS, TT
+         bitset_init(SS, self._groundset_size)
+         bitset_init(TT, self._groundset_size)
+-        self.__pack(SS,S)
+-        self.__pack(TT,T)
++        self._pack(SS,S)
++        self._pack(TT,T)
+         #F = set(self.groundset()) - (S | T)
+         cdef bitset_t F, I
+         bitset_init(F, self._groundset_size)
+@@ -1421,7 +1421,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         Rcoflats = SetSystem(self._E)
+         i = 0
+         bitset_clear(todo[0])
+-        self.__coclosure(coflats[0], todo[0])
++        self._coclosure_internal(coflats[0], todo[0])
+         bitset_complement(todo[0], coflats[0])
+         self._coflats_rec(Rcoflats, r, coflats, todo, 0, 0)
+         for i in range(r + 1):
+@@ -1443,7 +1443,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         while e >= 0:
+             bitset_copy(self._input, coflats[i])
+             bitset_add(self._input, e)
+-            self.__coclosure(coflats[i + 1], self._input)
++            self._coclosure_internal(coflats[i + 1], self._input)
+             bitset_difference(todo[i], todo[i], coflats[i + 1])
+             bitset_difference(todo[i + 1], coflats[i + 1], coflats[i])
+             if bitset_first(todo[i + 1]) == e:
+@@ -2397,7 +2397,7 @@ cdef class BasisExchangeMatroid(Matroid):
+                 # Set current basis to Y
+                 bitset_difference(self._inside, self._current_basis, BB._subsets[pointerY])
+                 bitset_difference(self._outside, BB._subsets[pointerY], self._current_basis)
+-                self.__move(self._inside, self._outside)
++                self._move(self._inside, self._outside)
+                 if not bitset_eq(self._current_basis, BB._subsets[pointerY]):
+                     # We failed to set the current basis to Y through basis exchanges.
+                     # Therefore, the exchange axioms are violated!
+@@ -2409,7 +2409,7 @@ cdef class BasisExchangeMatroid(Matroid):
+                     foundpair = False
+                     y = bitset_first(self._input2)
+                     while y >= 0:  # for y in Y-X
+-                        if self.__is_exchange_pair(y, x):
++                        if self._is_exchange_pair(y, x):
+                             foundpair = True
+                             y = -1
+                         else:
+diff --git a/src/sage/matroids/basis_matroid.pyx b/src/sage/matroids/basis_matroid.pyx
+index 3ac43112627..c1b6e9b04c8 100644
+--- a/src/sage/matroids/basis_matroid.pyx
++++ b/src/sage/matroids/basis_matroid.pyx
+@@ -219,7 +219,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+                     raise ValueError("basis has wrong cardinality.")
+                 if not b.issubset(self._groundset):
+                     raise ValueError("basis is not a subset of the groundset")
+-                self.__pack(self._b, b)
++                self._pack(self._b, b)
+                 i = set_to_index(self._b)
+                 if not bitset_in(self._bb, i):
+                     self._bcount += 1
+@@ -234,7 +234,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+                         raise ValueError("nonbasis has wrong cardinality")
+                     if not b.issubset(self._groundset):
+                         raise ValueError("nonbasis is not a subset of the groundset")
+-                    self.__pack(self._b, b)
++                    self._pack(self._b, b)
+                     i = set_to_index(self._b)
+                     if bitset_in(self._bb, i):
+                         self._bcount -= 1
+@@ -263,7 +263,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+ 
+     # support for parent BasisExchangeMatroid
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:      # test if current_basis-x + y is a basis
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:      # test if current_basis-x + y is a basis
+         """
+         Test if `B-e + f` is a basis of the current matroid.
+ 
+@@ -326,7 +326,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+             sage: M._is_basis(set(['a', 'b', 'c', 'd']))
+             False
+         """
+-        self.__pack(self._b, X)
++        self._pack(self._b, X)
+         return bitset_in(self._bb, set_to_index(self._b))
+ 
+     # dual and minors
+@@ -557,7 +557,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+ 
+         """
+         M = BasisMatroid(M=self)
+-        M.__relabel(l)
++        M._relabel(l)
+         return M
+ 
+     # enumeration
+@@ -1177,7 +1177,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+ 
+         """
+         N = BasisMatroid(M=self)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo=None):
+@@ -1201,7 +1201,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+         if memo is None:
+             memo = {}
+         N = BasisMatroid(M=self)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __reduce__(self):
+@@ -1230,7 +1230,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+         """
+         import sage.matroids.unpickling
+         BB = bitset_pickle(self._bb)
+-        data = (self._E, self._matroid_rank, getattr(self, '__custom_name'), BB)
++        data = (self._E, self._matroid_rank, self.get_custom_name(), BB)
+         version = 0
+         return sage.matroids.unpickling.unpickle_basis_matroid, (version, data)
+ 
+diff --git a/src/sage/matroids/circuit_closures_matroid.pyx b/src/sage/matroids/circuit_closures_matroid.pyx
+index 402822b2dc6..4e79b0575e2 100644
+--- a/src/sage/matroids/circuit_closures_matroid.pyx
++++ b/src/sage/matroids/circuit_closures_matroid.pyx
+@@ -513,8 +513,7 @@ cdef class CircuitClosuresMatroid(Matroid):
+         N._groundset = self._groundset
+         N._circuit_closures = self._circuit_closures
+         N._matroid_rank = self._matroid_rank
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo=None):
+@@ -539,8 +538,7 @@ cdef class CircuitClosuresMatroid(Matroid):
+         from copy import deepcopy
+         # Since matroids are immutable, N cannot reference itself in correct code, so no need to worry about the recursion.
+         N = CircuitClosuresMatroid(groundset=deepcopy(self._groundset, memo), circuit_closures=deepcopy(self._circuit_closures, memo))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -570,7 +568,7 @@ cdef class CircuitClosuresMatroid(Matroid):
+              4: {{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}}}
+         """
+         import sage.matroids.unpickling
+-        data = (self._groundset, self._circuit_closures, getattr(self, '__custom_name'))
++        data = (self._groundset, self._circuit_closures, self.get_custom_name())
+         version = 0
+         return sage.matroids.unpickling.unpickle_circuit_closures_matroid, (version, data)
+ 
+diff --git a/src/sage/matroids/dual_matroid.py b/src/sage/matroids/dual_matroid.py
+index 804e43f035b..da6639827e4 100644
+--- a/src/sage/matroids/dual_matroid.py
++++ b/src/sage/matroids/dual_matroid.py
+@@ -519,9 +519,7 @@ def __copy__(self):
+ 
+         """
+         N = DualMatroid(self._matroid)
+-        if getattr(self, '__custom_name') is not None:
+-            # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -543,10 +541,7 @@ def __deepcopy__(self, memo={}):
+         """
+         from copy import deepcopy
+         N = DualMatroid(deepcopy(self._matroid, memo))
+-        if getattr(self, '__custom_name') is not None:
+-            # because of name wrangling, this is not caught by the
+-            # default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -575,6 +570,6 @@ def __reduce__(self):
+              4: {{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}}}'
+         """
+         import sage.matroids.unpickling
+-        data = (self._matroid, getattr(self, '__custom_name'))
++        data = (self._matroid, self.get_custom_name())
+         version = 0
+         return sage.matroids.unpickling.unpickle_dual_matroid, (version, data)
+diff --git a/src/sage/matroids/graphic_matroid.py b/src/sage/matroids/graphic_matroid.py
+index 5216ef11517..c727dc54e52 100644
+--- a/src/sage/matroids/graphic_matroid.py
++++ b/src/sage/matroids/graphic_matroid.py
+@@ -481,8 +481,7 @@ def __copy__(self):
+             False
+         """
+         N = GraphicMatroid(self._G)
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -502,8 +501,7 @@ def __deepcopy__(self, memo={}):
+         """
+         # The only real difference between this and __copy__() is the memo
+         N = GraphicMatroid(deepcopy(self._G, memo))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -519,7 +517,7 @@ def __reduce__(self):
+             Graphic matroid of rank 9 on 15 elements
+         """
+         from .unpickling import unpickle_graphic_matroid
+-        data = (self._G, getattr(self, '__custom_name'))
++        data = (self._G, self.get_custom_name())
+         version = 0
+         return unpickle_graphic_matroid, (version, data)
+ 
+diff --git a/src/sage/matroids/linear_matroid.pxd b/src/sage/matroids/linear_matroid.pxd
+index 014c8aef57d..9aebd446b68 100644
+--- a/src/sage/matroids/linear_matroid.pxd
++++ b/src/sage/matroids/linear_matroid.pxd
+@@ -15,7 +15,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+     cpdef characteristic(self)
+ 
+     cdef list _setup_internal_representation(self, matrix, reduced_matrix, ring, keep_initial_representation)
+-    cdef __exchange_value(self, long x, long y)
++    cdef _exchange_value_internal(self, long x, long y)
+ 
+     cpdef representation(self, B=*, reduced=*, labels=*, order=*, lift_map=*)
+     cpdef _current_rows_cols(self, B=*)
+diff --git a/src/sage/matroids/linear_matroid.pyx b/src/sage/matroids/linear_matroid.pyx
+index 61452e80c48..36f563aa433 100644
+--- a/src/sage/matroids/linear_matroid.pyx
++++ b/src/sage/matroids/linear_matroid.pyx
+@@ -391,13 +391,13 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         """
+         return characteristic(self._A)
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return self._A.is_nonzero(self._prow[x], self._prow[y])
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         """
+         Put element indexed by ``x`` into basis, taking out element ``y``.
+         Assumptions are that this is a valid basis exchange.
+@@ -420,9 +420,9 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         self._A.set_unsafe(px, py, pivi)
+         self._prow[y] = px
+         self._prow[x] = py
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -605,7 +605,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+                     self._representation = self._basic_representation(B)
+                 A = self._representation
+             else:
+-                B = self.__subset(B)
++                B = self._subset_internal(B)
+                 A = self._basic_representation(B)
+             A = A.matrix_from_rows_and_columns(range(A.nrows()), order_idx)
+             if lift_map is None:
+@@ -622,7 +622,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+             if B is None:
+                 B = frozenset(self.basis())
+             else:
+-                B = self.__subset(B)
++                B = self._subset_internal(B)
+             A = self._reduced_representation(B)
+             R, C = self._current_rows_cols()
+             Ri = []
+@@ -1493,7 +1493,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+             sage: M._exchange_value(1, 3)
+             4
+         """
+-        return self.__exchange_value(self._idx[e], self._idx[f])
++        return self._exchange_value_internal(self._idx[e], self._idx[f])
+ 
+     cpdef fundamental_cycle(self, B, e):
+         """
+@@ -2909,7 +2909,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = LinearMatroid(groundset=rows + cols, reduced_matrix=self._A)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -2930,7 +2930,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = LinearMatroid(groundset=deepcopy(rows + cols, memo), reduced_matrix=deepcopy(self._A, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -2979,7 +2979,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+             rows, cols = self._current_rows_cols()
+             gs = rows + cols
+             reduced = True
+-        data = (A, gs, reduced, getattr(self, '__custom_name'))
++        data = (A, gs, reduced, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_linear_matroid, (version, data)
+ 
+ # Binary matroid
+@@ -3152,20 +3152,20 @@ cdef class BinaryMatroid(LinearMatroid):
+         """
+         return 2
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<BinaryMatrix>self._A).is_nonzero(self._prow[x], y)
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         r"""
+         Replace ``self.basis() with ``self.basis() - x + y``. Internal method, does no checks.
+         """
+         cdef long p = self._prow[x]
+         self._A.pivot(p, y)   # Not a Sage matrix operation
+         self._prow[y] = p
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+     cdef  __fundamental_cocircuit(self, bitset_t C, long x):
+         r"""
+@@ -3173,18 +3173,18 @@ cdef class BinaryMatroid(LinearMatroid):
+         """
+         bitset_copy(C, (<BinaryMatrix>self._A)._M[self._prow[x]])
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``coclosure``.
+ 
+-        This function overrides the internal function BasisExchangeMatroid.__coclosure() of the parent class.
++        This function overrides the internal function BasisExchangeMatroid._coclosure_internal() of the parent class.
+         The implementation should be more efficient for BinaryMatroid, due to the fact that in this class,
+         __fundamental_cocircuit is much faster than __fundamental_circuit.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+         bitset_copy(R, F)
+         bitset_difference(self._inside, self._current_basis, F)
+@@ -3196,7 +3196,7 @@ cdef class BinaryMatroid(LinearMatroid):
+                 bitset_add(R, y)
+             y = bitset_next(self._inside, y + 1)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -3964,7 +3964,7 @@ cdef class BinaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = BinaryMatroid(groundset=self._E, matrix=self._A, basis=basis)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -3989,7 +3989,7 @@ cdef class BinaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = BinaryMatroid(groundset=deepcopy(self._E, memo), matrix=deepcopy(self._A, memo), basis=deepcopy(basis, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -4047,7 +4047,7 @@ cdef class BinaryMatroid(LinearMatroid):
+             A = self._A
+             # current basis ordered so matrix cols form identity matrix:
+             basis = self._current_rows_cols()[0]
+-        data = (A, gs, basis, getattr(self, '__custom_name'))
++        data = (A, gs, basis, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_binary_matroid, (version, data)
+ 
+ cdef class TernaryMatroid(LinearMatroid):
+@@ -4220,20 +4220,20 @@ cdef class TernaryMatroid(LinearMatroid):
+         """
+         return 3
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<TernaryMatrix>self._A).is_nonzero(self._prow[x], y)
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         r"""
+         Replace ``self.basis() with ``self.basis() - x + y``. Internal method, does no checks.
+         """
+         cdef long p = self._prow[x]
+         self._A.pivot(p, y)   # Not a Sage matrix operation
+         self._prow[y] = p
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+     cdef  __fundamental_cocircuit(self, bitset_t C, long x):
+         r"""
+@@ -4241,18 +4241,18 @@ cdef class TernaryMatroid(LinearMatroid):
+         """
+         bitset_copy(C, (<TernaryMatrix>self._A)._M0[self._prow[x]])
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``coclosure``.
+ 
+-        This function overrides the internal function BasisExchangeMatroid.__coclosure() of the parent class.
++        This function overrides the internal function BasisExchangeMatroid._coclosure_internal() of the parent class.
+         The implementation should be more efficient for TernaryMatroid, due to the fact that in this class,
+         __fundamental_cocircuit is much faster than __fundamental_circuit.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+         bitset_copy(R, F)
+         bitset_difference(self._inside, self._current_basis, F)
+@@ -4264,7 +4264,7 @@ cdef class TernaryMatroid(LinearMatroid):
+                 bitset_add(R, y)
+             y = bitset_next(self._inside, y + 1)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -4858,7 +4858,7 @@ cdef class TernaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = TernaryMatroid(groundset=self._E, matrix=self._A, basis=basis)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -4883,7 +4883,7 @@ cdef class TernaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = TernaryMatroid(groundset=deepcopy(self._E, memo), matrix=deepcopy(self._A, memo), basis=deepcopy(basis, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -4945,7 +4945,7 @@ cdef class TernaryMatroid(LinearMatroid):
+             A = self._A
+             # current basis ordered so matrix cols form identity matrix:
+             basis = self._current_rows_cols()[0]
+-        data = (A, gs, basis, getattr(self, '__custom_name'))
++        data = (A, gs, basis, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_ternary_matroid, (version, data)
+ 
+ # Quaternary Matroids
+@@ -5122,20 +5122,20 @@ cdef class QuaternaryMatroid(LinearMatroid):
+         """
+         return 2
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<QuaternaryMatrix>self._A).is_nonzero(self._prow[x], y)
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         r"""
+         Replace ``self.basis() with ``self.basis() - x + y``. Internal method, does no checks.
+         """
+         cdef long p = self._prow[x]
+         self._A.pivot(p, y)   # Not a Sage matrix operation
+         self._prow[y] = p
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+     cdef  __fundamental_cocircuit(self, bitset_t C, long x):
+         r"""
+@@ -5143,18 +5143,18 @@ cdef class QuaternaryMatroid(LinearMatroid):
+         """
+         bitset_union(C, (<QuaternaryMatrix>self._A)._M0[self._prow[x]], (<QuaternaryMatrix>self._A)._M1[self._prow[x]])
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``coclosure``.
+ 
+-        This function overrides the internal function BasisExchangeMatroid.__coclosure() of the parent class.
++        This function overrides the internal function BasisExchangeMatroid._coclosure_internal() of the parent class.
+         The implementation should be more efficient for QuaternaryMatroid, due to the fact that in this class,
+         __fundamental_cocircuit is much faster than __fundamental_circuit.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+         bitset_copy(R, F)
+         bitset_difference(self._inside, self._current_basis, F)
+@@ -5166,7 +5166,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+                 bitset_add(R, y)
+             y = bitset_next(self._inside, y + 1)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -5589,7 +5589,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = QuaternaryMatroid(groundset=self._E, matrix=self._A, basis=basis)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -5614,7 +5614,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = QuaternaryMatroid(groundset=deepcopy(self._E, memo), matrix=deepcopy(self._A, memo), basis=deepcopy(basis, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -5672,7 +5672,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+             A = self._A
+             # current basis ordered so matrix cols form identity matrix:
+             basis = self._current_rows_cols()[0]
+-        data = (A, gs, basis, getattr(self, '__custom_name'))
++        data = (A, gs, basis, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_quaternary_matroid, (version, data)
+ 
+ # Regular Matroids
+@@ -5838,13 +5838,13 @@ cdef class RegularMatroid(LinearMatroid):
+         """
+         return 0
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<PlusMinusOneMatrix>self._A).is_nonzero(self._prow[x], self._prow[y])
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         """
+         Put element indexed by ``x`` into basis, taking out element ``y``. Assumptions are that this is a valid basis exchange.
+ 
+@@ -5867,9 +5867,9 @@ cdef class RegularMatroid(LinearMatroid):
+         (<PlusMinusOneMatrix>self._A).set(px, py, pivi)   # Not a Sage matrix operation
+         self._prow[y] = px
+         self._prow[x] = py
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+ 
+@@ -6524,7 +6524,7 @@ cdef class RegularMatroid(LinearMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = RegularMatroid(groundset=rows + cols, reduced_matrix=self._A)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -6544,7 +6544,7 @@ cdef class RegularMatroid(LinearMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = RegularMatroid(groundset=deepcopy(rows + cols, memo), reduced_matrix=deepcopy(self._A, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -6593,5 +6593,5 @@ cdef class RegularMatroid(LinearMatroid):
+             rows, cols = self._current_rows_cols()
+             gs = rows + cols
+             reduced = True
+-        data = (A, gs, reduced, getattr(self, '__custom_name'))
++        data = (A, gs, reduced, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_regular_matroid, (version, data)
+diff --git a/src/sage/matroids/matroid.pxd b/src/sage/matroids/matroid.pxd
+index fe6c07e3b71..e9ddfec96ae 100644
+--- a/src/sage/matroids/matroid.pxd
++++ b/src/sage/matroids/matroid.pxd
+@@ -1,8 +1,7 @@
+ from sage.structure.sage_object cimport SageObject
+ 
+ cdef class Matroid(SageObject):
+-    cdef public __custom_name
+-    cdef public _custom_name
++    cdef public _SageObject__custom_name
+     cdef public _cached_info
+     cdef int _stored_full_rank
+     cdef int _stored_size
+@@ -37,7 +36,7 @@ cdef class Matroid(SageObject):
+     cpdef _line_length(self, F)
+     cpdef _extension(self, element, hyperplanes)
+ 
+-    cdef inline __subset(self, X):
++    cdef inline _subset_internal(self, X):
+         """
+         Convert ``X`` to a ``frozenset`` and check that it is a subset
+         of the groundset.
+diff --git a/src/sage/matroids/matroid.pyx b/src/sage/matroids/matroid.pyx
+index dcee87ea49c..8ac5ec3f678 100644
+--- a/src/sage/matroids/matroid.pyx
++++ b/src/sage/matroids/matroid.pyx
+@@ -1307,7 +1307,7 @@ cdef class Matroid(SageObject):
+             TypeError: 'sage.rings.integer.Integer' object is not iterable
+         """
+         # Call corresponding Cython method
+-        return self.__subset(X)
++        return self._subset_internal(X)
+ 
+     def _subset_all(self, X):
+         """
+@@ -1374,7 +1374,7 @@ cdef class Matroid(SageObject):
+         """
+         if X is None:
+             return self.full_rank()
+-        return self._rank(self.__subset(X))
++        return self._rank(self._subset_internal(X))
+ 
+     cpdef full_rank(self):
+         r"""
+@@ -1453,7 +1453,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._max_independent(self.__subset(X))
++        return self._max_independent(self._subset_internal(X))
+ 
+     cpdef circuit(self, X=None):
+         """
+@@ -1558,7 +1558,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._closure(self.__subset(X))
++        return self._closure(self._subset_internal(X))
+ 
+     cpdef k_closure(self, X, k):
+         r"""
+@@ -1597,7 +1597,7 @@ cdef class Matroid(SageObject):
+             sage: sorted(M.k_closure({0,1}, 4))
+             [0, 1, 4]
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         cdef int cur
+         cdef frozenset S, cl
+         cur = 0
+@@ -1644,7 +1644,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         Y = self.__subset_all(Y)
+         return self._augment(X, Y.difference(X))
+ 
+@@ -1781,7 +1781,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._max_coindependent(self.__subset(X))
++        return self._max_coindependent(self._subset_internal(X))
+ 
+     cpdef coclosure(self, X):
+         """
+@@ -1813,7 +1813,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._coclosure(self.__subset(X))
++        return self._coclosure(self._subset_internal(X))
+ 
+     cpdef cocircuit(self, X=None):
+         """
+@@ -1947,7 +1947,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_independent(self.__subset(X))
++        return self._is_independent(self._subset_internal(X))
+ 
+     cpdef is_dependent(self, X):
+         r"""
+@@ -1973,7 +1973,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return not self._is_independent(self.__subset(X))
++        return not self._is_independent(self._subset_internal(X))
+ 
+     cpdef is_basis(self, X):
+         r"""
+@@ -1999,7 +1999,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         if len(X) != self.full_rank():
+             return False
+         return self._is_basis(X)
+@@ -2035,7 +2035,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_closed(self.__subset(X))
++        return self._is_closed(self._subset_internal(X))
+ 
+     cpdef is_subset_k_closed(self, X, int k):
+         r"""
+@@ -2118,7 +2118,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_circuit(self.__subset(X))
++        return self._is_circuit(self._subset_internal(X))
+ 
+     cpdef coloops(self):
+         r"""
+@@ -2178,7 +2178,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_coindependent(self.__subset(X))
++        return self._is_coindependent(self._subset_internal(X))
+ 
+     cpdef is_codependent(self, X):
+         r"""
+@@ -2211,7 +2211,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return not self._is_coindependent(self.__subset(X))
++        return not self._is_coindependent(self._subset_internal(X))
+ 
+     cpdef is_cobasis(self, X):
+         r"""
+@@ -2245,7 +2245,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         if len(X) != self.full_corank():
+             return False
+         return self._is_cobasis(X)
+@@ -2282,7 +2282,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_cocircuit(self.__subset(X))
++        return self._is_cocircuit(self._subset_internal(X))
+ 
+     cpdef is_coclosed(self, X):
+         r"""
+@@ -2315,7 +2315,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_coclosed(self.__subset(X))
++        return self._is_coclosed(self._subset_internal(X))
+ 
+     # verification
+ 
+@@ -4868,10 +4868,10 @@ cdef class Matroid(SageObject):
+             sage: M.connectivity('ab', 'cd')
+             2
+         """
+-        S = self.__subset(S)
++        S = self._subset_internal(S)
+         if T is None:
+             return self._rank(S) + self._rank(self.groundset()-S) - self.full_rank()
+-        T = self.__subset(T)
++        T = self._subset_internal(T)
+         if S.intersection(T):
+             raise ValueError("S and T are not disjoint")
+         return len(self._link(S, T)[0]) - self.full_rank() + self._rank(S) + self._rank(T)
+@@ -4956,8 +4956,8 @@ cdef class Matroid(SageObject):
+             sage: N.connectivity(S)
+             2
+         """
+-        S = self.__subset(S)
+-        T = self.__subset(T)
++        S = self._subset_internal(S)
++        T = self._subset_internal(T)
+         if not S.isdisjoint(T):
+             raise ValueError("S and T are not disjoint")
+         return self._link(S, T)
+diff --git a/src/sage/matroids/minor_matroid.py b/src/sage/matroids/minor_matroid.py
+index c0e756917f5..98856348ac1 100644
+--- a/src/sage/matroids/minor_matroid.py
++++ b/src/sage/matroids/minor_matroid.py
+@@ -486,8 +486,7 @@ def __copy__(self):
+             True
+         """
+         N = MinorMatroid(self._matroid, self._contractions, self._deletions)
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -512,8 +511,7 @@ def __deepcopy__(self, memo={}):
+         from copy import deepcopy
+         # Since matroids are immutable, N cannot reference itself in correct code, so no need to worry about the recursion.
+         N = MinorMatroid(deepcopy(self._matroid, memo), deepcopy(self._contractions, memo), deepcopy(self._deletions, memo))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -534,6 +532,6 @@ def __reduce__(self):
+              4: {{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}}}
+         """
+         import sage.matroids.unpickling
+-        data = (self._matroid, self._contractions, self._deletions, getattr(self, '__custom_name'))
++        data = (self._matroid, self._contractions, self._deletions, self.get_custom_name())
+         version = 0
+         return sage.matroids.unpickling.unpickle_minor_matroid, (version, data)
+diff --git a/src/sage/matroids/rank_matroid.py b/src/sage/matroids/rank_matroid.py
+index 4633ff0a792..6c4e9470ada 100644
+--- a/src/sage/matroids/rank_matroid.py
++++ b/src/sage/matroids/rank_matroid.py
+@@ -267,9 +267,7 @@ def __copy__(self):
+         N = RankMatroid(groundset=[], rank_function=None)
+         N._groundset = self._groundset
+         N._rank_function = self._rank_function
+-        if getattr(self, '__custom_name') is not None:
+-            # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -293,8 +291,7 @@ def __deepcopy__(self, memo={}):
+         from copy import deepcopy
+         # Since matroids are immutable, N cannot reference itself in correct code, so no need to worry about the recursion.
+         N = RankMatroid(groundset=deepcopy(self._groundset), rank_function=deepcopy(self._rank_function))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+diff --git a/src/sage/misc/cachefunc.pxd b/src/sage/misc/cachefunc.pxd
+index d3cc677dece..8e5d9dfa42a 100644
+--- a/src/sage/misc/cachefunc.pxd
++++ b/src/sage/misc/cachefunc.pxd
+@@ -5,7 +5,7 @@ cpdef cache_key(o)
+ 
+ cdef class CachedFunction():
+     cdef public str __name__
+-    cdef public str __module__
++    cdef public str __cached_module__
+     cdef ArgumentFixer _argument_fixer
+     cdef public f
+     cdef public cache  # not always of type <dict>
+@@ -20,7 +20,7 @@ cdef class CachedFunction():
+ cdef class CachedMethod():
+     cdef str _cache_name
+     cdef public str __name__
+-    cdef public str __module__
++    cdef public str __cached_module__
+     cdef CachedFunction _cachedfunc
+     cdef Py_ssize_t nargs
+     cpdef _get_instance_cache(self, inst)
+diff --git a/src/sage/misc/cachefunc.pyx b/src/sage/misc/cachefunc.pyx
+index a307c33e32b..8aa30a85272 100644
+--- a/src/sage/misc/cachefunc.pyx
++++ b/src/sage/misc/cachefunc.pyx
+@@ -60,7 +60,7 @@ be used::
+ 
+ We can proceed similarly for cached methods of Cython classes,
+ provided that they allow attribute assignment or have a public
+-attribute ``__cached_methods`` of type ``<dict>``. Since
++attribute ``_cached_methods`` of type ``<dict>``. Since
+ :trac:`11115`, this is the case for all classes inheriting from
+ :class:`~sage.structure.parent.Parent`. See below for a more explicit
+ example. By :trac:`12951`, cached methods of extension classes can
+@@ -301,14 +301,14 @@ ought to be chosen. A typical example is
+ 
+ By :trac:`12951`, the cached_method decorator is also supported on non-c(p)def
+ methods of extension classes, as long as they either support attribute assignment
+-or have a public attribute of type ``<dict>`` called ``__cached_methods``. The
++or have a public attribute of type ``<dict>`` called ``_cached_methods``. The
+ latter is easy::
+ 
+     sage: # needs sage.misc.cython
+     sage: cython_code = [
+     ....: "from sage.misc.cachefunc import cached_method",
+     ....: "cdef class MyClass:",
+-    ....: "    cdef public dict __cached_methods",
++    ....: "    cdef public dict _cached_methods",
+     ....: "    @cached_method",
+     ....: "    def f(self, a,b):",
+     ....: "        return a*b"]
+@@ -774,13 +774,17 @@ cdef class CachedFunction():
+         else:
+             self.__name__ = f.__name__
+         try:
+-            self.__module__ = f.__module__
++            self.__cached_module__ = f.__module__
+         except AttributeError:
+-            self.__module__ = f.__objclass__.__module__
++            self.__cached_module__ = f.__objclass__.__module__
+         if argument_fixer is not None: # it is None unless the argument fixer
+                                        # was known previously. See #15038.
+             self._argument_fixer = argument_fixer
+ 
++    @property
++    def __module__(self):
++        return self.__cached_module__
++
+     cdef get_key_args_kwds(self, tuple args, dict kwds):
+         """
+         Return the key in the cache to be used when ``args`` and
+@@ -841,7 +845,7 @@ cdef class CachedFunction():
+             sage: loads(dumps(hilbert_class_polynomial)) is hilbert_class_polynomial  #indirect doctest                 # needs sage.schemes
+             True
+         """
+-        return _cached_function_unpickle, (self.__module__, self.__name__, self.cache)
++        return _cached_function_unpickle, (self.__cached_module__, self.__name__, self.cache)
+ 
+     #########
+     ## Introspection
+@@ -2019,7 +2023,7 @@ cdef class CachedMethodCaller(CachedFunction):
+         This getter attempts to assign a bound method as an
+         attribute to the given instance. If this is not
+         possible (for example, for some extension classes),
+-        it is attempted to find an attribute ``__cached_methods``,
++        it is attempted to find an attribute ``_cached_methods``,
+         and store/retrieve the bound method there. In that
+         way, cached methods can be implemented for extension
+         classes deriving from :class:`~sage.structure.parent.Parent`
+@@ -2085,7 +2089,7 @@ cdef class CachedMethodCaller(CachedFunction):
+         """
+         # This is for Parents or Elements that do not allow attribute assignment
+         try:
+-            return (<dict>inst.__cached_methods)[self._cachedmethod._cachedfunc.__name__]
++            return (<dict>inst._cached_methods)[self._cachedmethod._cachedfunc.__name__]
+         except (AttributeError, TypeError, KeyError):
+             pass
+ 
+@@ -2100,10 +2104,10 @@ cdef class CachedMethodCaller(CachedFunction):
+         except AttributeError:
+             pass
+         try:
+-            if inst.__cached_methods is None:
+-                inst.__cached_methods = {self._cachedmethod._cachedfunc.__name__ : Caller}
++            if inst._cached_methods is None:
++                inst._cached_methods = {self._cachedmethod._cachedfunc.__name__ : Caller}
+             else:
+-                (<dict>inst.__cached_methods)[self._cachedmethod._cachedfunc.__name__] = Caller
++                (<dict>inst._cached_methods)[self._cachedmethod._cachedfunc.__name__] = Caller
+         except AttributeError:
+             pass
+         return Caller
+@@ -2421,7 +2425,7 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
+         This getter attempts to assign a bound method as an
+         attribute to the given instance. If this is not
+         possible (for example, for some extension classes),
+-        it is attempted to find an attribute ``__cached_methods``,
++        it is attempted to find an attribute ``_cached_methods``,
+         and store/retrieve the bound method there. In that
+         way, cached methods can be implemented for extension
+         classes deriving from :class:`~sage.structure.parent.Parent`
+@@ -2472,7 +2476,7 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
+         """
+         # This is for Parents or Elements that do not allow attribute assignment
+         try:
+-            return (<dict>inst.__cached_methods)[self.__name__]
++            return (<dict>inst._cached_methods)[self.__name__]
+         except (AttributeError, TypeError, KeyError):
+             pass
+         Caller = CachedMethodCallerNoArgs(inst, self.f, name=self.__name__, do_pickle=self.do_pickle)
+@@ -2482,10 +2486,10 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
+         except AttributeError:
+             pass
+         try:
+-            if inst.__cached_methods is None:
+-                inst.__cached_methods = {self.__name__ : Caller}
++            if inst._cached_methods is None:
++                inst._cached_methods = {self.__name__ : Caller}
+             else:
+-                (<dict>inst.__cached_methods)[self.__name__] = Caller
++                (<dict>inst._cached_methods)[self.__name__] = Caller
+         except AttributeError:
+             pass
+         return Caller
+@@ -2698,7 +2702,11 @@ cdef class CachedMethod():
+         self._cache_name = '_cache__' + (name or f.__name__)
+         self._cachedfunc = CachedFunction(f, classmethod=True, name=name, key=key, do_pickle=do_pickle)
+         self.__name__ = self._cachedfunc.__name__
+-        self.__module__ = self._cachedfunc.__module__
++        self.__cached_module__ = self._cachedfunc.__module__
++
++    @property
++    def __module__(self):
++        return self.__cached_module__
+ 
+     def __call__(self, inst, *args, **kwds):
+         """
+@@ -2828,7 +2836,7 @@ cdef class CachedMethod():
+         except AttributeError:
+             name = self.__name__
+         try:
+-            return (<dict>inst.__cached_methods)[name]
++            return (<dict>inst._cached_methods)[name]
+         except (AttributeError, TypeError, KeyError):
+             pass
+         # Apparently we need to construct the caller.
+@@ -2840,8 +2848,6 @@ cdef class CachedMethod():
+                 try:
+                     if METH_NOARGS&PyCFunction_GetFlags(f.__get__(inst,cls)):
+                         self.nargs = 1
+-                    else:
+-                        self.nargs = 2
+                 except Exception:
+                     pass
+             if self.nargs == 0:
+@@ -2864,10 +2870,10 @@ cdef class CachedMethod():
+         except AttributeError:
+             pass
+         try:
+-            if inst.__cached_methods is None:
+-                inst.__cached_methods = {name : Caller}
++            if inst._cached_methods is None:
++                inst._cached_methods = {name : Caller}
+             else:
+-                (<dict>inst.__cached_methods)[name] = Caller
++                (<dict>inst._cached_methods)[name] = Caller
+         except AttributeError:
+             pass
+         return Caller
+@@ -2965,12 +2971,12 @@ cdef class CachedSpecialMethod(CachedMethod):
+                 D = inst.__dict__
+             except (TypeError, AttributeError):
+                 try:
+-                    D = inst.__cached_methods
++                    D = inst._cached_methods
+                 except (TypeError, AttributeError):
+-                    raise TypeError("For a cached special method, either attribute assignment or a public '__cached_methods' attribute of type <dict> is needed")
++                    raise TypeError("For a cached special method, either attribute assignment or a public '_cached_methods' attribute of type <dict> is needed")
+             if D is None:
+-                # This can only happen in the case of __cached_methods
+-                D = inst.__cached_methods = {}
++                # This can only happen in the case of _cached_methods
++                D = inst._cached_methods = {}
+             else:
+                 try:
+                     return D[name]
+@@ -3298,13 +3304,13 @@ cdef class CachedInParentMethod(CachedMethod):
+             return P.__dict__.setdefault(self._cache_name, default)
+         except AttributeError:
+             pass
+-        if not hasattr(P,'__cached_methods'):
++        if not hasattr(P,'_cached_methods'):
+             raise TypeError("The parent of this element does not allow attribute assignment\n" +
+                             "    and does not descend from the Parent base class.\n" +
+                             "    Cannot use CachedInParentMethod.")
+-        if P.__cached_methods is None:
+-            P.__cached_methods = {}
+-        return (<dict>P.__cached_methods).setdefault(self._cache_name, default)
++        if P._cached_methods is None:
++            P._cached_methods = {}
++        return (<dict>P._cached_methods).setdefault(self._cache_name, default)
+ 
+     def __get__(self, inst, cls):
+         """
+diff --git a/src/sage/misc/cython.py b/src/sage/misc/cython.py
+index f4083f3909b..5f83f585c3a 100644
+--- a/src/sage/misc/cython.py
++++ b/src/sage/misc/cython.py
+@@ -646,9 +646,9 @@ def compile_and_load(code, **kwds):
+         ....:     cdef Polynomial_rational_flint res = f._new()
+         ....:     cdef unsigned long k
+         ....:     cdef Rational z = Rational(0)
+-        ....:     for k in range(fmpq_poly_length(f.__poly)):
+-        ....:         fmpq_poly_get_coeff_mpq(z.value, f.__poly, k)
+-        ....:         fmpq_poly_set_coeff_mpq(res.__poly, n*k, z.value)
++        ....:     for k in range(fmpq_poly_length(f._poly)):
++        ....:         fmpq_poly_get_coeff_mpq(z.value, f._poly, k)
++        ....:         fmpq_poly_set_coeff_mpq(res._poly, n*k, z.value)
+         ....:     return res
+         ....: '''
+         sage: module = compile_and_load(code)  # long time
+diff --git a/src/sage/misc/fpickle.pyx b/src/sage/misc/fpickle.pyx
+index 9f80a8f31aa..37c26e431ba 100644
+--- a/src/sage/misc/fpickle.pyx
++++ b/src/sage/misc/fpickle.pyx
+@@ -124,10 +124,12 @@ def call_pickled_function(fpargs):
+ def pickleMethod(method):
+     'support function for copyreg to pickle method refs'
+ 
+-    # Note: On Python 3 there is no .im_class but we can get the instance's
+-    # class through .__self__.__class__
+-    cls = getattr(method, 'im_class', method.__self__.__class__)
+-    return (unpickleMethod, (method.__func__.__name__, method.__self__, cls))
++    if isinstance(method.__self__, type):
++        # This is a class method, so get it from the type directly
++        return (getattr, (method.__self__, method.__func__.__name__))
++    else:
++        cls = method.__self__.__class__
++        return (unpickleMethod, (method.__func__.__name__, method.__self__, cls))
+ 
+ 
+ def unpickleMethod(im_name,
+@@ -139,10 +141,7 @@ def unpickleMethod(im_name,
+         if __self__ is None:
+             return unbound
+ 
+-        # Note: On Python 2 "unbound methods" are just functions, so they don't
+-        # have a __func__
+-        bound = types.MethodType(getattr(unbound, '__func__', unbound),
+-                                 __self__)
++        bound = types.MethodType(unbound, __self__)
+         return bound
+     except AttributeError:
+         assert __self__ is not None, "No recourse: no instance to guess from."
+@@ -150,11 +149,8 @@ def unpickleMethod(im_name,
+         # changed around since we pickled this method, we may still be
+         # able to get it by looking on the instance's current class.
+         unbound = getattr(__self__.__class__, im_name)
+-        if __self__ is None:
+-            return unbound
+ 
+-        bound = types.MethodType(getattr(unbound, '__func__', unbound),
+-                                 __self__)
++        bound = types.MethodType(unbound, __self__)
+         return bound
+ 
+ 
+diff --git a/src/sage/misc/inherit_comparison.pyx b/src/sage/misc/inherit_comparison.pyx
+index f046f5fb8ce..aa97f664496 100644
+--- a/src/sage/misc/inherit_comparison.pyx
++++ b/src/sage/misc/inherit_comparison.pyx
+@@ -54,6 +54,8 @@ cdef class InheritComparisonMetaclass(type):
+         sage: # needs sage.misc.cython
+         sage: cython(
+         ....: '''
++        ....: cimport cython
++        ....:
+         ....: from sage.misc.inherit_comparison cimport InheritComparisonMetaclass
+         ....:
+         ....: cdef class Base():
+@@ -66,6 +68,7 @@ cdef class InheritComparisonMetaclass(type):
+         ....:         return 1
+         ....:
+         ....: cdef class DerivedWithRichcmp(Base):
++        ....:     @cython.always_allow_keywords(False)
+         ....:     def __getmetaclass__(_):
+         ....:         from sage.misc.inherit_comparison import InheritComparisonMetaclass
+         ....:         return InheritComparisonMetaclass
+diff --git a/src/sage/misc/lazy_attribute.pyx b/src/sage/misc/lazy_attribute.pyx
+index 82a0f90b775..bdbec3b3ba1 100644
+--- a/src/sage/misc/lazy_attribute.pyx
++++ b/src/sage/misc/lazy_attribute.pyx
+@@ -111,12 +111,12 @@ cdef class _lazy_attribute():
+         if a is None: # when doing cls.x for cls a class and x a lazy attribute
+             return self
+         try:
+-            # __cached_methods is supposed to be a public Cython attribute.
++            # _cached_methods is supposed to be a public Cython attribute.
+             # Apparently, these are *not* subject to name mangling.
+-            CM = getattr(a, '__cached_methods')
++            CM = getattr(a, '_cached_methods')
+             if CM is None:
+                 CM = {}
+-                setattr(a, '__cached_methods', CM)
++                setattr(a, '_cached_methods', CM)
+         except AttributeError as msg:
+             CM = None
+         if CM is not None:
+diff --git a/src/sage/misc/lazy_list.pyx b/src/sage/misc/lazy_list.pyx
+index c1fa0250a95..ba62c446b69 100644
+--- a/src/sage/misc/lazy_list.pyx
++++ b/src/sage/misc/lazy_list.pyx
+@@ -1059,7 +1059,11 @@ cdef class lazy_list_from_function(lazy_list_generic):
+             step         1
+         """
+         while len(self.cache) <= i:
+-            self.cache.append(self.callable(len(self.cache)))
++            try:
++                value = self.callable(len(self.cache))
++            except StopIteration:
++                return 1
++            self.cache.append(value)
+ 
+     def __reduce__(self):
+         r"""
+diff --git a/src/sage/misc/sageinspect.py b/src/sage/misc/sageinspect.py
+index 3dd0cc0a45b..ce5e9987027 100644
+--- a/src/sage/misc/sageinspect.py
++++ b/src/sage/misc/sageinspect.py
+@@ -224,7 +224,11 @@ def isclassinstance(obj):
+     return (not inspect.isclass(obj) and
+             hasattr(obj, '__class__') and
+             hasattr(obj.__class__, '__module__') and
+-            obj.__class__.__module__ not in builtin_mods)
++            obj.__class__.__module__ not in builtin_mods and
++            # Starting with Cython 3, Cython's builtin types have __module__ set
++            # to the shared module names like _cython_3_0_0.
++            not (isinstance(obj.__class__.__module__, str) and
++                 obj.__class__.__module__.startswith('_cython_')))
+ 
+ 
+ # Parse strings of form "File: sage/rings/rational.pyx (starting at line 1080)"
+diff --git a/src/sage/misc/session.pyx b/src/sage/misc/session.pyx
+index de649f80425..31454dac993 100644
+--- a/src/sage/misc/session.pyx
++++ b/src/sage/misc/session.pyx
+@@ -80,6 +80,8 @@ from sage.misc.persist import load, save, loads, dumps
+ 
+ state_at_init = None
+ 
++CythonFunctionType = type(lambda: None)
++
+ def init(state=None):
+     """
+     Initialize some dictionaries needed by the :func:`show_identifiers`,
+@@ -311,7 +313,7 @@ def save_session(name='sage_session', verbose=False):
+     for k in show_identifiers(hidden = True):
+         try:
+             x = state[k]
+-            if isinstance(x, (types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType, type)):
++            if isinstance(x, (types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType, CythonFunctionType, type)):
+                 raise TypeError('{} is a function, method, class or type'.format(k))
+ 
+             # We attempt to pickle *and* unpickle every variable to
+diff --git a/src/sage/modular/modsym/p1list.pxd b/src/sage/modular/modsym/p1list.pxd
+index cc24a33139b..b66f28b8ad6 100644
+--- a/src/sage/modular/modsym/p1list.pxd
++++ b/src/sage/modular/modsym/p1list.pxd
+@@ -21,7 +21,7 @@ cdef class P1List:
+     # Here we use a pointer to a function, so the if logic
+     # for normalizing an element does not need to be used
+     # every time the user calls the normalize function.
+-    cdef int (*__normalize)(int N, int u, int v,
++    cdef int (*_normalize)(int N, int u, int v,
+                             int* uu, int* vv, int* ss,
+                             int compute_s) except -1
+     cpdef index(self, int u, int v)
+diff --git a/src/sage/modular/modsym/p1list.pyx b/src/sage/modular/modsym/p1list.pyx
+index 111d408cee4..30a8f7471dd 100644
+--- a/src/sage/modular/modsym/p1list.pyx
++++ b/src/sage/modular/modsym/p1list.pyx
+@@ -723,10 +723,10 @@ cdef class P1List():
+         self.__N = N
+         if N <= 46340:
+             self.__list = p1list_int(N)
+-            self.__normalize = c_p1_normalize_int
++            self._normalize = c_p1_normalize_int
+         elif N <= 2147483647:
+             self.__list = p1list_llong(N)
+-            self.__normalize = c_p1_normalize_llong
++            self._normalize = c_p1_normalize_llong
+         else:
+             raise OverflowError("p1list not defined for such large N.")
+         self.__list.sort()
+@@ -921,7 +921,7 @@ cdef class P1List():
+         """
+         cdef int u, v, uu, vv, ss
+         u,v = self.__list[i]
+-        self.__normalize(self.__N, -u, v, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, -u, v, &uu, &vv, &ss, 0)
+         _, j = search(self.__list, (uu,vv))
+         return j
+ 
+@@ -954,7 +954,7 @@ cdef class P1List():
+         """
+         cdef int u, v, uu, vv, ss
+         u,v = self.__list[i]
+-        self.__normalize(self.__N, -v, u, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, -v, u, &uu, &vv, &ss, 0)
+         _, j = search(self.__list, (uu,vv))
+         return j
+ 
+@@ -987,7 +987,7 @@ cdef class P1List():
+         """
+         cdef int u, v, uu, vv, ss
+         u,v = self.__list[i]
+-        self.__normalize(self.__N, v, -u-v, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, v, -u-v, &uu, &vv, &ss, 0)
+         _, j = search(self.__list, (uu,vv))
+         return j
+ 
+@@ -1153,7 +1153,7 @@ cdef class P1List():
+             True
+         """
+         cdef int uu, vv, ss
+-        self.__normalize(self.__N, u, v, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, u, v, &uu, &vv, &ss, 0)
+         return (uu,vv)
+ 
+     def normalize_with_scalar(self, int u, int v):
+@@ -1186,7 +1186,7 @@ cdef class P1List():
+             True
+         """
+         cdef int uu, vv, ss
+-        self.__normalize(self.__N, u, v, &uu, &vv, &ss, 1)
++        self._normalize(self.__N, u, v, &uu, &vv, &ss, 1)
+         return (uu, vv, ss)
+ 
+     def N(self):
+diff --git a/src/sage/numerical/gauss_legendre.pyx b/src/sage/numerical/gauss_legendre.pyx
+index 5325797c7aa..96708c5b1ac 100644
+--- a/src/sage/numerical/gauss_legendre.pyx
++++ b/src/sage/numerical/gauss_legendre.pyx
+@@ -117,8 +117,8 @@ def nodes_uncached(degree, prec):
+         raise ValueError("degree=%s not supported (degree must be 3 or even)" % degree)
+     R = RealField(int(prec*3/2))
+     Rout = RealField(prec)
+-    mpfr_init2(u,R.__prec)
+-    mpfr_init2(v,R.__prec)
++    mpfr_init2(u,R._prec)
++    mpfr_init2(v,R._prec)
+     ZERO = R.zero()
+     ONE = R.one()
+     HALF = ONE/2
+diff --git a/src/sage/numerical/linear_functions.pyx b/src/sage/numerical/linear_functions.pyx
+index 5549ff436f5..f3fc6fe419c 100644
+--- a/src/sage/numerical/linear_functions.pyx
++++ b/src/sage/numerical/linear_functions.pyx
+@@ -1579,7 +1579,10 @@ cdef class LinearConstraint(LinearFunctionOrConstraint):
+         while True:
+             yield (lhs, rhs)
+             lhs = rhs
+-            rhs = next(term_iter)
++            try:
++                rhs = next(term_iter)
++            except StopIteration:
++                return
+ 
+     def inequalities(self):
+         """
+@@ -1612,7 +1615,10 @@ cdef class LinearConstraint(LinearFunctionOrConstraint):
+         while True:
+             yield (lhs, rhs)
+             lhs = rhs
+-            rhs = next(term_iter)
++            try:
++                rhs = next(term_iter)
++            except StopIteration:
++                return
+ 
+     def _repr_(self):
+         r"""
+diff --git a/src/sage/quivers/representation.py b/src/sage/quivers/representation.py
+index 9c11eb8ad0e..db82cbd7c86 100644
+--- a/src/sage/quivers/representation.py
++++ b/src/sage/quivers/representation.py
+@@ -1297,10 +1297,7 @@ def copy(self):
+             sage: v.get_element(1)
+             (1, 0)
+         """
+-        if hasattr(self, '__custom_name'):
+-            name = self.__custom_name
+-        else:
+-            name = None
++        name = self.get_custom_name()
+         return self.parent()(self._elems.copy(), name)
+ 
+ ####################################################################
+diff --git a/src/sage/rings/complex_arb.pyx b/src/sage/rings/complex_arb.pyx
+index ef432c1e945..95e615f3ee6 100644
+--- a/src/sage/rings/complex_arb.pyx
++++ b/src/sage/rings/complex_arb.pyx
+@@ -874,7 +874,7 @@ class ComplexBallField(UniqueRepresentation, sage.rings.abc.ComplexBallField):
+         cdef RealBall rb
+         cdef ComplexBall cb
+         acb_poly_init(rounded_poly)
+-        cdef long deg = acb_poly_degree(poly.__poly)
++        cdef long deg = acb_poly_degree(poly._poly)
+         if deg < 0:
+             raise ArithmeticError("taking the roots of the zero polynomial")
+         cdef acb_ptr roots = _acb_vec_init(deg)
+@@ -883,7 +883,7 @@ class ComplexBallField(UniqueRepresentation, sage.rings.abc.ComplexBallField):
+             while ((isolated < deg or any(acb_rel_accuracy_bits(&roots[i]) < tgtprec
+                                         for i in range(deg)))
+                 and prec < maxprec):
+-                acb_poly_set_round(rounded_poly, poly.__poly, prec)
++                acb_poly_set_round(rounded_poly, poly._poly, prec)
+                 maxiter = min(max(deg, 32), prec)
+                 if (prec == initial_prec):
+                     isolated = acb_poly_find_roots(roots, rounded_poly, NULL, maxiter, prec)
+diff --git a/src/sage/rings/complex_mpc.pxd b/src/sage/rings/complex_mpc.pxd
+index 762c38afbdc..f7d8cb9492c 100644
+--- a/src/sage/rings/complex_mpc.pxd
++++ b/src/sage/rings/complex_mpc.pxd
+@@ -11,7 +11,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+     cpdef _mul_(self, other)
+ 
+ cdef class MPComplexField_class(sage.rings.ring.Field):
+-    cdef readonly int __prec
++    cdef readonly int _prec
+     cdef mpc_rnd_t __rnd
+     cdef object __rnd_str
+     cdef object __real_field
+diff --git a/src/sage/rings/complex_mpc.pyx b/src/sage/rings/complex_mpc.pyx
+index b3681ff724f..c847a9302b5 100644
+--- a/src/sage/rings/complex_mpc.pyx
++++ b/src/sage/rings/complex_mpc.pyx
+@@ -307,7 +307,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+         if prec < mpfr_prec_min() or prec > mpfr_prec_max():
+             raise ValueError("prec (=%s) must be >= %s and <= %s." % (
+                 prec, mpfr_prec_min(), mpfr_prec_max()))
+-        self.__prec = prec
++        self._prec = prec
+         if not isinstance(rnd, str):
+             raise TypeError("rnd must be a string")
+         try:
+@@ -331,7 +331,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+         cdef MPComplexNumber z
+         z = MPComplexNumber.__new__(MPComplexNumber)
+         z._parent = self
+-        mpc_init2(z.value, self.__prec)
++        mpc_init2(z.value, self._prec)
+         z.init = 1
+         return z
+ 
+@@ -344,7 +344,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: MPComplexField(200, 'RNDDU') # indirect doctest
+             Complex Field with 200 bits of precision and rounding RNDDU
+         """
+-        s = "Complex Field with %s bits of precision"%self.__prec
++        s = "Complex Field with %s bits of precision"%self._prec
+         if self.__rnd != MPC_RNDNN:
+             s = s + " and rounding %s"%(self.__rnd_str)
+         return s
+@@ -465,13 +465,13 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+         if RR.has_coerce_map_from(S):
+             return self._coerce_map_via([RR], S)
+ 
+-        if isinstance(S, MPComplexField_class) and S.prec() >= self.__prec:
++        if isinstance(S, MPComplexField_class) and S.prec() >= self._prec:
+             #FIXME: What map when rounding modes differ but prec is the same ?
+             #       How to provide commutativity of morphisms ?
+             #       Change _cmp_ when done
+             return MPCtoMPC(S, self)
+ 
+-        if isinstance(S, ComplexField_class) and S.prec() >= self.__prec:
++        if isinstance(S, ComplexField_class) and S.prec() >= self._prec:
+             return CCtoMPC(S, self)
+ 
+         late_import()
+@@ -490,7 +490,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: loads(dumps(C)) == C
+             True
+         """
+-        return __create__MPComplexField_version0, (self.__prec, self.__rnd_str)
++        return __create__MPComplexField_version0, (self._prec, self.__rnd_str)
+ 
+     def __richcmp__(left, right, int op):
+         """
+@@ -513,7 +513,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+ 
+         cdef MPComplexField_class s = <MPComplexField_class>left
+         cdef MPComplexField_class o = <MPComplexField_class>right
+-        return richcmp(s.__prec, o.__prec, op)
++        return richcmp(s._prec, o._prec, op)
+ 
+     def gen(self, n=0):
+         """
+@@ -604,7 +604,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: C = MPComplexField(10, 'RNDNZ'); C.name()
+             'MPComplexField10_RNDNZ'
+         """
+-        return "MPComplexField%s_%s"%(self.__prec, self.__rnd_str)
++        return "MPComplexField%s_%s"%(self._prec, self.__rnd_str)
+ 
+     def __hash__(self):
+         """
+@@ -629,7 +629,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: MPComplexField(22).prec()
+             22
+         """
+-        return self.__prec
++        return self._prec
+ 
+     def rounding_mode(self):
+         """
+@@ -707,7 +707,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+         cdef MPComplexNumber z
+         z = MPComplexNumber.__new__(MPComplexNumber)
+         z._parent = self._parent
+-        mpc_init2(z.value, (<MPComplexField_class>self._parent).__prec)
++        mpc_init2(z.value, (<MPComplexField_class>self._parent)._prec)
+         z.init = 1
+         return z
+ 
+@@ -760,7 +760,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+         if parent is None:
+             raise TypeError
+         self._parent = parent
+-        mpc_init2(self.value, parent.__prec)
++        mpc_init2(self.value, parent._prec)
+         self.init = 1
+         if x is None: return
+         self._set(x, y, base)
+@@ -1010,7 +1010,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+             sage: i.prec()
+             2000
+         """
+-        return <MPComplexField_class>(self._parent).__prec
++        return <MPComplexField_class>(self._parent)._prec
+ 
+     def real(self):
+         """
+@@ -1571,26 +1571,6 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+         mpc_norm(x.value, self.value, (<RealField_class>x._parent).rnd)
+         return x
+ 
+-    def __rtruediv__(self, left):
+-        r"""
+-        Returns the quotient of ``left`` with ``self``, that is: ``left/self``
+-        as a complex number.
+-
+-        INPUT:
+-
+-        - ``left`` -- a complex number
+-
+-        EXAMPLES::
+-
+-            sage: MPC = MPComplexField()
+-            sage: a = MPC(2, 2)
+-            sage: a.__rtruediv__(MPC(1))
+-            0.250000000000000 - 0.250000000000000*I
+-            sage: MPC(1)/a
+-            0.250000000000000 - 0.250000000000000*I
+-        """
+-        return MPComplexNumber(self._parent, left)/self
+-
+     def __pow__(self, right, modulus):
+         """
+         Compute ``self`` raised to the power of exponent, rounded in
+@@ -2347,7 +2327,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+ 
+         cdef mpc_rnd_t rnd = (<MPComplexField_class>(self._parent)).__rnd
+ 
+-        cdef int prec = self._parent.__prec
++        cdef int prec = self._parent._prec
+ 
+         if optimal or algorithm == "principal":
+             if not isinstance(right, MPComplexNumber) or (<MPComplexNumber>right)._parent is not self._parent:
+diff --git a/src/sage/rings/complex_mpfr.pyx b/src/sage/rings/complex_mpfr.pyx
+index 33d73d81b12..61f2cadc8e4 100644
+--- a/src/sage/rings/complex_mpfr.pyx
++++ b/src/sage/rings/complex_mpfr.pyx
+@@ -1658,28 +1658,6 @@ cdef class ComplexNumber(sage.structure.element.FieldElement):
+         mpfr_clear(right_nm)
+         return x
+ 
+-    def __rtruediv__(self, left):
+-        r"""
+-        Return the quotient of left with ``self``, that is:
+-
+-        ``left/self``
+-
+-        as a complex number.
+-
+-        INPUT:
+-
+-        - ``left`` -- a complex number to divide by ``self``
+-
+-        EXAMPLES::
+-
+-            sage: a = ComplexNumber(2,0)
+-            sage: a.__rtruediv__(CC(1))
+-            0.500000000000000
+-            sage: CC(1)/a
+-            0.500000000000000
+-        """
+-        return ComplexNumber(self._parent, left)/self
+-
+     def __pow__(self, right, modulus):
+         r"""
+         Raise ``self`` to the ``right`` exponent.
+diff --git a/src/sage/rings/finite_rings/integer_mod.pxd b/src/sage/rings/finite_rings/integer_mod.pxd
+index 1e3cb81c148..351ffa25e1b 100644
+--- a/src/sage/rings/finite_rings/integer_mod.pxd
++++ b/src/sage/rings/finite_rings/integer_mod.pxd
+@@ -20,7 +20,7 @@ cdef class NativeIntStruct:
+ 
+ 
+ cdef class IntegerMod_abstract(FiniteRingElement):
+-    cdef NativeIntStruct __modulus
++    cdef NativeIntStruct _modulus
+     cdef _new_c_from_long(self, long value)
+     cdef IntegerMod_abstract _new_c_fast(self, unsigned long value)
+     cdef void set_from_mpz(self, mpz_t value)
+diff --git a/src/sage/rings/finite_rings/integer_mod.pyx b/src/sage/rings/finite_rings/integer_mod.pyx
+index b9461bd362e..d64ba5af84f 100644
+--- a/src/sage/rings/finite_rings/integer_mod.pyx
++++ b/src/sage/rings/finite_rings/integer_mod.pyx
+@@ -361,7 +361,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             ZeroDivisionError: inverse of Mod(4, 30) does not exist
+         """
+         self._parent = parent
+-        self.__modulus = parent._pyx_order
++        self._modulus = parent._pyx_order
+ 
+         if value is None:
+             return
+@@ -373,7 +373,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         if isinstance(value, Integer):
+             z = <Integer>value
+         elif isinstance(value, rational.Rational):
+-            z = value % self.__modulus.sageInteger
++            z = value % self._modulus.sageInteger
+         elif integer_check_long_py(value, &longval, &err) and not err:
+             self.set_from_long(longval)
+             return
+@@ -388,7 +388,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+                     value = py_scalar_to_element(value)
+                 if isinstance(value, Element) and value.parent().is_exact():
+                     value = sage.rings.rational_field.QQ(value)
+-                    z = value % self.__modulus.sageInteger
++                    z = value % self._modulus.sageInteger
+                 else:
+                     raise
+         self.set_from_mpz(z.value)
+@@ -397,7 +397,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         cdef type t = type(self)
+         x = <IntegerMod_abstract>t.__new__(t)
+         x._parent = self._parent
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x.set_from_ulong_fast(value)
+         return x
+ 
+@@ -405,7 +405,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         cdef type t = type(self)
+         cdef IntegerMod_abstract x = <IntegerMod_abstract>t.__new__(t)
+         x._parent = self._parent
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x.set_from_long(value)
+         return x
+ 
+@@ -529,17 +529,17 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         """
+         if self.is_zero():
+             return True
+-        m = self.__modulus.sageInteger.exact_log(2) + 1
++        m = self._modulus.sageInteger.exact_log(2) + 1
+         return (self**m).is_zero()
+ 
+     #################################################################
+     # Interfaces
+     #################################################################
+     def _pari_init_(self):
+-        return 'Mod(%s,%s)'%(str(self), self.__modulus.sageInteger)
++        return 'Mod(%s,%s)'%(str(self), self._modulus.sageInteger)
+ 
+     def __pari__(self):
+-        return self.lift().__pari__().Mod(self.__modulus.sageInteger)
++        return self.lift().__pari__().Mod(self._modulus.sageInteger)
+ 
+     def _gap_init_(self):
+         r"""
+@@ -558,7 +558,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             sage: gap(Mod(4, 48))
+             ZmodnZObj( 4, 48 )
+         """
+-        return '%s*One(ZmodnZ(%s))' % (self, self.__modulus.sageInteger)
++        return '%s*One(ZmodnZ(%s))' % (self, self._modulus.sageInteger)
+ 
+     def _magma_init_(self, magma):
+         """
+@@ -869,7 +869,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             sage: Mod(3,17).modulus()
+             17
+         """
+-        return self.__modulus.sageInteger
++        return self._modulus.sageInteger
+ 
+     def charpoly(self, var='x'):
+         """
+@@ -1229,7 +1229,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+                 modulus = R.gen()**2 - R(self)
+                 if self._parent.is_field():
+                     from .finite_field_constructor import FiniteField
+-                    Q = FiniteField(self.__modulus.sageInteger**2, y, modulus)
++                    Q = FiniteField(self._modulus.sageInteger**2, y, modulus)
+                 else:
+                     R = self.parent()['x']
+                     Q = R.quotient(modulus, names=(y,))
+@@ -1250,7 +1250,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             if all and e > 1 and not self.is_unit():
+                 if self.is_zero():
+                     # All multiples of p^ciel(e/2) vanish
+-                    return [self._parent(x) for x in range(0, self.__modulus.sageInteger, p**((e+1)/2))]
++                    return [self._parent(x) for x in range(0, self._modulus.sageInteger, p**((e+1)/2))]
+                 else:
+                     z = self.lift()
+                     val = z.valuation(p)/2  # square => valuation is even
+@@ -1272,7 +1272,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+                     p_exp = p**exp
+                     w = [self._parent(a.lift() * p_val + b)
+                             for a in u.sqrt(all=True)
+-                            for b in range(0, self.__modulus.sageInteger, p_exp)]
++                            for b in range(0, self._modulus.sageInteger, p_exp)]
+                     if p == 2:
+                         w = list(set(w))
+                     w.sort()
+@@ -1624,7 +1624,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         despite the possibly probabilistic nature of the underlying
+         algorithm.
+         """
+-        if self.lift() > self.__modulus.sageInteger >> 1:
++        if self.lift() > self._modulus.sageInteger >> 1:
+             return -self
+         return self
+ 
+@@ -1705,27 +1705,27 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         cdef int_fast64_t new_modulus
+         if not isinstance(self, IntegerMod_gmp) and not isinstance(other, IntegerMod_gmp):
+ 
+-            if other.__modulus.int64 == 1: return self
+-            new_modulus = self.__modulus.int64 * other.__modulus.int64
++            if other._modulus.int64 == 1: return self
++            new_modulus = self._modulus.int64 * other._modulus.int64
+             if new_modulus < INTEGER_MOD_INT32_LIMIT:
+-                return self.__crt(other)
++                return self._crt(other)
+ 
+             elif new_modulus < INTEGER_MOD_INT64_LIMIT:
+                 if not isinstance(self, IntegerMod_int64):
+                     self = IntegerMod_int64(self._parent, self.lift())
+                 if not isinstance(other, IntegerMod_int64):
+                     other = IntegerMod_int64(other._parent, other.lift())
+-                return self.__crt(other)
++                return self._crt(other)
+ 
+         if not isinstance(self, IntegerMod_gmp):
+-            if self.__modulus.int64 == 1: return other
++            if self._modulus.int64 == 1: return other
+             self = IntegerMod_gmp(self._parent, self.lift())
+ 
+         if not isinstance(other, IntegerMod_gmp):
+-            if other.__modulus.int64 == 1: return self
++            if other._modulus.int64 == 1: return self
+             other = IntegerMod_gmp(other._parent, other.lift())
+ 
+-        return self.__crt(other)
++        return self._crt(other)
+ 
+     def additive_order(self):
+         r"""
+@@ -1742,7 +1742,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             sage: Integers(90308402384902)(2).additive_order()
+             45154201192451
+         """
+-        n = self.__modulus.sageInteger
++        n = self._modulus.sageInteger
+         return sage.rings.integer.Integer(n // self.lift().gcd(n))
+ 
+     def is_primitive_root(self):
+@@ -1856,7 +1856,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             return sage.rings.integer.Integer(self.__pari__().znorder())
+         except PariError:
+             raise ArithmeticError("multiplicative order of %s not defined since it is not a unit modulo %s"%(
+-                self, self.__modulus.sageInteger))
++                self, self._modulus.sageInteger))
+ 
+     def valuation(self, p):
+         """
+@@ -1905,7 +1905,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             2
+ 
+         """
+-        p=self.__modulus.sageInteger.gcd(p)
++        p=self._modulus.sageInteger.gcd(p)
+         if p==1:
+             raise ValueError("Valuation with respect to a unit is not defined.")
+         r = 0
+@@ -1913,7 +1913,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         while not (self % power): # self % power == 0
+             r += 1
+             power *= p
+-            if not power.divides(self.__modulus.sageInteger):
++            if not power.divides(self._modulus.sageInteger):
+                 from sage.rings.infinity import infinity
+                 return infinity
+         return r
+@@ -1980,7 +1980,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+     cdef IntegerMod_gmp _new_c(self):
+         cdef IntegerMod_gmp x
+         x = IntegerMod_gmp.__new__(IntegerMod_gmp)
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x._parent = self._parent
+         return x
+ 
+@@ -1989,7 +1989,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+ 
+     cdef void set_from_mpz(self, mpz_t value):
+         cdef sage.rings.integer.Integer modulus
+-        modulus = self.__modulus.sageInteger
++        modulus = self._modulus.sageInteger
+         mpz_mod(self.value, value, modulus.value)
+ 
+     cdef void set_from_long(self, long value):
+@@ -2001,7 +2001,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             1
+         """
+         mpz_set_si(self.value, value)
+-        mpz_mod(self.value, self.value, self.__modulus.sageInteger.value)
++        mpz_mod(self.value, self.value, self._modulus.sageInteger.value)
+ 
+     cdef void set_from_ulong_fast(self, unsigned long value):
+         mpz_set_ui(self.value, value)
+@@ -2071,7 +2071,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             x = self._new_c()
+             if k > 0:
+                 mpz_mul_2exp(x.value, self.value, k)
+-                mpz_fdiv_r(x.value, x.value, self.__modulus.sageInteger.value)
++                mpz_fdiv_r(x.value, x.value, self._modulus.sageInteger.value)
+             else:
+                 mpz_fdiv_q_2exp(x.value, self.value, -k)
+             return x
+@@ -2132,12 +2132,12 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         """
+         return self.lift().gcd(self.modulus()) == 1
+ 
+-    def __crt(IntegerMod_gmp self, IntegerMod_gmp other):
++    def _crt(IntegerMod_gmp self, IntegerMod_gmp other):
+         cdef IntegerMod_gmp lift, x
+         cdef sage.rings.integer.Integer modulus, other_modulus
+ 
+-        modulus = self.__modulus.sageInteger
+-        other_modulus = other.__modulus.sageInteger
++        modulus = self._modulus.sageInteger
++        other_modulus = other._modulus.sageInteger
+         from .integer_mod_ring import IntegerModRing
+         lift = IntegerMod_gmp(IntegerModRing(modulus*other_modulus))
+         try:
+@@ -2188,8 +2188,8 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+         mpz_add(x.value, self.value, (<IntegerMod_gmp>right).value)
+-        if mpz_cmp(x.value, self.__modulus.sageInteger.value)  >= 0:
+-            mpz_sub(x.value, x.value, self.__modulus.sageInteger.value)
++        if mpz_cmp(x.value, self._modulus.sageInteger.value)  >= 0:
++            mpz_sub(x.value, x.value, self._modulus.sageInteger.value)
+         return x
+ 
+     cpdef _sub_(self, right):
+@@ -2204,7 +2204,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         x = self._new_c()
+         mpz_sub(x.value, self.value, (<IntegerMod_gmp>right).value)
+         if mpz_sgn(x.value) == -1:
+-            mpz_add(x.value, x.value, self.__modulus.sageInteger.value)
++            mpz_add(x.value, x.value, self._modulus.sageInteger.value)
+         return x
+ 
+     cpdef _neg_(self):
+@@ -2220,7 +2220,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             return self
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+-        mpz_sub(x.value, self.__modulus.sageInteger.value, self.value)
++        mpz_sub(x.value, self._modulus.sageInteger.value, self.value)
+         return x
+ 
+     cpdef _mul_(self, right):
+@@ -2234,7 +2234,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+         mpz_mul(x.value, self.value,  (<IntegerMod_gmp>right).value)
+-        mpz_fdiv_r(x.value, x.value, self.__modulus.sageInteger.value)
++        mpz_fdiv_r(x.value, x.value, self._modulus.sageInteger.value)
+         return x
+ 
+     cpdef _div_(self, right):
+@@ -2310,7 +2310,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         cdef IntegerMod_gmp x = self._new_c()
+         sig_on()
+         try:
+-            mpz_pow_helper(x.value, self.value, exp, self.__modulus.sageInteger.value)
++            mpz_pow_helper(x.value, self.value, exp, self._modulus.sageInteger.value)
+         finally:
+             sig_off()
+         return x
+@@ -2331,12 +2331,12 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             ZeroDivisionError: inverse of Mod(2, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000) does not exist
+         """
+         if self.is_zero():
+-            raise ZeroDivisionError(f"inverse of Mod(0, {self.__modulus.sageInteger}) does not exist")
++            raise ZeroDivisionError(f"inverse of Mod(0, {self._modulus.sageInteger}) does not exist")
+ 
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+-        if not mpz_invert(x.value, self.value, self.__modulus.sageInteger.value):
+-            raise ZeroDivisionError(f"inverse of Mod({self}, {self.__modulus.sageInteger}) does not exist")
++        if not mpz_invert(x.value, self.value, self._modulus.sageInteger.value):
++            raise ZeroDivisionError(f"inverse of Mod({self}, {self._modulus.sageInteger}) does not exist")
+         return x
+ 
+     def lift(IntegerMod_gmp self):
+@@ -2391,10 +2391,10 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         """
+         cdef IntegerMod_gmp ans = self._new_c()
+         sig_on()
+-        mpz_gcd(ans.value, self.value, self.__modulus.sageInteger.value)
++        mpz_gcd(ans.value, self.value, self._modulus.sageInteger.value)
+         mpz_gcd(ans.value, ans.value, other.value)
+         sig_off()
+-        if mpz_cmp(ans.value, self.__modulus.sageInteger.value) == 0:
++        if mpz_cmp(ans.value, self._modulus.sageInteger.value) == 0:
+             # self = other = 0
+             mpz_set_ui(ans.value, 0)
+         return ans
+@@ -2422,30 +2422,30 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+     """
+ 
+     cdef IntegerMod_int _new_c(self, int_fast32_t value):
+-        if self.__modulus.table is not None:
+-            return self.__modulus.table[value]
++        if self._modulus.table is not None:
++            return self._modulus.table[value]
+         cdef IntegerMod_int x = IntegerMod_int.__new__(IntegerMod_int)
+         x._parent = self._parent
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x.ivalue = value
+         return x
+ 
+     cdef void set_from_mpz(self, mpz_t value):
+-        self.ivalue = mpz_fdiv_ui(value, self.__modulus.int32)
++        self.ivalue = mpz_fdiv_ui(value, self._modulus.int32)
+ 
+     cdef void set_from_long(self, long value):
+-        self.ivalue = value % self.__modulus.int32
++        self.ivalue = value % self._modulus.int32
+         if self.ivalue < 0:
+-            self.ivalue += self.__modulus.int32
++            self.ivalue += self._modulus.int32
+ 
+     cdef void set_from_ulong_fast(self, unsigned long value):
+         self.ivalue = value
+ 
+     cdef void set_from_int(IntegerMod_int self, int_fast32_t ivalue):
+         if ivalue < 0:
+-            self.ivalue = self.__modulus.int32 + (ivalue % self.__modulus.int32)
+-        elif ivalue >= self.__modulus.int32:
+-            self.ivalue = ivalue % self.__modulus.int32
++            self.ivalue = self._modulus.int32 + (ivalue % self._modulus.int32)
++        elif ivalue >= self._modulus.int32:
++            self.ivalue = ivalue % self._modulus.int32
+         else:
+             self.ivalue = ivalue
+ 
+@@ -2490,7 +2490,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: Zmod(1).one().is_one()
+             True
+         """
+-        return self.ivalue == 1 or self.__modulus.int32 == 1
++        return self.ivalue == 1 or self._modulus.int32 == 1
+ 
+     def __bool__(IntegerMod_int self):
+         """
+@@ -2519,9 +2519,9 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: a.is_unit()
+             False
+         """
+-        return gcd_int(self.ivalue, self.__modulus.int32) == 1
++        return gcd_int(self.ivalue, self._modulus.int32) == 1
+ 
+-    def __crt(IntegerMod_int self, IntegerMod_int other):
++    def _crt(IntegerMod_int self, IntegerMod_int other):
+         """
+         Use the Chinese Remainder Theorem to find an element of the
+         integers modulo the product of the moduli that reduces to self and
+@@ -2543,11 +2543,11 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         cdef int_fast32_t x
+ 
+         from .integer_mod_ring import IntegerModRing
+-        lift = IntegerMod_int(IntegerModRing(self.__modulus.int32 * other.__modulus.int32))
++        lift = IntegerMod_int(IntegerModRing(self._modulus.int32 * other._modulus.int32))
+ 
+         try:
+-            x = (other.ivalue - self.ivalue % other.__modulus.int32) * mod_inverse_int(self.__modulus.int32, other.__modulus.int32)
+-            lift.set_from_int( x * self.__modulus.int32 + self.ivalue )
++            x = (other.ivalue - self.ivalue % other._modulus.int32) * mod_inverse_int(self._modulus.int32, other._modulus.int32)
++            lift.set_from_int( x * self._modulus.int32 + self.ivalue )
+             return lift
+         except ZeroDivisionError:
+             raise ZeroDivisionError("moduli must be coprime")
+@@ -2586,8 +2586,8 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         """
+         cdef int_fast32_t x
+         x = self.ivalue + (<IntegerMod_int>right).ivalue
+-        if x >= self.__modulus.int32:
+-            x = x - self.__modulus.int32
++        if x >= self._modulus.int32:
++            x = x - self._modulus.int32
+         return self._new_c(x)
+ 
+     cpdef _sub_(self, right):
+@@ -2601,7 +2601,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         cdef int_fast32_t x
+         x = self.ivalue - (<IntegerMod_int>right).ivalue
+         if x < 0:
+-            x = x + self.__modulus.int32
++            x = x + self._modulus.int32
+         return self._new_c(x)
+ 
+     cpdef _neg_(self):
+@@ -2615,7 +2615,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         """
+         if self.ivalue == 0:
+             return self
+-        return self._new_c(self.__modulus.int32 - self.ivalue)
++        return self._new_c(self._modulus.int32 - self.ivalue)
+ 
+     cpdef _mul_(self, right):
+         """
+@@ -2625,7 +2625,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: R(7) * R(8)
+             6
+         """
+-        return self._new_c((self.ivalue * (<IntegerMod_int>right).ivalue) % self.__modulus.int32)
++        return self._new_c((self.ivalue * (<IntegerMod_int>right).ivalue) % self._modulus.int32)
+ 
+     cpdef _div_(self, right):
+         """
+@@ -2635,16 +2635,16 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: R(2)/3
+             4
+         """
+-        if self.__modulus.inverses is not None:
+-            right_inverse = self.__modulus.inverses[(<IntegerMod_int>right).ivalue]
++        if self._modulus.inverses is not None:
++            right_inverse = self._modulus.inverses[(<IntegerMod_int>right).ivalue]
+             if right_inverse is None:
+-                raise ZeroDivisionError(f"inverse of Mod({right}, {self.__modulus.sageInteger}) does not exist")
++                raise ZeroDivisionError(f"inverse of Mod({right}, {self._modulus.sageInteger}) does not exist")
+             else:
+-                return self._new_c((self.ivalue * (<IntegerMod_int>right_inverse).ivalue) % self.__modulus.int32)
++                return self._new_c((self.ivalue * (<IntegerMod_int>right_inverse).ivalue) % self._modulus.int32)
+ 
+         cdef int_fast32_t x
+-        x = self.ivalue * mod_inverse_int((<IntegerMod_int>right).ivalue, self.__modulus.int32)
+-        return self._new_c(x% self.__modulus.int32)
++        x = self.ivalue * mod_inverse_int((<IntegerMod_int>right).ivalue, self._modulus.int32)
++        return self._new_c(x% self._modulus.int32)
+ 
+     def __int__(IntegerMod_int self):
+         """
+@@ -2739,7 +2739,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         if k == 0:
+             return self
+         elif k > 0:
+-            return self._new_c((self.ivalue << k) % self.__modulus.int32)
++            return self._new_c((self.ivalue << k) % self._modulus.int32)
+         else:
+             return self._new_c(self.ivalue >> (-k))
+ 
+@@ -2802,7 +2802,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sig_on()
+             try:
+                 mpz_init(res_mpz)
+-                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self.__modulus.sageInteger.value)
++                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self._modulus.sageInteger.value)
+                 res = mpz_get_ui(res_mpz)
+                 mpz_clear(res_mpz)
+             finally:
+@@ -2811,12 +2811,12 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+ 
+         if long_exp == 0 and self.ivalue == 0:
+             # Return 0 if the modulus is 1, otherwise return 1.
+-            return self._new_c(self.__modulus.int32 != 1)
++            return self._new_c(self._modulus.int32 != 1)
+         cdef bint invert = False
+         if long_exp < 0:
+             invert = True
+             long_exp = -long_exp
+-        res = mod_pow_int(self.ivalue, long_exp, self.__modulus.int32)
++        res = mod_pow_int(self.ivalue, long_exp, self._modulus.int32)
+         if invert:
+             return ~self._new_c(res)
+         else:
+@@ -2833,14 +2833,14 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: Mod(0,1)^-1
+             0
+         """
+-        if self.__modulus.inverses is not None:
+-            x = self.__modulus.inverses[self.ivalue]
++        if self._modulus.inverses is not None:
++            x = self._modulus.inverses[self.ivalue]
+             if x is None:
+-                raise ZeroDivisionError(f"inverse of Mod({self}, {self.__modulus.sageInteger}) does not exist")
++                raise ZeroDivisionError(f"inverse of Mod({self}, {self._modulus.sageInteger}) does not exist")
+             else:
+                 return x
+         else:
+-            return self._new_c(mod_inverse_int(self.ivalue, self.__modulus.int32))
++            return self._new_c(mod_inverse_int(self.ivalue, self._modulus.int32))
+ 
+     def lift(IntegerMod_int self):
+         """
+@@ -3006,15 +3006,15 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: GF(103)(-1).sqrt(extend=False, all=True)
+             []
+         """
+-        cdef int_fast32_t i, n = self.__modulus.int32
++        cdef int_fast32_t i, n = self._modulus.int32
+         if n > 100:
+             moduli = self._parent.factored_order()
+         # Unless the modulus is tiny, test to see if we're in the really
+         # easy case of n prime, n = 3 mod 4.
+         if n > 100 and n % 4 == 3 and len(moduli) == 1 and moduli[0][1] == 1:
+-            if jacobi_int(self.ivalue, self.__modulus.int32) == 1:
++            if jacobi_int(self.ivalue, self._modulus.int32) == 1:
+                 # it's a non-zero square, sqrt(a) = a^(p+1)/4
+-                i = mod_pow_int(self.ivalue, (self.__modulus.int32+1)/4, n)
++                i = mod_pow_int(self.ivalue, (self._modulus.int32+1)/4, n)
+                 if i > n / 2:
+                     i = n - i
+                 if all:
+@@ -3049,7 +3049,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         This function returns `x` or `-x`, whichever has a
+         positive representative in `-n/2 < x \leq n/2`.
+         """
+-        if self.ivalue > self.__modulus.int32 / 2:
++        if self.ivalue > self._modulus.int32 / 2:
+             return -self
+         return self
+ 
+@@ -3082,9 +3082,9 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: mod(0,1).gcd(mod(0,1))
+             0
+         """
+-        cdef int_fast32_t g = gcd_int(self.ivalue, self.__modulus.int32)
++        cdef int_fast32_t g = gcd_int(self.ivalue, self._modulus.int32)
+         g = gcd_int(g, other.ivalue)
+-        if g == self.__modulus.int32: # self = other = 0
++        if g == self._modulus.int32: # self = other = 0
+             g = 0
+         return self._new_c(g)
+ 
+@@ -3256,27 +3256,27 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+     cdef IntegerMod_int64 _new_c(self, int_fast64_t value):
+         cdef IntegerMod_int64 x
+         x = IntegerMod_int64.__new__(IntegerMod_int64)
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x._parent = self._parent
+         x.ivalue = value
+         return x
+ 
+     cdef void set_from_mpz(self, mpz_t value):
+-        self.ivalue = mpz_fdiv_ui(value, self.__modulus.int64)
++        self.ivalue = mpz_fdiv_ui(value, self._modulus.int64)
+ 
+     cdef void set_from_long(self, long value):
+-        self.ivalue = value % self.__modulus.int64
++        self.ivalue = value % self._modulus.int64
+         if self.ivalue < 0:
+-            self.ivalue += self.__modulus.int64
++            self.ivalue += self._modulus.int64
+ 
+     cdef void set_from_ulong_fast(self, unsigned long value):
+         self.ivalue = value
+ 
+     cdef void set_from_int(IntegerMod_int64 self, int_fast64_t ivalue):
+         if ivalue < 0:
+-            self.ivalue = self.__modulus.int64 + (ivalue % self.__modulus.int64) # Is ivalue % self.__modulus.int64 actually negative?
+-        elif ivalue >= self.__modulus.int64:
+-            self.ivalue = ivalue % self.__modulus.int64
++            self.ivalue = self._modulus.int64 + (ivalue % self._modulus.int64) # Is ivalue % self._modulus.int64 actually negative?
++        elif ivalue >= self._modulus.int64:
++            self.ivalue = ivalue % self._modulus.int64
+         else:
+             self.ivalue = ivalue
+ 
+@@ -3344,9 +3344,9 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: mod(25, 5^10).is_unit()
+             False
+         """
+-        return gcd_int64(self.ivalue, self.__modulus.int64) == 1
++        return gcd_int64(self.ivalue, self._modulus.int64) == 1
+ 
+-    def __crt(IntegerMod_int64 self, IntegerMod_int64 other):
++    def _crt(IntegerMod_int64 self, IntegerMod_int64 other):
+         """
+         Use the Chinese Remainder Theorem to find an element of the
+         integers modulo the product of the moduli that reduces to self and
+@@ -3379,11 +3379,11 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         cdef int_fast64_t x
+ 
+         from .integer_mod_ring import IntegerModRing
+-        lift = IntegerMod_int64(IntegerModRing(self.__modulus.int64 * other.__modulus.int64))
++        lift = IntegerMod_int64(IntegerModRing(self._modulus.int64 * other._modulus.int64))
+ 
+         try:
+-            x = (other.ivalue - self.ivalue % other.__modulus.int64) * mod_inverse_int64(self.__modulus.int64, other.__modulus.int64)
+-            lift.set_from_int( x * self.__modulus.int64 + self.ivalue )
++            x = (other.ivalue - self.ivalue % other._modulus.int64) * mod_inverse_int64(self._modulus.int64, other._modulus.int64)
++            lift.set_from_int( x * self._modulus.int64 + self.ivalue )
+             return lift
+         except ZeroDivisionError:
+             raise ZeroDivisionError("moduli must be coprime")
+@@ -3422,8 +3422,8 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         """
+         cdef int_fast64_t x
+         x = self.ivalue + (<IntegerMod_int64>right).ivalue
+-        if x >= self.__modulus.int64:
+-            x = x - self.__modulus.int64
++        if x >= self._modulus.int64:
++            x = x - self._modulus.int64
+         return self._new_c(x)
+ 
+     cpdef _sub_(self, right):
+@@ -3437,7 +3437,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         cdef int_fast64_t x
+         x = self.ivalue - (<IntegerMod_int64>right).ivalue
+         if x < 0:
+-            x = x + self.__modulus.int64
++            x = x + self._modulus.int64
+         return self._new_c(x)
+ 
+     cpdef _neg_(self):
+@@ -3451,7 +3451,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         """
+         if self.ivalue == 0:
+             return self
+-        return self._new_c(self.__modulus.int64 - self.ivalue)
++        return self._new_c(self._modulus.int64 - self.ivalue)
+ 
+     cpdef _mul_(self, right):
+         """
+@@ -3461,7 +3461,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: R(700) * R(800)
+             60000
+         """
+-        return self._new_c((self.ivalue * (<IntegerMod_int64>right).ivalue) % self.__modulus.int64)
++        return self._new_c((self.ivalue * (<IntegerMod_int64>right).ivalue) % self._modulus.int64)
+ 
+ 
+     cpdef _div_(self, right):
+@@ -3473,7 +3473,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             33334
+         """
+         return self._new_c((self.ivalue * mod_inverse_int64((<IntegerMod_int64>right).ivalue,
+-                                   self.__modulus.int64) ) % self.__modulus.int64)
++                                   self._modulus.int64) ) % self._modulus.int64)
+ 
+     def __int__(IntegerMod_int64 self):
+         return self.ivalue
+@@ -3559,7 +3559,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         if k == 0:
+             return self
+         elif k > 0:
+-            return self._new_c((self.ivalue << k) % self.__modulus.int64)
++            return self._new_c((self.ivalue << k) % self._modulus.int64)
+         else:
+             return self._new_c(self.ivalue >> (-k))
+ 
+@@ -3633,7 +3633,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sig_on()
+             try:
+                 mpz_init(res_mpz)
+-                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self.__modulus.sageInteger.value)
++                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self._modulus.sageInteger.value)
+                 res = mpz_get_ui(res_mpz)
+                 mpz_clear(res_mpz)
+             finally:
+@@ -3642,14 +3642,14 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+ 
+         if long_exp == 0 and self.ivalue == 0:
+             # Return 0 if the modulus is 1, otherwise return 1.
+-            return self._new_c(self.__modulus.int64 != 1)
++            return self._new_c(self._modulus.int64 != 1)
+         cdef bint invert = False
+         if long_exp < 0:
+             invert = True
+             long_exp = -long_exp
+-        res = mod_pow_int64(self.ivalue, long_exp, self.__modulus.int64)
++        res = mod_pow_int64(self.ivalue, long_exp, self._modulus.int64)
+         if invert:
+-            return self._new_c(mod_inverse_int64(res, self.__modulus.int64))
++            return self._new_c(mod_inverse_int64(res, self._modulus.int64))
+         else:
+             return self._new_c(res)
+ 
+@@ -3666,7 +3666,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: a
+             7
+         """
+-        return self._new_c(mod_inverse_int64(self.ivalue, self.__modulus.int64))
++        return self._new_c(mod_inverse_int64(self.ivalue, self._modulus.int64))
+ 
+     def lift(IntegerMod_int64 self):
+         """
+@@ -3715,7 +3715,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         This function returns `x` or `-x`, whichever has a
+         positive representative in `-n/2 < x \leq n/2`.
+         """
+-        if self.ivalue > self.__modulus.int64 / 2:
++        if self.ivalue > self._modulus.int64 / 2:
+             return -self
+         return self
+ 
+@@ -3738,9 +3738,9 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: mod(0,17^5).gcd(mod(0,17^5))
+             0
+         """
+-        cdef int_fast64_t g = gcd_int64(self.ivalue, self.__modulus.int64)
++        cdef int_fast64_t g = gcd_int64(self.ivalue, self._modulus.int64)
+         g = gcd_int64(g, other.ivalue)
+-        if g == self.__modulus.int64: # self = other = 0
++        if g == self._modulus.int64: # self = other = 0
+             g = 0
+         return self._new_c(g)
+ 
+diff --git a/src/sage/rings/fraction_field_FpT.pyx b/src/sage/rings/fraction_field_FpT.pyx
+index 0a25191a11c..c9bb5d5a384 100644
+--- a/src/sage/rings/fraction_field_FpT.pyx
++++ b/src/sage/rings/fraction_field_FpT.pyx
+@@ -1650,7 +1650,7 @@ cdef class FpT_Fp_section(Section):
+                 raise ValueError("not constant")
+         ans = IntegerMod_int.__new__(IntegerMod_int)
+         ans._parent = self.codomain()
+-        ans.__modulus = ans._parent._pyx_order
++        ans._modulus = ans._parent._pyx_order
+         if nmod_poly_get_coeff_ui(x._denom, 0) != 1:
+             normalize(x._numer, x._denom, self.p)
+         ans.ivalue = nmod_poly_get_coeff_ui(x._numer, 0)
+diff --git a/src/sage/rings/fraction_field_element.pyx b/src/sage/rings/fraction_field_element.pyx
+index 11a2b646d35..75e47af1299 100644
+--- a/src/sage/rings/fraction_field_element.pyx
++++ b/src/sage/rings/fraction_field_element.pyx
+@@ -78,8 +78,8 @@ cdef class FractionFieldElement(FieldElement):
+         sage: F.one().quo_rem(F.one())
+         (1, 0)
+     """
+-    cdef object __numerator
+-    cdef object __denominator
++    cdef object _numerator
++    cdef object _denominator
+     cdef bint _is_reduced
+ 
+     def __init__(self, parent, numerator, denominator=1,
+@@ -108,17 +108,17 @@ cdef class FractionFieldElement(FieldElement):
+         """
+         FieldElement.__init__(self, parent)
+         if coerce:
+-            self.__numerator   = parent.ring()(numerator)
+-            self.__denominator = parent.ring()(denominator)
++            self._numerator   = parent.ring()(numerator)
++            self._denominator = parent.ring()(denominator)
+         else:
+-            self.__numerator   = numerator
+-            self.__denominator = denominator
++            self._numerator   = numerator
++            self._denominator = denominator
+         if reduce and parent.is_exact():
+             try:
+                 self.reduce()
+             except ArithmeticError:
+                 pass
+-        if self.__denominator.is_zero():
++        if self._denominator.is_zero():
+             raise ZeroDivisionError("fraction field element division by zero")
+ 
+     def _im_gens_(self, codomain, im_gens, base_map=None):
+@@ -154,8 +154,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: phi(i/a)                                                              # optional - sage.rings.number_field
+             ((-i))/b
+         """
+-        nnum = codomain.coerce(self.__numerator._im_gens_(codomain, im_gens, base_map=base_map))
+-        nden = codomain.coerce(self.__denominator._im_gens_(codomain, im_gens, base_map=base_map))
++        nnum = codomain.coerce(self._numerator._im_gens_(codomain, im_gens, base_map=base_map))
++        nden = codomain.coerce(self._denominator._im_gens_(codomain, im_gens, base_map=base_map))
+         return codomain.coerce(nnum/nden)
+ 
+     cpdef reduce(self):
+@@ -191,10 +191,10 @@ cdef class FractionFieldElement(FieldElement):
+         if self._is_reduced:
+             return
+         try:
+-            g = self.__numerator.gcd(self.__denominator)
++            g = self._numerator.gcd(self._denominator)
+             if not g.is_unit():
+-                self.__numerator //= g
+-                self.__denominator //= g
++                self._numerator //= g
++                self._denominator //= g
+             self._is_reduced = True
+         except AttributeError:
+             raise ArithmeticError("unable to reduce because lack of gcd or quo_rem algorithm")
+@@ -202,14 +202,14 @@ cdef class FractionFieldElement(FieldElement):
+             raise ArithmeticError("unable to reduce because gcd algorithm doesn't work on input")
+         except NotImplementedError:
+             raise ArithmeticError("unable to reduce because gcd algorithm not implemented on input")
+-        if not self.__denominator.is_one() and self.__denominator.is_unit():
++        if not self._denominator.is_one() and self._denominator.is_unit():
+             try:
+-                inv = self.__denominator.inverse_of_unit()
++                inv = self._denominator.inverse_of_unit()
+             except Exception:
+                 pass
+             else:
+-                self.__numerator *= inv
+-                self.__denominator = self.__denominator.parent().one()
++                self._numerator *= inv
++                self._denominator = self._denominator.parent().one()
+ 
+     def __copy__(self):
+         """
+@@ -223,8 +223,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: copy(f)
+             (x + y)/y
+         """
+-        return self.__class__(self._parent, self.__numerator,
+-                self.__denominator, coerce=False, reduce=False)
++        return self.__class__(self._parent, self._numerator,
++                self._denominator, coerce=False, reduce=False)
+ 
+     def numerator(self):
+         """
+@@ -238,7 +238,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f.numerator()
+             x + y
+         """
+-        return self.__numerator
++        return self._numerator
+ 
+     def denominator(self):
+         """
+@@ -252,7 +252,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f.denominator()
+             y
+         """
+-        return self.__denominator
++        return self._denominator
+ 
+ 
+     def is_square(self,root=False):
+@@ -399,10 +399,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: ((x+1)/(x^2+1)).subs({x: 1})                                          # optional - sage.rings.number_field
+             1
+         """
+-        if self.__denominator.is_one():
++        if self._denominator.is_one():
+             # Handle this case even over rings that don't support reduction, to
+             # avoid breaking existing code that carelessly mixes p and p/1
+-            return hash(self.__numerator)
++            return hash(self._numerator)
+         if self._parent.is_exact():
+             # May fail; let the exception propagate then.
+             # (In contrast, over inexact rings, we hash unreduced fractions
+@@ -413,8 +413,8 @@ cdef class FractionFieldElement(FieldElement):
+             # issues even if we didn't...)
+             self.reduce()
+         # Same algorithm as for elements of QQ
+-        n = hash(self.__numerator)
+-        d = hash(self.__denominator)
++        n = hash(self._numerator)
++        d = hash(self._denominator)
+         if d == 1:
+             return n
+         else:
+@@ -443,7 +443,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: h(x0=1)
+             (-2*x1*x2 + x1 + 1)/(x1 + x2)
+         """
+-        return self.__numerator(*x, **kwds) / self.__denominator(*x, **kwds)
++        return self._numerator(*x, **kwds) / self._denominator(*x, **kwds)
+ 
+     def _is_atomic(self):
+         """
+@@ -456,7 +456,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f._is_atomic()
+             False
+         """
+-        return self.__numerator._is_atomic() and self.__denominator._is_atomic()
++        return self._numerator._is_atomic() and self._denominator._is_atomic()
+ 
+     def _repr_(self):
+         """
+@@ -476,13 +476,13 @@ cdef class FractionFieldElement(FieldElement):
+         """
+         if self.is_zero():
+             return "0"
+-        s = "%s" % self.__numerator
+-        if self.__denominator != 1:
+-            denom_string = str( self.__denominator )
+-            if self.__denominator._is_atomic() and not ('*' in denom_string or '/' in denom_string):
+-                s = "%s/%s"%(self.__numerator._coeff_repr(no_space=False),denom_string)
++        s = "%s" % self._numerator
++        if self._denominator != 1:
++            denom_string = str( self._denominator )
++            if self._denominator._is_atomic() and not ('*' in denom_string or '/' in denom_string):
++                s = "%s/%s"%(self._numerator._coeff_repr(no_space=False),denom_string)
+             else:
+-                s = "%s/(%s)"%(self.__numerator._coeff_repr(no_space=False),denom_string)
++                s = "%s/(%s)"%(self._numerator._coeff_repr(no_space=False),denom_string)
+         return s
+ 
+     def _latex_(self):
+@@ -518,10 +518,10 @@ cdef class FractionFieldElement(FieldElement):
+         """
+         if self.is_zero():
+             return "0"
+-        if self.__denominator == 1:
+-            return latex.latex(self.__numerator)
+-        return "\\frac{%s}{%s}"%(latex.latex(self.__numerator),
+-                                 latex.latex(self.__denominator))
++        if self._denominator == 1:
++            return latex.latex(self._numerator)
++        return "\\frac{%s}{%s}"%(latex.latex(self._numerator),
++                                 latex.latex(self._denominator))
+ 
+     def _magma_init_(self, magma):
+         """
+@@ -577,10 +577,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: t - 1/t # indirect doctest                                            # optional - sage.rings.finite_rings
+             (t^2 + 6)/t
+         """
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         if (rnum.is_zero()):
+             return <FractionFieldElement> right
+@@ -602,7 +602,7 @@ cdef class FractionFieldElement(FieldElement):
+                             self._parent.ring().one(), coerce=False,
+                             reduce=False)
+                     else:
+-                        tden = self.__denominator * sden
++                        tden = self._denominator * sden
+                         e    = tnum.gcd(d)
+                         if not e.is_unit():
+                             tnum = tnum // e
+@@ -624,10 +624,10 @@ cdef class FractionFieldElement(FieldElement):
+             except TypeError:
+                 pass
+ 
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         return self.__class__(self._parent, rnum*sden + rden*snum, rden*sden,
+             coerce=False, reduce=False)
+@@ -652,10 +652,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: a * b # indirect doctest                                              # optional - sage.rings.finite_rings
+             3/(t + 1)
+         """
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         if (rnum.is_zero() or snum.is_zero()):
+             return self._parent.zero()
+@@ -689,10 +689,10 @@ cdef class FractionFieldElement(FieldElement):
+             except TypeError:
+                 pass
+ 
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         return self.__class__(self._parent, rnum * snum, rden * sden,
+             coerce=False, reduce=False)
+@@ -717,8 +717,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: a/b
+             (x*z - x + z - 1)/(z - 3)
+         """
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         if snum.is_zero():
+             raise ZeroDivisionError("fraction field element division by zero")
+@@ -743,10 +743,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: int(K(.5))
+             0
+         """
+-        if self.__denominator != 1:
++        if self._denominator != 1:
+             self.reduce()
+-        if self.__denominator == 1:
+-            return int(self.__numerator)
++        if self._denominator == 1:
++            return int(self._numerator)
+         else:
+             raise TypeError("denominator must equal 1")
+ 
+@@ -758,7 +758,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: float(x/x + y/y)
+             2.0
+         """
+-        return float(self.__numerator) / float(self.__denominator)
++        return float(self._numerator) / float(self._denominator)
+ 
+     def __complex__(self):
+         """
+@@ -768,7 +768,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: complex(x/(I*x) + (I*y)/y)
+             0j
+         """
+-        return complex(self.__numerator) / complex(self.__denominator)
++        return complex(self._numerator) / complex(self._denominator)
+ 
+     def _rational_(self):
+         r"""
+@@ -822,12 +822,12 @@ cdef class FractionFieldElement(FieldElement):
+             sage: A(C(u))                                                               # optional - sage.rings.number_field
+             u
+         """
+-        if self.__denominator.is_one():
+-            return R(self.__numerator)
++        if self._denominator.is_one():
++            return R(self._numerator)
+         else:
+             self.reduce()
+-            num = R(self.__numerator)
+-            inv_den = R(self.__denominator).inverse_of_unit()
++            num = R(self._numerator)
++            inv_den = R(self._denominator).inverse_of_unit()
+             return num * inv_den
+ 
+     _real_double_ = _conversion
+@@ -847,7 +847,7 @@ cdef class FractionFieldElement(FieldElement):
+         Returns self raised to the `right^{th}` power.
+ 
+         Note that we need to check whether or not right is negative so we
+-        don't set ``__numerator`` or ``__denominator`` to an element of the
++        don't set ``_numerator`` or ``_denominator`` to an element of the
+         fraction field instead of the underlying ring.
+ 
+         EXAMPLES::
+@@ -876,8 +876,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: ((x+y)/(x-y))^0
+             1
+         """
+-        snum = (<FractionFieldElement> self).__numerator
+-        sden = (<FractionFieldElement> self).__denominator
++        snum = (<FractionFieldElement> self)._numerator
++        sden = (<FractionFieldElement> self)._denominator
+         if right == 0:
+             R = self.parent().ring()
+             return self.__class__(self.parent(),
+@@ -904,7 +904,7 @@ cdef class FractionFieldElement(FieldElement):
+             (4*t^2 + 4*t)/(t + 2)
+         """
+         return self.__class__(self._parent,
+-            -self.__numerator, self.__denominator,
++            -self._numerator, self._denominator,
+             coerce=False, reduce=False)
+ 
+     def __abs__(self):
+@@ -915,7 +915,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: abs(FractionFieldElement(QQ, -2, 3, coerce=False))
+             2/3
+         """
+-        return abs(self.__numerator) / abs(self.__denominator)
++        return abs(self._numerator) / abs(self._denominator)
+ 
+     def __invert__(self):
+         """
+@@ -929,7 +929,7 @@ cdef class FractionFieldElement(FieldElement):
+         if self.is_zero():
+             raise ZeroDivisionError("Cannot invert 0")
+         return self.__class__(self._parent,
+-            self.__denominator, self.__numerator, coerce=False, reduce=False)
++            self._denominator, self._numerator, coerce=False, reduce=False)
+ 
+     cpdef _richcmp_(self, other, int op):
+         """
+@@ -951,10 +951,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: 1 > y
+             False
+         """
+-        return richcmp(self.__numerator *
+-                       (<FractionFieldElement>other).__denominator,
+-                       self.__denominator *
+-                       (<FractionFieldElement>other).__numerator, op)
++        return richcmp(self._numerator *
++                       (<FractionFieldElement>other)._denominator,
++                       self._denominator *
++                       (<FractionFieldElement>other)._numerator, op)
+ 
+     def valuation(self, v=None):
+         """
+@@ -972,7 +972,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f.valuation(x^2 + 1)
+             1
+         """
+-        return self.__numerator.valuation(v) - self.__denominator.valuation(v)
++        return self._numerator.valuation(v) - self._denominator.valuation(v)
+ 
+     def __bool__(self):
+         """
+@@ -991,7 +991,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: bool(1/x)
+             True
+         """
+-        return not self.__numerator.is_zero()
++        return not self._numerator.is_zero()
+ 
+     def is_zero(self):
+         """
+@@ -1010,7 +1010,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: u.parent() is F
+             True
+         """
+-        return self.__numerator.is_zero()
++        return self._numerator.is_zero()
+ 
+     def is_one(self):
+         """
+@@ -1025,7 +1025,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: (x/y).is_one()
+             False
+         """
+-        return self.__numerator == self.__denominator
++        return self._numerator == self._denominator
+ 
+     def _symbolic_(self, ring):
+         """
+@@ -1044,7 +1044,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: symbolic_expression(elt)                                              # optional - sage.symbolic
+             2/3*(x + y)/(x - y)
+         """
+-        return ring(self.__numerator)/ring(self.__denominator)
++        return ring(self._numerator)/ring(self._denominator)
+ 
+     def __reduce__(self):
+         """
+@@ -1058,7 +1058,7 @@ cdef class FractionFieldElement(FieldElement):
+             True
+         """
+         return (make_element,
+-                (self._parent, self.__numerator, self.__denominator))
++                (self._parent, self._numerator, self._denominator))
+ 
+     def _evaluate_polynomial(self, pol):
+         """
+@@ -1170,9 +1170,9 @@ cdef class FractionFieldElement_1poly_field(FractionFieldElement):
+         """
+         See :meth:`reduce`.
+         """
+-        invlc = ~self.__denominator.leading_coefficient()
+-        self.__denominator = self.__denominator.monic()
+-        self.__numerator *= invlc
++        invlc = ~self._denominator.leading_coefficient()
++        self._denominator = self._denominator.monic()
++        self._numerator *= invlc
+ 
+     def is_integral(self):
+         """
+diff --git a/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py b/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py
+index a27e75f5fce..74ef125fb6a 100644
+--- a/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py
++++ b/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py
+@@ -804,8 +804,8 @@ def _latex_(self):
+             \phi
+             sage: phi.reset_name()
+         """
+-        if hasattr(self, '__custom_name'):
+-            return latex_variable_name(getattr(self, '__custom_name'))
++        if self.get_custom_name() is not None:
++            return latex_variable_name(self.get_custom_name())
+         else:
+             return f'\\phi: {latex(self._function_ring.gen())} \\mapsto ' \
+                    f'{latex(self._gen)}'
+diff --git a/src/sage/rings/laurent_series_ring_element.pxd b/src/sage/rings/laurent_series_ring_element.pxd
+index d190645ce52..8df5a92c9e7 100644
+--- a/src/sage/rings/laurent_series_ring_element.pxd
++++ b/src/sage/rings/laurent_series_ring_element.pxd
+@@ -4,7 +4,7 @@ cdef class LaurentSeries(AlgebraElement):
+     cdef ModuleElement __u
+     cdef long __n
+ 
+-    cdef __normalize(self)
++    cdef _normalize(self)
+     cpdef _add_(self, other)
+     cpdef _mul_(self, other)
+ 
+diff --git a/src/sage/rings/laurent_series_ring_element.pyx b/src/sage/rings/laurent_series_ring_element.pyx
+index 8e950478045..9bef72396b7 100644
+--- a/src/sage/rings/laurent_series_ring_element.pyx
++++ b/src/sage/rings/laurent_series_ring_element.pyx
+@@ -302,7 +302,7 @@ cdef class LaurentSeries(AlgebraElement):
+         x = im_gens[0]
+         return codomain(self.__u._im_gens_(codomain, im_gens, base_map=base_map) * x**self.__n)
+ 
+-    cdef __normalize(self):
++    cdef _normalize(self):
+         r"""
+         A Laurent series is a pair (u(t), n), where either u=0 (to some
+         precision) or u is a unit. This pair corresponds to
+@@ -725,7 +725,7 @@ cdef class LaurentSeries(AlgebraElement):
+                 R = self._parent.base_ring()
+                 coeffs = [value] + [R(0) for _ in range(1,-j)] + self.__u.list()
+                 self.__u = self.__u._parent(coeffs)
+-        self.__normalize()
++        self._normalize()
+ 
+     cpdef _add_(self, right_m):
+         """
+diff --git a/src/sage/rings/morphism.pxd b/src/sage/rings/morphism.pxd
+index ea6089f29b4..4b8e8d052df 100644
+--- a/src/sage/rings/morphism.pxd
++++ b/src/sage/rings/morphism.pxd
+@@ -14,7 +14,7 @@ cdef class RingMap_lift(RingMap):
+ 
+ cdef class RingHomomorphism(RingMap):
+     cdef Morphism _lift
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+ cdef class RingHomomorphism_im_gens(RingHomomorphism):
+     cdef _im_gens
+diff --git a/src/sage/rings/number_field/number_field_element.pxd b/src/sage/rings/number_field/number_field_element.pxd
+index 9b6917223a0..c3d8a8b4a4b 100644
+--- a/src/sage/rings/number_field/number_field_element.pxd
++++ b/src/sage/rings/number_field/number_field_element.pxd
+@@ -11,12 +11,12 @@ from sage.libs.ntl.ntl_ZZ cimport ntl_ZZ
+ 
+ 
+ cdef class NumberFieldElement(NumberFieldElement_base):
+-    cdef ZZX_c __numerator
+-    cdef ZZ_c __denominator
++    cdef ZZX_c _numerator
++    cdef ZZ_c _denominator
+     # Pointers to the defining polynomial (with numerator) for the field.
+     # I keep these as pointers for arithmetic speed.
+-    cdef ntl_ZZX __fld_numerator
+-    cdef ntl_ZZ __fld_denominator
++    cdef ntl_ZZX _fld_numerator
++    cdef ntl_ZZ _fld_denominator
+     cdef object __multiplicative_order
+     cdef object __pari
+     cdef object __matrix
+diff --git a/src/sage/rings/number_field/number_field_element.pyx b/src/sage/rings/number_field/number_field_element.pyx
+index 27e33ad5be0..d44fc55b70c 100644
+--- a/src/sage/rings/number_field/number_field_element.pyx
++++ b/src/sage/rings/number_field/number_field_element.pyx
+@@ -218,8 +218,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef type t = type(self)
+         cdef NumberFieldElement x = <NumberFieldElement>t.__new__(t)
+         x._parent = self._parent
+-        x.__fld_numerator = self.__fld_numerator
+-        x.__fld_denominator = self.__fld_denominator
++        x._fld_numerator = self._fld_numerator
++        x._fld_denominator = self._fld_denominator
+         return x
+ 
+     cdef number_field(self):
+@@ -317,20 +317,20 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             True
+         """
+         FieldElement.__init__(self, parent)
+-        self.__fld_numerator, self.__fld_denominator = parent.absolute_polynomial_ntl()
++        self._fld_numerator, self._fld_denominator = parent.absolute_polynomial_ntl()
+ 
+         cdef ZZ_c coeff
+         if isinstance(f, (int, Integer_sage)):
+             # set it up and exit immediately
+             # fast pathway
+             mpz_to_ZZ(&coeff, (<Integer>ZZ(f)).value)
+-            ZZX_SetCoeff( self.__numerator, 0, coeff )
+-            ZZ_conv_from_int( self.__denominator, 1 )
++            ZZX_SetCoeff( self._numerator, 0, coeff )
++            ZZ_conv_from_int( self._denominator, 1 )
+             return
+         elif isinstance(f, NumberFieldElement):
+             if type(self) is type(f):
+-                self.__numerator = (<NumberFieldElement>f).__numerator
+-                self.__denominator = (<NumberFieldElement>f).__denominator
++                self._numerator = (<NumberFieldElement>f)._numerator
++                self._denominator = (<NumberFieldElement>f)._denominator
+                 return
+             else:
+                 f = f.polynomial()
+@@ -342,11 +342,11 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+ 
+         cdef long i
+         den = f.denominator()
+-        mpz_to_ZZ(&self.__denominator, (<Integer>ZZ(den)).value)
++        mpz_to_ZZ(&self._denominator, (<Integer>ZZ(den)).value)
+         num = f * den
+         for i from 0 <= i <= num.degree():
+             mpz_to_ZZ(&coeff, (<Integer>ZZ(num[i])).value)
+-            ZZX_SetCoeff( self.__numerator, i, coeff )
++            ZZX_SetCoeff( self._numerator, i, coeff )
+ 
+     def _lift_cyclotomic_element(self, new_parent, bint check=True, int rel=0):
+         """
+@@ -417,17 +417,17 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef type t = type(self)
+         cdef NumberFieldElement x = <NumberFieldElement>t.__new__(t)
+         x._parent = <ParentWithBase>new_parent
+-        x.__fld_numerator, x.__fld_denominator = new_parent.polynomial_ntl()
+-        x.__denominator = self.__denominator
++        x._fld_numerator, x._fld_denominator = new_parent.polynomial_ntl()
++        x._denominator = self._denominator
+         cdef ZZX_c result
+         cdef ZZ_c tmp
+         cdef int i
+         cdef ntl_ZZX _num
+         cdef ntl_ZZ _den
+-        for i from 0 <= i <= ZZX_deg(self.__numerator):
+-            tmp = ZZX_coeff(self.__numerator, i)
++        for i from 0 <= i <= ZZX_deg(self._numerator):
++            tmp = ZZX_coeff(self._numerator, i)
+             ZZX_SetCoeff(result, i*rel, tmp)
+-        ZZX_rem(x.__numerator, result, x.__fld_numerator.x)
++        ZZX_rem(x._numerator, result, x._fld_numerator.x)
+         return x
+ 
+     def __reduce__(self):
+@@ -858,7 +858,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef int res
+ 
+         # fast equality check
+-        res = left.__numerator == _right.__numerator and left.__denominator == _right.__denominator
++        res = left._numerator == _right._numerator and left._denominator == _right._denominator
+         if res:
+             if op == Py_EQ or op == Py_GE or op == Py_LE:
+                 return True
+@@ -883,15 +883,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         if P._embedded_real:
+             mpz_init(ld)
+             mpz_init(rd)
+-            ZZ_to_mpz(ld, &left.__denominator)
+-            ZZ_to_mpz(rd, &_right.__denominator)
++            ZZ_to_mpz(ld, &left._denominator)
++            ZZ_to_mpz(rd, &_right._denominator)
+ 
+             v = <RealIntervalFieldElement> P._get_embedding_approx(0)
+             mpfi_init2(la, mpfi_get_prec(v.value))
+             mpfi_init2(ra, mpfi_get_prec(v.value))
+-            ZZX_evaluation_mpfi(la, left.__numerator, v.value)
++            ZZX_evaluation_mpfi(la, left._numerator, v.value)
+             mpfi_div_z(la, la, ld)
+-            ZZX_evaluation_mpfi(ra, _right.__numerator, v.value)
++            ZZX_evaluation_mpfi(ra, _right._numerator, v.value)
+             mpfi_div_z(ra, ra, rd)
+             while mpfr_greaterequal_p(&la.right, &ra.left) \
+                   and mpfr_greaterequal_p(&ra.right, &la.left):
+@@ -899,9 +899,9 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+                 v = <RealIntervalFieldElement> P._get_embedding_approx(i)
+                 mpfi_set_prec(la, mpfi_get_prec(v.value))
+                 mpfi_set_prec(ra, mpfi_get_prec(v.value))
+-                ZZX_evaluation_mpfi(la, left.__numerator, v.value)
++                ZZX_evaluation_mpfi(la, left._numerator, v.value)
+                 mpfi_div_z(la, la, ld)
+-                ZZX_evaluation_mpfi(ra, _right.__numerator, v.value)
++                ZZX_evaluation_mpfi(ra, _right._numerator, v.value)
+                 mpfi_div_z(ra, ra, rd)
+             if op == Py_LT or op == Py_LE:
+                 res = mpfr_less_p(&la.right, &ra.left)
+@@ -950,8 +950,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef Rational tmp_rational
+ 
+         # It seems like a simpler approach would be to simply generate
+-        # random integers for each coefficient of self.__numerator
+-        # and an integer for self.__denominator. However, this would
++        # random integers for each coefficient of self._numerator
++        # and an integer for self._denominator. However, this would
+         # generate things with a fairly fixed shape: in particular,
+         # we'd be very unlikely to get elements like 1/3*a^3 + 1/7,
+         # or anything where the denominators are actually unrelated
+@@ -965,19 +965,19 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+ 
+             # set the denominator
+             mpz_set_si(denom_temp.value, 1)
+-            mpz_to_ZZ(&self.__denominator, (<Integer>denom_temp).value)
+-            for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
++            mpz_to_ZZ(&self._denominator, (<Integer>denom_temp).value)
++            for i from 0 <= i < ZZX_deg(self._fld_numerator.x):
+                 tmp_integer = <Integer>(ZZ.random_element(x=num_bound,
+                                                    distribution=distribution))
+                 mpz_to_ZZ(&ntl_temp, (<Integer>tmp_integer).value)
+-                ZZX_SetCoeff(self.__numerator, i, ntl_temp)
++                ZZX_SetCoeff(self._numerator, i, ntl_temp)
+ 
+         else:
+             coeff_list = []
+             mpz_set_si(denom_temp.value, 1)
+             tmp_integer = Integer.__new__(Integer)
+ 
+-            for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
++            for i from 0 <= i < ZZX_deg(self._fld_numerator.x):
+                 tmp_rational = <Rational>(QQ.random_element(num_bound=num_bound,
+                                                             den_bound=den_bound,
+                                                             distribution=distribution))
+@@ -989,10 +989,10 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             # scale the numerators and set everything appropriately
+ 
+             # first, the denominator (easy)
+-            mpz_to_ZZ(&self.__denominator, (<Integer>denom_temp).value)
++            mpz_to_ZZ(&self._denominator, (<Integer>denom_temp).value)
+ 
+             # now the coefficients themselves.
+-            for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
++            for i from 0 <= i < ZZX_deg(self._fld_numerator.x):
+                 # calculate the new numerator. if our old entry is
+                 # p/q, and the lcm is k, it's just pk/q, which we
+                 # also know is integral -- so we can use mpz_divexact
+@@ -1006,7 +1006,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+                 # now set the coefficient of self
+                 mpz_to_ZZ(&ntl_temp, (<Integer>tmp_integer).value)
+ 
+-                ZZX_SetCoeff(self.__numerator, i, ntl_temp)
++                ZZX_SetCoeff(self._numerator, i, ntl_temp)
+ 
+         return 0  # No error
+ 
+@@ -1089,10 +1089,10 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: L.zero().sign()
+             0
+         """
+-        if ZZX_deg(self.__numerator) == -1:
++        if ZZX_deg(self._numerator) == -1:
+             return 0
+-        if ZZX_deg(self.__numerator) == 0:
+-            return ZZ_sign(ZZX_coeff(self.__numerator, 0))
++        if ZZX_deg(self._numerator) == 0:
++            return ZZ_sign(ZZX_coeff(self._numerator, 0))
+ 
+         if not (<number_field_base.NumberField> self._parent)._embedded_real:
+             raise TypeError("sign not well defined since no real embedding is specified")
+@@ -1153,12 +1153,12 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef RealIntervalFieldElement v
+ 
+ 
+-        if ZZX_deg(self.__numerator) <= 0:
++        if ZZX_deg(self._numerator) <= 0:
+             mpz_init(num)
+             mpz_init(den)
+ 
+-            ZZX_getitem_as_mpz(num, &self.__numerator, 0)
+-            ZZ_to_mpz(den, &self.__denominator)
++            ZZX_getitem_as_mpz(num, &self._numerator, 0)
++            ZZ_to_mpz(den, &self._denominator)
+ 
+             ans = PY_NEW(Integer)
+             mpz_fdiv_q(ans.value, num, den)
+@@ -1183,9 +1183,9 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         mpz_init(den)
+         mpfi_init2(a, mpfi_get_prec(v.value))
+ 
+-        ZZ_to_mpz(den, &self.__denominator)
++        ZZ_to_mpz(den, &self._denominator)
+ 
+-        ZZX_evaluation_mpfi(a, self.__numerator, v.value)
++        ZZX_evaluation_mpfi(a, self._numerator, v.value)
+         mpfi_div_z(a, a, den)
+ 
+         mpfr_floor(&a.left, &a.left)
+@@ -1197,7 +1197,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             v = <RealIntervalFieldElement> P._get_embedding_approx(i)
+ 
+             mpfi_set_prec(a, mpfi_get_prec(v.value))
+-            ZZX_evaluation_mpfi(a, self.__numerator, v.value)
++            ZZX_evaluation_mpfi(a, self._numerator, v.value)
+             mpfi_div_z(a, a, den)
+             mpfr_floor(&a.left ,&a.left)
+             mpfr_floor(&a.right, &a.right)
+@@ -1248,7 +1248,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             ...
+             TypeError: ceil not uniquely defined since no real embedding is specified
+         """
+-        if ZZX_deg(self.__numerator) <= 0:
++        if ZZX_deg(self._numerator) <= 0:
+             return self._rational_().ceil()
+ 
+         if not (<number_field_base.NumberField> self._parent)._embedded_real:
+@@ -1311,7 +1311,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             ...
+             TypeError: floor not uniquely defined since no real embedding is specified
+         """
+-        if ZZX_deg(self.__numerator) <= 0:
++        if ZZX_deg(self._numerator) <= 0:
+             return self._rational_().round()
+ 
+         return (self + QQ((1,2))).floor()
+@@ -2483,17 +2483,17 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef ZZ_c gcd
+         cdef ZZ_c t1
+         cdef ZZX_c t2
+-        if ZZ_IsOne(self.__denominator):
++        if ZZ_IsOne(self._denominator):
+             return
+-        ZZX_content(t1, self.__numerator)
+-        ZZ_GCD(gcd, t1, self.__denominator)
+-        if ZZ_sign(gcd) != ZZ_sign(self.__denominator):
++        ZZX_content(t1, self._numerator)
++        ZZ_GCD(gcd, t1, self._denominator)
++        if ZZ_sign(gcd) != ZZ_sign(self._denominator):
+             ZZ_negate(t1, gcd)
+             gcd = t1
+-        ZZX_div_ZZ(t2, self.__numerator, gcd)
+-        ZZ_div(t1, self.__denominator, gcd)
+-        self.__numerator = t2
+-        self.__denominator = t1
++        ZZX_div_ZZ(t2, self._numerator, gcd)
++        ZZ_div(t1, self._denominator, gcd)
++        self._numerator = t2
++        self._denominator = t1
+ 
+     cpdef _add_(self, right):
+         r"""
+@@ -2509,15 +2509,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef NumberFieldElement _right = right
+         cdef ZZ_c g, q1, q2
+         x = self._new()
+-        ZZ_GCD(g, self.__denominator, _right.__denominator)
+-        ZZ_div(q1, self.__denominator, g)
+-        ZZ_div(q2, _right.__denominator, g)
+-        ZZ_mul(x.__denominator, q1, q2)
+-        ZZ_mul(x.__denominator, x.__denominator, g)
++        ZZ_GCD(g, self._denominator, _right._denominator)
++        ZZ_div(q1, self._denominator, g)
++        ZZ_div(q2, _right._denominator, g)
++        ZZ_mul(x._denominator, q1, q2)
++        ZZ_mul(x._denominator, x._denominator, g)
+         cdef ZZX_c t1, t2
+-        ZZX_mul_ZZ(t1, self.__numerator, q2)
+-        ZZX_mul_ZZ(t2, _right.__numerator, q1)
+-        ZZX_add(x.__numerator, t1, t2)
++        ZZX_mul_ZZ(t1, self._numerator, q2)
++        ZZX_mul_ZZ(t2, _right._numerator, q1)
++        ZZX_add(x._numerator, t1, t2)
+         x._reduce_c_()
+         return x
+ 
+@@ -2534,15 +2534,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef NumberFieldElement _right = right
+         cdef ZZ_c g, q1, q2
+         x = self._new()
+-        ZZ_GCD(g, self.__denominator, _right.__denominator)
+-        ZZ_div(q1, self.__denominator, g)
+-        ZZ_div(q2, _right.__denominator, g)
+-        ZZ_mul(x.__denominator, q1, q2)
+-        ZZ_mul(x.__denominator, x.__denominator, g)
++        ZZ_GCD(g, self._denominator, _right._denominator)
++        ZZ_div(q1, self._denominator, g)
++        ZZ_div(q2, _right._denominator, g)
++        ZZ_mul(x._denominator, q1, q2)
++        ZZ_mul(x._denominator, x._denominator, g)
+         cdef ZZX_c t1, t2
+-        ZZX_mul_ZZ(t1, self.__numerator, q2)
+-        ZZX_mul_ZZ(t2, _right.__numerator, q1)
+-        ZZX_sub(x.__numerator, t1, t2)
++        ZZX_mul_ZZ(t1, self._numerator, q2)
++        ZZX_mul_ZZ(t2, _right._numerator, q1)
++        ZZX_sub(x._numerator, t1, t2)
+         x._reduce_c_()
+         return x
+ 
+@@ -2571,18 +2571,18 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         sig_on()
+         # MulMod doesn't handle non-monic polynomials.
+         # Therefore, we handle the non-monic case entirely separately.
+-        ZZ_mul(x.__denominator, self.__denominator, _right.__denominator)
+-        if ZZ_IsOne(ZZX_LeadCoeff(self.__fld_numerator.x)):
+-            ZZX_MulMod(x.__numerator, self.__numerator, _right.__numerator, self.__fld_numerator.x)
++        ZZ_mul(x._denominator, self._denominator, _right._denominator)
++        if ZZ_IsOne(ZZX_LeadCoeff(self._fld_numerator.x)):
++            ZZX_MulMod(x._numerator, self._numerator, _right._numerator, self._fld_numerator.x)
+         else:
+-            ZZX_mul(x.__numerator, self.__numerator, _right.__numerator)
+-            if ZZX_deg(x.__numerator) >= ZZX_deg(self.__fld_numerator.x):
+-                ZZX_mul_ZZ( x.__numerator, x.__numerator, self.__fld_denominator.x )
+-                ZZX_mul_ZZ( temp, self.__fld_numerator.x, x.__denominator )
+-                ZZ_power(temp1,ZZX_LeadCoeff(temp),ZZX_deg(x.__numerator)-ZZX_deg(self.__fld_numerator.x)+1)
+-                ZZX_PseudoRem(x.__numerator, x.__numerator, temp)
+-                ZZ_mul(x.__denominator, x.__denominator, self.__fld_denominator.x)
+-                ZZ_mul(x.__denominator, x.__denominator, temp1)
++            ZZX_mul(x._numerator, self._numerator, _right._numerator)
++            if ZZX_deg(x._numerator) >= ZZX_deg(self._fld_numerator.x):
++                ZZX_mul_ZZ( x._numerator, x._numerator, self._fld_denominator.x )
++                ZZX_mul_ZZ( temp, self._fld_numerator.x, x._denominator )
++                ZZ_power(temp1,ZZX_LeadCoeff(temp),ZZX_deg(x._numerator)-ZZX_deg(self._fld_numerator.x)+1)
++                ZZX_PseudoRem(x._numerator, x._numerator, temp)
++                ZZ_mul(x._denominator, x._denominator, self._fld_denominator.x)
++                ZZ_mul(x._denominator, x._denominator, temp1)
+         sig_off()
+         x._reduce_c_()
+         return x
+@@ -2704,7 +2704,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: bool(b + 1)
+             True
+         """
+-        return not IsZero_ZZX(self.__numerator)
++        return not IsZero_ZZX(self._numerator)
+ 
+     cpdef _neg_(self):
+         r"""
+@@ -2717,8 +2717,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         """
+         cdef NumberFieldElement x
+         x = self._new()
+-        ZZX_mul_long(x.__numerator, self.__numerator, -1)
+-        x.__denominator = self.__denominator
++        ZZX_mul_long(x._numerator, self._numerator, -1)
++        x._denominator = self._denominator
+         return x
+ 
+     cpdef _copy_for_parent(self, Parent parent):
+@@ -2738,8 +2738,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         """
+         cdef NumberFieldElement x
+         x = self._new()
+-        x.__numerator = self.__numerator
+-        x.__denominator = self.__denominator
++        x._numerator = self._numerator
++        x._denominator = self._denominator
+         x._set_parent(parent)
+         return x
+ 
+@@ -2826,7 +2826,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: L.<a> = K.extension(f)
+             sage: alpha = (a^8 + (zeta22^9 - zeta22^6 + 2*zeta22^4 + 33)*a^7)/(10**2555) #long time
+         """
+-        if IsZero_ZZX(self.__numerator):
++        if IsZero_ZZX(self._numerator):
+             raise ZeroDivisionError("number field element division by zero")
+         cdef NumberFieldElement x
+         cdef ZZX_c temp
+@@ -2835,8 +2835,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             # but may fail if NTL runs out of FFT primes.
+             x = self._new()
+             sig_on()
+-            ZZX_XGCD(x.__denominator, x.__numerator, temp, self.__numerator, self.__fld_numerator.x, 1)
+-            ZZX_mul_ZZ(x.__numerator, x.__numerator, self.__denominator)
++            ZZX_XGCD(x._denominator, x._numerator, temp, self._numerator, self._fld_numerator.x, 1)
++            ZZX_mul_ZZ(x._numerator, x._numerator, self._denominator)
+             x._reduce_c_()
+             sig_off()
+         except NTLError:
+@@ -2858,7 +2858,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: (2*I*I)._integer_()
+             -2
+         """
+-        if ZZX_deg(self.__numerator) >= 1:
++        if ZZX_deg(self._numerator) >= 1:
+             raise TypeError("Unable to coerce %s to an integer" % self)
+         return ZZ(self._rational_())
+ 
+@@ -2877,12 +2877,12 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: (I*I/2)._rational_()
+             -1/2
+         """
+-        if ZZX_deg(self.__numerator) >= 1:
++        if ZZX_deg(self._numerator) >= 1:
+             raise TypeError("Unable to coerce %s to a rational"%self)
+         cdef Integer num = Integer.__new__(Integer)
+-        ZZX_getitem_as_mpz(num.value, &self.__numerator, 0)
++        ZZX_getitem_as_mpz(num.value, &self._numerator, 0)
+         cdef Integer den = Integer.__new__(Integer)
+-        ZZ_to_mpz(den.value, &self.__denominator)
++        ZZ_to_mpz(den.value, &self._denominator)
+         return num / den
+ 
+     def _algebraic_(self, parent):
+@@ -3268,15 +3268,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef mpz_t z
+ 
+         mpz_init(z)
+-        ZZX_getitem_as_mpz(z, &self.__numerator, 0)
++        ZZX_getitem_as_mpz(z, &self._numerator, 0)
+         h = mpz_pythonhash(z)
+ 
+-        for i from 1 <= i <= ZZX_deg(self.__numerator):
+-            ZZX_getitem_as_mpz(z, &self.__numerator, i)
++        for i from 1 <= i <= ZZX_deg(self._numerator):
++            ZZX_getitem_as_mpz(z, &self._numerator, i)
+             # magic number below is floor(2^63 / (2+sqrt(2)))
+             h ^= mpz_pythonhash(z) + (<Py_hash_t> 2701463124188384701) + (h << 16) + (h >> 2)
+ 
+-        ZZ_to_mpz(z, &self.__denominator)
++        ZZ_to_mpz(z, &self._denominator)
+         # magic number below is floor((1+sqrt(5)) * 2^61)
+         h += (mpz_pythonhash(z) - 1) * (<Py_hash_t> 7461864723258187525)
+ 
+@@ -3305,12 +3305,12 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef int i
+         cdef mpz_t den
+         mpz_init(den)
+-        ZZ_to_mpz(den, &self.__denominator)
+-        cdef int size = ZZX_deg(self.__numerator) + 1
++        ZZ_to_mpz(den, &self._denominator)
++        cdef int size = ZZX_deg(self._numerator) + 1
+         cdef list coeffs = [None]*size
+         for i in range(size):
+             coeff = Rational.__new__(Rational)
+-            ZZX_getitem_as_mpz(mpq_numref(coeff.value), &self.__numerator, i)
++            ZZX_getitem_as_mpz(mpq_numref(coeff.value), &self._numerator, i)
+             mpz_set(mpq_denref(coeff.value), den)
+             mpq_canonicalize(coeff.value)
+             coeffs[i] = coeff
+@@ -3318,14 +3318,14 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         return coeffs
+ 
+     cdef void _ntl_coeff_as_mpz(self, mpz_t z, long i):
+-        if i > ZZX_deg(self.__numerator):
++        if i > ZZX_deg(self._numerator):
+             mpz_set_ui(z, 0)
+         else:
+-            ZZX_getitem_as_mpz(z, &self.__numerator, i)
++            ZZX_getitem_as_mpz(z, &self._numerator, i)
+ 
+     cdef void _ntl_denom_as_mpz(self, mpz_t z):
+         cdef Integer denom = Integer.__new__(Integer)
+-        ZZ_to_mpz(denom.value, &self.__denominator)
++        ZZ_to_mpz(denom.value, &self._denominator)
+         mpz_set(z, denom.value)
+ 
+     def denominator(self):
+@@ -3344,7 +3344,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             15
+         """
+         cdef Integer ans = Integer.__new__(Integer)
+-        ZZ_to_mpz(ans.value, &self.__denominator)
++        ZZ_to_mpz(ans.value, &self._denominator)
+         return ans
+ 
+     def _set_multiplicative_order(self, n):
+@@ -3474,8 +3474,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: a.is_one()
+             False
+         """
+-        return ZZX_IsOne(self.__numerator) == 1 and \
+-               ZZ_IsOne(self.__denominator) == 1
++        return ZZX_IsOne(self._numerator) == 1 and \
++               ZZ_IsOne(self._denominator) == 1
+ 
+     cpdef bint is_rational(self):
+         r"""
+@@ -3501,7 +3501,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: K(1/2).is_rational()
+             True
+         """
+-        return ZZX_deg(self.__numerator) <= 0
++        return ZZX_deg(self._numerator) <= 0
+ 
+     def is_integer(self):
+         r"""
+@@ -3527,7 +3527,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: K(1/2).is_integer()
+             False
+         """
+-        return ZZX_deg(self.__numerator) <= 0 and ZZ_IsOne(self.__denominator) == 1
++        return ZZX_deg(self._numerator) <= 0 and ZZ_IsOne(self._denominator) == 1
+ 
+     def trace(self, K=None):
+         r"""
+@@ -5322,8 +5322,8 @@ cdef class OrderElement_absolute(NumberFieldElement_absolute):
+         cdef OrderElement_absolute x = <OrderElement_absolute>t.__new__(t)
+         x._parent = self._parent
+         x._number_field = self._parent.number_field()
+-        x.__fld_numerator = self.__fld_numerator
+-        x.__fld_denominator = self.__fld_denominator
++        x._fld_numerator = self._fld_numerator
++        x._fld_denominator = self._fld_denominator
+         return x
+ 
+     cdef number_field(self):
+@@ -5443,8 +5443,8 @@ cdef class OrderElement_relative(NumberFieldElement_relative):
+         cdef OrderElement_relative x = <OrderElement_relative>t.__new__(t)
+         x._parent = self._parent
+         x._number_field = self._parent.number_field()
+-        x.__fld_numerator = self.__fld_numerator
+-        x.__fld_denominator = self.__fld_denominator
++        x._fld_numerator = self._fld_numerator
++        x._fld_denominator = self._fld_denominator
+         return x
+ 
+     def __invert__(self):
+diff --git a/src/sage/rings/number_field/number_field_element_quadratic.pyx b/src/sage/rings/number_field/number_field_element_quadratic.pyx
+index 0992e7cd527..c32f6aadd10 100644
+--- a/src/sage/rings/number_field/number_field_element_quadratic.pyx
++++ b/src/sage/rings/number_field/number_field_element_quadratic.pyx
+@@ -610,8 +610,8 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+         mpz_clear(tmp_mpz)
+ 
+         x._parent = <ParentWithBase>new_parent
+-        x.__fld_numerator, x.__fld_denominator = new_parent.polynomial_ntl()
+-        x.__denominator = elt_den
++        x._fld_numerator, x._fld_denominator = new_parent.polynomial_ntl()
++        x._denominator = elt_den
+         cdef ZZX_c result
+         cdef ZZ_c tmp
+         cdef int i
+@@ -621,7 +621,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+         for i from 0 <= i <= ZZX_deg(elt_num):
+             tmp = ZZX_coeff(elt_num, i)
+             ZZX_SetCoeff(result, i*rel, tmp)
+-        ZZX_rem(x.__numerator, result, _num.x)
++        ZZX_rem(x._numerator, result, _num.x)
+         (<NumberFieldElement_absolute>x)._reduce_c_()
+         return x
+ 
+@@ -1643,7 +1643,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+         return res
+ 
+ #################################################################################
+-# We must override everything that makes uses of self.__numerator/__denominator
++# We must override everything that makes uses of self._numerator/_denominator
+ #################################################################################
+ 
+     def __hash__(self):
+diff --git a/src/sage/rings/padics/CA_template.pxi b/src/sage/rings/padics/CA_template.pxi
+index a0a66c19621..d821b5c1576 100644
+--- a/src/sage/rings/padics/CA_template.pxi
++++ b/src/sage/rings/padics/CA_template.pxi
+@@ -1463,7 +1463,7 @@ cdef class pAdicCoercion_CA_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         ans._normalize()
+         return ans
+ 
+@@ -1516,7 +1516,7 @@ cdef class pAdicCoercion_CA_frac_field(RingHomomorphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+             pass
+         return ans
+ 
+@@ -1686,7 +1686,7 @@ cdef class pAdicConvert_CA_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 R = ans.value.base_ring()
+-                ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++                ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1741,7 +1741,7 @@ cdef class pAdicConvert_CA_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 R = ans.value.base_ring()
+-                ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++                ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/CR_template.pxi b/src/sage/rings/padics/CR_template.pxi
+index cb57bb2cb48..863c612587c 100644
+--- a/src/sage/rings/padics/CR_template.pxi
++++ b/src/sage/rings/padics/CR_template.pxi
+@@ -2184,7 +2184,7 @@ cdef class pAdicCoercion_CR_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -2241,7 +2241,7 @@ cdef class pAdicCoercion_CR_frac_field(RingHomomorphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     def section(self):
+@@ -2404,7 +2404,7 @@ cdef class pAdicConvert_CR_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -2463,7 +2463,7 @@ cdef class pAdicConvert_CR_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/FM_template.pxi b/src/sage/rings/padics/FM_template.pxi
+index ea7d4055660..f47200074ea 100644
+--- a/src/sage/rings/padics/FM_template.pxi
++++ b/src/sage/rings/padics/FM_template.pxi
+@@ -1227,7 +1227,7 @@ cdef class pAdicCoercion_FM_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1277,7 +1277,7 @@ cdef class pAdicCoercion_FM_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     def section(self):
+@@ -1435,7 +1435,7 @@ cdef class pAdicConvert_FM_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             R = ans.value.base_ring()
+-            ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++            ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1483,7 +1483,7 @@ cdef class pAdicConvert_FM_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             R = ans.value.base_ring()
+-            ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++            ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/FP_template.pxi b/src/sage/rings/padics/FP_template.pxi
+index 57ec619b278..c718c0a5f8d 100644
+--- a/src/sage/rings/padics/FP_template.pxi
++++ b/src/sage/rings/padics/FP_template.pxi
+@@ -1849,7 +1849,7 @@ cdef class pAdicCoercion_FP_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1903,7 +1903,7 @@ cdef class pAdicCoercion_FP_frac_field(RingHomomorphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     def section(self):
+@@ -2025,7 +2025,7 @@ cdef class pAdicConvert_FP_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -2081,7 +2081,7 @@ cdef class pAdicConvert_FP_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/pow_computer.pxd b/src/sage/rings/padics/pow_computer.pxd
+index 2a93e42254e..8766725882e 100644
+--- a/src/sage/rings/padics/pow_computer.pxd
++++ b/src/sage/rings/padics/pow_computer.pxd
+@@ -6,7 +6,7 @@ cdef class PowComputer_class(SageObject):
+     cdef Integer prime
+     cdef Integer p2 # floor(p/2)
+     cdef bint in_field
+-    cdef int __allocated
++    cdef int _allocated
+     cdef public object _prec_type
+ 
+     cdef long ram_prec_cap # = prec_cap * e
+diff --git a/src/sage/rings/padics/pow_computer.pyx b/src/sage/rings/padics/pow_computer.pyx
+index c2fa8031086..1c5bdf86897 100644
+--- a/src/sage/rings/padics/pow_computer.pyx
++++ b/src/sage/rings/padics/pow_computer.pyx
+@@ -65,7 +65,7 @@ cdef class PowComputer_class(SageObject):
+         sig_on()
+         mpz_init(self.temp_m)
+         sig_off()
+-        self.__allocated = 1
++        self._allocated = 1
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly=None, shift_seed=None):
+         """
+@@ -485,7 +485,7 @@ cdef class PowComputer_base(PowComputer_class):
+         finally:
+             sig_off()
+ 
+-        self.__allocated = 2
++        self._allocated = 2
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly=None, shift_seed=None):
+         """
+@@ -529,7 +529,7 @@ cdef class PowComputer_base(PowComputer_class):
+         """
+         cdef Py_ssize_t i
+ 
+-        if self.__allocated >= 2:
++        if self._allocated >= 2:
+             for i in range(self.cache_limit + 1):
+                 mpz_clear(self.small_powers[i])
+             mpz_clear(self.top_power)
+diff --git a/src/sage/rings/padics/pow_computer_flint.pyx b/src/sage/rings/padics/pow_computer_flint.pyx
+index 9f914defcc6..e521ea6e078 100644
+--- a/src/sage/rings/padics/pow_computer_flint.pyx
++++ b/src/sage/rings/padics/pow_computer_flint.pyx
+@@ -59,7 +59,7 @@ cdef class PowComputer_flint(PowComputer_class):
+         finally:
+             sig_off()
+ 
+-        self.__allocated = 4
++        self._allocated = 4
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly=None, shift_seed=None):
+         """
+@@ -87,7 +87,7 @@ cdef class PowComputer_flint(PowComputer_class):
+             sage: A = PowComputer_flint(5, 20, 20, 20, False)
+             sage: del A
+         """
+-        if self.__allocated >= 4:
++        if self._allocated >= 4:
+             fmpz_clear(self.fprime)
+             fmpz_clear(self.half_prime)
+             fmpz_clear(self._fpow_variable)
+@@ -208,7 +208,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+ 
+         """
+         cdef Polynomial_integer_dense_flint poly = _poly
+-        cdef long length = fmpz_poly_length(poly.__poly)
++        cdef long length = fmpz_poly_length(poly._poly)
+ 
+         cdef Py_ssize_t i
+ 
+@@ -251,7 +251,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         finally:
+             sig_off()
+ 
+-        self.__allocated = 8
++        self._allocated = 8
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, _poly, shift_seed=None):
+         """
+@@ -268,10 +268,10 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         PowComputer_flint.__init__(self, prime, cache_limit, prec_cap, ram_prec_cap, in_field, _poly, shift_seed)
+ 
+         cdef Polynomial_integer_dense_flint poly = _poly
+-        cdef long length = fmpz_poly_length(poly.__poly)
++        cdef long length = fmpz_poly_length(poly._poly)
+         self.deg = length - 1
+ 
+-        fmpz_poly_set(self.modulus, poly.__poly)
++        fmpz_poly_set(self.modulus, poly._poly)
+ 
+         cdef Py_ssize_t i
+         cdef fmpz* coeffs = self.modulus.coeffs
+@@ -296,7 +296,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         """
+         cdef Py_ssize_t i
+ 
+-        if self.__allocated >= 8:
++        if self._allocated >= 8:
+             fmpz_clear(self.q)
+             fmpz_poly_clear(self.modulus)
+             fmpz_poly_clear(self.powhelper_oneunit)
+@@ -427,9 +427,9 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         x = R.gen()
+         cdef Polynomial_integer_dense_flint ans = (<Polynomial_integer_dense_flint?>x)._new()
+         if _n is None:
+-            fmpz_poly_set(ans.__poly, self.modulus)
++            fmpz_poly_set(ans._poly, self.modulus)
+         else:
+-            fmpz_poly_set(ans.__poly, self.get_modulus(_n)[0])
++            fmpz_poly_set(ans._poly, self.get_modulus(_n)[0])
+         return ans
+ 
+     cdef _new_fmpz_poly(self, fmpz_poly_t value, var='x'):
+@@ -440,7 +440,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         R = ZZ[var]
+         x = R.gen()
+         cdef Polynomial_integer_dense_flint ans = (<Polynomial_integer_dense_flint?>x)._new()
+-        fmpz_poly_set(ans.__poly, value)
++        fmpz_poly_set(ans._poly, value)
+         return ans
+ 
+ cdef class PowComputer_flint_unram(PowComputer_flint_1step):
+@@ -501,7 +501,7 @@ cdef class PowComputer_flint_unram(PowComputer_flint_1step):
+         mpz_init(self.mpz_matmod)
+         sig_off()
+ 
+-        self.__allocated = 16
++        self._allocated = 16
+ 
+     def __dealloc__(self):
+         """
+@@ -515,7 +515,7 @@ cdef class PowComputer_flint_unram(PowComputer_flint_1step):
+             sage: del A
+ 
+         """
+-        if self.__allocated >= 16:
++        if self._allocated >= 16:
+             fmpz_clear(self.fmpz_ccmp)
+             fmpz_clear(self.fmpz_cval)
+             fmpz_clear(self.fmpz_cinv)
+diff --git a/src/sage/rings/padics/pow_computer_relative.pxd b/src/sage/rings/padics/pow_computer_relative.pxd
+index fc7d5b21f42..e0e5aa5600e 100644
+--- a/src/sage/rings/padics/pow_computer_relative.pxd
++++ b/src/sage/rings/padics/pow_computer_relative.pxd
+@@ -18,7 +18,7 @@ cdef class PowComputer_relative(PowComputer_class):
+     cdef Polynomial_generic_dense shift_rem
+     cdef Polynomial_generic_dense aliasing
+     # allow cached methods
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+     cdef unsigned long capdiv(self, unsigned long n)
+ 
+diff --git a/src/sage/rings/padics/pow_computer_relative.pyx b/src/sage/rings/padics/pow_computer_relative.pyx
+index 39051a681de..2253281bd35 100644
+--- a/src/sage/rings/padics/pow_computer_relative.pyx
++++ b/src/sage/rings/padics/pow_computer_relative.pyx
+@@ -69,7 +69,7 @@ cdef class PowComputer_relative(PowComputer_class):
+             sage: PC = PowComputer_relative_maker(3, 20, 20, 60, False, f, shift_seed, 'fixed-mod')
+ 
+         """
+-        self.__allocated = 4
++        self._allocated = 4
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly, shift_seed):
+         r"""
+diff --git a/src/sage/rings/polynomial/hilbert.pyx b/src/sage/rings/polynomial/hilbert.pyx
+index a1f70e0c983..d2abf325fd8 100644
+--- a/src/sage/rings/polynomial/hilbert.pyx
++++ b/src/sage/rings/polynomial/hilbert.pyx
+@@ -170,7 +170,7 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+     cdef int e
+     # First, the easiest cases:
+     if not D.Id: # The zero ideal
+-        fmpz_poly_set_coeff_si(fhs.__poly, 0, 1) # = PR(1)
++        fmpz_poly_set_coeff_si(fhs._poly, 0, 1) # = PR(1)
+         return True
+     cdef ETuple m = <ETuple>PyList_GET_ITEM(D.Id, len(D.Id)-1)
+     if m._nonzero == 0: # The one ideal
+@@ -183,18 +183,18 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+     if m._nonzero == 1 and m._data[1] == 1:
+         fmpz_poly_init(poly_tmp)
+         fmpz_poly_set_coeff_si(poly_tmp, 0, 1)
+-        fmpz_poly_set_coeff_si(fhs.__poly, 0, 1) # = PR(1)
++        fmpz_poly_set_coeff_si(fhs._poly, 0, 1) # = PR(1)
+         if w is None:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).unweighted_degree()
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         else:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).weighted_degree(w)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         fmpz_poly_clear(poly_tmp)
+         return True # PR.prod([(1-t**degree(m,w)) for m in D.Id])
+@@ -210,18 +210,18 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+         # The ideal is generated by some powers of single variables, i.e., it splits.
+         fmpz_poly_init(poly_tmp)
+         fmpz_poly_set_coeff_si(poly_tmp, 0, 1)
+-        fmpz_poly_set_coeff_si(fhs.__poly, 0, 1) # = PR(1)
++        fmpz_poly_set_coeff_si(fhs._poly, 0, 1) # = PR(1)
+         if w is None:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).unweighted_degree()
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         else:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).weighted_degree(w)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         fmpz_poly_clear(poly_tmp)
+         return True # PR.prod([(1-t**degree(m,w)) for m in D.Id])
+@@ -278,8 +278,8 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+                     fmpz_poly_mul(SecondSummand, SecondSummand, poly_tmp)
+                     fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         fmpz_poly_clear(poly_tmp)
+-        fmpz_poly_add(fhs.__poly, fhs.__poly, FirstSummand)
+-        fmpz_poly_add(fhs.__poly, fhs.__poly, SecondSummand)
++        fmpz_poly_add(fhs._poly, fhs._poly, FirstSummand)
++        fmpz_poly_add(fhs._poly, fhs._poly, SecondSummand)
+         fmpz_poly_clear(FirstSummand)
+         fmpz_poly_clear(SecondSummand)
+         return True
+@@ -532,11 +532,11 @@ def first_hilbert_series(I, grading=None, return_grading=False):
+                 if AN.Back.Right is None:
+                     AN = AN.Back
+                     #~ fhs *= AN.LMult
+-                    fmpz_poly_mul(fhs.__poly, fhs.__poly, AN.LMult)
++                    fmpz_poly_mul(fhs._poly, fhs._poly, AN.LMult)
+                     got_result = True
+                 else:
+-                    fmpz_poly_set(AN.Back.LeftFHS, fhs.__poly)
+-                    fmpz_poly_set_si(fhs.__poly, 0)
++                    fmpz_poly_set(AN.Back.LeftFHS, fhs._poly)
++                    fmpz_poly_set_si(fhs._poly, 0)
+                     AN = AN.Back.Right
+                     AN.Back.Left = None
+                     got_result = HilbertBaseCase(fhs, AN, w)
+@@ -545,8 +545,8 @@ def first_hilbert_series(I, grading=None, return_grading=False):
+                 AN.Right = None
+                 #~ fhs = AN.LMult*AN.LeftFHS + AN.RMult*fhs
+                 fmpz_poly_mul(AN.LMult, AN.LMult, AN.LeftFHS)
+-                fmpz_poly_mul(AN.RMult, AN.RMult, fhs.__poly)
+-                fmpz_poly_add(fhs.__poly, AN.LMult, AN.RMult)
++                fmpz_poly_mul(AN.RMult, AN.RMult, fhs._poly)
++                fmpz_poly_add(fhs._poly, AN.LMult, AN.RMult)
+                 got_result = True
+ 
+ def hilbert_poincare_series(I, grading=None):
+diff --git a/src/sage/rings/polynomial/laurent_polynomial.pxd b/src/sage/rings/polynomial/laurent_polynomial.pxd
+index 3648d6d1ed1..8e9107aeb47 100644
+--- a/src/sage/rings/polynomial/laurent_polynomial.pxd
++++ b/src/sage/rings/polynomial/laurent_polynomial.pxd
+@@ -12,6 +12,6 @@ cdef class LaurentPolynomial(CommutativeAlgebraElement):
+ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+     cdef ModuleElement __u
+     cdef long __n
+-    cpdef __normalize(self)
++    cpdef _normalize(self)
+     cpdef _unsafe_mutate(self, i, value)
+ 
+diff --git a/src/sage/rings/polynomial/laurent_polynomial.pyx b/src/sage/rings/polynomial/laurent_polynomial.pyx
+index 4be246c6688..cd79996eed7 100644
+--- a/src/sage/rings/polynomial/laurent_polynomial.pyx
++++ b/src/sage/rings/polynomial/laurent_polynomial.pyx
+@@ -366,7 +366,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         # self is that t^n * u:
+         self.__u = f
+         self.__n = n
+-        self.__normalize()
++        self._normalize()
+ 
+     def __reduce__(self):
+         """
+@@ -531,7 +531,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+             u = u.map_coefficients(base_map)
+         return codomain(u(x) * x**self.__n)
+ 
+-    cpdef __normalize(self):
++    cpdef _normalize(self):
+         r"""
+         A Laurent series is a pair `(u(t), n)`, where either `u = 0`
+         (to some precision) or `u` is a unit. This pair corresponds to
+@@ -763,7 +763,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+             ret = <LaurentPolynomial_univariate> self._new_c()
+             ret.__u = f
+             ret.__n = self.__n
+-            ret.__normalize()
++            ret._normalize()
+             return ret
+ 
+         return self.__u[i - self.__n]
+@@ -919,7 +919,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+                 R = self._parent.base_ring()
+                 coeffs = [value] + [R.zero() for _ in range(1,-j)] + self.__u.list()
+                 self.__u = self.__u._parent(coeffs)
+-        self.__normalize()
++        self._normalize()
+ 
+     cpdef _add_(self, right_m):
+         """
+@@ -972,7 +972,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (f1 + f2)
+         ret.__n = m
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     cpdef _sub_(self, right_m):
+@@ -1012,7 +1012,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (f1 - f2)
+         ret.__n = m
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def degree(self):
+@@ -1063,7 +1063,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (self.__u * right.__u)
+         ret.__n = self.__n + right.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     cpdef _rmul_(self, Element c):
+@@ -1079,7 +1079,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self.__u._rmul_(c)
+         ret.__n = self.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     cpdef _lmul_(self, Element c):
+@@ -1095,7 +1095,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self.__u._lmul_(c)
+         ret.__n = self.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def is_monomial(self):
+@@ -1175,7 +1175,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (self.__u // right.__u)
+         ret.__n = self.__n - right.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def shift(self, k):
+@@ -1287,7 +1287,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+             if self.__u.is_unit():
+                 ret.__u = self.__u.inverse_of_unit()
+                 ret.__n = -self.__n
+-                ret.__normalize()
++                ret._normalize()
+                 return ret
+             # Enlarge the ring so we can divide by the coefficient
+             R = self._parent.base_ring().fraction_field()
+@@ -1362,7 +1362,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = self.__u.gcd(b.__u)
+         ret.__n = min(self.__n, b.__n)
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     @coerce_binop
+@@ -1408,11 +1408,11 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ql = <LaurentPolynomial_univariate> self._new_c()
+         ql.__u = <ModuleElement> q
+         ql.__n = self.__n - right.__n
+-        ql.__normalize()
++        ql._normalize()
+         qr = <LaurentPolynomial_univariate> self._new_c()
+         qr.__u = <ModuleElement> r
+         qr.__n = self.__n
+-        qr.__normalize()
++        qr._normalize()
+         return ql, qr
+ 
+     cpdef _richcmp_(self, right_r, int op):
+@@ -1519,7 +1519,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self.__u.truncate(n - self.__n)
+         ret.__n = self.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def variable_name(self):
+@@ -1777,7 +1777,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+                 ret = <LaurentPolynomial_univariate> self._new_c()
+                 ret.__u = <ModuleElement> self._parent._R(u)
+                 ret.__n = self.__n
+-                ret.__normalize()
++                ret._normalize()
+                 return ret
+             except AttributeError:
+                 raise ValueError('cannot differentiate with respect to {}'.format(var))
+@@ -1792,7 +1792,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self._parent._R(a)
+         ret.__n = self.__n - 1
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def integral(self):
+@@ -1857,7 +1857,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> u
+         ret.__n = n + 1
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def __call__(self, *x, **kwds):
+@@ -1919,14 +1919,14 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         u = <LaurentPolynomial_univariate> self._new_c()
+         u.__u = pf.unit()
+         u.__n = self.__n
+-        u.__normalize()
++        u._normalize()
+ 
+         f = []
+         for t in pf:
+             d = <LaurentPolynomial_univariate> self._new_c()
+             d.__u = t[0]
+             d.__n = 0
+-            d.__normalize()
++            d._normalize()
+             if d.is_unit():
+                 u *= d ** t[1]
+             else:
+diff --git a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx
+index d796b7f8169..83c79c39843 100644
+--- a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx
++++ b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx
+@@ -375,7 +375,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+             ...
+             NotImplementedError: polynomials in -1 variables are not supported in Singular
+         """
+-        self.__ngens = n
++        self._ngens = n
+         self._ring = singular_ring_new(base_ring, n, names, order)
+         self._zero_element = new_MP(self, NULL)
+         cdef MPolynomial_libsingular one = new_MP(self, p_ISet(1, self._ring))
+@@ -1019,7 +1019,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+             Multivariate Polynomial Ring in x, y over Rational Field
+         """
+         varstr = ", ".join(char_to_str(rRingVar(i,self._ring))
+-                           for i in range(self.__ngens))
++                           for i in range(self._ngens))
+         return "Multivariate Polynomial Ring in %s over %s" % (varstr, self.base_ring())
+ 
+     def ngens(self):
+@@ -1037,7 +1037,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+             sage: P.ngens()                                                             # needs sage.rings.finite_rings
+             1000
+         """
+-        return int(self.__ngens)
++        return int(self._ngens)
+ 
+     def gen(self, int n=0):
+         """
+@@ -1065,7 +1065,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+         cdef poly *_p
+         cdef ring *_ring = self._ring
+ 
+-        if n < 0 or n >= self.__ngens:
++        if n < 0 or n >= self._ngens:
+             raise ValueError("Generator not defined.")
+ 
+         rChangeCurrRing(_ring)
+@@ -1494,7 +1494,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+         return unpickle_MPolynomialRing_libsingular, \
+             (self.base_ring(), self.variable_names(), self.term_order())
+ 
+-    def __temporarily_change_names(self, names, latex_names):
++    def _temporarily_change_names(self, names, latex_names):
+         """
+         This is used by the variable names context manager.
+ 
+diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd b/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd
+index fc81cf6d298..eb6f8b70917 100644
+--- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd
++++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd
+@@ -2,8 +2,8 @@ cimport sage.rings.ring
+ from sage.structure.parent cimport Parent
+ 
+ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+-    cdef object __ngens
+-    cdef object __term_order
++    cdef object _ngens
++    cdef object _term_order
+     cdef public object _has_singular
+     cdef public object _magma_gens
+     cdef public dict _magma_cache
+diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx
+index 1d3fbc60944..c8f66508cc2 100644
+--- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx
++++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx
+@@ -80,8 +80,8 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+             raise ValueError("Multivariate Polynomial Rings must "
+                              "have more than 0 variables.")
+         order = TermOrder(order, n)
+-        self.__ngens = n
+-        self.__term_order = order
++        self._ngens = n
++        self._term_order = order
+         self._has_singular = False  # cannot convert to Singular by default
+         self._magma_cache = {}
+         # Ring.__init__ already does assign the names.
+@@ -639,12 +639,12 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         lft = <MPolynomialRing_base>left
+         other = <MPolynomialRing_base>right
+ 
+-        lx = (lft.base_ring(), lft.__ngens,
++        lx = (lft.base_ring(), lft._ngens,
+               lft.variable_names(),
+-              lft.__term_order)
+-        rx = (other.base_ring(), other.__ngens,
++              lft._term_order)
++        rx = (other.base_ring(), other._ngens,
+               other.variable_names(),
+-              other.__term_order)
++              other._term_order)
+         return richcmp(lx, rx, op)
+ 
+     def _repr_(self):
+@@ -849,7 +849,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         return False
+ 
+     def term_order(self):
+-        return self.__term_order
++        return self._term_order
+ 
+     def characteristic(self):
+         """
+@@ -867,7 +867,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         return self.base_ring().characteristic()
+ 
+     def gen(self, n=0):
+-        if n < 0 or n >= self.__ngens:
++        if n < 0 or n >= self._ngens:
+             raise ValueError("Generator not defined.")
+         return self._gens[int(n)]
+ 
+@@ -927,7 +927,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         return self.base_ring().krull_dimension() + self.ngens()
+ 
+     def ngens(self):
+-        return self.__ngens
++        return self._ngens
+ 
+     def _monomial_order_function(self):
+         raise NotImplementedError
+diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pxd b/src/sage/rings/polynomial/ore_polynomial_element.pxd
+index 3a3fe0a0d54..aa36112ab90 100644
+--- a/src/sage/rings/polynomial/ore_polynomial_element.pxd
++++ b/src/sage/rings/polynomial/ore_polynomial_element.pxd
+@@ -33,7 +33,7 @@ cdef void lmul_gen(list A, Morphism m, d)
+ cdef class OrePolynomial_generic_dense(OrePolynomial):
+     cdef list _coeffs
+ 
+-    cdef void __normalize(self)
++    cdef void _normalize(self)
+     cpdef _add_(self, other)
+     cdef list _mul_list(self, list A)
+     cpdef _mul_(self, other)
+diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pyx b/src/sage/rings/polynomial/ore_polynomial_element.pyx
+index d67c63b6be8..be154ba8b1a 100644
+--- a/src/sage/rings/polynomial/ore_polynomial_element.pyx
++++ b/src/sage/rings/polynomial/ore_polynomial_element.pyx
+@@ -2269,7 +2269,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+         if isinstance(x, list):
+             if check:
+                 self._coeffs = [R(t) for t in x]
+-                self.__normalize()
++                self._normalize()
+             else:
+                 self._coeffs = x
+             return
+@@ -2288,7 +2288,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+             else:
+                 self._coeffs = [R(a, **kwds) for a in x.list()]
+                 if check:
+-                    self.__normalize()
++                    self._normalize()
+                 return
+ 
+         elif isinstance(x, int) and x == 0:
+@@ -2302,7 +2302,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+             x = [x]
+         if check:
+             self._coeffs = [R(z, **kwds) for z in x]
+-            self.__normalize()
++            self._normalize()
+         else:
+             self._coeffs = x
+ 
+@@ -2377,10 +2377,10 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+         f._parent = P
+         f._coeffs = coeffs
+         if check:
+-            f.__normalize()
++            f._normalize()
+         return f
+ 
+-    cdef void __normalize(self):
++    cdef void _normalize(self):
+         r"""
+         Remove higher order `0`-coefficients from the representation of ``self``.
+ 
+diff --git a/src/sage/rings/polynomial/pbori/pbori.pyx b/src/sage/rings/polynomial/pbori/pbori.pyx
+index 07cc696477a..314196faa14 100644
+--- a/src/sage/rings/polynomial/pbori/pbori.pyx
++++ b/src/sage/rings/polynomial/pbori/pbori.pyx
+@@ -547,7 +547,7 @@ cdef class BooleanPolynomialRing(BooleanPolynomialRing_base):
+         """
+         return tuple(new_BP_from_PBVar(self,
+                                        self._pbring.variable(self.pbind[i]))
+-                     for i in range(self.__ngens))
++                     for i in range(self._ngens))
+ 
+     def change_ring(self, base_ring=None, names=None, order=None):
+         """
+diff --git a/src/sage/rings/polynomial/plural.pxd b/src/sage/rings/polynomial/plural.pxd
+index 41db2a144e7..d3a46f6aa0d 100644
+--- a/src/sage/rings/polynomial/plural.pxd
++++ b/src/sage/rings/polynomial/plural.pxd
+@@ -13,10 +13,10 @@ cdef extern from *:
+     ctypedef long Py_hash_t
+ 
+ cdef class NCPolynomialRing_plural(Ring):
+-    cdef object __ngens
++    cdef object _ngens
+     cdef object _c
+     cdef object _d
+-    cdef object __term_order
++    cdef object _term_order
+     cdef public object _has_singular
+     cdef public object _magma_gens, _magma_cache
+ 
+diff --git a/src/sage/rings/polynomial/plural.pyx b/src/sage/rings/polynomial/plural.pyx
+index a647d68e08d..bc432611c89 100644
+--- a/src/sage/rings/polynomial/plural.pyx
++++ b/src/sage/rings/polynomial/plural.pyx
+@@ -336,8 +336,8 @@ cdef class NCPolynomialRing_plural(Ring):
+         self._ring = singular_ring_reference(rw._ring)
+         self._ring.ShortOut = 0
+ 
+-        self.__ngens = n
+-        self.__term_order = order
++        self._ngens = n
++        self._term_order = order
+ 
+         Ring.__init__(self, base_ring, names, category=category)
+         self._populate_coercion_lists_()
+@@ -673,7 +673,7 @@ cdef class NCPolynomialRing_plural(Ring):
+             sage: P.term_order()
+             Degree reverse lexicographic term order
+         """
+-        return self.__term_order
++        return self._term_order
+ 
+     def is_commutative(self):
+         """
+@@ -727,7 +727,7 @@ cdef class NCPolynomialRing_plural(Ring):
+         from sage.repl.rich_output.backend_base import BackendBase
+         from sage.repl.display.pretty_print import SagePrettyPrinter
+         varstr = ", ".join(char_to_str(rRingVar(i, self._ring))
+-                           for i in range(self.__ngens))
++                           for i in range(self._ngens))
+         backend = BackendBase()
+         relations = backend._apply_pretty_printer(SagePrettyPrinter,
+                                                   self.relations())
+@@ -830,7 +830,7 @@ cdef class NCPolynomialRing_plural(Ring):
+             sage: P.ngens()
+             3
+         """
+-        return int(self.__ngens)
++        return int(self._ngens)
+ 
+     def gen(self, int n=0):
+         """
+@@ -857,7 +857,7 @@ cdef class NCPolynomialRing_plural(Ring):
+         cdef poly *_p
+         cdef ring *_ring = self._ring
+ 
+-        if n < 0 or n >= self.__ngens:
++        if n < 0 or n >= self._ngens:
+             raise ValueError("Generator not defined.")
+ 
+         rChangeCurrRing(_ring)
+@@ -2352,7 +2352,7 @@ cdef class NCPolynomial_plural(RingElement):
+             except TypeError:
+                 x = (x,)
+ 
+-        if len(x) != (<NCPolynomialRing_plural>self._parent).__ngens:
++        if len(x) != (<NCPolynomialRing_plural>self._parent)._ngens:
+             raise TypeError("x must have length self.ngens()")
+ 
+         m = p_ISet(1,r)
+@@ -2890,8 +2890,8 @@ cpdef MPolynomialRing_libsingular new_CRing(RingWrap rw, base_ring):
+ 
+     self._ring.ShortOut = 0
+ 
+-    self.__ngens = rw.ngens()
+-    self.__term_order =  TermOrder(rw.ordering_string(), force=True)
++    self._ngens = rw.ngens()
++    self._term_order =  TermOrder(rw.ordering_string(), force=True)
+ 
+     ParentWithGens.__init__(self, base_ring, tuple(rw.var_names()),
+                             normalize=False)
+@@ -2962,8 +2962,8 @@ cpdef NCPolynomialRing_plural new_NRing(RingWrap rw, base_ring):
+ 
+     self._ring.ShortOut = 0
+ 
+-    self.__ngens = rw.ngens()
+-    self.__term_order =  TermOrder(rw.ordering_string(), force=True)
++    self._ngens = rw.ngens()
++    self._term_order =  TermOrder(rw.ordering_string(), force=True)
+ 
+     ParentWithGens.__init__(self, base_ring, rw.var_names())
+ #    self._populate_coercion_lists_()  # ???
+diff --git a/src/sage/rings/polynomial/polynomial_complex_arb.pxd b/src/sage/rings/polynomial/polynomial_complex_arb.pxd
+index aa4e2a1c0dc..e54d85e961b 100644
+--- a/src/sage/rings/polynomial/polynomial_complex_arb.pxd
++++ b/src/sage/rings/polynomial/polynomial_complex_arb.pxd
+@@ -2,5 +2,5 @@ from sage.libs.arb.acb_poly cimport *
+ from sage.rings.polynomial.polynomial_element cimport Polynomial
+ 
+ cdef class Polynomial_complex_arb(Polynomial):
+-    cdef acb_poly_struct[1] __poly # https://github.com/cython/cython/issues/1984
++    cdef acb_poly_struct[1] _poly # https://github.com/cython/cython/issues/1984
+     cdef Polynomial_complex_arb _new(self)
+diff --git a/src/sage/rings/polynomial/polynomial_complex_arb.pyx b/src/sage/rings/polynomial/polynomial_complex_arb.pyx
+index e51268b4b54..57c1a52ede4 100644
+--- a/src/sage/rings/polynomial/polynomial_complex_arb.pyx
++++ b/src/sage/rings/polynomial/polynomial_complex_arb.pyx
+@@ -75,7 +75,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: ComplexBallField(2)['y']()
+             0
+         """
+-        acb_poly_init(self.__poly)
++        acb_poly_init(self._poly)
+ 
+     def __dealloc__(self):
+         r"""
+@@ -84,7 +84,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: pol = CBF['x']()
+             sage: del pol
+         """
+-        acb_poly_clear(self.__poly)
++        acb_poly_clear(self._poly)
+ 
+     cdef Polynomial_complex_arb _new(self):
+         r"""
+@@ -140,49 +140,49 @@ cdef class Polynomial_complex_arb(Polynomial):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+ 
+         if is_gen:
+-            acb_poly_set_coeff_si(self.__poly, 1, 1)
++            acb_poly_set_coeff_si(self._poly, 1, 1)
+         elif x is None:
+-            acb_poly_zero(self.__poly)
++            acb_poly_zero(self._poly)
+         elif isinstance(x, Polynomial_complex_arb):
+-            acb_poly_set(self.__poly, (<Polynomial_complex_arb> x).__poly)
++            acb_poly_set(self._poly, (<Polynomial_complex_arb> x)._poly)
+         elif isinstance(x, ComplexBall):
+-            acb_poly_set_coeff_acb(self.__poly, 0, (<ComplexBall> x).value)
++            acb_poly_set_coeff_acb(self._poly, 0, (<ComplexBall> x).value)
+         else:
+             Coeff = parent.base_ring()
+             if isinstance(x, list):
+                 lst = <list> x
+                 length = len(lst)
+-                sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                 for i in range(length):
+                     ball = Coeff(lst[i])
+-                    acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                    acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             elif isinstance(x, tuple):
+                 tpl = <tuple> x
+                 length = len(tpl)
+-                sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                 for i in range(length):
+                     ball = Coeff(tpl[i])
+-                    acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                    acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             elif isinstance(x, Polynomial):
+                 pol = <Polynomial> x
+                 length = pol.degree() + 1
+-                sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                 for i in range(length):
+                     ball = Coeff(pol.get_unsafe(i))
+-                    acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                    acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             elif isinstance(x, dict):
+                 dct = <dict> x
+                 if len(dct) == 0:
+-                    acb_poly_zero(self.__poly)
++                    acb_poly_zero(self._poly)
+                 else:
+                     length = max(int(i) for i in dct) + 1
+-                    sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                    sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                     for i, c in dct.iteritems():
+                         ball = Coeff(c)
+-                        acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                        acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             else:
+                 ball = Coeff(x)
+-                acb_poly_set_coeff_acb(self.__poly, 0, ball.value)
++                acb_poly_set_coeff_acb(self._poly, 0, ball.value)
+ 
+     def __reduce__(self):
+         r"""
+@@ -219,12 +219,12 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: Pol([1, 0, 0, 0]).degree()
+             0
+         """
+-        return smallInteger(acb_poly_degree(self.__poly))
++        return smallInteger(acb_poly_degree(self._poly))
+ 
+     cdef get_unsafe(self, Py_ssize_t n):
+         cdef ComplexBall res = ComplexBall.__new__(ComplexBall)
+         res._parent = self._parent._base
+-        acb_poly_get_coeff_acb(res.value, self.__poly, n)
++        acb_poly_get_coeff_acb(res.value, self._poly, n)
+         return res
+ 
+     cpdef list list(self, bint copy=True):
+@@ -241,7 +241,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: Pol([0, 1, RBF(0, rad=.1), 0]).list()
+             [0, 1.000000000000000, [+/- 0.101]]
+         """
+-        cdef unsigned long length = acb_poly_length(self.__poly)
++        cdef unsigned long length = acb_poly_length(self._poly)
+         return [self.get_unsafe(n) for n in range(length)]
+ 
+     def __bool__(self):
+@@ -257,7 +257,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: bool(z)
+             True
+         """
+-        return acb_poly_length(self.__poly)
++        return acb_poly_length(self._poly)
+ 
+     # Ring and Euclidean arithmetic
+ 
+@@ -274,9 +274,9 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+         acb_poly_add(
+-                res.__poly,
+-                self.__poly,
+-                (<Polynomial_complex_arb> other).__poly,
++                res._poly,
++                self._poly,
++                (<Polynomial_complex_arb> other)._poly,
+                 prec(self))
+         sig_off()
+         return res
+@@ -293,7 +293,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         """
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_neg(res.__poly, self.__poly)
++        acb_poly_neg(res._poly, self._poly)
+         sig_off()
+         return res
+ 
+@@ -310,9 +310,9 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+         acb_poly_sub(
+-                res.__poly,
+-                self.__poly,
+-                (<Polynomial_complex_arb> other).__poly,
++                res._poly,
++                self._poly,
++                (<Polynomial_complex_arb> other)._poly,
+                 prec(self))
+         sig_off()
+         return res
+@@ -331,9 +331,9 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+         acb_poly_mul(
+-                res.__poly,
+-                self.__poly,
+-                (<Polynomial_complex_arb> other).__poly,
++                res._poly,
++                self._poly,
++                (<Polynomial_complex_arb> other)._poly,
+                 prec(self))
+         sig_off()
+         return res
+@@ -354,7 +354,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         """
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_scalar_mul(res.__poly, self.__poly, (<ComplexBall> a).value, prec(self))
++        acb_poly_scalar_mul(res._poly, self._poly, (<ComplexBall> a).value, prec(self))
+         sig_off()
+         return res
+ 
+@@ -409,8 +409,8 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb quo = self._new()
+         cdef Polynomial_complex_arb rem = self._new()
+         sig_on()
+-        cdef bint success = acb_poly_divrem(quo.__poly, rem.__poly, self.__poly,
+-                div.__poly, prec(self))
++        cdef bint success = acb_poly_divrem(quo._poly, rem._poly, self._poly,
++                div._poly, prec(self))
+         sig_off()
+         if success:
+             return quo, rem
+@@ -445,15 +445,15 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_set(res.__poly, self.__poly)
+-        acb_poly_truncate(res.__poly, n)
++        acb_poly_set(res._poly, self._poly)
++        acb_poly_truncate(res._poly, n)
+         sig_off()
+         return res
+ 
+     cdef _inplace_truncate(self, long n):
+         if n < 0:
+             n = 0
+-        acb_poly_truncate(self.__poly, n)
++        acb_poly_truncate(self._poly, n)
+         return self
+ 
+     def __lshift__(val, n):
+@@ -485,7 +485,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb self = (<Polynomial_complex_arb> val)
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_shift_left(res.__poly, self.__poly, n)
++        acb_poly_shift_left(res._poly, self._poly, n)
+         sig_off()
+         return res
+ 
+@@ -518,7 +518,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb self = (<Polynomial_complex_arb> val)
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_shift_right(res.__poly, self.__poly, n)
++        acb_poly_shift_right(res._poly, self._poly, n)
+         sig_off()
+         return res
+ 
+@@ -548,7 +548,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_mullow(res.__poly, self.__poly, my_other.__poly, n, prec(self))
++        acb_poly_mullow(res._poly, self._poly, my_other._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -576,7 +576,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_inv_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_inv_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -612,7 +612,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_pow_ui_trunc_binexp(res.__poly, self.__poly, expo, n, prec(self))
++        acb_poly_pow_ui_trunc_binexp(res._poly, self._poly, expo, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -648,7 +648,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_log_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_log_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -672,7 +672,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_exp_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_exp_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -697,7 +697,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_sqrt_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_sqrt_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -716,7 +716,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_gamma_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_gamma_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -735,7 +735,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_lgamma_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_lgamma_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -754,7 +754,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_rgamma_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_rgamma_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -784,7 +784,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_lambertw_series(res.__poly, self.__poly, _branch, 0, n, prec(self))
++        acb_poly_lambertw_series(res._poly, self._poly, _branch, 0, n, prec(self))
+         sig_off()
+         fmpz_clear(_branch)
+         return res
+@@ -814,7 +814,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef ComplexBall _a = <ComplexBall> (self._parent._base.coerce(a))
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_zeta_series(res.__poly, self.__poly, _a.value, deflate, n, prec(self))
++        acb_poly_zeta_series(res._poly, self._poly, _a.value, deflate, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -846,24 +846,24 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         cdef acb_poly_t self_ts, other_ts
+         cdef acb_ptr cc
+-        if acb_poly_length(other1.__poly) > 0:
+-            cc = acb_poly_get_coeff_ptr(other1.__poly, 0)
++        if acb_poly_length(other1._poly) > 0:
++            cc = acb_poly_get_coeff_ptr(other1._poly, 0)
+             if not acb_is_zero(cc):
+                 sig_on()
+                 try:
+                     acb_poly_init(self_ts)
+                     acb_poly_init(other_ts)
+-                    acb_poly_taylor_shift(self_ts, self.__poly, cc, prec(self))
+-                    acb_poly_set(other_ts, other1.__poly)
++                    acb_poly_taylor_shift(self_ts, self._poly, cc, prec(self))
++                    acb_poly_set(other_ts, other1._poly)
+                     acb_zero(acb_poly_get_coeff_ptr(other_ts, 0))
+-                    acb_poly_compose_series(res.__poly, self_ts, other_ts, n, prec(self))
++                    acb_poly_compose_series(res._poly, self_ts, other_ts, n, prec(self))
+                 finally:
+                     acb_poly_clear(other_ts)
+                     acb_poly_clear(self_ts)
+                     sig_off()
+                 return res
+         sig_on()
+-        acb_poly_compose_series(res.__poly, self.__poly, other1.__poly, n, prec(self))
++        acb_poly_compose_series(res._poly, self._poly, other1._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -895,12 +895,12 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         if n < 0:
+             n = 0
+-        if not acb_is_zero(acb_poly_get_coeff_ptr(self.__poly, 0)):
++        if not acb_is_zero(acb_poly_get_coeff_ptr(self._poly, 0)):
+             raise ValueError("the constant coefficient must be zero")
+-        if acb_contains_zero(acb_poly_get_coeff_ptr(self.__poly, 1)):
++        if acb_contains_zero(acb_poly_get_coeff_ptr(self._poly, 1)):
+             raise ValueError("the linear term must be nonzero")
+         sig_on()
+-        acb_poly_revert_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_revert_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -938,15 +938,15 @@ cdef class Polynomial_complex_arb(Polynomial):
+                 ball = ComplexBall.__new__(ComplexBall)
+                 ball._parent = self._parent._base
+                 sig_on()
+-                acb_poly_evaluate(ball.value, self.__poly,
++                acb_poly_evaluate(ball.value, self._poly,
+                         (<ComplexBall> point).value, prec(self))
+                 sig_off()
+                 return ball
+             elif isinstance(point, Polynomial_complex_arb):
+                 poly = (<Polynomial_complex_arb> point)._new()
+                 sig_on()
+-                acb_poly_compose(poly.__poly, self.__poly,
+-                        (<Polynomial_complex_arb> point).__poly, prec(self))
++                acb_poly_compose(poly._poly, self._poly,
++                        (<Polynomial_complex_arb> point)._poly, prec(self))
+                 sig_off()
+                 return poly
+             # TODO: perhaps add more special cases, e.g. for real ball,
+diff --git a/src/sage/rings/polynomial/polynomial_element.pxd b/src/sage/rings/polynomial/polynomial_element.pxd
+index 083f506b222..5dcbf4597d0 100644
+--- a/src/sage/rings/polynomial/polynomial_element.pxd
++++ b/src/sage/rings/polynomial/polynomial_element.pxd
+@@ -45,12 +45,12 @@ cdef class Polynomial(CommutativePolynomial):
+     cpdef _mul_(self, right)
+     cpdef _floordiv_(self, right)
+ 
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+ cdef class Polynomial_generic_dense(Polynomial):
+     cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P)
+-    cdef list __coeffs
+-    cdef int __normalize(self) except -1
++    cdef list _coeffs
++    cdef int _normalize(self) except -1
+     cpdef list list(self, bint copy=*)
+ 
+ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+diff --git a/src/sage/rings/polynomial/polynomial_element.pyx b/src/sage/rings/polynomial/polynomial_element.pyx
+index 4d4b9dd10f5..d1c802835ae 100644
+--- a/src/sage/rings/polynomial/polynomial_element.pyx
++++ b/src/sage/rings/polynomial/polynomial_element.pyx
+@@ -9800,7 +9800,7 @@ cdef class Polynomial(CommutativePolynomial):
+             0
+         """
+         # __getitem__ already returns a polynomial!!
+-        # We must not have check=False, since 0 must not have __coeffs = [0].
++        # We must not have check=False, since 0 must not have _coeffs = [0].
+         return <Polynomial>self._parent(self[:n])#, check=False)
+ 
+     cdef _inplace_truncate(self, long prec):
+@@ -11541,16 +11541,16 @@ cdef class Polynomial_generic_dense(Polynomial):
+     def __init__(self, parent, x=None, int check=1, is_gen=False, int construct=0, **kwds):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+         if x is None:
+-            self.__coeffs = []
++            self._coeffs = []
+             return
+ 
+         R = parent.base_ring()
+         if isinstance(x, (list, tuple)):
+             if check:
+-                self.__coeffs = [R(t) for t in x]
+-                self.__normalize()
++                self._coeffs = [R(t) for t in x]
++                self._normalize()
+             else:
+-                self.__coeffs = x
++                self._coeffs = x
+             return
+ 
+         if sage.rings.fraction_field_element.is_FractionFieldElement(x):
+@@ -11565,19 +11565,19 @@ cdef class Polynomial_generic_dense(Polynomial):
+             elif R.has_coerce_map_from((<Element>x)._parent):# is R or (<Element>x)._parent == R:
+                 try:
+                     if x.is_zero():
+-                        self.__coeffs = []
++                        self._coeffs = []
+                         return
+                 except (AttributeError, TypeError):
+                     pass
+                 x = [x]
+             else:
+-                self.__coeffs = [R(a, **kwds) for a in x.list(copy=False)]
++                self._coeffs = [R(a, **kwds) for a in x.list(copy=False)]
+                 if check:
+-                    self.__normalize()
++                    self._normalize()
+                 return
+ 
+         elif isinstance(x, int) and x == 0:
+-            self.__coeffs = []
++            self._coeffs = []
+             return
+ 
+         elif isinstance(x, dict):
+@@ -11593,16 +11593,16 @@ cdef class Polynomial_generic_dense(Polynomial):
+ #            else:
+ #                x = []    # zero polynomial
+         if check:
+-            self.__coeffs = [R(z, **kwds) for z in x]
+-            self.__normalize()
++            self._coeffs = [R(z, **kwds) for z in x]
++            self._normalize()
+         else:
+-            self.__coeffs = x
++            self._coeffs = x
+ 
+     cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P):
+         cdef type t = type(self)
+         cdef Polynomial_generic_dense f = <Polynomial_generic_dense>t.__new__(t)
+         f._parent = P
+-        f.__coeffs = coeffs
++        f._coeffs = coeffs
+         return f
+ 
+     cpdef Polynomial _new_constant_poly(self, a, Parent P):
+@@ -11644,10 +11644,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: type(f)
+             <class 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense'>
+         """
+-        return make_generic_polynomial, (self._parent, self.__coeffs)
++        return make_generic_polynomial, (self._parent, self._coeffs)
+ 
+     def __bool__(self):
+-        return bool(self.__coeffs)
++        return bool(self._coeffs)
+ 
+     cpdef bint is_term(self) except -1:
+         """
+@@ -11667,10 +11667,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: (1 + 3*x^5).is_term()
+             False
+         """
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return False
+ 
+-        for c in self.__coeffs[:-1]:
++        for c in self._coeffs[:-1]:
+             if c:
+                 return False
+         return True
+@@ -11682,9 +11682,9 @@ cdef class Polynomial_generic_dense(Polynomial):
+         Return the product ``self * term``, where ``term`` is a polynomial
+         with a single term.
+         """
+-        cdef Py_ssize_t d = len( (<Polynomial_generic_dense> term).__coeffs ) - 1
++        cdef Py_ssize_t d = len( (<Polynomial_generic_dense> term)._coeffs ) - 1
+         cdef Py_ssize_t i
+-        cdef list x = self.__coeffs
++        cdef list x = self._coeffs
+         cdef Py_ssize_t ell = len(x)
+         c = term.get_unsafe(d)
+         cdef list v = [self.base_ring().zero()] * (d + ell)
+@@ -11697,10 +11697,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+         cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
+         #if not v[len(v)-1]:
+         # "normalize" checks this anyway...
+-        res.__normalize()
++        res._normalize()
+         return res
+ 
+-    cdef int __normalize(self) except -1:
++    cdef int _normalize(self) except -1:
+         """
+         TESTS:
+ 
+@@ -11718,7 +11718,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+             ...
+             NotImplementedError: cannot check whether number is non-zero
+         """
+-        cdef list x = self.__coeffs
++        cdef list x = self._coeffs
+         cdef Py_ssize_t n = len(x) - 1
+         while n >= 0 and not x[n]:
+             del x[n]
+@@ -11747,7 +11747,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: f[:3]
+             40.0*x^2 + 10.0*x + 1.0
+         """
+-        return self.__coeffs[n]
++        return self._coeffs[n]
+ 
+     def _unsafe_mutate(self, n, value):
+         """
+@@ -11770,17 +11770,17 @@ cdef class Polynomial_generic_dense(Polynomial):
+         """
+         n = int(n)
+         value = self.base_ring()(value)
+-        if n >= 0 and n < len(self.__coeffs):
+-            self.__coeffs[n] = value
+-            if n == len(self.__coeffs) and value == 0:
+-                self.__normalize()
++        if n >= 0 and n < len(self._coeffs):
++            self._coeffs[n] = value
++            if n == len(self._coeffs) and value == 0:
++                self._normalize()
+         elif n < 0:
+             raise IndexError("polynomial coefficient index must be nonnegative")
+         elif value != 0:
+             zero = self.base_ring().zero()
+-            for _ in range(len(self.__coeffs), n):
+-                self.__coeffs.append(zero)
+-            self.__coeffs.append(value)
++            for _ in range(len(self._coeffs), n):
++                self._coeffs.append(zero)
++            self._coeffs.append(value)
+ 
+     def __floordiv__(self, right):
+         """
+@@ -11822,8 +11822,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+             return (<Polynomial_generic_dense>self)._floordiv_(<Polynomial_generic_dense>right)
+         P = parent(self)
+         d = P.base_ring()(right)
+-        cdef Polynomial_generic_dense res = (<Polynomial_generic_dense>self)._new_c([c // d for c in (<Polynomial_generic_dense>self).__coeffs], P)
+-        res.__normalize()
++        cdef Polynomial_generic_dense res = (<Polynomial_generic_dense>self)._new_c([c // d for c in (<Polynomial_generic_dense>self)._coeffs], P)
++        res._normalize()
+         return res
+ 
+     cpdef _add_(self, right):
+@@ -11839,8 +11839,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+         """
+         cdef Polynomial_generic_dense res
+         cdef Py_ssize_t check=0, i, min
+-        x = (<Polynomial_generic_dense>self).__coeffs
+-        y = (<Polynomial_generic_dense>right).__coeffs
++        x = (<Polynomial_generic_dense>self)._coeffs
++        y = (<Polynomial_generic_dense>right)._coeffs
+         if len(x) > len(y):
+             min = len(y)
+             high = x[min:]
+@@ -11852,7 +11852,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+         cdef list low = [x[i] + y[i] for i from 0 <= i < min]
+         if len(x) == len(y):
+             res = self._new_c(low, self._parent)
+-            res.__normalize()
++            res._normalize()
+             return res
+         else:
+             return self._new_c(low + high, self._parent)
+@@ -11860,8 +11860,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+     cpdef _sub_(self, right):
+         cdef Polynomial_generic_dense res
+         cdef Py_ssize_t check=0, i, min
+-        x = (<Polynomial_generic_dense>self).__coeffs
+-        y = (<Polynomial_generic_dense>right).__coeffs
++        x = (<Polynomial_generic_dense>self)._coeffs
++        y = (<Polynomial_generic_dense>right)._coeffs
+         if len(x) > len(y):
+             min = len(y)
+             high = x[min:]
+@@ -11873,33 +11873,33 @@ cdef class Polynomial_generic_dense(Polynomial):
+         low = [x[i] - y[i] for i from 0 <= i < min]
+         if len(x) == len(y):
+             res = self._new_c(low, self._parent)
+-            res.__normalize()
++            res._normalize()
+             return res
+         else:
+             return self._new_c(low + high, self._parent)
+ 
+     cpdef _rmul_(self, Element c):
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return self
+-        if c._parent is not (<Element>self.__coeffs[0])._parent:
+-            c = (<Element>self.__coeffs[0])._parent.coerce(c)
+-        v = [c * a for a in self.__coeffs]
++        if c._parent is not (<Element>self._coeffs[0])._parent:
++            c = (<Element>self._coeffs[0])._parent.coerce(c)
++        v = [c * a for a in self._coeffs]
+         cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
+         #if not v[len(v)-1]:
+         # "normalize" checks this anyway...
+-        res.__normalize()
++        res._normalize()
+         return res
+ 
+     cpdef _lmul_(self, Element c):
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return self
+-        if c._parent is not (<Element>self.__coeffs[0])._parent:
+-            c = (<Element>self.__coeffs[0])._parent.coerce(c)
+-        v = [a * c for a in self.__coeffs]
++        if c._parent is not (<Element>self._coeffs[0])._parent:
++            c = (<Element>self._coeffs[0])._parent.coerce(c)
++        v = [a * c for a in self._coeffs]
+         cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
+         #if not v[len(v)-1]:
+         # "normalize" checks this anyway...
+-        res.__normalize()
++        res._normalize()
+         return res
+ 
+     cpdef constant_coefficient(self):
+@@ -11916,10 +11916,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: f.constant_coefficient()
+             t
+         """
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return self.base_ring().zero()
+         else:
+-            return self.__coeffs[0]
++            return self._coeffs[0]
+ 
+     cpdef list list(self, bint copy=True):
+         """
+@@ -11934,9 +11934,9 @@ cdef class Polynomial_generic_dense(Polynomial):
+             [1, 9, 12, 8]
+         """
+         if copy:
+-            return list(self.__coeffs)
++            return list(self._coeffs)
+         else:
+-            return self.__coeffs
++            return self._coeffs
+ 
+     def degree(self, gen=None):
+         """
+@@ -11955,7 +11955,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+             <class 'sage.rings.integer.Integer'>
+ 
+         """
+-        return smallInteger(len(self.__coeffs) - 1)
++        return smallInteger(len(self._coeffs) - 1)
+ 
+     def shift(self, Py_ssize_t n):
+         r"""
+@@ -11993,13 +11993,13 @@ cdef class Polynomial_generic_dense(Polynomial):
+             return self
+         if n > 0:
+             output = [self.base_ring().zero()] * n
+-            output.extend(self.__coeffs)
++            output.extend(self._coeffs)
+             return self._new_c(output, self._parent)
+         if n < 0:
+-            if n > len(self.__coeffs) - 1:
++            if n > len(self._coeffs) - 1:
+                 return self._parent([])
+             else:
+-                return self._new_c(self.__coeffs[-int(n):], self._parent)
++                return self._new_c(self._coeffs[-int(n):], self._parent)
+ 
+     @coerce_binop
+     def quo_rem(self, other):
+@@ -12073,8 +12073,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+             return self, self
+ 
+         R = self._parent.base_ring()
+-        cdef list x = list((<Polynomial_generic_dense>self).__coeffs) # make a copy
+-        cdef list y = (<Polynomial_generic_dense>other).__coeffs
++        cdef list x = list((<Polynomial_generic_dense>self)._coeffs) # make a copy
++        cdef list y = (<Polynomial_generic_dense>other)._coeffs
+         cdef Py_ssize_t m = len(x)  # deg(self)=m-1
+         cdef Py_ssize_t n = len(y)  # deg(other)=n-1
+         if m < n:
+@@ -12135,18 +12135,18 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: type(f)
+             <class 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense'>
+         """
+-        l = len(self.__coeffs)
++        l = len(self._coeffs)
+         if n > l:
+             n = l
+-        while n > 0 and not self.__coeffs[n-1]:
++        while n > 0 and not self._coeffs[n-1]:
+             n -= 1
+-        return self._new_c(self.__coeffs[:n], self._parent)
++        return self._new_c(self._coeffs[:n], self._parent)
+ 
+     cdef _inplace_truncate(self, long n):
+-        if n < len(self.__coeffs):
+-            while n > 0 and not self.__coeffs[n-1]:
++        if n < len(self._coeffs):
++            while n > 0 and not self._coeffs[n-1]:
+                 n -= 1
+-        self.__coeffs = self.__coeffs[:n]
++        self._coeffs = self._coeffs[:n]
+         return self
+ 
+ def make_generic_polynomial(parent, coeffs):
+@@ -12305,7 +12305,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+ 
+     - Xavier Caruso (2013-03)
+     """
+-    cdef int __normalize(self) except -1:
++    cdef int _normalize(self) except -1:
+         r"""
+         TESTS::
+ 
+@@ -12316,7 +12316,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+             sage: S([1, R(0, 20)])                                                      # needs sage.rings.padics
+             O(5^20)*x + 1 + O(5^20)
+         """
+-        cdef list x = self.__coeffs
++        cdef list x = self._coeffs
+         cdef Py_ssize_t n = len(x) - 1
+         cdef RingElement c
+         while n >= 0:
+@@ -12376,7 +12376,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+ 
+         - Xavier Caruso (2013-03)
+         """
+-        coeffs = self.__coeffs
++        coeffs = self._coeffs
+         d = len(coeffs) - 1
+         while d >= 0:
+             c = coeffs[d]
+@@ -12420,7 +12420,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+ 
+         - Xavier Caruso (2013-03)
+         """
+-        return len(self.__coeffs) - 1
++        return len(self._coeffs) - 1
+ 
+ 
+ cdef class ConstantPolynomialSection(Map):
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd
+index 03c5cebbf09..b1b593d6a26 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd
+@@ -5,7 +5,7 @@ from sage.rings.integer cimport Integer
+ from sage.structure.parent cimport Parent
+ 
+ cdef class Polynomial_integer_dense_flint(Polynomial):
+-    cdef fmpz_poly_t __poly
++    cdef fmpz_poly_t _poly
+ 
+     cdef Polynomial_integer_dense_flint _new(self)
+     cpdef _unsafe_mutate(self, long n, value)
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx
+index e201ac843ad..194eb9263b2 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx
+@@ -99,14 +99,14 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         r"""
+         This calls the underlying FLINT fmpz_poly constructor
+         """
+-        fmpz_poly_init(self.__poly)
++        fmpz_poly_init(self._poly)
+ 
+ 
+     def __dealloc__(self):
+         r"""
+         calls the underlying FLINT fmpz_poly destructor
+         """
+-        fmpz_poly_clear(self.__poly)
++        fmpz_poly_clear(self._poly)
+ 
+     cdef Polynomial_integer_dense_flint _new(self):
+         r"""
+@@ -139,7 +139,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         x._is_gen = 0
+         if not isinstance(a, Integer):
+             a = ZZ(a)
+-        fmpz_poly_set_coeff_mpz(x.__poly, 0, (<Integer>a).value)
++        fmpz_poly_set_coeff_mpz(x._poly, 0, (<Integer>a).value)
+         return x
+ 
+     def __init__(self, parent, x=None, check=True, is_gen=False,
+@@ -224,8 +224,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         if isinstance(x, Polynomial):
+             if x.parent() is self.parent():
+                 sig_on()
+-                fmpz_poly_set(self.__poly,
+-                              (<Polynomial_integer_dense_flint>x).__poly)
++                fmpz_poly_set(self._poly,
++                              (<Polynomial_integer_dense_flint>x)._poly)
+                 sig_off()
+                 return
+             else:
+@@ -246,7 +246,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                     degree = i
+             try:
+                 sig_on()
+-                fmpz_poly_realloc(self.__poly, degree + 1)
++                fmpz_poly_realloc(self._poly, degree + 1)
+                 sig_off()
+             except RuntimeError:
+                 raise OverflowError("Cannot allocate memory!")
+@@ -255,13 +255,13 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 i = ii[0] if type(ii) is tuple else ii
+                 if is_small_python_int(a):
+                     sig_on()
+-                    fmpz_poly_set_coeff_si(self.__poly, i, a)
++                    fmpz_poly_set_coeff_si(self._poly, i, a)
+                     sig_off()
+                 else:
+                     if not isinstance(a, Integer):
+                         a = ZZ(a)
+                     sig_on()
+-                    fmpz_poly_set_coeff_mpz(self.__poly, i, (<Integer>a).value)
++                    fmpz_poly_set_coeff_mpz(self._poly, i, (<Integer>a).value)
+                     sig_off()
+             return
+ 
+@@ -270,7 +270,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             check = False
+ 
+         elif isinstance(x, ntl_ZZX):    # coercion from ntl.pyx object
+-            fmpz_poly_set_ZZX(self.__poly, (<ntl_ZZX>x).x)
++            fmpz_poly_set_ZZX(self._poly, (<ntl_ZZX>x).x)
+             return
+ 
+         elif isinstance(x, FractionFieldElement) and \
+@@ -278,8 +278,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if x.denominator() == 1:
+                 # fraction of the form f(x)/1
+                 sig_on()
+-                fmpz_poly_set(self.__poly,
+-                        (<Polynomial_integer_dense_flint>x.numerator()).__poly)
++                fmpz_poly_set(self._poly,
++                        (<Polynomial_integer_dense_flint>x.numerator())._poly)
+                 sig_off()
+                 return
+ 
+@@ -287,19 +287,19 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             x = [x]   # constant polynomials
+ 
+         sig_on()
+-        fmpz_poly_realloc(self.__poly, len(x))
++        fmpz_poly_realloc(self._poly, len(x))
+         sig_off()
+         for i from 0 <= i < len(x):
+             a = x[i]
+             if is_small_python_int(a):
+                 sig_on()
+-                fmpz_poly_set_coeff_si(self.__poly, i, a)
++                fmpz_poly_set_coeff_si(self._poly, i, a)
+                 sig_off()
+             else:
+                 if not isinstance(a, Integer):
+                     a = ZZ(a)
+                 sig_on()
+-                fmpz_poly_set_coeff_mpz(self.__poly, i, (<Integer>a).value)
++                fmpz_poly_set_coeff_mpz(self._poly, i, (<Integer>a).value)
+                 sig_off()
+ 
+     def _eval_mpfr_(self, RealNumber a):
+@@ -327,7 +327,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef RealNumber res = a._new()
+         sig_on()
+-        fmpz_poly_evaluation_mpfr(res.value, self.__poly, a.value)
++        fmpz_poly_evaluation_mpfr(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -357,7 +357,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef RealIntervalFieldElement res = a._new()
+         sig_on()
+-        fmpz_poly_evaluation_mpfi(res.value, self.__poly, a.value)
++        fmpz_poly_evaluation_mpfi(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -412,8 +412,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if isinstance(x, Polynomial_integer_dense_flint):
+                 f = self._new()
+                 sig_on()
+-                fmpz_poly_compose(f.__poly, self.__poly,
+-                                  (<Polynomial_integer_dense_flint> x0).__poly)
++                fmpz_poly_compose(f._poly, self._poly,
++                                  (<Polynomial_integer_dense_flint> x0)._poly)
+                 sig_off()
+                 return f
+             if is_small_python_int(x0):
+@@ -422,7 +422,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 fmpz_init(a_fmpz)
+                 fmpz_init(z_fmpz)
+                 fmpz_set_si(a_fmpz, PyInt_AS_LONG(x0))
+-                fmpz_poly_evaluate_fmpz(z_fmpz, self.__poly, a_fmpz)
++                fmpz_poly_evaluate_fmpz(z_fmpz, self._poly, a_fmpz)
+                 fmpz_get_mpz(z.value, z_fmpz)
+                 fmpz_clear(a_fmpz)
+                 fmpz_clear(z_fmpz)
+@@ -433,7 +433,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if isinstance(x0, Integer):
+                 a = <Integer> x0
+ 
+-                if fmpz_poly_length(self.__poly) == 0:
++                if fmpz_poly_length(self._poly) == 0:
+                     return ZZ.zero()
+                 if mpz_sgn(a.value) == 0:
+                     return self[0]
+@@ -444,7 +444,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 fmpz_init(a_fmpz)
+                 fmpz_init(z_fmpz)
+                 fmpz_set_mpz(a_fmpz, a.value)
+-                fmpz_poly_evaluate_fmpz(z_fmpz, self.__poly, a_fmpz)
++                fmpz_poly_evaluate_fmpz(z_fmpz, self._poly, a_fmpz)
+                 fmpz_get_mpz(z.value, z_fmpz)
+                 fmpz_clear(a_fmpz)
+                 fmpz_clear(z_fmpz)
+@@ -460,14 +460,14 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 arb_a = <RealBall> x0
+                 arb_z = arb_a._new()
+                 sig_on()
+-                arb_fmpz_poly_evaluate_arb(arb_z.value, self.__poly, arb_a.value, arb_a._parent._prec)
++                arb_fmpz_poly_evaluate_arb(arb_z.value, self._poly, arb_a.value, arb_a._parent._prec)
+                 sig_off()
+                 return arb_z
+             if isinstance(x0, ComplexBall):
+                 acb_a = <ComplexBall> x0
+                 acb_z = acb_a._new()
+                 sig_on()
+-                arb_fmpz_poly_evaluate_acb(acb_z.value, self.__poly, acb_a.value, acb_a._parent._prec)
++                arb_fmpz_poly_evaluate_acb(acb_z.value, self._poly, acb_a.value, acb_a._parent._prec)
+                 sig_off()
+                 return acb_z
+ 
+@@ -510,10 +510,10 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+         cdef fmpz_t c
+         fmpz_init(c)
+-        fmpz_poly_get_coeff_fmpz(c, self.__poly, fmpz_poly_degree(self.__poly))
++        fmpz_poly_get_coeff_fmpz(c, self._poly, fmpz_poly_degree(self._poly))
+         cdef int sign = fmpz_sgn(c)
+ 
+-        fmpz_poly_content(c, self.__poly)
++        fmpz_poly_content(c, self._poly)
+ 
+         cdef Integer z = Integer.__new__(Integer)
+         fmpz_get_mpz(z.value, c)
+@@ -561,7 +561,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             5*x^5 + 4*x^4 + 3*x^3 + 2*x^2 + x + 1
+         """
+         cdef Integer z = Integer.__new__(Integer)
+-        fmpz_poly_get_coeff_mpz(z.value, self.__poly, n)
++        fmpz_poly_get_coeff_mpz(z.value, self._poly, n)
+         return z
+ 
+     def _repr(self, name=None, bint latex=False):
+@@ -583,8 +583,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef long i
+         cdef Integer coef = Integer.__new__(Integer)
+         cdef list all = []
+-        for i from fmpz_poly_degree(self.__poly) >= i >= 0:
+-            fmpz_poly_get_coeff_mpz(coef.value, self.__poly, i)
++        for i from fmpz_poly_degree(self._poly) >= i >= 0:
++            fmpz_poly_get_coeff_mpz(coef.value, self._poly, i)
+             if coef:
+                 if coef > 0:
+                     sign_str = '+'
+@@ -649,8 +649,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_add(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_add(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -669,8 +669,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_sub(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_sub(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -688,7 +688,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_neg(x.__poly, self.__poly)
++        fmpz_poly_neg(x._poly, self._poly)
+         sig_off()
+         return x
+ 
+@@ -758,7 +758,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef Polynomial_integer_dense_flint rr = self._new()
+ 
+         sig_on()
+-        fmpz_poly_divrem(qq.__poly, rr.__poly, self.__poly, right.__poly)
++        fmpz_poly_divrem(qq._poly, rr._poly, self._poly, right._poly)
+         sig_off()
+         return qq, rr
+ 
+@@ -776,7 +776,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: x.is_zero()
+             False
+         """
+-        return (fmpz_poly_degree(self.__poly) == -1)
++        return (fmpz_poly_degree(self._poly) == -1)
+ 
+     cpdef bint is_one(self) except -1:
+         """
+@@ -792,7 +792,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: x.is_one()
+             False
+         """
+-        return fmpz_poly_is_one(self.__poly)
++        return fmpz_poly_is_one(self._poly)
+ 
+     def __bool__(self):
+         """
+@@ -808,7 +808,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: bool(x)
+             True
+         """
+-        return not (fmpz_poly_degree(self.__poly) == -1)
++        return not (fmpz_poly_degree(self._poly) == -1)
+ 
+     @coerce_binop
+     def gcd(self, right):
+@@ -831,8 +831,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             return self
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_gcd(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_gcd(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -941,8 +941,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         fmpz_init(r)
+ 
+         sig_on()
+-        fmpz_poly_xgcd(r, ss.__poly, tt.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_xgcd(r, ss._poly, tt._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         cdef Integer rr = Integer.__new__(Integer)
+         fmpz_get_mpz(rr.value, r)
+@@ -970,8 +970,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_mul(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_mul(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -1000,8 +1000,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_mullow(x.__poly, self.__poly,
+-                    (<Polynomial_integer_dense_flint>right).__poly,
++        fmpz_poly_mullow(x._poly, self._poly,
++                    (<Polynomial_integer_dense_flint>right)._poly,
+                     n)
+         sig_off()
+         return x
+@@ -1020,7 +1020,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_scalar_mul_mpz(x.__poly, self.__poly, (<Integer>right).value)
++        fmpz_poly_scalar_mul_mpz(x._poly, self._poly, (<Integer>right).value)
+         sig_off()
+         return x
+ 
+@@ -1038,7 +1038,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_scalar_mul_mpz(x.__poly, self.__poly, (<Integer>right).value)
++        fmpz_poly_scalar_mul_mpz(x._poly, self._poly, (<Integer>right).value)
+         sig_off()
+         return x
+ 
+@@ -1132,7 +1132,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             num = n.numerator()
+             den = n.denominator()
+ 
+-            if fmpz_poly_degree(self.__poly) == 0:
++            if fmpz_poly_degree(self._poly) == 0:
+                 return self.parent()(self[0].nth_root(den) ** num)
+ 
+             return self.nth_root(den) ** num
+@@ -1142,7 +1142,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+             if self.is_zero():
+                 if nn == 0:
+-                    fmpz_poly_set_coeff_si(res.__poly, 0, 1)
++                    fmpz_poly_set_coeff_si(res._poly, 0, 1)
+                     return res
+                 elif nn < 0:
+                     raise ZeroDivisionError("negative exponent in power of zero")
+@@ -1150,17 +1150,17 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                     return res
+             if nn < 0:
+                 sig_on()
+-                fmpz_poly_pow(res.__poly, self.__poly, -nn)
++                fmpz_poly_pow(res._poly, self._poly, -nn)
+                 sig_off()
+                 return ~res
+             else:
+                 if self is self._parent.gen():
+                     sig_on()
+-                    fmpz_poly_set_coeff_ui(res.__poly, nn, 1)
++                    fmpz_poly_set_coeff_ui(res._poly, nn, 1)
+                     sig_off()
+                 else:
+                     sig_on()
+-                    fmpz_poly_pow(res.__poly, self.__poly, nn)
++                    fmpz_poly_pow(res._poly, self._poly, nn)
+                     sig_off()
+                 return res
+ 
+@@ -1187,7 +1187,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+         cdef Polynomial_integer_dense_flint res
+         res = self._new()
+-        fmpz_poly_pow_trunc(res.__poly, self.__poly, n, prec)
++        fmpz_poly_pow_trunc(res._poly, self._poly, n, prec)
+         return res
+ 
+     def __floordiv__(Polynomial_integer_dense_flint self, right):
+@@ -1226,14 +1226,14 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 else:
+                     res = self._new()
+                     sig_on()
+-                    fmpz_poly_scalar_fdiv_mpz(res.__poly, self.__poly,
++                    fmpz_poly_scalar_fdiv_mpz(res._poly, self._poly,
+                             (<Integer> right).value)
+                     sig_off()
+                 return res
+             elif right in ZZ:
+                 res = self._new()
+                 sig_on()
+-                fmpz_poly_scalar_fdiv_mpz(res.__poly, self.__poly,
++                fmpz_poly_scalar_fdiv_mpz(res._poly, self._poly,
+                         (<Integer>ZZ(right)).value)
+                 sig_off()
+                 return res
+@@ -1248,7 +1248,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         else:
+             res = self._new()
+             sig_on()
+-            fmpz_poly_div(res.__poly, self.__poly, _right.__poly)
++            fmpz_poly_div(res._poly, self._poly, _right._poly)
+             sig_off()
+             return res
+ 
+@@ -1293,9 +1293,9 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         if prec <= 0:
+             raise ValueError("the precision must be positive, got {}".format(prec))
+ 
+-        if fmpz_poly_degree(self.__poly) == -1:
++        if fmpz_poly_degree(self._poly) == -1:
+             raise ValueError("constant term is zero")
+-        cdef fmpz_t c = fmpz_poly_get_coeff_ptr(self.__poly, 0)
++        cdef fmpz_t c = fmpz_poly_get_coeff_ptr(self._poly, 0)
+         if fmpz_cmp_si(c, 1) and fmpz_cmp_si(c, -1):
+             raise ValueError("constant term {} is not a unit".format(self[0]))
+ 
+@@ -1303,7 +1303,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         if prec <= 0:
+             return res
+         sig_on()
+-        fmpz_poly_inv_series(res.__poly, self.__poly, prec)
++        fmpz_poly_inv_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1331,16 +1331,16 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             raise IndexError("n must be >= 0")
+         if isinstance(value, int):
+             sig_on()
+-            fmpz_poly_set_coeff_si(self.__poly, n, value)
++            fmpz_poly_set_coeff_si(self._poly, n, value)
+             sig_off()
+         elif isinstance(value, Integer):
+             sig_on()
+-            fmpz_poly_set_coeff_mpz(self.__poly, n, (<Integer>value).value)
++            fmpz_poly_set_coeff_mpz(self._poly, n, (<Integer>value).value)
+             sig_off()
+         else:
+             value = Integer(value)
+             sig_on()
+-            fmpz_poly_set_coeff_mpz(self.__poly, n, (<Integer>value).value)
++            fmpz_poly_set_coeff_mpz(self._poly, n, (<Integer>value).value)
+             sig_off()
+ 
+     def real_root_intervals(self):
+@@ -1364,7 +1364,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+ ##     def __copy__(self):
+ ##         f = Polynomial_integer_dense(self.parent())
+-##         f.__poly = self.__poly.copy()
++##         f._poly = self._poly.copy()
+ ##         return f
+ 
+ 
+@@ -1391,7 +1391,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: type(x.degree())
+             <class 'sage.rings.integer.Integer'>
+         """
+-        return smallInteger(fmpz_poly_degree(self.__poly))
++        return smallInteger(fmpz_poly_degree(self._poly))
+ 
+     def pseudo_divrem(self, B):
+         r"""
+@@ -1426,7 +1426,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint Q = self._new(), R = self._new(), _B = B
+         cdef ulong d
+-        fmpz_poly_pseudo_divrem(Q.__poly, R.__poly, &d, self.__poly, _B.__poly)
++        fmpz_poly_pseudo_divrem(Q._poly, R._poly, &d, self._poly, _B._poly)
+         return Q, R, Integer(d)
+ 
+     def discriminant(self, proof=True):
+@@ -1460,7 +1460,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef ZZX_c ntl_poly
+         cdef ZZ_c* temp
+-        fmpz_poly_get_ZZX(ntl_poly, self.__poly)
++        fmpz_poly_get_ZZX(ntl_poly, self._poly)
+ 
+         temp = ZZX_discriminant(&ntl_poly, proof)
+         cdef Integer x = Integer.__new__(Integer)
+@@ -1531,12 +1531,12 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+             # the primitive part returned by FLINT has positive leading
+             # coefficient
+-            fmpz_poly_primitive_part(ppart, self.__poly)
++            fmpz_poly_primitive_part(ppart, self._poly)
+ 
+             fmpz_poly_get_ZZX(ntl_poly, ppart)
+             fmpz_poly_clear(ppart)
+         else:
+-            fmpz_poly_get_ZZX(ntl_poly, self.__poly)
++            fmpz_poly_get_ZZX(ntl_poly, self._poly)
+ 
+         # input is primitive, with positive leading coefficient
+         ZZX_squarefree_decomposition(&v, &e, &n, &ntl_poly)
+@@ -1544,7 +1544,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         F = []
+         for i from 0 <= i < n:
+             fac = self._new()
+-            fmpz_poly_set_ZZX(fac.__poly, v[i][0])
++            fmpz_poly_set_ZZX(fac._poly, v[i][0])
+             F.append( (fac,e[i]) )
+             del v[i]
+         sig_free(v)
+@@ -1582,9 +1582,9 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef ZZ_c content
+         cdef vec_pair_ZZX_long_c factors
+         cdef long i
+-        cdef int sig_me = fmpz_poly_degree(self.__poly)
++        cdef int sig_me = fmpz_poly_degree(self._poly)
+ 
+-        fmpz_poly_get_ZZX(ntl_poly, self.__poly)
++        fmpz_poly_get_ZZX(ntl_poly, self._poly)
+ 
+         if sig_me > 10:
+             sig_on()
+@@ -1603,13 +1603,13 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             fac_py = self._new()
+             fmpz_init(tcontent)
+             fmpz_set_ZZ(tcontent, content)
+-            fmpz_poly_set_coeff_fmpz(fac_py.__poly, 0, tcontent)
++            fmpz_poly_set_coeff_fmpz(fac_py._poly, 0, tcontent)
+             results.append( (fac_py,1) )
+             fmpz_clear(tcontent)
+ 
+         for i from 0 <= i < factors.length():
+             fac_py = self._new()
+-            fmpz_poly_set_ZZX(fac_py.__poly, factors.RawGet(i).a)
++            fmpz_poly_set_ZZX(fac_py._poly, factors.RawGet(i).a)
+             results.append( (fac_py,factors.RawGet(i).b) )
+         return Factorization(results, unit = unit)
+ 
+@@ -1639,7 +1639,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             (-1) * 2 * 3 * 5 * x
+         """
+         cdef int i
+-        cdef long deg = fmpz_poly_degree(self.__poly)
++        cdef long deg = fmpz_poly_degree(self._poly)
+         # it appears that pari has a window from about degrees 30 and 300
+         # in which it beats NTL.
+         c = self.content()
+@@ -1783,8 +1783,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef Integer x = Integer.__new__(Integer)
+ 
+         sig_on()
+-        fmpz_poly_resultant(res, self.__poly,
+-                (<Polynomial_integer_dense_flint>other).__poly)
++        fmpz_poly_resultant(res, self._poly,
++                (<Polynomial_integer_dense_flint>other)._poly)
+         sig_off()
+         fmpz_get_mpz(x.value, res)
+         fmpz_clear(res)
+@@ -1830,10 +1830,10 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if d != degree:
+                 raise ValueError("degree argument must be a non-negative integer, got %s" % degree)
+             # FLINT expects length
+-            fmpz_poly_reverse(res.__poly, self.__poly, d+1)
++            fmpz_poly_reverse(res._poly, self._poly, d+1)
+         else:
+-            fmpz_poly_reverse(res.__poly, self.__poly,
+-                    fmpz_poly_length(self.__poly))
++            fmpz_poly_reverse(res._poly, self._poly,
++                    fmpz_poly_length(self._poly))
+         return res
+ 
+     def revert_series(self, n):
+@@ -1867,7 +1867,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             raise ValueError("self must have constant coefficient 0 and a unit for coefficient {}^1".format(self.parent().gen()))
+ 
+         sig_on()
+-        fmpz_poly_revert_series(res.__poly, self.__poly, m)
++        fmpz_poly_revert_series(res._poly, self._poly, m)
+         sig_off()
+ 
+         return res
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd
+index a7c380b49a2..fcd907e1abe 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd
+@@ -2,6 +2,6 @@ from sage.libs.ntl.types cimport ZZX_c
+ from sage.rings.polynomial.polynomial_element cimport Polynomial
+ 
+ cdef class Polynomial_integer_dense_ntl(Polynomial):
+-    cdef ZZX_c __poly
++    cdef ZZX_c _poly
+ 
+     cdef Polynomial_integer_dense_ntl _new(self)
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx
+index e7b708bbc51..80a1726bb4e 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx
+@@ -172,7 +172,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         if isinstance(x, Polynomial):
+             if x.parent() is self.parent():
+                 # copy with NTL assignment operator
+-                self.__poly = (<Polynomial_integer_dense_ntl>x).__poly
++                self._poly = (<Polynomial_integer_dense_ntl>x)._poly
+                 return
+             else:
+                 # coerce coefficients into Sage integers
+@@ -191,17 +191,17 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+                     degree = i
+             if degree >= NTL_OVFBND:
+                 raise OverflowError("Dense NTL integer polynomials have a maximum degree of %s" % (NTL_OVFBND-1))
+-            ZZX_SetCoeff_long(self.__poly, degree, 1)
++            ZZX_SetCoeff_long(self._poly, degree, 1)
+             # now fill them in
+             for ii, a in x:
+                 i = ii[0] if type(ii) is tuple else ii
+                 if type(a) is int:
+-                    ZZX_SetCoeff_long(self.__poly, i, a)
++                    ZZX_SetCoeff_long(self._poly, i, a)
+                 else:
+                     if not isinstance(a, Integer):
+                         a = ZZ(a)
+                     mpz_to_ZZ(&y, (<Integer>a).value)
+-                    ZZX_SetCoeff(self.__poly, i, y)
++                    ZZX_SetCoeff(self._poly, i, y)
+             return
+ 
+         elif isinstance(x, pari_gen):
+@@ -210,14 +210,14 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+ 
+         elif isinstance(x, ntl_ZZX):    # coercion from ntl.pyx object
+             # copy with NTL assignment operator
+-            self.__poly = (<ntl_ZZX>x).x
++            self._poly = (<ntl_ZZX>x).x
+             return
+ 
+         elif isinstance(x, FractionFieldElement) and \
+                  isinstance(x.numerator(), Polynomial_integer_dense_ntl):
+             if x.denominator() == 1:
+                 # fraction of the form f(x)/1
+-                self.__poly = (<Polynomial_integer_dense_ntl>x.numerator()).__poly
++                self._poly = (<Polynomial_integer_dense_ntl>x.numerator())._poly
+                 return
+ 
+         elif not isinstance(x, (list, tuple)):
+@@ -229,12 +229,12 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         for i from 0 <= i < len(x):
+             a = x[i]
+             if type(a) is int:
+-                ZZX_SetCoeff_long(self.__poly, i, a)
++                ZZX_SetCoeff_long(self._poly, i, a)
+             else:
+                 if not isinstance(a, Integer):
+                     a = ZZ(a)
+                 mpz_to_ZZ(&y, (<Integer>a).value)
+-                ZZX_SetCoeff(self.__poly, i, y)
++                ZZX_SetCoeff(self._poly, i, y)
+ 
+ 
+     def content(self):
+@@ -259,7 +259,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef ZZ_c y
+         cdef Integer z = Integer.__new__(Integer)
+-        ZZX_content(y, self.__poly)
++        ZZX_content(y, self._poly)
+         ZZ_to_mpz(z.value, &y)
+         return z
+ 
+@@ -288,7 +288,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef RealNumber res = a._new()
+         sig_on()
+-        ZZX_evaluation_mpfr(res.value, self.__poly, a.value)
++        ZZX_evaluation_mpfr(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -318,7 +318,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef RealIntervalFieldElement res = a._new()
+         sig_on()
+-        ZZX_evaluation_mpfi(res.value, self.__poly, a.value)
++        ZZX_evaluation_mpfi(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -363,7 +363,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             5*x^5 + 4*x^4 + 3*x^3 + 2*x^2 + x + 1
+         """
+         cdef Integer z = Integer.__new__(Integer)
+-        ZZ_to_mpz(z.value, &self.__poly.rep.elts()[n])
++        ZZ_to_mpz(z.value, &self._poly.rep.elts()[n])
+         return z
+ 
+     def _repr(self, name=None, bint latex=False):
+@@ -380,15 +380,15 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             name = self.parent().variable_name()
+         cdef long i
+         cdef list all = []
+-        for i from ZZX_deg(self.__poly) >= i >= 0:
+-            sign = ZZ_sign(ZZX_coeff(self.__poly, i))
++        for i from ZZX_deg(self._poly) >= i >= 0:
++            sign = ZZ_sign(ZZX_coeff(self._poly, i))
+             if sign:
+                 if sign > 0:
+                     sign_str = '+'
+-                    coeff_str = ccrepr(self.__poly.rep.elts()[i])
++                    coeff_str = ccrepr(self._poly.rep.elts()[i])
+                 else:
+                     sign_str = '-'
+-                    coeff_str = ccrepr(self.__poly.rep.elts()[i])[1:]
++                    coeff_str = ccrepr(self._poly.rep.elts()[i])[1:]
+                 if i > 0:
+                     if coeff_str == '1':
+                         coeff_str = ''
+@@ -441,8 +441,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             -3*x^2 + 2*x + 7
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_add(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_ntl>right).__poly)
++        ZZX_add(x._poly, self._poly,
++                (<Polynomial_integer_dense_ntl>right)._poly)
+         return x
+ 
+ 
+@@ -459,8 +459,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             3*x^2 + 2*x - 5
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_sub(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_ntl>right).__poly)
++        ZZX_sub(x._poly, self._poly,
++                (<Polynomial_integer_dense_ntl>right)._poly)
+         return x
+ 
+ 
+@@ -476,7 +476,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             -2*x + 1
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_negate(x.__poly, self.__poly)
++        ZZX_negate(x._poly, self._poly)
+         return x
+ 
+ 
+@@ -533,10 +533,10 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef Polynomial_integer_dense_ntl _right = <Polynomial_integer_dense_ntl> right
+ 
+-        if ZZX_IsZero(_right.__poly):
++        if ZZX_IsZero(_right._poly):
+             raise ArithmeticError("division by zero polynomial")
+ 
+-        if ZZX_IsZero(self.__poly):
++        if ZZX_IsZero(self._poly):
+             return self, self
+ 
+         cdef ZZX_c *q
+@@ -545,19 +545,19 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef Polynomial_integer_dense_ntl rr = self._new()
+         cdef int divisible
+ 
+-        if ZZ_IsOne(ZZX_LeadCoeff(_right.__poly)):
++        if ZZ_IsOne(ZZX_LeadCoeff(_right._poly)):
+             # divisor is monic. Just do the division and remainder
+-            ZZX_quo_rem(&self.__poly, &_right.__poly, &r, &q)
+-            ZZX_swap(qq.__poly, q[0])
+-            ZZX_swap(rr.__poly, r[0])
++            ZZX_quo_rem(&self._poly, &_right._poly, &r, &q)
++            ZZX_swap(qq._poly, q[0])
++            ZZX_swap(rr._poly, r[0])
+             del q
+             del r
+         else:
+             # Non-monic divisor. Check whether it divides exactly.
+-            q = ZZX_div(&self.__poly, &_right.__poly, &divisible)
++            q = ZZX_div(&self._poly, &_right._poly, &divisible)
+             if divisible:
+                 # exactly divisible
+-                ZZX_swap(q[0], qq.__poly)
++                ZZX_swap(q[0], qq._poly)
+                 del q
+             else:
+                 # division failed: clean up and raise exception
+@@ -584,8 +584,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         # todo: we're doing an unnecessary copy here
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        cdef ZZX_c* temp = ZZX_gcd(&self.__poly, &(<Polynomial_integer_dense_ntl>right).__poly)
+-        x.__poly = temp[0]
++        cdef ZZX_c* temp = ZZX_gcd(&self._poly, &(<Polynomial_integer_dense_ntl>right)._poly)
++        x._poly = temp[0]
+         del temp
+         return x
+ 
+@@ -658,13 +658,13 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZX_c *t
+         cdef ZZ_c *r
+ 
+-        ZZX_xgcd(&self.__poly, &(<Polynomial_integer_dense_ntl>right).__poly, &r, &s, &t, 1)    # proof = 1
++        ZZX_xgcd(&self._poly, &(<Polynomial_integer_dense_ntl>right)._poly, &r, &s, &t, 1)    # proof = 1
+         cdef Integer rr = Integer.__new__(Integer)
+         ZZ_to_mpz(rr.value, r)
+         cdef Polynomial_integer_dense_ntl ss = self._new()
+         cdef Polynomial_integer_dense_ntl tt = self._new()
+-        ss.__poly = s[0]
+-        tt.__poly = t[0]
++        ss._poly = s[0]
++        tt._poly = t[0]
+         del r
+         del s
+         del t
+@@ -691,8 +691,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             x^3 - 10*x^2 + 32*x - 32
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_mul(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_ntl>right).__poly)
++        ZZX_mul(x._poly, self._poly,
++                (<Polynomial_integer_dense_ntl>right)._poly)
+         return x
+ 
+     cpdef _lmul_(self, Element right):
+@@ -711,7 +711,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZ_c _right
+ 
+         mpz_to_ZZ(&_right, (<Integer>right).value)
+-        ZZX_mul_ZZ(x.__poly, self.__poly, _right)
++        ZZX_mul_ZZ(x._poly, self._poly, _right)
+         return x
+ 
+     cpdef _rmul_(self, Element right):
+@@ -730,7 +730,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZ_c _right
+ 
+         mpz_to_ZZ(&_right, (<Integer>right).value)
+-        ZZX_mul_ZZ(x.__poly, self.__poly, _right)
++        ZZX_mul_ZZ(x._poly, self._poly, _right)
+         return x
+ 
+ 
+@@ -783,7 +783,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         value = Integer(value)
+         cdef ZZ_c y
+         mpz_to_ZZ(&y, (<Integer>value).value)
+-        ZZX_SetCoeff(self.__poly, n, y)
++        ZZX_SetCoeff(self._poly, n, y)
+ 
+ 
+     def real_root_intervals(self):
+@@ -805,7 +805,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+ 
+ ##     def __copy__(self):
+ ##         f = Polynomial_integer_dense(self.parent())
+-##         f.__poly = self.__poly.copy()
++##         f._poly = self._poly.copy()
+ ##         return f
+ 
+ 
+@@ -826,7 +826,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             sage: R(0).degree()
+             -1
+         """
+-        return ZZX_deg(self.__poly)
++        return ZZX_deg(self._poly)
+ 
+     def discriminant(self, proof=True):
+         r"""
+@@ -849,7 +849,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             sage: f.discriminant(proof=False)
+             -339
+         """
+-        cdef ZZ_c* temp = ZZX_discriminant(&self.__poly, proof)
++        cdef ZZ_c* temp = ZZX_discriminant(&self._poly, proof)
+         cdef Integer x = Integer.__new__(Integer)
+         ZZ_to_mpz(x.value, temp)
+         del temp
+@@ -904,11 +904,11 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef long* e
+         cdef long i, n
+         cdef Polynomial_integer_dense_ntl z
+-        ZZX_squarefree_decomposition(&v, &e, &n, &p.__poly)
++        ZZX_squarefree_decomposition(&v, &e, &n, &p._poly)
+         F = []
+         for i from 0 <= i < n:
+             z = self._new()
+-            z.__poly = v[i][0]
++            z._poly = v[i][0]
+             F.append((z, e[i]))
+             del v[i]
+         sig_free(v)
+@@ -950,24 +950,24 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZ_c content
+         cdef vec_pair_ZZX_long_c factors
+         cdef long i
+-        cdef int sig_me = ZZX_deg(self.__poly)
++        cdef int sig_me = ZZX_deg(self._poly)
+         if sig_me > 10:
+             sig_on()
+-        ZZX_factor(content, factors, self.__poly, 0, 0)
++        ZZX_factor(content, factors, self._poly, 0, 0)
+         if sig_me > 10:
+             sig_off()
+         results = []
+         unit = None
+         if not ZZ_IsOne(content):
+             fac_py = self._new()
+-            ZZX_SetCoeff(fac_py.__poly, 0, content)
+-            if ZZX_deg(fac_py.__poly) == 0 and ZZ_to_int(fac_py.__poly.rep.elts())==-1:
++            ZZX_SetCoeff(fac_py._poly, 0, content)
++            if ZZX_deg(fac_py._poly) == 0 and ZZ_to_int(fac_py._poly.rep.elts())==-1:
+                 unit = fac_py
+             else:
+                 results.append( (fac_py,1) )
+         for i from 0 <= i < factors.length():
+             fac_py = self._new()
+-            fac_py.__poly = factors.RawGet(i).a
++            fac_py._poly = factors.RawGet(i).a
+             results.append( (fac_py,factors.RawGet(i).b) )
+         return Factorization(results, unit = unit)
+ 
+@@ -996,7 +996,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             sage: f = -30*x; f.factor()
+             (-1) * 2 * 3 * 5 * x
+         """
+-        cdef int deg = ZZX_deg(self.__poly)
++        cdef int deg = ZZX_deg(self._poly)
+         # it appears that pari has a window from about degrees 30 and 300
+         # in which it beats NTL.
+         c = self.content()
+@@ -1131,7 +1131,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             True
+         """
+         cdef Polynomial_integer_dense_ntl _other = <Polynomial_integer_dense_ntl>(self.parent().coerce(other))
+-        cdef ZZ_c* temp = ZZX_resultant(&self.__poly, &_other.__poly, proof)
++        cdef ZZ_c* temp = ZZX_resultant(&self._poly, &_other._poly, proof)
+         cdef Integer x = Integer.__new__(Integer)
+         ZZ_to_mpz(x.value, temp)
+         del temp
+diff --git a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd
+index 264f05f3c0d..6934acfee8d 100644
+--- a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd
++++ b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd
+@@ -16,7 +16,7 @@ from sage.libs.ntl.lzz_pX cimport *
+ 
+ 
+ cdef class Polynomial_dense_mod_n(Polynomial):
+-    cdef object __poly
++    cdef object _poly
+     cdef object __singular
+ 
+ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n):
+diff --git a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx
+index 57468e3510f..d69d5e09018 100644
+--- a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx
++++ b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx
+@@ -105,19 +105,19 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+ 
+         if construct:
+             if isinstance(x, ZZ_pX):
+-                self.__poly = x
++                self._poly = x
+                 return
+-            self.__poly = ZZ_pX(x, parent.modulus())
++            self._poly = ZZ_pX(x, parent.modulus())
+             return
+ 
+-        self.__poly = ZZ_pX([], parent.modulus())
++        self._poly = ZZ_pX([], parent.modulus())
+ 
+         if x is None:
+             return         # leave initialized to 0 polynomial.
+ 
+         if isinstance(x, Polynomial):
+             if x.parent() == self.parent():
+-                self.__poly = (<Polynomial_dense_modn_ntl_zz>x).__poly.__copy__()
++                self._poly = (<Polynomial_dense_modn_ntl_zz>x)._poly.__copy__()
+                 return
+             else:
+                 R = parent.base_ring()
+@@ -130,7 +130,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+ 
+ 
+         elif isinstance(x, ZZX):
+-            self.__poly = x.copy()
++            self._poly = x.copy()
+             return
+ 
+         elif isinstance(x, pari_gen):
+@@ -142,7 +142,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             if x.denominator().is_unit():
+                 numer = x.numerator()
+                 denom = x.denominator().inverse_of_unit()
+-                x = numer.__poly * denom.__poly
++                x = numer._poly * denom._poly
+                 check = False
+             else:
+                 raise TypeError("Denominator not a unit.")
+@@ -154,13 +154,13 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             R = parent.base_ring()
+             x = [ZZ(R(a)) for a in x]
+ 
+-        self.__poly = ZZ_pX(x, parent.modulus())
++        self._poly = ZZ_pX(x, parent.modulus())
+ 
+     def __reduce__(self):
+         return make_element, (self.parent(), (self.list(), False, self.is_gen()))
+ 
+     def int_list(self):
+-        return eval(str(self.__poly).replace(' ',','))
++        return eval(str(self._poly).replace(' ',','))
+ 
+     def __pari__(self, variable=None):
+         """
+@@ -186,7 +186,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             You must call ``ntl.set_modulus(ntl.ZZ(n))`` before doing
+             arithmetic with this object!
+         """
+-        return self.__poly
++        return self._poly
+ 
+     cdef get_unsafe(self, Py_ssize_t n):
+         """
+@@ -203,13 +203,13 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             sage: f[:3]
+             13*x^2 + 10*x + 5
+         """
+-        return self._parent._base((<ntl_ZZ_pX> self.__poly)[n]._integer_())
++        return self._parent._base((<ntl_ZZ_pX> self._poly)[n]._integer_())
+ 
+     def _unsafe_mutate(self, n, value):
+         n = int(n)
+         if n < 0:
+             raise IndexError("n must be >= 0")
+-        self.__poly[n] = int(value)
++        self._poly[n] = int(value)
+ 
+     def _pow(self, n):
+         n = int(n)
+@@ -218,10 +218,10 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             return self.parent()(self[0]**n)
+         if n < 0:
+             return (~self)**(-n)
+-        return self.parent()(self.__poly**n, construct=True)
++        return self.parent()(self._poly**n, construct=True)
+ 
+     cpdef _add_(self, right):
+-        return self.parent()(self.__poly + (<Polynomial_dense_mod_n>right).__poly, construct=True)
++        return self.parent()(self._poly + (<Polynomial_dense_mod_n>right)._poly, construct=True)
+ 
+     cpdef _mul_(self, right):
+         """
+@@ -231,11 +231,11 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             sage: (x - 2)*(x^2 - 8*x + 16)
+             x^3 + 90*x^2 + 32*x + 68
+         """
+-        return self.parent()(self.__poly * (<Polynomial_dense_mod_n>right).__poly, construct=True)
++        return self.parent()(self._poly * (<Polynomial_dense_mod_n>right)._poly, construct=True)
+ 
+     cpdef _lmul_(self, Element c):
+         try:
+-            return self.parent()(ZZ_pX([c], self.parent().modulus()) * self.__poly, construct=True)
++            return self.parent()(ZZ_pX([c], self.parent().modulus()) * self._poly, construct=True)
+         except RuntimeError as msg: # should this really be a TypeError
+             raise TypeError(msg)
+ 
+@@ -245,7 +245,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+         Return a tuple ``(quotient, remainder)`` where ``self = quotient*other +
+         remainder``.
+         """
+-        v = self.__poly.quo_rem((<Polynomial_dense_mod_n>right).__poly)
++        v = self._poly.quo_rem((<Polynomial_dense_mod_n>right)._poly)
+         P = self.parent()
+         return (P(v[0], construct=True), P(v[1], construct=True) )
+ 
+@@ -281,11 +281,11 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+         """
+         if n == 0 or self.degree() < 0:
+             return self
+-        return self.parent()(self.__poly.left_shift(n),
++        return self.parent()(self._poly.left_shift(n),
+                              construct=True)
+ 
+     cpdef _sub_(self, right):
+-        return self.parent()(self.__poly - (<Polynomial_dense_mod_n>right).__poly, construct=True)
++        return self.parent()(self._poly - (<Polynomial_dense_mod_n>right)._poly, construct=True)
+ 
+     def __floordiv__(self, right):
+         q, _ = self.quo_rem(right)
+@@ -314,7 +314,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             sage: isinstance(x.degree(), Integer)
+             True
+         """
+-        return smallInteger(max(self.__poly.degree(), -1))
++        return smallInteger(max(self._poly.degree(), -1))
+ 
+     cpdef list list(self, bint copy=True):
+         """
+@@ -358,7 +358,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+         """
+         if self.is_gen():
+             raise TypeError("Cannot change the value of the generator.")
+-        self.__poly = ZZ_pX(v, self.parent().modulus())
++        self._poly = ZZ_pX(v, self.parent().modulus())
+ 
+     # Polynomial_singular_repr stuff, copied due to lack of multiple inheritance
+     def _singular_(self, singular=singular_default, force=False):
+@@ -654,8 +654,8 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n):
+                 return
+ 
+         Polynomial_dense_mod_n.__init__(self, parent, v, check=check, is_gen=is_gen, construct=construct)
+-        v = [a for a in self.__poly.list()]
+-        self.__poly = None # this will eventually go away
++        v = [a for a in self._poly.list()]
++        self._poly = None # this will eventually go away
+         cdef ntl_zz_pX ntl = ntl_zz_pX(v, parent.modulus()) # let it handle the hard work
+         self.x = ntl.x
+         self.c = ntl.c
+@@ -668,8 +668,8 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n):
+         # TODO: Get rid of this
+         Polynomial_dense_mod_n.ntl_set_directly(self, v)
+         # verbatim from __init__
+-        v = [int(a) for a in self.__poly.list()]
+-        self.__poly = None # this will eventually go away
++        v = [int(a) for a in self._poly.list()]
++        self._poly = None # this will eventually go away
+         cdef ntl_zz_pX ntl = ntl_zz_pX(v, self._parent.modulus()) # let it handle the hard work
+         self.x = ntl.x
+         self.c = ntl.c
+@@ -1241,8 +1241,8 @@ cdef class Polynomial_dense_modn_ntl_ZZ(Polynomial_dense_mod_n):
+                 return
+ 
+         Polynomial_dense_mod_n.__init__(self, parent, v, check=check, is_gen=is_gen, construct=construct)
+-        cdef ntl_ZZ_pX ntl = self.__poly
+-        self.__poly = None # this will eventually go away
++        cdef ntl_ZZ_pX ntl = self._poly
++        self._poly = None # this will eventually go away
+         self.x = ntl.x
+         self.c = ntl.c
+ 
+diff --git a/src/sage/rings/polynomial/polynomial_rational_flint.pxd b/src/sage/rings/polynomial/polynomial_rational_flint.pxd
+index 055d7842668..f4644f19d04 100644
+--- a/src/sage/rings/polynomial/polynomial_rational_flint.pxd
++++ b/src/sage/rings/polynomial/polynomial_rational_flint.pxd
+@@ -11,7 +11,7 @@ from sage.libs.flint.types cimport fmpq_poly_t
+ from sage.rings.polynomial.polynomial_element cimport Polynomial
+ 
+ cdef class Polynomial_rational_flint(Polynomial):
+-    cdef fmpq_poly_t __poly
++    cdef fmpq_poly_t _poly
+ 
+     cdef Polynomial_rational_flint _new(self)
+     cpdef _mod_(self, right)
+diff --git a/src/sage/rings/polynomial/polynomial_rational_flint.pyx b/src/sage/rings/polynomial/polynomial_rational_flint.pyx
+index d0dd15522e9..26d070ac77f 100644
+--- a/src/sage/rings/polynomial/polynomial_rational_flint.pyx
++++ b/src/sage/rings/polynomial/polynomial_rational_flint.pyx
+@@ -155,16 +155,16 @@ cdef class Polynomial_rational_flint(Polynomial):
+         res._parent = P
+         res._is_gen = <char>0
+         if isinstance(x, int):
+-            fmpq_poly_set_si(res.__poly, <int> x)
++            fmpq_poly_set_si(res._poly, <int> x)
+ 
+         elif isinstance(x, Integer):
+-            fmpq_poly_set_mpz(res.__poly, (<Integer> x).value)
++            fmpq_poly_set_mpz(res._poly, (<Integer> x).value)
+ 
+         elif isinstance(x, Rational):
+-            fmpq_poly_set_mpq(res.__poly, (<Rational> x).value)
++            fmpq_poly_set_mpq(res._poly, (<Rational> x).value)
+ 
+         else:
+-            fmpq_poly_set_si(res.__poly, int(x))
++            fmpq_poly_set_si(res._poly, int(x))
+         return res
+ 
+ 
+@@ -177,7 +177,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: R.<t> = QQ[]
+             sage: f = 2/3 * t - 7  #indirect doctest
+         """
+-        fmpq_poly_init(self.__poly)
++        fmpq_poly_init(self._poly)
+ 
+     def __dealloc__(self):
+         """
+@@ -189,7 +189,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: f = 1/3 * t
+             sage: del f
+         """
+-        fmpq_poly_clear(self.__poly)
++        fmpq_poly_clear(self._poly)
+ 
+     def __init__(self, parent, x=None, check=True, is_gen=False, construct=False):
+         """
+@@ -227,19 +227,19 @@ cdef class Polynomial_rational_flint(Polynomial):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+ 
+         if is_gen:
+-            fmpq_poly_set_coeff_si(self.__poly, 1, 1)
++            fmpq_poly_set_coeff_si(self._poly, 1, 1)
+ 
+         elif isinstance(x, Polynomial_rational_flint):
+-            fmpq_poly_set(self.__poly, (<Polynomial_rational_flint> x).__poly)
++            fmpq_poly_set(self._poly, (<Polynomial_rational_flint> x)._poly)
+ 
+         elif isinstance(x, int):
+-            fmpq_poly_set_si(self.__poly, <int> x)
++            fmpq_poly_set_si(self._poly, <int> x)
+ 
+         elif isinstance(x, Integer):
+-            fmpq_poly_set_mpz(self.__poly, (<Integer> x).value)
++            fmpq_poly_set_mpz(self._poly, (<Integer> x).value)
+ 
+         elif isinstance(x, Rational):
+-            fmpq_poly_set_mpq(self.__poly, (<Rational> x).value)
++            fmpq_poly_set_mpq(self._poly, (<Rational> x).value)
+ 
+         elif isinstance(x, list) or isinstance(x, tuple):
+ 
+@@ -257,7 +257,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             for deg from 0 <= deg < n:
+                 mpq_init(L2[deg])
+                 mpq_set(L2[deg], (<Rational> L1[deg]).value)
+-            fmpq_poly_set_array_mpq(self.__poly, L2, n)
++            fmpq_poly_set_array_mpq(self._poly, L2, n)
+             for deg from 0 <= deg < n:
+                 mpq_clear(L2[deg])
+             sig_free(L2)
+@@ -266,13 +266,13 @@ cdef class Polynomial_rational_flint(Polynomial):
+ #           deg = 0
+ #           for e in x:
+ #               c = Rational(e)
+-#               fmpq_poly_set_coeff_mpq(self.__poly, deg, c.value)
++#               fmpq_poly_set_coeff_mpq(self._poly, deg, c.value)
+ #               deg += 1
+ 
+         elif isinstance(x, dict):
+             for deg, e in x.iteritems():
+                 c = Rational(e)
+-                fmpq_poly_set_coeff_mpq(self.__poly, deg, c.value)
++                fmpq_poly_set_coeff_mpq(self._poly, deg, c.value)
+ 
+         elif isinstance(x, pari_gen):
+             k = self._parent.base_ring()
+@@ -281,7 +281,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+                                              is_gen=False, construct=construct)
+ 
+         elif isinstance(x, Polynomial_integer_dense_flint):
+-            fmpq_poly_set_fmpz_poly(self.__poly, (<Polynomial_integer_dense_flint>x).__poly)
++            fmpq_poly_set_fmpz_poly(self._poly, (<Polynomial_integer_dense_flint>x)._poly)
+ 
+         elif isinstance(x, Polynomial):
+             k = self._parent.base_ring()
+@@ -329,7 +329,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             True
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        fmpq_poly_set(res.__poly, self.__poly)
++        fmpq_poly_set(res._poly, self._poly)
+         return res
+ 
+     def _singular_(self, singular=singular_default):
+@@ -364,7 +364,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: g.list()
+             []
+         """
+-        cdef unsigned long length = fmpq_poly_length(self.__poly)
++        cdef unsigned long length = fmpq_poly_length(self._poly)
+         return [self.get_unsafe(n) for n in range(length)]
+ 
+     ###########################################################################
+@@ -392,7 +392,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: type(f.degree())
+             <class 'sage.rings.integer.Integer'>
+         """
+-        return smallInteger(fmpq_poly_degree(self.__poly))
++        return smallInteger(fmpq_poly_degree(self._poly))
+ 
+     cdef get_unsafe(self, Py_ssize_t n):
+         """
+@@ -413,7 +413,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             1/2*t^2 + t + 1
+         """
+         cdef Rational z = Rational.__new__(Rational)
+-        fmpq_poly_get_coeff_mpq(z.value, self.__poly, n)
++        fmpq_poly_get_coeff_mpq(z.value, self._poly, n)
+         return z
+ 
+     cpdef _unsafe_mutate(self, unsigned long n, value):
+@@ -434,24 +434,24 @@ cdef class Polynomial_rational_flint(Polynomial):
+         rely on this convention.  This method should be used only with the
+         utmost care.
+         """
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if isinstance(value, int):
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_si(self.__poly, n, value)
++            fmpq_poly_set_coeff_si(self._poly, n, value)
+             if do_sig: sig_off()
+         elif isinstance(value, Integer):
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_mpz(self.__poly, n, (<Integer> value).value)
++            fmpq_poly_set_coeff_mpz(self._poly, n, (<Integer> value).value)
+             if do_sig: sig_off()
+         elif isinstance(value, Rational):
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_mpq(self.__poly, n, (<Rational> value).value)
++            fmpq_poly_set_coeff_mpq(self._poly, n, (<Rational> value).value)
+             if do_sig: sig_off()
+         else:
+             value = Rational(value)
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_mpq(self.__poly, n, (<Rational> value).value)
++            fmpq_poly_set_coeff_mpq(self._poly, n, (<Rational> value).value)
+             if do_sig: sig_off()
+ 
+     def __call__(self, *x, **kwds):
+@@ -501,20 +501,20 @@ cdef class Polynomial_rational_flint(Polynomial):
+             if isinstance(a, Polynomial_rational_flint):
+                 f = (<Polynomial_rational_flint> a)._new()
+                 sig_str("FLINT exception")
+-                fmpq_poly_compose(f.__poly, self.__poly,
+-                    (<Polynomial_rational_flint> a).__poly)
++                fmpq_poly_compose(f._poly, self._poly,
++                    (<Polynomial_rational_flint> a)._poly)
+                 sig_off()
+                 return f
+             elif isinstance(a, Rational):
+                 r = Rational.__new__(Rational)
+                 sig_str("FLINT exception")
+-                fmpq_poly_evaluate_mpq(r.value, self.__poly, (<Rational> a).value)
++                fmpq_poly_evaluate_mpq(r.value, self._poly, (<Rational> a).value)
+                 sig_off()
+                 return r
+             elif isinstance(a, Integer):
+                 r = Rational.__new__(Rational)
+                 sig_str("FLINT exception")
+-                fmpq_poly_evaluate_mpz(r.value, self.__poly, (<Integer> a).value)
++                fmpq_poly_evaluate_mpz(r.value, self._poly, (<Integer> a).value)
+                 sig_off()
+                 return r
+             elif isinstance(a, int):
+@@ -523,7 +523,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+                 fmpz_init(tmpfz)
+                 fmpq_init(tmpfq)
+                 fmpz_set_si(tmpfz, PyInt_AS_LONG(a))
+-                fmpq_poly_evaluate_fmpz(tmpfq, self.__poly, tmpfz)
++                fmpq_poly_evaluate_fmpz(tmpfq, self._poly, tmpfz)
+                 fmpq_get_mpq(r.value, tmpfq)
+                 fmpq_clear(tmpfq)
+                 fmpz_clear(tmpfz)
+@@ -533,18 +533,18 @@ cdef class Polynomial_rational_flint(Polynomial):
+                 arb_a = <RealBall> a
+                 arb_z = arb_a._new()
+                 sig_on()
+-                _arb_fmpz_poly_evaluate_arb(arb_z.value, fmpq_poly_numref(self.__poly),
+-                        fmpq_poly_length(self.__poly), arb_a.value, arb_a._parent._prec)
+-                arb_div_fmpz(arb_z.value, arb_z.value, fmpq_poly_denref(self.__poly), arb_a._parent._prec)
++                _arb_fmpz_poly_evaluate_arb(arb_z.value, fmpq_poly_numref(self._poly),
++                        fmpq_poly_length(self._poly), arb_a.value, arb_a._parent._prec)
++                arb_div_fmpz(arb_z.value, arb_z.value, fmpq_poly_denref(self._poly), arb_a._parent._prec)
+                 sig_off()
+                 return arb_z
+             if isinstance(a, ComplexBall):
+                 acb_a = <ComplexBall> a
+                 acb_z = acb_a._new()
+                 sig_on()
+-                _arb_fmpz_poly_evaluate_acb(acb_z.value, fmpq_poly_numref(self.__poly),
+-                        fmpq_poly_length(self.__poly), acb_a.value, acb_a._parent._prec)
+-                acb_div_fmpz(acb_z.value, acb_z.value, fmpq_poly_denref(self.__poly), acb_a._parent._prec)
++                _arb_fmpz_poly_evaluate_acb(acb_z.value, fmpq_poly_numref(self._poly),
++                        fmpq_poly_length(self._poly), acb_a.value, acb_a._parent._prec)
++                acb_div_fmpz(acb_z.value, acb_z.value, fmpq_poly_denref(self._poly), acb_a._parent._prec)
+                 sig_off()
+                 return acb_z
+ 
+@@ -570,14 +570,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res
+         cdef bint do_sig
+ 
+-        if (n >= fmpq_poly_length(self.__poly)):
++        if (n >= fmpq_poly_length(self._poly)):
+             return self
+         else:
+             res = self._new()
+             if n > 0:
+-                do_sig = _do_sig(self.__poly)
++                do_sig = _do_sig(self._poly)
+                 if do_sig: sig_str("FLINT exception")
+-                fmpq_poly_get_slice(res.__poly, self.__poly, 0, n)
++                fmpq_poly_get_slice(res._poly, self._poly, 0, n)
+                 if do_sig: sig_off()
+             return res
+ 
+@@ -664,7 +664,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef bint do_sig
+ 
+         if degree is None:
+-            len = fmpq_poly_length(self.__poly)
++            len = fmpq_poly_length(self._poly)
+         else:
+             try:
+                 len = <unsigned long> (degree + 1)
+@@ -672,9 +672,9 @@ cdef class Polynomial_rational_flint(Polynomial):
+                 raise ValueError('degree must be convertible to long')
+ 
+         res = self._new()
+-        do_sig = _do_sig(self.__poly)
++        do_sig = _do_sig(self._poly)
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_reverse(res.__poly, self.__poly, len)
++        fmpq_poly_reverse(res._poly, self._poly, len)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -709,7 +709,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             raise ValueError("self must have constant coefficient 0 and a unit for coefficient {}^1".format(self.parent().gen()))
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_revert_series(res.__poly, self.__poly, m)
++        fmpq_poly_revert_series(res._poly, self._poly, m)
+         sig_off()
+ 
+         return res
+@@ -731,7 +731,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: R(0).is_zero()
+             True
+         """
+-        return fmpq_poly_is_zero(self.__poly)
++        return fmpq_poly_is_zero(self._poly)
+ 
+     cpdef bint is_one(self) except -1:
+         r"""
+@@ -751,7 +751,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: R([1,1]).is_one()
+             False
+         """
+-        return fmpq_poly_is_one(self.__poly)
++        return fmpq_poly_is_one(self._poly)
+ 
+     def __bool__(self):
+         """
+@@ -766,7 +766,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: bool(R(0))
+             False
+         """
+-        return not fmpq_poly_is_zero(self.__poly)
++        return not fmpq_poly_is_zero(self._poly)
+ 
+     ###########################################################################
+     # Shifting                                                                #
+@@ -794,14 +794,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res
+         cdef bint do_sig
+ 
+-        if k == 0 or fmpq_poly_is_zero(f.__poly):
++        if k == 0 or fmpq_poly_is_zero(f._poly):
+             return self
+         else:
+             res = f._new()
+-            do_sig = fmpq_poly_length(f.__poly) > 5000 or n > 5000
++            do_sig = fmpq_poly_length(f._poly) > 5000 or n > 5000
+ 
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_shift_left(res.__poly, f.__poly, k)
++            fmpq_poly_shift_left(res._poly, f._poly, k)
+             if do_sig: sig_off()
+             return res
+ 
+@@ -822,14 +822,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res
+         cdef bint do_sig
+ 
+-        if k == 0 or fmpq_poly_is_zero(f.__poly):
++        if k == 0 or fmpq_poly_is_zero(f._poly):
+             return self
+         else:
+             res = f._new()
+-            do_sig = _do_sig(f.__poly)
++            do_sig = _do_sig(f._poly)
+ 
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_shift_right(res.__poly, f.__poly, k)
++            fmpq_poly_shift_right(res._poly, f._poly, k)
+             if do_sig: sig_off()
+             return res
+ 
+@@ -858,10 +858,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_add(res.__poly, self.__poly, op2.__poly)
++        fmpq_poly_add(res._poly, self._poly, op2._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -886,10 +886,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_sub(res.__poly, self.__poly, op2.__poly)
++        fmpq_poly_sub(res._poly, self._poly, op2._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -912,10 +912,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             True
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_neg(res.__poly, self.__poly)
++        fmpq_poly_neg(res._poly, self._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -945,8 +945,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint rr = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_divrem(qq.__poly, rr.__poly, self.__poly,
+-                         (<Polynomial_rational_flint> right).__poly)
++        fmpq_poly_divrem(qq._poly, rr._poly, self._poly,
++                         (<Polynomial_rational_flint> right)._poly)
+         sig_off()
+         return qq, rr
+ 
+@@ -974,8 +974,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_gcd(res.__poly, self.__poly,
+-                (<Polynomial_rational_flint> right).__poly)
++        fmpq_poly_gcd(res._poly, self._poly,
++                (<Polynomial_rational_flint> right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1001,8 +1001,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_lcm(res.__poly, self.__poly,
+-                      (<Polynomial_rational_flint> right).__poly)
++        fmpq_poly_lcm(res._poly, self._poly,
++                      (<Polynomial_rational_flint> right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1043,7 +1043,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint t = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_xgcd(d.__poly, s.__poly, t.__poly, self.__poly, (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_xgcd(d._poly, s._poly, t._poly, self._poly, (<Polynomial_rational_flint>right)._poly)
+         sig_off()
+         return d, s, t
+ 
+@@ -1069,10 +1069,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_mul(res.__poly, self.__poly, op2.__poly)
++        fmpq_poly_mul(res._poly, self._poly, op2._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -1103,13 +1103,13 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if n <= 0:
+             raise ValueError("n must be > 0")
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_mullow(res.__poly, self.__poly, op2.__poly, n)
++        fmpq_poly_mullow(res._poly, self._poly, op2._poly, n)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -1125,10 +1125,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             9*t^3 - 6*t + 2
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_scalar_mul_mpq(res.__poly, self.__poly,
++        fmpq_poly_scalar_mul_mpq(res._poly, self._poly,
+                                  (<Rational> left).value)
+         if do_sig: sig_off()
+         return res
+@@ -1145,10 +1145,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             9*t^3 - 6*t + 2
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_scalar_mul_mpq(res.__poly, self.__poly,
++        fmpq_poly_scalar_mul_mpq(res._poly, self._poly,
+                                  (<Rational> right).value)
+         if do_sig: sig_off()
+         return res
+@@ -1272,27 +1272,27 @@ cdef class Polynomial_rational_flint(Polynomial):
+             num = r.numerator()
+             den = r.denominator()
+ 
+-            if fmpq_poly_degree(self.__poly) == 0:
++            if fmpq_poly_degree(self._poly) == 0:
+                 return self.parent()(self[0].nth_root(den) ** num)
+ 
+             return self.nth_root(den) ** num
+ 
+         else:
+             if n < 0:
+-                if fmpq_poly_is_zero(self.__poly):
++                if fmpq_poly_is_zero(self._poly):
+                     raise ZeroDivisionError("negative exponent in power of zero")
+                 res = self._new()
+                 sig_str("FLINT exception")
+-                fmpq_poly_pow(res.__poly, self.__poly, -n)
++                fmpq_poly_pow(res._poly, self._poly, -n)
+                 sig_off()
+                 return ~res
+             else:
+                 res = self._new()
+                 sig_str("FLINT exception")
+                 if self._is_gen:
+-                    fmpq_poly_set_coeff_si(res.__poly, n, 1)
++                    fmpq_poly_set_coeff_si(res._poly, n, 1)
+                 else:
+-                    fmpq_poly_pow(res.__poly, self.__poly, n)
++                    fmpq_poly_pow(res._poly, self._poly, n)
+                 sig_off()
+                 return res
+ 
+@@ -1328,10 +1328,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         if not isinstance(right, Polynomial_rational_flint):
+             if right in QQ:
+                 res = self._new()
+-                do_sig = _do_sig(self.__poly)
++                do_sig = _do_sig(self._poly)
+ 
+                 if do_sig: sig_str("FLINT exception")
+-                fmpq_poly_scalar_div_mpq(res.__poly, self.__poly,
++                fmpq_poly_scalar_div_mpq(res._poly, self._poly,
+                                                   (<Rational> QQ(right)).value)
+                 if do_sig: sig_off()
+                 return res
+@@ -1340,8 +1340,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+ 
+         res = self._new()
+         sig_str("FLINT exception")
+-        fmpq_poly_div(res.__poly, self.__poly,
+-                                     (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_div(res._poly, self._poly,
++                                     (<Polynomial_rational_flint>right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1381,15 +1381,15 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         if prec <= 0:
+             raise ValueError("the precision must be positive, got {}".format(prec))
+-        if fmpq_poly_degree(self.__poly) == -1 or \
+-           fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        if fmpq_poly_degree(self._poly) == -1 or \
++           fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term is zero")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         if prec <= 0:
+             return res
+         sig_on()
+-        fmpq_poly_inv_series(res.__poly, self.__poly, prec)
++        fmpq_poly_inv_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1423,8 +1423,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+ 
+         res = self._new()
+         sig_str("FLINT exception")
+-        fmpq_poly_rem(res.__poly, self.__poly,
+-                                     (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_rem(res._poly, self._poly,
++                                     (<Polynomial_rational_flint>right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1453,7 +1453,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+         Polynomial_integer_dense_flint.__init__(num, parent, x=None,
+                                     check=False, is_gen=False, construct=False)
+         sig_str("FLINT exception")
+-        fmpq_poly_get_numerator(num.__poly, self.__poly)
++        fmpq_poly_get_numerator(num._poly, self._poly)
+         sig_off()
+         return num
+ 
+@@ -1469,10 +1469,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             3
+         """
+         cdef Integer den = Integer.__new__(Integer)
+-        if fmpq_poly_denref(self.__poly) is NULL:
++        if fmpq_poly_denref(self._poly) is NULL:
+             mpz_set_ui(den.value, 1)
+         else:
+-            fmpz_get_mpz(den.value, <fmpz *> fmpq_poly_denref(self.__poly))
++            fmpz_get_mpz(den.value, <fmpz *> fmpq_poly_denref(self._poly))
+         return den
+ 
+     def _derivative(self, var = None):
+@@ -1517,10 +1517,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             raise ValueError("cannot differentiate with respect to {}".format(var))
+ 
+         der = self._new()
+-        do_sig = _do_sig(self.__poly)
++        do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_derivative(der.__poly, self.__poly)
++        fmpq_poly_derivative(der._poly, self._poly)
+         if do_sig: sig_off()
+         return der
+ 
+@@ -1574,8 +1574,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef fmpq_t t
+         fmpq_init(t)
+         sig_str("FLINT exception")
+-        fmpq_poly_resultant(t, self.__poly,
+-                            (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_resultant(t, self._poly,
++                            (<Polynomial_rational_flint>right)._poly)
+         fmpq_get_mpq(res.value, t)
+         sig_off()
+         fmpq_clear(t)
+@@ -1623,7 +1623,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+ 
+         """
+         cdef Polynomial_integer_dense_flint primitive
+-        cdef unsigned long length = fmpq_poly_length(self.__poly)
++        cdef unsigned long length = fmpq_poly_length(self._poly)
+ 
+         if length < 2:
+             return False
+@@ -1636,8 +1636,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+                              x=None, check=True, is_gen=False, construct=False)
+ 
+             sig_str("FLINT exception")
+-            fmpq_poly_get_numerator(primitive.__poly, self.__poly)
+-            fmpz_poly_primitive_part(primitive.__poly, primitive.__poly)
++            fmpq_poly_get_numerator(primitive._poly, self._poly)
++            fmpz_poly_primitive_part(primitive._poly, primitive._poly)
+             sig_off()
+             return primitive.is_irreducible()
+ 
+@@ -1669,14 +1669,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             ...
+             ValueError: constant term should be 1 in order to take logarithm
+         """
+-        if fmpq_poly_degree(self.__poly) == -1 or \
+-           fmpz_cmp(fmpq_poly_numref(self.__poly),
+-                    fmpq_poly_denref(self.__poly)):
++        if fmpq_poly_degree(self._poly) == -1 or \
++           fmpz_cmp(fmpq_poly_numref(self._poly),
++                    fmpq_poly_denref(self._poly)):
+             raise ValueError("constant term should be 1 in order to take logarithm")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_log_series(res.__poly, self.__poly, prec)
++        fmpq_poly_log_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1703,14 +1703,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.one()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take exponential")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_exp_series(res.__poly, self.__poly, prec)
++        fmpq_poly_exp_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1737,14 +1737,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take arctangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_atan_series(res.__poly, self.__poly, prec)
++        fmpq_poly_atan_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1768,14 +1768,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic arctangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_atanh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_atanh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1802,14 +1802,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take arcsine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_asin_series(res.__poly, self.__poly, prec)
++        fmpq_poly_asin_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1837,14 +1837,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic arcsine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_asinh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_asinh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1871,14 +1871,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take tangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_tan_series(res.__poly, self.__poly, prec)
++        fmpq_poly_tan_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1905,14 +1905,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take sine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_sin_series(res.__poly, self.__poly, prec)
++        fmpq_poly_sin_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1937,14 +1937,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take cosine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_cos_series(res.__poly, self.__poly, prec)
++        fmpq_poly_cos_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1969,14 +1969,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic sine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_sinh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_sinh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -2007,14 +2007,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.one()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic cosine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_cosh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_cosh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -2040,14 +2040,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic tangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_tanh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_tanh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+diff --git a/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx b/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx
+index fbe96d186c5..955f83468e4 100644
+--- a/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx
++++ b/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx
+@@ -116,7 +116,7 @@ cdef class PolynomialRealDense(Polynomial):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+         self._base_ring = parent._base
+         cdef Py_ssize_t i, degree
+-        cdef int prec = self._base_ring.__prec
++        cdef int prec = self._base_ring._prec
+         cdef mpfr_rnd_t rnd = self._base_ring.rnd
+         if x is None:
+             self._coeffs = <mpfr_t*>check_allocarray(1, sizeof(mpfr_t)) # degree zero
+@@ -227,7 +227,7 @@ cdef class PolynomialRealDense(Polynomial):
+ 
+     cdef PolynomialRealDense _new(self, Py_ssize_t degree):
+         cdef Py_ssize_t i
+-        cdef int prec = self._base_ring.__prec
++        cdef int prec = self._base_ring._prec
+         cdef PolynomialRealDense f = <PolynomialRealDense>PolynomialRealDense.__new__(PolynomialRealDense)
+         f._parent = self._parent
+         f._base_ring = self._base_ring
+@@ -501,7 +501,7 @@ cdef class PolynomialRealDense(Polynomial):
+         else:
+             f = left._new(left._degree + right._degree)
+         sig_on()
+-        mpfr_init2(tmp, left._base_ring.__prec)
++        mpfr_init2(tmp, left._base_ring._prec)
+         for i from 0 <= i <= f._degree:
+             # Yes, we could make this more efficient by initializing with
+             # a multiple of left rather than all zeros...
+@@ -661,7 +661,7 @@ cdef class PolynomialRealDense(Polynomial):
+         q = self._new(self._degree - other._degree)
+         # This is the standard division algorithm
+         sig_on()
+-        mpfr_init2(tmp, self._base_ring.__prec)
++        mpfr_init2(tmp, self._base_ring._prec)
+         for i from self._degree >= i >= other._degree:
+             mpfr_set(q._coeffs[i-other._degree], r._coeffs[i], rnd)
+             for j from 0 <= j < other._degree:
+@@ -725,7 +725,7 @@ cdef class PolynomialRealDense(Polynomial):
+         cdef RealNumber x = <RealNumber>xx
+         cdef RealNumber res
+ 
+-        if (<RealField_class>x._parent).__prec < self._base_ring.__prec:
++        if (<RealField_class>x._parent)._prec < self._base_ring._prec:
+             res = RealNumber(x._parent)
+         else:
+             res = RealNumber(self._base_ring)
+diff --git a/src/sage/rings/polynomial/polynomial_zmod_flint.pyx b/src/sage/rings/polynomial/polynomial_zmod_flint.pyx
+index 253ab949fcc..4c480673861 100644
+--- a/src/sage/rings/polynomial/polynomial_zmod_flint.pyx
++++ b/src/sage/rings/polynomial/polynomial_zmod_flint.pyx
+@@ -110,7 +110,7 @@ cdef class Polynomial_zmod_flint(Polynomial_template):
+             return
+         elif isinstance(x, Polynomial_integer_dense_flint):
+             Polynomial_template.__init__(self, parent, 0, check, is_gen, construct)
+-            self._set_fmpz_poly((<Polynomial_integer_dense_flint>x).__poly)
++            self._set_fmpz_poly((<Polynomial_integer_dense_flint>x)._poly)
+             return
+         else:
+             if isinstance(x, ntl_zz_pX):
+diff --git a/src/sage/rings/power_series_mpoly.pxd b/src/sage/rings/power_series_mpoly.pxd
+index f822ecc1227..d358ada1356 100644
+--- a/src/sage/rings/power_series_mpoly.pxd
++++ b/src/sage/rings/power_series_mpoly.pxd
+@@ -3,6 +3,6 @@ from .power_series_ring_element cimport PowerSeries
+ 
+ cdef class PowerSeries_mpoly(PowerSeries):
+     cdef ModuleElement __f
+-    cdef object __poly
++    cdef object _poly
+     cdef object __list
+     cdef bint _truncated
+diff --git a/src/sage/rings/power_series_mpoly.pyx b/src/sage/rings/power_series_mpoly.pyx
+index 0c901a3557b..be59294e75b 100644
+--- a/src/sage/rings/power_series_mpoly.pyx
++++ b/src/sage/rings/power_series_mpoly.pyx
+@@ -65,7 +65,7 @@ cdef class PowerSeries_mpoly(PowerSeries):
+ 
+     def __reduce__(self):
+         # do *not* delete old versions.
+-        return make_powerseries_mpoly_v0, (self._parent, self.__f, self._prec, self.__is_gen)
++        return make_powerseries_mpoly_v0, (self._parent, self.__f, self._prec, self._is_gen)
+ 
+     def __call__(self, *args, **kwds):
+         if len(kwds) == 0 and len(args) == 1:
+@@ -92,10 +92,10 @@ cdef class PowerSeries_mpoly(PowerSeries):
+         return self.__list
+ 
+     def polynomial(self):
+-        if self.__poly is None:
++        if self._poly is None:
+             S = self.parent()._mpoly_ring()
+-            self.__poly = self.__f.polynomial(S.gens()[-1])
+-        return self.__poly
++            self._poly = self.__f.polynomial(S.gens()[-1])
++        return self._poly
+ 
+     def _mpoly(self):
+         return self.__f
+diff --git a/src/sage/rings/power_series_poly.pyx b/src/sage/rings/power_series_poly.pyx
+index 7c93168d4b1..6cacab1f0c8 100644
+--- a/src/sage/rings/power_series_poly.pyx
++++ b/src/sage/rings/power_series_poly.pyx
+@@ -97,7 +97,7 @@ cdef class PowerSeries_poly(PowerSeries):
+             sage: f == loads(dumps(f)) # indirect doctest
+             True
+         """
+-        return self.__class__, (self._parent, self.__f, self._prec, self.__is_gen)
++        return self.__class__, (self._parent, self.__f, self._prec, self._is_gen)
+ 
+     def polynomial(self):
+         """
+diff --git a/src/sage/rings/power_series_ring_element.pxd b/src/sage/rings/power_series_ring_element.pxd
+index 067c4f3c6d4..e5c031ee147 100644
+--- a/src/sage/rings/power_series_ring_element.pxd
++++ b/src/sage/rings/power_series_ring_element.pxd
+@@ -1,7 +1,7 @@
+ from sage.structure.element cimport AlgebraElement, RingElement
+ 
+ cdef class PowerSeries(AlgebraElement):
+-    cdef char __is_gen
++    cdef char _is_gen
+     cdef _prec
+     cdef common_prec_c(self, PowerSeries other)
+     #_prec(self, RingElement right_r)
+diff --git a/src/sage/rings/power_series_ring_element.pyx b/src/sage/rings/power_series_ring_element.pyx
+index 54314d538ed..e5e2df79e1b 100644
+--- a/src/sage/rings/power_series_ring_element.pyx
++++ b/src/sage/rings/power_series_ring_element.pyx
+@@ -159,7 +159,7 @@ cdef class PowerSeries(AlgebraElement):
+              over Finite Field of size 3
+         """
+         AlgebraElement.__init__(self, parent)
+-        self.__is_gen = is_gen
++        self._is_gen = is_gen
+         self._prec = prec
+ 
+     def __hash__(self):
+@@ -234,7 +234,7 @@ cdef class PowerSeries(AlgebraElement):
+             sage: 1*t == t
+             True
+         """
+-        return bool(self.__is_gen)
++        return bool(self._is_gen)
+ 
+     def _im_gens_(self, codomain, im_gens, base_map=None):
+         """
+diff --git a/src/sage/rings/real_mpfi.pxd b/src/sage/rings/real_mpfi.pxd
+index 959a650aafc..4201788d198 100644
+--- a/src/sage/rings/real_mpfi.pxd
++++ b/src/sage/rings/real_mpfi.pxd
+@@ -11,7 +11,7 @@ from .real_mpfr cimport RealField_class
+ cdef class RealIntervalFieldElement(RingElement)  # forward decl
+ 
+ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+-    cdef mpfr_prec_t __prec
++    cdef mpfr_prec_t _prec
+     cdef bint sci_not
+     # Cache RealField instances for the lower, upper, and middle bounds.
+     # These have the same precision as the interval field;
+diff --git a/src/sage/rings/real_mpfi.pyx b/src/sage/rings/real_mpfi.pyx
+index 1193a14baff..509f6f63da0 100644
+--- a/src/sage/rings/real_mpfi.pyx
++++ b/src/sage/rings/real_mpfi.pyx
+@@ -526,7 +526,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         if prec < MPFR_PREC_MIN or prec > MPFR_PREC_MAX:
+             raise ValueError("prec (=%s) must be >= %s and <= %s." % (
+                 prec, MPFR_PREC_MIN, MPFR_PREC_MAX))
+-        self.__prec = prec
++        self._prec = prec
+         self.sci_not = sci_not
+         self.__lower_field = RealField(prec, sci_not, "RNDD")
+         self.__middle_field = RealField(prec, sci_not, "RNDN")
+@@ -598,7 +598,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         elif rnd == "RNDU":
+             return self.upper_field()
+         else:
+-            return RealField(self.__prec, self.sci_not, rnd)
++            return RealField(self._prec, self.sci_not, rnd)
+ 
+     def _repr_(self):
+         """
+@@ -611,7 +611,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RealIntervalField(200) # indirect doctest
+             Real Interval Field with 200 bits of precision
+         """
+-        s = "Real Interval Field with %s bits of precision"%self.__prec
++        s = "Real Interval Field with %s bits of precision"%self._prec
+         return s
+ 
+     def _latex_(self):
+@@ -802,7 +802,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RIF.has_coerce_map_from(float)
+             False
+         """
+-        prec = self.__prec
++        prec = self._prec
+ 
+         # Direct and efficient conversions
+         if S is ZZ or S is QQ:
+@@ -810,7 +810,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         if S is int or S is long:
+             return True
+         if isinstance(S, RealIntervalField_class):
+-            return (<RealIntervalField_class>S).__prec >= prec
++            return (<RealIntervalField_class>S)._prec >= prec
+         if isinstance(S, sage.rings.abc.NumberField_quadratic):
+             return S.discriminant() > 0
+ 
+@@ -844,7 +844,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         cdef RealIntervalField_class right
+         left = self
+         right = other  # to access C structure
+-        return richcmp(left.__prec, right.__prec, op)
++        return richcmp(left._prec, right._prec, op)
+ 
+     def __reduce__(self):
+         """
+@@ -856,7 +856,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: loads(dumps(R)) == R
+             True
+         """
+-        return __create__RealIntervalField_version0, (self.__prec, self.sci_not)
++        return __create__RealIntervalField_version0, (self._prec, self.sci_not)
+ 
+     def random_element(self, *args, **kwds):
+         """
+@@ -997,7 +997,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RealIntervalField(200).name()
+             'IntervalRealIntervalField200'
+         """
+-        return "IntervalRealIntervalField%s"%(self.__prec)
++        return "IntervalRealIntervalField%s"%(self._prec)
+ 
+     def __hash__(self):
+         """
+@@ -1023,7 +1023,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RealIntervalField(200).precision()
+             200
+         """
+-        return self.__prec
++        return self._prec
+ 
+     prec = precision
+ 
+@@ -1187,7 +1187,7 @@ cdef class RealIntervalFieldElement(RingElement):
+             sage: TestSuite(x).run(skip=["_test_eq", "_test_pickling"])
+         """
+         cdef RealIntervalField_class p = <RealIntervalField_class?>parent
+-        mpfi_init2(self.value, p.__prec)
++        mpfi_init2(self.value, p._prec)
+         self._parent = p
+ 
+     def __init__(self, parent, x, int base=10):
+@@ -1864,7 +1864,7 @@ cdef class RealIntervalFieldElement(RingElement):
+ 
+         cdef mp_exp_t self_exp
+         cdef mpz_t self_zz
+-        cdef mpfr_prec_t prec = (<RealIntervalField_class>self._parent).__prec
++        cdef mpfr_prec_t prec = (<RealIntervalField_class>self._parent)._prec
+         cdef char *zz_str
+         cdef size_t zz_str_maxlen
+ 
+@@ -2977,7 +2977,7 @@ cdef class RealIntervalFieldElement(RingElement):
+             sage: RealIntervalField(200)(2.1).precision()
+             200
+         """
+-        return (<RealIntervalField_class>self._parent).__prec
++        return (<RealIntervalField_class>self._parent)._prec
+ 
+     prec = precision
+ 
+diff --git a/src/sage/rings/real_mpfr.pxd b/src/sage/rings/real_mpfr.pxd
+index 3549eccfd03..dd18e87715b 100644
+--- a/src/sage/rings/real_mpfr.pxd
++++ b/src/sage/rings/real_mpfr.pxd
+@@ -9,7 +9,7 @@ from sage.libs.mpfr.types cimport mpfr_prec_t
+ cdef class RealNumber(sage.structure.element.RingElement)  # forward decl
+ 
+ cdef class RealField_class(sage.rings.abc.RealField):
+-    cdef mpfr_prec_t __prec
++    cdef mpfr_prec_t _prec
+     cdef bint sci_not
+     cdef mpfr_rnd_t rnd
+     cdef object rnd_str
+diff --git a/src/sage/rings/real_mpfr.pyx b/src/sage/rings/real_mpfr.pyx
+index ea7ff07a216..7440fadd265 100644
+--- a/src/sage/rings/real_mpfr.pyx
++++ b/src/sage/rings/real_mpfr.pyx
+@@ -524,7 +524,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+         if prec < MPFR_PREC_MIN or prec > MPFR_PREC_MAX:
+             raise ValueError("prec (=%s) must be >= %s and <= %s" % (
+                 prec, MPFR_PREC_MIN, MPFR_PREC_MAX))
+-        self.__prec = prec
++        self._prec = prec
+         self.sci_not = sci_not
+ 
+         self.rnd = <mpfr_rnd_t>rnd
+@@ -561,7 +561,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: RealField(17,rnd='RNDD') # indirect doctest
+             Real Field with 17 bits of precision and rounding RNDD
+         """
+-        s = "Real Field with %s bits of precision"%self.__prec
++        s = "Real Field with %s bits of precision"%self._prec
+         if self.rnd != MPFR_RNDN:
+             s = s + " and rounding %s"%(self.rnd_str)
+         return s
+@@ -733,13 +733,13 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             return ZZtoRR(ZZ, self)
+         elif S is QQ:
+             return QQtoRR(QQ, self)
+-        elif (S is RDF or S is float) and self.__prec <= 53:
++        elif (S is RDF or S is float) and self._prec <= 53:
+             return double_toRR(S, self)
+         elif S is long:
+             return int_toRR(long, self)
+         elif S is int:
+             return int_toRR(int, self)
+-        elif isinstance(S, RealField_class) and S.prec() >= self.__prec:
++        elif isinstance(S, RealField_class) and S.prec() >= self._prec:
+             return RRtoRR(S, self)
+         elif QQ.has_coerce_map_from(S):
+             return QQtoRR(QQ, self) * QQ._internal_coerce_map_from(S)
+@@ -786,7 +786,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             return NotImplemented
+ 
+         _other = <RealField_class>other  # to access C structure
+-        return (self.__prec == _other.__prec and
++        return (self._prec == _other._prec and
+                 self.rnd == _other.rnd) == (op == Py_EQ)
+ 
+     def __reduce__(self):
+@@ -799,7 +799,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: loads(dumps(R)) == R
+             True
+         """
+-        return __create__RealField_version0, (self.__prec, self.sci_not, self.rnd_str)
++        return __create__RealField_version0, (self._prec, self.sci_not, self.rnd_str)
+ 
+     def construction(self):
+         r"""
+@@ -968,7 +968,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: RealField(100,rnd='RNDU').name()
+             'RealField100_2'
+         """
+-        return "RealField%s_%s"%(self.__prec,self.rnd)
++        return "RealField%s_%s"%(self._prec,self.rnd)
+ 
+     def __hash__(self):
+         """
+@@ -995,7 +995,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: RealField(20).precision()
+             20
+         """
+-        return Integer(self.__prec)
++        return Integer(self._prec)
+ 
+     prec=precision # an alias
+ 
+@@ -1031,7 +1031,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: R.to_prec(300)
+             Real Field with 300 bits of precision and rounding RNDZ
+         """
+-        if prec == self.__prec:
++        if prec == self._prec:
+             return self
+         else:
+             return RealField(prec, self.sci_not, self.rnd)
+@@ -1052,7 +1052,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             0.88622692545275801364908374167057259139877473
+         """
+         cdef RealNumber x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD: sig_on()
+         # The docs for mpfr_free_cache say "Free the cache used by
+         # the functions computing constants if needed (currently
+         # mpfr_const_log2, mpfr_const_pi and mpfr_const_euler)", so
+@@ -1062,7 +1062,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+         # functions, but this free is needed for them too!
+         mpfr_free_cache()
+         mpfr_const_pi(x.value, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def euler_constant(self):
+@@ -1091,10 +1091,10 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             0.91596559417721901505460351493
+         """
+         cdef RealNumber x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_free_cache()
+         mpfr_const_catalan(x.value, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log2(self):
+@@ -1111,10 +1111,10 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             0.69314718055994530941723212146
+         """
+         cdef RealNumber x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_free_cache()
+         mpfr_const_log2(x.value, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def random_element(self, min=-1, max=1, distribution=None):
+@@ -1181,9 +1181,9 @@ cdef class RealField_class(sage.rings.abc.RealField):
+         if n < 0:
+             raise ArithmeticError("n must be nonnegative")
+         x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_on()
+         mpfr_fac_ui(x.value, n, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def rounding_mode(self):
+@@ -1346,7 +1346,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             NaN
+         """
+         cdef RealField_class p = <RealField_class?>parent
+-        mpfr_init2(self.value, p.__prec)
++        mpfr_init2(self.value, p._prec)
+         self._parent = p
+ 
+     def __init__(self, parent, x=0, int base=10):
+@@ -1446,7 +1446,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             sage: numpy.array([1.000000000000000000000000000000000000]).dtype           # optional - numpy
+             dtype('O')
+         """
+-        if (<RealField_class>self._parent).__prec <= 53:
++        if (<RealField_class>self._parent)._prec <= 53:
+             return numpy_double_interface
+         else:
+             return numpy_object_interface
+@@ -2075,7 +2075,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             # This avoids the confusion a lot of people have with the last
+             # 1-2 binary digits being wrong due to rounding coming from
+             # representing numbers in binary.
+-            digits = <size_t>(((<RealField_class>self._parent).__prec - 1) * M_LN2_LN10)
++            digits = <size_t>(((<RealField_class>self._parent)._prec - 1) * M_LN2_LN10)
+             if digits < 2:
+                 digits = 2
+ 
+@@ -2303,7 +2303,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if sgn == 0:
+             return z
+ 
+-        cdef mpfr_prec_t prec = (<RealField_class>self._parent).__prec
++        cdef mpfr_prec_t prec = (<RealField_class>self._parent)._prec
+ 
+         if mpfr_inf_p(self.value):
+             mpz_set_ui(z.value, EXP_MAX+1-EXP_MIN)
+@@ -2757,7 +2757,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             sage: RealField(101)(-1).precision()
+             101
+         """
+-        return Integer((<RealField_class>self._parent).__prec)
++        return Integer((<RealField_class>self._parent)._prec)
+ 
+     prec = precision # alias
+ 
+@@ -3364,7 +3364,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         cdef unsigned long wordsize = sizeof(long)*8
+ 
+         cdef mpfr_prec_t prec
+-        prec = (<RealField_class>self._parent).__prec
++        prec = (<RealField_class>self._parent)._prec
+ 
+         # We round up the precision to the nearest multiple of wordsize.
+         cdef int rounded_prec
+@@ -3699,7 +3699,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         from .real_mpfi import RealIntervalField
+ 
+         cdef mpfr_rnd_t rnd = (<RealField_class>self._parent).rnd
+-        cdef mpfr_prec_t prec = (<RealField_class>self._parent).__prec
++        cdef mpfr_prec_t prec = (<RealField_class>self._parent)._prec
+ 
+         cdef RealNumber low, high
+         cdef int odd
+@@ -4249,9 +4249,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         cdef RealNumber x
+         if mpfr_cmp_ui(self.value, 0) >= 0:
+             x = self._new()
+-            if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_on()
++            if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_on()
+             mpfr_sqrt(x.value, self.value, (<RealField_class>self._parent).rnd)
+-            if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_off()
++            if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_off()
+             if all:
+                 if x.is_zero():
+                     return [x]
+@@ -4295,12 +4295,12 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             -1.42108547152020e-14
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_on()
+         mpfr_cbrt(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+-    def __pow(self, RealNumber exponent):
++    def _pow(self, RealNumber exponent):
+         """
+         Compute ``self`` raised to the power of exponent, rounded in the
+         direction specified by the parent of ``self``.
+@@ -4309,7 +4309,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+ 
+             sage: R = RealField(30)
+             sage: a = R('1.23456')
+-            sage: a.__pow(20.0)
++            sage: a._pow(20.0)
+             67.646297
+         """
+         cdef RealNumber x
+@@ -4435,9 +4435,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+                 return self._complex_number_().log(base)
+         if base is None or base == 'e':
+             x = self._new()
+-            if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++            if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+             mpfr_log(x.value, self.value, (<RealField_class>self._parent).rnd)
+-            if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++            if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+             return x
+         elif base == 10:
+             return self.log10()
+@@ -4476,9 +4476,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if self < 0:
+             return self._complex_number_().log(2)
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_log2(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log10(self):
+@@ -4513,9 +4513,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if self < 0:
+             return self._complex_number_().log(10)
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_log10(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log1p(self):
+@@ -4562,9 +4562,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if self < -1:
+             return (self+1.0)._complex_number_().log()
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_log1p(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def exp(self):
+@@ -4620,9 +4620,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             1.89117248253021e-10
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_exp2(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def exp10(self):
+@@ -4648,9 +4648,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             5.01187233627276e-33
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_exp10(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def expm1(self):
+@@ -4672,9 +4672,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             1.00000000000000e-16
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_expm1(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def eint(self):
+@@ -4694,9 +4694,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             -0.219383934395520
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_eint(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         return x
+ 
+     def cos(self):
+@@ -5125,9 +5125,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             _other = self._parent(other)
+ 
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > 10000: sig_on()
++        if (<RealField_class>self._parent)._prec > 10000: sig_on()
+         mpfr_agm(x.value, self.value, _other.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > 10000: sig_off()
++        if (<RealField_class>self._parent)._prec > 10000: sig_off()
+         return x
+ 
+     def erf(self):
+@@ -5280,9 +5280,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             0.886226925452758
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_gamma(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log_gamma(self):
+@@ -5306,10 +5306,10 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         cdef RealNumber x = self._new()
+         parent = (<RealField_class>self._parent)
+         if not mpfr_sgn(self.value) < 0:
+-            if parent.__prec > SIG_PREC_THRESHOLD:
++            if parent._prec > SIG_PREC_THRESHOLD:
+                 sig_on()
+             mpfr_lngamma(x.value, self.value, parent.rnd)
+-            if parent.__prec > SIG_PREC_THRESHOLD:
++            if parent._prec > SIG_PREC_THRESHOLD:
+                 sig_off()
+             return x
+         from sage.libs.mpmath.utils import call
+@@ -5534,7 +5534,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+ 
+         cdef RealField_class fld = <RealField_class>self._parent
+ 
+-        if algorithm == 0 and n <= 10000 / fld.__prec:
++        if algorithm == 0 and n <= 10000 / fld._prec:
+             # This is a rough estimate for when it is probably
+             # faster to call mpfr directly.  (This is a pretty
+             # good estimate on one particular machine, a
+@@ -5639,7 +5639,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+ 
+         from .real_mpfi import RealIntervalField
+ 
+-        cdef mpfr_prec_t prec = fld.__prec + 10
++        cdef mpfr_prec_t prec = fld._prec + 10
+ 
+         cdef RealNumber lower
+         cdef RealNumber upper
+diff --git a/src/sage/rings/ring.pxd b/src/sage/rings/ring.pxd
+index 9384f39f258..1322697688f 100644
+--- a/src/sage/rings/ring.pxd
++++ b/src/sage/rings/ring.pxd
+@@ -7,7 +7,7 @@ cdef class Ring(ParentWithGens):
+     cdef public object _one_element
+     cdef public object _zero_ideal
+     cdef public object _unit_ideal
+-    cdef public object __ideal_monoid
++    cdef public object _ideal_monoid
+ 
+ 
+ cdef class CommutativeRing(Ring):
+diff --git a/src/sage/rings/ring.pyx b/src/sage/rings/ring.pyx
+index 4cba2c9ba7f..8acf4383270 100644
+--- a/src/sage/rings/ring.pyx
++++ b/src/sage/rings/ring.pyx
+@@ -325,12 +325,12 @@ cdef class Ring(ParentWithGens):
+              by the ideal (x*y + y*z, x*x + x*y - y*x - y*y)
+ 
+         """
+-        if self.__ideal_monoid is not None:
+-            return self.__ideal_monoid
++        if self._ideal_monoid is not None:
++            return self._ideal_monoid
+         else:
+             from sage.rings.noncommutative_ideals import IdealMonoid_nc
+             M = IdealMonoid_nc(self)
+-            self.__ideal_monoid = M
++            self._ideal_monoid = M
+             return M
+ 
+     def ideal(self, *args, **kwds):
+@@ -1106,12 +1106,12 @@ cdef class Ring(ParentWithGens):
+             sage: R.<x>=QQ[]; R.ideal_monoid()
+             Monoid of ideals of Univariate Polynomial Ring in x over Rational Field
+         """
+-        if self.__ideal_monoid is not None:
+-            return self.__ideal_monoid
++        if self._ideal_monoid is not None:
++            return self._ideal_monoid
+         else:
+             from sage.rings.ideal_monoid import IdealMonoid
+             M = IdealMonoid(self)
+-            self.__ideal_monoid = M
++            self._ideal_monoid = M
+             return M
+ 
+     @cached_method
+@@ -1345,12 +1345,12 @@ cdef class CommutativeRing(Ring):
+             sage: R.<x>=QQ[]; R.ideal_monoid()
+             Monoid of ideals of Univariate Polynomial Ring in x over Rational Field
+         """
+-        if self.__ideal_monoid is not None:
+-            return self.__ideal_monoid
++        if self._ideal_monoid is not None:
++            return self._ideal_monoid
+         else:
+             from sage.rings.ideal_monoid import IdealMonoid
+             M = IdealMonoid(self)
+-            self.__ideal_monoid = M
++            self._ideal_monoid = M
+             return M
+ 
+     def extension(self, poly, name=None, names=None, **kwds):
+diff --git a/src/sage/schemes/elliptic_curves/mod_sym_num.pyx b/src/sage/schemes/elliptic_curves/mod_sym_num.pyx
+index 65742f28d72..296a6b5d075 100644
+--- a/src/sage/schemes/elliptic_curves/mod_sym_num.pyx
++++ b/src/sage/schemes/elliptic_curves/mod_sym_num.pyx
+@@ -730,7 +730,7 @@ cdef class ModularSymbolNumerical:
+         double _eps_plus, _eps_minus, _eps_unitary_plus, _eps_unitary_minus
+         public RealNumber _om1, _om2
+         object _E, _epsQs, _Mt, _Epari
+-        public dict __cached_methods
++        public dict _cached_methods
+         Rational _twist_q
+         Integer _D
+         int _global_sign
+@@ -785,7 +785,7 @@ cdef class ModularSymbolNumerical:
+         self._set_epsQs()
+         self._initialise_an_coefficients()
+         self._set_den_bounds()
+-        self.__cached_methods = {}
++        self._cached_methods = {}
+ 
+         # self.nc_sums = Integer(0)
+         # self.nc_direct = Integer(0)
+@@ -1357,7 +1357,7 @@ cdef class ModularSymbolNumerical:
+             sage: M(0)
+             1/5
+         """
+-        cadi = self.__cached_methods
++        cadi = self._cached_methods
+         for me in cadi:
+             cadi[me].clear_cache()
+ 
+@@ -1833,7 +1833,7 @@ cdef class ModularSymbolNumerical:
+ 
+         # if called with a previous (m,z,eps) but a larger eps,
+         # return the cached value
+-        cac = self.__cached_methods['_kappa'].cache
++        cac = self._cached_methods['_kappa'].cache
+         for ke in cac:
+             mm, zz, eeps = ke[0]
+             if mm == m and zz == z:
+@@ -2746,16 +2746,16 @@ cdef class ModularSymbolNumerical:
+             sage: ms = ModularSymbolNumerical(E)
+             sage: ms.manin_symbol(4,17)
+             1
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache # random
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache # random
+             {((1, 5, 1), ()): 1,
+             ((1, 15, 1), ()): -1,
+             ((1, 22, 1), ()): -1,
+             ((1, 32, 1), ()): 1}
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache[(1,15,1),()]
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache[(1,15,1),()]
+             -1
+             sage: ms.manin_symbol(4+17,-4)
+             0
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache # random
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache # random
+             {((1, 4, 1), ()): 0,
+             ((1, 5, 1), ()): 1,
+             ((1, 8, 1), ()): 1,
+@@ -2768,7 +2768,7 @@ cdef class ModularSymbolNumerical:
+             ((1, 29, 1), ()): 1,
+             ((1, 32, 1), ()): 1,
+             ((1, 33, 1), ()): 0}
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache[ (1,23,1), () ]
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache[ (1,23,1), () ]
+             -1
+         """
+         cdef:
+@@ -2903,7 +2903,7 @@ cdef class ModularSymbolNumerical:
+         #        "(%s :%s)"%(un, vn), level=3)
+ 
+         # is it already in the cache ?
+-        c = self.__cached_methods
++        c = self._cached_methods
+         if "_manin_symbol_with_cache" in c:
+             c = c["_manin_symbol_with_cache"]
+             if c.is_in_cache(un,vn,sign):
+@@ -2919,7 +2919,7 @@ cdef class ModularSymbolNumerical:
+         # we get for free additional values of Manin
+         # symbols that we cache, too.
+         # This sets 6 values in average
+-        c = self.__cached_methods["_manin_symbol_with_cache"]
++        c = self._cached_methods["_manin_symbol_with_cache"]
+ 
+         # (-v:u) = - (u:v)
+         oi = proj_normalise(self._N_E, -v, u, &un, &vn)
+diff --git a/src/sage/sets/set_from_iterator.py b/src/sage/sets/set_from_iterator.py
+index c47bb76920b..11f12e6d5ea 100644
+--- a/src/sage/sets/set_from_iterator.py
++++ b/src/sage/sets/set_from_iterator.py
+@@ -214,12 +214,12 @@ def __reduce__(self):
+             True
+         """
+         return (EnumeratedSetFromIterator,
+-                (self._func,                            # func
+-                 getattr(self, '_args', None),          # args
+-                 getattr(self, '_kwds', None),          # kwds
+-                 getattr(self, '__custom_name', None),  # name
+-                 self.category(),                       # category
+-                 hasattr(self, '_cache'))               # cache
++                (self._func,                    # func
++                 getattr(self, '_args', None),  # args
++                 getattr(self, '_kwds', None),  # kwds
++                 self.get_custom_name(),        # name
++                 self.category(),               # category
++                 hasattr(self, '_cache'))       # cache
+                 )
+ 
+     def _repr_(self):
+diff --git a/src/sage/structure/category_object.pxd b/src/sage/structure/category_object.pxd
+index ff3088ae9b6..83d3d4967d4 100644
+--- a/src/sage/structure/category_object.pxd
++++ b/src/sage/structure/category_object.pxd
+@@ -13,7 +13,7 @@ from sage.structure.sage_object cimport SageObject
+ cpdef check_default_category(default_category, category)
+ 
+ cdef class CategoryObject(SageObject):
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+     cdef _category
+     cdef public _base
+     cdef public _names
+diff --git a/src/sage/structure/category_object.pyx b/src/sage/structure/category_object.pyx
+index 3859f24095a..b6a7eaecb5b 100644
+--- a/src/sage/structure/category_object.pyx
++++ b/src/sage/structure/category_object.pyx
+@@ -113,7 +113,7 @@ cdef class CategoryObject(SageObject):
+             self._init_category_(category)
+ 
+     def __cinit__(self):
+-        self.__cached_methods = {}
++        self._cached_methods = {}
+         self._hash_value = -1
+ 
+     def _init_category_(self, category):
+@@ -491,7 +491,7 @@ cdef class CategoryObject(SageObject):
+         """
+         return self.variable_names()[0]
+ 
+-    def __temporarily_change_names(self, names, latex_names):
++    def _temporarily_change_names(self, names, latex_names):
+         """
+         This is used by the variable names context manager.
+ 
+@@ -844,7 +844,7 @@ cdef class CategoryObject(SageObject):
+         # Lookup a method or attribute from the category abstract classes.
+         # See __getattr__ above for documentation.
+         try:
+-            return self.__cached_methods[name]
++            return self._cached_methods[name]
+         except KeyError:
+             if self._category is None:
+                 # Usually, this will just raise AttributeError in
+@@ -854,7 +854,7 @@ cdef class CategoryObject(SageObject):
+                 cls = self._category.parent_class
+ 
+             attr = getattr_from_other_class(self, cls, name)
+-            self.__cached_methods[name] = attr
++            self._cached_methods[name] = attr
+             return attr
+ 
+     def __dir__(self):
+diff --git a/src/sage/structure/element.pxd b/src/sage/structure/element.pxd
+index 79e86d8a5c3..20c556b985e 100644
+--- a/src/sage/structure/element.pxd
++++ b/src/sage/structure/element.pxd
+@@ -176,7 +176,7 @@ cdef class Element(SageObject):
+ 
+ 
+ cdef class ElementWithCachedMethod(Element):
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+ cdef class ModuleElement(Element)       # forward declaration
+ 
+diff --git a/src/sage/structure/element.pyx b/src/sage/structure/element.pyx
+index ab6ee157a94..36da1c0cc12 100644
+--- a/src/sage/structure/element.pyx
++++ b/src/sage/structure/element.pyx
+@@ -379,6 +379,7 @@ cdef class Element(SageObject):
+     .. automethod:: __mod__
+     """
+     @cython.binding(False)
++    @cython.always_allow_keywords(False)
+     def __getmetaclass__(_):
+         from sage.misc.inherit_comparison import InheritComparisonMetaclass
+         return InheritComparisonMetaclass
+@@ -2356,18 +2357,18 @@ cdef class ElementWithCachedMethod(Element):
+             True
+         """
+         try:
+-            return self.__cached_methods[name]
++            return self._cached_methods[name]
+         except KeyError:
+             attr = getattr_from_other_class(self,
+                                         self._parent.category().element_class,
+                                         name)
+-            self.__cached_methods[name] = attr
++            self._cached_methods[name] = attr
+             return attr
+         except TypeError:
+             attr = getattr_from_other_class(self,
+                                         self._parent.category().element_class,
+                                         name)
+-            self.__cached_methods = {name : attr}
++            self._cached_methods = {name : attr}
+             return attr
+ 
+ 
+diff --git a/src/sage/structure/parent_gens.pyx b/src/sage/structure/parent_gens.pyx
+index ab531314458..cc6ffaace21 100644
+--- a/src/sage/structure/parent_gens.pyx
++++ b/src/sage/structure/parent_gens.pyx
+@@ -371,7 +371,7 @@ cdef class localvars:
+             self._latex_names = latex_names
+ 
+     def __enter__(self):
+-        self._orig = self._obj.__temporarily_change_names(self._names, self._latex_names)
++        self._orig = self._obj._temporarily_change_names(self._names, self._latex_names)
+ 
+     def __exit__(self, type, value, traceback):
+-        self._obj.__temporarily_change_names(self._orig[0], self._orig[1])
++        self._obj._temporarily_change_names(self._orig[0], self._orig[1])
+diff --git a/src/sage/structure/sage_object.pyx b/src/sage/structure/sage_object.pyx
+index 8474142eaa1..10000aef394 100644
+--- a/src/sage/structure/sage_object.pyx
++++ b/src/sage/structure/sage_object.pyx
+@@ -69,6 +69,8 @@ cdef class SageObject:
+         r"""
+         Change self so it prints as x, where x is a string.
+ 
++        If x is ``None``, the existing custom name is removed.
++
+         .. NOTE::
+ 
+            This is *only* supported for Python classes that derive
+@@ -91,6 +93,9 @@ cdef class SageObject:
+             sage: h.rename('x^300 + ...')
+             sage: h
+             x^300 + ...
++            sage: g.rename(None)
++            sage: g
++            x^3 + x - 5
+ 
+         Real numbers are not Python classes, so rename is not supported::
+ 
+@@ -110,15 +115,16 @@ cdef class SageObject:
+            a lot of memory.
+ 
+            To support them for a specific class, add a
+-           ``cdef public __custom_name`` attribute.
++           ``cdef public _SageObject__custom_name`` attribute.
+         """
+         if x is None:
+-            #if hasattr(self, '__custom_name'):
+-            # that's tested in reset_name anyway...
+             self.reset_name()
+         else:
+             try:
+-                self.__custom_name = str(x)
++                # TODO: after dropping support for Cython < 3.0.0, all
++                # the self._SageObject__custom_name in this class can be
++                # changed to self.__custom_name
++                self._SageObject__custom_name = str(x)
+             except AttributeError:
+                 raise NotImplementedError("object does not support renaming: %s" % self)
+ 
+@@ -138,8 +144,30 @@ cdef class SageObject:
+             sage: P
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if hasattr(self, '__custom_name'):
+-            del self.__custom_name
++        if hasattr(self, '_SageObject__custom_name'):
++            del self._SageObject__custom_name
++
++    def get_custom_name(self):
++        """
++        Return the custom name of this object, or ``None`` if it is not
++        renamed.
++
++        EXAMPLES::
++
++            sage: P.<x> = QQ[]
++            sage: P.get_custom_name() is None
++            True
++            sage: P.rename('A polynomial ring')
++            sage: P.get_custom_name()
++            'A polynomial ring'
++            sage: P.reset_name()
++            sage: P.get_custom_name() is None
++            True
++        """
++        try:
++            return self._SageObject__custom_name
++        except AttributeError:
++            return None
+ 
+     def __repr__(self):
+         """
+@@ -181,7 +209,7 @@ cdef class SageObject:
+             <sage.structure.sage_object.SageObject object at ...>
+         """
+         try:
+-            name = self.__custom_name
++            name = self._SageObject__custom_name
+             if name is not None:
+                 return name
+         except AttributeError:
+diff --git a/src/sage/topology/simplicial_set.py b/src/sage/topology/simplicial_set.py
+index 42cc3f77780..3ee14ae2da8 100644
+--- a/src/sage/topology/simplicial_set.py
++++ b/src/sage/topology/simplicial_set.py
+@@ -570,13 +570,12 @@ def __lt__(self, other):
+             return True
+         if self.degeneracies() and other.degeneracies() and self.degeneracies() != other.degeneracies():
+             return self.degeneracies() < other.degeneracies()
+-        if hasattr(self.nondegenerate(), '__custom_name'):
+-            if hasattr(other.nondegenerate(), '__custom_name'):
+-                return str(self) < str(other)
++        if self.nondegenerate().get_custom_name() is not None:
++            if other.nondegenerate().get_custom_name() is not None:
++                return self.nondegenerate().get_custom_name() < other.nondegenerate().get_custom_name()
+             return True
+ 
+-        if (hasattr(other, '__custom_name')
+-                or hasattr(other.nondegenerate(), '__custom_name')):
++        if other.nondegenerate().get_custom_name() is not None:
+             return False
+         return id(self) < id(other)
+ 
+@@ -793,8 +792,8 @@ def __copy__(self):
+         # dimension, the degeneracies, and the name (with a prime
+         # added).
+         sigma = AbstractSimplex(self._dim, degeneracies=self.degeneracies())
+-        if hasattr(self, '__custom_name'):
+-            sigma.rename(str(self) + "'")
++        if self.get_custom_name() is not None:
++            sigma.rename(self.get_custom_name() + "'")
+         return sigma
+ 
+     def __deepcopy__(self, memo):
+@@ -839,8 +838,8 @@ def __deepcopy__(self, memo):
+             return memo[underlying].apply_degeneracies(*degens)
+         except KeyError:
+             sigma = AbstractSimplex(underlying._dim)
+-            if hasattr(underlying, '__custom_name'):
+-                sigma.rename(str(self) + "'")
++            if underlying.get_custom_name() is not None:
++                sigma.rename(underlying.get_custom_name() + "'")
+             memo[underlying] = sigma
+             return sigma.apply_degeneracies(*degens)
+ 
+@@ -896,12 +895,12 @@ def _latex_(self):
+         """
+         if self._latex_name is not None:
+             return self._latex_name
+-        if hasattr(self, '__custom_name'):
+-            return str(self)
++        if self.get_custom_name() is not None:
++            return self.get_custom_name()
+         if self.nondegenerate()._latex_name is not None:
+             simplex = self.nondegenerate()._latex_name
+-        elif hasattr(self.nondegenerate(), '__custom_name'):
+-            simplex = str(self.nondegenerate())
++        elif self.nondegenerate().get_custom_name() is not None:
++            simplex = self.nondegenerate().get_custom_name()
+         else:
+             simplex = "\\Delta^{{{}}}".format(self._dim)
+         if self.degeneracies():
+diff --git a/src/sage/topology/simplicial_set_constructions.py b/src/sage/topology/simplicial_set_constructions.py
+index ae98821df8a..3a217286ac5 100644
+--- a/src/sage/topology/simplicial_set_constructions.py
++++ b/src/sage/topology/simplicial_set_constructions.py
+@@ -176,8 +176,7 @@ def __init__(self, data, ambient=None):
+         else:
+             SimplicialSet_finite.__init__(self, data)
+         if self == ambient:
+-            if hasattr(ambient, '__custom_name'):
+-                self.rename(str(ambient))
++            self.rename(ambient.get_custom_name())
+             self._latex_name = latex(ambient)
+         # When constructing the inclusion map, we do not need to check
+         # the validity of the morphism, and more importantly, we
diff --git a/srcpkgs/sagemath/patches/build-cython3.patch b/srcpkgs/sagemath/patches/build-cython3.patch
new file mode 100644
index 0000000000000..57d1ade89fc77
--- /dev/null
+++ b/srcpkgs/sagemath/patches/build-cython3.patch
@@ -0,0 +1,44 @@
+diff --git a/src/sage/ext/stdsage.pxd b/src/sage/ext/stdsage.pxd
+index 15abe13b7cd..e2bf7434f35 100644
+--- a/src/sage/ext/stdsage.pxd
++++ b/src/sage/ext/stdsage.pxd
+@@ -10,7 +10,7 @@ Standard C helper code for Cython modules
+ #                  http://www.gnu.org/licenses/
+ #*****************************************************************************
+ 
+-from cpython.object cimport Py_TYPE, PyTypeObject
++from cpython.object cimport Py_TYPE, PyTypeObject, PyObject
+ 
+ 
+ cdef inline PY_NEW(type t):
+@@ -19,7 +19,7 @@ cdef inline PY_NEW(type t):
+     :class:`Integer` where we change ``tp_new`` at runtime (Cython
+     optimizations assume that ``tp_new`` doesn't change).
+     """
+-    return (<PyTypeObject*>t).tp_new(t, <object>NULL, <object>NULL)
++    return (<PyTypeObject*>t).tp_new(t, <PyObject*>NULL, <PyObject*>NULL)
+ 
+ 
+ cdef inline void PY_SET_TP_NEW(type dst, type src):
+diff --git a/src/sage_setup/cython_options.py b/src/sage_setup/cython_options.py
+index 086aa070ca9..9725ce0e1af 100644
+--- a/src/sage_setup/cython_options.py
++++ b/src/sage_setup/cython_options.py
+@@ -10,13 +10,17 @@ def compiler_directives(profile: bool):
+         auto_pickle=False,
+         # Do not create __test__ dictionary automatically from docstrings
+         autotestdict=False,
++        binding=False,
++        c_api_binop_methods=True,
+         # Do not check for division by 0 (this is about 35% quicker than with check)
+         cdivision=True,
++        cpow=True,
+         # Embed a textual copy of the call signature in the docstring (to support tools like IPython)
+         embedsignature=True,
+         fast_getattr=True,
+         # Use Python 3 (including source code semantics) for module compilation
+         language_level="3",
++        legacy_implicit_noexcept=True,
+         # Enable support for late includes (make declarations in Cython code available to C include files)
+         preliminary_late_includes_cy28=True,
+         # Add hooks for Python profilers into the compiled C code
diff --git a/srcpkgs/sagemath/patches/fix-doctest-cython3.patch b/srcpkgs/sagemath/patches/fix-doctest-cython3.patch
new file mode 100644
index 0000000000000..4cff1fb1828db
--- /dev/null
+++ b/srcpkgs/sagemath/patches/fix-doctest-cython3.patch
@@ -0,0 +1,207 @@
+diff --git a/src/doc/en/thematic_tutorials/coercion_and_categories.rst b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+index de2349a9a3f..bb23331c151 100644
+--- a/src/doc/en/thematic_tutorials/coercion_and_categories.rst
++++ b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+@@ -105,7 +105,7 @@ it makes sense to build on top of the base class
+ This base class provides a lot more methods than a general parent::
+ 
+     sage: [p for p in dir(Field) if p not in dir(Parent)]
+-    ['__fraction_field',
++    ['_CommutativeRing__fraction_field',
+      '__iter__',
+      '__len__',
+      '__rxor__',
+diff --git a/src/sage/arith/srange.pyx b/src/sage/arith/srange.pyx
+index 156e548a11a..132cf93d085 100644
+--- a/src/sage/arith/srange.pyx
++++ b/src/sage/arith/srange.pyx
+@@ -84,7 +84,7 @@ def xsrange(start, end=None, step=1, universe=None, *, coerce=True, bint include
+     EXAMPLES::
+ 
+         sage: xsrange(10)
+-        <generator object at 0x...>
++        <...generator object at 0x...>
+         sage: for i in xsrange(1,5):
+         ....:     print(i)
+         1
+diff --git a/src/sage/combinat/sloane_functions.py b/src/sage/combinat/sloane_functions.py
+index c3cf9299093..e5c99b71fe7 100644
+--- a/src/sage/combinat/sloane_functions.py
++++ b/src/sage/combinat/sloane_functions.py
+@@ -9169,7 +9169,7 @@ class Sloane(SageObject):
+         ::
+ 
+             sage: sloane.__repr__
+-            <method-wrapper '__repr__' of Sloane object at 0x...>
++            <built-in method __repr__ of Sloane object at 0x...>
+             sage: sloane.__name__
+             Traceback (most recent call last):
+             ...
+diff --git a/src/sage/misc/cachefunc.pyx b/src/sage/misc/cachefunc.pyx
+index 8aa30a85272..2b1d38c12b9 100644
+--- a/src/sage/misc/cachefunc.pyx
++++ b/src/sage/misc/cachefunc.pyx
+@@ -50,7 +50,7 @@ be used::
+     sage: cython('''cpdef test_funct(x): return -x''')                          # optional - sage.misc.cython
+     sage: wrapped_funct = cached_function(test_funct, name='wrapped_funct')     # optional - sage.misc.cython
+     sage: wrapped_funct                                                         # optional - sage.misc.cython
+-    Cached version of <built-in function test_funct>
++    Cached version of <cyfunction test_funct at ...>
+     sage: wrapped_funct.__name__                                                # optional - sage.misc.cython
+     'wrapped_funct'
+     sage: wrapped_funct(5)                                                      # optional - sage.misc.cython
+@@ -82,9 +82,9 @@ approach is still needed for cpdef methods::
+     sage: cython(os.linesep.join(cython_code))                                  # optional - sage.misc.cython
+     sage: O = MyClass()                                                         # optional - sage.misc.cython
+     sage: O.direct_method                                                       # optional - sage.misc.cython
+-    Cached version of <method 'direct_method' of '...MyClass' objects>
++    Cached version of <cyfunction MyClass.direct_method at ...>
+     sage: O.wrapped_method                                                      # optional - sage.misc.cython
+-    Cached version of <built-in function test_meth>
++    Cached version of <cyfunction test_meth at ...>
+     sage: O.wrapped_method.__name__                                             # optional - sage.misc.cython
+     'wrapped_method'
+     sage: O.wrapped_method(5)                                                   # optional - sage.misc.cython
+@@ -270,6 +270,7 @@ Introspection works::
+         "some doc for a wrapped cython method"
+         return -x
+     sage: print(sage_getsource(O.direct_method))                                # optional - sage.misc.cython
++    @cached_method
+     def direct_method(self, x):
+         "Some doc for direct method"
+         return 2*x
+diff --git a/src/sage/misc/lazy_import.pyx b/src/sage/misc/lazy_import.pyx
+index c33a1e74efd..7fc73407ace 100644
+--- a/src/sage/misc/lazy_import.pyx
++++ b/src/sage/misc/lazy_import.pyx
+@@ -1095,7 +1095,7 @@ def lazy_import(module, names, as_=None, *,
+         sage: from sage.features import PythonModule
+         sage: lazy_import('ppl', 'equation', feature=PythonModule('ppl', spkg='pplpy', type='standard'))
+         sage: equation
+-        <built-in function equation>
++        <cyfunction equation at ...>
+         sage: lazy_import('PyNormaliz', 'NmzListConeProperties', feature=PythonModule('PyNormaliz', spkg='pynormaliz'))  # optional - pynormaliz
+         sage: NmzListConeProperties  # optional - pynormaliz
+         <built-in function NmzListConeProperties>
+diff --git a/src/sage/misc/lazy_list.pyx b/src/sage/misc/lazy_list.pyx
+index ba62c446b69..cd750933860 100644
+--- a/src/sage/misc/lazy_list.pyx
++++ b/src/sage/misc/lazy_list.pyx
+@@ -678,7 +678,7 @@ cdef class lazy_list_generic():
+             sage: from itertools import count
+             sage: from sage.misc.lazy_list import lazy_list
+             sage: iter(lazy_list(count()))
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+ 
+         ::
+ 
+diff --git a/src/sage/misc/sageinspect.py b/src/sage/misc/sageinspect.py
+index ce5e9987027..df8e6bf89ac 100644
+--- a/src/sage/misc/sageinspect.py
++++ b/src/sage/misc/sageinspect.py
+@@ -76,8 +76,8 @@ Cython functions::
+     sage: sage_getdoc(sage.rings.rational.make_rational).lstrip()
+     'Make a rational number ...'
+ 
+-    sage: sage_getsource(sage.rings.rational.make_rational)[4:]
+-    'make_rational(s):...'
++    sage: sage_getsource(sage.rings.rational.make_rational)
++    '@cython.binding(True)\ndef make_rational(s):...'
+ 
+ Python functions::
+ 
+diff --git a/src/sage/modules/free_module_element.pyx b/src/sage/modules/free_module_element.pyx
+index d5e8256b68c..c9af9bcbdf7 100644
+--- a/src/sage/modules/free_module_element.pyx
++++ b/src/sage/modules/free_module_element.pyx
+@@ -1634,7 +1634,7 @@ cdef class FreeModuleElement(Vector):   # abstract base class
+ 
+             sage: v = vector([1,2/3,pi])
+             sage: v.items()
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: list(v.items())
+             [(0, 1), (1, 2/3), (2, pi)]
+ 
+diff --git a/src/sage/rings/finite_rings/finite_field_base.pyx b/src/sage/rings/finite_rings/finite_field_base.pyx
+index 7e2eed91153..3a6db8995c6 100644
+--- a/src/sage/rings/finite_rings/finite_field_base.pyx
++++ b/src/sage/rings/finite_rings/finite_field_base.pyx
+@@ -328,7 +328,7 @@ cdef class FiniteField(Field):
+             sage: p = next_prime(2^64)
+             sage: k.<a> = FiniteField(p^2, impl="pari")
+             sage: it = iter(k); it
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: [next(it) for i in range(10)]
+             [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+ 
+diff --git a/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx b/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx
+index 41951687939..c6b67cba5fb 100644
+--- a/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx
++++ b/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx
+@@ -629,7 +629,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense):
+             sage: S.<x> = k['x',Frob]
+             sage: a = x^4 + 2*t*x^3 + 3*t^2*x^2 + (t^2 + t + 1)*x + 4*t + 3
+             sage: iter = a.right_irreducible_divisors(); iter
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+             sage: next(iter)   # random
+             x + 2*t^2 + 4*t + 4
+             sage: next(iter)   # random
+@@ -664,7 +664,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense):
+             sage: S.<x> = k['x',Frob]
+             sage: a = x^4 + 2*t*x^3 + 3*t^2*x^2 + (t^2 + t + 1)*x + 4*t + 3
+             sage: iter = a.left_irreducible_divisors(); iter
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+             sage: next(iter)  # random
+             x + 3*t + 3
+             sage: next(iter)  # random
+@@ -1052,7 +1052,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense):
+             sage: S.<x> = k['x',Frob]
+             sage: a = x^3 + (t^2 + 1)*x^2 + (2*t + 3)*x + t^2 + t + 2
+             sage: iter = a.factorizations(); iter
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+             sage: next(iter)   # random
+             (x + 3*t^2 + 4*t) * (x + 2*t^2) * (x + 4*t^2 + 4*t + 2)
+             sage: next(iter)   # random
+diff --git a/src/sage/structure/coerce_dict.pyx b/src/sage/structure/coerce_dict.pyx
+index a2e8443084c..ef86c6af35c 100644
+--- a/src/sage/structure/coerce_dict.pyx
++++ b/src/sage/structure/coerce_dict.pyx
+@@ -777,7 +777,7 @@ cdef class MonoDict:
+             sage: L[1] = None
+             sage: L[2] = True
+             sage: L.items()
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: sorted(L.items())
+             [(1, None), (2, True)]
+         """
+@@ -1452,7 +1452,7 @@ cdef class TripleDict:
+             sage: L = TripleDict()
+             sage: L[1,2,3] = None
+             sage: L.items()
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: list(L.items())
+             [((1, 2, 3), None)]
+         """
+diff --git a/src/sage/tests/cmdline.py b/src/sage/tests/cmdline.py
+index ad0c44aa274..f14cd2db768 100644
+--- a/src/sage/tests/cmdline.py
++++ b/src/sage/tests/cmdline.py
+@@ -491,9 +491,8 @@ def test_executable(args, input="", timeout=100.0, pydebug_ignore_warnings=False
+ 
+         sage: (out, err, ret) = test_executable(["sage", "--cython"])
+         sage: print(err)
+-        Cython (http://cython.org) is a compiler for code written in the
+-        Cython language.  Cython is based on Pyrex by Greg Ewing.
+         ...
++        cython: error: cython: Need at least one source file
+ 
+         sage: def has_tty():
+         ....:     try:
diff --git a/srcpkgs/sagemath/patches/get_patches b/srcpkgs/sagemath/patches/get_patches
index c2c5aa1c7eccd..8d50f9a3cd3b3 100755
--- a/srcpkgs/sagemath/patches/get_patches
+++ b/srcpkgs/sagemath/patches/get_patches
@@ -12,7 +12,7 @@ esac
 # get_pr <PR number> <description> [ext]
 get_pr() {
 	pr=$1
-	desc=$(echo "$2" | sed -e 's/ /_/g')
+	desc=$(echo "$2" | tr ' /' '_-')
 	ext=${3-diff}
 	$DO wget "$URL_BASE_PR$pr.$ext" -O "$pr-$desc.patch"
 }
@@ -24,6 +24,9 @@ cd $(dirname "$0")
 #get_pr  36018   "singular 4.3.2p4" # included in #35934
 get_pr  36046   "fix memory leak"
 
-# positive review
+# merged in 10.2.beta1
 get_pr  35934   "singular 4.3.2p7"
+get_pr  36109   "prepare for cython 3.0" # included in #36110
+
+# positive review
 get_pr  36006   "gmp 6.3.0"
diff --git a/srcpkgs/sagemath/template b/srcpkgs/sagemath/template
index 019ad37cb3a70..5d30bb0bfc163 100644
--- a/srcpkgs/sagemath/template
+++ b/srcpkgs/sagemath/template
@@ -1,12 +1,12 @@
 # Template file for 'sagemath'
 pkgname=sagemath
 version=10.1
-revision=2
+revision=3
 build_wrksrc=pkgs/sagemath-standard
 build_style=python3-module
 _bindir=/usr/lib/sagemath/$version/bin
 make_install_args="--install-scripts=$_bindir"
-hostmakedepends="m4 pkg-config python3-Cython0.29 python3-Jinja2
+hostmakedepends="m4 pkg-config python3-Cython python3-Jinja2
  python3-pkgconfig python3-setuptools"
 makedepends="arb-devel boost-devel brial-devel cliquer-devel ecl eclib-devel
  ecm-devel fflas-ffpack flintlib-devel gap-devel gd-devel giac-devel glpk-devel
@@ -18,7 +18,7 @@ makedepends="arb-devel boost-devel brial-devel cliquer-devel ecl eclib-devel
 depends="eclib-devel fflas-ffpack flintlib-devel gcc-fortran gd-devel
  gfan giac gsl-devel gzip libpng-devel linbox-devel m4ri-devel maxima-ecl
  mpfr-devel nauty ntl-devel palp pari-devel pari-elldata-small pari-galdata
- pari-galpol-small pari-seadata-small pkg-config python3-Cython0.29 python3-cypari2
+ pari-galpol-small pari-seadata-small pkg-config python3-Cython python3-cypari2
  python3-cysignals python3-devel python3-fpylll python3-ipython python3-lrcalc
  python3-ipython_ipykernel python3-jupyter_ipywidgets python3-matplotlib
  python3-memory_allocator python3-networkx python3-pip python3-pkgconfig

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PR PATCH] [Updated] sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
@ 2023-09-02 22:37 ` tornaria
  2023-09-02 23:33 ` ahesford
                   ` (15 subsequent siblings)
  16 siblings, 0 replies; 18+ messages in thread
From: tornaria @ 2023-09-02 22:37 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 2442 bytes --]

There is an updated pull request by tornaria against master on the void-packages repository

https://github.com/tornaria/void-packages sagemath-cython3
https://github.com/void-linux/void-packages/pull/45887

sagemath: use cython 3
#### Testing the changes
- I tested the changes in this PR: **briefly**

Since https://github.com/sagemath/sage/pull/36109 was merged upstream, it's now almost trivial to build sagemath with cython 3. This PR is pretty straightforward to understand:

 - commit 7f8e6514ffa54449a80e01fbae7f9355a7739a46 rebuilds `python3-pplpy` using cython 3. Nothing fancy here and this commit was already tested and only dropped since it turned out it had to be built with the same version of cython as sagemath itself.
 - commit df0d21871ce850efea3fc01f19a3d9e8c0d5f0d4 is just adding a few patches to sagemath, switching to cython 3, and bumping.

Description of added patches:
1. patch `36109-00pre.patch`: this is hand picked trivial patch that allows us to apply https://github.com/sagemath/sage/pull/36109 cleanly on 10.1 (since that PR is based on 10.1.beta0). All changes are comments!
2. patch `36109-prepare_for_cython_3.0.patch`: this is long, taken verbatim from https://github.com/sagemath/sage/pull/36109.diff, and is already merged.
3. patch `build-cython3.patch`: this is 2 lines changed plus 4 legacy build options added to cython setup.
4. patch `fix-doctest-cython3.patch`: this is a few fixes in doctests to accomodate minor changes in cython output (`__repr__` for cython classes, functions, and generators).

CC: @ahesford 

<!--
#### New package
- This new package conforms to the [package requirements](https://github.com/void-linux/void-packages/blob/master/CONTRIBUTING.md#package-requirements): **YES**|**NO**
-->

<!-- Note: If the build is likely to take more than 2 hours, please add ci skip tag as described in
https://github.com/void-linux/void-packages/blob/master/CONTRIBUTING.md#continuous-integration
and test at least one native build and, if supported, at least one cross build.
Ignore this section if this PR is not skipping CI.
-->
<!--
#### Local build testing
- I built this PR locally for my native architecture, (ARCH-LIBC)
- I built this PR locally for these architectures (if supported. mark crossbuilds):
  - aarch64-musl
  - armv7l
  - armv6l-musl
-->


A patch file from https://github.com/void-linux/void-packages/pull/45887.patch is attached

[-- Warning: decoded text below may be mangled, UTF-8 assumed --]
[-- Attachment #2: github-pr-sagemath-cython3-45887.patch --]
[-- Type: text/x-diff, Size: 464760 bytes --]

From 1d1eb3bfbb283db3b32c0e1177f46e9dd4d086e3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gonzalo=20Tornar=C3=ADa?= <tornaria@cmat.edu.uy>
Date: Wed, 19 Jul 2023 21:04:33 -0300
Subject: [PATCH 1/2] python3-pplpy: patch and rebuild for Cython 3

---
 ...8537fa7ea061ebb8d5131b1e23673eaf741d.patch | 22 ++++++++++++++++++
 .../patches/cython3-legacy.patch              | 23 +++++++++++++++++++
 srcpkgs/python3-pplpy/template                |  4 ++--
 3 files changed, 47 insertions(+), 2 deletions(-)
 create mode 100644 srcpkgs/python3-pplpy/patches/aaa28537fa7ea061ebb8d5131b1e23673eaf741d.patch
 create mode 100644 srcpkgs/python3-pplpy/patches/cython3-legacy.patch

diff --git a/srcpkgs/python3-pplpy/patches/aaa28537fa7ea061ebb8d5131b1e23673eaf741d.patch b/srcpkgs/python3-pplpy/patches/aaa28537fa7ea061ebb8d5131b1e23673eaf741d.patch
new file mode 100644
index 0000000000000..21bc2a5214df4
--- /dev/null
+++ b/srcpkgs/python3-pplpy/patches/aaa28537fa7ea061ebb8d5131b1e23673eaf741d.patch
@@ -0,0 +1,22 @@
+From aaa28537fa7ea061ebb8d5131b1e23673eaf741d Mon Sep 17 00:00:00 2001
+From: Matthias Koeppe <mkoeppe@math.ucdavis.edu>
+Date: Sun, 31 Jul 2022 12:39:34 -0700
+Subject: [PATCH] ppl/bit_arrays.pxd: Use relative cimport
+
+---
+ ppl/bit_arrays.pxd | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/ppl/bit_arrays.pxd b/ppl/bit_arrays.pxd
+index eb57434..145a978 100644
+--- a/ppl/bit_arrays.pxd
++++ b/ppl/bit_arrays.pxd
+@@ -1,4 +1,4 @@
+-from ppl_decl cimport *
++from .ppl_decl cimport *
+ 
+ cdef class Bit_Row(object):
+     cdef PPL_Bit_Row *thisptr
+-- 
+GitLab
+
diff --git a/srcpkgs/python3-pplpy/patches/cython3-legacy.patch b/srcpkgs/python3-pplpy/patches/cython3-legacy.patch
new file mode 100644
index 0000000000000..e00b99f8c5f2e
--- /dev/null
+++ b/srcpkgs/python3-pplpy/patches/cython3-legacy.patch
@@ -0,0 +1,23 @@
+commit e6f3e66154138ce3e31e803e74b8c71787c70acc
+Author: Gonzalo Tornaría <tornaria@cmat.edu.uy>
+Date:   Wed Jul 19 20:47:52 2023 -0300
+
+    cython3 support using legacy directives
+
+diff --git a/setup.py b/setup.py
+index 13d543b..55dcd34 100755
+--- a/setup.py
++++ b/setup.py
+@@ -38,7 +38,11 @@ class build_ext(_build_ext):
+         self.extensions[:] = cythonize(
+             self.extensions,
+             include_path=sys.path,
+-            compiler_directives={'embedsignature': True})
++            compiler_directives={
++                'embedsignature': True,
++                'legacy_implicit_noexcept': True,
++                'c_api_binop_methods': True,
++                })
+ 
+         _build_ext.run(self)
+ 
diff --git a/srcpkgs/python3-pplpy/template b/srcpkgs/python3-pplpy/template
index 6c1e83aa091c7..6023c63f87982 100644
--- a/srcpkgs/python3-pplpy/template
+++ b/srcpkgs/python3-pplpy/template
@@ -1,9 +1,9 @@
 # Template file for 'python3-pplpy'
 pkgname=python3-pplpy
 version=0.8.7
-revision=3
+revision=4
 build_style=python3-module
-hostmakedepends="python3-setuptools python3-Cython0.29"
+hostmakedepends="python3-setuptools python3-Cython"
 makedepends="python3-cysignals python3-gmpy2 python3-devel gmp-devel
  gmpxx-devel ppl-devel mpfr-devel libmpc-devel pari-devel"
 depends="python3"

From 6ac18ef4d636b2e980b88fcc88360fd400d01cee Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gonzalo=20Tornar=C3=ADa?= <tornaria@cmat.edu.uy>
Date: Tue, 29 Aug 2023 22:14:49 -0300
Subject: [PATCH 2/2] sagemath: use cython 3.0

---
 srcpkgs/sagemath/patches/36109-00pre.patch    |   50 +
 .../36109-prepare_for_cython_3.0.patch        | 9995 +++++++++++++++++
 srcpkgs/sagemath/patches/build-cython3.patch  |   44 +
 .../patches/fix-doctest-cython3.patch         |  207 +
 srcpkgs/sagemath/patches/get_patches          |    7 +-
 srcpkgs/sagemath/template                     |    6 +-
 6 files changed, 10304 insertions(+), 5 deletions(-)
 create mode 100644 srcpkgs/sagemath/patches/36109-00pre.patch
 create mode 100644 srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch
 create mode 100644 srcpkgs/sagemath/patches/build-cython3.patch
 create mode 100644 srcpkgs/sagemath/patches/fix-doctest-cython3.patch

diff --git a/srcpkgs/sagemath/patches/36109-00pre.patch b/srcpkgs/sagemath/patches/36109-00pre.patch
new file mode 100644
index 0000000000000..0a30d622f0f62
--- /dev/null
+++ b/srcpkgs/sagemath/patches/36109-00pre.patch
@@ -0,0 +1,50 @@
+Pre-patch so that PR #36109 applies cleanly on top of 10.1
+
+diff --git a/src/sage/categories/hopf_algebras_with_basis.py b/src/sage/categories/hopf_algebras_with_basis.py
+index ea401896ca0..29b6f48a86f 100644
+--- a/src/sage/categories/hopf_algebras_with_basis.py
++++ b/src/sage/categories/hopf_algebras_with_basis.py
+@@ -33,11 +33,11 @@ class HopfAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
+     We now show how to use a simple Hopf algebra, namely the group algebra of the dihedral group
+     (see also AlgebrasWithBasis)::
+ 
+-        sage: A = C.example(); A                                                        # optional - sage.groups
++        sage: A = C.example(); A                                                        # needs sage.groups
+         An example of Hopf algebra with basis: the group algebra of the
+          Dihedral group of order 6 as a permutation group over Rational Field
+-        sage: A.__custom_name = "A"                                                     # optional - sage.groups
+-        sage: A.category()                                                              # optional - sage.groups
++        sage: A.__custom_name = "A"                                                     # needs sage.groups
++        sage: A.category()                                                              # needs sage.groups
+         Category of finite dimensional hopf algebras with basis over Rational Field
+ 
+         sage: A.one_basis()                                                             # optional - sage.groups
+diff --git a/src/sage/categories/modules_with_basis.py b/src/sage/categories/modules_with_basis.py
+index 85a0d50239a..c0e29886b5f 100644
+--- a/src/sage/categories/modules_with_basis.py
++++ b/src/sage/categories/modules_with_basis.py
+@@ -66,9 +66,9 @@ class ModulesWithBasis(CategoryWithAxiom_over_base_ring):
+ 
+     Let `X` and `Y` be two modules with basis. We can build `Hom(X,Y)`::
+ 
+-        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.__custom_name = "X"             # optional - sage.modules
+-        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.__custom_name = "Y"             # optional - sage.modules
+-        sage: H = Hom(X, Y); H                                                          # optional - sage.modules
++        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.__custom_name = "X"             # needs sage.modules
++        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.__custom_name = "Y"             # needs sage.modules
++        sage: H = Hom(X, Y); H                                                          # needs sage.modules
+         Set of Morphisms from X to Y
+          in Category of finite dimensional vector spaces with basis over Rational Field
+ 
+diff --git a/src/sage/misc/cachefunc.pyx b/src/sage/misc/cachefunc.pyx
+index dac4c684f47..9b2916e547d 100644
+--- a/src/sage/misc/cachefunc.pyx
++++ b/src/sage/misc/cachefunc.pyx
+@@ -297,6 +297,7 @@ methods of extension classes, as long as they either support attribute assignmen
+ or have a public attribute of type ``<dict>`` called ``__cached_methods``. The
+ latter is easy::
+ 
++    sage: # needs sage.misc.cython
+     sage: cython_code = [
+     ....: "from sage.misc.cachefunc import cached_method",
+     ....: "cdef class MyClass:",
diff --git a/srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch b/srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch
new file mode 100644
index 0000000000000..93390f7eef992
--- /dev/null
+++ b/srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch
@@ -0,0 +1,9995 @@
+diff --git a/src/doc/en/thematic_tutorials/coercion_and_categories.rst b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+index 4efe68a2617..de2349a9a3f 100644
+--- a/src/doc/en/thematic_tutorials/coercion_and_categories.rst
++++ b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+@@ -106,7 +106,6 @@ This base class provides a lot more methods than a general parent::
+ 
+     sage: [p for p in dir(Field) if p not in dir(Parent)]
+     ['__fraction_field',
+-     '__ideal_monoid',
+      '__iter__',
+      '__len__',
+      '__rxor__',
+@@ -119,6 +118,7 @@ This base class provides a lot more methods than a general parent::
+      '_default_category',
+      '_gens',
+      '_ideal_class_',
++     '_ideal_monoid',
+      '_latex_names',
+      '_list',
+      '_one_element',
+diff --git a/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst b/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst
+index 51aec989810..553a946c4d8 100644
+--- a/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst
++++ b/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst
+@@ -298,7 +298,7 @@ http://docs.python.org/library/ for a complete list. ::
+         sage: el
+         bla
+         sage: el.__dict__
+-        {'__custom_name': 'bla', 'value': 42}
++        {'_SageObject__custom_name': 'bla', 'value': 42}
+ 
+     Lots of Sage objects are not Python objects but compiled Cython
+     objects. Python sees them as builtin objects and you do not have
+diff --git a/src/sage/algebras/letterplace/free_algebra_letterplace.pxd b/src/sage/algebras/letterplace/free_algebra_letterplace.pxd
+index d1d162c3b40..47a7275aba0 100644
+--- a/src/sage/algebras/letterplace/free_algebra_letterplace.pxd
++++ b/src/sage/algebras/letterplace/free_algebra_letterplace.pxd
+@@ -20,16 +20,15 @@ cdef class FreeAlgebra_letterplace_libsingular():
+     cdef ring* _lp_ring
+     cdef MPolynomialRing_libsingular _commutative_ring
+     cdef MPolynomialRing_libsingular _lp_ring_internal
+-    cdef object __ngens
++    cdef object _ngens
+ 
+ cdef class FreeAlgebra_letterplace(Algebra):
+     cdef MPolynomialRing_libsingular _commutative_ring
+     cdef MPolynomialRing_libsingular _current_ring
+     cdef int _degbound
+-    cdef int __ngens
++    cdef int _ngens
+     cdef int _nb_slackvars
+     cdef object __monoid
+-    cdef public object __custom_name
+     cdef str exponents_to_string(self, E)
+     cdef str exponents_to_latex(self, E)
+     cdef tuple _degrees
+diff --git a/src/sage/algebras/letterplace/free_algebra_letterplace.pyx b/src/sage/algebras/letterplace/free_algebra_letterplace.pyx
+index e9c70c9de29..53f0dfdea6d 100644
+--- a/src/sage/algebras/letterplace/free_algebra_letterplace.pyx
++++ b/src/sage/algebras/letterplace/free_algebra_letterplace.pyx
+@@ -255,7 +255,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+         """
+         if not isinstance(R, MPolynomialRing_libsingular):
+             raise TypeError("a letterplace algebra must be provided by a polynomial ring of type %s" % MPolynomialRing_libsingular)
+-        self.__ngens = R.ngens()
++        self._ngens = R.ngens()
+         if degrees is None:
+             varnames = R.variable_names()
+             self._nb_slackvars = 0
+@@ -269,12 +269,12 @@ cdef class FreeAlgebra_letterplace(Algebra):
+         self._current_ring = make_letterplace_ring(R, 1)
+         self._degbound = 1
+         if degrees is None:
+-            self._degrees = tuple([int(1)] * self.__ngens)
++            self._degrees = tuple([int(1)] * self._ngens)
+         else:
+             if (not isinstance(degrees, (tuple, list))) \
+-                    or len(degrees) != self.__ngens - self._nb_slackvars \
++                    or len(degrees) != self._ngens - self._nb_slackvars \
+                     or any(i <= 0 for i in degrees):
+-                raise TypeError("the generator degrees must be given by a list or tuple of %d positive integers" % (self.__ngens - 1))
++                raise TypeError("the generator degrees must be given by a list or tuple of %d positive integers" % (self._ngens - 1))
+             self._degrees = tuple([int(i) for i in degrees])
+             self.set_degbound(max(self._degrees))
+         self._populate_coercion_lists_(coerce_list=[base_ring])
+@@ -305,7 +305,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F.ngens()
+             3
+         """
+-        return self.__ngens - self._nb_slackvars
++        return self._ngens - self._nb_slackvars
+ 
+     def gen(self, i):
+         """
+@@ -327,17 +327,17 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F.gen(2)
+             c
+         """
+-        if i >= self.__ngens - self._nb_slackvars:
+-            raise ValueError("this free algebra only has %d generators" % (self.__ngens - self._nb_slackvars))
++        if i >= self._ngens - self._nb_slackvars:
++            raise ValueError("this free algebra only has %d generators" % (self._ngens - self._nb_slackvars))
+         if self._gens is not None:
+             return self._gens[i]
+         deg = self._degrees[i]
+         # self.set_degbound(deg)
+         p = self._current_ring.gen(i)
+         cdef int n
+-        cdef int j = self.__ngens - 1
++        cdef int j = self._ngens - 1
+         for n in range(1, deg):
+-            j += self.__ngens
++            j += self._ngens
+             p *= self._current_ring.gen(j)
+         return FreeAlgebraElement_letterplace(self, p)
+ 
+@@ -413,7 +413,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: FreeAlgebra(QQ, implementation='letterplace', names=['x']).is_commutative()
+             True
+         """
+-        return self.__ngens - self._nb_slackvars <= 1
++        return self._ngens - self._nb_slackvars <= 1
+ 
+     def is_field(self, proof=True):
+         """
+@@ -430,7 +430,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F.is_field()
+             False
+         """
+-        return (not (self.__ngens - self._nb_slackvars)) and self._base.is_field(proof=proof)
++        return (not (self._ngens - self._nb_slackvars)) and self._base.is_field(proof=proof)
+ 
+     def _repr_(self):
+         """
+@@ -446,7 +446,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F
+             Free Associative Unital Algebra on 3 generators (x, y, z) over Rational Field
+         """
+-        return "Free Associative Unital Algebra on %d generators %s over %s" % (self.__ngens - self._nb_slackvars, self.gens(), self._base)
++        return "Free Associative Unital Algebra on %d generators %s over %s" % (self._ngens - self._nb_slackvars, self.gens(), self._base)
+ 
+     def _latex_(self):
+         r"""
+@@ -586,7 +586,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+               generated free abelian monoid.
+               In principle, this is correct, but it is not implemented, yet.>
+         """
+-        cdef int ngens = self.__ngens
++        cdef int ngens = self._ngens
+         cdef int nblocks = len(E) // ngens
+         cdef int i, j, base, exp, var_ind
+         cdef list out = []
+@@ -618,7 +618,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: latex(-(a*b*(z+1)-c)^2)     # indirect doctest
+             \left(2 z + 1\right) a b a b + \left(z + 1\right) a b c + \left(z + 1\right) c a b - c c
+         """
+-        cdef int ngens = self.__ngens
++        cdef int ngens = self._ngens
+         cdef int nblocks = len(E) // ngens
+         cdef int i, j, base, exp, var_ind
+         cdef list out = []
+@@ -678,7 +678,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+         cdef list out = []
+         C = self.current_ring()
+         cdef FreeAlgebraElement_letterplace x
+-        ngens = self.__ngens
++        ngens = self._ngens
+         cdef list G = [C(x._poly) for x in g]
+         from sage.groups.perm_gps.permgroup_named import CyclicPermutationGroup
+         CG = CyclicPermutationGroup(C.ngens())
+@@ -811,7 +811,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             l = len(e)
+             break
+         cdef dict out = {}
+-        self.set_degbound(l // self.__ngens)
++        self.set_degbound(l // self._ngens)
+         cdef Py_ssize_t n = self._current_ring.ngens()
+         for e, c in D.iteritems():
+             out[tuple(e) + (0,) * (n - l)] = c
+@@ -896,7 +896,7 @@ cdef class FreeAlgebra_letterplace_libsingular():
+         self._commutative_ring = commutative_ring
+ 
+     def __init__(self, commutative_ring, degbound):
+-        self.__ngens = commutative_ring.ngens() * degbound
++        self._ngens = commutative_ring.ngens() * degbound
+ 
+     def __dealloc__(self):
+         r"""
+diff --git a/src/sage/algebras/quatalg/quaternion_algebra_element.pyx b/src/sage/algebras/quatalg/quaternion_algebra_element.pyx
+index f6e87440fe9..8cb7e848fd0 100644
+--- a/src/sage/algebras/quatalg/quaternion_algebra_element.pyx
++++ b/src/sage/algebras/quatalg/quaternion_algebra_element.pyx
+@@ -1700,15 +1700,15 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra
+             x, y, z, w = v
+         cdef NumberFieldElement a = <NumberFieldElement>(parent._base(parent._a))
+         cdef NumberFieldElement b = <NumberFieldElement>(parent._base(parent._b))
+-        fmpz_poly_set_ZZX(self.x, (<NumberFieldElement>x).__numerator)
+-        fmpz_poly_set_ZZX(self.y, (<NumberFieldElement>y).__numerator)
+-        fmpz_poly_set_ZZX(self.z, (<NumberFieldElement>z).__numerator)
+-        fmpz_poly_set_ZZX(self.w, (<NumberFieldElement>w).__numerator)
++        fmpz_poly_set_ZZX(self.x, (<NumberFieldElement>x)._numerator)
++        fmpz_poly_set_ZZX(self.y, (<NumberFieldElement>y)._numerator)
++        fmpz_poly_set_ZZX(self.z, (<NumberFieldElement>z)._numerator)
++        fmpz_poly_set_ZZX(self.w, (<NumberFieldElement>w)._numerator)
+ 
+-        ZZ_to_mpz(T1, &(<NumberFieldElement>x).__denominator)
+-        ZZ_to_mpz(T2, &(<NumberFieldElement>y).__denominator)
+-        ZZ_to_mpz(t3, &(<NumberFieldElement>z).__denominator)
+-        ZZ_to_mpz(t4, &(<NumberFieldElement>w).__denominator)
++        ZZ_to_mpz(T1, &(<NumberFieldElement>x)._denominator)
++        ZZ_to_mpz(T2, &(<NumberFieldElement>y)._denominator)
++        ZZ_to_mpz(t3, &(<NumberFieldElement>z)._denominator)
++        ZZ_to_mpz(t4, &(<NumberFieldElement>w)._denominator)
+ 
+         mpz_lcm(self.d, T1, T2)
+         mpz_lcm(self.d, self.d, t3)
+@@ -1724,10 +1724,10 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra
+         fmpz_poly_scalar_mul_mpz(self.z, self.z, t3)
+         fmpz_poly_scalar_mul_mpz(self.w, self.w, t4)
+ 
+-        fmpz_poly_set_ZZX(self.a, a.__numerator)     # we will assume that the denominator of a and b are 1
+-        fmpz_poly_set_ZZX(self.b, b.__numerator)
++        fmpz_poly_set_ZZX(self.a, a._numerator)     # we will assume that the denominator of a and b are 1
++        fmpz_poly_set_ZZX(self.b, b._numerator)
+ 
+-        fmpz_poly_set_ZZX(self.modulus, (<NumberFieldElement>x).__fld_numerator.x)  # and same for the modulus
++        fmpz_poly_set_ZZX(self.modulus, (<NumberFieldElement>x)._fld_numerator.x)  # and same for the modulus
+ 
+     def __getitem__(self, int i):
+         """
+@@ -1756,17 +1756,17 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra
+         cdef NumberFieldElement item = el._new()
+ 
+         if i == 0:
+-            fmpz_poly_get_ZZX(item.__numerator, self.x)
++            fmpz_poly_get_ZZX(item._numerator, self.x)
+         elif i == 1:
+-            fmpz_poly_get_ZZX(item.__numerator, self.y)
++            fmpz_poly_get_ZZX(item._numerator, self.y)
+         elif i == 2:
+-            fmpz_poly_get_ZZX(item.__numerator, self.z)
++            fmpz_poly_get_ZZX(item._numerator, self.z)
+         elif i == 3:
+-            fmpz_poly_get_ZZX(item.__numerator, self.w)
++            fmpz_poly_get_ZZX(item._numerator, self.w)
+         else:
+             raise IndexError("quaternion element index out of range")
+ 
+-        mpz_to_ZZ(&item.__denominator, self.d)
++        mpz_to_ZZ(&item._denominator, self.d)
+ 
+         return item
+ 
+diff --git a/src/sage/categories/hopf_algebras_with_basis.py b/src/sage/categories/hopf_algebras_with_basis.py
+index 1be964cb6c9..615fc4eae06 100644
+--- a/src/sage/categories/hopf_algebras_with_basis.py
++++ b/src/sage/categories/hopf_algebras_with_basis.py
+@@ -36,7 +36,7 @@ class HopfAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
+         sage: A = C.example(); A                                                        # needs sage.groups
+         An example of Hopf algebra with basis: the group algebra of the
+          Dihedral group of order 6 as a permutation group over Rational Field
+-        sage: A.__custom_name = "A"                                                     # needs sage.groups
++        sage: A.rename("A")                                                             # needs sage.groups
+         sage: A.category()                                                              # needs sage.groups
+         Category of finite dimensional hopf algebras with basis over Rational Field
+ 
+diff --git a/src/sage/categories/modules_with_basis.py b/src/sage/categories/modules_with_basis.py
+index 65fd47cb890..fc1857f0c8e 100644
+--- a/src/sage/categories/modules_with_basis.py
++++ b/src/sage/categories/modules_with_basis.py
+@@ -66,8 +66,8 @@ class ModulesWithBasis(CategoryWithAxiom_over_base_ring):
+ 
+     Let `X` and `Y` be two modules with basis. We can build `Hom(X,Y)`::
+ 
+-        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.__custom_name = "X"             # needs sage.modules
+-        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.__custom_name = "Y"             # needs sage.modules
++        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.rename("X")                     # needs sage.modules
++        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.rename("Y")                     # needs sage.modules
+         sage: H = Hom(X, Y); H                                                          # needs sage.modules
+         Set of Morphisms from X to Y
+          in Category of finite dimensional vector spaces with basis over Rational Field
+diff --git a/src/sage/combinat/cluster_complex.py b/src/sage/combinat/cluster_complex.py
+index edc4f235aeb..e263d983887 100644
+--- a/src/sage/combinat/cluster_complex.py
++++ b/src/sage/combinat/cluster_complex.py
+@@ -222,10 +222,6 @@ def __init__(self, W, k, coxeter_element, algorithm):
+         self._W = W
+         self._w0 = w
+         self._k = k
+-        if k == 1:
+-            self.__custom_name = 'Cluster complex'
+-        else:
+-            self.__custom_name = 'Multi-cluster complex'
+ 
+         self.set_immutable()
+ 
+@@ -271,7 +267,10 @@ def _repr_(self):
+             sage: ClusterComplex(['A', 2])._repr_()
+             "Cluster complex of type ['A', 2] with 5 vertices and 5 facets"
+         """
+-        name = self.__custom_name
++        if self._k == 1:
++            name = 'Cluster complex'
++        else:
++            name = 'Multi-cluster complex'
+         name += (' of type %s with %s vertices and %s facets'
+                  % (self.cartan_type(), len(self.vertices()),
+                     len(self._facets)))
+diff --git a/src/sage/combinat/integer_lists/base.pxd b/src/sage/combinat/integer_lists/base.pxd
+index ecb5550a9cf..3d373a64fe0 100644
+--- a/src/sage/combinat/integer_lists/base.pxd
++++ b/src/sage/combinat/integer_lists/base.pxd
+@@ -12,4 +12,4 @@ cdef class IntegerListsBackend():
+     cdef readonly min_part, max_part
+     cdef readonly min_slope, max_slope
+     cdef readonly Envelope floor, ceiling
+-    cdef public dict __cached_methods  # Support cached_method
++    cdef public dict _cached_methods  # Support cached_method
+diff --git a/src/sage/combinat/subword_complex.py b/src/sage/combinat/subword_complex.py
+index b7489bdf754..de7eefe946e 100644
+--- a/src/sage/combinat/subword_complex.py
++++ b/src/sage/combinat/subword_complex.py
+@@ -1131,7 +1131,6 @@ def __init__(self, Q, w, algorithm="inductive"):
+         SimplicialComplex.__init__(self, maximal_faces=Fs,
+                                    maximality_check=False,
+                                    category=cat)
+-        self.__custom_name = 'Subword complex'
+         self._W = W
+         try:
+             T = W.coxeter_matrix().coxeter_type()
+diff --git a/src/sage/cpython/cython_metaclass.h b/src/sage/cpython/cython_metaclass.h
+index da06ab75a6b..ecf7f973c3e 100644
+--- a/src/sage/cpython/cython_metaclass.h
++++ b/src/sage/cpython/cython_metaclass.h
+@@ -52,6 +52,16 @@ static CYTHON_INLINE int Sage_PyType_Ready(PyTypeObject* t)
+     if (r < 0)
+         return r;
+ 
++#if PY_VERSION_HEX >= 0x03050000
++    // Cython 3 sets Py_TPFLAGS_HEAPTYPE before calling PyType_Ready,
++    // and resets just after the call. We need to reset it earlier,
++    // since otherwise the call to metaclass.__init__ below may have
++    // illegal memory accesses.
++    // See also:
++    // https://github.com/cython/cython/issues/3603
++    t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE;
++#endif
++
+     /* Set or get metaclass (the type of t) */
+     PyTypeObject* metaclass;
+ 
+diff --git a/src/sage/cpython/cython_metaclass.pyx b/src/sage/cpython/cython_metaclass.pyx
+index a8fe853661d..a8fa92fc1a8 100644
+--- a/src/sage/cpython/cython_metaclass.pyx
++++ b/src/sage/cpython/cython_metaclass.pyx
+@@ -19,13 +19,16 @@ file if you are using one).
+ 
+ In the extension type (a.k.a. ``cdef class``) for which you want to
+ define a metaclass, define a method ``__getmetaclass__`` with a single
+-unused argument. This method should return a type to be used as
++unused argument, and turn off the Cython directive
++``always_allow_keywords``. This method should return a type to be used as
+ metaclass:
+ 
+ .. code-block:: cython
+ 
++    cimport cython
+     cimport sage.cpython.cython_metaclass
+     cdef class MyCustomType():
++        @cython.always_allow_keywords(False)
+         def __getmetaclass__(_):
+             from foo import MyMetaclass
+             return MyMetaclass
+@@ -63,8 +66,10 @@ EXAMPLES::
+ 
+     sage: cython(                                                                       # needs sage.misc.cython
+     ....: '''
++    ....: cimport cython
+     ....: cimport sage.cpython.cython_metaclass
+     ....: cdef class MyCustomType():
++    ....:     @cython.always_allow_keywords(False)
+     ....:     def __getmetaclass__(_):
+     ....:         class MyMetaclass(type):
+     ....:             def __init__(*args):
+@@ -101,8 +106,10 @@ returns a non-type::
+ 
+     sage: cython(                                                                       # needs sage.misc.cython
+     ....: '''
++    ....: cimport cython
+     ....: cimport sage.cpython.cython_metaclass
+     ....: cdef class MyCustomType():
++    ....:     @cython.always_allow_keywords(False)
+     ....:     def __getmetaclass__(_):
+     ....:         return 2
+     ....: ''')
+diff --git a/src/sage/cpython/getattr.pyx b/src/sage/cpython/getattr.pyx
+index 3f603b98040..16f649c083d 100644
+--- a/src/sage/cpython/getattr.pyx
++++ b/src/sage/cpython/getattr.pyx
+@@ -271,7 +271,7 @@ cpdef getattr_from_other_class(self, cls, name):
+ 
+     Caveat: lazy attributes work with extension types only
+     if they allow attribute assignment or have a public attribute
+-    ``__cached_methods`` of type ``<dict>``. This condition
++    ``_cached_methods`` of type ``<dict>``. This condition
+     is satisfied, e.g., by any class that is derived from
+     :class:`Parent`::
+ 
+diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd
+index bdd49225ff2..030c9defa45 100644
+--- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd
++++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd
+@@ -8,7 +8,7 @@ from .polyhedron_face_lattice           cimport PolyhedronFaceLattice
+ 
+ @cython.final
+ cdef class CombinatorialPolyhedron(SageObject):
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+     # Do not assume any of those attributes to be initialized, use the corresponding methods instead.
+     cdef tuple _Vrep                       # the names of VRep, if they exist
+diff --git a/src/sage/groups/perm_gps/permgroup_element.pxd b/src/sage/groups/perm_gps/permgroup_element.pxd
+index a2ac8f20eaa..0a584745f96 100644
+--- a/src/sage/groups/perm_gps/permgroup_element.pxd
++++ b/src/sage/groups/perm_gps/permgroup_element.pxd
+@@ -22,7 +22,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement):
+     cpdef PermutationGroupElement _generate_new_GAP(self, old)
+     cpdef _gap_list(self)
+     cpdef domain(self)
+-    cdef public __custom_name
++    cdef public _SageObject__custom_name
+     cpdef list _act_on_list_on_position(self, list x)
+     cpdef ClonableIntArray _act_on_array_on_position(self, ClonableIntArray x)
+     cpdef ETuple _act_on_etuple_on_position(self, ETuple x)
+diff --git a/src/sage/interfaces/interface.py b/src/sage/interfaces/interface.py
+index f8237d3ad94..3180113c9c7 100644
+--- a/src/sage/interfaces/interface.py
++++ b/src/sage/interfaces/interface.py
+@@ -1169,11 +1169,8 @@ def __repr__(self):
+             s = cr
+         else:
+             s = self._repr_()
+-        if self._name in s:
+-            try:
+-                s = s.replace(self._name, getattr(self, '__custom_name'))
+-            except AttributeError:
+-                pass
++        if self._name in s and self.get_custom_name() is not None:
++            s = s.replace(self._name, self.get_custom_name())
+         if cr:
+             self._cached_repr = s
+         return s
+diff --git a/src/sage/interfaces/singular.py b/src/sage/interfaces/singular.py
+index 4b5c76e2bfa..705fa6f66e1 100644
+--- a/src/sage/interfaces/singular.py
++++ b/src/sage/interfaces/singular.py
+@@ -1400,8 +1400,8 @@ def _repr_(self):
+         """
+         s = super(SingularElement, self)._repr_()
+         if self._name in s:
+-            if (not hasattr(self, "__custom_name")) and self.type() == 'matrix':
+-                s = self.parent().eval('pmat(%s,20)'%(self.name()))
++            if self.get_custom_name() is None and self.type() == 'matrix':
++                s = self.parent().eval('pmat(%s,20)' % (self.name()))
+         return s
+ 
+     def __copy__(self):
+diff --git a/src/sage/libs/arb/arith.pyx b/src/sage/libs/arb/arith.pyx
+index d885f97b238..3b32fe7e8ed 100644
+--- a/src/sage/libs/arb/arith.pyx
++++ b/src/sage/libs/arb/arith.pyx
+@@ -81,5 +81,5 @@ def hilbert_class_polynomial(D):
+     cdef long n = D
+     cdef Polynomial_integer_dense_flint poly
+     poly = PolynomialRing(ZZ, "x", implementation="FLINT")()
+-    acb_modular_hilbert_class_poly(poly.__poly, n)
++    acb_modular_hilbert_class_poly(poly._poly, n)
+     return poly
+diff --git a/src/sage/libs/coxeter3/coxeter.pxd b/src/sage/libs/coxeter3/coxeter.pxd
+index 9d5cb2a3f5d..dbd2b8a61c6 100644
+--- a/src/sage/libs/coxeter3/coxeter.pxd
++++ b/src/sage/libs/coxeter3/coxeter.pxd
+@@ -29,6 +29,3 @@ cdef class CoxGroupElement:
+     cdef CoxGroup _parent_group
+     cdef CoxGroupElement _new(self)
+     cpdef CoxGroup parent_group(self)
+-
+-cdef class CoxGraph:
+-    cdef c_CoxGraph x
+diff --git a/src/sage/libs/gap/element.pyx b/src/sage/libs/gap/element.pyx
+index 1dc53c81f67..478caf9f9d0 100644
+--- a/src/sage/libs/gap/element.pyx
++++ b/src/sage/libs/gap/element.pyx
+@@ -720,7 +720,7 @@ cdef class GapElement(RingElement):
+             ...
+             AttributeError: 'some_name' does not define a GAP function
+         """
+-        if name in ('__dict__', '_getAttributeNames', '__custom_name', 'keys'):
++        if name in ('__dict__', '_getAttributeNames', '_SageObject__custom_name', 'keys'):
+             raise AttributeError('Python special name, not a GAP function.')
+         try:
+             proxy = make_GapElement_MethodProxy\
+diff --git a/src/sage/libs/gap/gap_includes.pxd b/src/sage/libs/gap/gap_includes.pxd
+index 840b8a0042e..1ed4378a6c7 100644
+--- a/src/sage/libs/gap/gap_includes.pxd
++++ b/src/sage/libs/gap/gap_includes.pxd
+@@ -144,3 +144,18 @@ cdef extern from "gap/stringobj.h" nogil:
+     bint IS_STRING(Obj obj)
+     bint IsStringConv(Obj obj)
+     Obj NEW_STRING(Int)
++
++
++cdef extern from "<structmember.h>" nogil:
++    """
++    /* Hack: Cython 3.0 automatically includes <structmember.h>, which
++     * defines several macros that collides with enum definitions in
++     * gap/objects.h. We need to include the header explicitly and
++     * undefine these macros.
++     */
++    #undef T_INT
++    #undef T_STRING
++    #undef T_CHAR
++    #undef T_BOOL
++    """
++    pass
+diff --git a/src/sage/libs/lcalc/lcalc_Lfunction.pxd b/src/sage/libs/lcalc/lcalc_Lfunction.pxd
+index 5edf0844f3e..1d595180a6f 100644
+--- a/src/sage/libs/lcalc/lcalc_Lfunction.pxd
++++ b/src/sage/libs/lcalc/lcalc_Lfunction.pxd
+@@ -99,19 +99,19 @@ cdef extern from "lcalc_sage.h":
+ ################
+ 
+ # strange bug, I can't compile without this trick ???
+-# it's only used in __typedN
++# it's only used in _typedN
+ ctypedef double Double
+ 
+ cdef class Lfunction:
+     cdef void *thisptr
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r)
+-    cdef c_Complex __value(self,c_Complex s,int derivative)
+-    cdef c_Complex __hardy_z_function(self,c_Complex s)
+-    cdef int __compute_rank(self)
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r)
++    cdef c_Complex _value(self,c_Complex s,int derivative)
++    cdef c_Complex _hardy_z_function(self,c_Complex s)
++    cdef int _compute_rank(self)
+     #strange bug, replacing Double with double gives me a compile error
+-    cdef Double __typedN(self, double T)
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize,doublevec *result)
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec* result)
++    cdef Double _typedN(self, double T)
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize,doublevec *result)
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec* result)
+ 
+     cdef str _repr
+ 
+diff --git a/src/sage/libs/lcalc/lcalc_Lfunction.pyx b/src/sage/libs/lcalc/lcalc_Lfunction.pyx
+index 6e9005c502b..7b871ed049f 100644
+--- a/src/sage/libs/lcalc/lcalc_Lfunction.pyx
++++ b/src/sage/libs/lcalc/lcalc_Lfunction.pyx
+@@ -99,7 +99,7 @@ cdef class Lfunction:
+             tmpc=CCC(residue[i])
+             r[i+1] = new_Complex(mpfr_get_d(tmpc.__re, MPFR_RNDN), mpfr_get_d(tmpc.__im, MPFR_RNDN))
+ 
+-        self.__init_fun(NAME, what_type, dirichlet_coefficient, Period, q,  w,  A, g, l, n_poles, p, r)
++        self._init_fun(NAME, what_type, dirichlet_coefficient, Period, q,  w,  A, g, l, n_poles, p, r)
+ 
+         if name:
+             name += ': '
+@@ -180,7 +180,7 @@ cdef class Lfunction:
+         """
+         cdef ComplexNumber complexified_s = CCC(s)
+         cdef c_Complex z = new_Complex(mpfr_get_d(complexified_s.__re, MPFR_RNDN), mpfr_get_d(complexified_s.__im, MPFR_RNDN))
+-        cdef c_Complex result = self.__value(z, derivative)
++        cdef c_Complex result = self._value(z, derivative)
+         return CCC(result.real(),result.imag())
+ 
+     def hardy_z_function(self, s):
+@@ -223,7 +223,7 @@ cdef class Lfunction:
+         #This takes s -> .5 + I*s
+         cdef ComplexNumber complexified_s = CCC(0.5)+ CCC(0,1)*CCC(s)
+         cdef c_Complex z = new_Complex(mpfr_get_d(complexified_s.__re, MPFR_RNDN), mpfr_get_d(complexified_s.__im, MPFR_RNDN))
+-        cdef c_Complex result = self.__hardy_z_function(z)
++        cdef c_Complex result = self._hardy_z_function(z)
+         return CCC(result.real(),result.imag())
+ 
+ 
+@@ -249,9 +249,9 @@ cdef class Lfunction:
+             3
+ 
+         """
+-        return self.__compute_rank()
++        return self._compute_rank()
+ 
+-    def __N(self, T):
++    def _N(self, T):
+         """
+         Compute the number of zeroes upto height `T` using the formula for
+         `N(T)` with the error of `S(T)`. Please do not use this. It is only
+@@ -262,12 +262,12 @@ cdef class Lfunction:
+             sage: from sage.libs.lcalc.lcalc_Lfunction import *
+             sage: chi = DirichletGroup(5)[2] #This is a quadratic character
+             sage: L=Lfunction_from_character(chi, type="complex")
+-            sage: L.__N(10) # abs tol 1e-8
++            sage: L._N(10) # abs tol 1e-8
+             4.0
+         """
+         cdef RealNumber real_T=RRR(T)
+         cdef double double_T = mpfr_get_d(real_T.value, MPFR_RNDN)
+-        cdef double res_d = self.__typedN(double_T)
++        cdef double res_d = self._typedN(double_T)
+         return RRR(res_d)
+ 
+     def find_zeros(self, T1, T2, stepsize):
+@@ -323,7 +323,7 @@ cdef class Lfunction:
+         cdef RealNumber real_T2 = RRR(T2)
+         cdef RealNumber real_stepsize = RRR(stepsize)
+         sig_on()
+-        self.__find_zeros_v( mpfr_get_d(real_T1.value, MPFR_RNDN), mpfr_get_d(real_T2.value, MPFR_RNDN), mpfr_get_d(real_stepsize.value, MPFR_RNDN),&result)
++        self._find_zeros_v( mpfr_get_d(real_T1.value, MPFR_RNDN), mpfr_get_d(real_T2.value, MPFR_RNDN), mpfr_get_d(real_stepsize.value, MPFR_RNDN),&result)
+         sig_off()
+         i=result.size()
+         returnvalue = []
+@@ -399,7 +399,7 @@ cdef class Lfunction:
+         cdef const char* message_stamp = ""
+         cdef doublevec result
+         sig_on()
+-        self.__find_zeros(count, start, max_refine, rank, message_stamp, &result)
++        self._find_zeros(count, start, max_refine, rank, message_stamp, &result)
+         sig_off()
+         returnvalue = []
+         for i in range(result.size()):
+@@ -408,25 +408,25 @@ cdef class Lfunction:
+         return returnvalue
+ 
+     # Needs to be overriden
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         raise NotImplementedError
+ 
+-    cdef c_Complex __value(self,c_Complex s,int derivative):
++    cdef c_Complex _value(self,c_Complex s,int derivative):
+         raise NotImplementedError
+ 
+-    cdef c_Complex __hardy_z_function(self,c_Complex s):
++    cdef c_Complex _hardy_z_function(self,c_Complex s):
+         raise NotImplementedError
+ 
+-    cdef int __compute_rank(self):
++    cdef int _compute_rank(self):
+         raise NotImplementedError
+ 
+-    cdef double __typedN(self,double T):
++    cdef double _typedN(self,double T):
+         raise NotImplementedError
+ 
+-    cdef void __find_zeros_v(self,double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self,double T1, double T2, double stepsize, doublevec *result):
+         raise NotImplementedError
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         raise NotImplementedError
+ 
+ ##############################################################################
+@@ -497,7 +497,7 @@ cdef class Lfunction_I(Lfunction):
+         self._repr += " with integer Dirichlet coefficients"
+ 
+     # override
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         cdef int N = len(dirichlet_coeff)
+         cdef Integer tmpi
+         cdef int * coeffs = new_ints(N+1) #lcalc ignores 0the coefficient
+@@ -507,22 +507,22 @@ cdef class Lfunction_I(Lfunction):
+         self.thisptr=new_c_Lfunction_I(NAME, what_type,  N, coeffs, Period, q,  w,  A, g, l, n_poles, p, r)
+         del_ints(coeffs)
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_I *>(self.thisptr)).value(s, derivative, "pure")
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_I *>(self.thisptr)).value(s, 0, "rotated pure")
+ 
+-    cdef int __compute_rank(self):
++    cdef int _compute_rank(self):
+         return (<c_Lfunction_I *>(self.thisptr)).compute_rank()
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_I *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_I *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_I *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     # debug tools
+@@ -633,7 +633,7 @@ cdef class Lfunction_D(Lfunction):
+         self._repr += " with real Dirichlet coefficients"
+ 
+     # override
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         cdef int i
+         cdef RealNumber tmpr
+         cdef int N = len(dirichlet_coeff)
+@@ -644,23 +644,23 @@ cdef class Lfunction_D(Lfunction):
+         self.thisptr=new_c_Lfunction_D(NAME, what_type,  N, coeffs, Period, q,  w,  A, g, l, n_poles, p, r)
+         del_doubles(coeffs)
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_D *>(self.thisptr)).value(s, derivative, "pure")
+ 
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_D *>(self.thisptr)).value(s, 0, "rotated pure")
+ 
+-    cdef inline int __compute_rank(self):
++    cdef inline int _compute_rank(self):
+         return (<c_Lfunction_D *>(self.thisptr)).compute_rank()
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_D *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_D *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start,double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start,double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_D *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     # debug tools
+@@ -773,7 +773,7 @@ cdef class Lfunction_C:
+         self._repr += " with complex Dirichlet coefficients"
+ 
+     # override
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         cdef int i
+         cdef int N = len(dirichlet_coeff)
+         cdef ComplexNumber tmpc
+@@ -788,24 +788,24 @@ cdef class Lfunction_C:
+ 
+         del_Complexes(coeffs)
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_C *>(self.thisptr)).value(s, derivative, "pure")
+ 
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_C *>(self.thisptr)).value(s, 0,"rotated pure")
+ 
+-    cdef inline int __compute_rank(self):
++    cdef inline int _compute_rank(self):
+         return (<c_Lfunction_C *>(self.thisptr)).compute_rank()
+ 
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_C *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_C *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_C *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     # debug tools
+@@ -873,24 +873,24 @@ cdef class Lfunction_Zeta(Lfunction):
+         self.thisptr = new_c_Lfunction_Zeta()
+         self._repr = "The Riemann zeta function"
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_Zeta *>(self.thisptr)).value(s, derivative, "pure")
+ 
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_Zeta *>(self.thisptr)).value(s, 0, "rotated pure")
+ 
+-    cdef inline int __compute_rank(self):
++    cdef inline int _compute_rank(self):
+         return (<c_Lfunction_Zeta *>(self.thisptr)).compute_rank()
+ 
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_Zeta *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_Zeta *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_Zeta *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     def __dealloc__(self):
+diff --git a/src/sage/libs/linkages/padics/Polynomial_ram.pxi b/src/sage/libs/linkages/padics/Polynomial_ram.pxi
+index 1ac51f1211f..e0584ecb8ad 100644
+--- a/src/sage/libs/linkages/padics/Polynomial_ram.pxi
++++ b/src/sage/libs/linkages/padics/Polynomial_ram.pxi
+@@ -55,16 +55,16 @@ cdef inline bint creduce(celement out, celement a, long prec, PowComputer_ prime
+     """
+     cdef celement ared = a % prime_pow.modulus
+     if ared is a and out is not a:
+-        out.__coeffs = ared.__coeffs[:]
++        out._coeffs = ared._coeffs[:]
+     else:
+-        out.__coeffs = ared.__coeffs
++        out._coeffs = ared._coeffs
+     cdef long coeff_prec = prec / prime_pow.e + 1
+     cdef long break_pt = prec % prime_pow.e
+-    for i in range(len(out.__coeffs)):
++    for i in range(len(out._coeffs)):
+         if i == break_pt:
+             coeff_prec -= 1
+-        out.__coeffs[i] = out.__coeffs[i].add_bigoh(coeff_prec)
+-    out.__normalize()
++        out._coeffs[i] = out._coeffs[i].add_bigoh(coeff_prec)
++    out._normalize()
+     return out == 0
+ 
+ cdef inline bint creduce_small(celement out, celement a, long prec, PowComputer_ prime_pow) except -1:
+@@ -116,7 +116,7 @@ cdef inline long cvaluation(celement a, long prec, PowComputer_ prime_pow) excep
+     higher.
+ 
+     """
+-    C = a.__coeffs
++    C = a._coeffs
+     if not C:
+         return prec
+     cdef long ret = maxordp
+@@ -161,7 +161,7 @@ cdef inline int cshift(celement shifted, celement rem, celement a, long n, long
+         v = cvaluation(a, prec, prime_pow)
+         notrunc = (v >= -n)
+     if notrunc:
+-        rem.__coeffs = []
++        rem._coeffs = []
+         return cshift_notrunc(shifted, a, n, prec, prime_pow, reduce_afterward)
+     if v > 0:
+         b = prime_pow.poly_ring(0)
+@@ -185,7 +185,7 @@ cdef inline int cshift(celement shifted, celement rem, celement a, long n, long
+     if reduce_afterward:
+         creduce(shifted, a, prec, prime_pow)
+     else:
+-        shifted.__coeffs = a.__coeffs[:]
++        shifted._coeffs = a._coeffs[:]
+ 
+ cdef inline int cshift_notrunc(celement out, celement a, long n, long prec, PowComputer_ prime_pow, bint reduce_afterward) except -1:
+     r"""
+@@ -236,7 +236,7 @@ cdef inline int cshift_notrunc(celement out, celement a, long n, long prec, PowC
+     if reduce_afterward:
+         creduce(out, a, prec, prime_pow)
+     else:
+-        out.__coeffs = a.__coeffs[:]
++        out._coeffs = a._coeffs[:]
+ 
+ cdef inline int cinvert(celement out, celement a, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -253,7 +253,7 @@ cdef inline int cinvert(celement out, celement a, long prec, PowComputer_ prime_
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = prime_pow.invert(a, prec).__coeffs
++    out._coeffs = prime_pow.invert(a, prec)._coeffs
+     creduce(out, out, prec, prime_pow)
+ 
+ cdef inline int cdivunit(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+@@ -335,7 +335,7 @@ cdef inline cexpansion_next(celement value, expansion_mode mode, long curpower,
+     # the following is specific to the ramified over unramified case.
+     modp_rep, term = value[0]._modp_rep(mode == smallest_mode)
+     if term:
+-        value.__coeffs[0] -= modp_rep
++        value._coeffs[0] -= modp_rep
+     cshift_notrunc(value, value, -1, curpower, prime_pow, False)
+     return term
+ 
+@@ -354,10 +354,10 @@ cdef inline cexpansion_getitem(celement value, long m, PowComputer_ prime_pow):
+     while m >= 0:
+         modp_rep, term = value[0]._modp_rep()
+         if m:
+-            if len(value.__coeffs):
+-                value.__coeffs[0] -= modp_rep
++            if len(value._coeffs):
++                value._coeffs[0] -= modp_rep
+             else:
+-                value.__coeffs.append(-modp_rep)
++                value._coeffs.append(-modp_rep)
+             cshift_notrunc(value, value, -1, 1, prime_pow, False)
+         m -= 1
+     return term
+@@ -379,9 +379,9 @@ cdef int cteichmuller(celement out, celement value, long prec, PowComputer_ prim
+ 
+     """
+     if value[0].valuation() > 0:
+-        out.__coeffs = []
++        out._coeffs = []
+     else:
+-        out.__coeffs = [value[0].parent().teichmuller(value[0])]
++        out._coeffs = [value[0].parent().teichmuller(value[0])]
+ 
+ cdef list ccoefficients(celement x, long valshift, long prec, PowComputer_ prime_pow):
+     """
+diff --git a/src/sage/libs/linkages/padics/Polynomial_shared.pxi b/src/sage/libs/linkages/padics/Polynomial_shared.pxi
+index 495dc6b0848..367bbc2f33d 100644
+--- a/src/sage/libs/linkages/padics/Polynomial_shared.pxi
++++ b/src/sage/libs/linkages/padics/Polynomial_shared.pxi
+@@ -106,7 +106,7 @@ cdef inline int ccmp(celement a, celement b, long prec, bint reduce_a, bint redu
+     if not (reduce_a or reduce_b):
+         return 0 if a == b else 1
+     csub(prime_pow.tmp_ccmp_a, a, b, prec, prime_pow)
+-    coeffs = prime_pow.tmp_ccmp_a.__coeffs
++    coeffs = prime_pow.tmp_ccmp_a._coeffs
+     cdef long i, coeff_prec, break_pt
+     if prime_pow.e == 1:
+         for i in range(prime_pow.tmp_ccmp_a.degree()+1):
+@@ -186,9 +186,9 @@ cdef inline int cneg(celement out, celement a, long prec, PowComputer_ prime_pow
+     """
+     cdef celement ma = -a
+     if ma is a:
+-        out.__coeffs = ma.__coeffs[:]
++        out._coeffs = ma._coeffs[:]
+     else:
+-        out.__coeffs = ma.__coeffs
++        out._coeffs = ma._coeffs
+ 
+ cdef inline int cadd(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -211,9 +211,9 @@ cdef inline int cadd(celement out, celement a, celement b, long prec, PowCompute
+     """
+     cdef celement sm = a + b
+     if sm is a or sm is b:
+-        out.__coeffs = sm.__coeffs[:]
++        out._coeffs = sm._coeffs[:]
+     else:
+-        out.__coeffs = sm.__coeffs
++        out._coeffs = sm._coeffs
+ 
+ cdef inline int csub(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -236,9 +236,9 @@ cdef inline int csub(celement out, celement a, celement b, long prec, PowCompute
+     """
+     cdef celement df = a - b
+     if df is a or df is b:
+-        out.__coeffs = df.__coeffs[:]
++        out._coeffs = df._coeffs[:]
+     else:
+-        out.__coeffs = df.__coeffs
++        out._coeffs = df._coeffs
+ 
+ cdef inline int cmul(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -261,9 +261,9 @@ cdef inline int cmul(celement out, celement a, celement b, long prec, PowCompute
+     """
+     cdef celement pd = a*b
+     if pd is a or pd is b:
+-        out.__coeffs = pd.__coeffs[:]
++        out._coeffs = pd._coeffs[:]
+     else:
+-        out.__coeffs = pd.__coeffs
++        out._coeffs = pd._coeffs
+ 
+ cdef inline int csetone(celement out, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -276,7 +276,7 @@ cdef inline int csetone(celement out, PowComputer_ prime_pow) except -1:
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = [prime_pow.base_ring(1)]
++    out._coeffs = [prime_pow.base_ring(1)]
+ 
+ cdef inline int csetzero(celement out, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -289,7 +289,7 @@ cdef inline int csetzero(celement out, PowComputer_ prime_pow) except -1:
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = []
++    out._coeffs = []
+ 
+ cdef inline bint cisone(celement a, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -330,7 +330,7 @@ cdef inline int ccopy(celement out, celement a, PowComputer_ prime_pow) except -
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = a.__coeffs[:]
++    out._coeffs = a._coeffs[:]
+ 
+ cdef inline cpickle(celement a, PowComputer_ prime_pow):
+     r"""
+@@ -343,7 +343,7 @@ cdef inline cpickle(celement a, PowComputer_ prime_pow):
+     - ``prime_pow`` the ``PowComputer`` for the ring
+ 
+     """
+-    return a.__coeffs
++    return a._coeffs
+ 
+ cdef inline int cunpickle(celement out, x, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -358,7 +358,7 @@ cdef inline int cunpickle(celement out, x, PowComputer_ prime_pow) except -1:
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = x
++    out._coeffs = x
+ 
+ cdef inline long chash(celement a, long ordp, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -413,9 +413,9 @@ cdef int cconv(celement out, x, long prec, long valshift, PowComputer_ prime_pow
+     else:
+         xx = prime_pow.poly_ring(x)
+     if xx is x:
+-        out.__coeffs = xx.__coeffs[:]
++        out._coeffs = xx._coeffs[:]
+     else:
+-        out.__coeffs = xx.__coeffs
++        out._coeffs = xx._coeffs
+     if valshift > 0:
+         cshift_notrunc(out, out, -valshift, prec, prime_pow, True)
+     elif valshift == 0:
+@@ -458,12 +458,12 @@ cdef inline long cconv_mpz_t(celement out, mpz_t x, long prec, bint absolute, Po
+     mpz_set(n.value, x)
+ 
+     if n:
+-        out.__coeffs = [prime_pow.base_ring(n)]
++        out._coeffs = [prime_pow.base_ring(n)]
+         if not absolute:
+             valuation = cremove(out, out, prec, prime_pow)
+         creduce(out, out, prec, prime_pow)
+     else:
+-        out.__coeffs = []
++        out._coeffs = []
+ 
+     return valuation
+ 
+@@ -492,12 +492,12 @@ cdef inline int cconv_mpz_t_out(mpz_t out, celement x, long valshift, long prec,
+     else:
+         prime_pow.powhelper_cconv_out = x
+ 
+-    if len(prime_pow.powhelper_cconv_out.__coeffs) == 0:
++    if len(prime_pow.powhelper_cconv_out._coeffs) == 0:
+         mpz_set_ui(out, 0)
+-    elif len(prime_pow.powhelper_cconv_out.__coeffs) == 1:
++    elif len(prime_pow.powhelper_cconv_out._coeffs) == 1:
+         # recursively let the underlying polynomial convert the constant
+         # coefficient to an integer (if possible)
+-        n = ZZ(prime_pow.powhelper_cconv_out.__coeffs[0])
++        n = ZZ(prime_pow.powhelper_cconv_out._coeffs[0])
+         mpz_set(out, n.value)
+     else:
+         raise ValueError("cannot convert to integer")
+@@ -532,7 +532,7 @@ cdef inline long cconv_mpq_t(celement out, mpq_t x, long prec, bint absolute, Po
+     """
+     cdef Rational r = PY_NEW(Rational)
+     mpq_set(r.value, x)
+-    out.__coeffs = [prime_pow.base_ring(r)]
++    out._coeffs = [prime_pow.base_ring(r)]
+ 
+     if not absolute:
+         return cremove(out, out, prec, prime_pow)
+@@ -565,12 +565,12 @@ cdef inline int cconv_mpq_t_out(mpq_t out, celement x, long valshift, long prec,
+     else:
+         prime_pow.powhelper_cconv_out = x
+ 
+-    if len(prime_pow.powhelper_cconv_out.__coeffs) == 0:
++    if len(prime_pow.powhelper_cconv_out._coeffs) == 0:
+         mpq_set_ui(out, 0, 1)
+-    elif len(prime_pow.powhelper_cconv_out.__coeffs) == 1:
++    elif len(prime_pow.powhelper_cconv_out._coeffs) == 1:
+         # recursively let the underlying polynomial convert the constant
+         # coefficient to a rational (if possible)
+-        c = QQ(prime_pow.powhelper_cconv_out.__coeffs[0])
++        c = QQ(prime_pow.powhelper_cconv_out._coeffs[0])
+         mpq_set(out, c.value)
+     else:
+         raise ValueError("cannot convert to rational")
+diff --git a/src/sage/libs/ntl/ntl_lzz_p.pyx b/src/sage/libs/ntl/ntl_lzz_p.pyx
+index 161d0782bc2..af86b9bcf69 100644
+--- a/src/sage/libs/ntl/ntl_lzz_p.pyx
++++ b/src/sage/libs/ntl/ntl_lzz_p.pyx
+@@ -89,19 +89,19 @@ cdef class ntl_zz_p():
+         #self.c.restore_c()   ## This was done in __new__
+ 
+         if isinstance(a, IntegerMod_int):
+-            if (self.c.p == (<IntegerMod_int>a).__modulus.int32): ## this is slow
++            if (self.c.p == (<IntegerMod_int>a)._modulus.int32): ## this is slow
+                 self.x = (<IntegerMod_int>a).ivalue
+             else:
+                 raise ValueError("Mismatched modulus for converting to zz_p.")
+ 
+         elif isinstance(a, IntegerMod_int64):
+-            if (self.c.p == (<IntegerMod_int64>a).__modulus.int64): ## this is slow
++            if (self.c.p == (<IntegerMod_int64>a)._modulus.int64): ## this is slow
+                 self.x = (<IntegerMod_int64>a).ivalue
+             else:
+                 raise ValueError("Mismatched modulus for converting to zz_p.")
+ 
+         elif isinstance(a, IntegerMod_gmp):
+-            if (p_sage == (<IntegerMod_gmp>a).__modulus.sageInteger): ## this is slow
++            if (p_sage == (<IntegerMod_gmp>a)._modulus.sageInteger): ## this is slow
+                 self.x = mpz_get_si((<IntegerMod_gmp>a).value)
+             else:
+                 raise ValueError("Mismatched modulus for converting to zz_p.")
+diff --git a/src/sage/libs/ntl/ntl_lzz_pX.pyx b/src/sage/libs/ntl/ntl_lzz_pX.pyx
+index 24b503a9a62..7d19cc55e37 100644
+--- a/src/sage/libs/ntl/ntl_lzz_pX.pyx
++++ b/src/sage/libs/ntl/ntl_lzz_pX.pyx
+@@ -108,17 +108,17 @@ cdef class ntl_zz_pX():
+             a = ls[i]
+ 
+             if isinstance(a, IntegerMod_int):
+-                if (self.c.p == (<IntegerMod_int>a).__modulus.int32): ## this is slow
++                if (self.c.p == (<IntegerMod_int>a)._modulus.int32): ## this is slow
+                     zz_pX_SetCoeff_long(self.x, i, (<IntegerMod_int>a).ivalue)
+                 else:
+                     raise ValueError("Mismatched modulus for converting to zz_pX.")
+             elif isinstance(a, IntegerMod_int64):
+-                if (self.c.p == (<IntegerMod_int64>a).__modulus.int64): ## this is slow
++                if (self.c.p == (<IntegerMod_int64>a)._modulus.int64): ## this is slow
+                     zz_pX_SetCoeff_long(self.x, i, (<IntegerMod_int64>a).ivalue)
+                 else:
+                     raise ValueError("Mismatched modulus for converting to zz_pX.")
+             elif isinstance(a, IntegerMod_gmp):
+-                if (p_sage == (<IntegerMod_gmp>a).__modulus.sageInteger): ## this is slow
++                if (p_sage == (<IntegerMod_gmp>a)._modulus.sageInteger): ## this is slow
+                     zz_pX_SetCoeff_long(self.x, i, mpz_get_si((<IntegerMod_gmp>a).value))
+                 else:
+                     raise ValueError("Mismatched modulus for converting to zz_pX.")
+diff --git a/src/sage/matrix/matrix_complex_ball_dense.pyx b/src/sage/matrix/matrix_complex_ball_dense.pyx
+index 9e14079c6d4..47ca41070fa 100644
+--- a/src/sage/matrix/matrix_complex_ball_dense.pyx
++++ b/src/sage/matrix/matrix_complex_ball_dense.pyx
+@@ -664,7 +664,7 @@ cdef class Matrix_complex_ball_dense(Matrix_dense):
+         Pol = polynomial_ring_constructor._single_variate(self.base_ring(), var)
+         cdef Polynomial_complex_arb res = Polynomial_complex_arb(Pol)
+         sig_on()
+-        acb_mat_charpoly(res.__poly, self.value, prec(self))
++        acb_mat_charpoly(res._poly, self.value, prec(self))
+         sig_off()
+         return res
+ 
+diff --git a/src/sage/matrix/matrix_cyclo_dense.pyx b/src/sage/matrix/matrix_cyclo_dense.pyx
+index 15ff6394951..f1ed9af8403 100644
+--- a/src/sage/matrix/matrix_cyclo_dense.pyx
++++ b/src/sage/matrix/matrix_cyclo_dense.pyx
+@@ -396,11 +396,11 @@ cdef class Matrix_cyclo_dense(Matrix_dense):
+             # Now set k-th entry of x's numerator to tmp
+             fmpz_get_mpz(tmp, ftmp)
+             mpz_to_ZZ(&coeff, tmp)
+-            ZZX_SetCoeff(x.__numerator, k, coeff)
++            ZZX_SetCoeff(x._numerator, k, coeff)
+ 
+         # Set the denominator of x to denom.
+         fmpz_get_mpz(tmp, denom)
+-        mpz_to_ZZ(&x.__denominator, tmp)
++        mpz_to_ZZ(&x._denominator, tmp)
+         fmpz_clear(denom)
+         mpz_clear(tmp)
+         fmpz_clear(ftmp)
+diff --git a/src/sage/matrix/matrix_integer_dense.pyx b/src/sage/matrix/matrix_integer_dense.pyx
+index 9c509104967..8088350577c 100644
+--- a/src/sage/matrix/matrix_integer_dense.pyx
++++ b/src/sage/matrix/matrix_integer_dense.pyx
+@@ -1371,12 +1371,12 @@ cdef class Matrix_integer_dense(Matrix_dense):
+         if algorithm == 'flint':
+             g = (<Polynomial_integer_dense_flint> PolynomialRing(ZZ, names=var).gen())._new()
+             sig_on()
+-            fmpz_mat_charpoly(g.__poly, self._matrix)
++            fmpz_mat_charpoly(g._poly, self._matrix)
+             sig_off()
+         elif algorithm == 'linbox':
+             g = (<Polynomial_integer_dense_flint> PolynomialRing(ZZ, names=var).gen())._new()
+             sig_on()
+-            linbox_fmpz_mat_charpoly(g.__poly, self._matrix)
++            linbox_fmpz_mat_charpoly(g._poly, self._matrix)
+             sig_off()
+         elif algorithm == 'generic':
+             g = Matrix_dense.charpoly(self, var)
+@@ -1460,7 +1460,7 @@ cdef class Matrix_integer_dense(Matrix_dense):
+         if algorithm == 'linbox':
+             g = (<Polynomial_integer_dense_flint> PolynomialRing(ZZ, names=var).gen())._new()
+             sig_on()
+-            linbox_fmpz_mat_minpoly(g.__poly, self._matrix)
++            linbox_fmpz_mat_minpoly(g._poly, self._matrix)
+             sig_off()
+         elif algorithm == 'generic':
+             g = Matrix_dense.minpoly(self, var)
+diff --git a/src/sage/matrix/matrix_integer_sparse.pyx b/src/sage/matrix/matrix_integer_sparse.pyx
+index a41677c7b6a..83d5ee42fbe 100644
+--- a/src/sage/matrix/matrix_integer_sparse.pyx
++++ b/src/sage/matrix/matrix_integer_sparse.pyx
+@@ -869,10 +869,10 @@ cdef class Matrix_integer_sparse(Matrix_sparse):
+         sig_off()
+ 
+         cdef size_t i
+-        fmpz_poly_fit_length(g.__poly, p.size())
++        fmpz_poly_fit_length(g._poly, p.size())
+         for i in range(p.size()):
+-            fmpz_poly_set_coeff_mpz(g.__poly, i, p[0][i].get_mpz_const())
+-        _fmpz_poly_set_length(g.__poly, p.size())
++            fmpz_poly_set_coeff_mpz(g._poly, i, p[0][i].get_mpz_const())
++        _fmpz_poly_set_length(g._poly, p.size())
+ 
+         del M
+         del p
+@@ -968,10 +968,10 @@ cdef class Matrix_integer_sparse(Matrix_sparse):
+         sig_off()
+ 
+         cdef size_t i
+-        fmpz_poly_fit_length(g.__poly, p.size())
++        fmpz_poly_fit_length(g._poly, p.size())
+         for i in range(p.size()):
+-            fmpz_poly_set_coeff_mpz(g.__poly, i, p[0][i].get_mpz_const())
+-        _fmpz_poly_set_length(g.__poly, p.size())
++            fmpz_poly_set_coeff_mpz(g._poly, i, p[0][i].get_mpz_const())
++        _fmpz_poly_set_length(g._poly, p.size())
+ 
+         del M
+         del p
+diff --git a/src/sage/matroids/basis_exchange_matroid.pxd b/src/sage/matroids/basis_exchange_matroid.pxd
+index aec3bb54c42..28cc7ad868c 100644
+--- a/src/sage/matroids/basis_exchange_matroid.pxd
++++ b/src/sage/matroids/basis_exchange_matroid.pxd
+@@ -15,13 +15,13 @@ cdef class BasisExchangeMatroid(Matroid):
+     cdef _weak_invariant_var, _strong_invariant_var, _heuristic_invariant_var
+     cdef SetSystem _weak_partition_var, _strong_partition_var, _heuristic_partition_var
+ 
+-    cdef __relabel(self, l)
++    cdef _relabel(self, l)
+ 
+-    cdef __pack(self, bitset_t, X)
++    cdef _pack(self, bitset_t, X)
+     cdef __unpack(self, bitset_t)
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1
+-    cdef int __exchange(self, long x, long y) except -1
+-    cdef int __move(self, bitset_t X, bitset_t Y) except -1
++    cdef bint _is_exchange_pair(self, long x, long y) except -1
++    cdef int _exchange(self, long x, long y) except -1
++    cdef int _move(self, bitset_t X, bitset_t Y) except -1
+     cdef __fundamental_cocircuit(self, bitset_t, long x)
+     cdef __fundamental_circuit(self, bitset_t, long y)
+ 
+@@ -30,7 +30,7 @@ cdef class BasisExchangeMatroid(Matroid):
+     cdef __closure(self, bitset_t, bitset_t)
+     cdef __max_coindependent(self, bitset_t, bitset_t)
+     cdef __cocircuit(self, bitset_t, bitset_t)
+-    cdef __coclosure(self, bitset_t, bitset_t)
++    cdef _coclosure_internal(self, bitset_t, bitset_t)
+ 
+     cdef __augment(self, bitset_t, bitset_t, bitset_t)
+     cdef bint __is_independent(self, bitset_t F) except -1
+diff --git a/src/sage/matroids/basis_exchange_matroid.pyx b/src/sage/matroids/basis_exchange_matroid.pyx
+index 90d10842d46..015fa8b8df3 100644
+--- a/src/sage/matroids/basis_exchange_matroid.pyx
++++ b/src/sage/matroids/basis_exchange_matroid.pyx
+@@ -57,10 +57,10 @@ cdef class BasisExchangeMatroid(Matroid):
+ 
+     This base exchange graph is not stored as such, but should be provided
+     implicitly by the child class in the form of two methods
+-    ``__is_exchange_pair(x, y)`` and ``__exchange(x, y)``, as well as an
++    ``_is_exchange_pair(x, y)`` and ``_exchange(x, y)``, as well as an
+     initial basis. At any moment, BasisExchangeMatroid keeps a current basis
+-    `B`. The method ``__is_exchange_pair(x, y)`` should return a boolean
+-    indicating whether `B - x + y` is a basis. The method ``__exchange(x, y)``
++    `B`. The method ``_is_exchange_pair(x, y)`` should return a boolean
++    indicating whether `B - x + y` is a basis. The method ``_exchange(x, y)``
+     is called when the current basis `B` is replaced by said `B-x + y`. It is
+     up to the child class to update its internal data structure to make
+     information relative to the new basis more accessible. For instance, a
+@@ -81,16 +81,16 @@ cdef class BasisExchangeMatroid(Matroid):
+     - :class:`BasisMatroid <sage.matroids.basis_matroid.BasisMatroid>`: keeps
+       a list of all bases.
+ 
+-        - ``__is_exchange_pair(x, y)`` reduces to a query whether `B - x + y`
++        - ``_is_exchange_pair(x, y)`` reduces to a query whether `B - x + y`
+           is a basis.
+-        - ``__exchange(x, y)`` has no work to do.
++        - ``_exchange(x, y)`` has no work to do.
+ 
+     - :class:`LinearMatroid <sage.matroids.linear_matroid.LinearMatroid>`:
+       keeps a matrix representation `A` of the matroid so that `A[B] = I`.
+ 
+-        - ``__is_exchange_pair(x, y)`` reduces to testing whether `A[r, y]`
++        - ``_is_exchange_pair(x, y)`` reduces to testing whether `A[r, y]`
+           is nonzero, where `A[r, x]=1`.
+-        - ``__exchange(x, y)`` should modify the matrix so that `A[B - x + y]`
++        - ``_exchange(x, y)`` should modify the matrix so that `A[B - x + y]`
+           becomes `I`, which means pivoting on `A[r, y]`.
+ 
+     - ``TransversalMatroid`` (not yet implemented): If `A` is a set of subsets
+@@ -100,17 +100,17 @@ cdef class BasisExchangeMatroid(Matroid):
+       edge `(A_i,e)` if `e` is in the subset `A_i`. At any time you keep a
+       maximum matching `M` of `G` covering the current basis `B`.
+ 
+-        - ``__is_exchange_pair(x, y)`` checks for the existence of an
++        - ``_is_exchange_pair(x, y)`` checks for the existence of an
+           `M`-alternating path `P` from `y` to `x`.
+-        - ``__exchange(x, y)`` replaces `M` by the symmetric difference of
++        - ``_exchange(x, y)`` replaces `M` by the symmetric difference of
+           `M` and `E(P)`.
+ 
+     - ``AlgebraicMatroid`` (not yet implemented): keeps a list of polynomials
+       in variables `E - B + e` for each variable `e` in `B`.
+ 
+-        - ``__is_exchange_pair(x, y)`` checks whether the polynomial that
++        - ``_is_exchange_pair(x, y)`` checks whether the polynomial that
+           relates `y` to `E-B` uses `x`.
+-        - ``__exchange(x, y)`` make new list of polynomials by computing
++        - ``_exchange(x, y)`` make new list of polynomials by computing
+           resultants.
+ 
+     All but the first of the above matroids are algebraic, and all
+@@ -139,7 +139,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         This initializer sets up a correspondence between elements of
+         ``groundset`` and ``range(len(groundset))``. ``BasisExchangeMatroid``
+         uses this correspondence for encoding of subsets of the groundset as
+-        bitpacked sets of integers --- see ``__pack()`` and ``__unpack()``. In
++        bitpacked sets of integers --- see ``_pack()`` and ``__unpack()``. In
+         general, methods of ``BasisExchangeMatroid`` having a name starting
+         with two underscores deal with such encoded subsets.
+ 
+@@ -180,7 +180,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             self._idx[self._E[i]] = i
+ 
+         if basis is not None:
+-            self.__pack(self._current_basis, frozenset(basis))
++            self._pack(self._current_basis, frozenset(basis))
+ 
+     def __dealloc__(self):
+         bitset_free(self._current_basis)
+@@ -191,7 +191,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_free(self._output)
+         bitset_free(self._temp)
+ 
+-    cdef __relabel(self, l):
++    cdef _relabel(self, l):
+         """
+         Relabel each element `e` as `l[e]`, where `l` is a given injective map.
+ 
+@@ -231,7 +231,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             self._heuristic_partition_var._relabel(l)
+ 
+     # the engine
+-    cdef __pack(self, bitset_t I, F):
++    cdef _pack(self, bitset_t I, F):
+         """
+         Encode a subset F of the groundset into a bitpacked set of integers
+         """
+@@ -252,21 +252,21 @@ cdef class BasisExchangeMatroid(Matroid):
+         return frozenset(F)
+ 
+     # this method needs to be overridden by child class
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         """
+         Test if current_basis-x + y is a basis
+         """
+         raise NotImplementedError
+ 
+     # if this method is overridden by a child class, the child class needs to call this method
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         """
+         put current_basis <-- current_basis-x + y
+         """
+         bitset_discard(self._current_basis, x)
+         bitset_add(self._current_basis, y)
+ 
+-    cdef int __move(self, bitset_t X, bitset_t Y) except -1:
++    cdef int _move(self, bitset_t X, bitset_t Y) except -1:
+         """
+         Change current_basis to minimize intersection with ``X``, maximize intersection with ``Y``.
+         """
+@@ -275,8 +275,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         while x >= 0:
+             y = bitset_first(Y)
+             while y >= 0:
+-                if self.__is_exchange_pair(x, y):
+-                    self.__exchange(x, y)
++                if self._is_exchange_pair(x, y):
++                    self._exchange(x, y)
+                     bitset_discard(Y, y)
+                     bitset_discard(X, x)
+                     if bitset_isempty(Y):
+@@ -295,7 +295,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_complement(self._temp, self._current_basis)
+         y = bitset_first(self._temp)
+         while y >= 0:
+-            if self.__is_exchange_pair(x, y):
++            if self._is_exchange_pair(x, y):
+                 bitset_add(C, y)
+             y = bitset_next(self._temp, y + 1)
+         bitset_add(C, x)
+@@ -308,7 +308,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_clear(C)
+         x = bitset_first(self._current_basis)
+         while x >= 0:
+-            if self.__is_exchange_pair(x, y):
++            if self._is_exchange_pair(x, y):
+                 bitset_add(C, x)
+             x = bitset_next(self._current_basis, x + 1)
+         bitset_add(C, y)
+@@ -319,7 +319,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, F)
+         bitset_difference(self._outside, F, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_intersection(R, self._current_basis, F)
+ 
+     cdef __circuit(self, bitset_t R, bitset_t F):
+@@ -335,8 +335,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         while y >= 0:
+             x = bitset_first(self._inside)
+             while x >= 0:
+-                if self.__is_exchange_pair(x, y):
+-                    self.__exchange(x, y)
++                if self._is_exchange_pair(x, y):
++                    self._exchange(x, y)
+                     bitset_discard(self._outside, y)
+                     bitset_discard(self._inside, x)
+                     if bitset_isempty(self._outside):
+@@ -355,7 +355,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, F)
+         bitset_difference(self._outside, F, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_set_first_n(R, self._groundset_size)
+         cdef long x = bitset_first(self._inside)
+         while x >= 0:
+@@ -370,7 +370,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_difference(R, F, self._current_basis)
+ 
+     cdef __cocircuit(self, bitset_t R, bitset_t F):
+@@ -387,8 +387,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         while x >= 0:
+             y = bitset_first(self._outside)
+             while y >= 0:
+-                if self.__is_exchange_pair(x, y):
+-                    self.__exchange(x, y)
++                if self._is_exchange_pair(x, y):
++                    self._exchange(x, y)
+                     bitset_discard(self._outside, y)
+                     bitset_discard(self._inside, x)
+                     if bitset_isempty(self._inside):
+@@ -401,14 +401,14 @@ cdef class BasisExchangeMatroid(Matroid):
+                 return
+             x = bitset_next(self._inside, x + 1)
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``closure``.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_set_first_n(R, self._groundset_size)
+         cdef long y = bitset_first(self._outside)
+         while y >= 0:
+@@ -422,10 +422,10 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, X)
+         bitset_difference(self._outside, X, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_difference(self._inside, self._inside, Y)
+         bitset_difference(self._outside, Y, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_intersection(R, self._current_basis, Y)
+ 
+     cdef bint __is_independent(self, bitset_t F) except -1:
+@@ -434,7 +434,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, F)
+         bitset_difference(self._outside, F, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         return bitset_isempty(self._outside)
+ 
+     cdef __move_current_basis(self, bitset_t X, bitset_t Y):
+@@ -443,21 +443,21 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, X)
+         bitset_difference(self._outside, X, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_intersection(self._inside, self._current_basis, Y)
+         bitset_complement(self._outside, self._current_basis)
+         bitset_difference(self._outside, self._outside, Y)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+     # functions for derived classes and for parent class
+     cdef bint _set_current_basis(self, F):
+         """
+         Set _current_basis to subset of the groundset ``F``.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         bitset_difference(self._inside, self._current_basis, self._input)
+         bitset_difference(self._outside, self._input, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         return bitset_isempty(self._outside) and bitset_isempty(self._inside)
+ 
+     # groundset and full_rank
+@@ -630,8 +630,8 @@ cdef class BasisExchangeMatroid(Matroid):
+             ['b', 'c', 'e', 'f']
+ 
+         """
+-        self.__pack(self._input, X)
+-        self.__pack(self._input2, Y)
++        self._pack(self._input, X)
++        self._pack(self._input2, Y)
+         self.__move_current_basis(self._input, self._input2)
+ 
+     cpdef _max_independent(self, F):
+@@ -661,7 +661,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.max_independent>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_independent(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -692,7 +692,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.rank>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_independent(self._output, self._input)
+         return bitset_len(self._output)
+ 
+@@ -729,7 +729,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             the input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.circuit>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__circuit(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -754,7 +754,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             sage: sorted(M._fundamental_circuit('abcd', 'e'))
+             ['a', 'b', 'c', 'e']
+         """
+-        self.__pack(self._input, B)
++        self._pack(self._input, B)
+         bitset_clear(self._input2)
+         self.__move_current_basis(self._input, self._input2)
+         self.__fundamental_circuit(self._output, self._idx[e])
+@@ -787,7 +787,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             :meth:`<sage.matroids.matroid.Matroid.closure>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__closure(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -818,7 +818,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.max_coindependent>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_coindependent(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -848,7 +848,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.corank>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_coindependent(self._output, self._input)
+         return bitset_len(self._output)
+ 
+@@ -885,7 +885,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.cocircuit>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__cocircuit(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -910,7 +910,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             sage: sorted(M._fundamental_cocircuit('efgh', 'e'))
+             ['b', 'c', 'd', 'e']
+         """
+-        self.__pack(self._input, B)
++        self._pack(self._input, B)
+         bitset_clear(self._input2)
+         self.__move_current_basis(self._input, self._input2)
+         self.__fundamental_cocircuit(self._output, self._idx[e])
+@@ -943,8 +943,8 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.coclosure>`.
+ 
+         """
+-        self.__pack(self._input, F)
+-        self.__coclosure(self._output, self._input)
++        self._pack(self._input, F)
++        self._coclosure_internal(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+     cpdef _augment(self, X, Y):
+@@ -973,8 +973,8 @@ cdef class BasisExchangeMatroid(Matroid):
+             ['e', 'f', 'g']
+ 
+         """
+-        self.__pack(self._input, X)
+-        self.__pack(self._input2, Y)
++        self._pack(self._input, X)
++        self._pack(self._input2, Y)
+         self.__augment(self._output, self._input, self._input2)
+         return self.__unpack(self._output)
+ 
+@@ -1006,7 +1006,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             the input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.is_independent>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         return self.__is_independent(self._input)
+ 
+     # connectivity
+@@ -1142,8 +1142,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         cdef bitset_t SS, TT
+         bitset_init(SS, self._groundset_size)
+         bitset_init(TT, self._groundset_size)
+-        self.__pack(SS,S)
+-        self.__pack(TT,T)
++        self._pack(SS,S)
++        self._pack(TT,T)
+         #F = set(self.groundset()) - (S | T)
+         cdef bitset_t F, I
+         bitset_init(F, self._groundset_size)
+@@ -1421,7 +1421,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         Rcoflats = SetSystem(self._E)
+         i = 0
+         bitset_clear(todo[0])
+-        self.__coclosure(coflats[0], todo[0])
++        self._coclosure_internal(coflats[0], todo[0])
+         bitset_complement(todo[0], coflats[0])
+         self._coflats_rec(Rcoflats, r, coflats, todo, 0, 0)
+         for i in range(r + 1):
+@@ -1443,7 +1443,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         while e >= 0:
+             bitset_copy(self._input, coflats[i])
+             bitset_add(self._input, e)
+-            self.__coclosure(coflats[i + 1], self._input)
++            self._coclosure_internal(coflats[i + 1], self._input)
+             bitset_difference(todo[i], todo[i], coflats[i + 1])
+             bitset_difference(todo[i + 1], coflats[i + 1], coflats[i])
+             if bitset_first(todo[i + 1]) == e:
+@@ -2397,7 +2397,7 @@ cdef class BasisExchangeMatroid(Matroid):
+                 # Set current basis to Y
+                 bitset_difference(self._inside, self._current_basis, BB._subsets[pointerY])
+                 bitset_difference(self._outside, BB._subsets[pointerY], self._current_basis)
+-                self.__move(self._inside, self._outside)
++                self._move(self._inside, self._outside)
+                 if not bitset_eq(self._current_basis, BB._subsets[pointerY]):
+                     # We failed to set the current basis to Y through basis exchanges.
+                     # Therefore, the exchange axioms are violated!
+@@ -2409,7 +2409,7 @@ cdef class BasisExchangeMatroid(Matroid):
+                     foundpair = False
+                     y = bitset_first(self._input2)
+                     while y >= 0:  # for y in Y-X
+-                        if self.__is_exchange_pair(y, x):
++                        if self._is_exchange_pair(y, x):
+                             foundpair = True
+                             y = -1
+                         else:
+diff --git a/src/sage/matroids/basis_matroid.pyx b/src/sage/matroids/basis_matroid.pyx
+index 3ac43112627..c1b6e9b04c8 100644
+--- a/src/sage/matroids/basis_matroid.pyx
++++ b/src/sage/matroids/basis_matroid.pyx
+@@ -219,7 +219,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+                     raise ValueError("basis has wrong cardinality.")
+                 if not b.issubset(self._groundset):
+                     raise ValueError("basis is not a subset of the groundset")
+-                self.__pack(self._b, b)
++                self._pack(self._b, b)
+                 i = set_to_index(self._b)
+                 if not bitset_in(self._bb, i):
+                     self._bcount += 1
+@@ -234,7 +234,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+                         raise ValueError("nonbasis has wrong cardinality")
+                     if not b.issubset(self._groundset):
+                         raise ValueError("nonbasis is not a subset of the groundset")
+-                    self.__pack(self._b, b)
++                    self._pack(self._b, b)
+                     i = set_to_index(self._b)
+                     if bitset_in(self._bb, i):
+                         self._bcount -= 1
+@@ -263,7 +263,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+ 
+     # support for parent BasisExchangeMatroid
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:      # test if current_basis-x + y is a basis
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:      # test if current_basis-x + y is a basis
+         """
+         Test if `B-e + f` is a basis of the current matroid.
+ 
+@@ -326,7 +326,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+             sage: M._is_basis(set(['a', 'b', 'c', 'd']))
+             False
+         """
+-        self.__pack(self._b, X)
++        self._pack(self._b, X)
+         return bitset_in(self._bb, set_to_index(self._b))
+ 
+     # dual and minors
+@@ -557,7 +557,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+ 
+         """
+         M = BasisMatroid(M=self)
+-        M.__relabel(l)
++        M._relabel(l)
+         return M
+ 
+     # enumeration
+@@ -1177,7 +1177,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+ 
+         """
+         N = BasisMatroid(M=self)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo=None):
+@@ -1201,7 +1201,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+         if memo is None:
+             memo = {}
+         N = BasisMatroid(M=self)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __reduce__(self):
+@@ -1230,7 +1230,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+         """
+         import sage.matroids.unpickling
+         BB = bitset_pickle(self._bb)
+-        data = (self._E, self._matroid_rank, getattr(self, '__custom_name'), BB)
++        data = (self._E, self._matroid_rank, self.get_custom_name(), BB)
+         version = 0
+         return sage.matroids.unpickling.unpickle_basis_matroid, (version, data)
+ 
+diff --git a/src/sage/matroids/circuit_closures_matroid.pyx b/src/sage/matroids/circuit_closures_matroid.pyx
+index 402822b2dc6..4e79b0575e2 100644
+--- a/src/sage/matroids/circuit_closures_matroid.pyx
++++ b/src/sage/matroids/circuit_closures_matroid.pyx
+@@ -513,8 +513,7 @@ cdef class CircuitClosuresMatroid(Matroid):
+         N._groundset = self._groundset
+         N._circuit_closures = self._circuit_closures
+         N._matroid_rank = self._matroid_rank
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo=None):
+@@ -539,8 +538,7 @@ cdef class CircuitClosuresMatroid(Matroid):
+         from copy import deepcopy
+         # Since matroids are immutable, N cannot reference itself in correct code, so no need to worry about the recursion.
+         N = CircuitClosuresMatroid(groundset=deepcopy(self._groundset, memo), circuit_closures=deepcopy(self._circuit_closures, memo))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -570,7 +568,7 @@ cdef class CircuitClosuresMatroid(Matroid):
+              4: {{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}}}
+         """
+         import sage.matroids.unpickling
+-        data = (self._groundset, self._circuit_closures, getattr(self, '__custom_name'))
++        data = (self._groundset, self._circuit_closures, self.get_custom_name())
+         version = 0
+         return sage.matroids.unpickling.unpickle_circuit_closures_matroid, (version, data)
+ 
+diff --git a/src/sage/matroids/dual_matroid.py b/src/sage/matroids/dual_matroid.py
+index 804e43f035b..da6639827e4 100644
+--- a/src/sage/matroids/dual_matroid.py
++++ b/src/sage/matroids/dual_matroid.py
+@@ -519,9 +519,7 @@ def __copy__(self):
+ 
+         """
+         N = DualMatroid(self._matroid)
+-        if getattr(self, '__custom_name') is not None:
+-            # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -543,10 +541,7 @@ def __deepcopy__(self, memo={}):
+         """
+         from copy import deepcopy
+         N = DualMatroid(deepcopy(self._matroid, memo))
+-        if getattr(self, '__custom_name') is not None:
+-            # because of name wrangling, this is not caught by the
+-            # default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -575,6 +570,6 @@ def __reduce__(self):
+              4: {{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}}}'
+         """
+         import sage.matroids.unpickling
+-        data = (self._matroid, getattr(self, '__custom_name'))
++        data = (self._matroid, self.get_custom_name())
+         version = 0
+         return sage.matroids.unpickling.unpickle_dual_matroid, (version, data)
+diff --git a/src/sage/matroids/graphic_matroid.py b/src/sage/matroids/graphic_matroid.py
+index 5216ef11517..c727dc54e52 100644
+--- a/src/sage/matroids/graphic_matroid.py
++++ b/src/sage/matroids/graphic_matroid.py
+@@ -481,8 +481,7 @@ def __copy__(self):
+             False
+         """
+         N = GraphicMatroid(self._G)
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -502,8 +501,7 @@ def __deepcopy__(self, memo={}):
+         """
+         # The only real difference between this and __copy__() is the memo
+         N = GraphicMatroid(deepcopy(self._G, memo))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -519,7 +517,7 @@ def __reduce__(self):
+             Graphic matroid of rank 9 on 15 elements
+         """
+         from .unpickling import unpickle_graphic_matroid
+-        data = (self._G, getattr(self, '__custom_name'))
++        data = (self._G, self.get_custom_name())
+         version = 0
+         return unpickle_graphic_matroid, (version, data)
+ 
+diff --git a/src/sage/matroids/linear_matroid.pxd b/src/sage/matroids/linear_matroid.pxd
+index 014c8aef57d..9aebd446b68 100644
+--- a/src/sage/matroids/linear_matroid.pxd
++++ b/src/sage/matroids/linear_matroid.pxd
+@@ -15,7 +15,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+     cpdef characteristic(self)
+ 
+     cdef list _setup_internal_representation(self, matrix, reduced_matrix, ring, keep_initial_representation)
+-    cdef __exchange_value(self, long x, long y)
++    cdef _exchange_value_internal(self, long x, long y)
+ 
+     cpdef representation(self, B=*, reduced=*, labels=*, order=*, lift_map=*)
+     cpdef _current_rows_cols(self, B=*)
+diff --git a/src/sage/matroids/linear_matroid.pyx b/src/sage/matroids/linear_matroid.pyx
+index 61452e80c48..36f563aa433 100644
+--- a/src/sage/matroids/linear_matroid.pyx
++++ b/src/sage/matroids/linear_matroid.pyx
+@@ -391,13 +391,13 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         """
+         return characteristic(self._A)
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return self._A.is_nonzero(self._prow[x], self._prow[y])
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         """
+         Put element indexed by ``x`` into basis, taking out element ``y``.
+         Assumptions are that this is a valid basis exchange.
+@@ -420,9 +420,9 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         self._A.set_unsafe(px, py, pivi)
+         self._prow[y] = px
+         self._prow[x] = py
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -605,7 +605,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+                     self._representation = self._basic_representation(B)
+                 A = self._representation
+             else:
+-                B = self.__subset(B)
++                B = self._subset_internal(B)
+                 A = self._basic_representation(B)
+             A = A.matrix_from_rows_and_columns(range(A.nrows()), order_idx)
+             if lift_map is None:
+@@ -622,7 +622,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+             if B is None:
+                 B = frozenset(self.basis())
+             else:
+-                B = self.__subset(B)
++                B = self._subset_internal(B)
+             A = self._reduced_representation(B)
+             R, C = self._current_rows_cols()
+             Ri = []
+@@ -1493,7 +1493,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+             sage: M._exchange_value(1, 3)
+             4
+         """
+-        return self.__exchange_value(self._idx[e], self._idx[f])
++        return self._exchange_value_internal(self._idx[e], self._idx[f])
+ 
+     cpdef fundamental_cycle(self, B, e):
+         """
+@@ -2909,7 +2909,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = LinearMatroid(groundset=rows + cols, reduced_matrix=self._A)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -2930,7 +2930,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = LinearMatroid(groundset=deepcopy(rows + cols, memo), reduced_matrix=deepcopy(self._A, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -2979,7 +2979,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+             rows, cols = self._current_rows_cols()
+             gs = rows + cols
+             reduced = True
+-        data = (A, gs, reduced, getattr(self, '__custom_name'))
++        data = (A, gs, reduced, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_linear_matroid, (version, data)
+ 
+ # Binary matroid
+@@ -3152,20 +3152,20 @@ cdef class BinaryMatroid(LinearMatroid):
+         """
+         return 2
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<BinaryMatrix>self._A).is_nonzero(self._prow[x], y)
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         r"""
+         Replace ``self.basis() with ``self.basis() - x + y``. Internal method, does no checks.
+         """
+         cdef long p = self._prow[x]
+         self._A.pivot(p, y)   # Not a Sage matrix operation
+         self._prow[y] = p
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+     cdef  __fundamental_cocircuit(self, bitset_t C, long x):
+         r"""
+@@ -3173,18 +3173,18 @@ cdef class BinaryMatroid(LinearMatroid):
+         """
+         bitset_copy(C, (<BinaryMatrix>self._A)._M[self._prow[x]])
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``coclosure``.
+ 
+-        This function overrides the internal function BasisExchangeMatroid.__coclosure() of the parent class.
++        This function overrides the internal function BasisExchangeMatroid._coclosure_internal() of the parent class.
+         The implementation should be more efficient for BinaryMatroid, due to the fact that in this class,
+         __fundamental_cocircuit is much faster than __fundamental_circuit.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+         bitset_copy(R, F)
+         bitset_difference(self._inside, self._current_basis, F)
+@@ -3196,7 +3196,7 @@ cdef class BinaryMatroid(LinearMatroid):
+                 bitset_add(R, y)
+             y = bitset_next(self._inside, y + 1)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -3964,7 +3964,7 @@ cdef class BinaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = BinaryMatroid(groundset=self._E, matrix=self._A, basis=basis)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -3989,7 +3989,7 @@ cdef class BinaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = BinaryMatroid(groundset=deepcopy(self._E, memo), matrix=deepcopy(self._A, memo), basis=deepcopy(basis, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -4047,7 +4047,7 @@ cdef class BinaryMatroid(LinearMatroid):
+             A = self._A
+             # current basis ordered so matrix cols form identity matrix:
+             basis = self._current_rows_cols()[0]
+-        data = (A, gs, basis, getattr(self, '__custom_name'))
++        data = (A, gs, basis, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_binary_matroid, (version, data)
+ 
+ cdef class TernaryMatroid(LinearMatroid):
+@@ -4220,20 +4220,20 @@ cdef class TernaryMatroid(LinearMatroid):
+         """
+         return 3
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<TernaryMatrix>self._A).is_nonzero(self._prow[x], y)
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         r"""
+         Replace ``self.basis() with ``self.basis() - x + y``. Internal method, does no checks.
+         """
+         cdef long p = self._prow[x]
+         self._A.pivot(p, y)   # Not a Sage matrix operation
+         self._prow[y] = p
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+     cdef  __fundamental_cocircuit(self, bitset_t C, long x):
+         r"""
+@@ -4241,18 +4241,18 @@ cdef class TernaryMatroid(LinearMatroid):
+         """
+         bitset_copy(C, (<TernaryMatrix>self._A)._M0[self._prow[x]])
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``coclosure``.
+ 
+-        This function overrides the internal function BasisExchangeMatroid.__coclosure() of the parent class.
++        This function overrides the internal function BasisExchangeMatroid._coclosure_internal() of the parent class.
+         The implementation should be more efficient for TernaryMatroid, due to the fact that in this class,
+         __fundamental_cocircuit is much faster than __fundamental_circuit.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+         bitset_copy(R, F)
+         bitset_difference(self._inside, self._current_basis, F)
+@@ -4264,7 +4264,7 @@ cdef class TernaryMatroid(LinearMatroid):
+                 bitset_add(R, y)
+             y = bitset_next(self._inside, y + 1)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -4858,7 +4858,7 @@ cdef class TernaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = TernaryMatroid(groundset=self._E, matrix=self._A, basis=basis)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -4883,7 +4883,7 @@ cdef class TernaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = TernaryMatroid(groundset=deepcopy(self._E, memo), matrix=deepcopy(self._A, memo), basis=deepcopy(basis, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -4945,7 +4945,7 @@ cdef class TernaryMatroid(LinearMatroid):
+             A = self._A
+             # current basis ordered so matrix cols form identity matrix:
+             basis = self._current_rows_cols()[0]
+-        data = (A, gs, basis, getattr(self, '__custom_name'))
++        data = (A, gs, basis, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_ternary_matroid, (version, data)
+ 
+ # Quaternary Matroids
+@@ -5122,20 +5122,20 @@ cdef class QuaternaryMatroid(LinearMatroid):
+         """
+         return 2
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<QuaternaryMatrix>self._A).is_nonzero(self._prow[x], y)
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         r"""
+         Replace ``self.basis() with ``self.basis() - x + y``. Internal method, does no checks.
+         """
+         cdef long p = self._prow[x]
+         self._A.pivot(p, y)   # Not a Sage matrix operation
+         self._prow[y] = p
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+     cdef  __fundamental_cocircuit(self, bitset_t C, long x):
+         r"""
+@@ -5143,18 +5143,18 @@ cdef class QuaternaryMatroid(LinearMatroid):
+         """
+         bitset_union(C, (<QuaternaryMatrix>self._A)._M0[self._prow[x]], (<QuaternaryMatrix>self._A)._M1[self._prow[x]])
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``coclosure``.
+ 
+-        This function overrides the internal function BasisExchangeMatroid.__coclosure() of the parent class.
++        This function overrides the internal function BasisExchangeMatroid._coclosure_internal() of the parent class.
+         The implementation should be more efficient for QuaternaryMatroid, due to the fact that in this class,
+         __fundamental_cocircuit is much faster than __fundamental_circuit.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+         bitset_copy(R, F)
+         bitset_difference(self._inside, self._current_basis, F)
+@@ -5166,7 +5166,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+                 bitset_add(R, y)
+             y = bitset_next(self._inside, y + 1)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -5589,7 +5589,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = QuaternaryMatroid(groundset=self._E, matrix=self._A, basis=basis)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -5614,7 +5614,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = QuaternaryMatroid(groundset=deepcopy(self._E, memo), matrix=deepcopy(self._A, memo), basis=deepcopy(basis, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -5672,7 +5672,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+             A = self._A
+             # current basis ordered so matrix cols form identity matrix:
+             basis = self._current_rows_cols()[0]
+-        data = (A, gs, basis, getattr(self, '__custom_name'))
++        data = (A, gs, basis, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_quaternary_matroid, (version, data)
+ 
+ # Regular Matroids
+@@ -5838,13 +5838,13 @@ cdef class RegularMatroid(LinearMatroid):
+         """
+         return 0
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<PlusMinusOneMatrix>self._A).is_nonzero(self._prow[x], self._prow[y])
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         """
+         Put element indexed by ``x`` into basis, taking out element ``y``. Assumptions are that this is a valid basis exchange.
+ 
+@@ -5867,9 +5867,9 @@ cdef class RegularMatroid(LinearMatroid):
+         (<PlusMinusOneMatrix>self._A).set(px, py, pivi)   # Not a Sage matrix operation
+         self._prow[y] = px
+         self._prow[x] = py
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+ 
+@@ -6524,7 +6524,7 @@ cdef class RegularMatroid(LinearMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = RegularMatroid(groundset=rows + cols, reduced_matrix=self._A)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -6544,7 +6544,7 @@ cdef class RegularMatroid(LinearMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = RegularMatroid(groundset=deepcopy(rows + cols, memo), reduced_matrix=deepcopy(self._A, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -6593,5 +6593,5 @@ cdef class RegularMatroid(LinearMatroid):
+             rows, cols = self._current_rows_cols()
+             gs = rows + cols
+             reduced = True
+-        data = (A, gs, reduced, getattr(self, '__custom_name'))
++        data = (A, gs, reduced, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_regular_matroid, (version, data)
+diff --git a/src/sage/matroids/matroid.pxd b/src/sage/matroids/matroid.pxd
+index fe6c07e3b71..e9ddfec96ae 100644
+--- a/src/sage/matroids/matroid.pxd
++++ b/src/sage/matroids/matroid.pxd
+@@ -1,8 +1,7 @@
+ from sage.structure.sage_object cimport SageObject
+ 
+ cdef class Matroid(SageObject):
+-    cdef public __custom_name
+-    cdef public _custom_name
++    cdef public _SageObject__custom_name
+     cdef public _cached_info
+     cdef int _stored_full_rank
+     cdef int _stored_size
+@@ -37,7 +36,7 @@ cdef class Matroid(SageObject):
+     cpdef _line_length(self, F)
+     cpdef _extension(self, element, hyperplanes)
+ 
+-    cdef inline __subset(self, X):
++    cdef inline _subset_internal(self, X):
+         """
+         Convert ``X`` to a ``frozenset`` and check that it is a subset
+         of the groundset.
+diff --git a/src/sage/matroids/matroid.pyx b/src/sage/matroids/matroid.pyx
+index dcee87ea49c..8ac5ec3f678 100644
+--- a/src/sage/matroids/matroid.pyx
++++ b/src/sage/matroids/matroid.pyx
+@@ -1307,7 +1307,7 @@ cdef class Matroid(SageObject):
+             TypeError: 'sage.rings.integer.Integer' object is not iterable
+         """
+         # Call corresponding Cython method
+-        return self.__subset(X)
++        return self._subset_internal(X)
+ 
+     def _subset_all(self, X):
+         """
+@@ -1374,7 +1374,7 @@ cdef class Matroid(SageObject):
+         """
+         if X is None:
+             return self.full_rank()
+-        return self._rank(self.__subset(X))
++        return self._rank(self._subset_internal(X))
+ 
+     cpdef full_rank(self):
+         r"""
+@@ -1453,7 +1453,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._max_independent(self.__subset(X))
++        return self._max_independent(self._subset_internal(X))
+ 
+     cpdef circuit(self, X=None):
+         """
+@@ -1558,7 +1558,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._closure(self.__subset(X))
++        return self._closure(self._subset_internal(X))
+ 
+     cpdef k_closure(self, X, k):
+         r"""
+@@ -1597,7 +1597,7 @@ cdef class Matroid(SageObject):
+             sage: sorted(M.k_closure({0,1}, 4))
+             [0, 1, 4]
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         cdef int cur
+         cdef frozenset S, cl
+         cur = 0
+@@ -1644,7 +1644,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         Y = self.__subset_all(Y)
+         return self._augment(X, Y.difference(X))
+ 
+@@ -1781,7 +1781,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._max_coindependent(self.__subset(X))
++        return self._max_coindependent(self._subset_internal(X))
+ 
+     cpdef coclosure(self, X):
+         """
+@@ -1813,7 +1813,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._coclosure(self.__subset(X))
++        return self._coclosure(self._subset_internal(X))
+ 
+     cpdef cocircuit(self, X=None):
+         """
+@@ -1947,7 +1947,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_independent(self.__subset(X))
++        return self._is_independent(self._subset_internal(X))
+ 
+     cpdef is_dependent(self, X):
+         r"""
+@@ -1973,7 +1973,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return not self._is_independent(self.__subset(X))
++        return not self._is_independent(self._subset_internal(X))
+ 
+     cpdef is_basis(self, X):
+         r"""
+@@ -1999,7 +1999,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         if len(X) != self.full_rank():
+             return False
+         return self._is_basis(X)
+@@ -2035,7 +2035,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_closed(self.__subset(X))
++        return self._is_closed(self._subset_internal(X))
+ 
+     cpdef is_subset_k_closed(self, X, int k):
+         r"""
+@@ -2118,7 +2118,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_circuit(self.__subset(X))
++        return self._is_circuit(self._subset_internal(X))
+ 
+     cpdef coloops(self):
+         r"""
+@@ -2178,7 +2178,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_coindependent(self.__subset(X))
++        return self._is_coindependent(self._subset_internal(X))
+ 
+     cpdef is_codependent(self, X):
+         r"""
+@@ -2211,7 +2211,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return not self._is_coindependent(self.__subset(X))
++        return not self._is_coindependent(self._subset_internal(X))
+ 
+     cpdef is_cobasis(self, X):
+         r"""
+@@ -2245,7 +2245,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         if len(X) != self.full_corank():
+             return False
+         return self._is_cobasis(X)
+@@ -2282,7 +2282,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_cocircuit(self.__subset(X))
++        return self._is_cocircuit(self._subset_internal(X))
+ 
+     cpdef is_coclosed(self, X):
+         r"""
+@@ -2315,7 +2315,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_coclosed(self.__subset(X))
++        return self._is_coclosed(self._subset_internal(X))
+ 
+     # verification
+ 
+@@ -4868,10 +4868,10 @@ cdef class Matroid(SageObject):
+             sage: M.connectivity('ab', 'cd')
+             2
+         """
+-        S = self.__subset(S)
++        S = self._subset_internal(S)
+         if T is None:
+             return self._rank(S) + self._rank(self.groundset()-S) - self.full_rank()
+-        T = self.__subset(T)
++        T = self._subset_internal(T)
+         if S.intersection(T):
+             raise ValueError("S and T are not disjoint")
+         return len(self._link(S, T)[0]) - self.full_rank() + self._rank(S) + self._rank(T)
+@@ -4956,8 +4956,8 @@ cdef class Matroid(SageObject):
+             sage: N.connectivity(S)
+             2
+         """
+-        S = self.__subset(S)
+-        T = self.__subset(T)
++        S = self._subset_internal(S)
++        T = self._subset_internal(T)
+         if not S.isdisjoint(T):
+             raise ValueError("S and T are not disjoint")
+         return self._link(S, T)
+diff --git a/src/sage/matroids/minor_matroid.py b/src/sage/matroids/minor_matroid.py
+index c0e756917f5..98856348ac1 100644
+--- a/src/sage/matroids/minor_matroid.py
++++ b/src/sage/matroids/minor_matroid.py
+@@ -486,8 +486,7 @@ def __copy__(self):
+             True
+         """
+         N = MinorMatroid(self._matroid, self._contractions, self._deletions)
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -512,8 +511,7 @@ def __deepcopy__(self, memo={}):
+         from copy import deepcopy
+         # Since matroids are immutable, N cannot reference itself in correct code, so no need to worry about the recursion.
+         N = MinorMatroid(deepcopy(self._matroid, memo), deepcopy(self._contractions, memo), deepcopy(self._deletions, memo))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -534,6 +532,6 @@ def __reduce__(self):
+              4: {{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}}}
+         """
+         import sage.matroids.unpickling
+-        data = (self._matroid, self._contractions, self._deletions, getattr(self, '__custom_name'))
++        data = (self._matroid, self._contractions, self._deletions, self.get_custom_name())
+         version = 0
+         return sage.matroids.unpickling.unpickle_minor_matroid, (version, data)
+diff --git a/src/sage/matroids/rank_matroid.py b/src/sage/matroids/rank_matroid.py
+index 4633ff0a792..6c4e9470ada 100644
+--- a/src/sage/matroids/rank_matroid.py
++++ b/src/sage/matroids/rank_matroid.py
+@@ -267,9 +267,7 @@ def __copy__(self):
+         N = RankMatroid(groundset=[], rank_function=None)
+         N._groundset = self._groundset
+         N._rank_function = self._rank_function
+-        if getattr(self, '__custom_name') is not None:
+-            # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -293,8 +291,7 @@ def __deepcopy__(self, memo={}):
+         from copy import deepcopy
+         # Since matroids are immutable, N cannot reference itself in correct code, so no need to worry about the recursion.
+         N = RankMatroid(groundset=deepcopy(self._groundset), rank_function=deepcopy(self._rank_function))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+diff --git a/src/sage/misc/cachefunc.pxd b/src/sage/misc/cachefunc.pxd
+index d3cc677dece..8e5d9dfa42a 100644
+--- a/src/sage/misc/cachefunc.pxd
++++ b/src/sage/misc/cachefunc.pxd
+@@ -5,7 +5,7 @@ cpdef cache_key(o)
+ 
+ cdef class CachedFunction():
+     cdef public str __name__
+-    cdef public str __module__
++    cdef public str __cached_module__
+     cdef ArgumentFixer _argument_fixer
+     cdef public f
+     cdef public cache  # not always of type <dict>
+@@ -20,7 +20,7 @@ cdef class CachedFunction():
+ cdef class CachedMethod():
+     cdef str _cache_name
+     cdef public str __name__
+-    cdef public str __module__
++    cdef public str __cached_module__
+     cdef CachedFunction _cachedfunc
+     cdef Py_ssize_t nargs
+     cpdef _get_instance_cache(self, inst)
+diff --git a/src/sage/misc/cachefunc.pyx b/src/sage/misc/cachefunc.pyx
+index a307c33e32b..8aa30a85272 100644
+--- a/src/sage/misc/cachefunc.pyx
++++ b/src/sage/misc/cachefunc.pyx
+@@ -60,7 +60,7 @@ be used::
+ 
+ We can proceed similarly for cached methods of Cython classes,
+ provided that they allow attribute assignment or have a public
+-attribute ``__cached_methods`` of type ``<dict>``. Since
++attribute ``_cached_methods`` of type ``<dict>``. Since
+ :trac:`11115`, this is the case for all classes inheriting from
+ :class:`~sage.structure.parent.Parent`. See below for a more explicit
+ example. By :trac:`12951`, cached methods of extension classes can
+@@ -301,14 +301,14 @@ ought to be chosen. A typical example is
+ 
+ By :trac:`12951`, the cached_method decorator is also supported on non-c(p)def
+ methods of extension classes, as long as they either support attribute assignment
+-or have a public attribute of type ``<dict>`` called ``__cached_methods``. The
++or have a public attribute of type ``<dict>`` called ``_cached_methods``. The
+ latter is easy::
+ 
+     sage: # needs sage.misc.cython
+     sage: cython_code = [
+     ....: "from sage.misc.cachefunc import cached_method",
+     ....: "cdef class MyClass:",
+-    ....: "    cdef public dict __cached_methods",
++    ....: "    cdef public dict _cached_methods",
+     ....: "    @cached_method",
+     ....: "    def f(self, a,b):",
+     ....: "        return a*b"]
+@@ -774,13 +774,17 @@ cdef class CachedFunction():
+         else:
+             self.__name__ = f.__name__
+         try:
+-            self.__module__ = f.__module__
++            self.__cached_module__ = f.__module__
+         except AttributeError:
+-            self.__module__ = f.__objclass__.__module__
++            self.__cached_module__ = f.__objclass__.__module__
+         if argument_fixer is not None: # it is None unless the argument fixer
+                                        # was known previously. See #15038.
+             self._argument_fixer = argument_fixer
+ 
++    @property
++    def __module__(self):
++        return self.__cached_module__
++
+     cdef get_key_args_kwds(self, tuple args, dict kwds):
+         """
+         Return the key in the cache to be used when ``args`` and
+@@ -841,7 +845,7 @@ cdef class CachedFunction():
+             sage: loads(dumps(hilbert_class_polynomial)) is hilbert_class_polynomial  #indirect doctest                 # needs sage.schemes
+             True
+         """
+-        return _cached_function_unpickle, (self.__module__, self.__name__, self.cache)
++        return _cached_function_unpickle, (self.__cached_module__, self.__name__, self.cache)
+ 
+     #########
+     ## Introspection
+@@ -2019,7 +2023,7 @@ cdef class CachedMethodCaller(CachedFunction):
+         This getter attempts to assign a bound method as an
+         attribute to the given instance. If this is not
+         possible (for example, for some extension classes),
+-        it is attempted to find an attribute ``__cached_methods``,
++        it is attempted to find an attribute ``_cached_methods``,
+         and store/retrieve the bound method there. In that
+         way, cached methods can be implemented for extension
+         classes deriving from :class:`~sage.structure.parent.Parent`
+@@ -2085,7 +2089,7 @@ cdef class CachedMethodCaller(CachedFunction):
+         """
+         # This is for Parents or Elements that do not allow attribute assignment
+         try:
+-            return (<dict>inst.__cached_methods)[self._cachedmethod._cachedfunc.__name__]
++            return (<dict>inst._cached_methods)[self._cachedmethod._cachedfunc.__name__]
+         except (AttributeError, TypeError, KeyError):
+             pass
+ 
+@@ -2100,10 +2104,10 @@ cdef class CachedMethodCaller(CachedFunction):
+         except AttributeError:
+             pass
+         try:
+-            if inst.__cached_methods is None:
+-                inst.__cached_methods = {self._cachedmethod._cachedfunc.__name__ : Caller}
++            if inst._cached_methods is None:
++                inst._cached_methods = {self._cachedmethod._cachedfunc.__name__ : Caller}
+             else:
+-                (<dict>inst.__cached_methods)[self._cachedmethod._cachedfunc.__name__] = Caller
++                (<dict>inst._cached_methods)[self._cachedmethod._cachedfunc.__name__] = Caller
+         except AttributeError:
+             pass
+         return Caller
+@@ -2421,7 +2425,7 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
+         This getter attempts to assign a bound method as an
+         attribute to the given instance. If this is not
+         possible (for example, for some extension classes),
+-        it is attempted to find an attribute ``__cached_methods``,
++        it is attempted to find an attribute ``_cached_methods``,
+         and store/retrieve the bound method there. In that
+         way, cached methods can be implemented for extension
+         classes deriving from :class:`~sage.structure.parent.Parent`
+@@ -2472,7 +2476,7 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
+         """
+         # This is for Parents or Elements that do not allow attribute assignment
+         try:
+-            return (<dict>inst.__cached_methods)[self.__name__]
++            return (<dict>inst._cached_methods)[self.__name__]
+         except (AttributeError, TypeError, KeyError):
+             pass
+         Caller = CachedMethodCallerNoArgs(inst, self.f, name=self.__name__, do_pickle=self.do_pickle)
+@@ -2482,10 +2486,10 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
+         except AttributeError:
+             pass
+         try:
+-            if inst.__cached_methods is None:
+-                inst.__cached_methods = {self.__name__ : Caller}
++            if inst._cached_methods is None:
++                inst._cached_methods = {self.__name__ : Caller}
+             else:
+-                (<dict>inst.__cached_methods)[self.__name__] = Caller
++                (<dict>inst._cached_methods)[self.__name__] = Caller
+         except AttributeError:
+             pass
+         return Caller
+@@ -2698,7 +2702,11 @@ cdef class CachedMethod():
+         self._cache_name = '_cache__' + (name or f.__name__)
+         self._cachedfunc = CachedFunction(f, classmethod=True, name=name, key=key, do_pickle=do_pickle)
+         self.__name__ = self._cachedfunc.__name__
+-        self.__module__ = self._cachedfunc.__module__
++        self.__cached_module__ = self._cachedfunc.__module__
++
++    @property
++    def __module__(self):
++        return self.__cached_module__
+ 
+     def __call__(self, inst, *args, **kwds):
+         """
+@@ -2828,7 +2836,7 @@ cdef class CachedMethod():
+         except AttributeError:
+             name = self.__name__
+         try:
+-            return (<dict>inst.__cached_methods)[name]
++            return (<dict>inst._cached_methods)[name]
+         except (AttributeError, TypeError, KeyError):
+             pass
+         # Apparently we need to construct the caller.
+@@ -2840,8 +2848,6 @@ cdef class CachedMethod():
+                 try:
+                     if METH_NOARGS&PyCFunction_GetFlags(f.__get__(inst,cls)):
+                         self.nargs = 1
+-                    else:
+-                        self.nargs = 2
+                 except Exception:
+                     pass
+             if self.nargs == 0:
+@@ -2864,10 +2870,10 @@ cdef class CachedMethod():
+         except AttributeError:
+             pass
+         try:
+-            if inst.__cached_methods is None:
+-                inst.__cached_methods = {name : Caller}
++            if inst._cached_methods is None:
++                inst._cached_methods = {name : Caller}
+             else:
+-                (<dict>inst.__cached_methods)[name] = Caller
++                (<dict>inst._cached_methods)[name] = Caller
+         except AttributeError:
+             pass
+         return Caller
+@@ -2965,12 +2971,12 @@ cdef class CachedSpecialMethod(CachedMethod):
+                 D = inst.__dict__
+             except (TypeError, AttributeError):
+                 try:
+-                    D = inst.__cached_methods
++                    D = inst._cached_methods
+                 except (TypeError, AttributeError):
+-                    raise TypeError("For a cached special method, either attribute assignment or a public '__cached_methods' attribute of type <dict> is needed")
++                    raise TypeError("For a cached special method, either attribute assignment or a public '_cached_methods' attribute of type <dict> is needed")
+             if D is None:
+-                # This can only happen in the case of __cached_methods
+-                D = inst.__cached_methods = {}
++                # This can only happen in the case of _cached_methods
++                D = inst._cached_methods = {}
+             else:
+                 try:
+                     return D[name]
+@@ -3298,13 +3304,13 @@ cdef class CachedInParentMethod(CachedMethod):
+             return P.__dict__.setdefault(self._cache_name, default)
+         except AttributeError:
+             pass
+-        if not hasattr(P,'__cached_methods'):
++        if not hasattr(P,'_cached_methods'):
+             raise TypeError("The parent of this element does not allow attribute assignment\n" +
+                             "    and does not descend from the Parent base class.\n" +
+                             "    Cannot use CachedInParentMethod.")
+-        if P.__cached_methods is None:
+-            P.__cached_methods = {}
+-        return (<dict>P.__cached_methods).setdefault(self._cache_name, default)
++        if P._cached_methods is None:
++            P._cached_methods = {}
++        return (<dict>P._cached_methods).setdefault(self._cache_name, default)
+ 
+     def __get__(self, inst, cls):
+         """
+diff --git a/src/sage/misc/cython.py b/src/sage/misc/cython.py
+index f4083f3909b..5f83f585c3a 100644
+--- a/src/sage/misc/cython.py
++++ b/src/sage/misc/cython.py
+@@ -646,9 +646,9 @@ def compile_and_load(code, **kwds):
+         ....:     cdef Polynomial_rational_flint res = f._new()
+         ....:     cdef unsigned long k
+         ....:     cdef Rational z = Rational(0)
+-        ....:     for k in range(fmpq_poly_length(f.__poly)):
+-        ....:         fmpq_poly_get_coeff_mpq(z.value, f.__poly, k)
+-        ....:         fmpq_poly_set_coeff_mpq(res.__poly, n*k, z.value)
++        ....:     for k in range(fmpq_poly_length(f._poly)):
++        ....:         fmpq_poly_get_coeff_mpq(z.value, f._poly, k)
++        ....:         fmpq_poly_set_coeff_mpq(res._poly, n*k, z.value)
+         ....:     return res
+         ....: '''
+         sage: module = compile_and_load(code)  # long time
+diff --git a/src/sage/misc/fpickle.pyx b/src/sage/misc/fpickle.pyx
+index 9f80a8f31aa..37c26e431ba 100644
+--- a/src/sage/misc/fpickle.pyx
++++ b/src/sage/misc/fpickle.pyx
+@@ -124,10 +124,12 @@ def call_pickled_function(fpargs):
+ def pickleMethod(method):
+     'support function for copyreg to pickle method refs'
+ 
+-    # Note: On Python 3 there is no .im_class but we can get the instance's
+-    # class through .__self__.__class__
+-    cls = getattr(method, 'im_class', method.__self__.__class__)
+-    return (unpickleMethod, (method.__func__.__name__, method.__self__, cls))
++    if isinstance(method.__self__, type):
++        # This is a class method, so get it from the type directly
++        return (getattr, (method.__self__, method.__func__.__name__))
++    else:
++        cls = method.__self__.__class__
++        return (unpickleMethod, (method.__func__.__name__, method.__self__, cls))
+ 
+ 
+ def unpickleMethod(im_name,
+@@ -139,10 +141,7 @@ def unpickleMethod(im_name,
+         if __self__ is None:
+             return unbound
+ 
+-        # Note: On Python 2 "unbound methods" are just functions, so they don't
+-        # have a __func__
+-        bound = types.MethodType(getattr(unbound, '__func__', unbound),
+-                                 __self__)
++        bound = types.MethodType(unbound, __self__)
+         return bound
+     except AttributeError:
+         assert __self__ is not None, "No recourse: no instance to guess from."
+@@ -150,11 +149,8 @@ def unpickleMethod(im_name,
+         # changed around since we pickled this method, we may still be
+         # able to get it by looking on the instance's current class.
+         unbound = getattr(__self__.__class__, im_name)
+-        if __self__ is None:
+-            return unbound
+ 
+-        bound = types.MethodType(getattr(unbound, '__func__', unbound),
+-                                 __self__)
++        bound = types.MethodType(unbound, __self__)
+         return bound
+ 
+ 
+diff --git a/src/sage/misc/inherit_comparison.pyx b/src/sage/misc/inherit_comparison.pyx
+index f046f5fb8ce..aa97f664496 100644
+--- a/src/sage/misc/inherit_comparison.pyx
++++ b/src/sage/misc/inherit_comparison.pyx
+@@ -54,6 +54,8 @@ cdef class InheritComparisonMetaclass(type):
+         sage: # needs sage.misc.cython
+         sage: cython(
+         ....: '''
++        ....: cimport cython
++        ....:
+         ....: from sage.misc.inherit_comparison cimport InheritComparisonMetaclass
+         ....:
+         ....: cdef class Base():
+@@ -66,6 +68,7 @@ cdef class InheritComparisonMetaclass(type):
+         ....:         return 1
+         ....:
+         ....: cdef class DerivedWithRichcmp(Base):
++        ....:     @cython.always_allow_keywords(False)
+         ....:     def __getmetaclass__(_):
+         ....:         from sage.misc.inherit_comparison import InheritComparisonMetaclass
+         ....:         return InheritComparisonMetaclass
+diff --git a/src/sage/misc/lazy_attribute.pyx b/src/sage/misc/lazy_attribute.pyx
+index 82a0f90b775..bdbec3b3ba1 100644
+--- a/src/sage/misc/lazy_attribute.pyx
++++ b/src/sage/misc/lazy_attribute.pyx
+@@ -111,12 +111,12 @@ cdef class _lazy_attribute():
+         if a is None: # when doing cls.x for cls a class and x a lazy attribute
+             return self
+         try:
+-            # __cached_methods is supposed to be a public Cython attribute.
++            # _cached_methods is supposed to be a public Cython attribute.
+             # Apparently, these are *not* subject to name mangling.
+-            CM = getattr(a, '__cached_methods')
++            CM = getattr(a, '_cached_methods')
+             if CM is None:
+                 CM = {}
+-                setattr(a, '__cached_methods', CM)
++                setattr(a, '_cached_methods', CM)
+         except AttributeError as msg:
+             CM = None
+         if CM is not None:
+diff --git a/src/sage/misc/lazy_list.pyx b/src/sage/misc/lazy_list.pyx
+index c1fa0250a95..ba62c446b69 100644
+--- a/src/sage/misc/lazy_list.pyx
++++ b/src/sage/misc/lazy_list.pyx
+@@ -1059,7 +1059,11 @@ cdef class lazy_list_from_function(lazy_list_generic):
+             step         1
+         """
+         while len(self.cache) <= i:
+-            self.cache.append(self.callable(len(self.cache)))
++            try:
++                value = self.callable(len(self.cache))
++            except StopIteration:
++                return 1
++            self.cache.append(value)
+ 
+     def __reduce__(self):
+         r"""
+diff --git a/src/sage/misc/sageinspect.py b/src/sage/misc/sageinspect.py
+index 3dd0cc0a45b..ce5e9987027 100644
+--- a/src/sage/misc/sageinspect.py
++++ b/src/sage/misc/sageinspect.py
+@@ -224,7 +224,11 @@ def isclassinstance(obj):
+     return (not inspect.isclass(obj) and
+             hasattr(obj, '__class__') and
+             hasattr(obj.__class__, '__module__') and
+-            obj.__class__.__module__ not in builtin_mods)
++            obj.__class__.__module__ not in builtin_mods and
++            # Starting with Cython 3, Cython's builtin types have __module__ set
++            # to the shared module names like _cython_3_0_0.
++            not (isinstance(obj.__class__.__module__, str) and
++                 obj.__class__.__module__.startswith('_cython_')))
+ 
+ 
+ # Parse strings of form "File: sage/rings/rational.pyx (starting at line 1080)"
+diff --git a/src/sage/misc/session.pyx b/src/sage/misc/session.pyx
+index de649f80425..31454dac993 100644
+--- a/src/sage/misc/session.pyx
++++ b/src/sage/misc/session.pyx
+@@ -80,6 +80,8 @@ from sage.misc.persist import load, save, loads, dumps
+ 
+ state_at_init = None
+ 
++CythonFunctionType = type(lambda: None)
++
+ def init(state=None):
+     """
+     Initialize some dictionaries needed by the :func:`show_identifiers`,
+@@ -311,7 +313,7 @@ def save_session(name='sage_session', verbose=False):
+     for k in show_identifiers(hidden = True):
+         try:
+             x = state[k]
+-            if isinstance(x, (types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType, type)):
++            if isinstance(x, (types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType, CythonFunctionType, type)):
+                 raise TypeError('{} is a function, method, class or type'.format(k))
+ 
+             # We attempt to pickle *and* unpickle every variable to
+diff --git a/src/sage/modular/modsym/p1list.pxd b/src/sage/modular/modsym/p1list.pxd
+index cc24a33139b..b66f28b8ad6 100644
+--- a/src/sage/modular/modsym/p1list.pxd
++++ b/src/sage/modular/modsym/p1list.pxd
+@@ -21,7 +21,7 @@ cdef class P1List:
+     # Here we use a pointer to a function, so the if logic
+     # for normalizing an element does not need to be used
+     # every time the user calls the normalize function.
+-    cdef int (*__normalize)(int N, int u, int v,
++    cdef int (*_normalize)(int N, int u, int v,
+                             int* uu, int* vv, int* ss,
+                             int compute_s) except -1
+     cpdef index(self, int u, int v)
+diff --git a/src/sage/modular/modsym/p1list.pyx b/src/sage/modular/modsym/p1list.pyx
+index 111d408cee4..30a8f7471dd 100644
+--- a/src/sage/modular/modsym/p1list.pyx
++++ b/src/sage/modular/modsym/p1list.pyx
+@@ -723,10 +723,10 @@ cdef class P1List():
+         self.__N = N
+         if N <= 46340:
+             self.__list = p1list_int(N)
+-            self.__normalize = c_p1_normalize_int
++            self._normalize = c_p1_normalize_int
+         elif N <= 2147483647:
+             self.__list = p1list_llong(N)
+-            self.__normalize = c_p1_normalize_llong
++            self._normalize = c_p1_normalize_llong
+         else:
+             raise OverflowError("p1list not defined for such large N.")
+         self.__list.sort()
+@@ -921,7 +921,7 @@ cdef class P1List():
+         """
+         cdef int u, v, uu, vv, ss
+         u,v = self.__list[i]
+-        self.__normalize(self.__N, -u, v, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, -u, v, &uu, &vv, &ss, 0)
+         _, j = search(self.__list, (uu,vv))
+         return j
+ 
+@@ -954,7 +954,7 @@ cdef class P1List():
+         """
+         cdef int u, v, uu, vv, ss
+         u,v = self.__list[i]
+-        self.__normalize(self.__N, -v, u, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, -v, u, &uu, &vv, &ss, 0)
+         _, j = search(self.__list, (uu,vv))
+         return j
+ 
+@@ -987,7 +987,7 @@ cdef class P1List():
+         """
+         cdef int u, v, uu, vv, ss
+         u,v = self.__list[i]
+-        self.__normalize(self.__N, v, -u-v, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, v, -u-v, &uu, &vv, &ss, 0)
+         _, j = search(self.__list, (uu,vv))
+         return j
+ 
+@@ -1153,7 +1153,7 @@ cdef class P1List():
+             True
+         """
+         cdef int uu, vv, ss
+-        self.__normalize(self.__N, u, v, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, u, v, &uu, &vv, &ss, 0)
+         return (uu,vv)
+ 
+     def normalize_with_scalar(self, int u, int v):
+@@ -1186,7 +1186,7 @@ cdef class P1List():
+             True
+         """
+         cdef int uu, vv, ss
+-        self.__normalize(self.__N, u, v, &uu, &vv, &ss, 1)
++        self._normalize(self.__N, u, v, &uu, &vv, &ss, 1)
+         return (uu, vv, ss)
+ 
+     def N(self):
+diff --git a/src/sage/numerical/gauss_legendre.pyx b/src/sage/numerical/gauss_legendre.pyx
+index 5325797c7aa..96708c5b1ac 100644
+--- a/src/sage/numerical/gauss_legendre.pyx
++++ b/src/sage/numerical/gauss_legendre.pyx
+@@ -117,8 +117,8 @@ def nodes_uncached(degree, prec):
+         raise ValueError("degree=%s not supported (degree must be 3 or even)" % degree)
+     R = RealField(int(prec*3/2))
+     Rout = RealField(prec)
+-    mpfr_init2(u,R.__prec)
+-    mpfr_init2(v,R.__prec)
++    mpfr_init2(u,R._prec)
++    mpfr_init2(v,R._prec)
+     ZERO = R.zero()
+     ONE = R.one()
+     HALF = ONE/2
+diff --git a/src/sage/numerical/linear_functions.pyx b/src/sage/numerical/linear_functions.pyx
+index 5549ff436f5..f3fc6fe419c 100644
+--- a/src/sage/numerical/linear_functions.pyx
++++ b/src/sage/numerical/linear_functions.pyx
+@@ -1579,7 +1579,10 @@ cdef class LinearConstraint(LinearFunctionOrConstraint):
+         while True:
+             yield (lhs, rhs)
+             lhs = rhs
+-            rhs = next(term_iter)
++            try:
++                rhs = next(term_iter)
++            except StopIteration:
++                return
+ 
+     def inequalities(self):
+         """
+@@ -1612,7 +1615,10 @@ cdef class LinearConstraint(LinearFunctionOrConstraint):
+         while True:
+             yield (lhs, rhs)
+             lhs = rhs
+-            rhs = next(term_iter)
++            try:
++                rhs = next(term_iter)
++            except StopIteration:
++                return
+ 
+     def _repr_(self):
+         r"""
+diff --git a/src/sage/quivers/representation.py b/src/sage/quivers/representation.py
+index 9c11eb8ad0e..db82cbd7c86 100644
+--- a/src/sage/quivers/representation.py
++++ b/src/sage/quivers/representation.py
+@@ -1297,10 +1297,7 @@ def copy(self):
+             sage: v.get_element(1)
+             (1, 0)
+         """
+-        if hasattr(self, '__custom_name'):
+-            name = self.__custom_name
+-        else:
+-            name = None
++        name = self.get_custom_name()
+         return self.parent()(self._elems.copy(), name)
+ 
+ ####################################################################
+diff --git a/src/sage/rings/complex_arb.pyx b/src/sage/rings/complex_arb.pyx
+index ef432c1e945..95e615f3ee6 100644
+--- a/src/sage/rings/complex_arb.pyx
++++ b/src/sage/rings/complex_arb.pyx
+@@ -874,7 +874,7 @@ class ComplexBallField(UniqueRepresentation, sage.rings.abc.ComplexBallField):
+         cdef RealBall rb
+         cdef ComplexBall cb
+         acb_poly_init(rounded_poly)
+-        cdef long deg = acb_poly_degree(poly.__poly)
++        cdef long deg = acb_poly_degree(poly._poly)
+         if deg < 0:
+             raise ArithmeticError("taking the roots of the zero polynomial")
+         cdef acb_ptr roots = _acb_vec_init(deg)
+@@ -883,7 +883,7 @@ class ComplexBallField(UniqueRepresentation, sage.rings.abc.ComplexBallField):
+             while ((isolated < deg or any(acb_rel_accuracy_bits(&roots[i]) < tgtprec
+                                         for i in range(deg)))
+                 and prec < maxprec):
+-                acb_poly_set_round(rounded_poly, poly.__poly, prec)
++                acb_poly_set_round(rounded_poly, poly._poly, prec)
+                 maxiter = min(max(deg, 32), prec)
+                 if (prec == initial_prec):
+                     isolated = acb_poly_find_roots(roots, rounded_poly, NULL, maxiter, prec)
+diff --git a/src/sage/rings/complex_mpc.pxd b/src/sage/rings/complex_mpc.pxd
+index 762c38afbdc..f7d8cb9492c 100644
+--- a/src/sage/rings/complex_mpc.pxd
++++ b/src/sage/rings/complex_mpc.pxd
+@@ -11,7 +11,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+     cpdef _mul_(self, other)
+ 
+ cdef class MPComplexField_class(sage.rings.ring.Field):
+-    cdef readonly int __prec
++    cdef readonly int _prec
+     cdef mpc_rnd_t __rnd
+     cdef object __rnd_str
+     cdef object __real_field
+diff --git a/src/sage/rings/complex_mpc.pyx b/src/sage/rings/complex_mpc.pyx
+index b3681ff724f..c847a9302b5 100644
+--- a/src/sage/rings/complex_mpc.pyx
++++ b/src/sage/rings/complex_mpc.pyx
+@@ -307,7 +307,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+         if prec < mpfr_prec_min() or prec > mpfr_prec_max():
+             raise ValueError("prec (=%s) must be >= %s and <= %s." % (
+                 prec, mpfr_prec_min(), mpfr_prec_max()))
+-        self.__prec = prec
++        self._prec = prec
+         if not isinstance(rnd, str):
+             raise TypeError("rnd must be a string")
+         try:
+@@ -331,7 +331,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+         cdef MPComplexNumber z
+         z = MPComplexNumber.__new__(MPComplexNumber)
+         z._parent = self
+-        mpc_init2(z.value, self.__prec)
++        mpc_init2(z.value, self._prec)
+         z.init = 1
+         return z
+ 
+@@ -344,7 +344,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: MPComplexField(200, 'RNDDU') # indirect doctest
+             Complex Field with 200 bits of precision and rounding RNDDU
+         """
+-        s = "Complex Field with %s bits of precision"%self.__prec
++        s = "Complex Field with %s bits of precision"%self._prec
+         if self.__rnd != MPC_RNDNN:
+             s = s + " and rounding %s"%(self.__rnd_str)
+         return s
+@@ -465,13 +465,13 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+         if RR.has_coerce_map_from(S):
+             return self._coerce_map_via([RR], S)
+ 
+-        if isinstance(S, MPComplexField_class) and S.prec() >= self.__prec:
++        if isinstance(S, MPComplexField_class) and S.prec() >= self._prec:
+             #FIXME: What map when rounding modes differ but prec is the same ?
+             #       How to provide commutativity of morphisms ?
+             #       Change _cmp_ when done
+             return MPCtoMPC(S, self)
+ 
+-        if isinstance(S, ComplexField_class) and S.prec() >= self.__prec:
++        if isinstance(S, ComplexField_class) and S.prec() >= self._prec:
+             return CCtoMPC(S, self)
+ 
+         late_import()
+@@ -490,7 +490,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: loads(dumps(C)) == C
+             True
+         """
+-        return __create__MPComplexField_version0, (self.__prec, self.__rnd_str)
++        return __create__MPComplexField_version0, (self._prec, self.__rnd_str)
+ 
+     def __richcmp__(left, right, int op):
+         """
+@@ -513,7 +513,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+ 
+         cdef MPComplexField_class s = <MPComplexField_class>left
+         cdef MPComplexField_class o = <MPComplexField_class>right
+-        return richcmp(s.__prec, o.__prec, op)
++        return richcmp(s._prec, o._prec, op)
+ 
+     def gen(self, n=0):
+         """
+@@ -604,7 +604,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: C = MPComplexField(10, 'RNDNZ'); C.name()
+             'MPComplexField10_RNDNZ'
+         """
+-        return "MPComplexField%s_%s"%(self.__prec, self.__rnd_str)
++        return "MPComplexField%s_%s"%(self._prec, self.__rnd_str)
+ 
+     def __hash__(self):
+         """
+@@ -629,7 +629,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: MPComplexField(22).prec()
+             22
+         """
+-        return self.__prec
++        return self._prec
+ 
+     def rounding_mode(self):
+         """
+@@ -707,7 +707,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+         cdef MPComplexNumber z
+         z = MPComplexNumber.__new__(MPComplexNumber)
+         z._parent = self._parent
+-        mpc_init2(z.value, (<MPComplexField_class>self._parent).__prec)
++        mpc_init2(z.value, (<MPComplexField_class>self._parent)._prec)
+         z.init = 1
+         return z
+ 
+@@ -760,7 +760,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+         if parent is None:
+             raise TypeError
+         self._parent = parent
+-        mpc_init2(self.value, parent.__prec)
++        mpc_init2(self.value, parent._prec)
+         self.init = 1
+         if x is None: return
+         self._set(x, y, base)
+@@ -1010,7 +1010,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+             sage: i.prec()
+             2000
+         """
+-        return <MPComplexField_class>(self._parent).__prec
++        return <MPComplexField_class>(self._parent)._prec
+ 
+     def real(self):
+         """
+@@ -1571,26 +1571,6 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+         mpc_norm(x.value, self.value, (<RealField_class>x._parent).rnd)
+         return x
+ 
+-    def __rtruediv__(self, left):
+-        r"""
+-        Returns the quotient of ``left`` with ``self``, that is: ``left/self``
+-        as a complex number.
+-
+-        INPUT:
+-
+-        - ``left`` -- a complex number
+-
+-        EXAMPLES::
+-
+-            sage: MPC = MPComplexField()
+-            sage: a = MPC(2, 2)
+-            sage: a.__rtruediv__(MPC(1))
+-            0.250000000000000 - 0.250000000000000*I
+-            sage: MPC(1)/a
+-            0.250000000000000 - 0.250000000000000*I
+-        """
+-        return MPComplexNumber(self._parent, left)/self
+-
+     def __pow__(self, right, modulus):
+         """
+         Compute ``self`` raised to the power of exponent, rounded in
+@@ -2347,7 +2327,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+ 
+         cdef mpc_rnd_t rnd = (<MPComplexField_class>(self._parent)).__rnd
+ 
+-        cdef int prec = self._parent.__prec
++        cdef int prec = self._parent._prec
+ 
+         if optimal or algorithm == "principal":
+             if not isinstance(right, MPComplexNumber) or (<MPComplexNumber>right)._parent is not self._parent:
+diff --git a/src/sage/rings/complex_mpfr.pyx b/src/sage/rings/complex_mpfr.pyx
+index 33d73d81b12..61f2cadc8e4 100644
+--- a/src/sage/rings/complex_mpfr.pyx
++++ b/src/sage/rings/complex_mpfr.pyx
+@@ -1658,28 +1658,6 @@ cdef class ComplexNumber(sage.structure.element.FieldElement):
+         mpfr_clear(right_nm)
+         return x
+ 
+-    def __rtruediv__(self, left):
+-        r"""
+-        Return the quotient of left with ``self``, that is:
+-
+-        ``left/self``
+-
+-        as a complex number.
+-
+-        INPUT:
+-
+-        - ``left`` -- a complex number to divide by ``self``
+-
+-        EXAMPLES::
+-
+-            sage: a = ComplexNumber(2,0)
+-            sage: a.__rtruediv__(CC(1))
+-            0.500000000000000
+-            sage: CC(1)/a
+-            0.500000000000000
+-        """
+-        return ComplexNumber(self._parent, left)/self
+-
+     def __pow__(self, right, modulus):
+         r"""
+         Raise ``self`` to the ``right`` exponent.
+diff --git a/src/sage/rings/finite_rings/integer_mod.pxd b/src/sage/rings/finite_rings/integer_mod.pxd
+index 1e3cb81c148..351ffa25e1b 100644
+--- a/src/sage/rings/finite_rings/integer_mod.pxd
++++ b/src/sage/rings/finite_rings/integer_mod.pxd
+@@ -20,7 +20,7 @@ cdef class NativeIntStruct:
+ 
+ 
+ cdef class IntegerMod_abstract(FiniteRingElement):
+-    cdef NativeIntStruct __modulus
++    cdef NativeIntStruct _modulus
+     cdef _new_c_from_long(self, long value)
+     cdef IntegerMod_abstract _new_c_fast(self, unsigned long value)
+     cdef void set_from_mpz(self, mpz_t value)
+diff --git a/src/sage/rings/finite_rings/integer_mod.pyx b/src/sage/rings/finite_rings/integer_mod.pyx
+index b9461bd362e..d64ba5af84f 100644
+--- a/src/sage/rings/finite_rings/integer_mod.pyx
++++ b/src/sage/rings/finite_rings/integer_mod.pyx
+@@ -361,7 +361,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             ZeroDivisionError: inverse of Mod(4, 30) does not exist
+         """
+         self._parent = parent
+-        self.__modulus = parent._pyx_order
++        self._modulus = parent._pyx_order
+ 
+         if value is None:
+             return
+@@ -373,7 +373,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         if isinstance(value, Integer):
+             z = <Integer>value
+         elif isinstance(value, rational.Rational):
+-            z = value % self.__modulus.sageInteger
++            z = value % self._modulus.sageInteger
+         elif integer_check_long_py(value, &longval, &err) and not err:
+             self.set_from_long(longval)
+             return
+@@ -388,7 +388,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+                     value = py_scalar_to_element(value)
+                 if isinstance(value, Element) and value.parent().is_exact():
+                     value = sage.rings.rational_field.QQ(value)
+-                    z = value % self.__modulus.sageInteger
++                    z = value % self._modulus.sageInteger
+                 else:
+                     raise
+         self.set_from_mpz(z.value)
+@@ -397,7 +397,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         cdef type t = type(self)
+         x = <IntegerMod_abstract>t.__new__(t)
+         x._parent = self._parent
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x.set_from_ulong_fast(value)
+         return x
+ 
+@@ -405,7 +405,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         cdef type t = type(self)
+         cdef IntegerMod_abstract x = <IntegerMod_abstract>t.__new__(t)
+         x._parent = self._parent
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x.set_from_long(value)
+         return x
+ 
+@@ -529,17 +529,17 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         """
+         if self.is_zero():
+             return True
+-        m = self.__modulus.sageInteger.exact_log(2) + 1
++        m = self._modulus.sageInteger.exact_log(2) + 1
+         return (self**m).is_zero()
+ 
+     #################################################################
+     # Interfaces
+     #################################################################
+     def _pari_init_(self):
+-        return 'Mod(%s,%s)'%(str(self), self.__modulus.sageInteger)
++        return 'Mod(%s,%s)'%(str(self), self._modulus.sageInteger)
+ 
+     def __pari__(self):
+-        return self.lift().__pari__().Mod(self.__modulus.sageInteger)
++        return self.lift().__pari__().Mod(self._modulus.sageInteger)
+ 
+     def _gap_init_(self):
+         r"""
+@@ -558,7 +558,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             sage: gap(Mod(4, 48))
+             ZmodnZObj( 4, 48 )
+         """
+-        return '%s*One(ZmodnZ(%s))' % (self, self.__modulus.sageInteger)
++        return '%s*One(ZmodnZ(%s))' % (self, self._modulus.sageInteger)
+ 
+     def _magma_init_(self, magma):
+         """
+@@ -869,7 +869,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             sage: Mod(3,17).modulus()
+             17
+         """
+-        return self.__modulus.sageInteger
++        return self._modulus.sageInteger
+ 
+     def charpoly(self, var='x'):
+         """
+@@ -1229,7 +1229,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+                 modulus = R.gen()**2 - R(self)
+                 if self._parent.is_field():
+                     from .finite_field_constructor import FiniteField
+-                    Q = FiniteField(self.__modulus.sageInteger**2, y, modulus)
++                    Q = FiniteField(self._modulus.sageInteger**2, y, modulus)
+                 else:
+                     R = self.parent()['x']
+                     Q = R.quotient(modulus, names=(y,))
+@@ -1250,7 +1250,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             if all and e > 1 and not self.is_unit():
+                 if self.is_zero():
+                     # All multiples of p^ciel(e/2) vanish
+-                    return [self._parent(x) for x in range(0, self.__modulus.sageInteger, p**((e+1)/2))]
++                    return [self._parent(x) for x in range(0, self._modulus.sageInteger, p**((e+1)/2))]
+                 else:
+                     z = self.lift()
+                     val = z.valuation(p)/2  # square => valuation is even
+@@ -1272,7 +1272,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+                     p_exp = p**exp
+                     w = [self._parent(a.lift() * p_val + b)
+                             for a in u.sqrt(all=True)
+-                            for b in range(0, self.__modulus.sageInteger, p_exp)]
++                            for b in range(0, self._modulus.sageInteger, p_exp)]
+                     if p == 2:
+                         w = list(set(w))
+                     w.sort()
+@@ -1624,7 +1624,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         despite the possibly probabilistic nature of the underlying
+         algorithm.
+         """
+-        if self.lift() > self.__modulus.sageInteger >> 1:
++        if self.lift() > self._modulus.sageInteger >> 1:
+             return -self
+         return self
+ 
+@@ -1705,27 +1705,27 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         cdef int_fast64_t new_modulus
+         if not isinstance(self, IntegerMod_gmp) and not isinstance(other, IntegerMod_gmp):
+ 
+-            if other.__modulus.int64 == 1: return self
+-            new_modulus = self.__modulus.int64 * other.__modulus.int64
++            if other._modulus.int64 == 1: return self
++            new_modulus = self._modulus.int64 * other._modulus.int64
+             if new_modulus < INTEGER_MOD_INT32_LIMIT:
+-                return self.__crt(other)
++                return self._crt(other)
+ 
+             elif new_modulus < INTEGER_MOD_INT64_LIMIT:
+                 if not isinstance(self, IntegerMod_int64):
+                     self = IntegerMod_int64(self._parent, self.lift())
+                 if not isinstance(other, IntegerMod_int64):
+                     other = IntegerMod_int64(other._parent, other.lift())
+-                return self.__crt(other)
++                return self._crt(other)
+ 
+         if not isinstance(self, IntegerMod_gmp):
+-            if self.__modulus.int64 == 1: return other
++            if self._modulus.int64 == 1: return other
+             self = IntegerMod_gmp(self._parent, self.lift())
+ 
+         if not isinstance(other, IntegerMod_gmp):
+-            if other.__modulus.int64 == 1: return self
++            if other._modulus.int64 == 1: return self
+             other = IntegerMod_gmp(other._parent, other.lift())
+ 
+-        return self.__crt(other)
++        return self._crt(other)
+ 
+     def additive_order(self):
+         r"""
+@@ -1742,7 +1742,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             sage: Integers(90308402384902)(2).additive_order()
+             45154201192451
+         """
+-        n = self.__modulus.sageInteger
++        n = self._modulus.sageInteger
+         return sage.rings.integer.Integer(n // self.lift().gcd(n))
+ 
+     def is_primitive_root(self):
+@@ -1856,7 +1856,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             return sage.rings.integer.Integer(self.__pari__().znorder())
+         except PariError:
+             raise ArithmeticError("multiplicative order of %s not defined since it is not a unit modulo %s"%(
+-                self, self.__modulus.sageInteger))
++                self, self._modulus.sageInteger))
+ 
+     def valuation(self, p):
+         """
+@@ -1905,7 +1905,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             2
+ 
+         """
+-        p=self.__modulus.sageInteger.gcd(p)
++        p=self._modulus.sageInteger.gcd(p)
+         if p==1:
+             raise ValueError("Valuation with respect to a unit is not defined.")
+         r = 0
+@@ -1913,7 +1913,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         while not (self % power): # self % power == 0
+             r += 1
+             power *= p
+-            if not power.divides(self.__modulus.sageInteger):
++            if not power.divides(self._modulus.sageInteger):
+                 from sage.rings.infinity import infinity
+                 return infinity
+         return r
+@@ -1980,7 +1980,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+     cdef IntegerMod_gmp _new_c(self):
+         cdef IntegerMod_gmp x
+         x = IntegerMod_gmp.__new__(IntegerMod_gmp)
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x._parent = self._parent
+         return x
+ 
+@@ -1989,7 +1989,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+ 
+     cdef void set_from_mpz(self, mpz_t value):
+         cdef sage.rings.integer.Integer modulus
+-        modulus = self.__modulus.sageInteger
++        modulus = self._modulus.sageInteger
+         mpz_mod(self.value, value, modulus.value)
+ 
+     cdef void set_from_long(self, long value):
+@@ -2001,7 +2001,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             1
+         """
+         mpz_set_si(self.value, value)
+-        mpz_mod(self.value, self.value, self.__modulus.sageInteger.value)
++        mpz_mod(self.value, self.value, self._modulus.sageInteger.value)
+ 
+     cdef void set_from_ulong_fast(self, unsigned long value):
+         mpz_set_ui(self.value, value)
+@@ -2071,7 +2071,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             x = self._new_c()
+             if k > 0:
+                 mpz_mul_2exp(x.value, self.value, k)
+-                mpz_fdiv_r(x.value, x.value, self.__modulus.sageInteger.value)
++                mpz_fdiv_r(x.value, x.value, self._modulus.sageInteger.value)
+             else:
+                 mpz_fdiv_q_2exp(x.value, self.value, -k)
+             return x
+@@ -2132,12 +2132,12 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         """
+         return self.lift().gcd(self.modulus()) == 1
+ 
+-    def __crt(IntegerMod_gmp self, IntegerMod_gmp other):
++    def _crt(IntegerMod_gmp self, IntegerMod_gmp other):
+         cdef IntegerMod_gmp lift, x
+         cdef sage.rings.integer.Integer modulus, other_modulus
+ 
+-        modulus = self.__modulus.sageInteger
+-        other_modulus = other.__modulus.sageInteger
++        modulus = self._modulus.sageInteger
++        other_modulus = other._modulus.sageInteger
+         from .integer_mod_ring import IntegerModRing
+         lift = IntegerMod_gmp(IntegerModRing(modulus*other_modulus))
+         try:
+@@ -2188,8 +2188,8 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+         mpz_add(x.value, self.value, (<IntegerMod_gmp>right).value)
+-        if mpz_cmp(x.value, self.__modulus.sageInteger.value)  >= 0:
+-            mpz_sub(x.value, x.value, self.__modulus.sageInteger.value)
++        if mpz_cmp(x.value, self._modulus.sageInteger.value)  >= 0:
++            mpz_sub(x.value, x.value, self._modulus.sageInteger.value)
+         return x
+ 
+     cpdef _sub_(self, right):
+@@ -2204,7 +2204,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         x = self._new_c()
+         mpz_sub(x.value, self.value, (<IntegerMod_gmp>right).value)
+         if mpz_sgn(x.value) == -1:
+-            mpz_add(x.value, x.value, self.__modulus.sageInteger.value)
++            mpz_add(x.value, x.value, self._modulus.sageInteger.value)
+         return x
+ 
+     cpdef _neg_(self):
+@@ -2220,7 +2220,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             return self
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+-        mpz_sub(x.value, self.__modulus.sageInteger.value, self.value)
++        mpz_sub(x.value, self._modulus.sageInteger.value, self.value)
+         return x
+ 
+     cpdef _mul_(self, right):
+@@ -2234,7 +2234,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+         mpz_mul(x.value, self.value,  (<IntegerMod_gmp>right).value)
+-        mpz_fdiv_r(x.value, x.value, self.__modulus.sageInteger.value)
++        mpz_fdiv_r(x.value, x.value, self._modulus.sageInteger.value)
+         return x
+ 
+     cpdef _div_(self, right):
+@@ -2310,7 +2310,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         cdef IntegerMod_gmp x = self._new_c()
+         sig_on()
+         try:
+-            mpz_pow_helper(x.value, self.value, exp, self.__modulus.sageInteger.value)
++            mpz_pow_helper(x.value, self.value, exp, self._modulus.sageInteger.value)
+         finally:
+             sig_off()
+         return x
+@@ -2331,12 +2331,12 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             ZeroDivisionError: inverse of Mod(2, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000) does not exist
+         """
+         if self.is_zero():
+-            raise ZeroDivisionError(f"inverse of Mod(0, {self.__modulus.sageInteger}) does not exist")
++            raise ZeroDivisionError(f"inverse of Mod(0, {self._modulus.sageInteger}) does not exist")
+ 
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+-        if not mpz_invert(x.value, self.value, self.__modulus.sageInteger.value):
+-            raise ZeroDivisionError(f"inverse of Mod({self}, {self.__modulus.sageInteger}) does not exist")
++        if not mpz_invert(x.value, self.value, self._modulus.sageInteger.value):
++            raise ZeroDivisionError(f"inverse of Mod({self}, {self._modulus.sageInteger}) does not exist")
+         return x
+ 
+     def lift(IntegerMod_gmp self):
+@@ -2391,10 +2391,10 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         """
+         cdef IntegerMod_gmp ans = self._new_c()
+         sig_on()
+-        mpz_gcd(ans.value, self.value, self.__modulus.sageInteger.value)
++        mpz_gcd(ans.value, self.value, self._modulus.sageInteger.value)
+         mpz_gcd(ans.value, ans.value, other.value)
+         sig_off()
+-        if mpz_cmp(ans.value, self.__modulus.sageInteger.value) == 0:
++        if mpz_cmp(ans.value, self._modulus.sageInteger.value) == 0:
+             # self = other = 0
+             mpz_set_ui(ans.value, 0)
+         return ans
+@@ -2422,30 +2422,30 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+     """
+ 
+     cdef IntegerMod_int _new_c(self, int_fast32_t value):
+-        if self.__modulus.table is not None:
+-            return self.__modulus.table[value]
++        if self._modulus.table is not None:
++            return self._modulus.table[value]
+         cdef IntegerMod_int x = IntegerMod_int.__new__(IntegerMod_int)
+         x._parent = self._parent
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x.ivalue = value
+         return x
+ 
+     cdef void set_from_mpz(self, mpz_t value):
+-        self.ivalue = mpz_fdiv_ui(value, self.__modulus.int32)
++        self.ivalue = mpz_fdiv_ui(value, self._modulus.int32)
+ 
+     cdef void set_from_long(self, long value):
+-        self.ivalue = value % self.__modulus.int32
++        self.ivalue = value % self._modulus.int32
+         if self.ivalue < 0:
+-            self.ivalue += self.__modulus.int32
++            self.ivalue += self._modulus.int32
+ 
+     cdef void set_from_ulong_fast(self, unsigned long value):
+         self.ivalue = value
+ 
+     cdef void set_from_int(IntegerMod_int self, int_fast32_t ivalue):
+         if ivalue < 0:
+-            self.ivalue = self.__modulus.int32 + (ivalue % self.__modulus.int32)
+-        elif ivalue >= self.__modulus.int32:
+-            self.ivalue = ivalue % self.__modulus.int32
++            self.ivalue = self._modulus.int32 + (ivalue % self._modulus.int32)
++        elif ivalue >= self._modulus.int32:
++            self.ivalue = ivalue % self._modulus.int32
+         else:
+             self.ivalue = ivalue
+ 
+@@ -2490,7 +2490,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: Zmod(1).one().is_one()
+             True
+         """
+-        return self.ivalue == 1 or self.__modulus.int32 == 1
++        return self.ivalue == 1 or self._modulus.int32 == 1
+ 
+     def __bool__(IntegerMod_int self):
+         """
+@@ -2519,9 +2519,9 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: a.is_unit()
+             False
+         """
+-        return gcd_int(self.ivalue, self.__modulus.int32) == 1
++        return gcd_int(self.ivalue, self._modulus.int32) == 1
+ 
+-    def __crt(IntegerMod_int self, IntegerMod_int other):
++    def _crt(IntegerMod_int self, IntegerMod_int other):
+         """
+         Use the Chinese Remainder Theorem to find an element of the
+         integers modulo the product of the moduli that reduces to self and
+@@ -2543,11 +2543,11 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         cdef int_fast32_t x
+ 
+         from .integer_mod_ring import IntegerModRing
+-        lift = IntegerMod_int(IntegerModRing(self.__modulus.int32 * other.__modulus.int32))
++        lift = IntegerMod_int(IntegerModRing(self._modulus.int32 * other._modulus.int32))
+ 
+         try:
+-            x = (other.ivalue - self.ivalue % other.__modulus.int32) * mod_inverse_int(self.__modulus.int32, other.__modulus.int32)
+-            lift.set_from_int( x * self.__modulus.int32 + self.ivalue )
++            x = (other.ivalue - self.ivalue % other._modulus.int32) * mod_inverse_int(self._modulus.int32, other._modulus.int32)
++            lift.set_from_int( x * self._modulus.int32 + self.ivalue )
+             return lift
+         except ZeroDivisionError:
+             raise ZeroDivisionError("moduli must be coprime")
+@@ -2586,8 +2586,8 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         """
+         cdef int_fast32_t x
+         x = self.ivalue + (<IntegerMod_int>right).ivalue
+-        if x >= self.__modulus.int32:
+-            x = x - self.__modulus.int32
++        if x >= self._modulus.int32:
++            x = x - self._modulus.int32
+         return self._new_c(x)
+ 
+     cpdef _sub_(self, right):
+@@ -2601,7 +2601,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         cdef int_fast32_t x
+         x = self.ivalue - (<IntegerMod_int>right).ivalue
+         if x < 0:
+-            x = x + self.__modulus.int32
++            x = x + self._modulus.int32
+         return self._new_c(x)
+ 
+     cpdef _neg_(self):
+@@ -2615,7 +2615,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         """
+         if self.ivalue == 0:
+             return self
+-        return self._new_c(self.__modulus.int32 - self.ivalue)
++        return self._new_c(self._modulus.int32 - self.ivalue)
+ 
+     cpdef _mul_(self, right):
+         """
+@@ -2625,7 +2625,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: R(7) * R(8)
+             6
+         """
+-        return self._new_c((self.ivalue * (<IntegerMod_int>right).ivalue) % self.__modulus.int32)
++        return self._new_c((self.ivalue * (<IntegerMod_int>right).ivalue) % self._modulus.int32)
+ 
+     cpdef _div_(self, right):
+         """
+@@ -2635,16 +2635,16 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: R(2)/3
+             4
+         """
+-        if self.__modulus.inverses is not None:
+-            right_inverse = self.__modulus.inverses[(<IntegerMod_int>right).ivalue]
++        if self._modulus.inverses is not None:
++            right_inverse = self._modulus.inverses[(<IntegerMod_int>right).ivalue]
+             if right_inverse is None:
+-                raise ZeroDivisionError(f"inverse of Mod({right}, {self.__modulus.sageInteger}) does not exist")
++                raise ZeroDivisionError(f"inverse of Mod({right}, {self._modulus.sageInteger}) does not exist")
+             else:
+-                return self._new_c((self.ivalue * (<IntegerMod_int>right_inverse).ivalue) % self.__modulus.int32)
++                return self._new_c((self.ivalue * (<IntegerMod_int>right_inverse).ivalue) % self._modulus.int32)
+ 
+         cdef int_fast32_t x
+-        x = self.ivalue * mod_inverse_int((<IntegerMod_int>right).ivalue, self.__modulus.int32)
+-        return self._new_c(x% self.__modulus.int32)
++        x = self.ivalue * mod_inverse_int((<IntegerMod_int>right).ivalue, self._modulus.int32)
++        return self._new_c(x% self._modulus.int32)
+ 
+     def __int__(IntegerMod_int self):
+         """
+@@ -2739,7 +2739,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         if k == 0:
+             return self
+         elif k > 0:
+-            return self._new_c((self.ivalue << k) % self.__modulus.int32)
++            return self._new_c((self.ivalue << k) % self._modulus.int32)
+         else:
+             return self._new_c(self.ivalue >> (-k))
+ 
+@@ -2802,7 +2802,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sig_on()
+             try:
+                 mpz_init(res_mpz)
+-                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self.__modulus.sageInteger.value)
++                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self._modulus.sageInteger.value)
+                 res = mpz_get_ui(res_mpz)
+                 mpz_clear(res_mpz)
+             finally:
+@@ -2811,12 +2811,12 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+ 
+         if long_exp == 0 and self.ivalue == 0:
+             # Return 0 if the modulus is 1, otherwise return 1.
+-            return self._new_c(self.__modulus.int32 != 1)
++            return self._new_c(self._modulus.int32 != 1)
+         cdef bint invert = False
+         if long_exp < 0:
+             invert = True
+             long_exp = -long_exp
+-        res = mod_pow_int(self.ivalue, long_exp, self.__modulus.int32)
++        res = mod_pow_int(self.ivalue, long_exp, self._modulus.int32)
+         if invert:
+             return ~self._new_c(res)
+         else:
+@@ -2833,14 +2833,14 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: Mod(0,1)^-1
+             0
+         """
+-        if self.__modulus.inverses is not None:
+-            x = self.__modulus.inverses[self.ivalue]
++        if self._modulus.inverses is not None:
++            x = self._modulus.inverses[self.ivalue]
+             if x is None:
+-                raise ZeroDivisionError(f"inverse of Mod({self}, {self.__modulus.sageInteger}) does not exist")
++                raise ZeroDivisionError(f"inverse of Mod({self}, {self._modulus.sageInteger}) does not exist")
+             else:
+                 return x
+         else:
+-            return self._new_c(mod_inverse_int(self.ivalue, self.__modulus.int32))
++            return self._new_c(mod_inverse_int(self.ivalue, self._modulus.int32))
+ 
+     def lift(IntegerMod_int self):
+         """
+@@ -3006,15 +3006,15 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: GF(103)(-1).sqrt(extend=False, all=True)
+             []
+         """
+-        cdef int_fast32_t i, n = self.__modulus.int32
++        cdef int_fast32_t i, n = self._modulus.int32
+         if n > 100:
+             moduli = self._parent.factored_order()
+         # Unless the modulus is tiny, test to see if we're in the really
+         # easy case of n prime, n = 3 mod 4.
+         if n > 100 and n % 4 == 3 and len(moduli) == 1 and moduli[0][1] == 1:
+-            if jacobi_int(self.ivalue, self.__modulus.int32) == 1:
++            if jacobi_int(self.ivalue, self._modulus.int32) == 1:
+                 # it's a non-zero square, sqrt(a) = a^(p+1)/4
+-                i = mod_pow_int(self.ivalue, (self.__modulus.int32+1)/4, n)
++                i = mod_pow_int(self.ivalue, (self._modulus.int32+1)/4, n)
+                 if i > n / 2:
+                     i = n - i
+                 if all:
+@@ -3049,7 +3049,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         This function returns `x` or `-x`, whichever has a
+         positive representative in `-n/2 < x \leq n/2`.
+         """
+-        if self.ivalue > self.__modulus.int32 / 2:
++        if self.ivalue > self._modulus.int32 / 2:
+             return -self
+         return self
+ 
+@@ -3082,9 +3082,9 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: mod(0,1).gcd(mod(0,1))
+             0
+         """
+-        cdef int_fast32_t g = gcd_int(self.ivalue, self.__modulus.int32)
++        cdef int_fast32_t g = gcd_int(self.ivalue, self._modulus.int32)
+         g = gcd_int(g, other.ivalue)
+-        if g == self.__modulus.int32: # self = other = 0
++        if g == self._modulus.int32: # self = other = 0
+             g = 0
+         return self._new_c(g)
+ 
+@@ -3256,27 +3256,27 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+     cdef IntegerMod_int64 _new_c(self, int_fast64_t value):
+         cdef IntegerMod_int64 x
+         x = IntegerMod_int64.__new__(IntegerMod_int64)
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x._parent = self._parent
+         x.ivalue = value
+         return x
+ 
+     cdef void set_from_mpz(self, mpz_t value):
+-        self.ivalue = mpz_fdiv_ui(value, self.__modulus.int64)
++        self.ivalue = mpz_fdiv_ui(value, self._modulus.int64)
+ 
+     cdef void set_from_long(self, long value):
+-        self.ivalue = value % self.__modulus.int64
++        self.ivalue = value % self._modulus.int64
+         if self.ivalue < 0:
+-            self.ivalue += self.__modulus.int64
++            self.ivalue += self._modulus.int64
+ 
+     cdef void set_from_ulong_fast(self, unsigned long value):
+         self.ivalue = value
+ 
+     cdef void set_from_int(IntegerMod_int64 self, int_fast64_t ivalue):
+         if ivalue < 0:
+-            self.ivalue = self.__modulus.int64 + (ivalue % self.__modulus.int64) # Is ivalue % self.__modulus.int64 actually negative?
+-        elif ivalue >= self.__modulus.int64:
+-            self.ivalue = ivalue % self.__modulus.int64
++            self.ivalue = self._modulus.int64 + (ivalue % self._modulus.int64) # Is ivalue % self._modulus.int64 actually negative?
++        elif ivalue >= self._modulus.int64:
++            self.ivalue = ivalue % self._modulus.int64
+         else:
+             self.ivalue = ivalue
+ 
+@@ -3344,9 +3344,9 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: mod(25, 5^10).is_unit()
+             False
+         """
+-        return gcd_int64(self.ivalue, self.__modulus.int64) == 1
++        return gcd_int64(self.ivalue, self._modulus.int64) == 1
+ 
+-    def __crt(IntegerMod_int64 self, IntegerMod_int64 other):
++    def _crt(IntegerMod_int64 self, IntegerMod_int64 other):
+         """
+         Use the Chinese Remainder Theorem to find an element of the
+         integers modulo the product of the moduli that reduces to self and
+@@ -3379,11 +3379,11 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         cdef int_fast64_t x
+ 
+         from .integer_mod_ring import IntegerModRing
+-        lift = IntegerMod_int64(IntegerModRing(self.__modulus.int64 * other.__modulus.int64))
++        lift = IntegerMod_int64(IntegerModRing(self._modulus.int64 * other._modulus.int64))
+ 
+         try:
+-            x = (other.ivalue - self.ivalue % other.__modulus.int64) * mod_inverse_int64(self.__modulus.int64, other.__modulus.int64)
+-            lift.set_from_int( x * self.__modulus.int64 + self.ivalue )
++            x = (other.ivalue - self.ivalue % other._modulus.int64) * mod_inverse_int64(self._modulus.int64, other._modulus.int64)
++            lift.set_from_int( x * self._modulus.int64 + self.ivalue )
+             return lift
+         except ZeroDivisionError:
+             raise ZeroDivisionError("moduli must be coprime")
+@@ -3422,8 +3422,8 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         """
+         cdef int_fast64_t x
+         x = self.ivalue + (<IntegerMod_int64>right).ivalue
+-        if x >= self.__modulus.int64:
+-            x = x - self.__modulus.int64
++        if x >= self._modulus.int64:
++            x = x - self._modulus.int64
+         return self._new_c(x)
+ 
+     cpdef _sub_(self, right):
+@@ -3437,7 +3437,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         cdef int_fast64_t x
+         x = self.ivalue - (<IntegerMod_int64>right).ivalue
+         if x < 0:
+-            x = x + self.__modulus.int64
++            x = x + self._modulus.int64
+         return self._new_c(x)
+ 
+     cpdef _neg_(self):
+@@ -3451,7 +3451,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         """
+         if self.ivalue == 0:
+             return self
+-        return self._new_c(self.__modulus.int64 - self.ivalue)
++        return self._new_c(self._modulus.int64 - self.ivalue)
+ 
+     cpdef _mul_(self, right):
+         """
+@@ -3461,7 +3461,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: R(700) * R(800)
+             60000
+         """
+-        return self._new_c((self.ivalue * (<IntegerMod_int64>right).ivalue) % self.__modulus.int64)
++        return self._new_c((self.ivalue * (<IntegerMod_int64>right).ivalue) % self._modulus.int64)
+ 
+ 
+     cpdef _div_(self, right):
+@@ -3473,7 +3473,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             33334
+         """
+         return self._new_c((self.ivalue * mod_inverse_int64((<IntegerMod_int64>right).ivalue,
+-                                   self.__modulus.int64) ) % self.__modulus.int64)
++                                   self._modulus.int64) ) % self._modulus.int64)
+ 
+     def __int__(IntegerMod_int64 self):
+         return self.ivalue
+@@ -3559,7 +3559,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         if k == 0:
+             return self
+         elif k > 0:
+-            return self._new_c((self.ivalue << k) % self.__modulus.int64)
++            return self._new_c((self.ivalue << k) % self._modulus.int64)
+         else:
+             return self._new_c(self.ivalue >> (-k))
+ 
+@@ -3633,7 +3633,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sig_on()
+             try:
+                 mpz_init(res_mpz)
+-                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self.__modulus.sageInteger.value)
++                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self._modulus.sageInteger.value)
+                 res = mpz_get_ui(res_mpz)
+                 mpz_clear(res_mpz)
+             finally:
+@@ -3642,14 +3642,14 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+ 
+         if long_exp == 0 and self.ivalue == 0:
+             # Return 0 if the modulus is 1, otherwise return 1.
+-            return self._new_c(self.__modulus.int64 != 1)
++            return self._new_c(self._modulus.int64 != 1)
+         cdef bint invert = False
+         if long_exp < 0:
+             invert = True
+             long_exp = -long_exp
+-        res = mod_pow_int64(self.ivalue, long_exp, self.__modulus.int64)
++        res = mod_pow_int64(self.ivalue, long_exp, self._modulus.int64)
+         if invert:
+-            return self._new_c(mod_inverse_int64(res, self.__modulus.int64))
++            return self._new_c(mod_inverse_int64(res, self._modulus.int64))
+         else:
+             return self._new_c(res)
+ 
+@@ -3666,7 +3666,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: a
+             7
+         """
+-        return self._new_c(mod_inverse_int64(self.ivalue, self.__modulus.int64))
++        return self._new_c(mod_inverse_int64(self.ivalue, self._modulus.int64))
+ 
+     def lift(IntegerMod_int64 self):
+         """
+@@ -3715,7 +3715,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         This function returns `x` or `-x`, whichever has a
+         positive representative in `-n/2 < x \leq n/2`.
+         """
+-        if self.ivalue > self.__modulus.int64 / 2:
++        if self.ivalue > self._modulus.int64 / 2:
+             return -self
+         return self
+ 
+@@ -3738,9 +3738,9 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: mod(0,17^5).gcd(mod(0,17^5))
+             0
+         """
+-        cdef int_fast64_t g = gcd_int64(self.ivalue, self.__modulus.int64)
++        cdef int_fast64_t g = gcd_int64(self.ivalue, self._modulus.int64)
+         g = gcd_int64(g, other.ivalue)
+-        if g == self.__modulus.int64: # self = other = 0
++        if g == self._modulus.int64: # self = other = 0
+             g = 0
+         return self._new_c(g)
+ 
+diff --git a/src/sage/rings/fraction_field_FpT.pyx b/src/sage/rings/fraction_field_FpT.pyx
+index 0a25191a11c..c9bb5d5a384 100644
+--- a/src/sage/rings/fraction_field_FpT.pyx
++++ b/src/sage/rings/fraction_field_FpT.pyx
+@@ -1650,7 +1650,7 @@ cdef class FpT_Fp_section(Section):
+                 raise ValueError("not constant")
+         ans = IntegerMod_int.__new__(IntegerMod_int)
+         ans._parent = self.codomain()
+-        ans.__modulus = ans._parent._pyx_order
++        ans._modulus = ans._parent._pyx_order
+         if nmod_poly_get_coeff_ui(x._denom, 0) != 1:
+             normalize(x._numer, x._denom, self.p)
+         ans.ivalue = nmod_poly_get_coeff_ui(x._numer, 0)
+diff --git a/src/sage/rings/fraction_field_element.pyx b/src/sage/rings/fraction_field_element.pyx
+index 11a2b646d35..75e47af1299 100644
+--- a/src/sage/rings/fraction_field_element.pyx
++++ b/src/sage/rings/fraction_field_element.pyx
+@@ -78,8 +78,8 @@ cdef class FractionFieldElement(FieldElement):
+         sage: F.one().quo_rem(F.one())
+         (1, 0)
+     """
+-    cdef object __numerator
+-    cdef object __denominator
++    cdef object _numerator
++    cdef object _denominator
+     cdef bint _is_reduced
+ 
+     def __init__(self, parent, numerator, denominator=1,
+@@ -108,17 +108,17 @@ cdef class FractionFieldElement(FieldElement):
+         """
+         FieldElement.__init__(self, parent)
+         if coerce:
+-            self.__numerator   = parent.ring()(numerator)
+-            self.__denominator = parent.ring()(denominator)
++            self._numerator   = parent.ring()(numerator)
++            self._denominator = parent.ring()(denominator)
+         else:
+-            self.__numerator   = numerator
+-            self.__denominator = denominator
++            self._numerator   = numerator
++            self._denominator = denominator
+         if reduce and parent.is_exact():
+             try:
+                 self.reduce()
+             except ArithmeticError:
+                 pass
+-        if self.__denominator.is_zero():
++        if self._denominator.is_zero():
+             raise ZeroDivisionError("fraction field element division by zero")
+ 
+     def _im_gens_(self, codomain, im_gens, base_map=None):
+@@ -154,8 +154,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: phi(i/a)                                                              # optional - sage.rings.number_field
+             ((-i))/b
+         """
+-        nnum = codomain.coerce(self.__numerator._im_gens_(codomain, im_gens, base_map=base_map))
+-        nden = codomain.coerce(self.__denominator._im_gens_(codomain, im_gens, base_map=base_map))
++        nnum = codomain.coerce(self._numerator._im_gens_(codomain, im_gens, base_map=base_map))
++        nden = codomain.coerce(self._denominator._im_gens_(codomain, im_gens, base_map=base_map))
+         return codomain.coerce(nnum/nden)
+ 
+     cpdef reduce(self):
+@@ -191,10 +191,10 @@ cdef class FractionFieldElement(FieldElement):
+         if self._is_reduced:
+             return
+         try:
+-            g = self.__numerator.gcd(self.__denominator)
++            g = self._numerator.gcd(self._denominator)
+             if not g.is_unit():
+-                self.__numerator //= g
+-                self.__denominator //= g
++                self._numerator //= g
++                self._denominator //= g
+             self._is_reduced = True
+         except AttributeError:
+             raise ArithmeticError("unable to reduce because lack of gcd or quo_rem algorithm")
+@@ -202,14 +202,14 @@ cdef class FractionFieldElement(FieldElement):
+             raise ArithmeticError("unable to reduce because gcd algorithm doesn't work on input")
+         except NotImplementedError:
+             raise ArithmeticError("unable to reduce because gcd algorithm not implemented on input")
+-        if not self.__denominator.is_one() and self.__denominator.is_unit():
++        if not self._denominator.is_one() and self._denominator.is_unit():
+             try:
+-                inv = self.__denominator.inverse_of_unit()
++                inv = self._denominator.inverse_of_unit()
+             except Exception:
+                 pass
+             else:
+-                self.__numerator *= inv
+-                self.__denominator = self.__denominator.parent().one()
++                self._numerator *= inv
++                self._denominator = self._denominator.parent().one()
+ 
+     def __copy__(self):
+         """
+@@ -223,8 +223,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: copy(f)
+             (x + y)/y
+         """
+-        return self.__class__(self._parent, self.__numerator,
+-                self.__denominator, coerce=False, reduce=False)
++        return self.__class__(self._parent, self._numerator,
++                self._denominator, coerce=False, reduce=False)
+ 
+     def numerator(self):
+         """
+@@ -238,7 +238,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f.numerator()
+             x + y
+         """
+-        return self.__numerator
++        return self._numerator
+ 
+     def denominator(self):
+         """
+@@ -252,7 +252,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f.denominator()
+             y
+         """
+-        return self.__denominator
++        return self._denominator
+ 
+ 
+     def is_square(self,root=False):
+@@ -399,10 +399,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: ((x+1)/(x^2+1)).subs({x: 1})                                          # optional - sage.rings.number_field
+             1
+         """
+-        if self.__denominator.is_one():
++        if self._denominator.is_one():
+             # Handle this case even over rings that don't support reduction, to
+             # avoid breaking existing code that carelessly mixes p and p/1
+-            return hash(self.__numerator)
++            return hash(self._numerator)
+         if self._parent.is_exact():
+             # May fail; let the exception propagate then.
+             # (In contrast, over inexact rings, we hash unreduced fractions
+@@ -413,8 +413,8 @@ cdef class FractionFieldElement(FieldElement):
+             # issues even if we didn't...)
+             self.reduce()
+         # Same algorithm as for elements of QQ
+-        n = hash(self.__numerator)
+-        d = hash(self.__denominator)
++        n = hash(self._numerator)
++        d = hash(self._denominator)
+         if d == 1:
+             return n
+         else:
+@@ -443,7 +443,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: h(x0=1)
+             (-2*x1*x2 + x1 + 1)/(x1 + x2)
+         """
+-        return self.__numerator(*x, **kwds) / self.__denominator(*x, **kwds)
++        return self._numerator(*x, **kwds) / self._denominator(*x, **kwds)
+ 
+     def _is_atomic(self):
+         """
+@@ -456,7 +456,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f._is_atomic()
+             False
+         """
+-        return self.__numerator._is_atomic() and self.__denominator._is_atomic()
++        return self._numerator._is_atomic() and self._denominator._is_atomic()
+ 
+     def _repr_(self):
+         """
+@@ -476,13 +476,13 @@ cdef class FractionFieldElement(FieldElement):
+         """
+         if self.is_zero():
+             return "0"
+-        s = "%s" % self.__numerator
+-        if self.__denominator != 1:
+-            denom_string = str( self.__denominator )
+-            if self.__denominator._is_atomic() and not ('*' in denom_string or '/' in denom_string):
+-                s = "%s/%s"%(self.__numerator._coeff_repr(no_space=False),denom_string)
++        s = "%s" % self._numerator
++        if self._denominator != 1:
++            denom_string = str( self._denominator )
++            if self._denominator._is_atomic() and not ('*' in denom_string or '/' in denom_string):
++                s = "%s/%s"%(self._numerator._coeff_repr(no_space=False),denom_string)
+             else:
+-                s = "%s/(%s)"%(self.__numerator._coeff_repr(no_space=False),denom_string)
++                s = "%s/(%s)"%(self._numerator._coeff_repr(no_space=False),denom_string)
+         return s
+ 
+     def _latex_(self):
+@@ -518,10 +518,10 @@ cdef class FractionFieldElement(FieldElement):
+         """
+         if self.is_zero():
+             return "0"
+-        if self.__denominator == 1:
+-            return latex.latex(self.__numerator)
+-        return "\\frac{%s}{%s}"%(latex.latex(self.__numerator),
+-                                 latex.latex(self.__denominator))
++        if self._denominator == 1:
++            return latex.latex(self._numerator)
++        return "\\frac{%s}{%s}"%(latex.latex(self._numerator),
++                                 latex.latex(self._denominator))
+ 
+     def _magma_init_(self, magma):
+         """
+@@ -577,10 +577,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: t - 1/t # indirect doctest                                            # optional - sage.rings.finite_rings
+             (t^2 + 6)/t
+         """
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         if (rnum.is_zero()):
+             return <FractionFieldElement> right
+@@ -602,7 +602,7 @@ cdef class FractionFieldElement(FieldElement):
+                             self._parent.ring().one(), coerce=False,
+                             reduce=False)
+                     else:
+-                        tden = self.__denominator * sden
++                        tden = self._denominator * sden
+                         e    = tnum.gcd(d)
+                         if not e.is_unit():
+                             tnum = tnum // e
+@@ -624,10 +624,10 @@ cdef class FractionFieldElement(FieldElement):
+             except TypeError:
+                 pass
+ 
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         return self.__class__(self._parent, rnum*sden + rden*snum, rden*sden,
+             coerce=False, reduce=False)
+@@ -652,10 +652,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: a * b # indirect doctest                                              # optional - sage.rings.finite_rings
+             3/(t + 1)
+         """
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         if (rnum.is_zero() or snum.is_zero()):
+             return self._parent.zero()
+@@ -689,10 +689,10 @@ cdef class FractionFieldElement(FieldElement):
+             except TypeError:
+                 pass
+ 
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         return self.__class__(self._parent, rnum * snum, rden * sden,
+             coerce=False, reduce=False)
+@@ -717,8 +717,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: a/b
+             (x*z - x + z - 1)/(z - 3)
+         """
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         if snum.is_zero():
+             raise ZeroDivisionError("fraction field element division by zero")
+@@ -743,10 +743,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: int(K(.5))
+             0
+         """
+-        if self.__denominator != 1:
++        if self._denominator != 1:
+             self.reduce()
+-        if self.__denominator == 1:
+-            return int(self.__numerator)
++        if self._denominator == 1:
++            return int(self._numerator)
+         else:
+             raise TypeError("denominator must equal 1")
+ 
+@@ -758,7 +758,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: float(x/x + y/y)
+             2.0
+         """
+-        return float(self.__numerator) / float(self.__denominator)
++        return float(self._numerator) / float(self._denominator)
+ 
+     def __complex__(self):
+         """
+@@ -768,7 +768,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: complex(x/(I*x) + (I*y)/y)
+             0j
+         """
+-        return complex(self.__numerator) / complex(self.__denominator)
++        return complex(self._numerator) / complex(self._denominator)
+ 
+     def _rational_(self):
+         r"""
+@@ -822,12 +822,12 @@ cdef class FractionFieldElement(FieldElement):
+             sage: A(C(u))                                                               # optional - sage.rings.number_field
+             u
+         """
+-        if self.__denominator.is_one():
+-            return R(self.__numerator)
++        if self._denominator.is_one():
++            return R(self._numerator)
+         else:
+             self.reduce()
+-            num = R(self.__numerator)
+-            inv_den = R(self.__denominator).inverse_of_unit()
++            num = R(self._numerator)
++            inv_den = R(self._denominator).inverse_of_unit()
+             return num * inv_den
+ 
+     _real_double_ = _conversion
+@@ -847,7 +847,7 @@ cdef class FractionFieldElement(FieldElement):
+         Returns self raised to the `right^{th}` power.
+ 
+         Note that we need to check whether or not right is negative so we
+-        don't set ``__numerator`` or ``__denominator`` to an element of the
++        don't set ``_numerator`` or ``_denominator`` to an element of the
+         fraction field instead of the underlying ring.
+ 
+         EXAMPLES::
+@@ -876,8 +876,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: ((x+y)/(x-y))^0
+             1
+         """
+-        snum = (<FractionFieldElement> self).__numerator
+-        sden = (<FractionFieldElement> self).__denominator
++        snum = (<FractionFieldElement> self)._numerator
++        sden = (<FractionFieldElement> self)._denominator
+         if right == 0:
+             R = self.parent().ring()
+             return self.__class__(self.parent(),
+@@ -904,7 +904,7 @@ cdef class FractionFieldElement(FieldElement):
+             (4*t^2 + 4*t)/(t + 2)
+         """
+         return self.__class__(self._parent,
+-            -self.__numerator, self.__denominator,
++            -self._numerator, self._denominator,
+             coerce=False, reduce=False)
+ 
+     def __abs__(self):
+@@ -915,7 +915,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: abs(FractionFieldElement(QQ, -2, 3, coerce=False))
+             2/3
+         """
+-        return abs(self.__numerator) / abs(self.__denominator)
++        return abs(self._numerator) / abs(self._denominator)
+ 
+     def __invert__(self):
+         """
+@@ -929,7 +929,7 @@ cdef class FractionFieldElement(FieldElement):
+         if self.is_zero():
+             raise ZeroDivisionError("Cannot invert 0")
+         return self.__class__(self._parent,
+-            self.__denominator, self.__numerator, coerce=False, reduce=False)
++            self._denominator, self._numerator, coerce=False, reduce=False)
+ 
+     cpdef _richcmp_(self, other, int op):
+         """
+@@ -951,10 +951,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: 1 > y
+             False
+         """
+-        return richcmp(self.__numerator *
+-                       (<FractionFieldElement>other).__denominator,
+-                       self.__denominator *
+-                       (<FractionFieldElement>other).__numerator, op)
++        return richcmp(self._numerator *
++                       (<FractionFieldElement>other)._denominator,
++                       self._denominator *
++                       (<FractionFieldElement>other)._numerator, op)
+ 
+     def valuation(self, v=None):
+         """
+@@ -972,7 +972,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f.valuation(x^2 + 1)
+             1
+         """
+-        return self.__numerator.valuation(v) - self.__denominator.valuation(v)
++        return self._numerator.valuation(v) - self._denominator.valuation(v)
+ 
+     def __bool__(self):
+         """
+@@ -991,7 +991,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: bool(1/x)
+             True
+         """
+-        return not self.__numerator.is_zero()
++        return not self._numerator.is_zero()
+ 
+     def is_zero(self):
+         """
+@@ -1010,7 +1010,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: u.parent() is F
+             True
+         """
+-        return self.__numerator.is_zero()
++        return self._numerator.is_zero()
+ 
+     def is_one(self):
+         """
+@@ -1025,7 +1025,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: (x/y).is_one()
+             False
+         """
+-        return self.__numerator == self.__denominator
++        return self._numerator == self._denominator
+ 
+     def _symbolic_(self, ring):
+         """
+@@ -1044,7 +1044,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: symbolic_expression(elt)                                              # optional - sage.symbolic
+             2/3*(x + y)/(x - y)
+         """
+-        return ring(self.__numerator)/ring(self.__denominator)
++        return ring(self._numerator)/ring(self._denominator)
+ 
+     def __reduce__(self):
+         """
+@@ -1058,7 +1058,7 @@ cdef class FractionFieldElement(FieldElement):
+             True
+         """
+         return (make_element,
+-                (self._parent, self.__numerator, self.__denominator))
++                (self._parent, self._numerator, self._denominator))
+ 
+     def _evaluate_polynomial(self, pol):
+         """
+@@ -1170,9 +1170,9 @@ cdef class FractionFieldElement_1poly_field(FractionFieldElement):
+         """
+         See :meth:`reduce`.
+         """
+-        invlc = ~self.__denominator.leading_coefficient()
+-        self.__denominator = self.__denominator.monic()
+-        self.__numerator *= invlc
++        invlc = ~self._denominator.leading_coefficient()
++        self._denominator = self._denominator.monic()
++        self._numerator *= invlc
+ 
+     def is_integral(self):
+         """
+diff --git a/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py b/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py
+index a27e75f5fce..74ef125fb6a 100644
+--- a/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py
++++ b/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py
+@@ -804,8 +804,8 @@ def _latex_(self):
+             \phi
+             sage: phi.reset_name()
+         """
+-        if hasattr(self, '__custom_name'):
+-            return latex_variable_name(getattr(self, '__custom_name'))
++        if self.get_custom_name() is not None:
++            return latex_variable_name(self.get_custom_name())
+         else:
+             return f'\\phi: {latex(self._function_ring.gen())} \\mapsto ' \
+                    f'{latex(self._gen)}'
+diff --git a/src/sage/rings/laurent_series_ring_element.pxd b/src/sage/rings/laurent_series_ring_element.pxd
+index d190645ce52..8df5a92c9e7 100644
+--- a/src/sage/rings/laurent_series_ring_element.pxd
++++ b/src/sage/rings/laurent_series_ring_element.pxd
+@@ -4,7 +4,7 @@ cdef class LaurentSeries(AlgebraElement):
+     cdef ModuleElement __u
+     cdef long __n
+ 
+-    cdef __normalize(self)
++    cdef _normalize(self)
+     cpdef _add_(self, other)
+     cpdef _mul_(self, other)
+ 
+diff --git a/src/sage/rings/laurent_series_ring_element.pyx b/src/sage/rings/laurent_series_ring_element.pyx
+index 8e950478045..9bef72396b7 100644
+--- a/src/sage/rings/laurent_series_ring_element.pyx
++++ b/src/sage/rings/laurent_series_ring_element.pyx
+@@ -302,7 +302,7 @@ cdef class LaurentSeries(AlgebraElement):
+         x = im_gens[0]
+         return codomain(self.__u._im_gens_(codomain, im_gens, base_map=base_map) * x**self.__n)
+ 
+-    cdef __normalize(self):
++    cdef _normalize(self):
+         r"""
+         A Laurent series is a pair (u(t), n), where either u=0 (to some
+         precision) or u is a unit. This pair corresponds to
+@@ -725,7 +725,7 @@ cdef class LaurentSeries(AlgebraElement):
+                 R = self._parent.base_ring()
+                 coeffs = [value] + [R(0) for _ in range(1,-j)] + self.__u.list()
+                 self.__u = self.__u._parent(coeffs)
+-        self.__normalize()
++        self._normalize()
+ 
+     cpdef _add_(self, right_m):
+         """
+diff --git a/src/sage/rings/morphism.pxd b/src/sage/rings/morphism.pxd
+index ea6089f29b4..4b8e8d052df 100644
+--- a/src/sage/rings/morphism.pxd
++++ b/src/sage/rings/morphism.pxd
+@@ -14,7 +14,7 @@ cdef class RingMap_lift(RingMap):
+ 
+ cdef class RingHomomorphism(RingMap):
+     cdef Morphism _lift
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+ cdef class RingHomomorphism_im_gens(RingHomomorphism):
+     cdef _im_gens
+diff --git a/src/sage/rings/number_field/number_field_element.pxd b/src/sage/rings/number_field/number_field_element.pxd
+index 9b6917223a0..c3d8a8b4a4b 100644
+--- a/src/sage/rings/number_field/number_field_element.pxd
++++ b/src/sage/rings/number_field/number_field_element.pxd
+@@ -11,12 +11,12 @@ from sage.libs.ntl.ntl_ZZ cimport ntl_ZZ
+ 
+ 
+ cdef class NumberFieldElement(NumberFieldElement_base):
+-    cdef ZZX_c __numerator
+-    cdef ZZ_c __denominator
++    cdef ZZX_c _numerator
++    cdef ZZ_c _denominator
+     # Pointers to the defining polynomial (with numerator) for the field.
+     # I keep these as pointers for arithmetic speed.
+-    cdef ntl_ZZX __fld_numerator
+-    cdef ntl_ZZ __fld_denominator
++    cdef ntl_ZZX _fld_numerator
++    cdef ntl_ZZ _fld_denominator
+     cdef object __multiplicative_order
+     cdef object __pari
+     cdef object __matrix
+diff --git a/src/sage/rings/number_field/number_field_element.pyx b/src/sage/rings/number_field/number_field_element.pyx
+index 27e33ad5be0..d44fc55b70c 100644
+--- a/src/sage/rings/number_field/number_field_element.pyx
++++ b/src/sage/rings/number_field/number_field_element.pyx
+@@ -218,8 +218,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef type t = type(self)
+         cdef NumberFieldElement x = <NumberFieldElement>t.__new__(t)
+         x._parent = self._parent
+-        x.__fld_numerator = self.__fld_numerator
+-        x.__fld_denominator = self.__fld_denominator
++        x._fld_numerator = self._fld_numerator
++        x._fld_denominator = self._fld_denominator
+         return x
+ 
+     cdef number_field(self):
+@@ -317,20 +317,20 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             True
+         """
+         FieldElement.__init__(self, parent)
+-        self.__fld_numerator, self.__fld_denominator = parent.absolute_polynomial_ntl()
++        self._fld_numerator, self._fld_denominator = parent.absolute_polynomial_ntl()
+ 
+         cdef ZZ_c coeff
+         if isinstance(f, (int, Integer_sage)):
+             # set it up and exit immediately
+             # fast pathway
+             mpz_to_ZZ(&coeff, (<Integer>ZZ(f)).value)
+-            ZZX_SetCoeff( self.__numerator, 0, coeff )
+-            ZZ_conv_from_int( self.__denominator, 1 )
++            ZZX_SetCoeff( self._numerator, 0, coeff )
++            ZZ_conv_from_int( self._denominator, 1 )
+             return
+         elif isinstance(f, NumberFieldElement):
+             if type(self) is type(f):
+-                self.__numerator = (<NumberFieldElement>f).__numerator
+-                self.__denominator = (<NumberFieldElement>f).__denominator
++                self._numerator = (<NumberFieldElement>f)._numerator
++                self._denominator = (<NumberFieldElement>f)._denominator
+                 return
+             else:
+                 f = f.polynomial()
+@@ -342,11 +342,11 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+ 
+         cdef long i
+         den = f.denominator()
+-        mpz_to_ZZ(&self.__denominator, (<Integer>ZZ(den)).value)
++        mpz_to_ZZ(&self._denominator, (<Integer>ZZ(den)).value)
+         num = f * den
+         for i from 0 <= i <= num.degree():
+             mpz_to_ZZ(&coeff, (<Integer>ZZ(num[i])).value)
+-            ZZX_SetCoeff( self.__numerator, i, coeff )
++            ZZX_SetCoeff( self._numerator, i, coeff )
+ 
+     def _lift_cyclotomic_element(self, new_parent, bint check=True, int rel=0):
+         """
+@@ -417,17 +417,17 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef type t = type(self)
+         cdef NumberFieldElement x = <NumberFieldElement>t.__new__(t)
+         x._parent = <ParentWithBase>new_parent
+-        x.__fld_numerator, x.__fld_denominator = new_parent.polynomial_ntl()
+-        x.__denominator = self.__denominator
++        x._fld_numerator, x._fld_denominator = new_parent.polynomial_ntl()
++        x._denominator = self._denominator
+         cdef ZZX_c result
+         cdef ZZ_c tmp
+         cdef int i
+         cdef ntl_ZZX _num
+         cdef ntl_ZZ _den
+-        for i from 0 <= i <= ZZX_deg(self.__numerator):
+-            tmp = ZZX_coeff(self.__numerator, i)
++        for i from 0 <= i <= ZZX_deg(self._numerator):
++            tmp = ZZX_coeff(self._numerator, i)
+             ZZX_SetCoeff(result, i*rel, tmp)
+-        ZZX_rem(x.__numerator, result, x.__fld_numerator.x)
++        ZZX_rem(x._numerator, result, x._fld_numerator.x)
+         return x
+ 
+     def __reduce__(self):
+@@ -858,7 +858,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef int res
+ 
+         # fast equality check
+-        res = left.__numerator == _right.__numerator and left.__denominator == _right.__denominator
++        res = left._numerator == _right._numerator and left._denominator == _right._denominator
+         if res:
+             if op == Py_EQ or op == Py_GE or op == Py_LE:
+                 return True
+@@ -883,15 +883,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         if P._embedded_real:
+             mpz_init(ld)
+             mpz_init(rd)
+-            ZZ_to_mpz(ld, &left.__denominator)
+-            ZZ_to_mpz(rd, &_right.__denominator)
++            ZZ_to_mpz(ld, &left._denominator)
++            ZZ_to_mpz(rd, &_right._denominator)
+ 
+             v = <RealIntervalFieldElement> P._get_embedding_approx(0)
+             mpfi_init2(la, mpfi_get_prec(v.value))
+             mpfi_init2(ra, mpfi_get_prec(v.value))
+-            ZZX_evaluation_mpfi(la, left.__numerator, v.value)
++            ZZX_evaluation_mpfi(la, left._numerator, v.value)
+             mpfi_div_z(la, la, ld)
+-            ZZX_evaluation_mpfi(ra, _right.__numerator, v.value)
++            ZZX_evaluation_mpfi(ra, _right._numerator, v.value)
+             mpfi_div_z(ra, ra, rd)
+             while mpfr_greaterequal_p(&la.right, &ra.left) \
+                   and mpfr_greaterequal_p(&ra.right, &la.left):
+@@ -899,9 +899,9 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+                 v = <RealIntervalFieldElement> P._get_embedding_approx(i)
+                 mpfi_set_prec(la, mpfi_get_prec(v.value))
+                 mpfi_set_prec(ra, mpfi_get_prec(v.value))
+-                ZZX_evaluation_mpfi(la, left.__numerator, v.value)
++                ZZX_evaluation_mpfi(la, left._numerator, v.value)
+                 mpfi_div_z(la, la, ld)
+-                ZZX_evaluation_mpfi(ra, _right.__numerator, v.value)
++                ZZX_evaluation_mpfi(ra, _right._numerator, v.value)
+                 mpfi_div_z(ra, ra, rd)
+             if op == Py_LT or op == Py_LE:
+                 res = mpfr_less_p(&la.right, &ra.left)
+@@ -950,8 +950,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef Rational tmp_rational
+ 
+         # It seems like a simpler approach would be to simply generate
+-        # random integers for each coefficient of self.__numerator
+-        # and an integer for self.__denominator. However, this would
++        # random integers for each coefficient of self._numerator
++        # and an integer for self._denominator. However, this would
+         # generate things with a fairly fixed shape: in particular,
+         # we'd be very unlikely to get elements like 1/3*a^3 + 1/7,
+         # or anything where the denominators are actually unrelated
+@@ -965,19 +965,19 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+ 
+             # set the denominator
+             mpz_set_si(denom_temp.value, 1)
+-            mpz_to_ZZ(&self.__denominator, (<Integer>denom_temp).value)
+-            for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
++            mpz_to_ZZ(&self._denominator, (<Integer>denom_temp).value)
++            for i from 0 <= i < ZZX_deg(self._fld_numerator.x):
+                 tmp_integer = <Integer>(ZZ.random_element(x=num_bound,
+                                                    distribution=distribution))
+                 mpz_to_ZZ(&ntl_temp, (<Integer>tmp_integer).value)
+-                ZZX_SetCoeff(self.__numerator, i, ntl_temp)
++                ZZX_SetCoeff(self._numerator, i, ntl_temp)
+ 
+         else:
+             coeff_list = []
+             mpz_set_si(denom_temp.value, 1)
+             tmp_integer = Integer.__new__(Integer)
+ 
+-            for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
++            for i from 0 <= i < ZZX_deg(self._fld_numerator.x):
+                 tmp_rational = <Rational>(QQ.random_element(num_bound=num_bound,
+                                                             den_bound=den_bound,
+                                                             distribution=distribution))
+@@ -989,10 +989,10 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             # scale the numerators and set everything appropriately
+ 
+             # first, the denominator (easy)
+-            mpz_to_ZZ(&self.__denominator, (<Integer>denom_temp).value)
++            mpz_to_ZZ(&self._denominator, (<Integer>denom_temp).value)
+ 
+             # now the coefficients themselves.
+-            for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
++            for i from 0 <= i < ZZX_deg(self._fld_numerator.x):
+                 # calculate the new numerator. if our old entry is
+                 # p/q, and the lcm is k, it's just pk/q, which we
+                 # also know is integral -- so we can use mpz_divexact
+@@ -1006,7 +1006,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+                 # now set the coefficient of self
+                 mpz_to_ZZ(&ntl_temp, (<Integer>tmp_integer).value)
+ 
+-                ZZX_SetCoeff(self.__numerator, i, ntl_temp)
++                ZZX_SetCoeff(self._numerator, i, ntl_temp)
+ 
+         return 0  # No error
+ 
+@@ -1089,10 +1089,10 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: L.zero().sign()
+             0
+         """
+-        if ZZX_deg(self.__numerator) == -1:
++        if ZZX_deg(self._numerator) == -1:
+             return 0
+-        if ZZX_deg(self.__numerator) == 0:
+-            return ZZ_sign(ZZX_coeff(self.__numerator, 0))
++        if ZZX_deg(self._numerator) == 0:
++            return ZZ_sign(ZZX_coeff(self._numerator, 0))
+ 
+         if not (<number_field_base.NumberField> self._parent)._embedded_real:
+             raise TypeError("sign not well defined since no real embedding is specified")
+@@ -1153,12 +1153,12 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef RealIntervalFieldElement v
+ 
+ 
+-        if ZZX_deg(self.__numerator) <= 0:
++        if ZZX_deg(self._numerator) <= 0:
+             mpz_init(num)
+             mpz_init(den)
+ 
+-            ZZX_getitem_as_mpz(num, &self.__numerator, 0)
+-            ZZ_to_mpz(den, &self.__denominator)
++            ZZX_getitem_as_mpz(num, &self._numerator, 0)
++            ZZ_to_mpz(den, &self._denominator)
+ 
+             ans = PY_NEW(Integer)
+             mpz_fdiv_q(ans.value, num, den)
+@@ -1183,9 +1183,9 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         mpz_init(den)
+         mpfi_init2(a, mpfi_get_prec(v.value))
+ 
+-        ZZ_to_mpz(den, &self.__denominator)
++        ZZ_to_mpz(den, &self._denominator)
+ 
+-        ZZX_evaluation_mpfi(a, self.__numerator, v.value)
++        ZZX_evaluation_mpfi(a, self._numerator, v.value)
+         mpfi_div_z(a, a, den)
+ 
+         mpfr_floor(&a.left, &a.left)
+@@ -1197,7 +1197,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             v = <RealIntervalFieldElement> P._get_embedding_approx(i)
+ 
+             mpfi_set_prec(a, mpfi_get_prec(v.value))
+-            ZZX_evaluation_mpfi(a, self.__numerator, v.value)
++            ZZX_evaluation_mpfi(a, self._numerator, v.value)
+             mpfi_div_z(a, a, den)
+             mpfr_floor(&a.left ,&a.left)
+             mpfr_floor(&a.right, &a.right)
+@@ -1248,7 +1248,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             ...
+             TypeError: ceil not uniquely defined since no real embedding is specified
+         """
+-        if ZZX_deg(self.__numerator) <= 0:
++        if ZZX_deg(self._numerator) <= 0:
+             return self._rational_().ceil()
+ 
+         if not (<number_field_base.NumberField> self._parent)._embedded_real:
+@@ -1311,7 +1311,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             ...
+             TypeError: floor not uniquely defined since no real embedding is specified
+         """
+-        if ZZX_deg(self.__numerator) <= 0:
++        if ZZX_deg(self._numerator) <= 0:
+             return self._rational_().round()
+ 
+         return (self + QQ((1,2))).floor()
+@@ -2483,17 +2483,17 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef ZZ_c gcd
+         cdef ZZ_c t1
+         cdef ZZX_c t2
+-        if ZZ_IsOne(self.__denominator):
++        if ZZ_IsOne(self._denominator):
+             return
+-        ZZX_content(t1, self.__numerator)
+-        ZZ_GCD(gcd, t1, self.__denominator)
+-        if ZZ_sign(gcd) != ZZ_sign(self.__denominator):
++        ZZX_content(t1, self._numerator)
++        ZZ_GCD(gcd, t1, self._denominator)
++        if ZZ_sign(gcd) != ZZ_sign(self._denominator):
+             ZZ_negate(t1, gcd)
+             gcd = t1
+-        ZZX_div_ZZ(t2, self.__numerator, gcd)
+-        ZZ_div(t1, self.__denominator, gcd)
+-        self.__numerator = t2
+-        self.__denominator = t1
++        ZZX_div_ZZ(t2, self._numerator, gcd)
++        ZZ_div(t1, self._denominator, gcd)
++        self._numerator = t2
++        self._denominator = t1
+ 
+     cpdef _add_(self, right):
+         r"""
+@@ -2509,15 +2509,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef NumberFieldElement _right = right
+         cdef ZZ_c g, q1, q2
+         x = self._new()
+-        ZZ_GCD(g, self.__denominator, _right.__denominator)
+-        ZZ_div(q1, self.__denominator, g)
+-        ZZ_div(q2, _right.__denominator, g)
+-        ZZ_mul(x.__denominator, q1, q2)
+-        ZZ_mul(x.__denominator, x.__denominator, g)
++        ZZ_GCD(g, self._denominator, _right._denominator)
++        ZZ_div(q1, self._denominator, g)
++        ZZ_div(q2, _right._denominator, g)
++        ZZ_mul(x._denominator, q1, q2)
++        ZZ_mul(x._denominator, x._denominator, g)
+         cdef ZZX_c t1, t2
+-        ZZX_mul_ZZ(t1, self.__numerator, q2)
+-        ZZX_mul_ZZ(t2, _right.__numerator, q1)
+-        ZZX_add(x.__numerator, t1, t2)
++        ZZX_mul_ZZ(t1, self._numerator, q2)
++        ZZX_mul_ZZ(t2, _right._numerator, q1)
++        ZZX_add(x._numerator, t1, t2)
+         x._reduce_c_()
+         return x
+ 
+@@ -2534,15 +2534,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef NumberFieldElement _right = right
+         cdef ZZ_c g, q1, q2
+         x = self._new()
+-        ZZ_GCD(g, self.__denominator, _right.__denominator)
+-        ZZ_div(q1, self.__denominator, g)
+-        ZZ_div(q2, _right.__denominator, g)
+-        ZZ_mul(x.__denominator, q1, q2)
+-        ZZ_mul(x.__denominator, x.__denominator, g)
++        ZZ_GCD(g, self._denominator, _right._denominator)
++        ZZ_div(q1, self._denominator, g)
++        ZZ_div(q2, _right._denominator, g)
++        ZZ_mul(x._denominator, q1, q2)
++        ZZ_mul(x._denominator, x._denominator, g)
+         cdef ZZX_c t1, t2
+-        ZZX_mul_ZZ(t1, self.__numerator, q2)
+-        ZZX_mul_ZZ(t2, _right.__numerator, q1)
+-        ZZX_sub(x.__numerator, t1, t2)
++        ZZX_mul_ZZ(t1, self._numerator, q2)
++        ZZX_mul_ZZ(t2, _right._numerator, q1)
++        ZZX_sub(x._numerator, t1, t2)
+         x._reduce_c_()
+         return x
+ 
+@@ -2571,18 +2571,18 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         sig_on()
+         # MulMod doesn't handle non-monic polynomials.
+         # Therefore, we handle the non-monic case entirely separately.
+-        ZZ_mul(x.__denominator, self.__denominator, _right.__denominator)
+-        if ZZ_IsOne(ZZX_LeadCoeff(self.__fld_numerator.x)):
+-            ZZX_MulMod(x.__numerator, self.__numerator, _right.__numerator, self.__fld_numerator.x)
++        ZZ_mul(x._denominator, self._denominator, _right._denominator)
++        if ZZ_IsOne(ZZX_LeadCoeff(self._fld_numerator.x)):
++            ZZX_MulMod(x._numerator, self._numerator, _right._numerator, self._fld_numerator.x)
+         else:
+-            ZZX_mul(x.__numerator, self.__numerator, _right.__numerator)
+-            if ZZX_deg(x.__numerator) >= ZZX_deg(self.__fld_numerator.x):
+-                ZZX_mul_ZZ( x.__numerator, x.__numerator, self.__fld_denominator.x )
+-                ZZX_mul_ZZ( temp, self.__fld_numerator.x, x.__denominator )
+-                ZZ_power(temp1,ZZX_LeadCoeff(temp),ZZX_deg(x.__numerator)-ZZX_deg(self.__fld_numerator.x)+1)
+-                ZZX_PseudoRem(x.__numerator, x.__numerator, temp)
+-                ZZ_mul(x.__denominator, x.__denominator, self.__fld_denominator.x)
+-                ZZ_mul(x.__denominator, x.__denominator, temp1)
++            ZZX_mul(x._numerator, self._numerator, _right._numerator)
++            if ZZX_deg(x._numerator) >= ZZX_deg(self._fld_numerator.x):
++                ZZX_mul_ZZ( x._numerator, x._numerator, self._fld_denominator.x )
++                ZZX_mul_ZZ( temp, self._fld_numerator.x, x._denominator )
++                ZZ_power(temp1,ZZX_LeadCoeff(temp),ZZX_deg(x._numerator)-ZZX_deg(self._fld_numerator.x)+1)
++                ZZX_PseudoRem(x._numerator, x._numerator, temp)
++                ZZ_mul(x._denominator, x._denominator, self._fld_denominator.x)
++                ZZ_mul(x._denominator, x._denominator, temp1)
+         sig_off()
+         x._reduce_c_()
+         return x
+@@ -2704,7 +2704,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: bool(b + 1)
+             True
+         """
+-        return not IsZero_ZZX(self.__numerator)
++        return not IsZero_ZZX(self._numerator)
+ 
+     cpdef _neg_(self):
+         r"""
+@@ -2717,8 +2717,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         """
+         cdef NumberFieldElement x
+         x = self._new()
+-        ZZX_mul_long(x.__numerator, self.__numerator, -1)
+-        x.__denominator = self.__denominator
++        ZZX_mul_long(x._numerator, self._numerator, -1)
++        x._denominator = self._denominator
+         return x
+ 
+     cpdef _copy_for_parent(self, Parent parent):
+@@ -2738,8 +2738,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         """
+         cdef NumberFieldElement x
+         x = self._new()
+-        x.__numerator = self.__numerator
+-        x.__denominator = self.__denominator
++        x._numerator = self._numerator
++        x._denominator = self._denominator
+         x._set_parent(parent)
+         return x
+ 
+@@ -2826,7 +2826,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: L.<a> = K.extension(f)
+             sage: alpha = (a^8 + (zeta22^9 - zeta22^6 + 2*zeta22^4 + 33)*a^7)/(10**2555) #long time
+         """
+-        if IsZero_ZZX(self.__numerator):
++        if IsZero_ZZX(self._numerator):
+             raise ZeroDivisionError("number field element division by zero")
+         cdef NumberFieldElement x
+         cdef ZZX_c temp
+@@ -2835,8 +2835,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             # but may fail if NTL runs out of FFT primes.
+             x = self._new()
+             sig_on()
+-            ZZX_XGCD(x.__denominator, x.__numerator, temp, self.__numerator, self.__fld_numerator.x, 1)
+-            ZZX_mul_ZZ(x.__numerator, x.__numerator, self.__denominator)
++            ZZX_XGCD(x._denominator, x._numerator, temp, self._numerator, self._fld_numerator.x, 1)
++            ZZX_mul_ZZ(x._numerator, x._numerator, self._denominator)
+             x._reduce_c_()
+             sig_off()
+         except NTLError:
+@@ -2858,7 +2858,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: (2*I*I)._integer_()
+             -2
+         """
+-        if ZZX_deg(self.__numerator) >= 1:
++        if ZZX_deg(self._numerator) >= 1:
+             raise TypeError("Unable to coerce %s to an integer" % self)
+         return ZZ(self._rational_())
+ 
+@@ -2877,12 +2877,12 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: (I*I/2)._rational_()
+             -1/2
+         """
+-        if ZZX_deg(self.__numerator) >= 1:
++        if ZZX_deg(self._numerator) >= 1:
+             raise TypeError("Unable to coerce %s to a rational"%self)
+         cdef Integer num = Integer.__new__(Integer)
+-        ZZX_getitem_as_mpz(num.value, &self.__numerator, 0)
++        ZZX_getitem_as_mpz(num.value, &self._numerator, 0)
+         cdef Integer den = Integer.__new__(Integer)
+-        ZZ_to_mpz(den.value, &self.__denominator)
++        ZZ_to_mpz(den.value, &self._denominator)
+         return num / den
+ 
+     def _algebraic_(self, parent):
+@@ -3268,15 +3268,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef mpz_t z
+ 
+         mpz_init(z)
+-        ZZX_getitem_as_mpz(z, &self.__numerator, 0)
++        ZZX_getitem_as_mpz(z, &self._numerator, 0)
+         h = mpz_pythonhash(z)
+ 
+-        for i from 1 <= i <= ZZX_deg(self.__numerator):
+-            ZZX_getitem_as_mpz(z, &self.__numerator, i)
++        for i from 1 <= i <= ZZX_deg(self._numerator):
++            ZZX_getitem_as_mpz(z, &self._numerator, i)
+             # magic number below is floor(2^63 / (2+sqrt(2)))
+             h ^= mpz_pythonhash(z) + (<Py_hash_t> 2701463124188384701) + (h << 16) + (h >> 2)
+ 
+-        ZZ_to_mpz(z, &self.__denominator)
++        ZZ_to_mpz(z, &self._denominator)
+         # magic number below is floor((1+sqrt(5)) * 2^61)
+         h += (mpz_pythonhash(z) - 1) * (<Py_hash_t> 7461864723258187525)
+ 
+@@ -3305,12 +3305,12 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef int i
+         cdef mpz_t den
+         mpz_init(den)
+-        ZZ_to_mpz(den, &self.__denominator)
+-        cdef int size = ZZX_deg(self.__numerator) + 1
++        ZZ_to_mpz(den, &self._denominator)
++        cdef int size = ZZX_deg(self._numerator) + 1
+         cdef list coeffs = [None]*size
+         for i in range(size):
+             coeff = Rational.__new__(Rational)
+-            ZZX_getitem_as_mpz(mpq_numref(coeff.value), &self.__numerator, i)
++            ZZX_getitem_as_mpz(mpq_numref(coeff.value), &self._numerator, i)
+             mpz_set(mpq_denref(coeff.value), den)
+             mpq_canonicalize(coeff.value)
+             coeffs[i] = coeff
+@@ -3318,14 +3318,14 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         return coeffs
+ 
+     cdef void _ntl_coeff_as_mpz(self, mpz_t z, long i):
+-        if i > ZZX_deg(self.__numerator):
++        if i > ZZX_deg(self._numerator):
+             mpz_set_ui(z, 0)
+         else:
+-            ZZX_getitem_as_mpz(z, &self.__numerator, i)
++            ZZX_getitem_as_mpz(z, &self._numerator, i)
+ 
+     cdef void _ntl_denom_as_mpz(self, mpz_t z):
+         cdef Integer denom = Integer.__new__(Integer)
+-        ZZ_to_mpz(denom.value, &self.__denominator)
++        ZZ_to_mpz(denom.value, &self._denominator)
+         mpz_set(z, denom.value)
+ 
+     def denominator(self):
+@@ -3344,7 +3344,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             15
+         """
+         cdef Integer ans = Integer.__new__(Integer)
+-        ZZ_to_mpz(ans.value, &self.__denominator)
++        ZZ_to_mpz(ans.value, &self._denominator)
+         return ans
+ 
+     def _set_multiplicative_order(self, n):
+@@ -3474,8 +3474,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: a.is_one()
+             False
+         """
+-        return ZZX_IsOne(self.__numerator) == 1 and \
+-               ZZ_IsOne(self.__denominator) == 1
++        return ZZX_IsOne(self._numerator) == 1 and \
++               ZZ_IsOne(self._denominator) == 1
+ 
+     cpdef bint is_rational(self):
+         r"""
+@@ -3501,7 +3501,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: K(1/2).is_rational()
+             True
+         """
+-        return ZZX_deg(self.__numerator) <= 0
++        return ZZX_deg(self._numerator) <= 0
+ 
+     def is_integer(self):
+         r"""
+@@ -3527,7 +3527,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: K(1/2).is_integer()
+             False
+         """
+-        return ZZX_deg(self.__numerator) <= 0 and ZZ_IsOne(self.__denominator) == 1
++        return ZZX_deg(self._numerator) <= 0 and ZZ_IsOne(self._denominator) == 1
+ 
+     def trace(self, K=None):
+         r"""
+@@ -5322,8 +5322,8 @@ cdef class OrderElement_absolute(NumberFieldElement_absolute):
+         cdef OrderElement_absolute x = <OrderElement_absolute>t.__new__(t)
+         x._parent = self._parent
+         x._number_field = self._parent.number_field()
+-        x.__fld_numerator = self.__fld_numerator
+-        x.__fld_denominator = self.__fld_denominator
++        x._fld_numerator = self._fld_numerator
++        x._fld_denominator = self._fld_denominator
+         return x
+ 
+     cdef number_field(self):
+@@ -5443,8 +5443,8 @@ cdef class OrderElement_relative(NumberFieldElement_relative):
+         cdef OrderElement_relative x = <OrderElement_relative>t.__new__(t)
+         x._parent = self._parent
+         x._number_field = self._parent.number_field()
+-        x.__fld_numerator = self.__fld_numerator
+-        x.__fld_denominator = self.__fld_denominator
++        x._fld_numerator = self._fld_numerator
++        x._fld_denominator = self._fld_denominator
+         return x
+ 
+     def __invert__(self):
+diff --git a/src/sage/rings/number_field/number_field_element_quadratic.pyx b/src/sage/rings/number_field/number_field_element_quadratic.pyx
+index 0992e7cd527..c32f6aadd10 100644
+--- a/src/sage/rings/number_field/number_field_element_quadratic.pyx
++++ b/src/sage/rings/number_field/number_field_element_quadratic.pyx
+@@ -610,8 +610,8 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+         mpz_clear(tmp_mpz)
+ 
+         x._parent = <ParentWithBase>new_parent
+-        x.__fld_numerator, x.__fld_denominator = new_parent.polynomial_ntl()
+-        x.__denominator = elt_den
++        x._fld_numerator, x._fld_denominator = new_parent.polynomial_ntl()
++        x._denominator = elt_den
+         cdef ZZX_c result
+         cdef ZZ_c tmp
+         cdef int i
+@@ -621,7 +621,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+         for i from 0 <= i <= ZZX_deg(elt_num):
+             tmp = ZZX_coeff(elt_num, i)
+             ZZX_SetCoeff(result, i*rel, tmp)
+-        ZZX_rem(x.__numerator, result, _num.x)
++        ZZX_rem(x._numerator, result, _num.x)
+         (<NumberFieldElement_absolute>x)._reduce_c_()
+         return x
+ 
+@@ -1643,7 +1643,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+         return res
+ 
+ #################################################################################
+-# We must override everything that makes uses of self.__numerator/__denominator
++# We must override everything that makes uses of self._numerator/_denominator
+ #################################################################################
+ 
+     def __hash__(self):
+diff --git a/src/sage/rings/padics/CA_template.pxi b/src/sage/rings/padics/CA_template.pxi
+index a0a66c19621..d821b5c1576 100644
+--- a/src/sage/rings/padics/CA_template.pxi
++++ b/src/sage/rings/padics/CA_template.pxi
+@@ -1463,7 +1463,7 @@ cdef class pAdicCoercion_CA_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         ans._normalize()
+         return ans
+ 
+@@ -1516,7 +1516,7 @@ cdef class pAdicCoercion_CA_frac_field(RingHomomorphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+             pass
+         return ans
+ 
+@@ -1686,7 +1686,7 @@ cdef class pAdicConvert_CA_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 R = ans.value.base_ring()
+-                ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++                ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1741,7 +1741,7 @@ cdef class pAdicConvert_CA_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 R = ans.value.base_ring()
+-                ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++                ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/CR_template.pxi b/src/sage/rings/padics/CR_template.pxi
+index cb57bb2cb48..863c612587c 100644
+--- a/src/sage/rings/padics/CR_template.pxi
++++ b/src/sage/rings/padics/CR_template.pxi
+@@ -2184,7 +2184,7 @@ cdef class pAdicCoercion_CR_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -2241,7 +2241,7 @@ cdef class pAdicCoercion_CR_frac_field(RingHomomorphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     def section(self):
+@@ -2404,7 +2404,7 @@ cdef class pAdicConvert_CR_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -2463,7 +2463,7 @@ cdef class pAdicConvert_CR_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/FM_template.pxi b/src/sage/rings/padics/FM_template.pxi
+index ea7d4055660..f47200074ea 100644
+--- a/src/sage/rings/padics/FM_template.pxi
++++ b/src/sage/rings/padics/FM_template.pxi
+@@ -1227,7 +1227,7 @@ cdef class pAdicCoercion_FM_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1277,7 +1277,7 @@ cdef class pAdicCoercion_FM_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     def section(self):
+@@ -1435,7 +1435,7 @@ cdef class pAdicConvert_FM_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             R = ans.value.base_ring()
+-            ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++            ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1483,7 +1483,7 @@ cdef class pAdicConvert_FM_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             R = ans.value.base_ring()
+-            ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++            ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/FP_template.pxi b/src/sage/rings/padics/FP_template.pxi
+index 57ec619b278..c718c0a5f8d 100644
+--- a/src/sage/rings/padics/FP_template.pxi
++++ b/src/sage/rings/padics/FP_template.pxi
+@@ -1849,7 +1849,7 @@ cdef class pAdicCoercion_FP_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1903,7 +1903,7 @@ cdef class pAdicCoercion_FP_frac_field(RingHomomorphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     def section(self):
+@@ -2025,7 +2025,7 @@ cdef class pAdicConvert_FP_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -2081,7 +2081,7 @@ cdef class pAdicConvert_FP_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/pow_computer.pxd b/src/sage/rings/padics/pow_computer.pxd
+index 2a93e42254e..8766725882e 100644
+--- a/src/sage/rings/padics/pow_computer.pxd
++++ b/src/sage/rings/padics/pow_computer.pxd
+@@ -6,7 +6,7 @@ cdef class PowComputer_class(SageObject):
+     cdef Integer prime
+     cdef Integer p2 # floor(p/2)
+     cdef bint in_field
+-    cdef int __allocated
++    cdef int _allocated
+     cdef public object _prec_type
+ 
+     cdef long ram_prec_cap # = prec_cap * e
+diff --git a/src/sage/rings/padics/pow_computer.pyx b/src/sage/rings/padics/pow_computer.pyx
+index c2fa8031086..1c5bdf86897 100644
+--- a/src/sage/rings/padics/pow_computer.pyx
++++ b/src/sage/rings/padics/pow_computer.pyx
+@@ -65,7 +65,7 @@ cdef class PowComputer_class(SageObject):
+         sig_on()
+         mpz_init(self.temp_m)
+         sig_off()
+-        self.__allocated = 1
++        self._allocated = 1
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly=None, shift_seed=None):
+         """
+@@ -485,7 +485,7 @@ cdef class PowComputer_base(PowComputer_class):
+         finally:
+             sig_off()
+ 
+-        self.__allocated = 2
++        self._allocated = 2
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly=None, shift_seed=None):
+         """
+@@ -529,7 +529,7 @@ cdef class PowComputer_base(PowComputer_class):
+         """
+         cdef Py_ssize_t i
+ 
+-        if self.__allocated >= 2:
++        if self._allocated >= 2:
+             for i in range(self.cache_limit + 1):
+                 mpz_clear(self.small_powers[i])
+             mpz_clear(self.top_power)
+diff --git a/src/sage/rings/padics/pow_computer_flint.pyx b/src/sage/rings/padics/pow_computer_flint.pyx
+index 9f914defcc6..e521ea6e078 100644
+--- a/src/sage/rings/padics/pow_computer_flint.pyx
++++ b/src/sage/rings/padics/pow_computer_flint.pyx
+@@ -59,7 +59,7 @@ cdef class PowComputer_flint(PowComputer_class):
+         finally:
+             sig_off()
+ 
+-        self.__allocated = 4
++        self._allocated = 4
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly=None, shift_seed=None):
+         """
+@@ -87,7 +87,7 @@ cdef class PowComputer_flint(PowComputer_class):
+             sage: A = PowComputer_flint(5, 20, 20, 20, False)
+             sage: del A
+         """
+-        if self.__allocated >= 4:
++        if self._allocated >= 4:
+             fmpz_clear(self.fprime)
+             fmpz_clear(self.half_prime)
+             fmpz_clear(self._fpow_variable)
+@@ -208,7 +208,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+ 
+         """
+         cdef Polynomial_integer_dense_flint poly = _poly
+-        cdef long length = fmpz_poly_length(poly.__poly)
++        cdef long length = fmpz_poly_length(poly._poly)
+ 
+         cdef Py_ssize_t i
+ 
+@@ -251,7 +251,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         finally:
+             sig_off()
+ 
+-        self.__allocated = 8
++        self._allocated = 8
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, _poly, shift_seed=None):
+         """
+@@ -268,10 +268,10 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         PowComputer_flint.__init__(self, prime, cache_limit, prec_cap, ram_prec_cap, in_field, _poly, shift_seed)
+ 
+         cdef Polynomial_integer_dense_flint poly = _poly
+-        cdef long length = fmpz_poly_length(poly.__poly)
++        cdef long length = fmpz_poly_length(poly._poly)
+         self.deg = length - 1
+ 
+-        fmpz_poly_set(self.modulus, poly.__poly)
++        fmpz_poly_set(self.modulus, poly._poly)
+ 
+         cdef Py_ssize_t i
+         cdef fmpz* coeffs = self.modulus.coeffs
+@@ -296,7 +296,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         """
+         cdef Py_ssize_t i
+ 
+-        if self.__allocated >= 8:
++        if self._allocated >= 8:
+             fmpz_clear(self.q)
+             fmpz_poly_clear(self.modulus)
+             fmpz_poly_clear(self.powhelper_oneunit)
+@@ -427,9 +427,9 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         x = R.gen()
+         cdef Polynomial_integer_dense_flint ans = (<Polynomial_integer_dense_flint?>x)._new()
+         if _n is None:
+-            fmpz_poly_set(ans.__poly, self.modulus)
++            fmpz_poly_set(ans._poly, self.modulus)
+         else:
+-            fmpz_poly_set(ans.__poly, self.get_modulus(_n)[0])
++            fmpz_poly_set(ans._poly, self.get_modulus(_n)[0])
+         return ans
+ 
+     cdef _new_fmpz_poly(self, fmpz_poly_t value, var='x'):
+@@ -440,7 +440,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         R = ZZ[var]
+         x = R.gen()
+         cdef Polynomial_integer_dense_flint ans = (<Polynomial_integer_dense_flint?>x)._new()
+-        fmpz_poly_set(ans.__poly, value)
++        fmpz_poly_set(ans._poly, value)
+         return ans
+ 
+ cdef class PowComputer_flint_unram(PowComputer_flint_1step):
+@@ -501,7 +501,7 @@ cdef class PowComputer_flint_unram(PowComputer_flint_1step):
+         mpz_init(self.mpz_matmod)
+         sig_off()
+ 
+-        self.__allocated = 16
++        self._allocated = 16
+ 
+     def __dealloc__(self):
+         """
+@@ -515,7 +515,7 @@ cdef class PowComputer_flint_unram(PowComputer_flint_1step):
+             sage: del A
+ 
+         """
+-        if self.__allocated >= 16:
++        if self._allocated >= 16:
+             fmpz_clear(self.fmpz_ccmp)
+             fmpz_clear(self.fmpz_cval)
+             fmpz_clear(self.fmpz_cinv)
+diff --git a/src/sage/rings/padics/pow_computer_relative.pxd b/src/sage/rings/padics/pow_computer_relative.pxd
+index fc7d5b21f42..e0e5aa5600e 100644
+--- a/src/sage/rings/padics/pow_computer_relative.pxd
++++ b/src/sage/rings/padics/pow_computer_relative.pxd
+@@ -18,7 +18,7 @@ cdef class PowComputer_relative(PowComputer_class):
+     cdef Polynomial_generic_dense shift_rem
+     cdef Polynomial_generic_dense aliasing
+     # allow cached methods
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+     cdef unsigned long capdiv(self, unsigned long n)
+ 
+diff --git a/src/sage/rings/padics/pow_computer_relative.pyx b/src/sage/rings/padics/pow_computer_relative.pyx
+index 39051a681de..2253281bd35 100644
+--- a/src/sage/rings/padics/pow_computer_relative.pyx
++++ b/src/sage/rings/padics/pow_computer_relative.pyx
+@@ -69,7 +69,7 @@ cdef class PowComputer_relative(PowComputer_class):
+             sage: PC = PowComputer_relative_maker(3, 20, 20, 60, False, f, shift_seed, 'fixed-mod')
+ 
+         """
+-        self.__allocated = 4
++        self._allocated = 4
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly, shift_seed):
+         r"""
+diff --git a/src/sage/rings/polynomial/hilbert.pyx b/src/sage/rings/polynomial/hilbert.pyx
+index a1f70e0c983..d2abf325fd8 100644
+--- a/src/sage/rings/polynomial/hilbert.pyx
++++ b/src/sage/rings/polynomial/hilbert.pyx
+@@ -170,7 +170,7 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+     cdef int e
+     # First, the easiest cases:
+     if not D.Id: # The zero ideal
+-        fmpz_poly_set_coeff_si(fhs.__poly, 0, 1) # = PR(1)
++        fmpz_poly_set_coeff_si(fhs._poly, 0, 1) # = PR(1)
+         return True
+     cdef ETuple m = <ETuple>PyList_GET_ITEM(D.Id, len(D.Id)-1)
+     if m._nonzero == 0: # The one ideal
+@@ -183,18 +183,18 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+     if m._nonzero == 1 and m._data[1] == 1:
+         fmpz_poly_init(poly_tmp)
+         fmpz_poly_set_coeff_si(poly_tmp, 0, 1)
+-        fmpz_poly_set_coeff_si(fhs.__poly, 0, 1) # = PR(1)
++        fmpz_poly_set_coeff_si(fhs._poly, 0, 1) # = PR(1)
+         if w is None:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).unweighted_degree()
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         else:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).weighted_degree(w)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         fmpz_poly_clear(poly_tmp)
+         return True # PR.prod([(1-t**degree(m,w)) for m in D.Id])
+@@ -210,18 +210,18 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+         # The ideal is generated by some powers of single variables, i.e., it splits.
+         fmpz_poly_init(poly_tmp)
+         fmpz_poly_set_coeff_si(poly_tmp, 0, 1)
+-        fmpz_poly_set_coeff_si(fhs.__poly, 0, 1) # = PR(1)
++        fmpz_poly_set_coeff_si(fhs._poly, 0, 1) # = PR(1)
+         if w is None:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).unweighted_degree()
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         else:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).weighted_degree(w)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         fmpz_poly_clear(poly_tmp)
+         return True # PR.prod([(1-t**degree(m,w)) for m in D.Id])
+@@ -278,8 +278,8 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+                     fmpz_poly_mul(SecondSummand, SecondSummand, poly_tmp)
+                     fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         fmpz_poly_clear(poly_tmp)
+-        fmpz_poly_add(fhs.__poly, fhs.__poly, FirstSummand)
+-        fmpz_poly_add(fhs.__poly, fhs.__poly, SecondSummand)
++        fmpz_poly_add(fhs._poly, fhs._poly, FirstSummand)
++        fmpz_poly_add(fhs._poly, fhs._poly, SecondSummand)
+         fmpz_poly_clear(FirstSummand)
+         fmpz_poly_clear(SecondSummand)
+         return True
+@@ -532,11 +532,11 @@ def first_hilbert_series(I, grading=None, return_grading=False):
+                 if AN.Back.Right is None:
+                     AN = AN.Back
+                     #~ fhs *= AN.LMult
+-                    fmpz_poly_mul(fhs.__poly, fhs.__poly, AN.LMult)
++                    fmpz_poly_mul(fhs._poly, fhs._poly, AN.LMult)
+                     got_result = True
+                 else:
+-                    fmpz_poly_set(AN.Back.LeftFHS, fhs.__poly)
+-                    fmpz_poly_set_si(fhs.__poly, 0)
++                    fmpz_poly_set(AN.Back.LeftFHS, fhs._poly)
++                    fmpz_poly_set_si(fhs._poly, 0)
+                     AN = AN.Back.Right
+                     AN.Back.Left = None
+                     got_result = HilbertBaseCase(fhs, AN, w)
+@@ -545,8 +545,8 @@ def first_hilbert_series(I, grading=None, return_grading=False):
+                 AN.Right = None
+                 #~ fhs = AN.LMult*AN.LeftFHS + AN.RMult*fhs
+                 fmpz_poly_mul(AN.LMult, AN.LMult, AN.LeftFHS)
+-                fmpz_poly_mul(AN.RMult, AN.RMult, fhs.__poly)
+-                fmpz_poly_add(fhs.__poly, AN.LMult, AN.RMult)
++                fmpz_poly_mul(AN.RMult, AN.RMult, fhs._poly)
++                fmpz_poly_add(fhs._poly, AN.LMult, AN.RMult)
+                 got_result = True
+ 
+ def hilbert_poincare_series(I, grading=None):
+diff --git a/src/sage/rings/polynomial/laurent_polynomial.pxd b/src/sage/rings/polynomial/laurent_polynomial.pxd
+index 3648d6d1ed1..8e9107aeb47 100644
+--- a/src/sage/rings/polynomial/laurent_polynomial.pxd
++++ b/src/sage/rings/polynomial/laurent_polynomial.pxd
+@@ -12,6 +12,6 @@ cdef class LaurentPolynomial(CommutativeAlgebraElement):
+ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+     cdef ModuleElement __u
+     cdef long __n
+-    cpdef __normalize(self)
++    cpdef _normalize(self)
+     cpdef _unsafe_mutate(self, i, value)
+ 
+diff --git a/src/sage/rings/polynomial/laurent_polynomial.pyx b/src/sage/rings/polynomial/laurent_polynomial.pyx
+index 4be246c6688..cd79996eed7 100644
+--- a/src/sage/rings/polynomial/laurent_polynomial.pyx
++++ b/src/sage/rings/polynomial/laurent_polynomial.pyx
+@@ -366,7 +366,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         # self is that t^n * u:
+         self.__u = f
+         self.__n = n
+-        self.__normalize()
++        self._normalize()
+ 
+     def __reduce__(self):
+         """
+@@ -531,7 +531,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+             u = u.map_coefficients(base_map)
+         return codomain(u(x) * x**self.__n)
+ 
+-    cpdef __normalize(self):
++    cpdef _normalize(self):
+         r"""
+         A Laurent series is a pair `(u(t), n)`, where either `u = 0`
+         (to some precision) or `u` is a unit. This pair corresponds to
+@@ -763,7 +763,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+             ret = <LaurentPolynomial_univariate> self._new_c()
+             ret.__u = f
+             ret.__n = self.__n
+-            ret.__normalize()
++            ret._normalize()
+             return ret
+ 
+         return self.__u[i - self.__n]
+@@ -919,7 +919,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+                 R = self._parent.base_ring()
+                 coeffs = [value] + [R.zero() for _ in range(1,-j)] + self.__u.list()
+                 self.__u = self.__u._parent(coeffs)
+-        self.__normalize()
++        self._normalize()
+ 
+     cpdef _add_(self, right_m):
+         """
+@@ -972,7 +972,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (f1 + f2)
+         ret.__n = m
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     cpdef _sub_(self, right_m):
+@@ -1012,7 +1012,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (f1 - f2)
+         ret.__n = m
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def degree(self):
+@@ -1063,7 +1063,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (self.__u * right.__u)
+         ret.__n = self.__n + right.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     cpdef _rmul_(self, Element c):
+@@ -1079,7 +1079,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self.__u._rmul_(c)
+         ret.__n = self.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     cpdef _lmul_(self, Element c):
+@@ -1095,7 +1095,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self.__u._lmul_(c)
+         ret.__n = self.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def is_monomial(self):
+@@ -1175,7 +1175,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (self.__u // right.__u)
+         ret.__n = self.__n - right.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def shift(self, k):
+@@ -1287,7 +1287,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+             if self.__u.is_unit():
+                 ret.__u = self.__u.inverse_of_unit()
+                 ret.__n = -self.__n
+-                ret.__normalize()
++                ret._normalize()
+                 return ret
+             # Enlarge the ring so we can divide by the coefficient
+             R = self._parent.base_ring().fraction_field()
+@@ -1362,7 +1362,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = self.__u.gcd(b.__u)
+         ret.__n = min(self.__n, b.__n)
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     @coerce_binop
+@@ -1408,11 +1408,11 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ql = <LaurentPolynomial_univariate> self._new_c()
+         ql.__u = <ModuleElement> q
+         ql.__n = self.__n - right.__n
+-        ql.__normalize()
++        ql._normalize()
+         qr = <LaurentPolynomial_univariate> self._new_c()
+         qr.__u = <ModuleElement> r
+         qr.__n = self.__n
+-        qr.__normalize()
++        qr._normalize()
+         return ql, qr
+ 
+     cpdef _richcmp_(self, right_r, int op):
+@@ -1519,7 +1519,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self.__u.truncate(n - self.__n)
+         ret.__n = self.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def variable_name(self):
+@@ -1777,7 +1777,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+                 ret = <LaurentPolynomial_univariate> self._new_c()
+                 ret.__u = <ModuleElement> self._parent._R(u)
+                 ret.__n = self.__n
+-                ret.__normalize()
++                ret._normalize()
+                 return ret
+             except AttributeError:
+                 raise ValueError('cannot differentiate with respect to {}'.format(var))
+@@ -1792,7 +1792,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self._parent._R(a)
+         ret.__n = self.__n - 1
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def integral(self):
+@@ -1857,7 +1857,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> u
+         ret.__n = n + 1
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def __call__(self, *x, **kwds):
+@@ -1919,14 +1919,14 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         u = <LaurentPolynomial_univariate> self._new_c()
+         u.__u = pf.unit()
+         u.__n = self.__n
+-        u.__normalize()
++        u._normalize()
+ 
+         f = []
+         for t in pf:
+             d = <LaurentPolynomial_univariate> self._new_c()
+             d.__u = t[0]
+             d.__n = 0
+-            d.__normalize()
++            d._normalize()
+             if d.is_unit():
+                 u *= d ** t[1]
+             else:
+diff --git a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx
+index d796b7f8169..83c79c39843 100644
+--- a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx
++++ b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx
+@@ -375,7 +375,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+             ...
+             NotImplementedError: polynomials in -1 variables are not supported in Singular
+         """
+-        self.__ngens = n
++        self._ngens = n
+         self._ring = singular_ring_new(base_ring, n, names, order)
+         self._zero_element = new_MP(self, NULL)
+         cdef MPolynomial_libsingular one = new_MP(self, p_ISet(1, self._ring))
+@@ -1019,7 +1019,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+             Multivariate Polynomial Ring in x, y over Rational Field
+         """
+         varstr = ", ".join(char_to_str(rRingVar(i,self._ring))
+-                           for i in range(self.__ngens))
++                           for i in range(self._ngens))
+         return "Multivariate Polynomial Ring in %s over %s" % (varstr, self.base_ring())
+ 
+     def ngens(self):
+@@ -1037,7 +1037,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+             sage: P.ngens()                                                             # needs sage.rings.finite_rings
+             1000
+         """
+-        return int(self.__ngens)
++        return int(self._ngens)
+ 
+     def gen(self, int n=0):
+         """
+@@ -1065,7 +1065,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+         cdef poly *_p
+         cdef ring *_ring = self._ring
+ 
+-        if n < 0 or n >= self.__ngens:
++        if n < 0 or n >= self._ngens:
+             raise ValueError("Generator not defined.")
+ 
+         rChangeCurrRing(_ring)
+@@ -1494,7 +1494,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+         return unpickle_MPolynomialRing_libsingular, \
+             (self.base_ring(), self.variable_names(), self.term_order())
+ 
+-    def __temporarily_change_names(self, names, latex_names):
++    def _temporarily_change_names(self, names, latex_names):
+         """
+         This is used by the variable names context manager.
+ 
+diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd b/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd
+index fc81cf6d298..eb6f8b70917 100644
+--- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd
++++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd
+@@ -2,8 +2,8 @@ cimport sage.rings.ring
+ from sage.structure.parent cimport Parent
+ 
+ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+-    cdef object __ngens
+-    cdef object __term_order
++    cdef object _ngens
++    cdef object _term_order
+     cdef public object _has_singular
+     cdef public object _magma_gens
+     cdef public dict _magma_cache
+diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx
+index 1d3fbc60944..c8f66508cc2 100644
+--- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx
++++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx
+@@ -80,8 +80,8 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+             raise ValueError("Multivariate Polynomial Rings must "
+                              "have more than 0 variables.")
+         order = TermOrder(order, n)
+-        self.__ngens = n
+-        self.__term_order = order
++        self._ngens = n
++        self._term_order = order
+         self._has_singular = False  # cannot convert to Singular by default
+         self._magma_cache = {}
+         # Ring.__init__ already does assign the names.
+@@ -639,12 +639,12 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         lft = <MPolynomialRing_base>left
+         other = <MPolynomialRing_base>right
+ 
+-        lx = (lft.base_ring(), lft.__ngens,
++        lx = (lft.base_ring(), lft._ngens,
+               lft.variable_names(),
+-              lft.__term_order)
+-        rx = (other.base_ring(), other.__ngens,
++              lft._term_order)
++        rx = (other.base_ring(), other._ngens,
+               other.variable_names(),
+-              other.__term_order)
++              other._term_order)
+         return richcmp(lx, rx, op)
+ 
+     def _repr_(self):
+@@ -849,7 +849,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         return False
+ 
+     def term_order(self):
+-        return self.__term_order
++        return self._term_order
+ 
+     def characteristic(self):
+         """
+@@ -867,7 +867,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         return self.base_ring().characteristic()
+ 
+     def gen(self, n=0):
+-        if n < 0 or n >= self.__ngens:
++        if n < 0 or n >= self._ngens:
+             raise ValueError("Generator not defined.")
+         return self._gens[int(n)]
+ 
+@@ -927,7 +927,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         return self.base_ring().krull_dimension() + self.ngens()
+ 
+     def ngens(self):
+-        return self.__ngens
++        return self._ngens
+ 
+     def _monomial_order_function(self):
+         raise NotImplementedError
+diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pxd b/src/sage/rings/polynomial/ore_polynomial_element.pxd
+index 3a3fe0a0d54..aa36112ab90 100644
+--- a/src/sage/rings/polynomial/ore_polynomial_element.pxd
++++ b/src/sage/rings/polynomial/ore_polynomial_element.pxd
+@@ -33,7 +33,7 @@ cdef void lmul_gen(list A, Morphism m, d)
+ cdef class OrePolynomial_generic_dense(OrePolynomial):
+     cdef list _coeffs
+ 
+-    cdef void __normalize(self)
++    cdef void _normalize(self)
+     cpdef _add_(self, other)
+     cdef list _mul_list(self, list A)
+     cpdef _mul_(self, other)
+diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pyx b/src/sage/rings/polynomial/ore_polynomial_element.pyx
+index d67c63b6be8..be154ba8b1a 100644
+--- a/src/sage/rings/polynomial/ore_polynomial_element.pyx
++++ b/src/sage/rings/polynomial/ore_polynomial_element.pyx
+@@ -2269,7 +2269,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+         if isinstance(x, list):
+             if check:
+                 self._coeffs = [R(t) for t in x]
+-                self.__normalize()
++                self._normalize()
+             else:
+                 self._coeffs = x
+             return
+@@ -2288,7 +2288,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+             else:
+                 self._coeffs = [R(a, **kwds) for a in x.list()]
+                 if check:
+-                    self.__normalize()
++                    self._normalize()
+                 return
+ 
+         elif isinstance(x, int) and x == 0:
+@@ -2302,7 +2302,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+             x = [x]
+         if check:
+             self._coeffs = [R(z, **kwds) for z in x]
+-            self.__normalize()
++            self._normalize()
+         else:
+             self._coeffs = x
+ 
+@@ -2377,10 +2377,10 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+         f._parent = P
+         f._coeffs = coeffs
+         if check:
+-            f.__normalize()
++            f._normalize()
+         return f
+ 
+-    cdef void __normalize(self):
++    cdef void _normalize(self):
+         r"""
+         Remove higher order `0`-coefficients from the representation of ``self``.
+ 
+diff --git a/src/sage/rings/polynomial/pbori/pbori.pyx b/src/sage/rings/polynomial/pbori/pbori.pyx
+index 07cc696477a..314196faa14 100644
+--- a/src/sage/rings/polynomial/pbori/pbori.pyx
++++ b/src/sage/rings/polynomial/pbori/pbori.pyx
+@@ -547,7 +547,7 @@ cdef class BooleanPolynomialRing(BooleanPolynomialRing_base):
+         """
+         return tuple(new_BP_from_PBVar(self,
+                                        self._pbring.variable(self.pbind[i]))
+-                     for i in range(self.__ngens))
++                     for i in range(self._ngens))
+ 
+     def change_ring(self, base_ring=None, names=None, order=None):
+         """
+diff --git a/src/sage/rings/polynomial/plural.pxd b/src/sage/rings/polynomial/plural.pxd
+index 41db2a144e7..d3a46f6aa0d 100644
+--- a/src/sage/rings/polynomial/plural.pxd
++++ b/src/sage/rings/polynomial/plural.pxd
+@@ -13,10 +13,10 @@ cdef extern from *:
+     ctypedef long Py_hash_t
+ 
+ cdef class NCPolynomialRing_plural(Ring):
+-    cdef object __ngens
++    cdef object _ngens
+     cdef object _c
+     cdef object _d
+-    cdef object __term_order
++    cdef object _term_order
+     cdef public object _has_singular
+     cdef public object _magma_gens, _magma_cache
+ 
+diff --git a/src/sage/rings/polynomial/plural.pyx b/src/sage/rings/polynomial/plural.pyx
+index a647d68e08d..bc432611c89 100644
+--- a/src/sage/rings/polynomial/plural.pyx
++++ b/src/sage/rings/polynomial/plural.pyx
+@@ -336,8 +336,8 @@ cdef class NCPolynomialRing_plural(Ring):
+         self._ring = singular_ring_reference(rw._ring)
+         self._ring.ShortOut = 0
+ 
+-        self.__ngens = n
+-        self.__term_order = order
++        self._ngens = n
++        self._term_order = order
+ 
+         Ring.__init__(self, base_ring, names, category=category)
+         self._populate_coercion_lists_()
+@@ -673,7 +673,7 @@ cdef class NCPolynomialRing_plural(Ring):
+             sage: P.term_order()
+             Degree reverse lexicographic term order
+         """
+-        return self.__term_order
++        return self._term_order
+ 
+     def is_commutative(self):
+         """
+@@ -727,7 +727,7 @@ cdef class NCPolynomialRing_plural(Ring):
+         from sage.repl.rich_output.backend_base import BackendBase
+         from sage.repl.display.pretty_print import SagePrettyPrinter
+         varstr = ", ".join(char_to_str(rRingVar(i, self._ring))
+-                           for i in range(self.__ngens))
++                           for i in range(self._ngens))
+         backend = BackendBase()
+         relations = backend._apply_pretty_printer(SagePrettyPrinter,
+                                                   self.relations())
+@@ -830,7 +830,7 @@ cdef class NCPolynomialRing_plural(Ring):
+             sage: P.ngens()
+             3
+         """
+-        return int(self.__ngens)
++        return int(self._ngens)
+ 
+     def gen(self, int n=0):
+         """
+@@ -857,7 +857,7 @@ cdef class NCPolynomialRing_plural(Ring):
+         cdef poly *_p
+         cdef ring *_ring = self._ring
+ 
+-        if n < 0 or n >= self.__ngens:
++        if n < 0 or n >= self._ngens:
+             raise ValueError("Generator not defined.")
+ 
+         rChangeCurrRing(_ring)
+@@ -2352,7 +2352,7 @@ cdef class NCPolynomial_plural(RingElement):
+             except TypeError:
+                 x = (x,)
+ 
+-        if len(x) != (<NCPolynomialRing_plural>self._parent).__ngens:
++        if len(x) != (<NCPolynomialRing_plural>self._parent)._ngens:
+             raise TypeError("x must have length self.ngens()")
+ 
+         m = p_ISet(1,r)
+@@ -2890,8 +2890,8 @@ cpdef MPolynomialRing_libsingular new_CRing(RingWrap rw, base_ring):
+ 
+     self._ring.ShortOut = 0
+ 
+-    self.__ngens = rw.ngens()
+-    self.__term_order =  TermOrder(rw.ordering_string(), force=True)
++    self._ngens = rw.ngens()
++    self._term_order =  TermOrder(rw.ordering_string(), force=True)
+ 
+     ParentWithGens.__init__(self, base_ring, tuple(rw.var_names()),
+                             normalize=False)
+@@ -2962,8 +2962,8 @@ cpdef NCPolynomialRing_plural new_NRing(RingWrap rw, base_ring):
+ 
+     self._ring.ShortOut = 0
+ 
+-    self.__ngens = rw.ngens()
+-    self.__term_order =  TermOrder(rw.ordering_string(), force=True)
++    self._ngens = rw.ngens()
++    self._term_order =  TermOrder(rw.ordering_string(), force=True)
+ 
+     ParentWithGens.__init__(self, base_ring, rw.var_names())
+ #    self._populate_coercion_lists_()  # ???
+diff --git a/src/sage/rings/polynomial/polynomial_complex_arb.pxd b/src/sage/rings/polynomial/polynomial_complex_arb.pxd
+index aa4e2a1c0dc..e54d85e961b 100644
+--- a/src/sage/rings/polynomial/polynomial_complex_arb.pxd
++++ b/src/sage/rings/polynomial/polynomial_complex_arb.pxd
+@@ -2,5 +2,5 @@ from sage.libs.arb.acb_poly cimport *
+ from sage.rings.polynomial.polynomial_element cimport Polynomial
+ 
+ cdef class Polynomial_complex_arb(Polynomial):
+-    cdef acb_poly_struct[1] __poly # https://github.com/cython/cython/issues/1984
++    cdef acb_poly_struct[1] _poly # https://github.com/cython/cython/issues/1984
+     cdef Polynomial_complex_arb _new(self)
+diff --git a/src/sage/rings/polynomial/polynomial_complex_arb.pyx b/src/sage/rings/polynomial/polynomial_complex_arb.pyx
+index e51268b4b54..57c1a52ede4 100644
+--- a/src/sage/rings/polynomial/polynomial_complex_arb.pyx
++++ b/src/sage/rings/polynomial/polynomial_complex_arb.pyx
+@@ -75,7 +75,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: ComplexBallField(2)['y']()
+             0
+         """
+-        acb_poly_init(self.__poly)
++        acb_poly_init(self._poly)
+ 
+     def __dealloc__(self):
+         r"""
+@@ -84,7 +84,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: pol = CBF['x']()
+             sage: del pol
+         """
+-        acb_poly_clear(self.__poly)
++        acb_poly_clear(self._poly)
+ 
+     cdef Polynomial_complex_arb _new(self):
+         r"""
+@@ -140,49 +140,49 @@ cdef class Polynomial_complex_arb(Polynomial):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+ 
+         if is_gen:
+-            acb_poly_set_coeff_si(self.__poly, 1, 1)
++            acb_poly_set_coeff_si(self._poly, 1, 1)
+         elif x is None:
+-            acb_poly_zero(self.__poly)
++            acb_poly_zero(self._poly)
+         elif isinstance(x, Polynomial_complex_arb):
+-            acb_poly_set(self.__poly, (<Polynomial_complex_arb> x).__poly)
++            acb_poly_set(self._poly, (<Polynomial_complex_arb> x)._poly)
+         elif isinstance(x, ComplexBall):
+-            acb_poly_set_coeff_acb(self.__poly, 0, (<ComplexBall> x).value)
++            acb_poly_set_coeff_acb(self._poly, 0, (<ComplexBall> x).value)
+         else:
+             Coeff = parent.base_ring()
+             if isinstance(x, list):
+                 lst = <list> x
+                 length = len(lst)
+-                sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                 for i in range(length):
+                     ball = Coeff(lst[i])
+-                    acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                    acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             elif isinstance(x, tuple):
+                 tpl = <tuple> x
+                 length = len(tpl)
+-                sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                 for i in range(length):
+                     ball = Coeff(tpl[i])
+-                    acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                    acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             elif isinstance(x, Polynomial):
+                 pol = <Polynomial> x
+                 length = pol.degree() + 1
+-                sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                 for i in range(length):
+                     ball = Coeff(pol.get_unsafe(i))
+-                    acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                    acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             elif isinstance(x, dict):
+                 dct = <dict> x
+                 if len(dct) == 0:
+-                    acb_poly_zero(self.__poly)
++                    acb_poly_zero(self._poly)
+                 else:
+                     length = max(int(i) for i in dct) + 1
+-                    sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                    sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                     for i, c in dct.iteritems():
+                         ball = Coeff(c)
+-                        acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                        acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             else:
+                 ball = Coeff(x)
+-                acb_poly_set_coeff_acb(self.__poly, 0, ball.value)
++                acb_poly_set_coeff_acb(self._poly, 0, ball.value)
+ 
+     def __reduce__(self):
+         r"""
+@@ -219,12 +219,12 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: Pol([1, 0, 0, 0]).degree()
+             0
+         """
+-        return smallInteger(acb_poly_degree(self.__poly))
++        return smallInteger(acb_poly_degree(self._poly))
+ 
+     cdef get_unsafe(self, Py_ssize_t n):
+         cdef ComplexBall res = ComplexBall.__new__(ComplexBall)
+         res._parent = self._parent._base
+-        acb_poly_get_coeff_acb(res.value, self.__poly, n)
++        acb_poly_get_coeff_acb(res.value, self._poly, n)
+         return res
+ 
+     cpdef list list(self, bint copy=True):
+@@ -241,7 +241,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: Pol([0, 1, RBF(0, rad=.1), 0]).list()
+             [0, 1.000000000000000, [+/- 0.101]]
+         """
+-        cdef unsigned long length = acb_poly_length(self.__poly)
++        cdef unsigned long length = acb_poly_length(self._poly)
+         return [self.get_unsafe(n) for n in range(length)]
+ 
+     def __bool__(self):
+@@ -257,7 +257,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: bool(z)
+             True
+         """
+-        return acb_poly_length(self.__poly)
++        return acb_poly_length(self._poly)
+ 
+     # Ring and Euclidean arithmetic
+ 
+@@ -274,9 +274,9 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+         acb_poly_add(
+-                res.__poly,
+-                self.__poly,
+-                (<Polynomial_complex_arb> other).__poly,
++                res._poly,
++                self._poly,
++                (<Polynomial_complex_arb> other)._poly,
+                 prec(self))
+         sig_off()
+         return res
+@@ -293,7 +293,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         """
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_neg(res.__poly, self.__poly)
++        acb_poly_neg(res._poly, self._poly)
+         sig_off()
+         return res
+ 
+@@ -310,9 +310,9 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+         acb_poly_sub(
+-                res.__poly,
+-                self.__poly,
+-                (<Polynomial_complex_arb> other).__poly,
++                res._poly,
++                self._poly,
++                (<Polynomial_complex_arb> other)._poly,
+                 prec(self))
+         sig_off()
+         return res
+@@ -331,9 +331,9 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+         acb_poly_mul(
+-                res.__poly,
+-                self.__poly,
+-                (<Polynomial_complex_arb> other).__poly,
++                res._poly,
++                self._poly,
++                (<Polynomial_complex_arb> other)._poly,
+                 prec(self))
+         sig_off()
+         return res
+@@ -354,7 +354,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         """
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_scalar_mul(res.__poly, self.__poly, (<ComplexBall> a).value, prec(self))
++        acb_poly_scalar_mul(res._poly, self._poly, (<ComplexBall> a).value, prec(self))
+         sig_off()
+         return res
+ 
+@@ -409,8 +409,8 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb quo = self._new()
+         cdef Polynomial_complex_arb rem = self._new()
+         sig_on()
+-        cdef bint success = acb_poly_divrem(quo.__poly, rem.__poly, self.__poly,
+-                div.__poly, prec(self))
++        cdef bint success = acb_poly_divrem(quo._poly, rem._poly, self._poly,
++                div._poly, prec(self))
+         sig_off()
+         if success:
+             return quo, rem
+@@ -445,15 +445,15 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_set(res.__poly, self.__poly)
+-        acb_poly_truncate(res.__poly, n)
++        acb_poly_set(res._poly, self._poly)
++        acb_poly_truncate(res._poly, n)
+         sig_off()
+         return res
+ 
+     cdef _inplace_truncate(self, long n):
+         if n < 0:
+             n = 0
+-        acb_poly_truncate(self.__poly, n)
++        acb_poly_truncate(self._poly, n)
+         return self
+ 
+     def __lshift__(val, n):
+@@ -485,7 +485,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb self = (<Polynomial_complex_arb> val)
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_shift_left(res.__poly, self.__poly, n)
++        acb_poly_shift_left(res._poly, self._poly, n)
+         sig_off()
+         return res
+ 
+@@ -518,7 +518,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb self = (<Polynomial_complex_arb> val)
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_shift_right(res.__poly, self.__poly, n)
++        acb_poly_shift_right(res._poly, self._poly, n)
+         sig_off()
+         return res
+ 
+@@ -548,7 +548,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_mullow(res.__poly, self.__poly, my_other.__poly, n, prec(self))
++        acb_poly_mullow(res._poly, self._poly, my_other._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -576,7 +576,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_inv_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_inv_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -612,7 +612,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_pow_ui_trunc_binexp(res.__poly, self.__poly, expo, n, prec(self))
++        acb_poly_pow_ui_trunc_binexp(res._poly, self._poly, expo, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -648,7 +648,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_log_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_log_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -672,7 +672,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_exp_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_exp_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -697,7 +697,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_sqrt_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_sqrt_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -716,7 +716,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_gamma_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_gamma_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -735,7 +735,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_lgamma_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_lgamma_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -754,7 +754,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_rgamma_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_rgamma_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -784,7 +784,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_lambertw_series(res.__poly, self.__poly, _branch, 0, n, prec(self))
++        acb_poly_lambertw_series(res._poly, self._poly, _branch, 0, n, prec(self))
+         sig_off()
+         fmpz_clear(_branch)
+         return res
+@@ -814,7 +814,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef ComplexBall _a = <ComplexBall> (self._parent._base.coerce(a))
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_zeta_series(res.__poly, self.__poly, _a.value, deflate, n, prec(self))
++        acb_poly_zeta_series(res._poly, self._poly, _a.value, deflate, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -846,24 +846,24 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         cdef acb_poly_t self_ts, other_ts
+         cdef acb_ptr cc
+-        if acb_poly_length(other1.__poly) > 0:
+-            cc = acb_poly_get_coeff_ptr(other1.__poly, 0)
++        if acb_poly_length(other1._poly) > 0:
++            cc = acb_poly_get_coeff_ptr(other1._poly, 0)
+             if not acb_is_zero(cc):
+                 sig_on()
+                 try:
+                     acb_poly_init(self_ts)
+                     acb_poly_init(other_ts)
+-                    acb_poly_taylor_shift(self_ts, self.__poly, cc, prec(self))
+-                    acb_poly_set(other_ts, other1.__poly)
++                    acb_poly_taylor_shift(self_ts, self._poly, cc, prec(self))
++                    acb_poly_set(other_ts, other1._poly)
+                     acb_zero(acb_poly_get_coeff_ptr(other_ts, 0))
+-                    acb_poly_compose_series(res.__poly, self_ts, other_ts, n, prec(self))
++                    acb_poly_compose_series(res._poly, self_ts, other_ts, n, prec(self))
+                 finally:
+                     acb_poly_clear(other_ts)
+                     acb_poly_clear(self_ts)
+                     sig_off()
+                 return res
+         sig_on()
+-        acb_poly_compose_series(res.__poly, self.__poly, other1.__poly, n, prec(self))
++        acb_poly_compose_series(res._poly, self._poly, other1._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -895,12 +895,12 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         if n < 0:
+             n = 0
+-        if not acb_is_zero(acb_poly_get_coeff_ptr(self.__poly, 0)):
++        if not acb_is_zero(acb_poly_get_coeff_ptr(self._poly, 0)):
+             raise ValueError("the constant coefficient must be zero")
+-        if acb_contains_zero(acb_poly_get_coeff_ptr(self.__poly, 1)):
++        if acb_contains_zero(acb_poly_get_coeff_ptr(self._poly, 1)):
+             raise ValueError("the linear term must be nonzero")
+         sig_on()
+-        acb_poly_revert_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_revert_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -938,15 +938,15 @@ cdef class Polynomial_complex_arb(Polynomial):
+                 ball = ComplexBall.__new__(ComplexBall)
+                 ball._parent = self._parent._base
+                 sig_on()
+-                acb_poly_evaluate(ball.value, self.__poly,
++                acb_poly_evaluate(ball.value, self._poly,
+                         (<ComplexBall> point).value, prec(self))
+                 sig_off()
+                 return ball
+             elif isinstance(point, Polynomial_complex_arb):
+                 poly = (<Polynomial_complex_arb> point)._new()
+                 sig_on()
+-                acb_poly_compose(poly.__poly, self.__poly,
+-                        (<Polynomial_complex_arb> point).__poly, prec(self))
++                acb_poly_compose(poly._poly, self._poly,
++                        (<Polynomial_complex_arb> point)._poly, prec(self))
+                 sig_off()
+                 return poly
+             # TODO: perhaps add more special cases, e.g. for real ball,
+diff --git a/src/sage/rings/polynomial/polynomial_element.pxd b/src/sage/rings/polynomial/polynomial_element.pxd
+index 083f506b222..5dcbf4597d0 100644
+--- a/src/sage/rings/polynomial/polynomial_element.pxd
++++ b/src/sage/rings/polynomial/polynomial_element.pxd
+@@ -45,12 +45,12 @@ cdef class Polynomial(CommutativePolynomial):
+     cpdef _mul_(self, right)
+     cpdef _floordiv_(self, right)
+ 
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+ cdef class Polynomial_generic_dense(Polynomial):
+     cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P)
+-    cdef list __coeffs
+-    cdef int __normalize(self) except -1
++    cdef list _coeffs
++    cdef int _normalize(self) except -1
+     cpdef list list(self, bint copy=*)
+ 
+ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+diff --git a/src/sage/rings/polynomial/polynomial_element.pyx b/src/sage/rings/polynomial/polynomial_element.pyx
+index 4d4b9dd10f5..d1c802835ae 100644
+--- a/src/sage/rings/polynomial/polynomial_element.pyx
++++ b/src/sage/rings/polynomial/polynomial_element.pyx
+@@ -9800,7 +9800,7 @@ cdef class Polynomial(CommutativePolynomial):
+             0
+         """
+         # __getitem__ already returns a polynomial!!
+-        # We must not have check=False, since 0 must not have __coeffs = [0].
++        # We must not have check=False, since 0 must not have _coeffs = [0].
+         return <Polynomial>self._parent(self[:n])#, check=False)
+ 
+     cdef _inplace_truncate(self, long prec):
+@@ -11541,16 +11541,16 @@ cdef class Polynomial_generic_dense(Polynomial):
+     def __init__(self, parent, x=None, int check=1, is_gen=False, int construct=0, **kwds):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+         if x is None:
+-            self.__coeffs = []
++            self._coeffs = []
+             return
+ 
+         R = parent.base_ring()
+         if isinstance(x, (list, tuple)):
+             if check:
+-                self.__coeffs = [R(t) for t in x]
+-                self.__normalize()
++                self._coeffs = [R(t) for t in x]
++                self._normalize()
+             else:
+-                self.__coeffs = x
++                self._coeffs = x
+             return
+ 
+         if sage.rings.fraction_field_element.is_FractionFieldElement(x):
+@@ -11565,19 +11565,19 @@ cdef class Polynomial_generic_dense(Polynomial):
+             elif R.has_coerce_map_from((<Element>x)._parent):# is R or (<Element>x)._parent == R:
+                 try:
+                     if x.is_zero():
+-                        self.__coeffs = []
++                        self._coeffs = []
+                         return
+                 except (AttributeError, TypeError):
+                     pass
+                 x = [x]
+             else:
+-                self.__coeffs = [R(a, **kwds) for a in x.list(copy=False)]
++                self._coeffs = [R(a, **kwds) for a in x.list(copy=False)]
+                 if check:
+-                    self.__normalize()
++                    self._normalize()
+                 return
+ 
+         elif isinstance(x, int) and x == 0:
+-            self.__coeffs = []
++            self._coeffs = []
+             return
+ 
+         elif isinstance(x, dict):
+@@ -11593,16 +11593,16 @@ cdef class Polynomial_generic_dense(Polynomial):
+ #            else:
+ #                x = []    # zero polynomial
+         if check:
+-            self.__coeffs = [R(z, **kwds) for z in x]
+-            self.__normalize()
++            self._coeffs = [R(z, **kwds) for z in x]
++            self._normalize()
+         else:
+-            self.__coeffs = x
++            self._coeffs = x
+ 
+     cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P):
+         cdef type t = type(self)
+         cdef Polynomial_generic_dense f = <Polynomial_generic_dense>t.__new__(t)
+         f._parent = P
+-        f.__coeffs = coeffs
++        f._coeffs = coeffs
+         return f
+ 
+     cpdef Polynomial _new_constant_poly(self, a, Parent P):
+@@ -11644,10 +11644,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: type(f)
+             <class 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense'>
+         """
+-        return make_generic_polynomial, (self._parent, self.__coeffs)
++        return make_generic_polynomial, (self._parent, self._coeffs)
+ 
+     def __bool__(self):
+-        return bool(self.__coeffs)
++        return bool(self._coeffs)
+ 
+     cpdef bint is_term(self) except -1:
+         """
+@@ -11667,10 +11667,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: (1 + 3*x^5).is_term()
+             False
+         """
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return False
+ 
+-        for c in self.__coeffs[:-1]:
++        for c in self._coeffs[:-1]:
+             if c:
+                 return False
+         return True
+@@ -11682,9 +11682,9 @@ cdef class Polynomial_generic_dense(Polynomial):
+         Return the product ``self * term``, where ``term`` is a polynomial
+         with a single term.
+         """
+-        cdef Py_ssize_t d = len( (<Polynomial_generic_dense> term).__coeffs ) - 1
++        cdef Py_ssize_t d = len( (<Polynomial_generic_dense> term)._coeffs ) - 1
+         cdef Py_ssize_t i
+-        cdef list x = self.__coeffs
++        cdef list x = self._coeffs
+         cdef Py_ssize_t ell = len(x)
+         c = term.get_unsafe(d)
+         cdef list v = [self.base_ring().zero()] * (d + ell)
+@@ -11697,10 +11697,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+         cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
+         #if not v[len(v)-1]:
+         # "normalize" checks this anyway...
+-        res.__normalize()
++        res._normalize()
+         return res
+ 
+-    cdef int __normalize(self) except -1:
++    cdef int _normalize(self) except -1:
+         """
+         TESTS:
+ 
+@@ -11718,7 +11718,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+             ...
+             NotImplementedError: cannot check whether number is non-zero
+         """
+-        cdef list x = self.__coeffs
++        cdef list x = self._coeffs
+         cdef Py_ssize_t n = len(x) - 1
+         while n >= 0 and not x[n]:
+             del x[n]
+@@ -11747,7 +11747,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: f[:3]
+             40.0*x^2 + 10.0*x + 1.0
+         """
+-        return self.__coeffs[n]
++        return self._coeffs[n]
+ 
+     def _unsafe_mutate(self, n, value):
+         """
+@@ -11770,17 +11770,17 @@ cdef class Polynomial_generic_dense(Polynomial):
+         """
+         n = int(n)
+         value = self.base_ring()(value)
+-        if n >= 0 and n < len(self.__coeffs):
+-            self.__coeffs[n] = value
+-            if n == len(self.__coeffs) and value == 0:
+-                self.__normalize()
++        if n >= 0 and n < len(self._coeffs):
++            self._coeffs[n] = value
++            if n == len(self._coeffs) and value == 0:
++                self._normalize()
+         elif n < 0:
+             raise IndexError("polynomial coefficient index must be nonnegative")
+         elif value != 0:
+             zero = self.base_ring().zero()
+-            for _ in range(len(self.__coeffs), n):
+-                self.__coeffs.append(zero)
+-            self.__coeffs.append(value)
++            for _ in range(len(self._coeffs), n):
++                self._coeffs.append(zero)
++            self._coeffs.append(value)
+ 
+     def __floordiv__(self, right):
+         """
+@@ -11822,8 +11822,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+             return (<Polynomial_generic_dense>self)._floordiv_(<Polynomial_generic_dense>right)
+         P = parent(self)
+         d = P.base_ring()(right)
+-        cdef Polynomial_generic_dense res = (<Polynomial_generic_dense>self)._new_c([c // d for c in (<Polynomial_generic_dense>self).__coeffs], P)
+-        res.__normalize()
++        cdef Polynomial_generic_dense res = (<Polynomial_generic_dense>self)._new_c([c // d for c in (<Polynomial_generic_dense>self)._coeffs], P)
++        res._normalize()
+         return res
+ 
+     cpdef _add_(self, right):
+@@ -11839,8 +11839,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+         """
+         cdef Polynomial_generic_dense res
+         cdef Py_ssize_t check=0, i, min
+-        x = (<Polynomial_generic_dense>self).__coeffs
+-        y = (<Polynomial_generic_dense>right).__coeffs
++        x = (<Polynomial_generic_dense>self)._coeffs
++        y = (<Polynomial_generic_dense>right)._coeffs
+         if len(x) > len(y):
+             min = len(y)
+             high = x[min:]
+@@ -11852,7 +11852,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+         cdef list low = [x[i] + y[i] for i from 0 <= i < min]
+         if len(x) == len(y):
+             res = self._new_c(low, self._parent)
+-            res.__normalize()
++            res._normalize()
+             return res
+         else:
+             return self._new_c(low + high, self._parent)
+@@ -11860,8 +11860,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+     cpdef _sub_(self, right):
+         cdef Polynomial_generic_dense res
+         cdef Py_ssize_t check=0, i, min
+-        x = (<Polynomial_generic_dense>self).__coeffs
+-        y = (<Polynomial_generic_dense>right).__coeffs
++        x = (<Polynomial_generic_dense>self)._coeffs
++        y = (<Polynomial_generic_dense>right)._coeffs
+         if len(x) > len(y):
+             min = len(y)
+             high = x[min:]
+@@ -11873,33 +11873,33 @@ cdef class Polynomial_generic_dense(Polynomial):
+         low = [x[i] - y[i] for i from 0 <= i < min]
+         if len(x) == len(y):
+             res = self._new_c(low, self._parent)
+-            res.__normalize()
++            res._normalize()
+             return res
+         else:
+             return self._new_c(low + high, self._parent)
+ 
+     cpdef _rmul_(self, Element c):
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return self
+-        if c._parent is not (<Element>self.__coeffs[0])._parent:
+-            c = (<Element>self.__coeffs[0])._parent.coerce(c)
+-        v = [c * a for a in self.__coeffs]
++        if c._parent is not (<Element>self._coeffs[0])._parent:
++            c = (<Element>self._coeffs[0])._parent.coerce(c)
++        v = [c * a for a in self._coeffs]
+         cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
+         #if not v[len(v)-1]:
+         # "normalize" checks this anyway...
+-        res.__normalize()
++        res._normalize()
+         return res
+ 
+     cpdef _lmul_(self, Element c):
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return self
+-        if c._parent is not (<Element>self.__coeffs[0])._parent:
+-            c = (<Element>self.__coeffs[0])._parent.coerce(c)
+-        v = [a * c for a in self.__coeffs]
++        if c._parent is not (<Element>self._coeffs[0])._parent:
++            c = (<Element>self._coeffs[0])._parent.coerce(c)
++        v = [a * c for a in self._coeffs]
+         cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
+         #if not v[len(v)-1]:
+         # "normalize" checks this anyway...
+-        res.__normalize()
++        res._normalize()
+         return res
+ 
+     cpdef constant_coefficient(self):
+@@ -11916,10 +11916,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: f.constant_coefficient()
+             t
+         """
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return self.base_ring().zero()
+         else:
+-            return self.__coeffs[0]
++            return self._coeffs[0]
+ 
+     cpdef list list(self, bint copy=True):
+         """
+@@ -11934,9 +11934,9 @@ cdef class Polynomial_generic_dense(Polynomial):
+             [1, 9, 12, 8]
+         """
+         if copy:
+-            return list(self.__coeffs)
++            return list(self._coeffs)
+         else:
+-            return self.__coeffs
++            return self._coeffs
+ 
+     def degree(self, gen=None):
+         """
+@@ -11955,7 +11955,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+             <class 'sage.rings.integer.Integer'>
+ 
+         """
+-        return smallInteger(len(self.__coeffs) - 1)
++        return smallInteger(len(self._coeffs) - 1)
+ 
+     def shift(self, Py_ssize_t n):
+         r"""
+@@ -11993,13 +11993,13 @@ cdef class Polynomial_generic_dense(Polynomial):
+             return self
+         if n > 0:
+             output = [self.base_ring().zero()] * n
+-            output.extend(self.__coeffs)
++            output.extend(self._coeffs)
+             return self._new_c(output, self._parent)
+         if n < 0:
+-            if n > len(self.__coeffs) - 1:
++            if n > len(self._coeffs) - 1:
+                 return self._parent([])
+             else:
+-                return self._new_c(self.__coeffs[-int(n):], self._parent)
++                return self._new_c(self._coeffs[-int(n):], self._parent)
+ 
+     @coerce_binop
+     def quo_rem(self, other):
+@@ -12073,8 +12073,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+             return self, self
+ 
+         R = self._parent.base_ring()
+-        cdef list x = list((<Polynomial_generic_dense>self).__coeffs) # make a copy
+-        cdef list y = (<Polynomial_generic_dense>other).__coeffs
++        cdef list x = list((<Polynomial_generic_dense>self)._coeffs) # make a copy
++        cdef list y = (<Polynomial_generic_dense>other)._coeffs
+         cdef Py_ssize_t m = len(x)  # deg(self)=m-1
+         cdef Py_ssize_t n = len(y)  # deg(other)=n-1
+         if m < n:
+@@ -12135,18 +12135,18 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: type(f)
+             <class 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense'>
+         """
+-        l = len(self.__coeffs)
++        l = len(self._coeffs)
+         if n > l:
+             n = l
+-        while n > 0 and not self.__coeffs[n-1]:
++        while n > 0 and not self._coeffs[n-1]:
+             n -= 1
+-        return self._new_c(self.__coeffs[:n], self._parent)
++        return self._new_c(self._coeffs[:n], self._parent)
+ 
+     cdef _inplace_truncate(self, long n):
+-        if n < len(self.__coeffs):
+-            while n > 0 and not self.__coeffs[n-1]:
++        if n < len(self._coeffs):
++            while n > 0 and not self._coeffs[n-1]:
+                 n -= 1
+-        self.__coeffs = self.__coeffs[:n]
++        self._coeffs = self._coeffs[:n]
+         return self
+ 
+ def make_generic_polynomial(parent, coeffs):
+@@ -12305,7 +12305,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+ 
+     - Xavier Caruso (2013-03)
+     """
+-    cdef int __normalize(self) except -1:
++    cdef int _normalize(self) except -1:
+         r"""
+         TESTS::
+ 
+@@ -12316,7 +12316,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+             sage: S([1, R(0, 20)])                                                      # needs sage.rings.padics
+             O(5^20)*x + 1 + O(5^20)
+         """
+-        cdef list x = self.__coeffs
++        cdef list x = self._coeffs
+         cdef Py_ssize_t n = len(x) - 1
+         cdef RingElement c
+         while n >= 0:
+@@ -12376,7 +12376,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+ 
+         - Xavier Caruso (2013-03)
+         """
+-        coeffs = self.__coeffs
++        coeffs = self._coeffs
+         d = len(coeffs) - 1
+         while d >= 0:
+             c = coeffs[d]
+@@ -12420,7 +12420,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+ 
+         - Xavier Caruso (2013-03)
+         """
+-        return len(self.__coeffs) - 1
++        return len(self._coeffs) - 1
+ 
+ 
+ cdef class ConstantPolynomialSection(Map):
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd
+index 03c5cebbf09..b1b593d6a26 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd
+@@ -5,7 +5,7 @@ from sage.rings.integer cimport Integer
+ from sage.structure.parent cimport Parent
+ 
+ cdef class Polynomial_integer_dense_flint(Polynomial):
+-    cdef fmpz_poly_t __poly
++    cdef fmpz_poly_t _poly
+ 
+     cdef Polynomial_integer_dense_flint _new(self)
+     cpdef _unsafe_mutate(self, long n, value)
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx
+index e201ac843ad..194eb9263b2 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx
+@@ -99,14 +99,14 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         r"""
+         This calls the underlying FLINT fmpz_poly constructor
+         """
+-        fmpz_poly_init(self.__poly)
++        fmpz_poly_init(self._poly)
+ 
+ 
+     def __dealloc__(self):
+         r"""
+         calls the underlying FLINT fmpz_poly destructor
+         """
+-        fmpz_poly_clear(self.__poly)
++        fmpz_poly_clear(self._poly)
+ 
+     cdef Polynomial_integer_dense_flint _new(self):
+         r"""
+@@ -139,7 +139,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         x._is_gen = 0
+         if not isinstance(a, Integer):
+             a = ZZ(a)
+-        fmpz_poly_set_coeff_mpz(x.__poly, 0, (<Integer>a).value)
++        fmpz_poly_set_coeff_mpz(x._poly, 0, (<Integer>a).value)
+         return x
+ 
+     def __init__(self, parent, x=None, check=True, is_gen=False,
+@@ -224,8 +224,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         if isinstance(x, Polynomial):
+             if x.parent() is self.parent():
+                 sig_on()
+-                fmpz_poly_set(self.__poly,
+-                              (<Polynomial_integer_dense_flint>x).__poly)
++                fmpz_poly_set(self._poly,
++                              (<Polynomial_integer_dense_flint>x)._poly)
+                 sig_off()
+                 return
+             else:
+@@ -246,7 +246,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                     degree = i
+             try:
+                 sig_on()
+-                fmpz_poly_realloc(self.__poly, degree + 1)
++                fmpz_poly_realloc(self._poly, degree + 1)
+                 sig_off()
+             except RuntimeError:
+                 raise OverflowError("Cannot allocate memory!")
+@@ -255,13 +255,13 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 i = ii[0] if type(ii) is tuple else ii
+                 if is_small_python_int(a):
+                     sig_on()
+-                    fmpz_poly_set_coeff_si(self.__poly, i, a)
++                    fmpz_poly_set_coeff_si(self._poly, i, a)
+                     sig_off()
+                 else:
+                     if not isinstance(a, Integer):
+                         a = ZZ(a)
+                     sig_on()
+-                    fmpz_poly_set_coeff_mpz(self.__poly, i, (<Integer>a).value)
++                    fmpz_poly_set_coeff_mpz(self._poly, i, (<Integer>a).value)
+                     sig_off()
+             return
+ 
+@@ -270,7 +270,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             check = False
+ 
+         elif isinstance(x, ntl_ZZX):    # coercion from ntl.pyx object
+-            fmpz_poly_set_ZZX(self.__poly, (<ntl_ZZX>x).x)
++            fmpz_poly_set_ZZX(self._poly, (<ntl_ZZX>x).x)
+             return
+ 
+         elif isinstance(x, FractionFieldElement) and \
+@@ -278,8 +278,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if x.denominator() == 1:
+                 # fraction of the form f(x)/1
+                 sig_on()
+-                fmpz_poly_set(self.__poly,
+-                        (<Polynomial_integer_dense_flint>x.numerator()).__poly)
++                fmpz_poly_set(self._poly,
++                        (<Polynomial_integer_dense_flint>x.numerator())._poly)
+                 sig_off()
+                 return
+ 
+@@ -287,19 +287,19 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             x = [x]   # constant polynomials
+ 
+         sig_on()
+-        fmpz_poly_realloc(self.__poly, len(x))
++        fmpz_poly_realloc(self._poly, len(x))
+         sig_off()
+         for i from 0 <= i < len(x):
+             a = x[i]
+             if is_small_python_int(a):
+                 sig_on()
+-                fmpz_poly_set_coeff_si(self.__poly, i, a)
++                fmpz_poly_set_coeff_si(self._poly, i, a)
+                 sig_off()
+             else:
+                 if not isinstance(a, Integer):
+                     a = ZZ(a)
+                 sig_on()
+-                fmpz_poly_set_coeff_mpz(self.__poly, i, (<Integer>a).value)
++                fmpz_poly_set_coeff_mpz(self._poly, i, (<Integer>a).value)
+                 sig_off()
+ 
+     def _eval_mpfr_(self, RealNumber a):
+@@ -327,7 +327,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef RealNumber res = a._new()
+         sig_on()
+-        fmpz_poly_evaluation_mpfr(res.value, self.__poly, a.value)
++        fmpz_poly_evaluation_mpfr(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -357,7 +357,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef RealIntervalFieldElement res = a._new()
+         sig_on()
+-        fmpz_poly_evaluation_mpfi(res.value, self.__poly, a.value)
++        fmpz_poly_evaluation_mpfi(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -412,8 +412,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if isinstance(x, Polynomial_integer_dense_flint):
+                 f = self._new()
+                 sig_on()
+-                fmpz_poly_compose(f.__poly, self.__poly,
+-                                  (<Polynomial_integer_dense_flint> x0).__poly)
++                fmpz_poly_compose(f._poly, self._poly,
++                                  (<Polynomial_integer_dense_flint> x0)._poly)
+                 sig_off()
+                 return f
+             if is_small_python_int(x0):
+@@ -422,7 +422,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 fmpz_init(a_fmpz)
+                 fmpz_init(z_fmpz)
+                 fmpz_set_si(a_fmpz, PyInt_AS_LONG(x0))
+-                fmpz_poly_evaluate_fmpz(z_fmpz, self.__poly, a_fmpz)
++                fmpz_poly_evaluate_fmpz(z_fmpz, self._poly, a_fmpz)
+                 fmpz_get_mpz(z.value, z_fmpz)
+                 fmpz_clear(a_fmpz)
+                 fmpz_clear(z_fmpz)
+@@ -433,7 +433,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if isinstance(x0, Integer):
+                 a = <Integer> x0
+ 
+-                if fmpz_poly_length(self.__poly) == 0:
++                if fmpz_poly_length(self._poly) == 0:
+                     return ZZ.zero()
+                 if mpz_sgn(a.value) == 0:
+                     return self[0]
+@@ -444,7 +444,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 fmpz_init(a_fmpz)
+                 fmpz_init(z_fmpz)
+                 fmpz_set_mpz(a_fmpz, a.value)
+-                fmpz_poly_evaluate_fmpz(z_fmpz, self.__poly, a_fmpz)
++                fmpz_poly_evaluate_fmpz(z_fmpz, self._poly, a_fmpz)
+                 fmpz_get_mpz(z.value, z_fmpz)
+                 fmpz_clear(a_fmpz)
+                 fmpz_clear(z_fmpz)
+@@ -460,14 +460,14 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 arb_a = <RealBall> x0
+                 arb_z = arb_a._new()
+                 sig_on()
+-                arb_fmpz_poly_evaluate_arb(arb_z.value, self.__poly, arb_a.value, arb_a._parent._prec)
++                arb_fmpz_poly_evaluate_arb(arb_z.value, self._poly, arb_a.value, arb_a._parent._prec)
+                 sig_off()
+                 return arb_z
+             if isinstance(x0, ComplexBall):
+                 acb_a = <ComplexBall> x0
+                 acb_z = acb_a._new()
+                 sig_on()
+-                arb_fmpz_poly_evaluate_acb(acb_z.value, self.__poly, acb_a.value, acb_a._parent._prec)
++                arb_fmpz_poly_evaluate_acb(acb_z.value, self._poly, acb_a.value, acb_a._parent._prec)
+                 sig_off()
+                 return acb_z
+ 
+@@ -510,10 +510,10 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+         cdef fmpz_t c
+         fmpz_init(c)
+-        fmpz_poly_get_coeff_fmpz(c, self.__poly, fmpz_poly_degree(self.__poly))
++        fmpz_poly_get_coeff_fmpz(c, self._poly, fmpz_poly_degree(self._poly))
+         cdef int sign = fmpz_sgn(c)
+ 
+-        fmpz_poly_content(c, self.__poly)
++        fmpz_poly_content(c, self._poly)
+ 
+         cdef Integer z = Integer.__new__(Integer)
+         fmpz_get_mpz(z.value, c)
+@@ -561,7 +561,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             5*x^5 + 4*x^4 + 3*x^3 + 2*x^2 + x + 1
+         """
+         cdef Integer z = Integer.__new__(Integer)
+-        fmpz_poly_get_coeff_mpz(z.value, self.__poly, n)
++        fmpz_poly_get_coeff_mpz(z.value, self._poly, n)
+         return z
+ 
+     def _repr(self, name=None, bint latex=False):
+@@ -583,8 +583,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef long i
+         cdef Integer coef = Integer.__new__(Integer)
+         cdef list all = []
+-        for i from fmpz_poly_degree(self.__poly) >= i >= 0:
+-            fmpz_poly_get_coeff_mpz(coef.value, self.__poly, i)
++        for i from fmpz_poly_degree(self._poly) >= i >= 0:
++            fmpz_poly_get_coeff_mpz(coef.value, self._poly, i)
+             if coef:
+                 if coef > 0:
+                     sign_str = '+'
+@@ -649,8 +649,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_add(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_add(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -669,8 +669,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_sub(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_sub(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -688,7 +688,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_neg(x.__poly, self.__poly)
++        fmpz_poly_neg(x._poly, self._poly)
+         sig_off()
+         return x
+ 
+@@ -758,7 +758,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef Polynomial_integer_dense_flint rr = self._new()
+ 
+         sig_on()
+-        fmpz_poly_divrem(qq.__poly, rr.__poly, self.__poly, right.__poly)
++        fmpz_poly_divrem(qq._poly, rr._poly, self._poly, right._poly)
+         sig_off()
+         return qq, rr
+ 
+@@ -776,7 +776,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: x.is_zero()
+             False
+         """
+-        return (fmpz_poly_degree(self.__poly) == -1)
++        return (fmpz_poly_degree(self._poly) == -1)
+ 
+     cpdef bint is_one(self) except -1:
+         """
+@@ -792,7 +792,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: x.is_one()
+             False
+         """
+-        return fmpz_poly_is_one(self.__poly)
++        return fmpz_poly_is_one(self._poly)
+ 
+     def __bool__(self):
+         """
+@@ -808,7 +808,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: bool(x)
+             True
+         """
+-        return not (fmpz_poly_degree(self.__poly) == -1)
++        return not (fmpz_poly_degree(self._poly) == -1)
+ 
+     @coerce_binop
+     def gcd(self, right):
+@@ -831,8 +831,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             return self
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_gcd(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_gcd(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -941,8 +941,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         fmpz_init(r)
+ 
+         sig_on()
+-        fmpz_poly_xgcd(r, ss.__poly, tt.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_xgcd(r, ss._poly, tt._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         cdef Integer rr = Integer.__new__(Integer)
+         fmpz_get_mpz(rr.value, r)
+@@ -970,8 +970,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_mul(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_mul(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -1000,8 +1000,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_mullow(x.__poly, self.__poly,
+-                    (<Polynomial_integer_dense_flint>right).__poly,
++        fmpz_poly_mullow(x._poly, self._poly,
++                    (<Polynomial_integer_dense_flint>right)._poly,
+                     n)
+         sig_off()
+         return x
+@@ -1020,7 +1020,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_scalar_mul_mpz(x.__poly, self.__poly, (<Integer>right).value)
++        fmpz_poly_scalar_mul_mpz(x._poly, self._poly, (<Integer>right).value)
+         sig_off()
+         return x
+ 
+@@ -1038,7 +1038,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_scalar_mul_mpz(x.__poly, self.__poly, (<Integer>right).value)
++        fmpz_poly_scalar_mul_mpz(x._poly, self._poly, (<Integer>right).value)
+         sig_off()
+         return x
+ 
+@@ -1132,7 +1132,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             num = n.numerator()
+             den = n.denominator()
+ 
+-            if fmpz_poly_degree(self.__poly) == 0:
++            if fmpz_poly_degree(self._poly) == 0:
+                 return self.parent()(self[0].nth_root(den) ** num)
+ 
+             return self.nth_root(den) ** num
+@@ -1142,7 +1142,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+             if self.is_zero():
+                 if nn == 0:
+-                    fmpz_poly_set_coeff_si(res.__poly, 0, 1)
++                    fmpz_poly_set_coeff_si(res._poly, 0, 1)
+                     return res
+                 elif nn < 0:
+                     raise ZeroDivisionError("negative exponent in power of zero")
+@@ -1150,17 +1150,17 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                     return res
+             if nn < 0:
+                 sig_on()
+-                fmpz_poly_pow(res.__poly, self.__poly, -nn)
++                fmpz_poly_pow(res._poly, self._poly, -nn)
+                 sig_off()
+                 return ~res
+             else:
+                 if self is self._parent.gen():
+                     sig_on()
+-                    fmpz_poly_set_coeff_ui(res.__poly, nn, 1)
++                    fmpz_poly_set_coeff_ui(res._poly, nn, 1)
+                     sig_off()
+                 else:
+                     sig_on()
+-                    fmpz_poly_pow(res.__poly, self.__poly, nn)
++                    fmpz_poly_pow(res._poly, self._poly, nn)
+                     sig_off()
+                 return res
+ 
+@@ -1187,7 +1187,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+         cdef Polynomial_integer_dense_flint res
+         res = self._new()
+-        fmpz_poly_pow_trunc(res.__poly, self.__poly, n, prec)
++        fmpz_poly_pow_trunc(res._poly, self._poly, n, prec)
+         return res
+ 
+     def __floordiv__(Polynomial_integer_dense_flint self, right):
+@@ -1226,14 +1226,14 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 else:
+                     res = self._new()
+                     sig_on()
+-                    fmpz_poly_scalar_fdiv_mpz(res.__poly, self.__poly,
++                    fmpz_poly_scalar_fdiv_mpz(res._poly, self._poly,
+                             (<Integer> right).value)
+                     sig_off()
+                 return res
+             elif right in ZZ:
+                 res = self._new()
+                 sig_on()
+-                fmpz_poly_scalar_fdiv_mpz(res.__poly, self.__poly,
++                fmpz_poly_scalar_fdiv_mpz(res._poly, self._poly,
+                         (<Integer>ZZ(right)).value)
+                 sig_off()
+                 return res
+@@ -1248,7 +1248,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         else:
+             res = self._new()
+             sig_on()
+-            fmpz_poly_div(res.__poly, self.__poly, _right.__poly)
++            fmpz_poly_div(res._poly, self._poly, _right._poly)
+             sig_off()
+             return res
+ 
+@@ -1293,9 +1293,9 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         if prec <= 0:
+             raise ValueError("the precision must be positive, got {}".format(prec))
+ 
+-        if fmpz_poly_degree(self.__poly) == -1:
++        if fmpz_poly_degree(self._poly) == -1:
+             raise ValueError("constant term is zero")
+-        cdef fmpz_t c = fmpz_poly_get_coeff_ptr(self.__poly, 0)
++        cdef fmpz_t c = fmpz_poly_get_coeff_ptr(self._poly, 0)
+         if fmpz_cmp_si(c, 1) and fmpz_cmp_si(c, -1):
+             raise ValueError("constant term {} is not a unit".format(self[0]))
+ 
+@@ -1303,7 +1303,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         if prec <= 0:
+             return res
+         sig_on()
+-        fmpz_poly_inv_series(res.__poly, self.__poly, prec)
++        fmpz_poly_inv_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1331,16 +1331,16 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             raise IndexError("n must be >= 0")
+         if isinstance(value, int):
+             sig_on()
+-            fmpz_poly_set_coeff_si(self.__poly, n, value)
++            fmpz_poly_set_coeff_si(self._poly, n, value)
+             sig_off()
+         elif isinstance(value, Integer):
+             sig_on()
+-            fmpz_poly_set_coeff_mpz(self.__poly, n, (<Integer>value).value)
++            fmpz_poly_set_coeff_mpz(self._poly, n, (<Integer>value).value)
+             sig_off()
+         else:
+             value = Integer(value)
+             sig_on()
+-            fmpz_poly_set_coeff_mpz(self.__poly, n, (<Integer>value).value)
++            fmpz_poly_set_coeff_mpz(self._poly, n, (<Integer>value).value)
+             sig_off()
+ 
+     def real_root_intervals(self):
+@@ -1364,7 +1364,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+ ##     def __copy__(self):
+ ##         f = Polynomial_integer_dense(self.parent())
+-##         f.__poly = self.__poly.copy()
++##         f._poly = self._poly.copy()
+ ##         return f
+ 
+ 
+@@ -1391,7 +1391,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: type(x.degree())
+             <class 'sage.rings.integer.Integer'>
+         """
+-        return smallInteger(fmpz_poly_degree(self.__poly))
++        return smallInteger(fmpz_poly_degree(self._poly))
+ 
+     def pseudo_divrem(self, B):
+         r"""
+@@ -1426,7 +1426,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint Q = self._new(), R = self._new(), _B = B
+         cdef ulong d
+-        fmpz_poly_pseudo_divrem(Q.__poly, R.__poly, &d, self.__poly, _B.__poly)
++        fmpz_poly_pseudo_divrem(Q._poly, R._poly, &d, self._poly, _B._poly)
+         return Q, R, Integer(d)
+ 
+     def discriminant(self, proof=True):
+@@ -1460,7 +1460,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef ZZX_c ntl_poly
+         cdef ZZ_c* temp
+-        fmpz_poly_get_ZZX(ntl_poly, self.__poly)
++        fmpz_poly_get_ZZX(ntl_poly, self._poly)
+ 
+         temp = ZZX_discriminant(&ntl_poly, proof)
+         cdef Integer x = Integer.__new__(Integer)
+@@ -1531,12 +1531,12 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+             # the primitive part returned by FLINT has positive leading
+             # coefficient
+-            fmpz_poly_primitive_part(ppart, self.__poly)
++            fmpz_poly_primitive_part(ppart, self._poly)
+ 
+             fmpz_poly_get_ZZX(ntl_poly, ppart)
+             fmpz_poly_clear(ppart)
+         else:
+-            fmpz_poly_get_ZZX(ntl_poly, self.__poly)
++            fmpz_poly_get_ZZX(ntl_poly, self._poly)
+ 
+         # input is primitive, with positive leading coefficient
+         ZZX_squarefree_decomposition(&v, &e, &n, &ntl_poly)
+@@ -1544,7 +1544,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         F = []
+         for i from 0 <= i < n:
+             fac = self._new()
+-            fmpz_poly_set_ZZX(fac.__poly, v[i][0])
++            fmpz_poly_set_ZZX(fac._poly, v[i][0])
+             F.append( (fac,e[i]) )
+             del v[i]
+         sig_free(v)
+@@ -1582,9 +1582,9 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef ZZ_c content
+         cdef vec_pair_ZZX_long_c factors
+         cdef long i
+-        cdef int sig_me = fmpz_poly_degree(self.__poly)
++        cdef int sig_me = fmpz_poly_degree(self._poly)
+ 
+-        fmpz_poly_get_ZZX(ntl_poly, self.__poly)
++        fmpz_poly_get_ZZX(ntl_poly, self._poly)
+ 
+         if sig_me > 10:
+             sig_on()
+@@ -1603,13 +1603,13 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             fac_py = self._new()
+             fmpz_init(tcontent)
+             fmpz_set_ZZ(tcontent, content)
+-            fmpz_poly_set_coeff_fmpz(fac_py.__poly, 0, tcontent)
++            fmpz_poly_set_coeff_fmpz(fac_py._poly, 0, tcontent)
+             results.append( (fac_py,1) )
+             fmpz_clear(tcontent)
+ 
+         for i from 0 <= i < factors.length():
+             fac_py = self._new()
+-            fmpz_poly_set_ZZX(fac_py.__poly, factors.RawGet(i).a)
++            fmpz_poly_set_ZZX(fac_py._poly, factors.RawGet(i).a)
+             results.append( (fac_py,factors.RawGet(i).b) )
+         return Factorization(results, unit = unit)
+ 
+@@ -1639,7 +1639,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             (-1) * 2 * 3 * 5 * x
+         """
+         cdef int i
+-        cdef long deg = fmpz_poly_degree(self.__poly)
++        cdef long deg = fmpz_poly_degree(self._poly)
+         # it appears that pari has a window from about degrees 30 and 300
+         # in which it beats NTL.
+         c = self.content()
+@@ -1783,8 +1783,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef Integer x = Integer.__new__(Integer)
+ 
+         sig_on()
+-        fmpz_poly_resultant(res, self.__poly,
+-                (<Polynomial_integer_dense_flint>other).__poly)
++        fmpz_poly_resultant(res, self._poly,
++                (<Polynomial_integer_dense_flint>other)._poly)
+         sig_off()
+         fmpz_get_mpz(x.value, res)
+         fmpz_clear(res)
+@@ -1830,10 +1830,10 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if d != degree:
+                 raise ValueError("degree argument must be a non-negative integer, got %s" % degree)
+             # FLINT expects length
+-            fmpz_poly_reverse(res.__poly, self.__poly, d+1)
++            fmpz_poly_reverse(res._poly, self._poly, d+1)
+         else:
+-            fmpz_poly_reverse(res.__poly, self.__poly,
+-                    fmpz_poly_length(self.__poly))
++            fmpz_poly_reverse(res._poly, self._poly,
++                    fmpz_poly_length(self._poly))
+         return res
+ 
+     def revert_series(self, n):
+@@ -1867,7 +1867,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             raise ValueError("self must have constant coefficient 0 and a unit for coefficient {}^1".format(self.parent().gen()))
+ 
+         sig_on()
+-        fmpz_poly_revert_series(res.__poly, self.__poly, m)
++        fmpz_poly_revert_series(res._poly, self._poly, m)
+         sig_off()
+ 
+         return res
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd
+index a7c380b49a2..fcd907e1abe 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd
+@@ -2,6 +2,6 @@ from sage.libs.ntl.types cimport ZZX_c
+ from sage.rings.polynomial.polynomial_element cimport Polynomial
+ 
+ cdef class Polynomial_integer_dense_ntl(Polynomial):
+-    cdef ZZX_c __poly
++    cdef ZZX_c _poly
+ 
+     cdef Polynomial_integer_dense_ntl _new(self)
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx
+index e7b708bbc51..80a1726bb4e 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx
+@@ -172,7 +172,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         if isinstance(x, Polynomial):
+             if x.parent() is self.parent():
+                 # copy with NTL assignment operator
+-                self.__poly = (<Polynomial_integer_dense_ntl>x).__poly
++                self._poly = (<Polynomial_integer_dense_ntl>x)._poly
+                 return
+             else:
+                 # coerce coefficients into Sage integers
+@@ -191,17 +191,17 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+                     degree = i
+             if degree >= NTL_OVFBND:
+                 raise OverflowError("Dense NTL integer polynomials have a maximum degree of %s" % (NTL_OVFBND-1))
+-            ZZX_SetCoeff_long(self.__poly, degree, 1)
++            ZZX_SetCoeff_long(self._poly, degree, 1)
+             # now fill them in
+             for ii, a in x:
+                 i = ii[0] if type(ii) is tuple else ii
+                 if type(a) is int:
+-                    ZZX_SetCoeff_long(self.__poly, i, a)
++                    ZZX_SetCoeff_long(self._poly, i, a)
+                 else:
+                     if not isinstance(a, Integer):
+                         a = ZZ(a)
+                     mpz_to_ZZ(&y, (<Integer>a).value)
+-                    ZZX_SetCoeff(self.__poly, i, y)
++                    ZZX_SetCoeff(self._poly, i, y)
+             return
+ 
+         elif isinstance(x, pari_gen):
+@@ -210,14 +210,14 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+ 
+         elif isinstance(x, ntl_ZZX):    # coercion from ntl.pyx object
+             # copy with NTL assignment operator
+-            self.__poly = (<ntl_ZZX>x).x
++            self._poly = (<ntl_ZZX>x).x
+             return
+ 
+         elif isinstance(x, FractionFieldElement) and \
+                  isinstance(x.numerator(), Polynomial_integer_dense_ntl):
+             if x.denominator() == 1:
+                 # fraction of the form f(x)/1
+-                self.__poly = (<Polynomial_integer_dense_ntl>x.numerator()).__poly
++                self._poly = (<Polynomial_integer_dense_ntl>x.numerator())._poly
+                 return
+ 
+         elif not isinstance(x, (list, tuple)):
+@@ -229,12 +229,12 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         for i from 0 <= i < len(x):
+             a = x[i]
+             if type(a) is int:
+-                ZZX_SetCoeff_long(self.__poly, i, a)
++                ZZX_SetCoeff_long(self._poly, i, a)
+             else:
+                 if not isinstance(a, Integer):
+                     a = ZZ(a)
+                 mpz_to_ZZ(&y, (<Integer>a).value)
+-                ZZX_SetCoeff(self.__poly, i, y)
++                ZZX_SetCoeff(self._poly, i, y)
+ 
+ 
+     def content(self):
+@@ -259,7 +259,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef ZZ_c y
+         cdef Integer z = Integer.__new__(Integer)
+-        ZZX_content(y, self.__poly)
++        ZZX_content(y, self._poly)
+         ZZ_to_mpz(z.value, &y)
+         return z
+ 
+@@ -288,7 +288,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef RealNumber res = a._new()
+         sig_on()
+-        ZZX_evaluation_mpfr(res.value, self.__poly, a.value)
++        ZZX_evaluation_mpfr(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -318,7 +318,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef RealIntervalFieldElement res = a._new()
+         sig_on()
+-        ZZX_evaluation_mpfi(res.value, self.__poly, a.value)
++        ZZX_evaluation_mpfi(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -363,7 +363,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             5*x^5 + 4*x^4 + 3*x^3 + 2*x^2 + x + 1
+         """
+         cdef Integer z = Integer.__new__(Integer)
+-        ZZ_to_mpz(z.value, &self.__poly.rep.elts()[n])
++        ZZ_to_mpz(z.value, &self._poly.rep.elts()[n])
+         return z
+ 
+     def _repr(self, name=None, bint latex=False):
+@@ -380,15 +380,15 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             name = self.parent().variable_name()
+         cdef long i
+         cdef list all = []
+-        for i from ZZX_deg(self.__poly) >= i >= 0:
+-            sign = ZZ_sign(ZZX_coeff(self.__poly, i))
++        for i from ZZX_deg(self._poly) >= i >= 0:
++            sign = ZZ_sign(ZZX_coeff(self._poly, i))
+             if sign:
+                 if sign > 0:
+                     sign_str = '+'
+-                    coeff_str = ccrepr(self.__poly.rep.elts()[i])
++                    coeff_str = ccrepr(self._poly.rep.elts()[i])
+                 else:
+                     sign_str = '-'
+-                    coeff_str = ccrepr(self.__poly.rep.elts()[i])[1:]
++                    coeff_str = ccrepr(self._poly.rep.elts()[i])[1:]
+                 if i > 0:
+                     if coeff_str == '1':
+                         coeff_str = ''
+@@ -441,8 +441,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             -3*x^2 + 2*x + 7
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_add(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_ntl>right).__poly)
++        ZZX_add(x._poly, self._poly,
++                (<Polynomial_integer_dense_ntl>right)._poly)
+         return x
+ 
+ 
+@@ -459,8 +459,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             3*x^2 + 2*x - 5
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_sub(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_ntl>right).__poly)
++        ZZX_sub(x._poly, self._poly,
++                (<Polynomial_integer_dense_ntl>right)._poly)
+         return x
+ 
+ 
+@@ -476,7 +476,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             -2*x + 1
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_negate(x.__poly, self.__poly)
++        ZZX_negate(x._poly, self._poly)
+         return x
+ 
+ 
+@@ -533,10 +533,10 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef Polynomial_integer_dense_ntl _right = <Polynomial_integer_dense_ntl> right
+ 
+-        if ZZX_IsZero(_right.__poly):
++        if ZZX_IsZero(_right._poly):
+             raise ArithmeticError("division by zero polynomial")
+ 
+-        if ZZX_IsZero(self.__poly):
++        if ZZX_IsZero(self._poly):
+             return self, self
+ 
+         cdef ZZX_c *q
+@@ -545,19 +545,19 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef Polynomial_integer_dense_ntl rr = self._new()
+         cdef int divisible
+ 
+-        if ZZ_IsOne(ZZX_LeadCoeff(_right.__poly)):
++        if ZZ_IsOne(ZZX_LeadCoeff(_right._poly)):
+             # divisor is monic. Just do the division and remainder
+-            ZZX_quo_rem(&self.__poly, &_right.__poly, &r, &q)
+-            ZZX_swap(qq.__poly, q[0])
+-            ZZX_swap(rr.__poly, r[0])
++            ZZX_quo_rem(&self._poly, &_right._poly, &r, &q)
++            ZZX_swap(qq._poly, q[0])
++            ZZX_swap(rr._poly, r[0])
+             del q
+             del r
+         else:
+             # Non-monic divisor. Check whether it divides exactly.
+-            q = ZZX_div(&self.__poly, &_right.__poly, &divisible)
++            q = ZZX_div(&self._poly, &_right._poly, &divisible)
+             if divisible:
+                 # exactly divisible
+-                ZZX_swap(q[0], qq.__poly)
++                ZZX_swap(q[0], qq._poly)
+                 del q
+             else:
+                 # division failed: clean up and raise exception
+@@ -584,8 +584,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         # todo: we're doing an unnecessary copy here
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        cdef ZZX_c* temp = ZZX_gcd(&self.__poly, &(<Polynomial_integer_dense_ntl>right).__poly)
+-        x.__poly = temp[0]
++        cdef ZZX_c* temp = ZZX_gcd(&self._poly, &(<Polynomial_integer_dense_ntl>right)._poly)
++        x._poly = temp[0]
+         del temp
+         return x
+ 
+@@ -658,13 +658,13 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZX_c *t
+         cdef ZZ_c *r
+ 
+-        ZZX_xgcd(&self.__poly, &(<Polynomial_integer_dense_ntl>right).__poly, &r, &s, &t, 1)    # proof = 1
++        ZZX_xgcd(&self._poly, &(<Polynomial_integer_dense_ntl>right)._poly, &r, &s, &t, 1)    # proof = 1
+         cdef Integer rr = Integer.__new__(Integer)
+         ZZ_to_mpz(rr.value, r)
+         cdef Polynomial_integer_dense_ntl ss = self._new()
+         cdef Polynomial_integer_dense_ntl tt = self._new()
+-        ss.__poly = s[0]
+-        tt.__poly = t[0]
++        ss._poly = s[0]
++        tt._poly = t[0]
+         del r
+         del s
+         del t
+@@ -691,8 +691,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             x^3 - 10*x^2 + 32*x - 32
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_mul(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_ntl>right).__poly)
++        ZZX_mul(x._poly, self._poly,
++                (<Polynomial_integer_dense_ntl>right)._poly)
+         return x
+ 
+     cpdef _lmul_(self, Element right):
+@@ -711,7 +711,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZ_c _right
+ 
+         mpz_to_ZZ(&_right, (<Integer>right).value)
+-        ZZX_mul_ZZ(x.__poly, self.__poly, _right)
++        ZZX_mul_ZZ(x._poly, self._poly, _right)
+         return x
+ 
+     cpdef _rmul_(self, Element right):
+@@ -730,7 +730,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZ_c _right
+ 
+         mpz_to_ZZ(&_right, (<Integer>right).value)
+-        ZZX_mul_ZZ(x.__poly, self.__poly, _right)
++        ZZX_mul_ZZ(x._poly, self._poly, _right)
+         return x
+ 
+ 
+@@ -783,7 +783,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         value = Integer(value)
+         cdef ZZ_c y
+         mpz_to_ZZ(&y, (<Integer>value).value)
+-        ZZX_SetCoeff(self.__poly, n, y)
++        ZZX_SetCoeff(self._poly, n, y)
+ 
+ 
+     def real_root_intervals(self):
+@@ -805,7 +805,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+ 
+ ##     def __copy__(self):
+ ##         f = Polynomial_integer_dense(self.parent())
+-##         f.__poly = self.__poly.copy()
++##         f._poly = self._poly.copy()
+ ##         return f
+ 
+ 
+@@ -826,7 +826,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             sage: R(0).degree()
+             -1
+         """
+-        return ZZX_deg(self.__poly)
++        return ZZX_deg(self._poly)
+ 
+     def discriminant(self, proof=True):
+         r"""
+@@ -849,7 +849,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             sage: f.discriminant(proof=False)
+             -339
+         """
+-        cdef ZZ_c* temp = ZZX_discriminant(&self.__poly, proof)
++        cdef ZZ_c* temp = ZZX_discriminant(&self._poly, proof)
+         cdef Integer x = Integer.__new__(Integer)
+         ZZ_to_mpz(x.value, temp)
+         del temp
+@@ -904,11 +904,11 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef long* e
+         cdef long i, n
+         cdef Polynomial_integer_dense_ntl z
+-        ZZX_squarefree_decomposition(&v, &e, &n, &p.__poly)
++        ZZX_squarefree_decomposition(&v, &e, &n, &p._poly)
+         F = []
+         for i from 0 <= i < n:
+             z = self._new()
+-            z.__poly = v[i][0]
++            z._poly = v[i][0]
+             F.append((z, e[i]))
+             del v[i]
+         sig_free(v)
+@@ -950,24 +950,24 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZ_c content
+         cdef vec_pair_ZZX_long_c factors
+         cdef long i
+-        cdef int sig_me = ZZX_deg(self.__poly)
++        cdef int sig_me = ZZX_deg(self._poly)
+         if sig_me > 10:
+             sig_on()
+-        ZZX_factor(content, factors, self.__poly, 0, 0)
++        ZZX_factor(content, factors, self._poly, 0, 0)
+         if sig_me > 10:
+             sig_off()
+         results = []
+         unit = None
+         if not ZZ_IsOne(content):
+             fac_py = self._new()
+-            ZZX_SetCoeff(fac_py.__poly, 0, content)
+-            if ZZX_deg(fac_py.__poly) == 0 and ZZ_to_int(fac_py.__poly.rep.elts())==-1:
++            ZZX_SetCoeff(fac_py._poly, 0, content)
++            if ZZX_deg(fac_py._poly) == 0 and ZZ_to_int(fac_py._poly.rep.elts())==-1:
+                 unit = fac_py
+             else:
+                 results.append( (fac_py,1) )
+         for i from 0 <= i < factors.length():
+             fac_py = self._new()
+-            fac_py.__poly = factors.RawGet(i).a
++            fac_py._poly = factors.RawGet(i).a
+             results.append( (fac_py,factors.RawGet(i).b) )
+         return Factorization(results, unit = unit)
+ 
+@@ -996,7 +996,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             sage: f = -30*x; f.factor()
+             (-1) * 2 * 3 * 5 * x
+         """
+-        cdef int deg = ZZX_deg(self.__poly)
++        cdef int deg = ZZX_deg(self._poly)
+         # it appears that pari has a window from about degrees 30 and 300
+         # in which it beats NTL.
+         c = self.content()
+@@ -1131,7 +1131,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             True
+         """
+         cdef Polynomial_integer_dense_ntl _other = <Polynomial_integer_dense_ntl>(self.parent().coerce(other))
+-        cdef ZZ_c* temp = ZZX_resultant(&self.__poly, &_other.__poly, proof)
++        cdef ZZ_c* temp = ZZX_resultant(&self._poly, &_other._poly, proof)
+         cdef Integer x = Integer.__new__(Integer)
+         ZZ_to_mpz(x.value, temp)
+         del temp
+diff --git a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd
+index 264f05f3c0d..6934acfee8d 100644
+--- a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd
++++ b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd
+@@ -16,7 +16,7 @@ from sage.libs.ntl.lzz_pX cimport *
+ 
+ 
+ cdef class Polynomial_dense_mod_n(Polynomial):
+-    cdef object __poly
++    cdef object _poly
+     cdef object __singular
+ 
+ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n):
+diff --git a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx
+index 57468e3510f..d69d5e09018 100644
+--- a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx
++++ b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx
+@@ -105,19 +105,19 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+ 
+         if construct:
+             if isinstance(x, ZZ_pX):
+-                self.__poly = x
++                self._poly = x
+                 return
+-            self.__poly = ZZ_pX(x, parent.modulus())
++            self._poly = ZZ_pX(x, parent.modulus())
+             return
+ 
+-        self.__poly = ZZ_pX([], parent.modulus())
++        self._poly = ZZ_pX([], parent.modulus())
+ 
+         if x is None:
+             return         # leave initialized to 0 polynomial.
+ 
+         if isinstance(x, Polynomial):
+             if x.parent() == self.parent():
+-                self.__poly = (<Polynomial_dense_modn_ntl_zz>x).__poly.__copy__()
++                self._poly = (<Polynomial_dense_modn_ntl_zz>x)._poly.__copy__()
+                 return
+             else:
+                 R = parent.base_ring()
+@@ -130,7 +130,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+ 
+ 
+         elif isinstance(x, ZZX):
+-            self.__poly = x.copy()
++            self._poly = x.copy()
+             return
+ 
+         elif isinstance(x, pari_gen):
+@@ -142,7 +142,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             if x.denominator().is_unit():
+                 numer = x.numerator()
+                 denom = x.denominator().inverse_of_unit()
+-                x = numer.__poly * denom.__poly
++                x = numer._poly * denom._poly
+                 check = False
+             else:
+                 raise TypeError("Denominator not a unit.")
+@@ -154,13 +154,13 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             R = parent.base_ring()
+             x = [ZZ(R(a)) for a in x]
+ 
+-        self.__poly = ZZ_pX(x, parent.modulus())
++        self._poly = ZZ_pX(x, parent.modulus())
+ 
+     def __reduce__(self):
+         return make_element, (self.parent(), (self.list(), False, self.is_gen()))
+ 
+     def int_list(self):
+-        return eval(str(self.__poly).replace(' ',','))
++        return eval(str(self._poly).replace(' ',','))
+ 
+     def __pari__(self, variable=None):
+         """
+@@ -186,7 +186,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             You must call ``ntl.set_modulus(ntl.ZZ(n))`` before doing
+             arithmetic with this object!
+         """
+-        return self.__poly
++        return self._poly
+ 
+     cdef get_unsafe(self, Py_ssize_t n):
+         """
+@@ -203,13 +203,13 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             sage: f[:3]
+             13*x^2 + 10*x + 5
+         """
+-        return self._parent._base((<ntl_ZZ_pX> self.__poly)[n]._integer_())
++        return self._parent._base((<ntl_ZZ_pX> self._poly)[n]._integer_())
+ 
+     def _unsafe_mutate(self, n, value):
+         n = int(n)
+         if n < 0:
+             raise IndexError("n must be >= 0")
+-        self.__poly[n] = int(value)
++        self._poly[n] = int(value)
+ 
+     def _pow(self, n):
+         n = int(n)
+@@ -218,10 +218,10 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             return self.parent()(self[0]**n)
+         if n < 0:
+             return (~self)**(-n)
+-        return self.parent()(self.__poly**n, construct=True)
++        return self.parent()(self._poly**n, construct=True)
+ 
+     cpdef _add_(self, right):
+-        return self.parent()(self.__poly + (<Polynomial_dense_mod_n>right).__poly, construct=True)
++        return self.parent()(self._poly + (<Polynomial_dense_mod_n>right)._poly, construct=True)
+ 
+     cpdef _mul_(self, right):
+         """
+@@ -231,11 +231,11 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             sage: (x - 2)*(x^2 - 8*x + 16)
+             x^3 + 90*x^2 + 32*x + 68
+         """
+-        return self.parent()(self.__poly * (<Polynomial_dense_mod_n>right).__poly, construct=True)
++        return self.parent()(self._poly * (<Polynomial_dense_mod_n>right)._poly, construct=True)
+ 
+     cpdef _lmul_(self, Element c):
+         try:
+-            return self.parent()(ZZ_pX([c], self.parent().modulus()) * self.__poly, construct=True)
++            return self.parent()(ZZ_pX([c], self.parent().modulus()) * self._poly, construct=True)
+         except RuntimeError as msg: # should this really be a TypeError
+             raise TypeError(msg)
+ 
+@@ -245,7 +245,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+         Return a tuple ``(quotient, remainder)`` where ``self = quotient*other +
+         remainder``.
+         """
+-        v = self.__poly.quo_rem((<Polynomial_dense_mod_n>right).__poly)
++        v = self._poly.quo_rem((<Polynomial_dense_mod_n>right)._poly)
+         P = self.parent()
+         return (P(v[0], construct=True), P(v[1], construct=True) )
+ 
+@@ -281,11 +281,11 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+         """
+         if n == 0 or self.degree() < 0:
+             return self
+-        return self.parent()(self.__poly.left_shift(n),
++        return self.parent()(self._poly.left_shift(n),
+                              construct=True)
+ 
+     cpdef _sub_(self, right):
+-        return self.parent()(self.__poly - (<Polynomial_dense_mod_n>right).__poly, construct=True)
++        return self.parent()(self._poly - (<Polynomial_dense_mod_n>right)._poly, construct=True)
+ 
+     def __floordiv__(self, right):
+         q, _ = self.quo_rem(right)
+@@ -314,7 +314,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             sage: isinstance(x.degree(), Integer)
+             True
+         """
+-        return smallInteger(max(self.__poly.degree(), -1))
++        return smallInteger(max(self._poly.degree(), -1))
+ 
+     cpdef list list(self, bint copy=True):
+         """
+@@ -358,7 +358,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+         """
+         if self.is_gen():
+             raise TypeError("Cannot change the value of the generator.")
+-        self.__poly = ZZ_pX(v, self.parent().modulus())
++        self._poly = ZZ_pX(v, self.parent().modulus())
+ 
+     # Polynomial_singular_repr stuff, copied due to lack of multiple inheritance
+     def _singular_(self, singular=singular_default, force=False):
+@@ -654,8 +654,8 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n):
+                 return
+ 
+         Polynomial_dense_mod_n.__init__(self, parent, v, check=check, is_gen=is_gen, construct=construct)
+-        v = [a for a in self.__poly.list()]
+-        self.__poly = None # this will eventually go away
++        v = [a for a in self._poly.list()]
++        self._poly = None # this will eventually go away
+         cdef ntl_zz_pX ntl = ntl_zz_pX(v, parent.modulus()) # let it handle the hard work
+         self.x = ntl.x
+         self.c = ntl.c
+@@ -668,8 +668,8 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n):
+         # TODO: Get rid of this
+         Polynomial_dense_mod_n.ntl_set_directly(self, v)
+         # verbatim from __init__
+-        v = [int(a) for a in self.__poly.list()]
+-        self.__poly = None # this will eventually go away
++        v = [int(a) for a in self._poly.list()]
++        self._poly = None # this will eventually go away
+         cdef ntl_zz_pX ntl = ntl_zz_pX(v, self._parent.modulus()) # let it handle the hard work
+         self.x = ntl.x
+         self.c = ntl.c
+@@ -1241,8 +1241,8 @@ cdef class Polynomial_dense_modn_ntl_ZZ(Polynomial_dense_mod_n):
+                 return
+ 
+         Polynomial_dense_mod_n.__init__(self, parent, v, check=check, is_gen=is_gen, construct=construct)
+-        cdef ntl_ZZ_pX ntl = self.__poly
+-        self.__poly = None # this will eventually go away
++        cdef ntl_ZZ_pX ntl = self._poly
++        self._poly = None # this will eventually go away
+         self.x = ntl.x
+         self.c = ntl.c
+ 
+diff --git a/src/sage/rings/polynomial/polynomial_rational_flint.pxd b/src/sage/rings/polynomial/polynomial_rational_flint.pxd
+index 055d7842668..f4644f19d04 100644
+--- a/src/sage/rings/polynomial/polynomial_rational_flint.pxd
++++ b/src/sage/rings/polynomial/polynomial_rational_flint.pxd
+@@ -11,7 +11,7 @@ from sage.libs.flint.types cimport fmpq_poly_t
+ from sage.rings.polynomial.polynomial_element cimport Polynomial
+ 
+ cdef class Polynomial_rational_flint(Polynomial):
+-    cdef fmpq_poly_t __poly
++    cdef fmpq_poly_t _poly
+ 
+     cdef Polynomial_rational_flint _new(self)
+     cpdef _mod_(self, right)
+diff --git a/src/sage/rings/polynomial/polynomial_rational_flint.pyx b/src/sage/rings/polynomial/polynomial_rational_flint.pyx
+index d0dd15522e9..26d070ac77f 100644
+--- a/src/sage/rings/polynomial/polynomial_rational_flint.pyx
++++ b/src/sage/rings/polynomial/polynomial_rational_flint.pyx
+@@ -155,16 +155,16 @@ cdef class Polynomial_rational_flint(Polynomial):
+         res._parent = P
+         res._is_gen = <char>0
+         if isinstance(x, int):
+-            fmpq_poly_set_si(res.__poly, <int> x)
++            fmpq_poly_set_si(res._poly, <int> x)
+ 
+         elif isinstance(x, Integer):
+-            fmpq_poly_set_mpz(res.__poly, (<Integer> x).value)
++            fmpq_poly_set_mpz(res._poly, (<Integer> x).value)
+ 
+         elif isinstance(x, Rational):
+-            fmpq_poly_set_mpq(res.__poly, (<Rational> x).value)
++            fmpq_poly_set_mpq(res._poly, (<Rational> x).value)
+ 
+         else:
+-            fmpq_poly_set_si(res.__poly, int(x))
++            fmpq_poly_set_si(res._poly, int(x))
+         return res
+ 
+ 
+@@ -177,7 +177,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: R.<t> = QQ[]
+             sage: f = 2/3 * t - 7  #indirect doctest
+         """
+-        fmpq_poly_init(self.__poly)
++        fmpq_poly_init(self._poly)
+ 
+     def __dealloc__(self):
+         """
+@@ -189,7 +189,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: f = 1/3 * t
+             sage: del f
+         """
+-        fmpq_poly_clear(self.__poly)
++        fmpq_poly_clear(self._poly)
+ 
+     def __init__(self, parent, x=None, check=True, is_gen=False, construct=False):
+         """
+@@ -227,19 +227,19 @@ cdef class Polynomial_rational_flint(Polynomial):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+ 
+         if is_gen:
+-            fmpq_poly_set_coeff_si(self.__poly, 1, 1)
++            fmpq_poly_set_coeff_si(self._poly, 1, 1)
+ 
+         elif isinstance(x, Polynomial_rational_flint):
+-            fmpq_poly_set(self.__poly, (<Polynomial_rational_flint> x).__poly)
++            fmpq_poly_set(self._poly, (<Polynomial_rational_flint> x)._poly)
+ 
+         elif isinstance(x, int):
+-            fmpq_poly_set_si(self.__poly, <int> x)
++            fmpq_poly_set_si(self._poly, <int> x)
+ 
+         elif isinstance(x, Integer):
+-            fmpq_poly_set_mpz(self.__poly, (<Integer> x).value)
++            fmpq_poly_set_mpz(self._poly, (<Integer> x).value)
+ 
+         elif isinstance(x, Rational):
+-            fmpq_poly_set_mpq(self.__poly, (<Rational> x).value)
++            fmpq_poly_set_mpq(self._poly, (<Rational> x).value)
+ 
+         elif isinstance(x, list) or isinstance(x, tuple):
+ 
+@@ -257,7 +257,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             for deg from 0 <= deg < n:
+                 mpq_init(L2[deg])
+                 mpq_set(L2[deg], (<Rational> L1[deg]).value)
+-            fmpq_poly_set_array_mpq(self.__poly, L2, n)
++            fmpq_poly_set_array_mpq(self._poly, L2, n)
+             for deg from 0 <= deg < n:
+                 mpq_clear(L2[deg])
+             sig_free(L2)
+@@ -266,13 +266,13 @@ cdef class Polynomial_rational_flint(Polynomial):
+ #           deg = 0
+ #           for e in x:
+ #               c = Rational(e)
+-#               fmpq_poly_set_coeff_mpq(self.__poly, deg, c.value)
++#               fmpq_poly_set_coeff_mpq(self._poly, deg, c.value)
+ #               deg += 1
+ 
+         elif isinstance(x, dict):
+             for deg, e in x.iteritems():
+                 c = Rational(e)
+-                fmpq_poly_set_coeff_mpq(self.__poly, deg, c.value)
++                fmpq_poly_set_coeff_mpq(self._poly, deg, c.value)
+ 
+         elif isinstance(x, pari_gen):
+             k = self._parent.base_ring()
+@@ -281,7 +281,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+                                              is_gen=False, construct=construct)
+ 
+         elif isinstance(x, Polynomial_integer_dense_flint):
+-            fmpq_poly_set_fmpz_poly(self.__poly, (<Polynomial_integer_dense_flint>x).__poly)
++            fmpq_poly_set_fmpz_poly(self._poly, (<Polynomial_integer_dense_flint>x)._poly)
+ 
+         elif isinstance(x, Polynomial):
+             k = self._parent.base_ring()
+@@ -329,7 +329,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             True
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        fmpq_poly_set(res.__poly, self.__poly)
++        fmpq_poly_set(res._poly, self._poly)
+         return res
+ 
+     def _singular_(self, singular=singular_default):
+@@ -364,7 +364,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: g.list()
+             []
+         """
+-        cdef unsigned long length = fmpq_poly_length(self.__poly)
++        cdef unsigned long length = fmpq_poly_length(self._poly)
+         return [self.get_unsafe(n) for n in range(length)]
+ 
+     ###########################################################################
+@@ -392,7 +392,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: type(f.degree())
+             <class 'sage.rings.integer.Integer'>
+         """
+-        return smallInteger(fmpq_poly_degree(self.__poly))
++        return smallInteger(fmpq_poly_degree(self._poly))
+ 
+     cdef get_unsafe(self, Py_ssize_t n):
+         """
+@@ -413,7 +413,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             1/2*t^2 + t + 1
+         """
+         cdef Rational z = Rational.__new__(Rational)
+-        fmpq_poly_get_coeff_mpq(z.value, self.__poly, n)
++        fmpq_poly_get_coeff_mpq(z.value, self._poly, n)
+         return z
+ 
+     cpdef _unsafe_mutate(self, unsigned long n, value):
+@@ -434,24 +434,24 @@ cdef class Polynomial_rational_flint(Polynomial):
+         rely on this convention.  This method should be used only with the
+         utmost care.
+         """
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if isinstance(value, int):
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_si(self.__poly, n, value)
++            fmpq_poly_set_coeff_si(self._poly, n, value)
+             if do_sig: sig_off()
+         elif isinstance(value, Integer):
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_mpz(self.__poly, n, (<Integer> value).value)
++            fmpq_poly_set_coeff_mpz(self._poly, n, (<Integer> value).value)
+             if do_sig: sig_off()
+         elif isinstance(value, Rational):
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_mpq(self.__poly, n, (<Rational> value).value)
++            fmpq_poly_set_coeff_mpq(self._poly, n, (<Rational> value).value)
+             if do_sig: sig_off()
+         else:
+             value = Rational(value)
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_mpq(self.__poly, n, (<Rational> value).value)
++            fmpq_poly_set_coeff_mpq(self._poly, n, (<Rational> value).value)
+             if do_sig: sig_off()
+ 
+     def __call__(self, *x, **kwds):
+@@ -501,20 +501,20 @@ cdef class Polynomial_rational_flint(Polynomial):
+             if isinstance(a, Polynomial_rational_flint):
+                 f = (<Polynomial_rational_flint> a)._new()
+                 sig_str("FLINT exception")
+-                fmpq_poly_compose(f.__poly, self.__poly,
+-                    (<Polynomial_rational_flint> a).__poly)
++                fmpq_poly_compose(f._poly, self._poly,
++                    (<Polynomial_rational_flint> a)._poly)
+                 sig_off()
+                 return f
+             elif isinstance(a, Rational):
+                 r = Rational.__new__(Rational)
+                 sig_str("FLINT exception")
+-                fmpq_poly_evaluate_mpq(r.value, self.__poly, (<Rational> a).value)
++                fmpq_poly_evaluate_mpq(r.value, self._poly, (<Rational> a).value)
+                 sig_off()
+                 return r
+             elif isinstance(a, Integer):
+                 r = Rational.__new__(Rational)
+                 sig_str("FLINT exception")
+-                fmpq_poly_evaluate_mpz(r.value, self.__poly, (<Integer> a).value)
++                fmpq_poly_evaluate_mpz(r.value, self._poly, (<Integer> a).value)
+                 sig_off()
+                 return r
+             elif isinstance(a, int):
+@@ -523,7 +523,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+                 fmpz_init(tmpfz)
+                 fmpq_init(tmpfq)
+                 fmpz_set_si(tmpfz, PyInt_AS_LONG(a))
+-                fmpq_poly_evaluate_fmpz(tmpfq, self.__poly, tmpfz)
++                fmpq_poly_evaluate_fmpz(tmpfq, self._poly, tmpfz)
+                 fmpq_get_mpq(r.value, tmpfq)
+                 fmpq_clear(tmpfq)
+                 fmpz_clear(tmpfz)
+@@ -533,18 +533,18 @@ cdef class Polynomial_rational_flint(Polynomial):
+                 arb_a = <RealBall> a
+                 arb_z = arb_a._new()
+                 sig_on()
+-                _arb_fmpz_poly_evaluate_arb(arb_z.value, fmpq_poly_numref(self.__poly),
+-                        fmpq_poly_length(self.__poly), arb_a.value, arb_a._parent._prec)
+-                arb_div_fmpz(arb_z.value, arb_z.value, fmpq_poly_denref(self.__poly), arb_a._parent._prec)
++                _arb_fmpz_poly_evaluate_arb(arb_z.value, fmpq_poly_numref(self._poly),
++                        fmpq_poly_length(self._poly), arb_a.value, arb_a._parent._prec)
++                arb_div_fmpz(arb_z.value, arb_z.value, fmpq_poly_denref(self._poly), arb_a._parent._prec)
+                 sig_off()
+                 return arb_z
+             if isinstance(a, ComplexBall):
+                 acb_a = <ComplexBall> a
+                 acb_z = acb_a._new()
+                 sig_on()
+-                _arb_fmpz_poly_evaluate_acb(acb_z.value, fmpq_poly_numref(self.__poly),
+-                        fmpq_poly_length(self.__poly), acb_a.value, acb_a._parent._prec)
+-                acb_div_fmpz(acb_z.value, acb_z.value, fmpq_poly_denref(self.__poly), acb_a._parent._prec)
++                _arb_fmpz_poly_evaluate_acb(acb_z.value, fmpq_poly_numref(self._poly),
++                        fmpq_poly_length(self._poly), acb_a.value, acb_a._parent._prec)
++                acb_div_fmpz(acb_z.value, acb_z.value, fmpq_poly_denref(self._poly), acb_a._parent._prec)
+                 sig_off()
+                 return acb_z
+ 
+@@ -570,14 +570,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res
+         cdef bint do_sig
+ 
+-        if (n >= fmpq_poly_length(self.__poly)):
++        if (n >= fmpq_poly_length(self._poly)):
+             return self
+         else:
+             res = self._new()
+             if n > 0:
+-                do_sig = _do_sig(self.__poly)
++                do_sig = _do_sig(self._poly)
+                 if do_sig: sig_str("FLINT exception")
+-                fmpq_poly_get_slice(res.__poly, self.__poly, 0, n)
++                fmpq_poly_get_slice(res._poly, self._poly, 0, n)
+                 if do_sig: sig_off()
+             return res
+ 
+@@ -664,7 +664,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef bint do_sig
+ 
+         if degree is None:
+-            len = fmpq_poly_length(self.__poly)
++            len = fmpq_poly_length(self._poly)
+         else:
+             try:
+                 len = <unsigned long> (degree + 1)
+@@ -672,9 +672,9 @@ cdef class Polynomial_rational_flint(Polynomial):
+                 raise ValueError('degree must be convertible to long')
+ 
+         res = self._new()
+-        do_sig = _do_sig(self.__poly)
++        do_sig = _do_sig(self._poly)
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_reverse(res.__poly, self.__poly, len)
++        fmpq_poly_reverse(res._poly, self._poly, len)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -709,7 +709,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             raise ValueError("self must have constant coefficient 0 and a unit for coefficient {}^1".format(self.parent().gen()))
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_revert_series(res.__poly, self.__poly, m)
++        fmpq_poly_revert_series(res._poly, self._poly, m)
+         sig_off()
+ 
+         return res
+@@ -731,7 +731,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: R(0).is_zero()
+             True
+         """
+-        return fmpq_poly_is_zero(self.__poly)
++        return fmpq_poly_is_zero(self._poly)
+ 
+     cpdef bint is_one(self) except -1:
+         r"""
+@@ -751,7 +751,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: R([1,1]).is_one()
+             False
+         """
+-        return fmpq_poly_is_one(self.__poly)
++        return fmpq_poly_is_one(self._poly)
+ 
+     def __bool__(self):
+         """
+@@ -766,7 +766,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: bool(R(0))
+             False
+         """
+-        return not fmpq_poly_is_zero(self.__poly)
++        return not fmpq_poly_is_zero(self._poly)
+ 
+     ###########################################################################
+     # Shifting                                                                #
+@@ -794,14 +794,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res
+         cdef bint do_sig
+ 
+-        if k == 0 or fmpq_poly_is_zero(f.__poly):
++        if k == 0 or fmpq_poly_is_zero(f._poly):
+             return self
+         else:
+             res = f._new()
+-            do_sig = fmpq_poly_length(f.__poly) > 5000 or n > 5000
++            do_sig = fmpq_poly_length(f._poly) > 5000 or n > 5000
+ 
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_shift_left(res.__poly, f.__poly, k)
++            fmpq_poly_shift_left(res._poly, f._poly, k)
+             if do_sig: sig_off()
+             return res
+ 
+@@ -822,14 +822,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res
+         cdef bint do_sig
+ 
+-        if k == 0 or fmpq_poly_is_zero(f.__poly):
++        if k == 0 or fmpq_poly_is_zero(f._poly):
+             return self
+         else:
+             res = f._new()
+-            do_sig = _do_sig(f.__poly)
++            do_sig = _do_sig(f._poly)
+ 
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_shift_right(res.__poly, f.__poly, k)
++            fmpq_poly_shift_right(res._poly, f._poly, k)
+             if do_sig: sig_off()
+             return res
+ 
+@@ -858,10 +858,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_add(res.__poly, self.__poly, op2.__poly)
++        fmpq_poly_add(res._poly, self._poly, op2._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -886,10 +886,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_sub(res.__poly, self.__poly, op2.__poly)
++        fmpq_poly_sub(res._poly, self._poly, op2._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -912,10 +912,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             True
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_neg(res.__poly, self.__poly)
++        fmpq_poly_neg(res._poly, self._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -945,8 +945,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint rr = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_divrem(qq.__poly, rr.__poly, self.__poly,
+-                         (<Polynomial_rational_flint> right).__poly)
++        fmpq_poly_divrem(qq._poly, rr._poly, self._poly,
++                         (<Polynomial_rational_flint> right)._poly)
+         sig_off()
+         return qq, rr
+ 
+@@ -974,8 +974,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_gcd(res.__poly, self.__poly,
+-                (<Polynomial_rational_flint> right).__poly)
++        fmpq_poly_gcd(res._poly, self._poly,
++                (<Polynomial_rational_flint> right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1001,8 +1001,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_lcm(res.__poly, self.__poly,
+-                      (<Polynomial_rational_flint> right).__poly)
++        fmpq_poly_lcm(res._poly, self._poly,
++                      (<Polynomial_rational_flint> right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1043,7 +1043,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint t = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_xgcd(d.__poly, s.__poly, t.__poly, self.__poly, (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_xgcd(d._poly, s._poly, t._poly, self._poly, (<Polynomial_rational_flint>right)._poly)
+         sig_off()
+         return d, s, t
+ 
+@@ -1069,10 +1069,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_mul(res.__poly, self.__poly, op2.__poly)
++        fmpq_poly_mul(res._poly, self._poly, op2._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -1103,13 +1103,13 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if n <= 0:
+             raise ValueError("n must be > 0")
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_mullow(res.__poly, self.__poly, op2.__poly, n)
++        fmpq_poly_mullow(res._poly, self._poly, op2._poly, n)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -1125,10 +1125,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             9*t^3 - 6*t + 2
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_scalar_mul_mpq(res.__poly, self.__poly,
++        fmpq_poly_scalar_mul_mpq(res._poly, self._poly,
+                                  (<Rational> left).value)
+         if do_sig: sig_off()
+         return res
+@@ -1145,10 +1145,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             9*t^3 - 6*t + 2
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_scalar_mul_mpq(res.__poly, self.__poly,
++        fmpq_poly_scalar_mul_mpq(res._poly, self._poly,
+                                  (<Rational> right).value)
+         if do_sig: sig_off()
+         return res
+@@ -1272,27 +1272,27 @@ cdef class Polynomial_rational_flint(Polynomial):
+             num = r.numerator()
+             den = r.denominator()
+ 
+-            if fmpq_poly_degree(self.__poly) == 0:
++            if fmpq_poly_degree(self._poly) == 0:
+                 return self.parent()(self[0].nth_root(den) ** num)
+ 
+             return self.nth_root(den) ** num
+ 
+         else:
+             if n < 0:
+-                if fmpq_poly_is_zero(self.__poly):
++                if fmpq_poly_is_zero(self._poly):
+                     raise ZeroDivisionError("negative exponent in power of zero")
+                 res = self._new()
+                 sig_str("FLINT exception")
+-                fmpq_poly_pow(res.__poly, self.__poly, -n)
++                fmpq_poly_pow(res._poly, self._poly, -n)
+                 sig_off()
+                 return ~res
+             else:
+                 res = self._new()
+                 sig_str("FLINT exception")
+                 if self._is_gen:
+-                    fmpq_poly_set_coeff_si(res.__poly, n, 1)
++                    fmpq_poly_set_coeff_si(res._poly, n, 1)
+                 else:
+-                    fmpq_poly_pow(res.__poly, self.__poly, n)
++                    fmpq_poly_pow(res._poly, self._poly, n)
+                 sig_off()
+                 return res
+ 
+@@ -1328,10 +1328,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         if not isinstance(right, Polynomial_rational_flint):
+             if right in QQ:
+                 res = self._new()
+-                do_sig = _do_sig(self.__poly)
++                do_sig = _do_sig(self._poly)
+ 
+                 if do_sig: sig_str("FLINT exception")
+-                fmpq_poly_scalar_div_mpq(res.__poly, self.__poly,
++                fmpq_poly_scalar_div_mpq(res._poly, self._poly,
+                                                   (<Rational> QQ(right)).value)
+                 if do_sig: sig_off()
+                 return res
+@@ -1340,8 +1340,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+ 
+         res = self._new()
+         sig_str("FLINT exception")
+-        fmpq_poly_div(res.__poly, self.__poly,
+-                                     (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_div(res._poly, self._poly,
++                                     (<Polynomial_rational_flint>right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1381,15 +1381,15 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         if prec <= 0:
+             raise ValueError("the precision must be positive, got {}".format(prec))
+-        if fmpq_poly_degree(self.__poly) == -1 or \
+-           fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        if fmpq_poly_degree(self._poly) == -1 or \
++           fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term is zero")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         if prec <= 0:
+             return res
+         sig_on()
+-        fmpq_poly_inv_series(res.__poly, self.__poly, prec)
++        fmpq_poly_inv_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1423,8 +1423,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+ 
+         res = self._new()
+         sig_str("FLINT exception")
+-        fmpq_poly_rem(res.__poly, self.__poly,
+-                                     (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_rem(res._poly, self._poly,
++                                     (<Polynomial_rational_flint>right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1453,7 +1453,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+         Polynomial_integer_dense_flint.__init__(num, parent, x=None,
+                                     check=False, is_gen=False, construct=False)
+         sig_str("FLINT exception")
+-        fmpq_poly_get_numerator(num.__poly, self.__poly)
++        fmpq_poly_get_numerator(num._poly, self._poly)
+         sig_off()
+         return num
+ 
+@@ -1469,10 +1469,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             3
+         """
+         cdef Integer den = Integer.__new__(Integer)
+-        if fmpq_poly_denref(self.__poly) is NULL:
++        if fmpq_poly_denref(self._poly) is NULL:
+             mpz_set_ui(den.value, 1)
+         else:
+-            fmpz_get_mpz(den.value, <fmpz *> fmpq_poly_denref(self.__poly))
++            fmpz_get_mpz(den.value, <fmpz *> fmpq_poly_denref(self._poly))
+         return den
+ 
+     def _derivative(self, var = None):
+@@ -1517,10 +1517,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             raise ValueError("cannot differentiate with respect to {}".format(var))
+ 
+         der = self._new()
+-        do_sig = _do_sig(self.__poly)
++        do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_derivative(der.__poly, self.__poly)
++        fmpq_poly_derivative(der._poly, self._poly)
+         if do_sig: sig_off()
+         return der
+ 
+@@ -1574,8 +1574,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef fmpq_t t
+         fmpq_init(t)
+         sig_str("FLINT exception")
+-        fmpq_poly_resultant(t, self.__poly,
+-                            (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_resultant(t, self._poly,
++                            (<Polynomial_rational_flint>right)._poly)
+         fmpq_get_mpq(res.value, t)
+         sig_off()
+         fmpq_clear(t)
+@@ -1623,7 +1623,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+ 
+         """
+         cdef Polynomial_integer_dense_flint primitive
+-        cdef unsigned long length = fmpq_poly_length(self.__poly)
++        cdef unsigned long length = fmpq_poly_length(self._poly)
+ 
+         if length < 2:
+             return False
+@@ -1636,8 +1636,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+                              x=None, check=True, is_gen=False, construct=False)
+ 
+             sig_str("FLINT exception")
+-            fmpq_poly_get_numerator(primitive.__poly, self.__poly)
+-            fmpz_poly_primitive_part(primitive.__poly, primitive.__poly)
++            fmpq_poly_get_numerator(primitive._poly, self._poly)
++            fmpz_poly_primitive_part(primitive._poly, primitive._poly)
+             sig_off()
+             return primitive.is_irreducible()
+ 
+@@ -1669,14 +1669,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             ...
+             ValueError: constant term should be 1 in order to take logarithm
+         """
+-        if fmpq_poly_degree(self.__poly) == -1 or \
+-           fmpz_cmp(fmpq_poly_numref(self.__poly),
+-                    fmpq_poly_denref(self.__poly)):
++        if fmpq_poly_degree(self._poly) == -1 or \
++           fmpz_cmp(fmpq_poly_numref(self._poly),
++                    fmpq_poly_denref(self._poly)):
+             raise ValueError("constant term should be 1 in order to take logarithm")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_log_series(res.__poly, self.__poly, prec)
++        fmpq_poly_log_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1703,14 +1703,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.one()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take exponential")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_exp_series(res.__poly, self.__poly, prec)
++        fmpq_poly_exp_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1737,14 +1737,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take arctangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_atan_series(res.__poly, self.__poly, prec)
++        fmpq_poly_atan_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1768,14 +1768,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic arctangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_atanh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_atanh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1802,14 +1802,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take arcsine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_asin_series(res.__poly, self.__poly, prec)
++        fmpq_poly_asin_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1837,14 +1837,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic arcsine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_asinh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_asinh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1871,14 +1871,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take tangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_tan_series(res.__poly, self.__poly, prec)
++        fmpq_poly_tan_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1905,14 +1905,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take sine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_sin_series(res.__poly, self.__poly, prec)
++        fmpq_poly_sin_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1937,14 +1937,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take cosine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_cos_series(res.__poly, self.__poly, prec)
++        fmpq_poly_cos_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1969,14 +1969,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic sine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_sinh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_sinh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -2007,14 +2007,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.one()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic cosine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_cosh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_cosh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -2040,14 +2040,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic tangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_tanh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_tanh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+diff --git a/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx b/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx
+index fbe96d186c5..955f83468e4 100644
+--- a/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx
++++ b/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx
+@@ -116,7 +116,7 @@ cdef class PolynomialRealDense(Polynomial):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+         self._base_ring = parent._base
+         cdef Py_ssize_t i, degree
+-        cdef int prec = self._base_ring.__prec
++        cdef int prec = self._base_ring._prec
+         cdef mpfr_rnd_t rnd = self._base_ring.rnd
+         if x is None:
+             self._coeffs = <mpfr_t*>check_allocarray(1, sizeof(mpfr_t)) # degree zero
+@@ -227,7 +227,7 @@ cdef class PolynomialRealDense(Polynomial):
+ 
+     cdef PolynomialRealDense _new(self, Py_ssize_t degree):
+         cdef Py_ssize_t i
+-        cdef int prec = self._base_ring.__prec
++        cdef int prec = self._base_ring._prec
+         cdef PolynomialRealDense f = <PolynomialRealDense>PolynomialRealDense.__new__(PolynomialRealDense)
+         f._parent = self._parent
+         f._base_ring = self._base_ring
+@@ -501,7 +501,7 @@ cdef class PolynomialRealDense(Polynomial):
+         else:
+             f = left._new(left._degree + right._degree)
+         sig_on()
+-        mpfr_init2(tmp, left._base_ring.__prec)
++        mpfr_init2(tmp, left._base_ring._prec)
+         for i from 0 <= i <= f._degree:
+             # Yes, we could make this more efficient by initializing with
+             # a multiple of left rather than all zeros...
+@@ -661,7 +661,7 @@ cdef class PolynomialRealDense(Polynomial):
+         q = self._new(self._degree - other._degree)
+         # This is the standard division algorithm
+         sig_on()
+-        mpfr_init2(tmp, self._base_ring.__prec)
++        mpfr_init2(tmp, self._base_ring._prec)
+         for i from self._degree >= i >= other._degree:
+             mpfr_set(q._coeffs[i-other._degree], r._coeffs[i], rnd)
+             for j from 0 <= j < other._degree:
+@@ -725,7 +725,7 @@ cdef class PolynomialRealDense(Polynomial):
+         cdef RealNumber x = <RealNumber>xx
+         cdef RealNumber res
+ 
+-        if (<RealField_class>x._parent).__prec < self._base_ring.__prec:
++        if (<RealField_class>x._parent)._prec < self._base_ring._prec:
+             res = RealNumber(x._parent)
+         else:
+             res = RealNumber(self._base_ring)
+diff --git a/src/sage/rings/polynomial/polynomial_zmod_flint.pyx b/src/sage/rings/polynomial/polynomial_zmod_flint.pyx
+index 253ab949fcc..4c480673861 100644
+--- a/src/sage/rings/polynomial/polynomial_zmod_flint.pyx
++++ b/src/sage/rings/polynomial/polynomial_zmod_flint.pyx
+@@ -110,7 +110,7 @@ cdef class Polynomial_zmod_flint(Polynomial_template):
+             return
+         elif isinstance(x, Polynomial_integer_dense_flint):
+             Polynomial_template.__init__(self, parent, 0, check, is_gen, construct)
+-            self._set_fmpz_poly((<Polynomial_integer_dense_flint>x).__poly)
++            self._set_fmpz_poly((<Polynomial_integer_dense_flint>x)._poly)
+             return
+         else:
+             if isinstance(x, ntl_zz_pX):
+diff --git a/src/sage/rings/power_series_mpoly.pxd b/src/sage/rings/power_series_mpoly.pxd
+index f822ecc1227..d358ada1356 100644
+--- a/src/sage/rings/power_series_mpoly.pxd
++++ b/src/sage/rings/power_series_mpoly.pxd
+@@ -3,6 +3,6 @@ from .power_series_ring_element cimport PowerSeries
+ 
+ cdef class PowerSeries_mpoly(PowerSeries):
+     cdef ModuleElement __f
+-    cdef object __poly
++    cdef object _poly
+     cdef object __list
+     cdef bint _truncated
+diff --git a/src/sage/rings/power_series_mpoly.pyx b/src/sage/rings/power_series_mpoly.pyx
+index 0c901a3557b..be59294e75b 100644
+--- a/src/sage/rings/power_series_mpoly.pyx
++++ b/src/sage/rings/power_series_mpoly.pyx
+@@ -65,7 +65,7 @@ cdef class PowerSeries_mpoly(PowerSeries):
+ 
+     def __reduce__(self):
+         # do *not* delete old versions.
+-        return make_powerseries_mpoly_v0, (self._parent, self.__f, self._prec, self.__is_gen)
++        return make_powerseries_mpoly_v0, (self._parent, self.__f, self._prec, self._is_gen)
+ 
+     def __call__(self, *args, **kwds):
+         if len(kwds) == 0 and len(args) == 1:
+@@ -92,10 +92,10 @@ cdef class PowerSeries_mpoly(PowerSeries):
+         return self.__list
+ 
+     def polynomial(self):
+-        if self.__poly is None:
++        if self._poly is None:
+             S = self.parent()._mpoly_ring()
+-            self.__poly = self.__f.polynomial(S.gens()[-1])
+-        return self.__poly
++            self._poly = self.__f.polynomial(S.gens()[-1])
++        return self._poly
+ 
+     def _mpoly(self):
+         return self.__f
+diff --git a/src/sage/rings/power_series_poly.pyx b/src/sage/rings/power_series_poly.pyx
+index 7c93168d4b1..6cacab1f0c8 100644
+--- a/src/sage/rings/power_series_poly.pyx
++++ b/src/sage/rings/power_series_poly.pyx
+@@ -97,7 +97,7 @@ cdef class PowerSeries_poly(PowerSeries):
+             sage: f == loads(dumps(f)) # indirect doctest
+             True
+         """
+-        return self.__class__, (self._parent, self.__f, self._prec, self.__is_gen)
++        return self.__class__, (self._parent, self.__f, self._prec, self._is_gen)
+ 
+     def polynomial(self):
+         """
+diff --git a/src/sage/rings/power_series_ring_element.pxd b/src/sage/rings/power_series_ring_element.pxd
+index 067c4f3c6d4..e5c031ee147 100644
+--- a/src/sage/rings/power_series_ring_element.pxd
++++ b/src/sage/rings/power_series_ring_element.pxd
+@@ -1,7 +1,7 @@
+ from sage.structure.element cimport AlgebraElement, RingElement
+ 
+ cdef class PowerSeries(AlgebraElement):
+-    cdef char __is_gen
++    cdef char _is_gen
+     cdef _prec
+     cdef common_prec_c(self, PowerSeries other)
+     #_prec(self, RingElement right_r)
+diff --git a/src/sage/rings/power_series_ring_element.pyx b/src/sage/rings/power_series_ring_element.pyx
+index 54314d538ed..e5e2df79e1b 100644
+--- a/src/sage/rings/power_series_ring_element.pyx
++++ b/src/sage/rings/power_series_ring_element.pyx
+@@ -159,7 +159,7 @@ cdef class PowerSeries(AlgebraElement):
+              over Finite Field of size 3
+         """
+         AlgebraElement.__init__(self, parent)
+-        self.__is_gen = is_gen
++        self._is_gen = is_gen
+         self._prec = prec
+ 
+     def __hash__(self):
+@@ -234,7 +234,7 @@ cdef class PowerSeries(AlgebraElement):
+             sage: 1*t == t
+             True
+         """
+-        return bool(self.__is_gen)
++        return bool(self._is_gen)
+ 
+     def _im_gens_(self, codomain, im_gens, base_map=None):
+         """
+diff --git a/src/sage/rings/real_mpfi.pxd b/src/sage/rings/real_mpfi.pxd
+index 959a650aafc..4201788d198 100644
+--- a/src/sage/rings/real_mpfi.pxd
++++ b/src/sage/rings/real_mpfi.pxd
+@@ -11,7 +11,7 @@ from .real_mpfr cimport RealField_class
+ cdef class RealIntervalFieldElement(RingElement)  # forward decl
+ 
+ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+-    cdef mpfr_prec_t __prec
++    cdef mpfr_prec_t _prec
+     cdef bint sci_not
+     # Cache RealField instances for the lower, upper, and middle bounds.
+     # These have the same precision as the interval field;
+diff --git a/src/sage/rings/real_mpfi.pyx b/src/sage/rings/real_mpfi.pyx
+index 1193a14baff..509f6f63da0 100644
+--- a/src/sage/rings/real_mpfi.pyx
++++ b/src/sage/rings/real_mpfi.pyx
+@@ -526,7 +526,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         if prec < MPFR_PREC_MIN or prec > MPFR_PREC_MAX:
+             raise ValueError("prec (=%s) must be >= %s and <= %s." % (
+                 prec, MPFR_PREC_MIN, MPFR_PREC_MAX))
+-        self.__prec = prec
++        self._prec = prec
+         self.sci_not = sci_not
+         self.__lower_field = RealField(prec, sci_not, "RNDD")
+         self.__middle_field = RealField(prec, sci_not, "RNDN")
+@@ -598,7 +598,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         elif rnd == "RNDU":
+             return self.upper_field()
+         else:
+-            return RealField(self.__prec, self.sci_not, rnd)
++            return RealField(self._prec, self.sci_not, rnd)
+ 
+     def _repr_(self):
+         """
+@@ -611,7 +611,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RealIntervalField(200) # indirect doctest
+             Real Interval Field with 200 bits of precision
+         """
+-        s = "Real Interval Field with %s bits of precision"%self.__prec
++        s = "Real Interval Field with %s bits of precision"%self._prec
+         return s
+ 
+     def _latex_(self):
+@@ -802,7 +802,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RIF.has_coerce_map_from(float)
+             False
+         """
+-        prec = self.__prec
++        prec = self._prec
+ 
+         # Direct and efficient conversions
+         if S is ZZ or S is QQ:
+@@ -810,7 +810,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         if S is int or S is long:
+             return True
+         if isinstance(S, RealIntervalField_class):
+-            return (<RealIntervalField_class>S).__prec >= prec
++            return (<RealIntervalField_class>S)._prec >= prec
+         if isinstance(S, sage.rings.abc.NumberField_quadratic):
+             return S.discriminant() > 0
+ 
+@@ -844,7 +844,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         cdef RealIntervalField_class right
+         left = self
+         right = other  # to access C structure
+-        return richcmp(left.__prec, right.__prec, op)
++        return richcmp(left._prec, right._prec, op)
+ 
+     def __reduce__(self):
+         """
+@@ -856,7 +856,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: loads(dumps(R)) == R
+             True
+         """
+-        return __create__RealIntervalField_version0, (self.__prec, self.sci_not)
++        return __create__RealIntervalField_version0, (self._prec, self.sci_not)
+ 
+     def random_element(self, *args, **kwds):
+         """
+@@ -997,7 +997,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RealIntervalField(200).name()
+             'IntervalRealIntervalField200'
+         """
+-        return "IntervalRealIntervalField%s"%(self.__prec)
++        return "IntervalRealIntervalField%s"%(self._prec)
+ 
+     def __hash__(self):
+         """
+@@ -1023,7 +1023,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RealIntervalField(200).precision()
+             200
+         """
+-        return self.__prec
++        return self._prec
+ 
+     prec = precision
+ 
+@@ -1187,7 +1187,7 @@ cdef class RealIntervalFieldElement(RingElement):
+             sage: TestSuite(x).run(skip=["_test_eq", "_test_pickling"])
+         """
+         cdef RealIntervalField_class p = <RealIntervalField_class?>parent
+-        mpfi_init2(self.value, p.__prec)
++        mpfi_init2(self.value, p._prec)
+         self._parent = p
+ 
+     def __init__(self, parent, x, int base=10):
+@@ -1864,7 +1864,7 @@ cdef class RealIntervalFieldElement(RingElement):
+ 
+         cdef mp_exp_t self_exp
+         cdef mpz_t self_zz
+-        cdef mpfr_prec_t prec = (<RealIntervalField_class>self._parent).__prec
++        cdef mpfr_prec_t prec = (<RealIntervalField_class>self._parent)._prec
+         cdef char *zz_str
+         cdef size_t zz_str_maxlen
+ 
+@@ -2977,7 +2977,7 @@ cdef class RealIntervalFieldElement(RingElement):
+             sage: RealIntervalField(200)(2.1).precision()
+             200
+         """
+-        return (<RealIntervalField_class>self._parent).__prec
++        return (<RealIntervalField_class>self._parent)._prec
+ 
+     prec = precision
+ 
+diff --git a/src/sage/rings/real_mpfr.pxd b/src/sage/rings/real_mpfr.pxd
+index 3549eccfd03..dd18e87715b 100644
+--- a/src/sage/rings/real_mpfr.pxd
++++ b/src/sage/rings/real_mpfr.pxd
+@@ -9,7 +9,7 @@ from sage.libs.mpfr.types cimport mpfr_prec_t
+ cdef class RealNumber(sage.structure.element.RingElement)  # forward decl
+ 
+ cdef class RealField_class(sage.rings.abc.RealField):
+-    cdef mpfr_prec_t __prec
++    cdef mpfr_prec_t _prec
+     cdef bint sci_not
+     cdef mpfr_rnd_t rnd
+     cdef object rnd_str
+diff --git a/src/sage/rings/real_mpfr.pyx b/src/sage/rings/real_mpfr.pyx
+index ea7ff07a216..7440fadd265 100644
+--- a/src/sage/rings/real_mpfr.pyx
++++ b/src/sage/rings/real_mpfr.pyx
+@@ -524,7 +524,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+         if prec < MPFR_PREC_MIN or prec > MPFR_PREC_MAX:
+             raise ValueError("prec (=%s) must be >= %s and <= %s" % (
+                 prec, MPFR_PREC_MIN, MPFR_PREC_MAX))
+-        self.__prec = prec
++        self._prec = prec
+         self.sci_not = sci_not
+ 
+         self.rnd = <mpfr_rnd_t>rnd
+@@ -561,7 +561,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: RealField(17,rnd='RNDD') # indirect doctest
+             Real Field with 17 bits of precision and rounding RNDD
+         """
+-        s = "Real Field with %s bits of precision"%self.__prec
++        s = "Real Field with %s bits of precision"%self._prec
+         if self.rnd != MPFR_RNDN:
+             s = s + " and rounding %s"%(self.rnd_str)
+         return s
+@@ -733,13 +733,13 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             return ZZtoRR(ZZ, self)
+         elif S is QQ:
+             return QQtoRR(QQ, self)
+-        elif (S is RDF or S is float) and self.__prec <= 53:
++        elif (S is RDF or S is float) and self._prec <= 53:
+             return double_toRR(S, self)
+         elif S is long:
+             return int_toRR(long, self)
+         elif S is int:
+             return int_toRR(int, self)
+-        elif isinstance(S, RealField_class) and S.prec() >= self.__prec:
++        elif isinstance(S, RealField_class) and S.prec() >= self._prec:
+             return RRtoRR(S, self)
+         elif QQ.has_coerce_map_from(S):
+             return QQtoRR(QQ, self) * QQ._internal_coerce_map_from(S)
+@@ -786,7 +786,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             return NotImplemented
+ 
+         _other = <RealField_class>other  # to access C structure
+-        return (self.__prec == _other.__prec and
++        return (self._prec == _other._prec and
+                 self.rnd == _other.rnd) == (op == Py_EQ)
+ 
+     def __reduce__(self):
+@@ -799,7 +799,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: loads(dumps(R)) == R
+             True
+         """
+-        return __create__RealField_version0, (self.__prec, self.sci_not, self.rnd_str)
++        return __create__RealField_version0, (self._prec, self.sci_not, self.rnd_str)
+ 
+     def construction(self):
+         r"""
+@@ -968,7 +968,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: RealField(100,rnd='RNDU').name()
+             'RealField100_2'
+         """
+-        return "RealField%s_%s"%(self.__prec,self.rnd)
++        return "RealField%s_%s"%(self._prec,self.rnd)
+ 
+     def __hash__(self):
+         """
+@@ -995,7 +995,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: RealField(20).precision()
+             20
+         """
+-        return Integer(self.__prec)
++        return Integer(self._prec)
+ 
+     prec=precision # an alias
+ 
+@@ -1031,7 +1031,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: R.to_prec(300)
+             Real Field with 300 bits of precision and rounding RNDZ
+         """
+-        if prec == self.__prec:
++        if prec == self._prec:
+             return self
+         else:
+             return RealField(prec, self.sci_not, self.rnd)
+@@ -1052,7 +1052,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             0.88622692545275801364908374167057259139877473
+         """
+         cdef RealNumber x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD: sig_on()
+         # The docs for mpfr_free_cache say "Free the cache used by
+         # the functions computing constants if needed (currently
+         # mpfr_const_log2, mpfr_const_pi and mpfr_const_euler)", so
+@@ -1062,7 +1062,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+         # functions, but this free is needed for them too!
+         mpfr_free_cache()
+         mpfr_const_pi(x.value, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def euler_constant(self):
+@@ -1091,10 +1091,10 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             0.91596559417721901505460351493
+         """
+         cdef RealNumber x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_free_cache()
+         mpfr_const_catalan(x.value, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log2(self):
+@@ -1111,10 +1111,10 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             0.69314718055994530941723212146
+         """
+         cdef RealNumber x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_free_cache()
+         mpfr_const_log2(x.value, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def random_element(self, min=-1, max=1, distribution=None):
+@@ -1181,9 +1181,9 @@ cdef class RealField_class(sage.rings.abc.RealField):
+         if n < 0:
+             raise ArithmeticError("n must be nonnegative")
+         x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_on()
+         mpfr_fac_ui(x.value, n, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def rounding_mode(self):
+@@ -1346,7 +1346,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             NaN
+         """
+         cdef RealField_class p = <RealField_class?>parent
+-        mpfr_init2(self.value, p.__prec)
++        mpfr_init2(self.value, p._prec)
+         self._parent = p
+ 
+     def __init__(self, parent, x=0, int base=10):
+@@ -1446,7 +1446,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             sage: numpy.array([1.000000000000000000000000000000000000]).dtype           # optional - numpy
+             dtype('O')
+         """
+-        if (<RealField_class>self._parent).__prec <= 53:
++        if (<RealField_class>self._parent)._prec <= 53:
+             return numpy_double_interface
+         else:
+             return numpy_object_interface
+@@ -2075,7 +2075,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             # This avoids the confusion a lot of people have with the last
+             # 1-2 binary digits being wrong due to rounding coming from
+             # representing numbers in binary.
+-            digits = <size_t>(((<RealField_class>self._parent).__prec - 1) * M_LN2_LN10)
++            digits = <size_t>(((<RealField_class>self._parent)._prec - 1) * M_LN2_LN10)
+             if digits < 2:
+                 digits = 2
+ 
+@@ -2303,7 +2303,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if sgn == 0:
+             return z
+ 
+-        cdef mpfr_prec_t prec = (<RealField_class>self._parent).__prec
++        cdef mpfr_prec_t prec = (<RealField_class>self._parent)._prec
+ 
+         if mpfr_inf_p(self.value):
+             mpz_set_ui(z.value, EXP_MAX+1-EXP_MIN)
+@@ -2757,7 +2757,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             sage: RealField(101)(-1).precision()
+             101
+         """
+-        return Integer((<RealField_class>self._parent).__prec)
++        return Integer((<RealField_class>self._parent)._prec)
+ 
+     prec = precision # alias
+ 
+@@ -3364,7 +3364,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         cdef unsigned long wordsize = sizeof(long)*8
+ 
+         cdef mpfr_prec_t prec
+-        prec = (<RealField_class>self._parent).__prec
++        prec = (<RealField_class>self._parent)._prec
+ 
+         # We round up the precision to the nearest multiple of wordsize.
+         cdef int rounded_prec
+@@ -3699,7 +3699,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         from .real_mpfi import RealIntervalField
+ 
+         cdef mpfr_rnd_t rnd = (<RealField_class>self._parent).rnd
+-        cdef mpfr_prec_t prec = (<RealField_class>self._parent).__prec
++        cdef mpfr_prec_t prec = (<RealField_class>self._parent)._prec
+ 
+         cdef RealNumber low, high
+         cdef int odd
+@@ -4249,9 +4249,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         cdef RealNumber x
+         if mpfr_cmp_ui(self.value, 0) >= 0:
+             x = self._new()
+-            if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_on()
++            if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_on()
+             mpfr_sqrt(x.value, self.value, (<RealField_class>self._parent).rnd)
+-            if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_off()
++            if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_off()
+             if all:
+                 if x.is_zero():
+                     return [x]
+@@ -4295,12 +4295,12 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             -1.42108547152020e-14
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_on()
+         mpfr_cbrt(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+-    def __pow(self, RealNumber exponent):
++    def _pow(self, RealNumber exponent):
+         """
+         Compute ``self`` raised to the power of exponent, rounded in the
+         direction specified by the parent of ``self``.
+@@ -4309,7 +4309,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+ 
+             sage: R = RealField(30)
+             sage: a = R('1.23456')
+-            sage: a.__pow(20.0)
++            sage: a._pow(20.0)
+             67.646297
+         """
+         cdef RealNumber x
+@@ -4435,9 +4435,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+                 return self._complex_number_().log(base)
+         if base is None or base == 'e':
+             x = self._new()
+-            if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++            if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+             mpfr_log(x.value, self.value, (<RealField_class>self._parent).rnd)
+-            if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++            if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+             return x
+         elif base == 10:
+             return self.log10()
+@@ -4476,9 +4476,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if self < 0:
+             return self._complex_number_().log(2)
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_log2(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log10(self):
+@@ -4513,9 +4513,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if self < 0:
+             return self._complex_number_().log(10)
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_log10(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log1p(self):
+@@ -4562,9 +4562,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if self < -1:
+             return (self+1.0)._complex_number_().log()
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_log1p(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def exp(self):
+@@ -4620,9 +4620,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             1.89117248253021e-10
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_exp2(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def exp10(self):
+@@ -4648,9 +4648,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             5.01187233627276e-33
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_exp10(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def expm1(self):
+@@ -4672,9 +4672,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             1.00000000000000e-16
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_expm1(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def eint(self):
+@@ -4694,9 +4694,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             -0.219383934395520
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_eint(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         return x
+ 
+     def cos(self):
+@@ -5125,9 +5125,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             _other = self._parent(other)
+ 
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > 10000: sig_on()
++        if (<RealField_class>self._parent)._prec > 10000: sig_on()
+         mpfr_agm(x.value, self.value, _other.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > 10000: sig_off()
++        if (<RealField_class>self._parent)._prec > 10000: sig_off()
+         return x
+ 
+     def erf(self):
+@@ -5280,9 +5280,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             0.886226925452758
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_gamma(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log_gamma(self):
+@@ -5306,10 +5306,10 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         cdef RealNumber x = self._new()
+         parent = (<RealField_class>self._parent)
+         if not mpfr_sgn(self.value) < 0:
+-            if parent.__prec > SIG_PREC_THRESHOLD:
++            if parent._prec > SIG_PREC_THRESHOLD:
+                 sig_on()
+             mpfr_lngamma(x.value, self.value, parent.rnd)
+-            if parent.__prec > SIG_PREC_THRESHOLD:
++            if parent._prec > SIG_PREC_THRESHOLD:
+                 sig_off()
+             return x
+         from sage.libs.mpmath.utils import call
+@@ -5534,7 +5534,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+ 
+         cdef RealField_class fld = <RealField_class>self._parent
+ 
+-        if algorithm == 0 and n <= 10000 / fld.__prec:
++        if algorithm == 0 and n <= 10000 / fld._prec:
+             # This is a rough estimate for when it is probably
+             # faster to call mpfr directly.  (This is a pretty
+             # good estimate on one particular machine, a
+@@ -5639,7 +5639,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+ 
+         from .real_mpfi import RealIntervalField
+ 
+-        cdef mpfr_prec_t prec = fld.__prec + 10
++        cdef mpfr_prec_t prec = fld._prec + 10
+ 
+         cdef RealNumber lower
+         cdef RealNumber upper
+diff --git a/src/sage/rings/ring.pxd b/src/sage/rings/ring.pxd
+index 9384f39f258..1322697688f 100644
+--- a/src/sage/rings/ring.pxd
++++ b/src/sage/rings/ring.pxd
+@@ -7,7 +7,7 @@ cdef class Ring(ParentWithGens):
+     cdef public object _one_element
+     cdef public object _zero_ideal
+     cdef public object _unit_ideal
+-    cdef public object __ideal_monoid
++    cdef public object _ideal_monoid
+ 
+ 
+ cdef class CommutativeRing(Ring):
+diff --git a/src/sage/rings/ring.pyx b/src/sage/rings/ring.pyx
+index 4cba2c9ba7f..8acf4383270 100644
+--- a/src/sage/rings/ring.pyx
++++ b/src/sage/rings/ring.pyx
+@@ -325,12 +325,12 @@ cdef class Ring(ParentWithGens):
+              by the ideal (x*y + y*z, x*x + x*y - y*x - y*y)
+ 
+         """
+-        if self.__ideal_monoid is not None:
+-            return self.__ideal_monoid
++        if self._ideal_monoid is not None:
++            return self._ideal_monoid
+         else:
+             from sage.rings.noncommutative_ideals import IdealMonoid_nc
+             M = IdealMonoid_nc(self)
+-            self.__ideal_monoid = M
++            self._ideal_monoid = M
+             return M
+ 
+     def ideal(self, *args, **kwds):
+@@ -1106,12 +1106,12 @@ cdef class Ring(ParentWithGens):
+             sage: R.<x>=QQ[]; R.ideal_monoid()
+             Monoid of ideals of Univariate Polynomial Ring in x over Rational Field
+         """
+-        if self.__ideal_monoid is not None:
+-            return self.__ideal_monoid
++        if self._ideal_monoid is not None:
++            return self._ideal_monoid
+         else:
+             from sage.rings.ideal_monoid import IdealMonoid
+             M = IdealMonoid(self)
+-            self.__ideal_monoid = M
++            self._ideal_monoid = M
+             return M
+ 
+     @cached_method
+@@ -1345,12 +1345,12 @@ cdef class CommutativeRing(Ring):
+             sage: R.<x>=QQ[]; R.ideal_monoid()
+             Monoid of ideals of Univariate Polynomial Ring in x over Rational Field
+         """
+-        if self.__ideal_monoid is not None:
+-            return self.__ideal_monoid
++        if self._ideal_monoid is not None:
++            return self._ideal_monoid
+         else:
+             from sage.rings.ideal_monoid import IdealMonoid
+             M = IdealMonoid(self)
+-            self.__ideal_monoid = M
++            self._ideal_monoid = M
+             return M
+ 
+     def extension(self, poly, name=None, names=None, **kwds):
+diff --git a/src/sage/schemes/elliptic_curves/mod_sym_num.pyx b/src/sage/schemes/elliptic_curves/mod_sym_num.pyx
+index 65742f28d72..296a6b5d075 100644
+--- a/src/sage/schemes/elliptic_curves/mod_sym_num.pyx
++++ b/src/sage/schemes/elliptic_curves/mod_sym_num.pyx
+@@ -730,7 +730,7 @@ cdef class ModularSymbolNumerical:
+         double _eps_plus, _eps_minus, _eps_unitary_plus, _eps_unitary_minus
+         public RealNumber _om1, _om2
+         object _E, _epsQs, _Mt, _Epari
+-        public dict __cached_methods
++        public dict _cached_methods
+         Rational _twist_q
+         Integer _D
+         int _global_sign
+@@ -785,7 +785,7 @@ cdef class ModularSymbolNumerical:
+         self._set_epsQs()
+         self._initialise_an_coefficients()
+         self._set_den_bounds()
+-        self.__cached_methods = {}
++        self._cached_methods = {}
+ 
+         # self.nc_sums = Integer(0)
+         # self.nc_direct = Integer(0)
+@@ -1357,7 +1357,7 @@ cdef class ModularSymbolNumerical:
+             sage: M(0)
+             1/5
+         """
+-        cadi = self.__cached_methods
++        cadi = self._cached_methods
+         for me in cadi:
+             cadi[me].clear_cache()
+ 
+@@ -1833,7 +1833,7 @@ cdef class ModularSymbolNumerical:
+ 
+         # if called with a previous (m,z,eps) but a larger eps,
+         # return the cached value
+-        cac = self.__cached_methods['_kappa'].cache
++        cac = self._cached_methods['_kappa'].cache
+         for ke in cac:
+             mm, zz, eeps = ke[0]
+             if mm == m and zz == z:
+@@ -2746,16 +2746,16 @@ cdef class ModularSymbolNumerical:
+             sage: ms = ModularSymbolNumerical(E)
+             sage: ms.manin_symbol(4,17)
+             1
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache # random
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache # random
+             {((1, 5, 1), ()): 1,
+             ((1, 15, 1), ()): -1,
+             ((1, 22, 1), ()): -1,
+             ((1, 32, 1), ()): 1}
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache[(1,15,1),()]
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache[(1,15,1),()]
+             -1
+             sage: ms.manin_symbol(4+17,-4)
+             0
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache # random
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache # random
+             {((1, 4, 1), ()): 0,
+             ((1, 5, 1), ()): 1,
+             ((1, 8, 1), ()): 1,
+@@ -2768,7 +2768,7 @@ cdef class ModularSymbolNumerical:
+             ((1, 29, 1), ()): 1,
+             ((1, 32, 1), ()): 1,
+             ((1, 33, 1), ()): 0}
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache[ (1,23,1), () ]
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache[ (1,23,1), () ]
+             -1
+         """
+         cdef:
+@@ -2903,7 +2903,7 @@ cdef class ModularSymbolNumerical:
+         #        "(%s :%s)"%(un, vn), level=3)
+ 
+         # is it already in the cache ?
+-        c = self.__cached_methods
++        c = self._cached_methods
+         if "_manin_symbol_with_cache" in c:
+             c = c["_manin_symbol_with_cache"]
+             if c.is_in_cache(un,vn,sign):
+@@ -2919,7 +2919,7 @@ cdef class ModularSymbolNumerical:
+         # we get for free additional values of Manin
+         # symbols that we cache, too.
+         # This sets 6 values in average
+-        c = self.__cached_methods["_manin_symbol_with_cache"]
++        c = self._cached_methods["_manin_symbol_with_cache"]
+ 
+         # (-v:u) = - (u:v)
+         oi = proj_normalise(self._N_E, -v, u, &un, &vn)
+diff --git a/src/sage/sets/set_from_iterator.py b/src/sage/sets/set_from_iterator.py
+index c47bb76920b..11f12e6d5ea 100644
+--- a/src/sage/sets/set_from_iterator.py
++++ b/src/sage/sets/set_from_iterator.py
+@@ -214,12 +214,12 @@ def __reduce__(self):
+             True
+         """
+         return (EnumeratedSetFromIterator,
+-                (self._func,                            # func
+-                 getattr(self, '_args', None),          # args
+-                 getattr(self, '_kwds', None),          # kwds
+-                 getattr(self, '__custom_name', None),  # name
+-                 self.category(),                       # category
+-                 hasattr(self, '_cache'))               # cache
++                (self._func,                    # func
++                 getattr(self, '_args', None),  # args
++                 getattr(self, '_kwds', None),  # kwds
++                 self.get_custom_name(),        # name
++                 self.category(),               # category
++                 hasattr(self, '_cache'))       # cache
+                 )
+ 
+     def _repr_(self):
+diff --git a/src/sage/structure/category_object.pxd b/src/sage/structure/category_object.pxd
+index ff3088ae9b6..83d3d4967d4 100644
+--- a/src/sage/structure/category_object.pxd
++++ b/src/sage/structure/category_object.pxd
+@@ -13,7 +13,7 @@ from sage.structure.sage_object cimport SageObject
+ cpdef check_default_category(default_category, category)
+ 
+ cdef class CategoryObject(SageObject):
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+     cdef _category
+     cdef public _base
+     cdef public _names
+diff --git a/src/sage/structure/category_object.pyx b/src/sage/structure/category_object.pyx
+index 3859f24095a..b6a7eaecb5b 100644
+--- a/src/sage/structure/category_object.pyx
++++ b/src/sage/structure/category_object.pyx
+@@ -113,7 +113,7 @@ cdef class CategoryObject(SageObject):
+             self._init_category_(category)
+ 
+     def __cinit__(self):
+-        self.__cached_methods = {}
++        self._cached_methods = {}
+         self._hash_value = -1
+ 
+     def _init_category_(self, category):
+@@ -491,7 +491,7 @@ cdef class CategoryObject(SageObject):
+         """
+         return self.variable_names()[0]
+ 
+-    def __temporarily_change_names(self, names, latex_names):
++    def _temporarily_change_names(self, names, latex_names):
+         """
+         This is used by the variable names context manager.
+ 
+@@ -844,7 +844,7 @@ cdef class CategoryObject(SageObject):
+         # Lookup a method or attribute from the category abstract classes.
+         # See __getattr__ above for documentation.
+         try:
+-            return self.__cached_methods[name]
++            return self._cached_methods[name]
+         except KeyError:
+             if self._category is None:
+                 # Usually, this will just raise AttributeError in
+@@ -854,7 +854,7 @@ cdef class CategoryObject(SageObject):
+                 cls = self._category.parent_class
+ 
+             attr = getattr_from_other_class(self, cls, name)
+-            self.__cached_methods[name] = attr
++            self._cached_methods[name] = attr
+             return attr
+ 
+     def __dir__(self):
+diff --git a/src/sage/structure/element.pxd b/src/sage/structure/element.pxd
+index 79e86d8a5c3..20c556b985e 100644
+--- a/src/sage/structure/element.pxd
++++ b/src/sage/structure/element.pxd
+@@ -176,7 +176,7 @@ cdef class Element(SageObject):
+ 
+ 
+ cdef class ElementWithCachedMethod(Element):
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+ cdef class ModuleElement(Element)       # forward declaration
+ 
+diff --git a/src/sage/structure/element.pyx b/src/sage/structure/element.pyx
+index ab6ee157a94..36da1c0cc12 100644
+--- a/src/sage/structure/element.pyx
++++ b/src/sage/structure/element.pyx
+@@ -379,6 +379,7 @@ cdef class Element(SageObject):
+     .. automethod:: __mod__
+     """
+     @cython.binding(False)
++    @cython.always_allow_keywords(False)
+     def __getmetaclass__(_):
+         from sage.misc.inherit_comparison import InheritComparisonMetaclass
+         return InheritComparisonMetaclass
+@@ -2356,18 +2357,18 @@ cdef class ElementWithCachedMethod(Element):
+             True
+         """
+         try:
+-            return self.__cached_methods[name]
++            return self._cached_methods[name]
+         except KeyError:
+             attr = getattr_from_other_class(self,
+                                         self._parent.category().element_class,
+                                         name)
+-            self.__cached_methods[name] = attr
++            self._cached_methods[name] = attr
+             return attr
+         except TypeError:
+             attr = getattr_from_other_class(self,
+                                         self._parent.category().element_class,
+                                         name)
+-            self.__cached_methods = {name : attr}
++            self._cached_methods = {name : attr}
+             return attr
+ 
+ 
+diff --git a/src/sage/structure/parent_gens.pyx b/src/sage/structure/parent_gens.pyx
+index ab531314458..cc6ffaace21 100644
+--- a/src/sage/structure/parent_gens.pyx
++++ b/src/sage/structure/parent_gens.pyx
+@@ -371,7 +371,7 @@ cdef class localvars:
+             self._latex_names = latex_names
+ 
+     def __enter__(self):
+-        self._orig = self._obj.__temporarily_change_names(self._names, self._latex_names)
++        self._orig = self._obj._temporarily_change_names(self._names, self._latex_names)
+ 
+     def __exit__(self, type, value, traceback):
+-        self._obj.__temporarily_change_names(self._orig[0], self._orig[1])
++        self._obj._temporarily_change_names(self._orig[0], self._orig[1])
+diff --git a/src/sage/structure/sage_object.pyx b/src/sage/structure/sage_object.pyx
+index 8474142eaa1..10000aef394 100644
+--- a/src/sage/structure/sage_object.pyx
++++ b/src/sage/structure/sage_object.pyx
+@@ -69,6 +69,8 @@ cdef class SageObject:
+         r"""
+         Change self so it prints as x, where x is a string.
+ 
++        If x is ``None``, the existing custom name is removed.
++
+         .. NOTE::
+ 
+            This is *only* supported for Python classes that derive
+@@ -91,6 +93,9 @@ cdef class SageObject:
+             sage: h.rename('x^300 + ...')
+             sage: h
+             x^300 + ...
++            sage: g.rename(None)
++            sage: g
++            x^3 + x - 5
+ 
+         Real numbers are not Python classes, so rename is not supported::
+ 
+@@ -110,15 +115,16 @@ cdef class SageObject:
+            a lot of memory.
+ 
+            To support them for a specific class, add a
+-           ``cdef public __custom_name`` attribute.
++           ``cdef public _SageObject__custom_name`` attribute.
+         """
+         if x is None:
+-            #if hasattr(self, '__custom_name'):
+-            # that's tested in reset_name anyway...
+             self.reset_name()
+         else:
+             try:
+-                self.__custom_name = str(x)
++                # TODO: after dropping support for Cython < 3.0.0, all
++                # the self._SageObject__custom_name in this class can be
++                # changed to self.__custom_name
++                self._SageObject__custom_name = str(x)
+             except AttributeError:
+                 raise NotImplementedError("object does not support renaming: %s" % self)
+ 
+@@ -138,8 +144,30 @@ cdef class SageObject:
+             sage: P
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if hasattr(self, '__custom_name'):
+-            del self.__custom_name
++        if hasattr(self, '_SageObject__custom_name'):
++            del self._SageObject__custom_name
++
++    def get_custom_name(self):
++        """
++        Return the custom name of this object, or ``None`` if it is not
++        renamed.
++
++        EXAMPLES::
++
++            sage: P.<x> = QQ[]
++            sage: P.get_custom_name() is None
++            True
++            sage: P.rename('A polynomial ring')
++            sage: P.get_custom_name()
++            'A polynomial ring'
++            sage: P.reset_name()
++            sage: P.get_custom_name() is None
++            True
++        """
++        try:
++            return self._SageObject__custom_name
++        except AttributeError:
++            return None
+ 
+     def __repr__(self):
+         """
+@@ -181,7 +209,7 @@ cdef class SageObject:
+             <sage.structure.sage_object.SageObject object at ...>
+         """
+         try:
+-            name = self.__custom_name
++            name = self._SageObject__custom_name
+             if name is not None:
+                 return name
+         except AttributeError:
+diff --git a/src/sage/topology/simplicial_set.py b/src/sage/topology/simplicial_set.py
+index 42cc3f77780..3ee14ae2da8 100644
+--- a/src/sage/topology/simplicial_set.py
++++ b/src/sage/topology/simplicial_set.py
+@@ -570,13 +570,12 @@ def __lt__(self, other):
+             return True
+         if self.degeneracies() and other.degeneracies() and self.degeneracies() != other.degeneracies():
+             return self.degeneracies() < other.degeneracies()
+-        if hasattr(self.nondegenerate(), '__custom_name'):
+-            if hasattr(other.nondegenerate(), '__custom_name'):
+-                return str(self) < str(other)
++        if self.nondegenerate().get_custom_name() is not None:
++            if other.nondegenerate().get_custom_name() is not None:
++                return self.nondegenerate().get_custom_name() < other.nondegenerate().get_custom_name()
+             return True
+ 
+-        if (hasattr(other, '__custom_name')
+-                or hasattr(other.nondegenerate(), '__custom_name')):
++        if other.nondegenerate().get_custom_name() is not None:
+             return False
+         return id(self) < id(other)
+ 
+@@ -793,8 +792,8 @@ def __copy__(self):
+         # dimension, the degeneracies, and the name (with a prime
+         # added).
+         sigma = AbstractSimplex(self._dim, degeneracies=self.degeneracies())
+-        if hasattr(self, '__custom_name'):
+-            sigma.rename(str(self) + "'")
++        if self.get_custom_name() is not None:
++            sigma.rename(self.get_custom_name() + "'")
+         return sigma
+ 
+     def __deepcopy__(self, memo):
+@@ -839,8 +838,8 @@ def __deepcopy__(self, memo):
+             return memo[underlying].apply_degeneracies(*degens)
+         except KeyError:
+             sigma = AbstractSimplex(underlying._dim)
+-            if hasattr(underlying, '__custom_name'):
+-                sigma.rename(str(self) + "'")
++            if underlying.get_custom_name() is not None:
++                sigma.rename(underlying.get_custom_name() + "'")
+             memo[underlying] = sigma
+             return sigma.apply_degeneracies(*degens)
+ 
+@@ -896,12 +895,12 @@ def _latex_(self):
+         """
+         if self._latex_name is not None:
+             return self._latex_name
+-        if hasattr(self, '__custom_name'):
+-            return str(self)
++        if self.get_custom_name() is not None:
++            return self.get_custom_name()
+         if self.nondegenerate()._latex_name is not None:
+             simplex = self.nondegenerate()._latex_name
+-        elif hasattr(self.nondegenerate(), '__custom_name'):
+-            simplex = str(self.nondegenerate())
++        elif self.nondegenerate().get_custom_name() is not None:
++            simplex = self.nondegenerate().get_custom_name()
+         else:
+             simplex = "\\Delta^{{{}}}".format(self._dim)
+         if self.degeneracies():
+diff --git a/src/sage/topology/simplicial_set_constructions.py b/src/sage/topology/simplicial_set_constructions.py
+index ae98821df8a..3a217286ac5 100644
+--- a/src/sage/topology/simplicial_set_constructions.py
++++ b/src/sage/topology/simplicial_set_constructions.py
+@@ -176,8 +176,7 @@ def __init__(self, data, ambient=None):
+         else:
+             SimplicialSet_finite.__init__(self, data)
+         if self == ambient:
+-            if hasattr(ambient, '__custom_name'):
+-                self.rename(str(ambient))
++            self.rename(ambient.get_custom_name())
+             self._latex_name = latex(ambient)
+         # When constructing the inclusion map, we do not need to check
+         # the validity of the morphism, and more importantly, we
diff --git a/srcpkgs/sagemath/patches/build-cython3.patch b/srcpkgs/sagemath/patches/build-cython3.patch
new file mode 100644
index 0000000000000..57d1ade89fc77
--- /dev/null
+++ b/srcpkgs/sagemath/patches/build-cython3.patch
@@ -0,0 +1,44 @@
+diff --git a/src/sage/ext/stdsage.pxd b/src/sage/ext/stdsage.pxd
+index 15abe13b7cd..e2bf7434f35 100644
+--- a/src/sage/ext/stdsage.pxd
++++ b/src/sage/ext/stdsage.pxd
+@@ -10,7 +10,7 @@ Standard C helper code for Cython modules
+ #                  http://www.gnu.org/licenses/
+ #*****************************************************************************
+ 
+-from cpython.object cimport Py_TYPE, PyTypeObject
++from cpython.object cimport Py_TYPE, PyTypeObject, PyObject
+ 
+ 
+ cdef inline PY_NEW(type t):
+@@ -19,7 +19,7 @@ cdef inline PY_NEW(type t):
+     :class:`Integer` where we change ``tp_new`` at runtime (Cython
+     optimizations assume that ``tp_new`` doesn't change).
+     """
+-    return (<PyTypeObject*>t).tp_new(t, <object>NULL, <object>NULL)
++    return (<PyTypeObject*>t).tp_new(t, <PyObject*>NULL, <PyObject*>NULL)
+ 
+ 
+ cdef inline void PY_SET_TP_NEW(type dst, type src):
+diff --git a/src/sage_setup/cython_options.py b/src/sage_setup/cython_options.py
+index 086aa070ca9..9725ce0e1af 100644
+--- a/src/sage_setup/cython_options.py
++++ b/src/sage_setup/cython_options.py
+@@ -10,13 +10,17 @@ def compiler_directives(profile: bool):
+         auto_pickle=False,
+         # Do not create __test__ dictionary automatically from docstrings
+         autotestdict=False,
++        binding=False,
++        c_api_binop_methods=True,
+         # Do not check for division by 0 (this is about 35% quicker than with check)
+         cdivision=True,
++        cpow=True,
+         # Embed a textual copy of the call signature in the docstring (to support tools like IPython)
+         embedsignature=True,
+         fast_getattr=True,
+         # Use Python 3 (including source code semantics) for module compilation
+         language_level="3",
++        legacy_implicit_noexcept=True,
+         # Enable support for late includes (make declarations in Cython code available to C include files)
+         preliminary_late_includes_cy28=True,
+         # Add hooks for Python profilers into the compiled C code
diff --git a/srcpkgs/sagemath/patches/fix-doctest-cython3.patch b/srcpkgs/sagemath/patches/fix-doctest-cython3.patch
new file mode 100644
index 0000000000000..4cff1fb1828db
--- /dev/null
+++ b/srcpkgs/sagemath/patches/fix-doctest-cython3.patch
@@ -0,0 +1,207 @@
+diff --git a/src/doc/en/thematic_tutorials/coercion_and_categories.rst b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+index de2349a9a3f..bb23331c151 100644
+--- a/src/doc/en/thematic_tutorials/coercion_and_categories.rst
++++ b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+@@ -105,7 +105,7 @@ it makes sense to build on top of the base class
+ This base class provides a lot more methods than a general parent::
+ 
+     sage: [p for p in dir(Field) if p not in dir(Parent)]
+-    ['__fraction_field',
++    ['_CommutativeRing__fraction_field',
+      '__iter__',
+      '__len__',
+      '__rxor__',
+diff --git a/src/sage/arith/srange.pyx b/src/sage/arith/srange.pyx
+index 156e548a11a..132cf93d085 100644
+--- a/src/sage/arith/srange.pyx
++++ b/src/sage/arith/srange.pyx
+@@ -84,7 +84,7 @@ def xsrange(start, end=None, step=1, universe=None, *, coerce=True, bint include
+     EXAMPLES::
+ 
+         sage: xsrange(10)
+-        <generator object at 0x...>
++        <...generator object at 0x...>
+         sage: for i in xsrange(1,5):
+         ....:     print(i)
+         1
+diff --git a/src/sage/combinat/sloane_functions.py b/src/sage/combinat/sloane_functions.py
+index c3cf9299093..e5c99b71fe7 100644
+--- a/src/sage/combinat/sloane_functions.py
++++ b/src/sage/combinat/sloane_functions.py
+@@ -9169,7 +9169,7 @@ class Sloane(SageObject):
+         ::
+ 
+             sage: sloane.__repr__
+-            <method-wrapper '__repr__' of Sloane object at 0x...>
++            <built-in method __repr__ of Sloane object at 0x...>
+             sage: sloane.__name__
+             Traceback (most recent call last):
+             ...
+diff --git a/src/sage/misc/cachefunc.pyx b/src/sage/misc/cachefunc.pyx
+index 8aa30a85272..2b1d38c12b9 100644
+--- a/src/sage/misc/cachefunc.pyx
++++ b/src/sage/misc/cachefunc.pyx
+@@ -50,7 +50,7 @@ be used::
+     sage: cython('''cpdef test_funct(x): return -x''')                          # optional - sage.misc.cython
+     sage: wrapped_funct = cached_function(test_funct, name='wrapped_funct')     # optional - sage.misc.cython
+     sage: wrapped_funct                                                         # optional - sage.misc.cython
+-    Cached version of <built-in function test_funct>
++    Cached version of <cyfunction test_funct at ...>
+     sage: wrapped_funct.__name__                                                # optional - sage.misc.cython
+     'wrapped_funct'
+     sage: wrapped_funct(5)                                                      # optional - sage.misc.cython
+@@ -82,9 +82,9 @@ approach is still needed for cpdef methods::
+     sage: cython(os.linesep.join(cython_code))                                  # optional - sage.misc.cython
+     sage: O = MyClass()                                                         # optional - sage.misc.cython
+     sage: O.direct_method                                                       # optional - sage.misc.cython
+-    Cached version of <method 'direct_method' of '...MyClass' objects>
++    Cached version of <cyfunction MyClass.direct_method at ...>
+     sage: O.wrapped_method                                                      # optional - sage.misc.cython
+-    Cached version of <built-in function test_meth>
++    Cached version of <cyfunction test_meth at ...>
+     sage: O.wrapped_method.__name__                                             # optional - sage.misc.cython
+     'wrapped_method'
+     sage: O.wrapped_method(5)                                                   # optional - sage.misc.cython
+@@ -270,6 +270,7 @@ Introspection works::
+         "some doc for a wrapped cython method"
+         return -x
+     sage: print(sage_getsource(O.direct_method))                                # optional - sage.misc.cython
++    @cached_method
+     def direct_method(self, x):
+         "Some doc for direct method"
+         return 2*x
+diff --git a/src/sage/misc/lazy_import.pyx b/src/sage/misc/lazy_import.pyx
+index c33a1e74efd..7fc73407ace 100644
+--- a/src/sage/misc/lazy_import.pyx
++++ b/src/sage/misc/lazy_import.pyx
+@@ -1095,7 +1095,7 @@ def lazy_import(module, names, as_=None, *,
+         sage: from sage.features import PythonModule
+         sage: lazy_import('ppl', 'equation', feature=PythonModule('ppl', spkg='pplpy', type='standard'))
+         sage: equation
+-        <built-in function equation>
++        <cyfunction equation at ...>
+         sage: lazy_import('PyNormaliz', 'NmzListConeProperties', feature=PythonModule('PyNormaliz', spkg='pynormaliz'))  # optional - pynormaliz
+         sage: NmzListConeProperties  # optional - pynormaliz
+         <built-in function NmzListConeProperties>
+diff --git a/src/sage/misc/lazy_list.pyx b/src/sage/misc/lazy_list.pyx
+index ba62c446b69..cd750933860 100644
+--- a/src/sage/misc/lazy_list.pyx
++++ b/src/sage/misc/lazy_list.pyx
+@@ -678,7 +678,7 @@ cdef class lazy_list_generic():
+             sage: from itertools import count
+             sage: from sage.misc.lazy_list import lazy_list
+             sage: iter(lazy_list(count()))
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+ 
+         ::
+ 
+diff --git a/src/sage/misc/sageinspect.py b/src/sage/misc/sageinspect.py
+index ce5e9987027..df8e6bf89ac 100644
+--- a/src/sage/misc/sageinspect.py
++++ b/src/sage/misc/sageinspect.py
+@@ -76,8 +76,8 @@ Cython functions::
+     sage: sage_getdoc(sage.rings.rational.make_rational).lstrip()
+     'Make a rational number ...'
+ 
+-    sage: sage_getsource(sage.rings.rational.make_rational)[4:]
+-    'make_rational(s):...'
++    sage: sage_getsource(sage.rings.rational.make_rational)
++    '@cython.binding(True)\ndef make_rational(s):...'
+ 
+ Python functions::
+ 
+diff --git a/src/sage/modules/free_module_element.pyx b/src/sage/modules/free_module_element.pyx
+index d5e8256b68c..c9af9bcbdf7 100644
+--- a/src/sage/modules/free_module_element.pyx
++++ b/src/sage/modules/free_module_element.pyx
+@@ -1634,7 +1634,7 @@ cdef class FreeModuleElement(Vector):   # abstract base class
+ 
+             sage: v = vector([1,2/3,pi])
+             sage: v.items()
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: list(v.items())
+             [(0, 1), (1, 2/3), (2, pi)]
+ 
+diff --git a/src/sage/rings/finite_rings/finite_field_base.pyx b/src/sage/rings/finite_rings/finite_field_base.pyx
+index 7e2eed91153..3a6db8995c6 100644
+--- a/src/sage/rings/finite_rings/finite_field_base.pyx
++++ b/src/sage/rings/finite_rings/finite_field_base.pyx
+@@ -328,7 +328,7 @@ cdef class FiniteField(Field):
+             sage: p = next_prime(2^64)
+             sage: k.<a> = FiniteField(p^2, impl="pari")
+             sage: it = iter(k); it
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: [next(it) for i in range(10)]
+             [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+ 
+diff --git a/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx b/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx
+index 41951687939..c6b67cba5fb 100644
+--- a/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx
++++ b/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx
+@@ -629,7 +629,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense):
+             sage: S.<x> = k['x',Frob]
+             sage: a = x^4 + 2*t*x^3 + 3*t^2*x^2 + (t^2 + t + 1)*x + 4*t + 3
+             sage: iter = a.right_irreducible_divisors(); iter
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+             sage: next(iter)   # random
+             x + 2*t^2 + 4*t + 4
+             sage: next(iter)   # random
+@@ -664,7 +664,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense):
+             sage: S.<x> = k['x',Frob]
+             sage: a = x^4 + 2*t*x^3 + 3*t^2*x^2 + (t^2 + t + 1)*x + 4*t + 3
+             sage: iter = a.left_irreducible_divisors(); iter
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+             sage: next(iter)  # random
+             x + 3*t + 3
+             sage: next(iter)  # random
+@@ -1052,7 +1052,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense):
+             sage: S.<x> = k['x',Frob]
+             sage: a = x^3 + (t^2 + 1)*x^2 + (2*t + 3)*x + t^2 + t + 2
+             sage: iter = a.factorizations(); iter
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+             sage: next(iter)   # random
+             (x + 3*t^2 + 4*t) * (x + 2*t^2) * (x + 4*t^2 + 4*t + 2)
+             sage: next(iter)   # random
+diff --git a/src/sage/structure/coerce_dict.pyx b/src/sage/structure/coerce_dict.pyx
+index a2e8443084c..ef86c6af35c 100644
+--- a/src/sage/structure/coerce_dict.pyx
++++ b/src/sage/structure/coerce_dict.pyx
+@@ -777,7 +777,7 @@ cdef class MonoDict:
+             sage: L[1] = None
+             sage: L[2] = True
+             sage: L.items()
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: sorted(L.items())
+             [(1, None), (2, True)]
+         """
+@@ -1452,7 +1452,7 @@ cdef class TripleDict:
+             sage: L = TripleDict()
+             sage: L[1,2,3] = None
+             sage: L.items()
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: list(L.items())
+             [((1, 2, 3), None)]
+         """
+diff --git a/src/sage/tests/cmdline.py b/src/sage/tests/cmdline.py
+index ad0c44aa274..f14cd2db768 100644
+--- a/src/sage/tests/cmdline.py
++++ b/src/sage/tests/cmdline.py
+@@ -491,9 +491,8 @@ def test_executable(args, input="", timeout=100.0, pydebug_ignore_warnings=False
+ 
+         sage: (out, err, ret) = test_executable(["sage", "--cython"])
+         sage: print(err)
+-        Cython (http://cython.org) is a compiler for code written in the
+-        Cython language.  Cython is based on Pyrex by Greg Ewing.
+         ...
++        cython: error: cython: Need at least one source file
+ 
+         sage: def has_tty():
+         ....:     try:
diff --git a/srcpkgs/sagemath/patches/get_patches b/srcpkgs/sagemath/patches/get_patches
index c2c5aa1c7eccd..8d50f9a3cd3b3 100755
--- a/srcpkgs/sagemath/patches/get_patches
+++ b/srcpkgs/sagemath/patches/get_patches
@@ -12,7 +12,7 @@ esac
 # get_pr <PR number> <description> [ext]
 get_pr() {
 	pr=$1
-	desc=$(echo "$2" | sed -e 's/ /_/g')
+	desc=$(echo "$2" | tr ' /' '_-')
 	ext=${3-diff}
 	$DO wget "$URL_BASE_PR$pr.$ext" -O "$pr-$desc.patch"
 }
@@ -24,6 +24,9 @@ cd $(dirname "$0")
 #get_pr  36018   "singular 4.3.2p4" # included in #35934
 get_pr  36046   "fix memory leak"
 
-# positive review
+# merged in 10.2.beta1
 get_pr  35934   "singular 4.3.2p7"
+get_pr  36109   "prepare for cython 3.0" # included in #36110
+
+# positive review
 get_pr  36006   "gmp 6.3.0"
diff --git a/srcpkgs/sagemath/template b/srcpkgs/sagemath/template
index 019ad37cb3a70..5d30bb0bfc163 100644
--- a/srcpkgs/sagemath/template
+++ b/srcpkgs/sagemath/template
@@ -1,12 +1,12 @@
 # Template file for 'sagemath'
 pkgname=sagemath
 version=10.1
-revision=2
+revision=3
 build_wrksrc=pkgs/sagemath-standard
 build_style=python3-module
 _bindir=/usr/lib/sagemath/$version/bin
 make_install_args="--install-scripts=$_bindir"
-hostmakedepends="m4 pkg-config python3-Cython0.29 python3-Jinja2
+hostmakedepends="m4 pkg-config python3-Cython python3-Jinja2
  python3-pkgconfig python3-setuptools"
 makedepends="arb-devel boost-devel brial-devel cliquer-devel ecl eclib-devel
  ecm-devel fflas-ffpack flintlib-devel gap-devel gd-devel giac-devel glpk-devel
@@ -18,7 +18,7 @@ makedepends="arb-devel boost-devel brial-devel cliquer-devel ecl eclib-devel
 depends="eclib-devel fflas-ffpack flintlib-devel gcc-fortran gd-devel
  gfan giac gsl-devel gzip libpng-devel linbox-devel m4ri-devel maxima-ecl
  mpfr-devel nauty ntl-devel palp pari-devel pari-elldata-small pari-galdata
- pari-galpol-small pari-seadata-small pkg-config python3-Cython0.29 python3-cypari2
+ pari-galpol-small pari-seadata-small pkg-config python3-Cython python3-cypari2
  python3-cysignals python3-devel python3-fpylll python3-ipython python3-lrcalc
  python3-ipython_ipykernel python3-jupyter_ipywidgets python3-matplotlib
  python3-memory_allocator python3-networkx python3-pip python3-pkgconfig

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
  2023-09-02 22:37 ` [PR PATCH] [Updated] " tornaria
@ 2023-09-02 23:33 ` ahesford
  2023-09-03  1:24 ` tornaria
                   ` (14 subsequent siblings)
  16 siblings, 0 replies; 18+ messages in thread
From: ahesford @ 2023-09-02 23:33 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 256 bytes --]

New comment by ahesford on void-packages repository

https://github.com/void-linux/void-packages/pull/45887#issuecomment-1703964058

Comment:
What is the benefit of building with Cython 3 in advance of an official Sage release that includes these changes?

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
  2023-09-02 22:37 ` [PR PATCH] [Updated] " tornaria
  2023-09-02 23:33 ` ahesford
@ 2023-09-03  1:24 ` tornaria
  2023-09-03  1:59 ` ahesford
                   ` (13 subsequent siblings)
  16 siblings, 0 replies; 18+ messages in thread
From: tornaria @ 2023-09-03  1:24 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 1077 bytes --]

New comment by tornaria on void-packages repository

https://github.com/void-linux/void-packages/pull/45887#issuecomment-1703979657

Comment:
> What is the benefit of building with Cython 3 in advance of an official Sage release that includes these changes?

Mainly that I can install cython 3 together with sagemath, which is quite useful for me to test beta releases of sagemath and proposed PRs in advance. But that's just me and I can build this locally myself.

Running this PR through CI is a way to make sure everything works fine for us, which is good feedback to give upstream before they do the next release, in particular https://github.com/sagemath/sage/pull/36110 is still not given positive review and the fact that we have tested it onthree different architectures is useful (unfortunately some deps are nocross).

I noticed that you made it so cython 3 can replace cython 0.29, but some  I'm now runing tests under this scenario, and there are a couple of failures (mainly because a mismatch in the type of cython functions between version 0.29 and 3.x).

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
                   ` (2 preceding siblings ...)
  2023-09-03  1:24 ` tornaria
@ 2023-09-03  1:59 ` ahesford
  2023-09-03  2:00 ` ahesford
                   ` (12 subsequent siblings)
  16 siblings, 0 replies; 18+ messages in thread
From: ahesford @ 2023-09-03  1:59 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 1007 bytes --]

New comment by ahesford on void-packages repository

https://github.com/void-linux/void-packages/pull/45887#issuecomment-1703985789

Comment:
You can also `ignorepkg=python3-Cython0.29` and install `python3-Cython` even if `sagemath` still requires the former.

Both Cython packages replace each other because that is needed to allow a clean update path to the current `sagemath` from an older package, and will be required in the future when `sagemath` moves to Cython 3.0; otherwise, the update would try to install the new Cython required for the Sage update, find that it conflicts with the version required by the old Sage, and abort. Unfortunately, there is also [some unexpected behavior](https://github.com/void-linux/xbps/issues/569) that will allow users to break package consistency by replacing the required Cython package with the other version. (This might be helpful for testing, because it allows quick swapping between Cython packages without having to replace the installed `sagemath`.)

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
                   ` (3 preceding siblings ...)
  2023-09-03  1:59 ` ahesford
@ 2023-09-03  2:00 ` ahesford
  2023-09-04 13:21 ` tornaria
                   ` (11 subsequent siblings)
  16 siblings, 0 replies; 18+ messages in thread
From: ahesford @ 2023-09-03  2:00 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 1002 bytes --]

New comment by ahesford on void-packages repository

https://github.com/void-linux/void-packages/pull/45887#issuecomment-1703985789

Comment:
You can `ignorepkg=python3-Cython0.29` and install `python3-Cython` even if `sagemath` still requires the former.

Both Cython packages replace each other because that is needed to allow a clean update path to the current `sagemath` from an older package, and will be required in the future when `sagemath` moves to Cython 3.0; otherwise, the update would try to install the new Cython required for the Sage update, find that it conflicts with the version required by the old Sage, and abort. Unfortunately, there is also [some unexpected behavior](https://github.com/void-linux/xbps/issues/569) that will allow users to break package consistency by replacing the required Cython package with the other version. (This might be helpful for testing, because it allows quick swapping between Cython packages without having to replace the installed `sagemath`.)

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
                   ` (4 preceding siblings ...)
  2023-09-03  2:00 ` ahesford
@ 2023-09-04 13:21 ` tornaria
  2023-09-05 11:57 ` [PR PATCH] [Updated] " tornaria
                   ` (10 subsequent siblings)
  16 siblings, 0 replies; 18+ messages in thread
From: tornaria @ 2023-09-04 13:21 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 1102 bytes --]

New comment by tornaria on void-packages repository

https://github.com/void-linux/void-packages/pull/45887#issuecomment-1705265625

Comment:
> You can `ignorepkg=python3-Cython0.29` and install `python3-Cython` even if `sagemath` still requires the former.
> 
> Both Cython packages replace each other because that is needed to allow a clean update path to the current `sagemath` from an older package, and will be required in the future when `sagemath` moves to Cython 3.0; otherwise, the update would try to install the new Cython required for the Sage update, find that it conflicts with the version required by the old Sage, and abort. Unfortunately, there is also [some unexpected behavior](https://github.com/void-linux/xbps/issues/569) that will allow users to break package consistency by replacing the required Cython package with the other version. (This might be helpful for testing, because it allows quick swapping between Cython packages without having to replace the installed `sagemath`.)

All of that is pointless, since sagemath built with cython 0.29 is broken with cython 3.0.

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PR PATCH] [Updated] sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
                   ` (5 preceding siblings ...)
  2023-09-04 13:21 ` tornaria
@ 2023-09-05 11:57 ` tornaria
  2023-09-06 14:50 ` ahesford
                   ` (9 subsequent siblings)
  16 siblings, 0 replies; 18+ messages in thread
From: tornaria @ 2023-09-05 11:57 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 2442 bytes --]

There is an updated pull request by tornaria against master on the void-packages repository

https://github.com/tornaria/void-packages sagemath-cython3
https://github.com/void-linux/void-packages/pull/45887

sagemath: use cython 3
#### Testing the changes
- I tested the changes in this PR: **briefly**

Since https://github.com/sagemath/sage/pull/36109 was merged upstream, it's now almost trivial to build sagemath with cython 3. This PR is pretty straightforward to understand:

 - commit 7f8e6514ffa54449a80e01fbae7f9355a7739a46 rebuilds `python3-pplpy` using cython 3. Nothing fancy here and this commit was already tested and only dropped since it turned out it had to be built with the same version of cython as sagemath itself.
 - commit df0d21871ce850efea3fc01f19a3d9e8c0d5f0d4 is just adding a few patches to sagemath, switching to cython 3, and bumping.

Description of added patches:
1. patch `36109-00pre.patch`: this is hand picked trivial patch that allows us to apply https://github.com/sagemath/sage/pull/36109 cleanly on 10.1 (since that PR is based on 10.1.beta0). All changes are comments!
2. patch `36109-prepare_for_cython_3.0.patch`: this is long, taken verbatim from https://github.com/sagemath/sage/pull/36109.diff, and is already merged.
3. patch `build-cython3.patch`: this is 2 lines changed plus 4 legacy build options added to cython setup.
4. patch `fix-doctest-cython3.patch`: this is a few fixes in doctests to accomodate minor changes in cython output (`__repr__` for cython classes, functions, and generators).

CC: @ahesford 

<!--
#### New package
- This new package conforms to the [package requirements](https://github.com/void-linux/void-packages/blob/master/CONTRIBUTING.md#package-requirements): **YES**|**NO**
-->

<!-- Note: If the build is likely to take more than 2 hours, please add ci skip tag as described in
https://github.com/void-linux/void-packages/blob/master/CONTRIBUTING.md#continuous-integration
and test at least one native build and, if supported, at least one cross build.
Ignore this section if this PR is not skipping CI.
-->
<!--
#### Local build testing
- I built this PR locally for my native architecture, (ARCH-LIBC)
- I built this PR locally for these architectures (if supported. mark crossbuilds):
  - aarch64-musl
  - armv7l
  - armv6l-musl
-->


A patch file from https://github.com/void-linux/void-packages/pull/45887.patch is attached

[-- Warning: decoded text below may be mangled, UTF-8 assumed --]
[-- Attachment #2: github-pr-sagemath-cython3-45887.patch --]
[-- Type: text/x-diff, Size: 463205 bytes --]

From f1bed676a846bb3f707d5ede2e26acf178916320 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gonzalo=20Tornar=C3=ADa?= <tornaria@cmat.edu.uy>
Date: Wed, 19 Jul 2023 21:04:33 -0300
Subject: [PATCH 1/2] python3-pplpy: update to 0.8.9, use cython 3.

---
 srcpkgs/python3-pplpy/template | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/srcpkgs/python3-pplpy/template b/srcpkgs/python3-pplpy/template
index 6c1e83aa091c7..d7a31aeab2023 100644
--- a/srcpkgs/python3-pplpy/template
+++ b/srcpkgs/python3-pplpy/template
@@ -1,19 +1,19 @@
 # Template file for 'python3-pplpy'
 pkgname=python3-pplpy
-version=0.8.7
-revision=3
+version=0.8.9
+revision=1
 build_style=python3-module
-hostmakedepends="python3-setuptools python3-Cython0.29"
+hostmakedepends="python3-setuptools python3-Cython"
 makedepends="python3-cysignals python3-gmpy2 python3-devel gmp-devel
  gmpxx-devel ppl-devel mpfr-devel libmpc-devel pari-devel"
 depends="python3"
 short_desc="Python wrapper to the C++ Parma Polyhedra Library (PPL)"
 maintainer="Gonzalo Tornaría <tornaria@cmat.edu.uy>"
 license="GPL-3.0-or-later"
-homepage="https://gitlab.com/videlec/pplpy"
-changelog="https://gitlab.com/videlec/pplpy/-/raw/master/CHANGES.txt"
+homepage="https://github.com/sagemath/pplpy"
+changelog="https://raw.githubusercontent.com/sagemath/pplpy/master/CHANGES.txt"
 distfiles="${PYPI_SITE}/p/pplpy/pplpy-${version}.tar.gz"
-checksum=500bd0f4ae1a76956fae7fcba77854f5ec3e64fce76803664983763c3f2bd8bd
+checksum=db7a3b571d6ef053f75137975e947c3a1c1e45a30bab90eaf215b4e5cc15797e
 
 do_check() {
 	PYTHONPATH=$(cd build/lib* && pwd) python3 setup.py test

From ba0c76366c1484c9bb69f12e4e569921a94928ba Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gonzalo=20Tornar=C3=ADa?= <tornaria@cmat.edu.uy>
Date: Tue, 29 Aug 2023 22:14:49 -0300
Subject: [PATCH 2/2] sagemath: use cython 3.0

---
 srcpkgs/sagemath/patches/36109-00pre.patch    |   50 +
 .../36109-prepare_for_cython_3.0.patch        | 9995 +++++++++++++++++
 srcpkgs/sagemath/patches/build-cython3.patch  |   44 +
 .../patches/fix-doctest-cython3.patch         |  207 +
 srcpkgs/sagemath/patches/get_patches          |    7 +-
 srcpkgs/sagemath/template                     |    6 +-
 6 files changed, 10304 insertions(+), 5 deletions(-)
 create mode 100644 srcpkgs/sagemath/patches/36109-00pre.patch
 create mode 100644 srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch
 create mode 100644 srcpkgs/sagemath/patches/build-cython3.patch
 create mode 100644 srcpkgs/sagemath/patches/fix-doctest-cython3.patch

diff --git a/srcpkgs/sagemath/patches/36109-00pre.patch b/srcpkgs/sagemath/patches/36109-00pre.patch
new file mode 100644
index 0000000000000..0a30d622f0f62
--- /dev/null
+++ b/srcpkgs/sagemath/patches/36109-00pre.patch
@@ -0,0 +1,50 @@
+Pre-patch so that PR #36109 applies cleanly on top of 10.1
+
+diff --git a/src/sage/categories/hopf_algebras_with_basis.py b/src/sage/categories/hopf_algebras_with_basis.py
+index ea401896ca0..29b6f48a86f 100644
+--- a/src/sage/categories/hopf_algebras_with_basis.py
++++ b/src/sage/categories/hopf_algebras_with_basis.py
+@@ -33,11 +33,11 @@ class HopfAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
+     We now show how to use a simple Hopf algebra, namely the group algebra of the dihedral group
+     (see also AlgebrasWithBasis)::
+ 
+-        sage: A = C.example(); A                                                        # optional - sage.groups
++        sage: A = C.example(); A                                                        # needs sage.groups
+         An example of Hopf algebra with basis: the group algebra of the
+          Dihedral group of order 6 as a permutation group over Rational Field
+-        sage: A.__custom_name = "A"                                                     # optional - sage.groups
+-        sage: A.category()                                                              # optional - sage.groups
++        sage: A.__custom_name = "A"                                                     # needs sage.groups
++        sage: A.category()                                                              # needs sage.groups
+         Category of finite dimensional hopf algebras with basis over Rational Field
+ 
+         sage: A.one_basis()                                                             # optional - sage.groups
+diff --git a/src/sage/categories/modules_with_basis.py b/src/sage/categories/modules_with_basis.py
+index 85a0d50239a..c0e29886b5f 100644
+--- a/src/sage/categories/modules_with_basis.py
++++ b/src/sage/categories/modules_with_basis.py
+@@ -66,9 +66,9 @@ class ModulesWithBasis(CategoryWithAxiom_over_base_ring):
+ 
+     Let `X` and `Y` be two modules with basis. We can build `Hom(X,Y)`::
+ 
+-        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.__custom_name = "X"             # optional - sage.modules
+-        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.__custom_name = "Y"             # optional - sage.modules
+-        sage: H = Hom(X, Y); H                                                          # optional - sage.modules
++        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.__custom_name = "X"             # needs sage.modules
++        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.__custom_name = "Y"             # needs sage.modules
++        sage: H = Hom(X, Y); H                                                          # needs sage.modules
+         Set of Morphisms from X to Y
+          in Category of finite dimensional vector spaces with basis over Rational Field
+ 
+diff --git a/src/sage/misc/cachefunc.pyx b/src/sage/misc/cachefunc.pyx
+index dac4c684f47..9b2916e547d 100644
+--- a/src/sage/misc/cachefunc.pyx
++++ b/src/sage/misc/cachefunc.pyx
+@@ -297,6 +297,7 @@ methods of extension classes, as long as they either support attribute assignmen
+ or have a public attribute of type ``<dict>`` called ``__cached_methods``. The
+ latter is easy::
+ 
++    sage: # needs sage.misc.cython
+     sage: cython_code = [
+     ....: "from sage.misc.cachefunc import cached_method",
+     ....: "cdef class MyClass:",
diff --git a/srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch b/srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch
new file mode 100644
index 0000000000000..93390f7eef992
--- /dev/null
+++ b/srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch
@@ -0,0 +1,9995 @@
+diff --git a/src/doc/en/thematic_tutorials/coercion_and_categories.rst b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+index 4efe68a2617..de2349a9a3f 100644
+--- a/src/doc/en/thematic_tutorials/coercion_and_categories.rst
++++ b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+@@ -106,7 +106,6 @@ This base class provides a lot more methods than a general parent::
+ 
+     sage: [p for p in dir(Field) if p not in dir(Parent)]
+     ['__fraction_field',
+-     '__ideal_monoid',
+      '__iter__',
+      '__len__',
+      '__rxor__',
+@@ -119,6 +118,7 @@ This base class provides a lot more methods than a general parent::
+      '_default_category',
+      '_gens',
+      '_ideal_class_',
++     '_ideal_monoid',
+      '_latex_names',
+      '_list',
+      '_one_element',
+diff --git a/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst b/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst
+index 51aec989810..553a946c4d8 100644
+--- a/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst
++++ b/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst
+@@ -298,7 +298,7 @@ http://docs.python.org/library/ for a complete list. ::
+         sage: el
+         bla
+         sage: el.__dict__
+-        {'__custom_name': 'bla', 'value': 42}
++        {'_SageObject__custom_name': 'bla', 'value': 42}
+ 
+     Lots of Sage objects are not Python objects but compiled Cython
+     objects. Python sees them as builtin objects and you do not have
+diff --git a/src/sage/algebras/letterplace/free_algebra_letterplace.pxd b/src/sage/algebras/letterplace/free_algebra_letterplace.pxd
+index d1d162c3b40..47a7275aba0 100644
+--- a/src/sage/algebras/letterplace/free_algebra_letterplace.pxd
++++ b/src/sage/algebras/letterplace/free_algebra_letterplace.pxd
+@@ -20,16 +20,15 @@ cdef class FreeAlgebra_letterplace_libsingular():
+     cdef ring* _lp_ring
+     cdef MPolynomialRing_libsingular _commutative_ring
+     cdef MPolynomialRing_libsingular _lp_ring_internal
+-    cdef object __ngens
++    cdef object _ngens
+ 
+ cdef class FreeAlgebra_letterplace(Algebra):
+     cdef MPolynomialRing_libsingular _commutative_ring
+     cdef MPolynomialRing_libsingular _current_ring
+     cdef int _degbound
+-    cdef int __ngens
++    cdef int _ngens
+     cdef int _nb_slackvars
+     cdef object __monoid
+-    cdef public object __custom_name
+     cdef str exponents_to_string(self, E)
+     cdef str exponents_to_latex(self, E)
+     cdef tuple _degrees
+diff --git a/src/sage/algebras/letterplace/free_algebra_letterplace.pyx b/src/sage/algebras/letterplace/free_algebra_letterplace.pyx
+index e9c70c9de29..53f0dfdea6d 100644
+--- a/src/sage/algebras/letterplace/free_algebra_letterplace.pyx
++++ b/src/sage/algebras/letterplace/free_algebra_letterplace.pyx
+@@ -255,7 +255,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+         """
+         if not isinstance(R, MPolynomialRing_libsingular):
+             raise TypeError("a letterplace algebra must be provided by a polynomial ring of type %s" % MPolynomialRing_libsingular)
+-        self.__ngens = R.ngens()
++        self._ngens = R.ngens()
+         if degrees is None:
+             varnames = R.variable_names()
+             self._nb_slackvars = 0
+@@ -269,12 +269,12 @@ cdef class FreeAlgebra_letterplace(Algebra):
+         self._current_ring = make_letterplace_ring(R, 1)
+         self._degbound = 1
+         if degrees is None:
+-            self._degrees = tuple([int(1)] * self.__ngens)
++            self._degrees = tuple([int(1)] * self._ngens)
+         else:
+             if (not isinstance(degrees, (tuple, list))) \
+-                    or len(degrees) != self.__ngens - self._nb_slackvars \
++                    or len(degrees) != self._ngens - self._nb_slackvars \
+                     or any(i <= 0 for i in degrees):
+-                raise TypeError("the generator degrees must be given by a list or tuple of %d positive integers" % (self.__ngens - 1))
++                raise TypeError("the generator degrees must be given by a list or tuple of %d positive integers" % (self._ngens - 1))
+             self._degrees = tuple([int(i) for i in degrees])
+             self.set_degbound(max(self._degrees))
+         self._populate_coercion_lists_(coerce_list=[base_ring])
+@@ -305,7 +305,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F.ngens()
+             3
+         """
+-        return self.__ngens - self._nb_slackvars
++        return self._ngens - self._nb_slackvars
+ 
+     def gen(self, i):
+         """
+@@ -327,17 +327,17 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F.gen(2)
+             c
+         """
+-        if i >= self.__ngens - self._nb_slackvars:
+-            raise ValueError("this free algebra only has %d generators" % (self.__ngens - self._nb_slackvars))
++        if i >= self._ngens - self._nb_slackvars:
++            raise ValueError("this free algebra only has %d generators" % (self._ngens - self._nb_slackvars))
+         if self._gens is not None:
+             return self._gens[i]
+         deg = self._degrees[i]
+         # self.set_degbound(deg)
+         p = self._current_ring.gen(i)
+         cdef int n
+-        cdef int j = self.__ngens - 1
++        cdef int j = self._ngens - 1
+         for n in range(1, deg):
+-            j += self.__ngens
++            j += self._ngens
+             p *= self._current_ring.gen(j)
+         return FreeAlgebraElement_letterplace(self, p)
+ 
+@@ -413,7 +413,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: FreeAlgebra(QQ, implementation='letterplace', names=['x']).is_commutative()
+             True
+         """
+-        return self.__ngens - self._nb_slackvars <= 1
++        return self._ngens - self._nb_slackvars <= 1
+ 
+     def is_field(self, proof=True):
+         """
+@@ -430,7 +430,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F.is_field()
+             False
+         """
+-        return (not (self.__ngens - self._nb_slackvars)) and self._base.is_field(proof=proof)
++        return (not (self._ngens - self._nb_slackvars)) and self._base.is_field(proof=proof)
+ 
+     def _repr_(self):
+         """
+@@ -446,7 +446,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F
+             Free Associative Unital Algebra on 3 generators (x, y, z) over Rational Field
+         """
+-        return "Free Associative Unital Algebra on %d generators %s over %s" % (self.__ngens - self._nb_slackvars, self.gens(), self._base)
++        return "Free Associative Unital Algebra on %d generators %s over %s" % (self._ngens - self._nb_slackvars, self.gens(), self._base)
+ 
+     def _latex_(self):
+         r"""
+@@ -586,7 +586,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+               generated free abelian monoid.
+               In principle, this is correct, but it is not implemented, yet.>
+         """
+-        cdef int ngens = self.__ngens
++        cdef int ngens = self._ngens
+         cdef int nblocks = len(E) // ngens
+         cdef int i, j, base, exp, var_ind
+         cdef list out = []
+@@ -618,7 +618,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: latex(-(a*b*(z+1)-c)^2)     # indirect doctest
+             \left(2 z + 1\right) a b a b + \left(z + 1\right) a b c + \left(z + 1\right) c a b - c c
+         """
+-        cdef int ngens = self.__ngens
++        cdef int ngens = self._ngens
+         cdef int nblocks = len(E) // ngens
+         cdef int i, j, base, exp, var_ind
+         cdef list out = []
+@@ -678,7 +678,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+         cdef list out = []
+         C = self.current_ring()
+         cdef FreeAlgebraElement_letterplace x
+-        ngens = self.__ngens
++        ngens = self._ngens
+         cdef list G = [C(x._poly) for x in g]
+         from sage.groups.perm_gps.permgroup_named import CyclicPermutationGroup
+         CG = CyclicPermutationGroup(C.ngens())
+@@ -811,7 +811,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             l = len(e)
+             break
+         cdef dict out = {}
+-        self.set_degbound(l // self.__ngens)
++        self.set_degbound(l // self._ngens)
+         cdef Py_ssize_t n = self._current_ring.ngens()
+         for e, c in D.iteritems():
+             out[tuple(e) + (0,) * (n - l)] = c
+@@ -896,7 +896,7 @@ cdef class FreeAlgebra_letterplace_libsingular():
+         self._commutative_ring = commutative_ring
+ 
+     def __init__(self, commutative_ring, degbound):
+-        self.__ngens = commutative_ring.ngens() * degbound
++        self._ngens = commutative_ring.ngens() * degbound
+ 
+     def __dealloc__(self):
+         r"""
+diff --git a/src/sage/algebras/quatalg/quaternion_algebra_element.pyx b/src/sage/algebras/quatalg/quaternion_algebra_element.pyx
+index f6e87440fe9..8cb7e848fd0 100644
+--- a/src/sage/algebras/quatalg/quaternion_algebra_element.pyx
++++ b/src/sage/algebras/quatalg/quaternion_algebra_element.pyx
+@@ -1700,15 +1700,15 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra
+             x, y, z, w = v
+         cdef NumberFieldElement a = <NumberFieldElement>(parent._base(parent._a))
+         cdef NumberFieldElement b = <NumberFieldElement>(parent._base(parent._b))
+-        fmpz_poly_set_ZZX(self.x, (<NumberFieldElement>x).__numerator)
+-        fmpz_poly_set_ZZX(self.y, (<NumberFieldElement>y).__numerator)
+-        fmpz_poly_set_ZZX(self.z, (<NumberFieldElement>z).__numerator)
+-        fmpz_poly_set_ZZX(self.w, (<NumberFieldElement>w).__numerator)
++        fmpz_poly_set_ZZX(self.x, (<NumberFieldElement>x)._numerator)
++        fmpz_poly_set_ZZX(self.y, (<NumberFieldElement>y)._numerator)
++        fmpz_poly_set_ZZX(self.z, (<NumberFieldElement>z)._numerator)
++        fmpz_poly_set_ZZX(self.w, (<NumberFieldElement>w)._numerator)
+ 
+-        ZZ_to_mpz(T1, &(<NumberFieldElement>x).__denominator)
+-        ZZ_to_mpz(T2, &(<NumberFieldElement>y).__denominator)
+-        ZZ_to_mpz(t3, &(<NumberFieldElement>z).__denominator)
+-        ZZ_to_mpz(t4, &(<NumberFieldElement>w).__denominator)
++        ZZ_to_mpz(T1, &(<NumberFieldElement>x)._denominator)
++        ZZ_to_mpz(T2, &(<NumberFieldElement>y)._denominator)
++        ZZ_to_mpz(t3, &(<NumberFieldElement>z)._denominator)
++        ZZ_to_mpz(t4, &(<NumberFieldElement>w)._denominator)
+ 
+         mpz_lcm(self.d, T1, T2)
+         mpz_lcm(self.d, self.d, t3)
+@@ -1724,10 +1724,10 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra
+         fmpz_poly_scalar_mul_mpz(self.z, self.z, t3)
+         fmpz_poly_scalar_mul_mpz(self.w, self.w, t4)
+ 
+-        fmpz_poly_set_ZZX(self.a, a.__numerator)     # we will assume that the denominator of a and b are 1
+-        fmpz_poly_set_ZZX(self.b, b.__numerator)
++        fmpz_poly_set_ZZX(self.a, a._numerator)     # we will assume that the denominator of a and b are 1
++        fmpz_poly_set_ZZX(self.b, b._numerator)
+ 
+-        fmpz_poly_set_ZZX(self.modulus, (<NumberFieldElement>x).__fld_numerator.x)  # and same for the modulus
++        fmpz_poly_set_ZZX(self.modulus, (<NumberFieldElement>x)._fld_numerator.x)  # and same for the modulus
+ 
+     def __getitem__(self, int i):
+         """
+@@ -1756,17 +1756,17 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra
+         cdef NumberFieldElement item = el._new()
+ 
+         if i == 0:
+-            fmpz_poly_get_ZZX(item.__numerator, self.x)
++            fmpz_poly_get_ZZX(item._numerator, self.x)
+         elif i == 1:
+-            fmpz_poly_get_ZZX(item.__numerator, self.y)
++            fmpz_poly_get_ZZX(item._numerator, self.y)
+         elif i == 2:
+-            fmpz_poly_get_ZZX(item.__numerator, self.z)
++            fmpz_poly_get_ZZX(item._numerator, self.z)
+         elif i == 3:
+-            fmpz_poly_get_ZZX(item.__numerator, self.w)
++            fmpz_poly_get_ZZX(item._numerator, self.w)
+         else:
+             raise IndexError("quaternion element index out of range")
+ 
+-        mpz_to_ZZ(&item.__denominator, self.d)
++        mpz_to_ZZ(&item._denominator, self.d)
+ 
+         return item
+ 
+diff --git a/src/sage/categories/hopf_algebras_with_basis.py b/src/sage/categories/hopf_algebras_with_basis.py
+index 1be964cb6c9..615fc4eae06 100644
+--- a/src/sage/categories/hopf_algebras_with_basis.py
++++ b/src/sage/categories/hopf_algebras_with_basis.py
+@@ -36,7 +36,7 @@ class HopfAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
+         sage: A = C.example(); A                                                        # needs sage.groups
+         An example of Hopf algebra with basis: the group algebra of the
+          Dihedral group of order 6 as a permutation group over Rational Field
+-        sage: A.__custom_name = "A"                                                     # needs sage.groups
++        sage: A.rename("A")                                                             # needs sage.groups
+         sage: A.category()                                                              # needs sage.groups
+         Category of finite dimensional hopf algebras with basis over Rational Field
+ 
+diff --git a/src/sage/categories/modules_with_basis.py b/src/sage/categories/modules_with_basis.py
+index 65fd47cb890..fc1857f0c8e 100644
+--- a/src/sage/categories/modules_with_basis.py
++++ b/src/sage/categories/modules_with_basis.py
+@@ -66,8 +66,8 @@ class ModulesWithBasis(CategoryWithAxiom_over_base_ring):
+ 
+     Let `X` and `Y` be two modules with basis. We can build `Hom(X,Y)`::
+ 
+-        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.__custom_name = "X"             # needs sage.modules
+-        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.__custom_name = "Y"             # needs sage.modules
++        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.rename("X")                     # needs sage.modules
++        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.rename("Y")                     # needs sage.modules
+         sage: H = Hom(X, Y); H                                                          # needs sage.modules
+         Set of Morphisms from X to Y
+          in Category of finite dimensional vector spaces with basis over Rational Field
+diff --git a/src/sage/combinat/cluster_complex.py b/src/sage/combinat/cluster_complex.py
+index edc4f235aeb..e263d983887 100644
+--- a/src/sage/combinat/cluster_complex.py
++++ b/src/sage/combinat/cluster_complex.py
+@@ -222,10 +222,6 @@ def __init__(self, W, k, coxeter_element, algorithm):
+         self._W = W
+         self._w0 = w
+         self._k = k
+-        if k == 1:
+-            self.__custom_name = 'Cluster complex'
+-        else:
+-            self.__custom_name = 'Multi-cluster complex'
+ 
+         self.set_immutable()
+ 
+@@ -271,7 +267,10 @@ def _repr_(self):
+             sage: ClusterComplex(['A', 2])._repr_()
+             "Cluster complex of type ['A', 2] with 5 vertices and 5 facets"
+         """
+-        name = self.__custom_name
++        if self._k == 1:
++            name = 'Cluster complex'
++        else:
++            name = 'Multi-cluster complex'
+         name += (' of type %s with %s vertices and %s facets'
+                  % (self.cartan_type(), len(self.vertices()),
+                     len(self._facets)))
+diff --git a/src/sage/combinat/integer_lists/base.pxd b/src/sage/combinat/integer_lists/base.pxd
+index ecb5550a9cf..3d373a64fe0 100644
+--- a/src/sage/combinat/integer_lists/base.pxd
++++ b/src/sage/combinat/integer_lists/base.pxd
+@@ -12,4 +12,4 @@ cdef class IntegerListsBackend():
+     cdef readonly min_part, max_part
+     cdef readonly min_slope, max_slope
+     cdef readonly Envelope floor, ceiling
+-    cdef public dict __cached_methods  # Support cached_method
++    cdef public dict _cached_methods  # Support cached_method
+diff --git a/src/sage/combinat/subword_complex.py b/src/sage/combinat/subword_complex.py
+index b7489bdf754..de7eefe946e 100644
+--- a/src/sage/combinat/subword_complex.py
++++ b/src/sage/combinat/subword_complex.py
+@@ -1131,7 +1131,6 @@ def __init__(self, Q, w, algorithm="inductive"):
+         SimplicialComplex.__init__(self, maximal_faces=Fs,
+                                    maximality_check=False,
+                                    category=cat)
+-        self.__custom_name = 'Subword complex'
+         self._W = W
+         try:
+             T = W.coxeter_matrix().coxeter_type()
+diff --git a/src/sage/cpython/cython_metaclass.h b/src/sage/cpython/cython_metaclass.h
+index da06ab75a6b..ecf7f973c3e 100644
+--- a/src/sage/cpython/cython_metaclass.h
++++ b/src/sage/cpython/cython_metaclass.h
+@@ -52,6 +52,16 @@ static CYTHON_INLINE int Sage_PyType_Ready(PyTypeObject* t)
+     if (r < 0)
+         return r;
+ 
++#if PY_VERSION_HEX >= 0x03050000
++    // Cython 3 sets Py_TPFLAGS_HEAPTYPE before calling PyType_Ready,
++    // and resets just after the call. We need to reset it earlier,
++    // since otherwise the call to metaclass.__init__ below may have
++    // illegal memory accesses.
++    // See also:
++    // https://github.com/cython/cython/issues/3603
++    t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE;
++#endif
++
+     /* Set or get metaclass (the type of t) */
+     PyTypeObject* metaclass;
+ 
+diff --git a/src/sage/cpython/cython_metaclass.pyx b/src/sage/cpython/cython_metaclass.pyx
+index a8fe853661d..a8fa92fc1a8 100644
+--- a/src/sage/cpython/cython_metaclass.pyx
++++ b/src/sage/cpython/cython_metaclass.pyx
+@@ -19,13 +19,16 @@ file if you are using one).
+ 
+ In the extension type (a.k.a. ``cdef class``) for which you want to
+ define a metaclass, define a method ``__getmetaclass__`` with a single
+-unused argument. This method should return a type to be used as
++unused argument, and turn off the Cython directive
++``always_allow_keywords``. This method should return a type to be used as
+ metaclass:
+ 
+ .. code-block:: cython
+ 
++    cimport cython
+     cimport sage.cpython.cython_metaclass
+     cdef class MyCustomType():
++        @cython.always_allow_keywords(False)
+         def __getmetaclass__(_):
+             from foo import MyMetaclass
+             return MyMetaclass
+@@ -63,8 +66,10 @@ EXAMPLES::
+ 
+     sage: cython(                                                                       # needs sage.misc.cython
+     ....: '''
++    ....: cimport cython
+     ....: cimport sage.cpython.cython_metaclass
+     ....: cdef class MyCustomType():
++    ....:     @cython.always_allow_keywords(False)
+     ....:     def __getmetaclass__(_):
+     ....:         class MyMetaclass(type):
+     ....:             def __init__(*args):
+@@ -101,8 +106,10 @@ returns a non-type::
+ 
+     sage: cython(                                                                       # needs sage.misc.cython
+     ....: '''
++    ....: cimport cython
+     ....: cimport sage.cpython.cython_metaclass
+     ....: cdef class MyCustomType():
++    ....:     @cython.always_allow_keywords(False)
+     ....:     def __getmetaclass__(_):
+     ....:         return 2
+     ....: ''')
+diff --git a/src/sage/cpython/getattr.pyx b/src/sage/cpython/getattr.pyx
+index 3f603b98040..16f649c083d 100644
+--- a/src/sage/cpython/getattr.pyx
++++ b/src/sage/cpython/getattr.pyx
+@@ -271,7 +271,7 @@ cpdef getattr_from_other_class(self, cls, name):
+ 
+     Caveat: lazy attributes work with extension types only
+     if they allow attribute assignment or have a public attribute
+-    ``__cached_methods`` of type ``<dict>``. This condition
++    ``_cached_methods`` of type ``<dict>``. This condition
+     is satisfied, e.g., by any class that is derived from
+     :class:`Parent`::
+ 
+diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd
+index bdd49225ff2..030c9defa45 100644
+--- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd
++++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd
+@@ -8,7 +8,7 @@ from .polyhedron_face_lattice           cimport PolyhedronFaceLattice
+ 
+ @cython.final
+ cdef class CombinatorialPolyhedron(SageObject):
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+     # Do not assume any of those attributes to be initialized, use the corresponding methods instead.
+     cdef tuple _Vrep                       # the names of VRep, if they exist
+diff --git a/src/sage/groups/perm_gps/permgroup_element.pxd b/src/sage/groups/perm_gps/permgroup_element.pxd
+index a2ac8f20eaa..0a584745f96 100644
+--- a/src/sage/groups/perm_gps/permgroup_element.pxd
++++ b/src/sage/groups/perm_gps/permgroup_element.pxd
+@@ -22,7 +22,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement):
+     cpdef PermutationGroupElement _generate_new_GAP(self, old)
+     cpdef _gap_list(self)
+     cpdef domain(self)
+-    cdef public __custom_name
++    cdef public _SageObject__custom_name
+     cpdef list _act_on_list_on_position(self, list x)
+     cpdef ClonableIntArray _act_on_array_on_position(self, ClonableIntArray x)
+     cpdef ETuple _act_on_etuple_on_position(self, ETuple x)
+diff --git a/src/sage/interfaces/interface.py b/src/sage/interfaces/interface.py
+index f8237d3ad94..3180113c9c7 100644
+--- a/src/sage/interfaces/interface.py
++++ b/src/sage/interfaces/interface.py
+@@ -1169,11 +1169,8 @@ def __repr__(self):
+             s = cr
+         else:
+             s = self._repr_()
+-        if self._name in s:
+-            try:
+-                s = s.replace(self._name, getattr(self, '__custom_name'))
+-            except AttributeError:
+-                pass
++        if self._name in s and self.get_custom_name() is not None:
++            s = s.replace(self._name, self.get_custom_name())
+         if cr:
+             self._cached_repr = s
+         return s
+diff --git a/src/sage/interfaces/singular.py b/src/sage/interfaces/singular.py
+index 4b5c76e2bfa..705fa6f66e1 100644
+--- a/src/sage/interfaces/singular.py
++++ b/src/sage/interfaces/singular.py
+@@ -1400,8 +1400,8 @@ def _repr_(self):
+         """
+         s = super(SingularElement, self)._repr_()
+         if self._name in s:
+-            if (not hasattr(self, "__custom_name")) and self.type() == 'matrix':
+-                s = self.parent().eval('pmat(%s,20)'%(self.name()))
++            if self.get_custom_name() is None and self.type() == 'matrix':
++                s = self.parent().eval('pmat(%s,20)' % (self.name()))
+         return s
+ 
+     def __copy__(self):
+diff --git a/src/sage/libs/arb/arith.pyx b/src/sage/libs/arb/arith.pyx
+index d885f97b238..3b32fe7e8ed 100644
+--- a/src/sage/libs/arb/arith.pyx
++++ b/src/sage/libs/arb/arith.pyx
+@@ -81,5 +81,5 @@ def hilbert_class_polynomial(D):
+     cdef long n = D
+     cdef Polynomial_integer_dense_flint poly
+     poly = PolynomialRing(ZZ, "x", implementation="FLINT")()
+-    acb_modular_hilbert_class_poly(poly.__poly, n)
++    acb_modular_hilbert_class_poly(poly._poly, n)
+     return poly
+diff --git a/src/sage/libs/coxeter3/coxeter.pxd b/src/sage/libs/coxeter3/coxeter.pxd
+index 9d5cb2a3f5d..dbd2b8a61c6 100644
+--- a/src/sage/libs/coxeter3/coxeter.pxd
++++ b/src/sage/libs/coxeter3/coxeter.pxd
+@@ -29,6 +29,3 @@ cdef class CoxGroupElement:
+     cdef CoxGroup _parent_group
+     cdef CoxGroupElement _new(self)
+     cpdef CoxGroup parent_group(self)
+-
+-cdef class CoxGraph:
+-    cdef c_CoxGraph x
+diff --git a/src/sage/libs/gap/element.pyx b/src/sage/libs/gap/element.pyx
+index 1dc53c81f67..478caf9f9d0 100644
+--- a/src/sage/libs/gap/element.pyx
++++ b/src/sage/libs/gap/element.pyx
+@@ -720,7 +720,7 @@ cdef class GapElement(RingElement):
+             ...
+             AttributeError: 'some_name' does not define a GAP function
+         """
+-        if name in ('__dict__', '_getAttributeNames', '__custom_name', 'keys'):
++        if name in ('__dict__', '_getAttributeNames', '_SageObject__custom_name', 'keys'):
+             raise AttributeError('Python special name, not a GAP function.')
+         try:
+             proxy = make_GapElement_MethodProxy\
+diff --git a/src/sage/libs/gap/gap_includes.pxd b/src/sage/libs/gap/gap_includes.pxd
+index 840b8a0042e..1ed4378a6c7 100644
+--- a/src/sage/libs/gap/gap_includes.pxd
++++ b/src/sage/libs/gap/gap_includes.pxd
+@@ -144,3 +144,18 @@ cdef extern from "gap/stringobj.h" nogil:
+     bint IS_STRING(Obj obj)
+     bint IsStringConv(Obj obj)
+     Obj NEW_STRING(Int)
++
++
++cdef extern from "<structmember.h>" nogil:
++    """
++    /* Hack: Cython 3.0 automatically includes <structmember.h>, which
++     * defines several macros that collides with enum definitions in
++     * gap/objects.h. We need to include the header explicitly and
++     * undefine these macros.
++     */
++    #undef T_INT
++    #undef T_STRING
++    #undef T_CHAR
++    #undef T_BOOL
++    """
++    pass
+diff --git a/src/sage/libs/lcalc/lcalc_Lfunction.pxd b/src/sage/libs/lcalc/lcalc_Lfunction.pxd
+index 5edf0844f3e..1d595180a6f 100644
+--- a/src/sage/libs/lcalc/lcalc_Lfunction.pxd
++++ b/src/sage/libs/lcalc/lcalc_Lfunction.pxd
+@@ -99,19 +99,19 @@ cdef extern from "lcalc_sage.h":
+ ################
+ 
+ # strange bug, I can't compile without this trick ???
+-# it's only used in __typedN
++# it's only used in _typedN
+ ctypedef double Double
+ 
+ cdef class Lfunction:
+     cdef void *thisptr
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r)
+-    cdef c_Complex __value(self,c_Complex s,int derivative)
+-    cdef c_Complex __hardy_z_function(self,c_Complex s)
+-    cdef int __compute_rank(self)
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r)
++    cdef c_Complex _value(self,c_Complex s,int derivative)
++    cdef c_Complex _hardy_z_function(self,c_Complex s)
++    cdef int _compute_rank(self)
+     #strange bug, replacing Double with double gives me a compile error
+-    cdef Double __typedN(self, double T)
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize,doublevec *result)
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec* result)
++    cdef Double _typedN(self, double T)
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize,doublevec *result)
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec* result)
+ 
+     cdef str _repr
+ 
+diff --git a/src/sage/libs/lcalc/lcalc_Lfunction.pyx b/src/sage/libs/lcalc/lcalc_Lfunction.pyx
+index 6e9005c502b..7b871ed049f 100644
+--- a/src/sage/libs/lcalc/lcalc_Lfunction.pyx
++++ b/src/sage/libs/lcalc/lcalc_Lfunction.pyx
+@@ -99,7 +99,7 @@ cdef class Lfunction:
+             tmpc=CCC(residue[i])
+             r[i+1] = new_Complex(mpfr_get_d(tmpc.__re, MPFR_RNDN), mpfr_get_d(tmpc.__im, MPFR_RNDN))
+ 
+-        self.__init_fun(NAME, what_type, dirichlet_coefficient, Period, q,  w,  A, g, l, n_poles, p, r)
++        self._init_fun(NAME, what_type, dirichlet_coefficient, Period, q,  w,  A, g, l, n_poles, p, r)
+ 
+         if name:
+             name += ': '
+@@ -180,7 +180,7 @@ cdef class Lfunction:
+         """
+         cdef ComplexNumber complexified_s = CCC(s)
+         cdef c_Complex z = new_Complex(mpfr_get_d(complexified_s.__re, MPFR_RNDN), mpfr_get_d(complexified_s.__im, MPFR_RNDN))
+-        cdef c_Complex result = self.__value(z, derivative)
++        cdef c_Complex result = self._value(z, derivative)
+         return CCC(result.real(),result.imag())
+ 
+     def hardy_z_function(self, s):
+@@ -223,7 +223,7 @@ cdef class Lfunction:
+         #This takes s -> .5 + I*s
+         cdef ComplexNumber complexified_s = CCC(0.5)+ CCC(0,1)*CCC(s)
+         cdef c_Complex z = new_Complex(mpfr_get_d(complexified_s.__re, MPFR_RNDN), mpfr_get_d(complexified_s.__im, MPFR_RNDN))
+-        cdef c_Complex result = self.__hardy_z_function(z)
++        cdef c_Complex result = self._hardy_z_function(z)
+         return CCC(result.real(),result.imag())
+ 
+ 
+@@ -249,9 +249,9 @@ cdef class Lfunction:
+             3
+ 
+         """
+-        return self.__compute_rank()
++        return self._compute_rank()
+ 
+-    def __N(self, T):
++    def _N(self, T):
+         """
+         Compute the number of zeroes upto height `T` using the formula for
+         `N(T)` with the error of `S(T)`. Please do not use this. It is only
+@@ -262,12 +262,12 @@ cdef class Lfunction:
+             sage: from sage.libs.lcalc.lcalc_Lfunction import *
+             sage: chi = DirichletGroup(5)[2] #This is a quadratic character
+             sage: L=Lfunction_from_character(chi, type="complex")
+-            sage: L.__N(10) # abs tol 1e-8
++            sage: L._N(10) # abs tol 1e-8
+             4.0
+         """
+         cdef RealNumber real_T=RRR(T)
+         cdef double double_T = mpfr_get_d(real_T.value, MPFR_RNDN)
+-        cdef double res_d = self.__typedN(double_T)
++        cdef double res_d = self._typedN(double_T)
+         return RRR(res_d)
+ 
+     def find_zeros(self, T1, T2, stepsize):
+@@ -323,7 +323,7 @@ cdef class Lfunction:
+         cdef RealNumber real_T2 = RRR(T2)
+         cdef RealNumber real_stepsize = RRR(stepsize)
+         sig_on()
+-        self.__find_zeros_v( mpfr_get_d(real_T1.value, MPFR_RNDN), mpfr_get_d(real_T2.value, MPFR_RNDN), mpfr_get_d(real_stepsize.value, MPFR_RNDN),&result)
++        self._find_zeros_v( mpfr_get_d(real_T1.value, MPFR_RNDN), mpfr_get_d(real_T2.value, MPFR_RNDN), mpfr_get_d(real_stepsize.value, MPFR_RNDN),&result)
+         sig_off()
+         i=result.size()
+         returnvalue = []
+@@ -399,7 +399,7 @@ cdef class Lfunction:
+         cdef const char* message_stamp = ""
+         cdef doublevec result
+         sig_on()
+-        self.__find_zeros(count, start, max_refine, rank, message_stamp, &result)
++        self._find_zeros(count, start, max_refine, rank, message_stamp, &result)
+         sig_off()
+         returnvalue = []
+         for i in range(result.size()):
+@@ -408,25 +408,25 @@ cdef class Lfunction:
+         return returnvalue
+ 
+     # Needs to be overriden
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         raise NotImplementedError
+ 
+-    cdef c_Complex __value(self,c_Complex s,int derivative):
++    cdef c_Complex _value(self,c_Complex s,int derivative):
+         raise NotImplementedError
+ 
+-    cdef c_Complex __hardy_z_function(self,c_Complex s):
++    cdef c_Complex _hardy_z_function(self,c_Complex s):
+         raise NotImplementedError
+ 
+-    cdef int __compute_rank(self):
++    cdef int _compute_rank(self):
+         raise NotImplementedError
+ 
+-    cdef double __typedN(self,double T):
++    cdef double _typedN(self,double T):
+         raise NotImplementedError
+ 
+-    cdef void __find_zeros_v(self,double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self,double T1, double T2, double stepsize, doublevec *result):
+         raise NotImplementedError
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         raise NotImplementedError
+ 
+ ##############################################################################
+@@ -497,7 +497,7 @@ cdef class Lfunction_I(Lfunction):
+         self._repr += " with integer Dirichlet coefficients"
+ 
+     # override
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         cdef int N = len(dirichlet_coeff)
+         cdef Integer tmpi
+         cdef int * coeffs = new_ints(N+1) #lcalc ignores 0the coefficient
+@@ -507,22 +507,22 @@ cdef class Lfunction_I(Lfunction):
+         self.thisptr=new_c_Lfunction_I(NAME, what_type,  N, coeffs, Period, q,  w,  A, g, l, n_poles, p, r)
+         del_ints(coeffs)
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_I *>(self.thisptr)).value(s, derivative, "pure")
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_I *>(self.thisptr)).value(s, 0, "rotated pure")
+ 
+-    cdef int __compute_rank(self):
++    cdef int _compute_rank(self):
+         return (<c_Lfunction_I *>(self.thisptr)).compute_rank()
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_I *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_I *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_I *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     # debug tools
+@@ -633,7 +633,7 @@ cdef class Lfunction_D(Lfunction):
+         self._repr += " with real Dirichlet coefficients"
+ 
+     # override
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         cdef int i
+         cdef RealNumber tmpr
+         cdef int N = len(dirichlet_coeff)
+@@ -644,23 +644,23 @@ cdef class Lfunction_D(Lfunction):
+         self.thisptr=new_c_Lfunction_D(NAME, what_type,  N, coeffs, Period, q,  w,  A, g, l, n_poles, p, r)
+         del_doubles(coeffs)
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_D *>(self.thisptr)).value(s, derivative, "pure")
+ 
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_D *>(self.thisptr)).value(s, 0, "rotated pure")
+ 
+-    cdef inline int __compute_rank(self):
++    cdef inline int _compute_rank(self):
+         return (<c_Lfunction_D *>(self.thisptr)).compute_rank()
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_D *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_D *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start,double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start,double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_D *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     # debug tools
+@@ -773,7 +773,7 @@ cdef class Lfunction_C:
+         self._repr += " with complex Dirichlet coefficients"
+ 
+     # override
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         cdef int i
+         cdef int N = len(dirichlet_coeff)
+         cdef ComplexNumber tmpc
+@@ -788,24 +788,24 @@ cdef class Lfunction_C:
+ 
+         del_Complexes(coeffs)
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_C *>(self.thisptr)).value(s, derivative, "pure")
+ 
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_C *>(self.thisptr)).value(s, 0,"rotated pure")
+ 
+-    cdef inline int __compute_rank(self):
++    cdef inline int _compute_rank(self):
+         return (<c_Lfunction_C *>(self.thisptr)).compute_rank()
+ 
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_C *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_C *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_C *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     # debug tools
+@@ -873,24 +873,24 @@ cdef class Lfunction_Zeta(Lfunction):
+         self.thisptr = new_c_Lfunction_Zeta()
+         self._repr = "The Riemann zeta function"
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_Zeta *>(self.thisptr)).value(s, derivative, "pure")
+ 
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_Zeta *>(self.thisptr)).value(s, 0, "rotated pure")
+ 
+-    cdef inline int __compute_rank(self):
++    cdef inline int _compute_rank(self):
+         return (<c_Lfunction_Zeta *>(self.thisptr)).compute_rank()
+ 
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_Zeta *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_Zeta *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_Zeta *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     def __dealloc__(self):
+diff --git a/src/sage/libs/linkages/padics/Polynomial_ram.pxi b/src/sage/libs/linkages/padics/Polynomial_ram.pxi
+index 1ac51f1211f..e0584ecb8ad 100644
+--- a/src/sage/libs/linkages/padics/Polynomial_ram.pxi
++++ b/src/sage/libs/linkages/padics/Polynomial_ram.pxi
+@@ -55,16 +55,16 @@ cdef inline bint creduce(celement out, celement a, long prec, PowComputer_ prime
+     """
+     cdef celement ared = a % prime_pow.modulus
+     if ared is a and out is not a:
+-        out.__coeffs = ared.__coeffs[:]
++        out._coeffs = ared._coeffs[:]
+     else:
+-        out.__coeffs = ared.__coeffs
++        out._coeffs = ared._coeffs
+     cdef long coeff_prec = prec / prime_pow.e + 1
+     cdef long break_pt = prec % prime_pow.e
+-    for i in range(len(out.__coeffs)):
++    for i in range(len(out._coeffs)):
+         if i == break_pt:
+             coeff_prec -= 1
+-        out.__coeffs[i] = out.__coeffs[i].add_bigoh(coeff_prec)
+-    out.__normalize()
++        out._coeffs[i] = out._coeffs[i].add_bigoh(coeff_prec)
++    out._normalize()
+     return out == 0
+ 
+ cdef inline bint creduce_small(celement out, celement a, long prec, PowComputer_ prime_pow) except -1:
+@@ -116,7 +116,7 @@ cdef inline long cvaluation(celement a, long prec, PowComputer_ prime_pow) excep
+     higher.
+ 
+     """
+-    C = a.__coeffs
++    C = a._coeffs
+     if not C:
+         return prec
+     cdef long ret = maxordp
+@@ -161,7 +161,7 @@ cdef inline int cshift(celement shifted, celement rem, celement a, long n, long
+         v = cvaluation(a, prec, prime_pow)
+         notrunc = (v >= -n)
+     if notrunc:
+-        rem.__coeffs = []
++        rem._coeffs = []
+         return cshift_notrunc(shifted, a, n, prec, prime_pow, reduce_afterward)
+     if v > 0:
+         b = prime_pow.poly_ring(0)
+@@ -185,7 +185,7 @@ cdef inline int cshift(celement shifted, celement rem, celement a, long n, long
+     if reduce_afterward:
+         creduce(shifted, a, prec, prime_pow)
+     else:
+-        shifted.__coeffs = a.__coeffs[:]
++        shifted._coeffs = a._coeffs[:]
+ 
+ cdef inline int cshift_notrunc(celement out, celement a, long n, long prec, PowComputer_ prime_pow, bint reduce_afterward) except -1:
+     r"""
+@@ -236,7 +236,7 @@ cdef inline int cshift_notrunc(celement out, celement a, long n, long prec, PowC
+     if reduce_afterward:
+         creduce(out, a, prec, prime_pow)
+     else:
+-        out.__coeffs = a.__coeffs[:]
++        out._coeffs = a._coeffs[:]
+ 
+ cdef inline int cinvert(celement out, celement a, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -253,7 +253,7 @@ cdef inline int cinvert(celement out, celement a, long prec, PowComputer_ prime_
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = prime_pow.invert(a, prec).__coeffs
++    out._coeffs = prime_pow.invert(a, prec)._coeffs
+     creduce(out, out, prec, prime_pow)
+ 
+ cdef inline int cdivunit(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+@@ -335,7 +335,7 @@ cdef inline cexpansion_next(celement value, expansion_mode mode, long curpower,
+     # the following is specific to the ramified over unramified case.
+     modp_rep, term = value[0]._modp_rep(mode == smallest_mode)
+     if term:
+-        value.__coeffs[0] -= modp_rep
++        value._coeffs[0] -= modp_rep
+     cshift_notrunc(value, value, -1, curpower, prime_pow, False)
+     return term
+ 
+@@ -354,10 +354,10 @@ cdef inline cexpansion_getitem(celement value, long m, PowComputer_ prime_pow):
+     while m >= 0:
+         modp_rep, term = value[0]._modp_rep()
+         if m:
+-            if len(value.__coeffs):
+-                value.__coeffs[0] -= modp_rep
++            if len(value._coeffs):
++                value._coeffs[0] -= modp_rep
+             else:
+-                value.__coeffs.append(-modp_rep)
++                value._coeffs.append(-modp_rep)
+             cshift_notrunc(value, value, -1, 1, prime_pow, False)
+         m -= 1
+     return term
+@@ -379,9 +379,9 @@ cdef int cteichmuller(celement out, celement value, long prec, PowComputer_ prim
+ 
+     """
+     if value[0].valuation() > 0:
+-        out.__coeffs = []
++        out._coeffs = []
+     else:
+-        out.__coeffs = [value[0].parent().teichmuller(value[0])]
++        out._coeffs = [value[0].parent().teichmuller(value[0])]
+ 
+ cdef list ccoefficients(celement x, long valshift, long prec, PowComputer_ prime_pow):
+     """
+diff --git a/src/sage/libs/linkages/padics/Polynomial_shared.pxi b/src/sage/libs/linkages/padics/Polynomial_shared.pxi
+index 495dc6b0848..367bbc2f33d 100644
+--- a/src/sage/libs/linkages/padics/Polynomial_shared.pxi
++++ b/src/sage/libs/linkages/padics/Polynomial_shared.pxi
+@@ -106,7 +106,7 @@ cdef inline int ccmp(celement a, celement b, long prec, bint reduce_a, bint redu
+     if not (reduce_a or reduce_b):
+         return 0 if a == b else 1
+     csub(prime_pow.tmp_ccmp_a, a, b, prec, prime_pow)
+-    coeffs = prime_pow.tmp_ccmp_a.__coeffs
++    coeffs = prime_pow.tmp_ccmp_a._coeffs
+     cdef long i, coeff_prec, break_pt
+     if prime_pow.e == 1:
+         for i in range(prime_pow.tmp_ccmp_a.degree()+1):
+@@ -186,9 +186,9 @@ cdef inline int cneg(celement out, celement a, long prec, PowComputer_ prime_pow
+     """
+     cdef celement ma = -a
+     if ma is a:
+-        out.__coeffs = ma.__coeffs[:]
++        out._coeffs = ma._coeffs[:]
+     else:
+-        out.__coeffs = ma.__coeffs
++        out._coeffs = ma._coeffs
+ 
+ cdef inline int cadd(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -211,9 +211,9 @@ cdef inline int cadd(celement out, celement a, celement b, long prec, PowCompute
+     """
+     cdef celement sm = a + b
+     if sm is a or sm is b:
+-        out.__coeffs = sm.__coeffs[:]
++        out._coeffs = sm._coeffs[:]
+     else:
+-        out.__coeffs = sm.__coeffs
++        out._coeffs = sm._coeffs
+ 
+ cdef inline int csub(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -236,9 +236,9 @@ cdef inline int csub(celement out, celement a, celement b, long prec, PowCompute
+     """
+     cdef celement df = a - b
+     if df is a or df is b:
+-        out.__coeffs = df.__coeffs[:]
++        out._coeffs = df._coeffs[:]
+     else:
+-        out.__coeffs = df.__coeffs
++        out._coeffs = df._coeffs
+ 
+ cdef inline int cmul(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -261,9 +261,9 @@ cdef inline int cmul(celement out, celement a, celement b, long prec, PowCompute
+     """
+     cdef celement pd = a*b
+     if pd is a or pd is b:
+-        out.__coeffs = pd.__coeffs[:]
++        out._coeffs = pd._coeffs[:]
+     else:
+-        out.__coeffs = pd.__coeffs
++        out._coeffs = pd._coeffs
+ 
+ cdef inline int csetone(celement out, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -276,7 +276,7 @@ cdef inline int csetone(celement out, PowComputer_ prime_pow) except -1:
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = [prime_pow.base_ring(1)]
++    out._coeffs = [prime_pow.base_ring(1)]
+ 
+ cdef inline int csetzero(celement out, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -289,7 +289,7 @@ cdef inline int csetzero(celement out, PowComputer_ prime_pow) except -1:
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = []
++    out._coeffs = []
+ 
+ cdef inline bint cisone(celement a, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -330,7 +330,7 @@ cdef inline int ccopy(celement out, celement a, PowComputer_ prime_pow) except -
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = a.__coeffs[:]
++    out._coeffs = a._coeffs[:]
+ 
+ cdef inline cpickle(celement a, PowComputer_ prime_pow):
+     r"""
+@@ -343,7 +343,7 @@ cdef inline cpickle(celement a, PowComputer_ prime_pow):
+     - ``prime_pow`` the ``PowComputer`` for the ring
+ 
+     """
+-    return a.__coeffs
++    return a._coeffs
+ 
+ cdef inline int cunpickle(celement out, x, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -358,7 +358,7 @@ cdef inline int cunpickle(celement out, x, PowComputer_ prime_pow) except -1:
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = x
++    out._coeffs = x
+ 
+ cdef inline long chash(celement a, long ordp, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -413,9 +413,9 @@ cdef int cconv(celement out, x, long prec, long valshift, PowComputer_ prime_pow
+     else:
+         xx = prime_pow.poly_ring(x)
+     if xx is x:
+-        out.__coeffs = xx.__coeffs[:]
++        out._coeffs = xx._coeffs[:]
+     else:
+-        out.__coeffs = xx.__coeffs
++        out._coeffs = xx._coeffs
+     if valshift > 0:
+         cshift_notrunc(out, out, -valshift, prec, prime_pow, True)
+     elif valshift == 0:
+@@ -458,12 +458,12 @@ cdef inline long cconv_mpz_t(celement out, mpz_t x, long prec, bint absolute, Po
+     mpz_set(n.value, x)
+ 
+     if n:
+-        out.__coeffs = [prime_pow.base_ring(n)]
++        out._coeffs = [prime_pow.base_ring(n)]
+         if not absolute:
+             valuation = cremove(out, out, prec, prime_pow)
+         creduce(out, out, prec, prime_pow)
+     else:
+-        out.__coeffs = []
++        out._coeffs = []
+ 
+     return valuation
+ 
+@@ -492,12 +492,12 @@ cdef inline int cconv_mpz_t_out(mpz_t out, celement x, long valshift, long prec,
+     else:
+         prime_pow.powhelper_cconv_out = x
+ 
+-    if len(prime_pow.powhelper_cconv_out.__coeffs) == 0:
++    if len(prime_pow.powhelper_cconv_out._coeffs) == 0:
+         mpz_set_ui(out, 0)
+-    elif len(prime_pow.powhelper_cconv_out.__coeffs) == 1:
++    elif len(prime_pow.powhelper_cconv_out._coeffs) == 1:
+         # recursively let the underlying polynomial convert the constant
+         # coefficient to an integer (if possible)
+-        n = ZZ(prime_pow.powhelper_cconv_out.__coeffs[0])
++        n = ZZ(prime_pow.powhelper_cconv_out._coeffs[0])
+         mpz_set(out, n.value)
+     else:
+         raise ValueError("cannot convert to integer")
+@@ -532,7 +532,7 @@ cdef inline long cconv_mpq_t(celement out, mpq_t x, long prec, bint absolute, Po
+     """
+     cdef Rational r = PY_NEW(Rational)
+     mpq_set(r.value, x)
+-    out.__coeffs = [prime_pow.base_ring(r)]
++    out._coeffs = [prime_pow.base_ring(r)]
+ 
+     if not absolute:
+         return cremove(out, out, prec, prime_pow)
+@@ -565,12 +565,12 @@ cdef inline int cconv_mpq_t_out(mpq_t out, celement x, long valshift, long prec,
+     else:
+         prime_pow.powhelper_cconv_out = x
+ 
+-    if len(prime_pow.powhelper_cconv_out.__coeffs) == 0:
++    if len(prime_pow.powhelper_cconv_out._coeffs) == 0:
+         mpq_set_ui(out, 0, 1)
+-    elif len(prime_pow.powhelper_cconv_out.__coeffs) == 1:
++    elif len(prime_pow.powhelper_cconv_out._coeffs) == 1:
+         # recursively let the underlying polynomial convert the constant
+         # coefficient to a rational (if possible)
+-        c = QQ(prime_pow.powhelper_cconv_out.__coeffs[0])
++        c = QQ(prime_pow.powhelper_cconv_out._coeffs[0])
+         mpq_set(out, c.value)
+     else:
+         raise ValueError("cannot convert to rational")
+diff --git a/src/sage/libs/ntl/ntl_lzz_p.pyx b/src/sage/libs/ntl/ntl_lzz_p.pyx
+index 161d0782bc2..af86b9bcf69 100644
+--- a/src/sage/libs/ntl/ntl_lzz_p.pyx
++++ b/src/sage/libs/ntl/ntl_lzz_p.pyx
+@@ -89,19 +89,19 @@ cdef class ntl_zz_p():
+         #self.c.restore_c()   ## This was done in __new__
+ 
+         if isinstance(a, IntegerMod_int):
+-            if (self.c.p == (<IntegerMod_int>a).__modulus.int32): ## this is slow
++            if (self.c.p == (<IntegerMod_int>a)._modulus.int32): ## this is slow
+                 self.x = (<IntegerMod_int>a).ivalue
+             else:
+                 raise ValueError("Mismatched modulus for converting to zz_p.")
+ 
+         elif isinstance(a, IntegerMod_int64):
+-            if (self.c.p == (<IntegerMod_int64>a).__modulus.int64): ## this is slow
++            if (self.c.p == (<IntegerMod_int64>a)._modulus.int64): ## this is slow
+                 self.x = (<IntegerMod_int64>a).ivalue
+             else:
+                 raise ValueError("Mismatched modulus for converting to zz_p.")
+ 
+         elif isinstance(a, IntegerMod_gmp):
+-            if (p_sage == (<IntegerMod_gmp>a).__modulus.sageInteger): ## this is slow
++            if (p_sage == (<IntegerMod_gmp>a)._modulus.sageInteger): ## this is slow
+                 self.x = mpz_get_si((<IntegerMod_gmp>a).value)
+             else:
+                 raise ValueError("Mismatched modulus for converting to zz_p.")
+diff --git a/src/sage/libs/ntl/ntl_lzz_pX.pyx b/src/sage/libs/ntl/ntl_lzz_pX.pyx
+index 24b503a9a62..7d19cc55e37 100644
+--- a/src/sage/libs/ntl/ntl_lzz_pX.pyx
++++ b/src/sage/libs/ntl/ntl_lzz_pX.pyx
+@@ -108,17 +108,17 @@ cdef class ntl_zz_pX():
+             a = ls[i]
+ 
+             if isinstance(a, IntegerMod_int):
+-                if (self.c.p == (<IntegerMod_int>a).__modulus.int32): ## this is slow
++                if (self.c.p == (<IntegerMod_int>a)._modulus.int32): ## this is slow
+                     zz_pX_SetCoeff_long(self.x, i, (<IntegerMod_int>a).ivalue)
+                 else:
+                     raise ValueError("Mismatched modulus for converting to zz_pX.")
+             elif isinstance(a, IntegerMod_int64):
+-                if (self.c.p == (<IntegerMod_int64>a).__modulus.int64): ## this is slow
++                if (self.c.p == (<IntegerMod_int64>a)._modulus.int64): ## this is slow
+                     zz_pX_SetCoeff_long(self.x, i, (<IntegerMod_int64>a).ivalue)
+                 else:
+                     raise ValueError("Mismatched modulus for converting to zz_pX.")
+             elif isinstance(a, IntegerMod_gmp):
+-                if (p_sage == (<IntegerMod_gmp>a).__modulus.sageInteger): ## this is slow
++                if (p_sage == (<IntegerMod_gmp>a)._modulus.sageInteger): ## this is slow
+                     zz_pX_SetCoeff_long(self.x, i, mpz_get_si((<IntegerMod_gmp>a).value))
+                 else:
+                     raise ValueError("Mismatched modulus for converting to zz_pX.")
+diff --git a/src/sage/matrix/matrix_complex_ball_dense.pyx b/src/sage/matrix/matrix_complex_ball_dense.pyx
+index 9e14079c6d4..47ca41070fa 100644
+--- a/src/sage/matrix/matrix_complex_ball_dense.pyx
++++ b/src/sage/matrix/matrix_complex_ball_dense.pyx
+@@ -664,7 +664,7 @@ cdef class Matrix_complex_ball_dense(Matrix_dense):
+         Pol = polynomial_ring_constructor._single_variate(self.base_ring(), var)
+         cdef Polynomial_complex_arb res = Polynomial_complex_arb(Pol)
+         sig_on()
+-        acb_mat_charpoly(res.__poly, self.value, prec(self))
++        acb_mat_charpoly(res._poly, self.value, prec(self))
+         sig_off()
+         return res
+ 
+diff --git a/src/sage/matrix/matrix_cyclo_dense.pyx b/src/sage/matrix/matrix_cyclo_dense.pyx
+index 15ff6394951..f1ed9af8403 100644
+--- a/src/sage/matrix/matrix_cyclo_dense.pyx
++++ b/src/sage/matrix/matrix_cyclo_dense.pyx
+@@ -396,11 +396,11 @@ cdef class Matrix_cyclo_dense(Matrix_dense):
+             # Now set k-th entry of x's numerator to tmp
+             fmpz_get_mpz(tmp, ftmp)
+             mpz_to_ZZ(&coeff, tmp)
+-            ZZX_SetCoeff(x.__numerator, k, coeff)
++            ZZX_SetCoeff(x._numerator, k, coeff)
+ 
+         # Set the denominator of x to denom.
+         fmpz_get_mpz(tmp, denom)
+-        mpz_to_ZZ(&x.__denominator, tmp)
++        mpz_to_ZZ(&x._denominator, tmp)
+         fmpz_clear(denom)
+         mpz_clear(tmp)
+         fmpz_clear(ftmp)
+diff --git a/src/sage/matrix/matrix_integer_dense.pyx b/src/sage/matrix/matrix_integer_dense.pyx
+index 9c509104967..8088350577c 100644
+--- a/src/sage/matrix/matrix_integer_dense.pyx
++++ b/src/sage/matrix/matrix_integer_dense.pyx
+@@ -1371,12 +1371,12 @@ cdef class Matrix_integer_dense(Matrix_dense):
+         if algorithm == 'flint':
+             g = (<Polynomial_integer_dense_flint> PolynomialRing(ZZ, names=var).gen())._new()
+             sig_on()
+-            fmpz_mat_charpoly(g.__poly, self._matrix)
++            fmpz_mat_charpoly(g._poly, self._matrix)
+             sig_off()
+         elif algorithm == 'linbox':
+             g = (<Polynomial_integer_dense_flint> PolynomialRing(ZZ, names=var).gen())._new()
+             sig_on()
+-            linbox_fmpz_mat_charpoly(g.__poly, self._matrix)
++            linbox_fmpz_mat_charpoly(g._poly, self._matrix)
+             sig_off()
+         elif algorithm == 'generic':
+             g = Matrix_dense.charpoly(self, var)
+@@ -1460,7 +1460,7 @@ cdef class Matrix_integer_dense(Matrix_dense):
+         if algorithm == 'linbox':
+             g = (<Polynomial_integer_dense_flint> PolynomialRing(ZZ, names=var).gen())._new()
+             sig_on()
+-            linbox_fmpz_mat_minpoly(g.__poly, self._matrix)
++            linbox_fmpz_mat_minpoly(g._poly, self._matrix)
+             sig_off()
+         elif algorithm == 'generic':
+             g = Matrix_dense.minpoly(self, var)
+diff --git a/src/sage/matrix/matrix_integer_sparse.pyx b/src/sage/matrix/matrix_integer_sparse.pyx
+index a41677c7b6a..83d5ee42fbe 100644
+--- a/src/sage/matrix/matrix_integer_sparse.pyx
++++ b/src/sage/matrix/matrix_integer_sparse.pyx
+@@ -869,10 +869,10 @@ cdef class Matrix_integer_sparse(Matrix_sparse):
+         sig_off()
+ 
+         cdef size_t i
+-        fmpz_poly_fit_length(g.__poly, p.size())
++        fmpz_poly_fit_length(g._poly, p.size())
+         for i in range(p.size()):
+-            fmpz_poly_set_coeff_mpz(g.__poly, i, p[0][i].get_mpz_const())
+-        _fmpz_poly_set_length(g.__poly, p.size())
++            fmpz_poly_set_coeff_mpz(g._poly, i, p[0][i].get_mpz_const())
++        _fmpz_poly_set_length(g._poly, p.size())
+ 
+         del M
+         del p
+@@ -968,10 +968,10 @@ cdef class Matrix_integer_sparse(Matrix_sparse):
+         sig_off()
+ 
+         cdef size_t i
+-        fmpz_poly_fit_length(g.__poly, p.size())
++        fmpz_poly_fit_length(g._poly, p.size())
+         for i in range(p.size()):
+-            fmpz_poly_set_coeff_mpz(g.__poly, i, p[0][i].get_mpz_const())
+-        _fmpz_poly_set_length(g.__poly, p.size())
++            fmpz_poly_set_coeff_mpz(g._poly, i, p[0][i].get_mpz_const())
++        _fmpz_poly_set_length(g._poly, p.size())
+ 
+         del M
+         del p
+diff --git a/src/sage/matroids/basis_exchange_matroid.pxd b/src/sage/matroids/basis_exchange_matroid.pxd
+index aec3bb54c42..28cc7ad868c 100644
+--- a/src/sage/matroids/basis_exchange_matroid.pxd
++++ b/src/sage/matroids/basis_exchange_matroid.pxd
+@@ -15,13 +15,13 @@ cdef class BasisExchangeMatroid(Matroid):
+     cdef _weak_invariant_var, _strong_invariant_var, _heuristic_invariant_var
+     cdef SetSystem _weak_partition_var, _strong_partition_var, _heuristic_partition_var
+ 
+-    cdef __relabel(self, l)
++    cdef _relabel(self, l)
+ 
+-    cdef __pack(self, bitset_t, X)
++    cdef _pack(self, bitset_t, X)
+     cdef __unpack(self, bitset_t)
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1
+-    cdef int __exchange(self, long x, long y) except -1
+-    cdef int __move(self, bitset_t X, bitset_t Y) except -1
++    cdef bint _is_exchange_pair(self, long x, long y) except -1
++    cdef int _exchange(self, long x, long y) except -1
++    cdef int _move(self, bitset_t X, bitset_t Y) except -1
+     cdef __fundamental_cocircuit(self, bitset_t, long x)
+     cdef __fundamental_circuit(self, bitset_t, long y)
+ 
+@@ -30,7 +30,7 @@ cdef class BasisExchangeMatroid(Matroid):
+     cdef __closure(self, bitset_t, bitset_t)
+     cdef __max_coindependent(self, bitset_t, bitset_t)
+     cdef __cocircuit(self, bitset_t, bitset_t)
+-    cdef __coclosure(self, bitset_t, bitset_t)
++    cdef _coclosure_internal(self, bitset_t, bitset_t)
+ 
+     cdef __augment(self, bitset_t, bitset_t, bitset_t)
+     cdef bint __is_independent(self, bitset_t F) except -1
+diff --git a/src/sage/matroids/basis_exchange_matroid.pyx b/src/sage/matroids/basis_exchange_matroid.pyx
+index 90d10842d46..015fa8b8df3 100644
+--- a/src/sage/matroids/basis_exchange_matroid.pyx
++++ b/src/sage/matroids/basis_exchange_matroid.pyx
+@@ -57,10 +57,10 @@ cdef class BasisExchangeMatroid(Matroid):
+ 
+     This base exchange graph is not stored as such, but should be provided
+     implicitly by the child class in the form of two methods
+-    ``__is_exchange_pair(x, y)`` and ``__exchange(x, y)``, as well as an
++    ``_is_exchange_pair(x, y)`` and ``_exchange(x, y)``, as well as an
+     initial basis. At any moment, BasisExchangeMatroid keeps a current basis
+-    `B`. The method ``__is_exchange_pair(x, y)`` should return a boolean
+-    indicating whether `B - x + y` is a basis. The method ``__exchange(x, y)``
++    `B`. The method ``_is_exchange_pair(x, y)`` should return a boolean
++    indicating whether `B - x + y` is a basis. The method ``_exchange(x, y)``
+     is called when the current basis `B` is replaced by said `B-x + y`. It is
+     up to the child class to update its internal data structure to make
+     information relative to the new basis more accessible. For instance, a
+@@ -81,16 +81,16 @@ cdef class BasisExchangeMatroid(Matroid):
+     - :class:`BasisMatroid <sage.matroids.basis_matroid.BasisMatroid>`: keeps
+       a list of all bases.
+ 
+-        - ``__is_exchange_pair(x, y)`` reduces to a query whether `B - x + y`
++        - ``_is_exchange_pair(x, y)`` reduces to a query whether `B - x + y`
+           is a basis.
+-        - ``__exchange(x, y)`` has no work to do.
++        - ``_exchange(x, y)`` has no work to do.
+ 
+     - :class:`LinearMatroid <sage.matroids.linear_matroid.LinearMatroid>`:
+       keeps a matrix representation `A` of the matroid so that `A[B] = I`.
+ 
+-        - ``__is_exchange_pair(x, y)`` reduces to testing whether `A[r, y]`
++        - ``_is_exchange_pair(x, y)`` reduces to testing whether `A[r, y]`
+           is nonzero, where `A[r, x]=1`.
+-        - ``__exchange(x, y)`` should modify the matrix so that `A[B - x + y]`
++        - ``_exchange(x, y)`` should modify the matrix so that `A[B - x + y]`
+           becomes `I`, which means pivoting on `A[r, y]`.
+ 
+     - ``TransversalMatroid`` (not yet implemented): If `A` is a set of subsets
+@@ -100,17 +100,17 @@ cdef class BasisExchangeMatroid(Matroid):
+       edge `(A_i,e)` if `e` is in the subset `A_i`. At any time you keep a
+       maximum matching `M` of `G` covering the current basis `B`.
+ 
+-        - ``__is_exchange_pair(x, y)`` checks for the existence of an
++        - ``_is_exchange_pair(x, y)`` checks for the existence of an
+           `M`-alternating path `P` from `y` to `x`.
+-        - ``__exchange(x, y)`` replaces `M` by the symmetric difference of
++        - ``_exchange(x, y)`` replaces `M` by the symmetric difference of
+           `M` and `E(P)`.
+ 
+     - ``AlgebraicMatroid`` (not yet implemented): keeps a list of polynomials
+       in variables `E - B + e` for each variable `e` in `B`.
+ 
+-        - ``__is_exchange_pair(x, y)`` checks whether the polynomial that
++        - ``_is_exchange_pair(x, y)`` checks whether the polynomial that
+           relates `y` to `E-B` uses `x`.
+-        - ``__exchange(x, y)`` make new list of polynomials by computing
++        - ``_exchange(x, y)`` make new list of polynomials by computing
+           resultants.
+ 
+     All but the first of the above matroids are algebraic, and all
+@@ -139,7 +139,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         This initializer sets up a correspondence between elements of
+         ``groundset`` and ``range(len(groundset))``. ``BasisExchangeMatroid``
+         uses this correspondence for encoding of subsets of the groundset as
+-        bitpacked sets of integers --- see ``__pack()`` and ``__unpack()``. In
++        bitpacked sets of integers --- see ``_pack()`` and ``__unpack()``. In
+         general, methods of ``BasisExchangeMatroid`` having a name starting
+         with two underscores deal with such encoded subsets.
+ 
+@@ -180,7 +180,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             self._idx[self._E[i]] = i
+ 
+         if basis is not None:
+-            self.__pack(self._current_basis, frozenset(basis))
++            self._pack(self._current_basis, frozenset(basis))
+ 
+     def __dealloc__(self):
+         bitset_free(self._current_basis)
+@@ -191,7 +191,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_free(self._output)
+         bitset_free(self._temp)
+ 
+-    cdef __relabel(self, l):
++    cdef _relabel(self, l):
+         """
+         Relabel each element `e` as `l[e]`, where `l` is a given injective map.
+ 
+@@ -231,7 +231,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             self._heuristic_partition_var._relabel(l)
+ 
+     # the engine
+-    cdef __pack(self, bitset_t I, F):
++    cdef _pack(self, bitset_t I, F):
+         """
+         Encode a subset F of the groundset into a bitpacked set of integers
+         """
+@@ -252,21 +252,21 @@ cdef class BasisExchangeMatroid(Matroid):
+         return frozenset(F)
+ 
+     # this method needs to be overridden by child class
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         """
+         Test if current_basis-x + y is a basis
+         """
+         raise NotImplementedError
+ 
+     # if this method is overridden by a child class, the child class needs to call this method
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         """
+         put current_basis <-- current_basis-x + y
+         """
+         bitset_discard(self._current_basis, x)
+         bitset_add(self._current_basis, y)
+ 
+-    cdef int __move(self, bitset_t X, bitset_t Y) except -1:
++    cdef int _move(self, bitset_t X, bitset_t Y) except -1:
+         """
+         Change current_basis to minimize intersection with ``X``, maximize intersection with ``Y``.
+         """
+@@ -275,8 +275,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         while x >= 0:
+             y = bitset_first(Y)
+             while y >= 0:
+-                if self.__is_exchange_pair(x, y):
+-                    self.__exchange(x, y)
++                if self._is_exchange_pair(x, y):
++                    self._exchange(x, y)
+                     bitset_discard(Y, y)
+                     bitset_discard(X, x)
+                     if bitset_isempty(Y):
+@@ -295,7 +295,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_complement(self._temp, self._current_basis)
+         y = bitset_first(self._temp)
+         while y >= 0:
+-            if self.__is_exchange_pair(x, y):
++            if self._is_exchange_pair(x, y):
+                 bitset_add(C, y)
+             y = bitset_next(self._temp, y + 1)
+         bitset_add(C, x)
+@@ -308,7 +308,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_clear(C)
+         x = bitset_first(self._current_basis)
+         while x >= 0:
+-            if self.__is_exchange_pair(x, y):
++            if self._is_exchange_pair(x, y):
+                 bitset_add(C, x)
+             x = bitset_next(self._current_basis, x + 1)
+         bitset_add(C, y)
+@@ -319,7 +319,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, F)
+         bitset_difference(self._outside, F, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_intersection(R, self._current_basis, F)
+ 
+     cdef __circuit(self, bitset_t R, bitset_t F):
+@@ -335,8 +335,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         while y >= 0:
+             x = bitset_first(self._inside)
+             while x >= 0:
+-                if self.__is_exchange_pair(x, y):
+-                    self.__exchange(x, y)
++                if self._is_exchange_pair(x, y):
++                    self._exchange(x, y)
+                     bitset_discard(self._outside, y)
+                     bitset_discard(self._inside, x)
+                     if bitset_isempty(self._outside):
+@@ -355,7 +355,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, F)
+         bitset_difference(self._outside, F, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_set_first_n(R, self._groundset_size)
+         cdef long x = bitset_first(self._inside)
+         while x >= 0:
+@@ -370,7 +370,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_difference(R, F, self._current_basis)
+ 
+     cdef __cocircuit(self, bitset_t R, bitset_t F):
+@@ -387,8 +387,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         while x >= 0:
+             y = bitset_first(self._outside)
+             while y >= 0:
+-                if self.__is_exchange_pair(x, y):
+-                    self.__exchange(x, y)
++                if self._is_exchange_pair(x, y):
++                    self._exchange(x, y)
+                     bitset_discard(self._outside, y)
+                     bitset_discard(self._inside, x)
+                     if bitset_isempty(self._inside):
+@@ -401,14 +401,14 @@ cdef class BasisExchangeMatroid(Matroid):
+                 return
+             x = bitset_next(self._inside, x + 1)
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``closure``.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_set_first_n(R, self._groundset_size)
+         cdef long y = bitset_first(self._outside)
+         while y >= 0:
+@@ -422,10 +422,10 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, X)
+         bitset_difference(self._outside, X, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_difference(self._inside, self._inside, Y)
+         bitset_difference(self._outside, Y, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_intersection(R, self._current_basis, Y)
+ 
+     cdef bint __is_independent(self, bitset_t F) except -1:
+@@ -434,7 +434,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, F)
+         bitset_difference(self._outside, F, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         return bitset_isempty(self._outside)
+ 
+     cdef __move_current_basis(self, bitset_t X, bitset_t Y):
+@@ -443,21 +443,21 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, X)
+         bitset_difference(self._outside, X, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_intersection(self._inside, self._current_basis, Y)
+         bitset_complement(self._outside, self._current_basis)
+         bitset_difference(self._outside, self._outside, Y)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+     # functions for derived classes and for parent class
+     cdef bint _set_current_basis(self, F):
+         """
+         Set _current_basis to subset of the groundset ``F``.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         bitset_difference(self._inside, self._current_basis, self._input)
+         bitset_difference(self._outside, self._input, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         return bitset_isempty(self._outside) and bitset_isempty(self._inside)
+ 
+     # groundset and full_rank
+@@ -630,8 +630,8 @@ cdef class BasisExchangeMatroid(Matroid):
+             ['b', 'c', 'e', 'f']
+ 
+         """
+-        self.__pack(self._input, X)
+-        self.__pack(self._input2, Y)
++        self._pack(self._input, X)
++        self._pack(self._input2, Y)
+         self.__move_current_basis(self._input, self._input2)
+ 
+     cpdef _max_independent(self, F):
+@@ -661,7 +661,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.max_independent>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_independent(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -692,7 +692,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.rank>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_independent(self._output, self._input)
+         return bitset_len(self._output)
+ 
+@@ -729,7 +729,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             the input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.circuit>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__circuit(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -754,7 +754,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             sage: sorted(M._fundamental_circuit('abcd', 'e'))
+             ['a', 'b', 'c', 'e']
+         """
+-        self.__pack(self._input, B)
++        self._pack(self._input, B)
+         bitset_clear(self._input2)
+         self.__move_current_basis(self._input, self._input2)
+         self.__fundamental_circuit(self._output, self._idx[e])
+@@ -787,7 +787,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             :meth:`<sage.matroids.matroid.Matroid.closure>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__closure(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -818,7 +818,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.max_coindependent>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_coindependent(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -848,7 +848,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.corank>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_coindependent(self._output, self._input)
+         return bitset_len(self._output)
+ 
+@@ -885,7 +885,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.cocircuit>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__cocircuit(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -910,7 +910,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             sage: sorted(M._fundamental_cocircuit('efgh', 'e'))
+             ['b', 'c', 'd', 'e']
+         """
+-        self.__pack(self._input, B)
++        self._pack(self._input, B)
+         bitset_clear(self._input2)
+         self.__move_current_basis(self._input, self._input2)
+         self.__fundamental_cocircuit(self._output, self._idx[e])
+@@ -943,8 +943,8 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.coclosure>`.
+ 
+         """
+-        self.__pack(self._input, F)
+-        self.__coclosure(self._output, self._input)
++        self._pack(self._input, F)
++        self._coclosure_internal(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+     cpdef _augment(self, X, Y):
+@@ -973,8 +973,8 @@ cdef class BasisExchangeMatroid(Matroid):
+             ['e', 'f', 'g']
+ 
+         """
+-        self.__pack(self._input, X)
+-        self.__pack(self._input2, Y)
++        self._pack(self._input, X)
++        self._pack(self._input2, Y)
+         self.__augment(self._output, self._input, self._input2)
+         return self.__unpack(self._output)
+ 
+@@ -1006,7 +1006,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             the input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.is_independent>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         return self.__is_independent(self._input)
+ 
+     # connectivity
+@@ -1142,8 +1142,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         cdef bitset_t SS, TT
+         bitset_init(SS, self._groundset_size)
+         bitset_init(TT, self._groundset_size)
+-        self.__pack(SS,S)
+-        self.__pack(TT,T)
++        self._pack(SS,S)
++        self._pack(TT,T)
+         #F = set(self.groundset()) - (S | T)
+         cdef bitset_t F, I
+         bitset_init(F, self._groundset_size)
+@@ -1421,7 +1421,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         Rcoflats = SetSystem(self._E)
+         i = 0
+         bitset_clear(todo[0])
+-        self.__coclosure(coflats[0], todo[0])
++        self._coclosure_internal(coflats[0], todo[0])
+         bitset_complement(todo[0], coflats[0])
+         self._coflats_rec(Rcoflats, r, coflats, todo, 0, 0)
+         for i in range(r + 1):
+@@ -1443,7 +1443,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         while e >= 0:
+             bitset_copy(self._input, coflats[i])
+             bitset_add(self._input, e)
+-            self.__coclosure(coflats[i + 1], self._input)
++            self._coclosure_internal(coflats[i + 1], self._input)
+             bitset_difference(todo[i], todo[i], coflats[i + 1])
+             bitset_difference(todo[i + 1], coflats[i + 1], coflats[i])
+             if bitset_first(todo[i + 1]) == e:
+@@ -2397,7 +2397,7 @@ cdef class BasisExchangeMatroid(Matroid):
+                 # Set current basis to Y
+                 bitset_difference(self._inside, self._current_basis, BB._subsets[pointerY])
+                 bitset_difference(self._outside, BB._subsets[pointerY], self._current_basis)
+-                self.__move(self._inside, self._outside)
++                self._move(self._inside, self._outside)
+                 if not bitset_eq(self._current_basis, BB._subsets[pointerY]):
+                     # We failed to set the current basis to Y through basis exchanges.
+                     # Therefore, the exchange axioms are violated!
+@@ -2409,7 +2409,7 @@ cdef class BasisExchangeMatroid(Matroid):
+                     foundpair = False
+                     y = bitset_first(self._input2)
+                     while y >= 0:  # for y in Y-X
+-                        if self.__is_exchange_pair(y, x):
++                        if self._is_exchange_pair(y, x):
+                             foundpair = True
+                             y = -1
+                         else:
+diff --git a/src/sage/matroids/basis_matroid.pyx b/src/sage/matroids/basis_matroid.pyx
+index 3ac43112627..c1b6e9b04c8 100644
+--- a/src/sage/matroids/basis_matroid.pyx
++++ b/src/sage/matroids/basis_matroid.pyx
+@@ -219,7 +219,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+                     raise ValueError("basis has wrong cardinality.")
+                 if not b.issubset(self._groundset):
+                     raise ValueError("basis is not a subset of the groundset")
+-                self.__pack(self._b, b)
++                self._pack(self._b, b)
+                 i = set_to_index(self._b)
+                 if not bitset_in(self._bb, i):
+                     self._bcount += 1
+@@ -234,7 +234,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+                         raise ValueError("nonbasis has wrong cardinality")
+                     if not b.issubset(self._groundset):
+                         raise ValueError("nonbasis is not a subset of the groundset")
+-                    self.__pack(self._b, b)
++                    self._pack(self._b, b)
+                     i = set_to_index(self._b)
+                     if bitset_in(self._bb, i):
+                         self._bcount -= 1
+@@ -263,7 +263,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+ 
+     # support for parent BasisExchangeMatroid
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:      # test if current_basis-x + y is a basis
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:      # test if current_basis-x + y is a basis
+         """
+         Test if `B-e + f` is a basis of the current matroid.
+ 
+@@ -326,7 +326,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+             sage: M._is_basis(set(['a', 'b', 'c', 'd']))
+             False
+         """
+-        self.__pack(self._b, X)
++        self._pack(self._b, X)
+         return bitset_in(self._bb, set_to_index(self._b))
+ 
+     # dual and minors
+@@ -557,7 +557,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+ 
+         """
+         M = BasisMatroid(M=self)
+-        M.__relabel(l)
++        M._relabel(l)
+         return M
+ 
+     # enumeration
+@@ -1177,7 +1177,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+ 
+         """
+         N = BasisMatroid(M=self)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo=None):
+@@ -1201,7 +1201,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+         if memo is None:
+             memo = {}
+         N = BasisMatroid(M=self)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __reduce__(self):
+@@ -1230,7 +1230,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+         """
+         import sage.matroids.unpickling
+         BB = bitset_pickle(self._bb)
+-        data = (self._E, self._matroid_rank, getattr(self, '__custom_name'), BB)
++        data = (self._E, self._matroid_rank, self.get_custom_name(), BB)
+         version = 0
+         return sage.matroids.unpickling.unpickle_basis_matroid, (version, data)
+ 
+diff --git a/src/sage/matroids/circuit_closures_matroid.pyx b/src/sage/matroids/circuit_closures_matroid.pyx
+index 402822b2dc6..4e79b0575e2 100644
+--- a/src/sage/matroids/circuit_closures_matroid.pyx
++++ b/src/sage/matroids/circuit_closures_matroid.pyx
+@@ -513,8 +513,7 @@ cdef class CircuitClosuresMatroid(Matroid):
+         N._groundset = self._groundset
+         N._circuit_closures = self._circuit_closures
+         N._matroid_rank = self._matroid_rank
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo=None):
+@@ -539,8 +538,7 @@ cdef class CircuitClosuresMatroid(Matroid):
+         from copy import deepcopy
+         # Since matroids are immutable, N cannot reference itself in correct code, so no need to worry about the recursion.
+         N = CircuitClosuresMatroid(groundset=deepcopy(self._groundset, memo), circuit_closures=deepcopy(self._circuit_closures, memo))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -570,7 +568,7 @@ cdef class CircuitClosuresMatroid(Matroid):
+              4: {{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}}}
+         """
+         import sage.matroids.unpickling
+-        data = (self._groundset, self._circuit_closures, getattr(self, '__custom_name'))
++        data = (self._groundset, self._circuit_closures, self.get_custom_name())
+         version = 0
+         return sage.matroids.unpickling.unpickle_circuit_closures_matroid, (version, data)
+ 
+diff --git a/src/sage/matroids/dual_matroid.py b/src/sage/matroids/dual_matroid.py
+index 804e43f035b..da6639827e4 100644
+--- a/src/sage/matroids/dual_matroid.py
++++ b/src/sage/matroids/dual_matroid.py
+@@ -519,9 +519,7 @@ def __copy__(self):
+ 
+         """
+         N = DualMatroid(self._matroid)
+-        if getattr(self, '__custom_name') is not None:
+-            # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -543,10 +541,7 @@ def __deepcopy__(self, memo={}):
+         """
+         from copy import deepcopy
+         N = DualMatroid(deepcopy(self._matroid, memo))
+-        if getattr(self, '__custom_name') is not None:
+-            # because of name wrangling, this is not caught by the
+-            # default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -575,6 +570,6 @@ def __reduce__(self):
+              4: {{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}}}'
+         """
+         import sage.matroids.unpickling
+-        data = (self._matroid, getattr(self, '__custom_name'))
++        data = (self._matroid, self.get_custom_name())
+         version = 0
+         return sage.matroids.unpickling.unpickle_dual_matroid, (version, data)
+diff --git a/src/sage/matroids/graphic_matroid.py b/src/sage/matroids/graphic_matroid.py
+index 5216ef11517..c727dc54e52 100644
+--- a/src/sage/matroids/graphic_matroid.py
++++ b/src/sage/matroids/graphic_matroid.py
+@@ -481,8 +481,7 @@ def __copy__(self):
+             False
+         """
+         N = GraphicMatroid(self._G)
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -502,8 +501,7 @@ def __deepcopy__(self, memo={}):
+         """
+         # The only real difference between this and __copy__() is the memo
+         N = GraphicMatroid(deepcopy(self._G, memo))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -519,7 +517,7 @@ def __reduce__(self):
+             Graphic matroid of rank 9 on 15 elements
+         """
+         from .unpickling import unpickle_graphic_matroid
+-        data = (self._G, getattr(self, '__custom_name'))
++        data = (self._G, self.get_custom_name())
+         version = 0
+         return unpickle_graphic_matroid, (version, data)
+ 
+diff --git a/src/sage/matroids/linear_matroid.pxd b/src/sage/matroids/linear_matroid.pxd
+index 014c8aef57d..9aebd446b68 100644
+--- a/src/sage/matroids/linear_matroid.pxd
++++ b/src/sage/matroids/linear_matroid.pxd
+@@ -15,7 +15,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+     cpdef characteristic(self)
+ 
+     cdef list _setup_internal_representation(self, matrix, reduced_matrix, ring, keep_initial_representation)
+-    cdef __exchange_value(self, long x, long y)
++    cdef _exchange_value_internal(self, long x, long y)
+ 
+     cpdef representation(self, B=*, reduced=*, labels=*, order=*, lift_map=*)
+     cpdef _current_rows_cols(self, B=*)
+diff --git a/src/sage/matroids/linear_matroid.pyx b/src/sage/matroids/linear_matroid.pyx
+index 61452e80c48..36f563aa433 100644
+--- a/src/sage/matroids/linear_matroid.pyx
++++ b/src/sage/matroids/linear_matroid.pyx
+@@ -391,13 +391,13 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         """
+         return characteristic(self._A)
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return self._A.is_nonzero(self._prow[x], self._prow[y])
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         """
+         Put element indexed by ``x`` into basis, taking out element ``y``.
+         Assumptions are that this is a valid basis exchange.
+@@ -420,9 +420,9 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         self._A.set_unsafe(px, py, pivi)
+         self._prow[y] = px
+         self._prow[x] = py
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -605,7 +605,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+                     self._representation = self._basic_representation(B)
+                 A = self._representation
+             else:
+-                B = self.__subset(B)
++                B = self._subset_internal(B)
+                 A = self._basic_representation(B)
+             A = A.matrix_from_rows_and_columns(range(A.nrows()), order_idx)
+             if lift_map is None:
+@@ -622,7 +622,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+             if B is None:
+                 B = frozenset(self.basis())
+             else:
+-                B = self.__subset(B)
++                B = self._subset_internal(B)
+             A = self._reduced_representation(B)
+             R, C = self._current_rows_cols()
+             Ri = []
+@@ -1493,7 +1493,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+             sage: M._exchange_value(1, 3)
+             4
+         """
+-        return self.__exchange_value(self._idx[e], self._idx[f])
++        return self._exchange_value_internal(self._idx[e], self._idx[f])
+ 
+     cpdef fundamental_cycle(self, B, e):
+         """
+@@ -2909,7 +2909,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = LinearMatroid(groundset=rows + cols, reduced_matrix=self._A)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -2930,7 +2930,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = LinearMatroid(groundset=deepcopy(rows + cols, memo), reduced_matrix=deepcopy(self._A, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -2979,7 +2979,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+             rows, cols = self._current_rows_cols()
+             gs = rows + cols
+             reduced = True
+-        data = (A, gs, reduced, getattr(self, '__custom_name'))
++        data = (A, gs, reduced, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_linear_matroid, (version, data)
+ 
+ # Binary matroid
+@@ -3152,20 +3152,20 @@ cdef class BinaryMatroid(LinearMatroid):
+         """
+         return 2
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<BinaryMatrix>self._A).is_nonzero(self._prow[x], y)
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         r"""
+         Replace ``self.basis() with ``self.basis() - x + y``. Internal method, does no checks.
+         """
+         cdef long p = self._prow[x]
+         self._A.pivot(p, y)   # Not a Sage matrix operation
+         self._prow[y] = p
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+     cdef  __fundamental_cocircuit(self, bitset_t C, long x):
+         r"""
+@@ -3173,18 +3173,18 @@ cdef class BinaryMatroid(LinearMatroid):
+         """
+         bitset_copy(C, (<BinaryMatrix>self._A)._M[self._prow[x]])
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``coclosure``.
+ 
+-        This function overrides the internal function BasisExchangeMatroid.__coclosure() of the parent class.
++        This function overrides the internal function BasisExchangeMatroid._coclosure_internal() of the parent class.
+         The implementation should be more efficient for BinaryMatroid, due to the fact that in this class,
+         __fundamental_cocircuit is much faster than __fundamental_circuit.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+         bitset_copy(R, F)
+         bitset_difference(self._inside, self._current_basis, F)
+@@ -3196,7 +3196,7 @@ cdef class BinaryMatroid(LinearMatroid):
+                 bitset_add(R, y)
+             y = bitset_next(self._inside, y + 1)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -3964,7 +3964,7 @@ cdef class BinaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = BinaryMatroid(groundset=self._E, matrix=self._A, basis=basis)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -3989,7 +3989,7 @@ cdef class BinaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = BinaryMatroid(groundset=deepcopy(self._E, memo), matrix=deepcopy(self._A, memo), basis=deepcopy(basis, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -4047,7 +4047,7 @@ cdef class BinaryMatroid(LinearMatroid):
+             A = self._A
+             # current basis ordered so matrix cols form identity matrix:
+             basis = self._current_rows_cols()[0]
+-        data = (A, gs, basis, getattr(self, '__custom_name'))
++        data = (A, gs, basis, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_binary_matroid, (version, data)
+ 
+ cdef class TernaryMatroid(LinearMatroid):
+@@ -4220,20 +4220,20 @@ cdef class TernaryMatroid(LinearMatroid):
+         """
+         return 3
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<TernaryMatrix>self._A).is_nonzero(self._prow[x], y)
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         r"""
+         Replace ``self.basis() with ``self.basis() - x + y``. Internal method, does no checks.
+         """
+         cdef long p = self._prow[x]
+         self._A.pivot(p, y)   # Not a Sage matrix operation
+         self._prow[y] = p
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+     cdef  __fundamental_cocircuit(self, bitset_t C, long x):
+         r"""
+@@ -4241,18 +4241,18 @@ cdef class TernaryMatroid(LinearMatroid):
+         """
+         bitset_copy(C, (<TernaryMatrix>self._A)._M0[self._prow[x]])
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``coclosure``.
+ 
+-        This function overrides the internal function BasisExchangeMatroid.__coclosure() of the parent class.
++        This function overrides the internal function BasisExchangeMatroid._coclosure_internal() of the parent class.
+         The implementation should be more efficient for TernaryMatroid, due to the fact that in this class,
+         __fundamental_cocircuit is much faster than __fundamental_circuit.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+         bitset_copy(R, F)
+         bitset_difference(self._inside, self._current_basis, F)
+@@ -4264,7 +4264,7 @@ cdef class TernaryMatroid(LinearMatroid):
+                 bitset_add(R, y)
+             y = bitset_next(self._inside, y + 1)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -4858,7 +4858,7 @@ cdef class TernaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = TernaryMatroid(groundset=self._E, matrix=self._A, basis=basis)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -4883,7 +4883,7 @@ cdef class TernaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = TernaryMatroid(groundset=deepcopy(self._E, memo), matrix=deepcopy(self._A, memo), basis=deepcopy(basis, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -4945,7 +4945,7 @@ cdef class TernaryMatroid(LinearMatroid):
+             A = self._A
+             # current basis ordered so matrix cols form identity matrix:
+             basis = self._current_rows_cols()[0]
+-        data = (A, gs, basis, getattr(self, '__custom_name'))
++        data = (A, gs, basis, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_ternary_matroid, (version, data)
+ 
+ # Quaternary Matroids
+@@ -5122,20 +5122,20 @@ cdef class QuaternaryMatroid(LinearMatroid):
+         """
+         return 2
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<QuaternaryMatrix>self._A).is_nonzero(self._prow[x], y)
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         r"""
+         Replace ``self.basis() with ``self.basis() - x + y``. Internal method, does no checks.
+         """
+         cdef long p = self._prow[x]
+         self._A.pivot(p, y)   # Not a Sage matrix operation
+         self._prow[y] = p
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+     cdef  __fundamental_cocircuit(self, bitset_t C, long x):
+         r"""
+@@ -5143,18 +5143,18 @@ cdef class QuaternaryMatroid(LinearMatroid):
+         """
+         bitset_union(C, (<QuaternaryMatrix>self._A)._M0[self._prow[x]], (<QuaternaryMatrix>self._A)._M1[self._prow[x]])
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``coclosure``.
+ 
+-        This function overrides the internal function BasisExchangeMatroid.__coclosure() of the parent class.
++        This function overrides the internal function BasisExchangeMatroid._coclosure_internal() of the parent class.
+         The implementation should be more efficient for QuaternaryMatroid, due to the fact that in this class,
+         __fundamental_cocircuit is much faster than __fundamental_circuit.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+         bitset_copy(R, F)
+         bitset_difference(self._inside, self._current_basis, F)
+@@ -5166,7 +5166,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+                 bitset_add(R, y)
+             y = bitset_next(self._inside, y + 1)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -5589,7 +5589,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = QuaternaryMatroid(groundset=self._E, matrix=self._A, basis=basis)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -5614,7 +5614,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = QuaternaryMatroid(groundset=deepcopy(self._E, memo), matrix=deepcopy(self._A, memo), basis=deepcopy(basis, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -5672,7 +5672,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+             A = self._A
+             # current basis ordered so matrix cols form identity matrix:
+             basis = self._current_rows_cols()[0]
+-        data = (A, gs, basis, getattr(self, '__custom_name'))
++        data = (A, gs, basis, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_quaternary_matroid, (version, data)
+ 
+ # Regular Matroids
+@@ -5838,13 +5838,13 @@ cdef class RegularMatroid(LinearMatroid):
+         """
+         return 0
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<PlusMinusOneMatrix>self._A).is_nonzero(self._prow[x], self._prow[y])
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         """
+         Put element indexed by ``x`` into basis, taking out element ``y``. Assumptions are that this is a valid basis exchange.
+ 
+@@ -5867,9 +5867,9 @@ cdef class RegularMatroid(LinearMatroid):
+         (<PlusMinusOneMatrix>self._A).set(px, py, pivi)   # Not a Sage matrix operation
+         self._prow[y] = px
+         self._prow[x] = py
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+ 
+@@ -6524,7 +6524,7 @@ cdef class RegularMatroid(LinearMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = RegularMatroid(groundset=rows + cols, reduced_matrix=self._A)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -6544,7 +6544,7 @@ cdef class RegularMatroid(LinearMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = RegularMatroid(groundset=deepcopy(rows + cols, memo), reduced_matrix=deepcopy(self._A, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -6593,5 +6593,5 @@ cdef class RegularMatroid(LinearMatroid):
+             rows, cols = self._current_rows_cols()
+             gs = rows + cols
+             reduced = True
+-        data = (A, gs, reduced, getattr(self, '__custom_name'))
++        data = (A, gs, reduced, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_regular_matroid, (version, data)
+diff --git a/src/sage/matroids/matroid.pxd b/src/sage/matroids/matroid.pxd
+index fe6c07e3b71..e9ddfec96ae 100644
+--- a/src/sage/matroids/matroid.pxd
++++ b/src/sage/matroids/matroid.pxd
+@@ -1,8 +1,7 @@
+ from sage.structure.sage_object cimport SageObject
+ 
+ cdef class Matroid(SageObject):
+-    cdef public __custom_name
+-    cdef public _custom_name
++    cdef public _SageObject__custom_name
+     cdef public _cached_info
+     cdef int _stored_full_rank
+     cdef int _stored_size
+@@ -37,7 +36,7 @@ cdef class Matroid(SageObject):
+     cpdef _line_length(self, F)
+     cpdef _extension(self, element, hyperplanes)
+ 
+-    cdef inline __subset(self, X):
++    cdef inline _subset_internal(self, X):
+         """
+         Convert ``X`` to a ``frozenset`` and check that it is a subset
+         of the groundset.
+diff --git a/src/sage/matroids/matroid.pyx b/src/sage/matroids/matroid.pyx
+index dcee87ea49c..8ac5ec3f678 100644
+--- a/src/sage/matroids/matroid.pyx
++++ b/src/sage/matroids/matroid.pyx
+@@ -1307,7 +1307,7 @@ cdef class Matroid(SageObject):
+             TypeError: 'sage.rings.integer.Integer' object is not iterable
+         """
+         # Call corresponding Cython method
+-        return self.__subset(X)
++        return self._subset_internal(X)
+ 
+     def _subset_all(self, X):
+         """
+@@ -1374,7 +1374,7 @@ cdef class Matroid(SageObject):
+         """
+         if X is None:
+             return self.full_rank()
+-        return self._rank(self.__subset(X))
++        return self._rank(self._subset_internal(X))
+ 
+     cpdef full_rank(self):
+         r"""
+@@ -1453,7 +1453,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._max_independent(self.__subset(X))
++        return self._max_independent(self._subset_internal(X))
+ 
+     cpdef circuit(self, X=None):
+         """
+@@ -1558,7 +1558,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._closure(self.__subset(X))
++        return self._closure(self._subset_internal(X))
+ 
+     cpdef k_closure(self, X, k):
+         r"""
+@@ -1597,7 +1597,7 @@ cdef class Matroid(SageObject):
+             sage: sorted(M.k_closure({0,1}, 4))
+             [0, 1, 4]
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         cdef int cur
+         cdef frozenset S, cl
+         cur = 0
+@@ -1644,7 +1644,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         Y = self.__subset_all(Y)
+         return self._augment(X, Y.difference(X))
+ 
+@@ -1781,7 +1781,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._max_coindependent(self.__subset(X))
++        return self._max_coindependent(self._subset_internal(X))
+ 
+     cpdef coclosure(self, X):
+         """
+@@ -1813,7 +1813,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._coclosure(self.__subset(X))
++        return self._coclosure(self._subset_internal(X))
+ 
+     cpdef cocircuit(self, X=None):
+         """
+@@ -1947,7 +1947,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_independent(self.__subset(X))
++        return self._is_independent(self._subset_internal(X))
+ 
+     cpdef is_dependent(self, X):
+         r"""
+@@ -1973,7 +1973,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return not self._is_independent(self.__subset(X))
++        return not self._is_independent(self._subset_internal(X))
+ 
+     cpdef is_basis(self, X):
+         r"""
+@@ -1999,7 +1999,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         if len(X) != self.full_rank():
+             return False
+         return self._is_basis(X)
+@@ -2035,7 +2035,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_closed(self.__subset(X))
++        return self._is_closed(self._subset_internal(X))
+ 
+     cpdef is_subset_k_closed(self, X, int k):
+         r"""
+@@ -2118,7 +2118,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_circuit(self.__subset(X))
++        return self._is_circuit(self._subset_internal(X))
+ 
+     cpdef coloops(self):
+         r"""
+@@ -2178,7 +2178,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_coindependent(self.__subset(X))
++        return self._is_coindependent(self._subset_internal(X))
+ 
+     cpdef is_codependent(self, X):
+         r"""
+@@ -2211,7 +2211,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return not self._is_coindependent(self.__subset(X))
++        return not self._is_coindependent(self._subset_internal(X))
+ 
+     cpdef is_cobasis(self, X):
+         r"""
+@@ -2245,7 +2245,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         if len(X) != self.full_corank():
+             return False
+         return self._is_cobasis(X)
+@@ -2282,7 +2282,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_cocircuit(self.__subset(X))
++        return self._is_cocircuit(self._subset_internal(X))
+ 
+     cpdef is_coclosed(self, X):
+         r"""
+@@ -2315,7 +2315,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_coclosed(self.__subset(X))
++        return self._is_coclosed(self._subset_internal(X))
+ 
+     # verification
+ 
+@@ -4868,10 +4868,10 @@ cdef class Matroid(SageObject):
+             sage: M.connectivity('ab', 'cd')
+             2
+         """
+-        S = self.__subset(S)
++        S = self._subset_internal(S)
+         if T is None:
+             return self._rank(S) + self._rank(self.groundset()-S) - self.full_rank()
+-        T = self.__subset(T)
++        T = self._subset_internal(T)
+         if S.intersection(T):
+             raise ValueError("S and T are not disjoint")
+         return len(self._link(S, T)[0]) - self.full_rank() + self._rank(S) + self._rank(T)
+@@ -4956,8 +4956,8 @@ cdef class Matroid(SageObject):
+             sage: N.connectivity(S)
+             2
+         """
+-        S = self.__subset(S)
+-        T = self.__subset(T)
++        S = self._subset_internal(S)
++        T = self._subset_internal(T)
+         if not S.isdisjoint(T):
+             raise ValueError("S and T are not disjoint")
+         return self._link(S, T)
+diff --git a/src/sage/matroids/minor_matroid.py b/src/sage/matroids/minor_matroid.py
+index c0e756917f5..98856348ac1 100644
+--- a/src/sage/matroids/minor_matroid.py
++++ b/src/sage/matroids/minor_matroid.py
+@@ -486,8 +486,7 @@ def __copy__(self):
+             True
+         """
+         N = MinorMatroid(self._matroid, self._contractions, self._deletions)
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -512,8 +511,7 @@ def __deepcopy__(self, memo={}):
+         from copy import deepcopy
+         # Since matroids are immutable, N cannot reference itself in correct code, so no need to worry about the recursion.
+         N = MinorMatroid(deepcopy(self._matroid, memo), deepcopy(self._contractions, memo), deepcopy(self._deletions, memo))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -534,6 +532,6 @@ def __reduce__(self):
+              4: {{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}}}
+         """
+         import sage.matroids.unpickling
+-        data = (self._matroid, self._contractions, self._deletions, getattr(self, '__custom_name'))
++        data = (self._matroid, self._contractions, self._deletions, self.get_custom_name())
+         version = 0
+         return sage.matroids.unpickling.unpickle_minor_matroid, (version, data)
+diff --git a/src/sage/matroids/rank_matroid.py b/src/sage/matroids/rank_matroid.py
+index 4633ff0a792..6c4e9470ada 100644
+--- a/src/sage/matroids/rank_matroid.py
++++ b/src/sage/matroids/rank_matroid.py
+@@ -267,9 +267,7 @@ def __copy__(self):
+         N = RankMatroid(groundset=[], rank_function=None)
+         N._groundset = self._groundset
+         N._rank_function = self._rank_function
+-        if getattr(self, '__custom_name') is not None:
+-            # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -293,8 +291,7 @@ def __deepcopy__(self, memo={}):
+         from copy import deepcopy
+         # Since matroids are immutable, N cannot reference itself in correct code, so no need to worry about the recursion.
+         N = RankMatroid(groundset=deepcopy(self._groundset), rank_function=deepcopy(self._rank_function))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+diff --git a/src/sage/misc/cachefunc.pxd b/src/sage/misc/cachefunc.pxd
+index d3cc677dece..8e5d9dfa42a 100644
+--- a/src/sage/misc/cachefunc.pxd
++++ b/src/sage/misc/cachefunc.pxd
+@@ -5,7 +5,7 @@ cpdef cache_key(o)
+ 
+ cdef class CachedFunction():
+     cdef public str __name__
+-    cdef public str __module__
++    cdef public str __cached_module__
+     cdef ArgumentFixer _argument_fixer
+     cdef public f
+     cdef public cache  # not always of type <dict>
+@@ -20,7 +20,7 @@ cdef class CachedFunction():
+ cdef class CachedMethod():
+     cdef str _cache_name
+     cdef public str __name__
+-    cdef public str __module__
++    cdef public str __cached_module__
+     cdef CachedFunction _cachedfunc
+     cdef Py_ssize_t nargs
+     cpdef _get_instance_cache(self, inst)
+diff --git a/src/sage/misc/cachefunc.pyx b/src/sage/misc/cachefunc.pyx
+index a307c33e32b..8aa30a85272 100644
+--- a/src/sage/misc/cachefunc.pyx
++++ b/src/sage/misc/cachefunc.pyx
+@@ -60,7 +60,7 @@ be used::
+ 
+ We can proceed similarly for cached methods of Cython classes,
+ provided that they allow attribute assignment or have a public
+-attribute ``__cached_methods`` of type ``<dict>``. Since
++attribute ``_cached_methods`` of type ``<dict>``. Since
+ :trac:`11115`, this is the case for all classes inheriting from
+ :class:`~sage.structure.parent.Parent`. See below for a more explicit
+ example. By :trac:`12951`, cached methods of extension classes can
+@@ -301,14 +301,14 @@ ought to be chosen. A typical example is
+ 
+ By :trac:`12951`, the cached_method decorator is also supported on non-c(p)def
+ methods of extension classes, as long as they either support attribute assignment
+-or have a public attribute of type ``<dict>`` called ``__cached_methods``. The
++or have a public attribute of type ``<dict>`` called ``_cached_methods``. The
+ latter is easy::
+ 
+     sage: # needs sage.misc.cython
+     sage: cython_code = [
+     ....: "from sage.misc.cachefunc import cached_method",
+     ....: "cdef class MyClass:",
+-    ....: "    cdef public dict __cached_methods",
++    ....: "    cdef public dict _cached_methods",
+     ....: "    @cached_method",
+     ....: "    def f(self, a,b):",
+     ....: "        return a*b"]
+@@ -774,13 +774,17 @@ cdef class CachedFunction():
+         else:
+             self.__name__ = f.__name__
+         try:
+-            self.__module__ = f.__module__
++            self.__cached_module__ = f.__module__
+         except AttributeError:
+-            self.__module__ = f.__objclass__.__module__
++            self.__cached_module__ = f.__objclass__.__module__
+         if argument_fixer is not None: # it is None unless the argument fixer
+                                        # was known previously. See #15038.
+             self._argument_fixer = argument_fixer
+ 
++    @property
++    def __module__(self):
++        return self.__cached_module__
++
+     cdef get_key_args_kwds(self, tuple args, dict kwds):
+         """
+         Return the key in the cache to be used when ``args`` and
+@@ -841,7 +845,7 @@ cdef class CachedFunction():
+             sage: loads(dumps(hilbert_class_polynomial)) is hilbert_class_polynomial  #indirect doctest                 # needs sage.schemes
+             True
+         """
+-        return _cached_function_unpickle, (self.__module__, self.__name__, self.cache)
++        return _cached_function_unpickle, (self.__cached_module__, self.__name__, self.cache)
+ 
+     #########
+     ## Introspection
+@@ -2019,7 +2023,7 @@ cdef class CachedMethodCaller(CachedFunction):
+         This getter attempts to assign a bound method as an
+         attribute to the given instance. If this is not
+         possible (for example, for some extension classes),
+-        it is attempted to find an attribute ``__cached_methods``,
++        it is attempted to find an attribute ``_cached_methods``,
+         and store/retrieve the bound method there. In that
+         way, cached methods can be implemented for extension
+         classes deriving from :class:`~sage.structure.parent.Parent`
+@@ -2085,7 +2089,7 @@ cdef class CachedMethodCaller(CachedFunction):
+         """
+         # This is for Parents or Elements that do not allow attribute assignment
+         try:
+-            return (<dict>inst.__cached_methods)[self._cachedmethod._cachedfunc.__name__]
++            return (<dict>inst._cached_methods)[self._cachedmethod._cachedfunc.__name__]
+         except (AttributeError, TypeError, KeyError):
+             pass
+ 
+@@ -2100,10 +2104,10 @@ cdef class CachedMethodCaller(CachedFunction):
+         except AttributeError:
+             pass
+         try:
+-            if inst.__cached_methods is None:
+-                inst.__cached_methods = {self._cachedmethod._cachedfunc.__name__ : Caller}
++            if inst._cached_methods is None:
++                inst._cached_methods = {self._cachedmethod._cachedfunc.__name__ : Caller}
+             else:
+-                (<dict>inst.__cached_methods)[self._cachedmethod._cachedfunc.__name__] = Caller
++                (<dict>inst._cached_methods)[self._cachedmethod._cachedfunc.__name__] = Caller
+         except AttributeError:
+             pass
+         return Caller
+@@ -2421,7 +2425,7 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
+         This getter attempts to assign a bound method as an
+         attribute to the given instance. If this is not
+         possible (for example, for some extension classes),
+-        it is attempted to find an attribute ``__cached_methods``,
++        it is attempted to find an attribute ``_cached_methods``,
+         and store/retrieve the bound method there. In that
+         way, cached methods can be implemented for extension
+         classes deriving from :class:`~sage.structure.parent.Parent`
+@@ -2472,7 +2476,7 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
+         """
+         # This is for Parents or Elements that do not allow attribute assignment
+         try:
+-            return (<dict>inst.__cached_methods)[self.__name__]
++            return (<dict>inst._cached_methods)[self.__name__]
+         except (AttributeError, TypeError, KeyError):
+             pass
+         Caller = CachedMethodCallerNoArgs(inst, self.f, name=self.__name__, do_pickle=self.do_pickle)
+@@ -2482,10 +2486,10 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
+         except AttributeError:
+             pass
+         try:
+-            if inst.__cached_methods is None:
+-                inst.__cached_methods = {self.__name__ : Caller}
++            if inst._cached_methods is None:
++                inst._cached_methods = {self.__name__ : Caller}
+             else:
+-                (<dict>inst.__cached_methods)[self.__name__] = Caller
++                (<dict>inst._cached_methods)[self.__name__] = Caller
+         except AttributeError:
+             pass
+         return Caller
+@@ -2698,7 +2702,11 @@ cdef class CachedMethod():
+         self._cache_name = '_cache__' + (name or f.__name__)
+         self._cachedfunc = CachedFunction(f, classmethod=True, name=name, key=key, do_pickle=do_pickle)
+         self.__name__ = self._cachedfunc.__name__
+-        self.__module__ = self._cachedfunc.__module__
++        self.__cached_module__ = self._cachedfunc.__module__
++
++    @property
++    def __module__(self):
++        return self.__cached_module__
+ 
+     def __call__(self, inst, *args, **kwds):
+         """
+@@ -2828,7 +2836,7 @@ cdef class CachedMethod():
+         except AttributeError:
+             name = self.__name__
+         try:
+-            return (<dict>inst.__cached_methods)[name]
++            return (<dict>inst._cached_methods)[name]
+         except (AttributeError, TypeError, KeyError):
+             pass
+         # Apparently we need to construct the caller.
+@@ -2840,8 +2848,6 @@ cdef class CachedMethod():
+                 try:
+                     if METH_NOARGS&PyCFunction_GetFlags(f.__get__(inst,cls)):
+                         self.nargs = 1
+-                    else:
+-                        self.nargs = 2
+                 except Exception:
+                     pass
+             if self.nargs == 0:
+@@ -2864,10 +2870,10 @@ cdef class CachedMethod():
+         except AttributeError:
+             pass
+         try:
+-            if inst.__cached_methods is None:
+-                inst.__cached_methods = {name : Caller}
++            if inst._cached_methods is None:
++                inst._cached_methods = {name : Caller}
+             else:
+-                (<dict>inst.__cached_methods)[name] = Caller
++                (<dict>inst._cached_methods)[name] = Caller
+         except AttributeError:
+             pass
+         return Caller
+@@ -2965,12 +2971,12 @@ cdef class CachedSpecialMethod(CachedMethod):
+                 D = inst.__dict__
+             except (TypeError, AttributeError):
+                 try:
+-                    D = inst.__cached_methods
++                    D = inst._cached_methods
+                 except (TypeError, AttributeError):
+-                    raise TypeError("For a cached special method, either attribute assignment or a public '__cached_methods' attribute of type <dict> is needed")
++                    raise TypeError("For a cached special method, either attribute assignment or a public '_cached_methods' attribute of type <dict> is needed")
+             if D is None:
+-                # This can only happen in the case of __cached_methods
+-                D = inst.__cached_methods = {}
++                # This can only happen in the case of _cached_methods
++                D = inst._cached_methods = {}
+             else:
+                 try:
+                     return D[name]
+@@ -3298,13 +3304,13 @@ cdef class CachedInParentMethod(CachedMethod):
+             return P.__dict__.setdefault(self._cache_name, default)
+         except AttributeError:
+             pass
+-        if not hasattr(P,'__cached_methods'):
++        if not hasattr(P,'_cached_methods'):
+             raise TypeError("The parent of this element does not allow attribute assignment\n" +
+                             "    and does not descend from the Parent base class.\n" +
+                             "    Cannot use CachedInParentMethod.")
+-        if P.__cached_methods is None:
+-            P.__cached_methods = {}
+-        return (<dict>P.__cached_methods).setdefault(self._cache_name, default)
++        if P._cached_methods is None:
++            P._cached_methods = {}
++        return (<dict>P._cached_methods).setdefault(self._cache_name, default)
+ 
+     def __get__(self, inst, cls):
+         """
+diff --git a/src/sage/misc/cython.py b/src/sage/misc/cython.py
+index f4083f3909b..5f83f585c3a 100644
+--- a/src/sage/misc/cython.py
++++ b/src/sage/misc/cython.py
+@@ -646,9 +646,9 @@ def compile_and_load(code, **kwds):
+         ....:     cdef Polynomial_rational_flint res = f._new()
+         ....:     cdef unsigned long k
+         ....:     cdef Rational z = Rational(0)
+-        ....:     for k in range(fmpq_poly_length(f.__poly)):
+-        ....:         fmpq_poly_get_coeff_mpq(z.value, f.__poly, k)
+-        ....:         fmpq_poly_set_coeff_mpq(res.__poly, n*k, z.value)
++        ....:     for k in range(fmpq_poly_length(f._poly)):
++        ....:         fmpq_poly_get_coeff_mpq(z.value, f._poly, k)
++        ....:         fmpq_poly_set_coeff_mpq(res._poly, n*k, z.value)
+         ....:     return res
+         ....: '''
+         sage: module = compile_and_load(code)  # long time
+diff --git a/src/sage/misc/fpickle.pyx b/src/sage/misc/fpickle.pyx
+index 9f80a8f31aa..37c26e431ba 100644
+--- a/src/sage/misc/fpickle.pyx
++++ b/src/sage/misc/fpickle.pyx
+@@ -124,10 +124,12 @@ def call_pickled_function(fpargs):
+ def pickleMethod(method):
+     'support function for copyreg to pickle method refs'
+ 
+-    # Note: On Python 3 there is no .im_class but we can get the instance's
+-    # class through .__self__.__class__
+-    cls = getattr(method, 'im_class', method.__self__.__class__)
+-    return (unpickleMethod, (method.__func__.__name__, method.__self__, cls))
++    if isinstance(method.__self__, type):
++        # This is a class method, so get it from the type directly
++        return (getattr, (method.__self__, method.__func__.__name__))
++    else:
++        cls = method.__self__.__class__
++        return (unpickleMethod, (method.__func__.__name__, method.__self__, cls))
+ 
+ 
+ def unpickleMethod(im_name,
+@@ -139,10 +141,7 @@ def unpickleMethod(im_name,
+         if __self__ is None:
+             return unbound
+ 
+-        # Note: On Python 2 "unbound methods" are just functions, so they don't
+-        # have a __func__
+-        bound = types.MethodType(getattr(unbound, '__func__', unbound),
+-                                 __self__)
++        bound = types.MethodType(unbound, __self__)
+         return bound
+     except AttributeError:
+         assert __self__ is not None, "No recourse: no instance to guess from."
+@@ -150,11 +149,8 @@ def unpickleMethod(im_name,
+         # changed around since we pickled this method, we may still be
+         # able to get it by looking on the instance's current class.
+         unbound = getattr(__self__.__class__, im_name)
+-        if __self__ is None:
+-            return unbound
+ 
+-        bound = types.MethodType(getattr(unbound, '__func__', unbound),
+-                                 __self__)
++        bound = types.MethodType(unbound, __self__)
+         return bound
+ 
+ 
+diff --git a/src/sage/misc/inherit_comparison.pyx b/src/sage/misc/inherit_comparison.pyx
+index f046f5fb8ce..aa97f664496 100644
+--- a/src/sage/misc/inherit_comparison.pyx
++++ b/src/sage/misc/inherit_comparison.pyx
+@@ -54,6 +54,8 @@ cdef class InheritComparisonMetaclass(type):
+         sage: # needs sage.misc.cython
+         sage: cython(
+         ....: '''
++        ....: cimport cython
++        ....:
+         ....: from sage.misc.inherit_comparison cimport InheritComparisonMetaclass
+         ....:
+         ....: cdef class Base():
+@@ -66,6 +68,7 @@ cdef class InheritComparisonMetaclass(type):
+         ....:         return 1
+         ....:
+         ....: cdef class DerivedWithRichcmp(Base):
++        ....:     @cython.always_allow_keywords(False)
+         ....:     def __getmetaclass__(_):
+         ....:         from sage.misc.inherit_comparison import InheritComparisonMetaclass
+         ....:         return InheritComparisonMetaclass
+diff --git a/src/sage/misc/lazy_attribute.pyx b/src/sage/misc/lazy_attribute.pyx
+index 82a0f90b775..bdbec3b3ba1 100644
+--- a/src/sage/misc/lazy_attribute.pyx
++++ b/src/sage/misc/lazy_attribute.pyx
+@@ -111,12 +111,12 @@ cdef class _lazy_attribute():
+         if a is None: # when doing cls.x for cls a class and x a lazy attribute
+             return self
+         try:
+-            # __cached_methods is supposed to be a public Cython attribute.
++            # _cached_methods is supposed to be a public Cython attribute.
+             # Apparently, these are *not* subject to name mangling.
+-            CM = getattr(a, '__cached_methods')
++            CM = getattr(a, '_cached_methods')
+             if CM is None:
+                 CM = {}
+-                setattr(a, '__cached_methods', CM)
++                setattr(a, '_cached_methods', CM)
+         except AttributeError as msg:
+             CM = None
+         if CM is not None:
+diff --git a/src/sage/misc/lazy_list.pyx b/src/sage/misc/lazy_list.pyx
+index c1fa0250a95..ba62c446b69 100644
+--- a/src/sage/misc/lazy_list.pyx
++++ b/src/sage/misc/lazy_list.pyx
+@@ -1059,7 +1059,11 @@ cdef class lazy_list_from_function(lazy_list_generic):
+             step         1
+         """
+         while len(self.cache) <= i:
+-            self.cache.append(self.callable(len(self.cache)))
++            try:
++                value = self.callable(len(self.cache))
++            except StopIteration:
++                return 1
++            self.cache.append(value)
+ 
+     def __reduce__(self):
+         r"""
+diff --git a/src/sage/misc/sageinspect.py b/src/sage/misc/sageinspect.py
+index 3dd0cc0a45b..ce5e9987027 100644
+--- a/src/sage/misc/sageinspect.py
++++ b/src/sage/misc/sageinspect.py
+@@ -224,7 +224,11 @@ def isclassinstance(obj):
+     return (not inspect.isclass(obj) and
+             hasattr(obj, '__class__') and
+             hasattr(obj.__class__, '__module__') and
+-            obj.__class__.__module__ not in builtin_mods)
++            obj.__class__.__module__ not in builtin_mods and
++            # Starting with Cython 3, Cython's builtin types have __module__ set
++            # to the shared module names like _cython_3_0_0.
++            not (isinstance(obj.__class__.__module__, str) and
++                 obj.__class__.__module__.startswith('_cython_')))
+ 
+ 
+ # Parse strings of form "File: sage/rings/rational.pyx (starting at line 1080)"
+diff --git a/src/sage/misc/session.pyx b/src/sage/misc/session.pyx
+index de649f80425..31454dac993 100644
+--- a/src/sage/misc/session.pyx
++++ b/src/sage/misc/session.pyx
+@@ -80,6 +80,8 @@ from sage.misc.persist import load, save, loads, dumps
+ 
+ state_at_init = None
+ 
++CythonFunctionType = type(lambda: None)
++
+ def init(state=None):
+     """
+     Initialize some dictionaries needed by the :func:`show_identifiers`,
+@@ -311,7 +313,7 @@ def save_session(name='sage_session', verbose=False):
+     for k in show_identifiers(hidden = True):
+         try:
+             x = state[k]
+-            if isinstance(x, (types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType, type)):
++            if isinstance(x, (types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType, CythonFunctionType, type)):
+                 raise TypeError('{} is a function, method, class or type'.format(k))
+ 
+             # We attempt to pickle *and* unpickle every variable to
+diff --git a/src/sage/modular/modsym/p1list.pxd b/src/sage/modular/modsym/p1list.pxd
+index cc24a33139b..b66f28b8ad6 100644
+--- a/src/sage/modular/modsym/p1list.pxd
++++ b/src/sage/modular/modsym/p1list.pxd
+@@ -21,7 +21,7 @@ cdef class P1List:
+     # Here we use a pointer to a function, so the if logic
+     # for normalizing an element does not need to be used
+     # every time the user calls the normalize function.
+-    cdef int (*__normalize)(int N, int u, int v,
++    cdef int (*_normalize)(int N, int u, int v,
+                             int* uu, int* vv, int* ss,
+                             int compute_s) except -1
+     cpdef index(self, int u, int v)
+diff --git a/src/sage/modular/modsym/p1list.pyx b/src/sage/modular/modsym/p1list.pyx
+index 111d408cee4..30a8f7471dd 100644
+--- a/src/sage/modular/modsym/p1list.pyx
++++ b/src/sage/modular/modsym/p1list.pyx
+@@ -723,10 +723,10 @@ cdef class P1List():
+         self.__N = N
+         if N <= 46340:
+             self.__list = p1list_int(N)
+-            self.__normalize = c_p1_normalize_int
++            self._normalize = c_p1_normalize_int
+         elif N <= 2147483647:
+             self.__list = p1list_llong(N)
+-            self.__normalize = c_p1_normalize_llong
++            self._normalize = c_p1_normalize_llong
+         else:
+             raise OverflowError("p1list not defined for such large N.")
+         self.__list.sort()
+@@ -921,7 +921,7 @@ cdef class P1List():
+         """
+         cdef int u, v, uu, vv, ss
+         u,v = self.__list[i]
+-        self.__normalize(self.__N, -u, v, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, -u, v, &uu, &vv, &ss, 0)
+         _, j = search(self.__list, (uu,vv))
+         return j
+ 
+@@ -954,7 +954,7 @@ cdef class P1List():
+         """
+         cdef int u, v, uu, vv, ss
+         u,v = self.__list[i]
+-        self.__normalize(self.__N, -v, u, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, -v, u, &uu, &vv, &ss, 0)
+         _, j = search(self.__list, (uu,vv))
+         return j
+ 
+@@ -987,7 +987,7 @@ cdef class P1List():
+         """
+         cdef int u, v, uu, vv, ss
+         u,v = self.__list[i]
+-        self.__normalize(self.__N, v, -u-v, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, v, -u-v, &uu, &vv, &ss, 0)
+         _, j = search(self.__list, (uu,vv))
+         return j
+ 
+@@ -1153,7 +1153,7 @@ cdef class P1List():
+             True
+         """
+         cdef int uu, vv, ss
+-        self.__normalize(self.__N, u, v, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, u, v, &uu, &vv, &ss, 0)
+         return (uu,vv)
+ 
+     def normalize_with_scalar(self, int u, int v):
+@@ -1186,7 +1186,7 @@ cdef class P1List():
+             True
+         """
+         cdef int uu, vv, ss
+-        self.__normalize(self.__N, u, v, &uu, &vv, &ss, 1)
++        self._normalize(self.__N, u, v, &uu, &vv, &ss, 1)
+         return (uu, vv, ss)
+ 
+     def N(self):
+diff --git a/src/sage/numerical/gauss_legendre.pyx b/src/sage/numerical/gauss_legendre.pyx
+index 5325797c7aa..96708c5b1ac 100644
+--- a/src/sage/numerical/gauss_legendre.pyx
++++ b/src/sage/numerical/gauss_legendre.pyx
+@@ -117,8 +117,8 @@ def nodes_uncached(degree, prec):
+         raise ValueError("degree=%s not supported (degree must be 3 or even)" % degree)
+     R = RealField(int(prec*3/2))
+     Rout = RealField(prec)
+-    mpfr_init2(u,R.__prec)
+-    mpfr_init2(v,R.__prec)
++    mpfr_init2(u,R._prec)
++    mpfr_init2(v,R._prec)
+     ZERO = R.zero()
+     ONE = R.one()
+     HALF = ONE/2
+diff --git a/src/sage/numerical/linear_functions.pyx b/src/sage/numerical/linear_functions.pyx
+index 5549ff436f5..f3fc6fe419c 100644
+--- a/src/sage/numerical/linear_functions.pyx
++++ b/src/sage/numerical/linear_functions.pyx
+@@ -1579,7 +1579,10 @@ cdef class LinearConstraint(LinearFunctionOrConstraint):
+         while True:
+             yield (lhs, rhs)
+             lhs = rhs
+-            rhs = next(term_iter)
++            try:
++                rhs = next(term_iter)
++            except StopIteration:
++                return
+ 
+     def inequalities(self):
+         """
+@@ -1612,7 +1615,10 @@ cdef class LinearConstraint(LinearFunctionOrConstraint):
+         while True:
+             yield (lhs, rhs)
+             lhs = rhs
+-            rhs = next(term_iter)
++            try:
++                rhs = next(term_iter)
++            except StopIteration:
++                return
+ 
+     def _repr_(self):
+         r"""
+diff --git a/src/sage/quivers/representation.py b/src/sage/quivers/representation.py
+index 9c11eb8ad0e..db82cbd7c86 100644
+--- a/src/sage/quivers/representation.py
++++ b/src/sage/quivers/representation.py
+@@ -1297,10 +1297,7 @@ def copy(self):
+             sage: v.get_element(1)
+             (1, 0)
+         """
+-        if hasattr(self, '__custom_name'):
+-            name = self.__custom_name
+-        else:
+-            name = None
++        name = self.get_custom_name()
+         return self.parent()(self._elems.copy(), name)
+ 
+ ####################################################################
+diff --git a/src/sage/rings/complex_arb.pyx b/src/sage/rings/complex_arb.pyx
+index ef432c1e945..95e615f3ee6 100644
+--- a/src/sage/rings/complex_arb.pyx
++++ b/src/sage/rings/complex_arb.pyx
+@@ -874,7 +874,7 @@ class ComplexBallField(UniqueRepresentation, sage.rings.abc.ComplexBallField):
+         cdef RealBall rb
+         cdef ComplexBall cb
+         acb_poly_init(rounded_poly)
+-        cdef long deg = acb_poly_degree(poly.__poly)
++        cdef long deg = acb_poly_degree(poly._poly)
+         if deg < 0:
+             raise ArithmeticError("taking the roots of the zero polynomial")
+         cdef acb_ptr roots = _acb_vec_init(deg)
+@@ -883,7 +883,7 @@ class ComplexBallField(UniqueRepresentation, sage.rings.abc.ComplexBallField):
+             while ((isolated < deg or any(acb_rel_accuracy_bits(&roots[i]) < tgtprec
+                                         for i in range(deg)))
+                 and prec < maxprec):
+-                acb_poly_set_round(rounded_poly, poly.__poly, prec)
++                acb_poly_set_round(rounded_poly, poly._poly, prec)
+                 maxiter = min(max(deg, 32), prec)
+                 if (prec == initial_prec):
+                     isolated = acb_poly_find_roots(roots, rounded_poly, NULL, maxiter, prec)
+diff --git a/src/sage/rings/complex_mpc.pxd b/src/sage/rings/complex_mpc.pxd
+index 762c38afbdc..f7d8cb9492c 100644
+--- a/src/sage/rings/complex_mpc.pxd
++++ b/src/sage/rings/complex_mpc.pxd
+@@ -11,7 +11,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+     cpdef _mul_(self, other)
+ 
+ cdef class MPComplexField_class(sage.rings.ring.Field):
+-    cdef readonly int __prec
++    cdef readonly int _prec
+     cdef mpc_rnd_t __rnd
+     cdef object __rnd_str
+     cdef object __real_field
+diff --git a/src/sage/rings/complex_mpc.pyx b/src/sage/rings/complex_mpc.pyx
+index b3681ff724f..c847a9302b5 100644
+--- a/src/sage/rings/complex_mpc.pyx
++++ b/src/sage/rings/complex_mpc.pyx
+@@ -307,7 +307,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+         if prec < mpfr_prec_min() or prec > mpfr_prec_max():
+             raise ValueError("prec (=%s) must be >= %s and <= %s." % (
+                 prec, mpfr_prec_min(), mpfr_prec_max()))
+-        self.__prec = prec
++        self._prec = prec
+         if not isinstance(rnd, str):
+             raise TypeError("rnd must be a string")
+         try:
+@@ -331,7 +331,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+         cdef MPComplexNumber z
+         z = MPComplexNumber.__new__(MPComplexNumber)
+         z._parent = self
+-        mpc_init2(z.value, self.__prec)
++        mpc_init2(z.value, self._prec)
+         z.init = 1
+         return z
+ 
+@@ -344,7 +344,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: MPComplexField(200, 'RNDDU') # indirect doctest
+             Complex Field with 200 bits of precision and rounding RNDDU
+         """
+-        s = "Complex Field with %s bits of precision"%self.__prec
++        s = "Complex Field with %s bits of precision"%self._prec
+         if self.__rnd != MPC_RNDNN:
+             s = s + " and rounding %s"%(self.__rnd_str)
+         return s
+@@ -465,13 +465,13 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+         if RR.has_coerce_map_from(S):
+             return self._coerce_map_via([RR], S)
+ 
+-        if isinstance(S, MPComplexField_class) and S.prec() >= self.__prec:
++        if isinstance(S, MPComplexField_class) and S.prec() >= self._prec:
+             #FIXME: What map when rounding modes differ but prec is the same ?
+             #       How to provide commutativity of morphisms ?
+             #       Change _cmp_ when done
+             return MPCtoMPC(S, self)
+ 
+-        if isinstance(S, ComplexField_class) and S.prec() >= self.__prec:
++        if isinstance(S, ComplexField_class) and S.prec() >= self._prec:
+             return CCtoMPC(S, self)
+ 
+         late_import()
+@@ -490,7 +490,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: loads(dumps(C)) == C
+             True
+         """
+-        return __create__MPComplexField_version0, (self.__prec, self.__rnd_str)
++        return __create__MPComplexField_version0, (self._prec, self.__rnd_str)
+ 
+     def __richcmp__(left, right, int op):
+         """
+@@ -513,7 +513,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+ 
+         cdef MPComplexField_class s = <MPComplexField_class>left
+         cdef MPComplexField_class o = <MPComplexField_class>right
+-        return richcmp(s.__prec, o.__prec, op)
++        return richcmp(s._prec, o._prec, op)
+ 
+     def gen(self, n=0):
+         """
+@@ -604,7 +604,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: C = MPComplexField(10, 'RNDNZ'); C.name()
+             'MPComplexField10_RNDNZ'
+         """
+-        return "MPComplexField%s_%s"%(self.__prec, self.__rnd_str)
++        return "MPComplexField%s_%s"%(self._prec, self.__rnd_str)
+ 
+     def __hash__(self):
+         """
+@@ -629,7 +629,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: MPComplexField(22).prec()
+             22
+         """
+-        return self.__prec
++        return self._prec
+ 
+     def rounding_mode(self):
+         """
+@@ -707,7 +707,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+         cdef MPComplexNumber z
+         z = MPComplexNumber.__new__(MPComplexNumber)
+         z._parent = self._parent
+-        mpc_init2(z.value, (<MPComplexField_class>self._parent).__prec)
++        mpc_init2(z.value, (<MPComplexField_class>self._parent)._prec)
+         z.init = 1
+         return z
+ 
+@@ -760,7 +760,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+         if parent is None:
+             raise TypeError
+         self._parent = parent
+-        mpc_init2(self.value, parent.__prec)
++        mpc_init2(self.value, parent._prec)
+         self.init = 1
+         if x is None: return
+         self._set(x, y, base)
+@@ -1010,7 +1010,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+             sage: i.prec()
+             2000
+         """
+-        return <MPComplexField_class>(self._parent).__prec
++        return <MPComplexField_class>(self._parent)._prec
+ 
+     def real(self):
+         """
+@@ -1571,26 +1571,6 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+         mpc_norm(x.value, self.value, (<RealField_class>x._parent).rnd)
+         return x
+ 
+-    def __rtruediv__(self, left):
+-        r"""
+-        Returns the quotient of ``left`` with ``self``, that is: ``left/self``
+-        as a complex number.
+-
+-        INPUT:
+-
+-        - ``left`` -- a complex number
+-
+-        EXAMPLES::
+-
+-            sage: MPC = MPComplexField()
+-            sage: a = MPC(2, 2)
+-            sage: a.__rtruediv__(MPC(1))
+-            0.250000000000000 - 0.250000000000000*I
+-            sage: MPC(1)/a
+-            0.250000000000000 - 0.250000000000000*I
+-        """
+-        return MPComplexNumber(self._parent, left)/self
+-
+     def __pow__(self, right, modulus):
+         """
+         Compute ``self`` raised to the power of exponent, rounded in
+@@ -2347,7 +2327,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+ 
+         cdef mpc_rnd_t rnd = (<MPComplexField_class>(self._parent)).__rnd
+ 
+-        cdef int prec = self._parent.__prec
++        cdef int prec = self._parent._prec
+ 
+         if optimal or algorithm == "principal":
+             if not isinstance(right, MPComplexNumber) or (<MPComplexNumber>right)._parent is not self._parent:
+diff --git a/src/sage/rings/complex_mpfr.pyx b/src/sage/rings/complex_mpfr.pyx
+index 33d73d81b12..61f2cadc8e4 100644
+--- a/src/sage/rings/complex_mpfr.pyx
++++ b/src/sage/rings/complex_mpfr.pyx
+@@ -1658,28 +1658,6 @@ cdef class ComplexNumber(sage.structure.element.FieldElement):
+         mpfr_clear(right_nm)
+         return x
+ 
+-    def __rtruediv__(self, left):
+-        r"""
+-        Return the quotient of left with ``self``, that is:
+-
+-        ``left/self``
+-
+-        as a complex number.
+-
+-        INPUT:
+-
+-        - ``left`` -- a complex number to divide by ``self``
+-
+-        EXAMPLES::
+-
+-            sage: a = ComplexNumber(2,0)
+-            sage: a.__rtruediv__(CC(1))
+-            0.500000000000000
+-            sage: CC(1)/a
+-            0.500000000000000
+-        """
+-        return ComplexNumber(self._parent, left)/self
+-
+     def __pow__(self, right, modulus):
+         r"""
+         Raise ``self`` to the ``right`` exponent.
+diff --git a/src/sage/rings/finite_rings/integer_mod.pxd b/src/sage/rings/finite_rings/integer_mod.pxd
+index 1e3cb81c148..351ffa25e1b 100644
+--- a/src/sage/rings/finite_rings/integer_mod.pxd
++++ b/src/sage/rings/finite_rings/integer_mod.pxd
+@@ -20,7 +20,7 @@ cdef class NativeIntStruct:
+ 
+ 
+ cdef class IntegerMod_abstract(FiniteRingElement):
+-    cdef NativeIntStruct __modulus
++    cdef NativeIntStruct _modulus
+     cdef _new_c_from_long(self, long value)
+     cdef IntegerMod_abstract _new_c_fast(self, unsigned long value)
+     cdef void set_from_mpz(self, mpz_t value)
+diff --git a/src/sage/rings/finite_rings/integer_mod.pyx b/src/sage/rings/finite_rings/integer_mod.pyx
+index b9461bd362e..d64ba5af84f 100644
+--- a/src/sage/rings/finite_rings/integer_mod.pyx
++++ b/src/sage/rings/finite_rings/integer_mod.pyx
+@@ -361,7 +361,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             ZeroDivisionError: inverse of Mod(4, 30) does not exist
+         """
+         self._parent = parent
+-        self.__modulus = parent._pyx_order
++        self._modulus = parent._pyx_order
+ 
+         if value is None:
+             return
+@@ -373,7 +373,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         if isinstance(value, Integer):
+             z = <Integer>value
+         elif isinstance(value, rational.Rational):
+-            z = value % self.__modulus.sageInteger
++            z = value % self._modulus.sageInteger
+         elif integer_check_long_py(value, &longval, &err) and not err:
+             self.set_from_long(longval)
+             return
+@@ -388,7 +388,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+                     value = py_scalar_to_element(value)
+                 if isinstance(value, Element) and value.parent().is_exact():
+                     value = sage.rings.rational_field.QQ(value)
+-                    z = value % self.__modulus.sageInteger
++                    z = value % self._modulus.sageInteger
+                 else:
+                     raise
+         self.set_from_mpz(z.value)
+@@ -397,7 +397,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         cdef type t = type(self)
+         x = <IntegerMod_abstract>t.__new__(t)
+         x._parent = self._parent
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x.set_from_ulong_fast(value)
+         return x
+ 
+@@ -405,7 +405,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         cdef type t = type(self)
+         cdef IntegerMod_abstract x = <IntegerMod_abstract>t.__new__(t)
+         x._parent = self._parent
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x.set_from_long(value)
+         return x
+ 
+@@ -529,17 +529,17 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         """
+         if self.is_zero():
+             return True
+-        m = self.__modulus.sageInteger.exact_log(2) + 1
++        m = self._modulus.sageInteger.exact_log(2) + 1
+         return (self**m).is_zero()
+ 
+     #################################################################
+     # Interfaces
+     #################################################################
+     def _pari_init_(self):
+-        return 'Mod(%s,%s)'%(str(self), self.__modulus.sageInteger)
++        return 'Mod(%s,%s)'%(str(self), self._modulus.sageInteger)
+ 
+     def __pari__(self):
+-        return self.lift().__pari__().Mod(self.__modulus.sageInteger)
++        return self.lift().__pari__().Mod(self._modulus.sageInteger)
+ 
+     def _gap_init_(self):
+         r"""
+@@ -558,7 +558,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             sage: gap(Mod(4, 48))
+             ZmodnZObj( 4, 48 )
+         """
+-        return '%s*One(ZmodnZ(%s))' % (self, self.__modulus.sageInteger)
++        return '%s*One(ZmodnZ(%s))' % (self, self._modulus.sageInteger)
+ 
+     def _magma_init_(self, magma):
+         """
+@@ -869,7 +869,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             sage: Mod(3,17).modulus()
+             17
+         """
+-        return self.__modulus.sageInteger
++        return self._modulus.sageInteger
+ 
+     def charpoly(self, var='x'):
+         """
+@@ -1229,7 +1229,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+                 modulus = R.gen()**2 - R(self)
+                 if self._parent.is_field():
+                     from .finite_field_constructor import FiniteField
+-                    Q = FiniteField(self.__modulus.sageInteger**2, y, modulus)
++                    Q = FiniteField(self._modulus.sageInteger**2, y, modulus)
+                 else:
+                     R = self.parent()['x']
+                     Q = R.quotient(modulus, names=(y,))
+@@ -1250,7 +1250,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             if all and e > 1 and not self.is_unit():
+                 if self.is_zero():
+                     # All multiples of p^ciel(e/2) vanish
+-                    return [self._parent(x) for x in range(0, self.__modulus.sageInteger, p**((e+1)/2))]
++                    return [self._parent(x) for x in range(0, self._modulus.sageInteger, p**((e+1)/2))]
+                 else:
+                     z = self.lift()
+                     val = z.valuation(p)/2  # square => valuation is even
+@@ -1272,7 +1272,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+                     p_exp = p**exp
+                     w = [self._parent(a.lift() * p_val + b)
+                             for a in u.sqrt(all=True)
+-                            for b in range(0, self.__modulus.sageInteger, p_exp)]
++                            for b in range(0, self._modulus.sageInteger, p_exp)]
+                     if p == 2:
+                         w = list(set(w))
+                     w.sort()
+@@ -1624,7 +1624,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         despite the possibly probabilistic nature of the underlying
+         algorithm.
+         """
+-        if self.lift() > self.__modulus.sageInteger >> 1:
++        if self.lift() > self._modulus.sageInteger >> 1:
+             return -self
+         return self
+ 
+@@ -1705,27 +1705,27 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         cdef int_fast64_t new_modulus
+         if not isinstance(self, IntegerMod_gmp) and not isinstance(other, IntegerMod_gmp):
+ 
+-            if other.__modulus.int64 == 1: return self
+-            new_modulus = self.__modulus.int64 * other.__modulus.int64
++            if other._modulus.int64 == 1: return self
++            new_modulus = self._modulus.int64 * other._modulus.int64
+             if new_modulus < INTEGER_MOD_INT32_LIMIT:
+-                return self.__crt(other)
++                return self._crt(other)
+ 
+             elif new_modulus < INTEGER_MOD_INT64_LIMIT:
+                 if not isinstance(self, IntegerMod_int64):
+                     self = IntegerMod_int64(self._parent, self.lift())
+                 if not isinstance(other, IntegerMod_int64):
+                     other = IntegerMod_int64(other._parent, other.lift())
+-                return self.__crt(other)
++                return self._crt(other)
+ 
+         if not isinstance(self, IntegerMod_gmp):
+-            if self.__modulus.int64 == 1: return other
++            if self._modulus.int64 == 1: return other
+             self = IntegerMod_gmp(self._parent, self.lift())
+ 
+         if not isinstance(other, IntegerMod_gmp):
+-            if other.__modulus.int64 == 1: return self
++            if other._modulus.int64 == 1: return self
+             other = IntegerMod_gmp(other._parent, other.lift())
+ 
+-        return self.__crt(other)
++        return self._crt(other)
+ 
+     def additive_order(self):
+         r"""
+@@ -1742,7 +1742,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             sage: Integers(90308402384902)(2).additive_order()
+             45154201192451
+         """
+-        n = self.__modulus.sageInteger
++        n = self._modulus.sageInteger
+         return sage.rings.integer.Integer(n // self.lift().gcd(n))
+ 
+     def is_primitive_root(self):
+@@ -1856,7 +1856,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             return sage.rings.integer.Integer(self.__pari__().znorder())
+         except PariError:
+             raise ArithmeticError("multiplicative order of %s not defined since it is not a unit modulo %s"%(
+-                self, self.__modulus.sageInteger))
++                self, self._modulus.sageInteger))
+ 
+     def valuation(self, p):
+         """
+@@ -1905,7 +1905,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             2
+ 
+         """
+-        p=self.__modulus.sageInteger.gcd(p)
++        p=self._modulus.sageInteger.gcd(p)
+         if p==1:
+             raise ValueError("Valuation with respect to a unit is not defined.")
+         r = 0
+@@ -1913,7 +1913,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         while not (self % power): # self % power == 0
+             r += 1
+             power *= p
+-            if not power.divides(self.__modulus.sageInteger):
++            if not power.divides(self._modulus.sageInteger):
+                 from sage.rings.infinity import infinity
+                 return infinity
+         return r
+@@ -1980,7 +1980,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+     cdef IntegerMod_gmp _new_c(self):
+         cdef IntegerMod_gmp x
+         x = IntegerMod_gmp.__new__(IntegerMod_gmp)
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x._parent = self._parent
+         return x
+ 
+@@ -1989,7 +1989,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+ 
+     cdef void set_from_mpz(self, mpz_t value):
+         cdef sage.rings.integer.Integer modulus
+-        modulus = self.__modulus.sageInteger
++        modulus = self._modulus.sageInteger
+         mpz_mod(self.value, value, modulus.value)
+ 
+     cdef void set_from_long(self, long value):
+@@ -2001,7 +2001,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             1
+         """
+         mpz_set_si(self.value, value)
+-        mpz_mod(self.value, self.value, self.__modulus.sageInteger.value)
++        mpz_mod(self.value, self.value, self._modulus.sageInteger.value)
+ 
+     cdef void set_from_ulong_fast(self, unsigned long value):
+         mpz_set_ui(self.value, value)
+@@ -2071,7 +2071,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             x = self._new_c()
+             if k > 0:
+                 mpz_mul_2exp(x.value, self.value, k)
+-                mpz_fdiv_r(x.value, x.value, self.__modulus.sageInteger.value)
++                mpz_fdiv_r(x.value, x.value, self._modulus.sageInteger.value)
+             else:
+                 mpz_fdiv_q_2exp(x.value, self.value, -k)
+             return x
+@@ -2132,12 +2132,12 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         """
+         return self.lift().gcd(self.modulus()) == 1
+ 
+-    def __crt(IntegerMod_gmp self, IntegerMod_gmp other):
++    def _crt(IntegerMod_gmp self, IntegerMod_gmp other):
+         cdef IntegerMod_gmp lift, x
+         cdef sage.rings.integer.Integer modulus, other_modulus
+ 
+-        modulus = self.__modulus.sageInteger
+-        other_modulus = other.__modulus.sageInteger
++        modulus = self._modulus.sageInteger
++        other_modulus = other._modulus.sageInteger
+         from .integer_mod_ring import IntegerModRing
+         lift = IntegerMod_gmp(IntegerModRing(modulus*other_modulus))
+         try:
+@@ -2188,8 +2188,8 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+         mpz_add(x.value, self.value, (<IntegerMod_gmp>right).value)
+-        if mpz_cmp(x.value, self.__modulus.sageInteger.value)  >= 0:
+-            mpz_sub(x.value, x.value, self.__modulus.sageInteger.value)
++        if mpz_cmp(x.value, self._modulus.sageInteger.value)  >= 0:
++            mpz_sub(x.value, x.value, self._modulus.sageInteger.value)
+         return x
+ 
+     cpdef _sub_(self, right):
+@@ -2204,7 +2204,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         x = self._new_c()
+         mpz_sub(x.value, self.value, (<IntegerMod_gmp>right).value)
+         if mpz_sgn(x.value) == -1:
+-            mpz_add(x.value, x.value, self.__modulus.sageInteger.value)
++            mpz_add(x.value, x.value, self._modulus.sageInteger.value)
+         return x
+ 
+     cpdef _neg_(self):
+@@ -2220,7 +2220,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             return self
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+-        mpz_sub(x.value, self.__modulus.sageInteger.value, self.value)
++        mpz_sub(x.value, self._modulus.sageInteger.value, self.value)
+         return x
+ 
+     cpdef _mul_(self, right):
+@@ -2234,7 +2234,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+         mpz_mul(x.value, self.value,  (<IntegerMod_gmp>right).value)
+-        mpz_fdiv_r(x.value, x.value, self.__modulus.sageInteger.value)
++        mpz_fdiv_r(x.value, x.value, self._modulus.sageInteger.value)
+         return x
+ 
+     cpdef _div_(self, right):
+@@ -2310,7 +2310,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         cdef IntegerMod_gmp x = self._new_c()
+         sig_on()
+         try:
+-            mpz_pow_helper(x.value, self.value, exp, self.__modulus.sageInteger.value)
++            mpz_pow_helper(x.value, self.value, exp, self._modulus.sageInteger.value)
+         finally:
+             sig_off()
+         return x
+@@ -2331,12 +2331,12 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             ZeroDivisionError: inverse of Mod(2, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000) does not exist
+         """
+         if self.is_zero():
+-            raise ZeroDivisionError(f"inverse of Mod(0, {self.__modulus.sageInteger}) does not exist")
++            raise ZeroDivisionError(f"inverse of Mod(0, {self._modulus.sageInteger}) does not exist")
+ 
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+-        if not mpz_invert(x.value, self.value, self.__modulus.sageInteger.value):
+-            raise ZeroDivisionError(f"inverse of Mod({self}, {self.__modulus.sageInteger}) does not exist")
++        if not mpz_invert(x.value, self.value, self._modulus.sageInteger.value):
++            raise ZeroDivisionError(f"inverse of Mod({self}, {self._modulus.sageInteger}) does not exist")
+         return x
+ 
+     def lift(IntegerMod_gmp self):
+@@ -2391,10 +2391,10 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         """
+         cdef IntegerMod_gmp ans = self._new_c()
+         sig_on()
+-        mpz_gcd(ans.value, self.value, self.__modulus.sageInteger.value)
++        mpz_gcd(ans.value, self.value, self._modulus.sageInteger.value)
+         mpz_gcd(ans.value, ans.value, other.value)
+         sig_off()
+-        if mpz_cmp(ans.value, self.__modulus.sageInteger.value) == 0:
++        if mpz_cmp(ans.value, self._modulus.sageInteger.value) == 0:
+             # self = other = 0
+             mpz_set_ui(ans.value, 0)
+         return ans
+@@ -2422,30 +2422,30 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+     """
+ 
+     cdef IntegerMod_int _new_c(self, int_fast32_t value):
+-        if self.__modulus.table is not None:
+-            return self.__modulus.table[value]
++        if self._modulus.table is not None:
++            return self._modulus.table[value]
+         cdef IntegerMod_int x = IntegerMod_int.__new__(IntegerMod_int)
+         x._parent = self._parent
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x.ivalue = value
+         return x
+ 
+     cdef void set_from_mpz(self, mpz_t value):
+-        self.ivalue = mpz_fdiv_ui(value, self.__modulus.int32)
++        self.ivalue = mpz_fdiv_ui(value, self._modulus.int32)
+ 
+     cdef void set_from_long(self, long value):
+-        self.ivalue = value % self.__modulus.int32
++        self.ivalue = value % self._modulus.int32
+         if self.ivalue < 0:
+-            self.ivalue += self.__modulus.int32
++            self.ivalue += self._modulus.int32
+ 
+     cdef void set_from_ulong_fast(self, unsigned long value):
+         self.ivalue = value
+ 
+     cdef void set_from_int(IntegerMod_int self, int_fast32_t ivalue):
+         if ivalue < 0:
+-            self.ivalue = self.__modulus.int32 + (ivalue % self.__modulus.int32)
+-        elif ivalue >= self.__modulus.int32:
+-            self.ivalue = ivalue % self.__modulus.int32
++            self.ivalue = self._modulus.int32 + (ivalue % self._modulus.int32)
++        elif ivalue >= self._modulus.int32:
++            self.ivalue = ivalue % self._modulus.int32
+         else:
+             self.ivalue = ivalue
+ 
+@@ -2490,7 +2490,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: Zmod(1).one().is_one()
+             True
+         """
+-        return self.ivalue == 1 or self.__modulus.int32 == 1
++        return self.ivalue == 1 or self._modulus.int32 == 1
+ 
+     def __bool__(IntegerMod_int self):
+         """
+@@ -2519,9 +2519,9 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: a.is_unit()
+             False
+         """
+-        return gcd_int(self.ivalue, self.__modulus.int32) == 1
++        return gcd_int(self.ivalue, self._modulus.int32) == 1
+ 
+-    def __crt(IntegerMod_int self, IntegerMod_int other):
++    def _crt(IntegerMod_int self, IntegerMod_int other):
+         """
+         Use the Chinese Remainder Theorem to find an element of the
+         integers modulo the product of the moduli that reduces to self and
+@@ -2543,11 +2543,11 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         cdef int_fast32_t x
+ 
+         from .integer_mod_ring import IntegerModRing
+-        lift = IntegerMod_int(IntegerModRing(self.__modulus.int32 * other.__modulus.int32))
++        lift = IntegerMod_int(IntegerModRing(self._modulus.int32 * other._modulus.int32))
+ 
+         try:
+-            x = (other.ivalue - self.ivalue % other.__modulus.int32) * mod_inverse_int(self.__modulus.int32, other.__modulus.int32)
+-            lift.set_from_int( x * self.__modulus.int32 + self.ivalue )
++            x = (other.ivalue - self.ivalue % other._modulus.int32) * mod_inverse_int(self._modulus.int32, other._modulus.int32)
++            lift.set_from_int( x * self._modulus.int32 + self.ivalue )
+             return lift
+         except ZeroDivisionError:
+             raise ZeroDivisionError("moduli must be coprime")
+@@ -2586,8 +2586,8 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         """
+         cdef int_fast32_t x
+         x = self.ivalue + (<IntegerMod_int>right).ivalue
+-        if x >= self.__modulus.int32:
+-            x = x - self.__modulus.int32
++        if x >= self._modulus.int32:
++            x = x - self._modulus.int32
+         return self._new_c(x)
+ 
+     cpdef _sub_(self, right):
+@@ -2601,7 +2601,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         cdef int_fast32_t x
+         x = self.ivalue - (<IntegerMod_int>right).ivalue
+         if x < 0:
+-            x = x + self.__modulus.int32
++            x = x + self._modulus.int32
+         return self._new_c(x)
+ 
+     cpdef _neg_(self):
+@@ -2615,7 +2615,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         """
+         if self.ivalue == 0:
+             return self
+-        return self._new_c(self.__modulus.int32 - self.ivalue)
++        return self._new_c(self._modulus.int32 - self.ivalue)
+ 
+     cpdef _mul_(self, right):
+         """
+@@ -2625,7 +2625,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: R(7) * R(8)
+             6
+         """
+-        return self._new_c((self.ivalue * (<IntegerMod_int>right).ivalue) % self.__modulus.int32)
++        return self._new_c((self.ivalue * (<IntegerMod_int>right).ivalue) % self._modulus.int32)
+ 
+     cpdef _div_(self, right):
+         """
+@@ -2635,16 +2635,16 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: R(2)/3
+             4
+         """
+-        if self.__modulus.inverses is not None:
+-            right_inverse = self.__modulus.inverses[(<IntegerMod_int>right).ivalue]
++        if self._modulus.inverses is not None:
++            right_inverse = self._modulus.inverses[(<IntegerMod_int>right).ivalue]
+             if right_inverse is None:
+-                raise ZeroDivisionError(f"inverse of Mod({right}, {self.__modulus.sageInteger}) does not exist")
++                raise ZeroDivisionError(f"inverse of Mod({right}, {self._modulus.sageInteger}) does not exist")
+             else:
+-                return self._new_c((self.ivalue * (<IntegerMod_int>right_inverse).ivalue) % self.__modulus.int32)
++                return self._new_c((self.ivalue * (<IntegerMod_int>right_inverse).ivalue) % self._modulus.int32)
+ 
+         cdef int_fast32_t x
+-        x = self.ivalue * mod_inverse_int((<IntegerMod_int>right).ivalue, self.__modulus.int32)
+-        return self._new_c(x% self.__modulus.int32)
++        x = self.ivalue * mod_inverse_int((<IntegerMod_int>right).ivalue, self._modulus.int32)
++        return self._new_c(x% self._modulus.int32)
+ 
+     def __int__(IntegerMod_int self):
+         """
+@@ -2739,7 +2739,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         if k == 0:
+             return self
+         elif k > 0:
+-            return self._new_c((self.ivalue << k) % self.__modulus.int32)
++            return self._new_c((self.ivalue << k) % self._modulus.int32)
+         else:
+             return self._new_c(self.ivalue >> (-k))
+ 
+@@ -2802,7 +2802,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sig_on()
+             try:
+                 mpz_init(res_mpz)
+-                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self.__modulus.sageInteger.value)
++                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self._modulus.sageInteger.value)
+                 res = mpz_get_ui(res_mpz)
+                 mpz_clear(res_mpz)
+             finally:
+@@ -2811,12 +2811,12 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+ 
+         if long_exp == 0 and self.ivalue == 0:
+             # Return 0 if the modulus is 1, otherwise return 1.
+-            return self._new_c(self.__modulus.int32 != 1)
++            return self._new_c(self._modulus.int32 != 1)
+         cdef bint invert = False
+         if long_exp < 0:
+             invert = True
+             long_exp = -long_exp
+-        res = mod_pow_int(self.ivalue, long_exp, self.__modulus.int32)
++        res = mod_pow_int(self.ivalue, long_exp, self._modulus.int32)
+         if invert:
+             return ~self._new_c(res)
+         else:
+@@ -2833,14 +2833,14 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: Mod(0,1)^-1
+             0
+         """
+-        if self.__modulus.inverses is not None:
+-            x = self.__modulus.inverses[self.ivalue]
++        if self._modulus.inverses is not None:
++            x = self._modulus.inverses[self.ivalue]
+             if x is None:
+-                raise ZeroDivisionError(f"inverse of Mod({self}, {self.__modulus.sageInteger}) does not exist")
++                raise ZeroDivisionError(f"inverse of Mod({self}, {self._modulus.sageInteger}) does not exist")
+             else:
+                 return x
+         else:
+-            return self._new_c(mod_inverse_int(self.ivalue, self.__modulus.int32))
++            return self._new_c(mod_inverse_int(self.ivalue, self._modulus.int32))
+ 
+     def lift(IntegerMod_int self):
+         """
+@@ -3006,15 +3006,15 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: GF(103)(-1).sqrt(extend=False, all=True)
+             []
+         """
+-        cdef int_fast32_t i, n = self.__modulus.int32
++        cdef int_fast32_t i, n = self._modulus.int32
+         if n > 100:
+             moduli = self._parent.factored_order()
+         # Unless the modulus is tiny, test to see if we're in the really
+         # easy case of n prime, n = 3 mod 4.
+         if n > 100 and n % 4 == 3 and len(moduli) == 1 and moduli[0][1] == 1:
+-            if jacobi_int(self.ivalue, self.__modulus.int32) == 1:
++            if jacobi_int(self.ivalue, self._modulus.int32) == 1:
+                 # it's a non-zero square, sqrt(a) = a^(p+1)/4
+-                i = mod_pow_int(self.ivalue, (self.__modulus.int32+1)/4, n)
++                i = mod_pow_int(self.ivalue, (self._modulus.int32+1)/4, n)
+                 if i > n / 2:
+                     i = n - i
+                 if all:
+@@ -3049,7 +3049,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         This function returns `x` or `-x`, whichever has a
+         positive representative in `-n/2 < x \leq n/2`.
+         """
+-        if self.ivalue > self.__modulus.int32 / 2:
++        if self.ivalue > self._modulus.int32 / 2:
+             return -self
+         return self
+ 
+@@ -3082,9 +3082,9 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: mod(0,1).gcd(mod(0,1))
+             0
+         """
+-        cdef int_fast32_t g = gcd_int(self.ivalue, self.__modulus.int32)
++        cdef int_fast32_t g = gcd_int(self.ivalue, self._modulus.int32)
+         g = gcd_int(g, other.ivalue)
+-        if g == self.__modulus.int32: # self = other = 0
++        if g == self._modulus.int32: # self = other = 0
+             g = 0
+         return self._new_c(g)
+ 
+@@ -3256,27 +3256,27 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+     cdef IntegerMod_int64 _new_c(self, int_fast64_t value):
+         cdef IntegerMod_int64 x
+         x = IntegerMod_int64.__new__(IntegerMod_int64)
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x._parent = self._parent
+         x.ivalue = value
+         return x
+ 
+     cdef void set_from_mpz(self, mpz_t value):
+-        self.ivalue = mpz_fdiv_ui(value, self.__modulus.int64)
++        self.ivalue = mpz_fdiv_ui(value, self._modulus.int64)
+ 
+     cdef void set_from_long(self, long value):
+-        self.ivalue = value % self.__modulus.int64
++        self.ivalue = value % self._modulus.int64
+         if self.ivalue < 0:
+-            self.ivalue += self.__modulus.int64
++            self.ivalue += self._modulus.int64
+ 
+     cdef void set_from_ulong_fast(self, unsigned long value):
+         self.ivalue = value
+ 
+     cdef void set_from_int(IntegerMod_int64 self, int_fast64_t ivalue):
+         if ivalue < 0:
+-            self.ivalue = self.__modulus.int64 + (ivalue % self.__modulus.int64) # Is ivalue % self.__modulus.int64 actually negative?
+-        elif ivalue >= self.__modulus.int64:
+-            self.ivalue = ivalue % self.__modulus.int64
++            self.ivalue = self._modulus.int64 + (ivalue % self._modulus.int64) # Is ivalue % self._modulus.int64 actually negative?
++        elif ivalue >= self._modulus.int64:
++            self.ivalue = ivalue % self._modulus.int64
+         else:
+             self.ivalue = ivalue
+ 
+@@ -3344,9 +3344,9 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: mod(25, 5^10).is_unit()
+             False
+         """
+-        return gcd_int64(self.ivalue, self.__modulus.int64) == 1
++        return gcd_int64(self.ivalue, self._modulus.int64) == 1
+ 
+-    def __crt(IntegerMod_int64 self, IntegerMod_int64 other):
++    def _crt(IntegerMod_int64 self, IntegerMod_int64 other):
+         """
+         Use the Chinese Remainder Theorem to find an element of the
+         integers modulo the product of the moduli that reduces to self and
+@@ -3379,11 +3379,11 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         cdef int_fast64_t x
+ 
+         from .integer_mod_ring import IntegerModRing
+-        lift = IntegerMod_int64(IntegerModRing(self.__modulus.int64 * other.__modulus.int64))
++        lift = IntegerMod_int64(IntegerModRing(self._modulus.int64 * other._modulus.int64))
+ 
+         try:
+-            x = (other.ivalue - self.ivalue % other.__modulus.int64) * mod_inverse_int64(self.__modulus.int64, other.__modulus.int64)
+-            lift.set_from_int( x * self.__modulus.int64 + self.ivalue )
++            x = (other.ivalue - self.ivalue % other._modulus.int64) * mod_inverse_int64(self._modulus.int64, other._modulus.int64)
++            lift.set_from_int( x * self._modulus.int64 + self.ivalue )
+             return lift
+         except ZeroDivisionError:
+             raise ZeroDivisionError("moduli must be coprime")
+@@ -3422,8 +3422,8 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         """
+         cdef int_fast64_t x
+         x = self.ivalue + (<IntegerMod_int64>right).ivalue
+-        if x >= self.__modulus.int64:
+-            x = x - self.__modulus.int64
++        if x >= self._modulus.int64:
++            x = x - self._modulus.int64
+         return self._new_c(x)
+ 
+     cpdef _sub_(self, right):
+@@ -3437,7 +3437,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         cdef int_fast64_t x
+         x = self.ivalue - (<IntegerMod_int64>right).ivalue
+         if x < 0:
+-            x = x + self.__modulus.int64
++            x = x + self._modulus.int64
+         return self._new_c(x)
+ 
+     cpdef _neg_(self):
+@@ -3451,7 +3451,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         """
+         if self.ivalue == 0:
+             return self
+-        return self._new_c(self.__modulus.int64 - self.ivalue)
++        return self._new_c(self._modulus.int64 - self.ivalue)
+ 
+     cpdef _mul_(self, right):
+         """
+@@ -3461,7 +3461,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: R(700) * R(800)
+             60000
+         """
+-        return self._new_c((self.ivalue * (<IntegerMod_int64>right).ivalue) % self.__modulus.int64)
++        return self._new_c((self.ivalue * (<IntegerMod_int64>right).ivalue) % self._modulus.int64)
+ 
+ 
+     cpdef _div_(self, right):
+@@ -3473,7 +3473,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             33334
+         """
+         return self._new_c((self.ivalue * mod_inverse_int64((<IntegerMod_int64>right).ivalue,
+-                                   self.__modulus.int64) ) % self.__modulus.int64)
++                                   self._modulus.int64) ) % self._modulus.int64)
+ 
+     def __int__(IntegerMod_int64 self):
+         return self.ivalue
+@@ -3559,7 +3559,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         if k == 0:
+             return self
+         elif k > 0:
+-            return self._new_c((self.ivalue << k) % self.__modulus.int64)
++            return self._new_c((self.ivalue << k) % self._modulus.int64)
+         else:
+             return self._new_c(self.ivalue >> (-k))
+ 
+@@ -3633,7 +3633,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sig_on()
+             try:
+                 mpz_init(res_mpz)
+-                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self.__modulus.sageInteger.value)
++                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self._modulus.sageInteger.value)
+                 res = mpz_get_ui(res_mpz)
+                 mpz_clear(res_mpz)
+             finally:
+@@ -3642,14 +3642,14 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+ 
+         if long_exp == 0 and self.ivalue == 0:
+             # Return 0 if the modulus is 1, otherwise return 1.
+-            return self._new_c(self.__modulus.int64 != 1)
++            return self._new_c(self._modulus.int64 != 1)
+         cdef bint invert = False
+         if long_exp < 0:
+             invert = True
+             long_exp = -long_exp
+-        res = mod_pow_int64(self.ivalue, long_exp, self.__modulus.int64)
++        res = mod_pow_int64(self.ivalue, long_exp, self._modulus.int64)
+         if invert:
+-            return self._new_c(mod_inverse_int64(res, self.__modulus.int64))
++            return self._new_c(mod_inverse_int64(res, self._modulus.int64))
+         else:
+             return self._new_c(res)
+ 
+@@ -3666,7 +3666,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: a
+             7
+         """
+-        return self._new_c(mod_inverse_int64(self.ivalue, self.__modulus.int64))
++        return self._new_c(mod_inverse_int64(self.ivalue, self._modulus.int64))
+ 
+     def lift(IntegerMod_int64 self):
+         """
+@@ -3715,7 +3715,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         This function returns `x` or `-x`, whichever has a
+         positive representative in `-n/2 < x \leq n/2`.
+         """
+-        if self.ivalue > self.__modulus.int64 / 2:
++        if self.ivalue > self._modulus.int64 / 2:
+             return -self
+         return self
+ 
+@@ -3738,9 +3738,9 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: mod(0,17^5).gcd(mod(0,17^5))
+             0
+         """
+-        cdef int_fast64_t g = gcd_int64(self.ivalue, self.__modulus.int64)
++        cdef int_fast64_t g = gcd_int64(self.ivalue, self._modulus.int64)
+         g = gcd_int64(g, other.ivalue)
+-        if g == self.__modulus.int64: # self = other = 0
++        if g == self._modulus.int64: # self = other = 0
+             g = 0
+         return self._new_c(g)
+ 
+diff --git a/src/sage/rings/fraction_field_FpT.pyx b/src/sage/rings/fraction_field_FpT.pyx
+index 0a25191a11c..c9bb5d5a384 100644
+--- a/src/sage/rings/fraction_field_FpT.pyx
++++ b/src/sage/rings/fraction_field_FpT.pyx
+@@ -1650,7 +1650,7 @@ cdef class FpT_Fp_section(Section):
+                 raise ValueError("not constant")
+         ans = IntegerMod_int.__new__(IntegerMod_int)
+         ans._parent = self.codomain()
+-        ans.__modulus = ans._parent._pyx_order
++        ans._modulus = ans._parent._pyx_order
+         if nmod_poly_get_coeff_ui(x._denom, 0) != 1:
+             normalize(x._numer, x._denom, self.p)
+         ans.ivalue = nmod_poly_get_coeff_ui(x._numer, 0)
+diff --git a/src/sage/rings/fraction_field_element.pyx b/src/sage/rings/fraction_field_element.pyx
+index 11a2b646d35..75e47af1299 100644
+--- a/src/sage/rings/fraction_field_element.pyx
++++ b/src/sage/rings/fraction_field_element.pyx
+@@ -78,8 +78,8 @@ cdef class FractionFieldElement(FieldElement):
+         sage: F.one().quo_rem(F.one())
+         (1, 0)
+     """
+-    cdef object __numerator
+-    cdef object __denominator
++    cdef object _numerator
++    cdef object _denominator
+     cdef bint _is_reduced
+ 
+     def __init__(self, parent, numerator, denominator=1,
+@@ -108,17 +108,17 @@ cdef class FractionFieldElement(FieldElement):
+         """
+         FieldElement.__init__(self, parent)
+         if coerce:
+-            self.__numerator   = parent.ring()(numerator)
+-            self.__denominator = parent.ring()(denominator)
++            self._numerator   = parent.ring()(numerator)
++            self._denominator = parent.ring()(denominator)
+         else:
+-            self.__numerator   = numerator
+-            self.__denominator = denominator
++            self._numerator   = numerator
++            self._denominator = denominator
+         if reduce and parent.is_exact():
+             try:
+                 self.reduce()
+             except ArithmeticError:
+                 pass
+-        if self.__denominator.is_zero():
++        if self._denominator.is_zero():
+             raise ZeroDivisionError("fraction field element division by zero")
+ 
+     def _im_gens_(self, codomain, im_gens, base_map=None):
+@@ -154,8 +154,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: phi(i/a)                                                              # optional - sage.rings.number_field
+             ((-i))/b
+         """
+-        nnum = codomain.coerce(self.__numerator._im_gens_(codomain, im_gens, base_map=base_map))
+-        nden = codomain.coerce(self.__denominator._im_gens_(codomain, im_gens, base_map=base_map))
++        nnum = codomain.coerce(self._numerator._im_gens_(codomain, im_gens, base_map=base_map))
++        nden = codomain.coerce(self._denominator._im_gens_(codomain, im_gens, base_map=base_map))
+         return codomain.coerce(nnum/nden)
+ 
+     cpdef reduce(self):
+@@ -191,10 +191,10 @@ cdef class FractionFieldElement(FieldElement):
+         if self._is_reduced:
+             return
+         try:
+-            g = self.__numerator.gcd(self.__denominator)
++            g = self._numerator.gcd(self._denominator)
+             if not g.is_unit():
+-                self.__numerator //= g
+-                self.__denominator //= g
++                self._numerator //= g
++                self._denominator //= g
+             self._is_reduced = True
+         except AttributeError:
+             raise ArithmeticError("unable to reduce because lack of gcd or quo_rem algorithm")
+@@ -202,14 +202,14 @@ cdef class FractionFieldElement(FieldElement):
+             raise ArithmeticError("unable to reduce because gcd algorithm doesn't work on input")
+         except NotImplementedError:
+             raise ArithmeticError("unable to reduce because gcd algorithm not implemented on input")
+-        if not self.__denominator.is_one() and self.__denominator.is_unit():
++        if not self._denominator.is_one() and self._denominator.is_unit():
+             try:
+-                inv = self.__denominator.inverse_of_unit()
++                inv = self._denominator.inverse_of_unit()
+             except Exception:
+                 pass
+             else:
+-                self.__numerator *= inv
+-                self.__denominator = self.__denominator.parent().one()
++                self._numerator *= inv
++                self._denominator = self._denominator.parent().one()
+ 
+     def __copy__(self):
+         """
+@@ -223,8 +223,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: copy(f)
+             (x + y)/y
+         """
+-        return self.__class__(self._parent, self.__numerator,
+-                self.__denominator, coerce=False, reduce=False)
++        return self.__class__(self._parent, self._numerator,
++                self._denominator, coerce=False, reduce=False)
+ 
+     def numerator(self):
+         """
+@@ -238,7 +238,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f.numerator()
+             x + y
+         """
+-        return self.__numerator
++        return self._numerator
+ 
+     def denominator(self):
+         """
+@@ -252,7 +252,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f.denominator()
+             y
+         """
+-        return self.__denominator
++        return self._denominator
+ 
+ 
+     def is_square(self,root=False):
+@@ -399,10 +399,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: ((x+1)/(x^2+1)).subs({x: 1})                                          # optional - sage.rings.number_field
+             1
+         """
+-        if self.__denominator.is_one():
++        if self._denominator.is_one():
+             # Handle this case even over rings that don't support reduction, to
+             # avoid breaking existing code that carelessly mixes p and p/1
+-            return hash(self.__numerator)
++            return hash(self._numerator)
+         if self._parent.is_exact():
+             # May fail; let the exception propagate then.
+             # (In contrast, over inexact rings, we hash unreduced fractions
+@@ -413,8 +413,8 @@ cdef class FractionFieldElement(FieldElement):
+             # issues even if we didn't...)
+             self.reduce()
+         # Same algorithm as for elements of QQ
+-        n = hash(self.__numerator)
+-        d = hash(self.__denominator)
++        n = hash(self._numerator)
++        d = hash(self._denominator)
+         if d == 1:
+             return n
+         else:
+@@ -443,7 +443,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: h(x0=1)
+             (-2*x1*x2 + x1 + 1)/(x1 + x2)
+         """
+-        return self.__numerator(*x, **kwds) / self.__denominator(*x, **kwds)
++        return self._numerator(*x, **kwds) / self._denominator(*x, **kwds)
+ 
+     def _is_atomic(self):
+         """
+@@ -456,7 +456,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f._is_atomic()
+             False
+         """
+-        return self.__numerator._is_atomic() and self.__denominator._is_atomic()
++        return self._numerator._is_atomic() and self._denominator._is_atomic()
+ 
+     def _repr_(self):
+         """
+@@ -476,13 +476,13 @@ cdef class FractionFieldElement(FieldElement):
+         """
+         if self.is_zero():
+             return "0"
+-        s = "%s" % self.__numerator
+-        if self.__denominator != 1:
+-            denom_string = str( self.__denominator )
+-            if self.__denominator._is_atomic() and not ('*' in denom_string or '/' in denom_string):
+-                s = "%s/%s"%(self.__numerator._coeff_repr(no_space=False),denom_string)
++        s = "%s" % self._numerator
++        if self._denominator != 1:
++            denom_string = str( self._denominator )
++            if self._denominator._is_atomic() and not ('*' in denom_string or '/' in denom_string):
++                s = "%s/%s"%(self._numerator._coeff_repr(no_space=False),denom_string)
+             else:
+-                s = "%s/(%s)"%(self.__numerator._coeff_repr(no_space=False),denom_string)
++                s = "%s/(%s)"%(self._numerator._coeff_repr(no_space=False),denom_string)
+         return s
+ 
+     def _latex_(self):
+@@ -518,10 +518,10 @@ cdef class FractionFieldElement(FieldElement):
+         """
+         if self.is_zero():
+             return "0"
+-        if self.__denominator == 1:
+-            return latex.latex(self.__numerator)
+-        return "\\frac{%s}{%s}"%(latex.latex(self.__numerator),
+-                                 latex.latex(self.__denominator))
++        if self._denominator == 1:
++            return latex.latex(self._numerator)
++        return "\\frac{%s}{%s}"%(latex.latex(self._numerator),
++                                 latex.latex(self._denominator))
+ 
+     def _magma_init_(self, magma):
+         """
+@@ -577,10 +577,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: t - 1/t # indirect doctest                                            # optional - sage.rings.finite_rings
+             (t^2 + 6)/t
+         """
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         if (rnum.is_zero()):
+             return <FractionFieldElement> right
+@@ -602,7 +602,7 @@ cdef class FractionFieldElement(FieldElement):
+                             self._parent.ring().one(), coerce=False,
+                             reduce=False)
+                     else:
+-                        tden = self.__denominator * sden
++                        tden = self._denominator * sden
+                         e    = tnum.gcd(d)
+                         if not e.is_unit():
+                             tnum = tnum // e
+@@ -624,10 +624,10 @@ cdef class FractionFieldElement(FieldElement):
+             except TypeError:
+                 pass
+ 
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         return self.__class__(self._parent, rnum*sden + rden*snum, rden*sden,
+             coerce=False, reduce=False)
+@@ -652,10 +652,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: a * b # indirect doctest                                              # optional - sage.rings.finite_rings
+             3/(t + 1)
+         """
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         if (rnum.is_zero() or snum.is_zero()):
+             return self._parent.zero()
+@@ -689,10 +689,10 @@ cdef class FractionFieldElement(FieldElement):
+             except TypeError:
+                 pass
+ 
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         return self.__class__(self._parent, rnum * snum, rden * sden,
+             coerce=False, reduce=False)
+@@ -717,8 +717,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: a/b
+             (x*z - x + z - 1)/(z - 3)
+         """
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         if snum.is_zero():
+             raise ZeroDivisionError("fraction field element division by zero")
+@@ -743,10 +743,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: int(K(.5))
+             0
+         """
+-        if self.__denominator != 1:
++        if self._denominator != 1:
+             self.reduce()
+-        if self.__denominator == 1:
+-            return int(self.__numerator)
++        if self._denominator == 1:
++            return int(self._numerator)
+         else:
+             raise TypeError("denominator must equal 1")
+ 
+@@ -758,7 +758,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: float(x/x + y/y)
+             2.0
+         """
+-        return float(self.__numerator) / float(self.__denominator)
++        return float(self._numerator) / float(self._denominator)
+ 
+     def __complex__(self):
+         """
+@@ -768,7 +768,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: complex(x/(I*x) + (I*y)/y)
+             0j
+         """
+-        return complex(self.__numerator) / complex(self.__denominator)
++        return complex(self._numerator) / complex(self._denominator)
+ 
+     def _rational_(self):
+         r"""
+@@ -822,12 +822,12 @@ cdef class FractionFieldElement(FieldElement):
+             sage: A(C(u))                                                               # optional - sage.rings.number_field
+             u
+         """
+-        if self.__denominator.is_one():
+-            return R(self.__numerator)
++        if self._denominator.is_one():
++            return R(self._numerator)
+         else:
+             self.reduce()
+-            num = R(self.__numerator)
+-            inv_den = R(self.__denominator).inverse_of_unit()
++            num = R(self._numerator)
++            inv_den = R(self._denominator).inverse_of_unit()
+             return num * inv_den
+ 
+     _real_double_ = _conversion
+@@ -847,7 +847,7 @@ cdef class FractionFieldElement(FieldElement):
+         Returns self raised to the `right^{th}` power.
+ 
+         Note that we need to check whether or not right is negative so we
+-        don't set ``__numerator`` or ``__denominator`` to an element of the
++        don't set ``_numerator`` or ``_denominator`` to an element of the
+         fraction field instead of the underlying ring.
+ 
+         EXAMPLES::
+@@ -876,8 +876,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: ((x+y)/(x-y))^0
+             1
+         """
+-        snum = (<FractionFieldElement> self).__numerator
+-        sden = (<FractionFieldElement> self).__denominator
++        snum = (<FractionFieldElement> self)._numerator
++        sden = (<FractionFieldElement> self)._denominator
+         if right == 0:
+             R = self.parent().ring()
+             return self.__class__(self.parent(),
+@@ -904,7 +904,7 @@ cdef class FractionFieldElement(FieldElement):
+             (4*t^2 + 4*t)/(t + 2)
+         """
+         return self.__class__(self._parent,
+-            -self.__numerator, self.__denominator,
++            -self._numerator, self._denominator,
+             coerce=False, reduce=False)
+ 
+     def __abs__(self):
+@@ -915,7 +915,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: abs(FractionFieldElement(QQ, -2, 3, coerce=False))
+             2/3
+         """
+-        return abs(self.__numerator) / abs(self.__denominator)
++        return abs(self._numerator) / abs(self._denominator)
+ 
+     def __invert__(self):
+         """
+@@ -929,7 +929,7 @@ cdef class FractionFieldElement(FieldElement):
+         if self.is_zero():
+             raise ZeroDivisionError("Cannot invert 0")
+         return self.__class__(self._parent,
+-            self.__denominator, self.__numerator, coerce=False, reduce=False)
++            self._denominator, self._numerator, coerce=False, reduce=False)
+ 
+     cpdef _richcmp_(self, other, int op):
+         """
+@@ -951,10 +951,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: 1 > y
+             False
+         """
+-        return richcmp(self.__numerator *
+-                       (<FractionFieldElement>other).__denominator,
+-                       self.__denominator *
+-                       (<FractionFieldElement>other).__numerator, op)
++        return richcmp(self._numerator *
++                       (<FractionFieldElement>other)._denominator,
++                       self._denominator *
++                       (<FractionFieldElement>other)._numerator, op)
+ 
+     def valuation(self, v=None):
+         """
+@@ -972,7 +972,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f.valuation(x^2 + 1)
+             1
+         """
+-        return self.__numerator.valuation(v) - self.__denominator.valuation(v)
++        return self._numerator.valuation(v) - self._denominator.valuation(v)
+ 
+     def __bool__(self):
+         """
+@@ -991,7 +991,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: bool(1/x)
+             True
+         """
+-        return not self.__numerator.is_zero()
++        return not self._numerator.is_zero()
+ 
+     def is_zero(self):
+         """
+@@ -1010,7 +1010,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: u.parent() is F
+             True
+         """
+-        return self.__numerator.is_zero()
++        return self._numerator.is_zero()
+ 
+     def is_one(self):
+         """
+@@ -1025,7 +1025,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: (x/y).is_one()
+             False
+         """
+-        return self.__numerator == self.__denominator
++        return self._numerator == self._denominator
+ 
+     def _symbolic_(self, ring):
+         """
+@@ -1044,7 +1044,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: symbolic_expression(elt)                                              # optional - sage.symbolic
+             2/3*(x + y)/(x - y)
+         """
+-        return ring(self.__numerator)/ring(self.__denominator)
++        return ring(self._numerator)/ring(self._denominator)
+ 
+     def __reduce__(self):
+         """
+@@ -1058,7 +1058,7 @@ cdef class FractionFieldElement(FieldElement):
+             True
+         """
+         return (make_element,
+-                (self._parent, self.__numerator, self.__denominator))
++                (self._parent, self._numerator, self._denominator))
+ 
+     def _evaluate_polynomial(self, pol):
+         """
+@@ -1170,9 +1170,9 @@ cdef class FractionFieldElement_1poly_field(FractionFieldElement):
+         """
+         See :meth:`reduce`.
+         """
+-        invlc = ~self.__denominator.leading_coefficient()
+-        self.__denominator = self.__denominator.monic()
+-        self.__numerator *= invlc
++        invlc = ~self._denominator.leading_coefficient()
++        self._denominator = self._denominator.monic()
++        self._numerator *= invlc
+ 
+     def is_integral(self):
+         """
+diff --git a/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py b/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py
+index a27e75f5fce..74ef125fb6a 100644
+--- a/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py
++++ b/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py
+@@ -804,8 +804,8 @@ def _latex_(self):
+             \phi
+             sage: phi.reset_name()
+         """
+-        if hasattr(self, '__custom_name'):
+-            return latex_variable_name(getattr(self, '__custom_name'))
++        if self.get_custom_name() is not None:
++            return latex_variable_name(self.get_custom_name())
+         else:
+             return f'\\phi: {latex(self._function_ring.gen())} \\mapsto ' \
+                    f'{latex(self._gen)}'
+diff --git a/src/sage/rings/laurent_series_ring_element.pxd b/src/sage/rings/laurent_series_ring_element.pxd
+index d190645ce52..8df5a92c9e7 100644
+--- a/src/sage/rings/laurent_series_ring_element.pxd
++++ b/src/sage/rings/laurent_series_ring_element.pxd
+@@ -4,7 +4,7 @@ cdef class LaurentSeries(AlgebraElement):
+     cdef ModuleElement __u
+     cdef long __n
+ 
+-    cdef __normalize(self)
++    cdef _normalize(self)
+     cpdef _add_(self, other)
+     cpdef _mul_(self, other)
+ 
+diff --git a/src/sage/rings/laurent_series_ring_element.pyx b/src/sage/rings/laurent_series_ring_element.pyx
+index 8e950478045..9bef72396b7 100644
+--- a/src/sage/rings/laurent_series_ring_element.pyx
++++ b/src/sage/rings/laurent_series_ring_element.pyx
+@@ -302,7 +302,7 @@ cdef class LaurentSeries(AlgebraElement):
+         x = im_gens[0]
+         return codomain(self.__u._im_gens_(codomain, im_gens, base_map=base_map) * x**self.__n)
+ 
+-    cdef __normalize(self):
++    cdef _normalize(self):
+         r"""
+         A Laurent series is a pair (u(t), n), where either u=0 (to some
+         precision) or u is a unit. This pair corresponds to
+@@ -725,7 +725,7 @@ cdef class LaurentSeries(AlgebraElement):
+                 R = self._parent.base_ring()
+                 coeffs = [value] + [R(0) for _ in range(1,-j)] + self.__u.list()
+                 self.__u = self.__u._parent(coeffs)
+-        self.__normalize()
++        self._normalize()
+ 
+     cpdef _add_(self, right_m):
+         """
+diff --git a/src/sage/rings/morphism.pxd b/src/sage/rings/morphism.pxd
+index ea6089f29b4..4b8e8d052df 100644
+--- a/src/sage/rings/morphism.pxd
++++ b/src/sage/rings/morphism.pxd
+@@ -14,7 +14,7 @@ cdef class RingMap_lift(RingMap):
+ 
+ cdef class RingHomomorphism(RingMap):
+     cdef Morphism _lift
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+ cdef class RingHomomorphism_im_gens(RingHomomorphism):
+     cdef _im_gens
+diff --git a/src/sage/rings/number_field/number_field_element.pxd b/src/sage/rings/number_field/number_field_element.pxd
+index 9b6917223a0..c3d8a8b4a4b 100644
+--- a/src/sage/rings/number_field/number_field_element.pxd
++++ b/src/sage/rings/number_field/number_field_element.pxd
+@@ -11,12 +11,12 @@ from sage.libs.ntl.ntl_ZZ cimport ntl_ZZ
+ 
+ 
+ cdef class NumberFieldElement(NumberFieldElement_base):
+-    cdef ZZX_c __numerator
+-    cdef ZZ_c __denominator
++    cdef ZZX_c _numerator
++    cdef ZZ_c _denominator
+     # Pointers to the defining polynomial (with numerator) for the field.
+     # I keep these as pointers for arithmetic speed.
+-    cdef ntl_ZZX __fld_numerator
+-    cdef ntl_ZZ __fld_denominator
++    cdef ntl_ZZX _fld_numerator
++    cdef ntl_ZZ _fld_denominator
+     cdef object __multiplicative_order
+     cdef object __pari
+     cdef object __matrix
+diff --git a/src/sage/rings/number_field/number_field_element.pyx b/src/sage/rings/number_field/number_field_element.pyx
+index 27e33ad5be0..d44fc55b70c 100644
+--- a/src/sage/rings/number_field/number_field_element.pyx
++++ b/src/sage/rings/number_field/number_field_element.pyx
+@@ -218,8 +218,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef type t = type(self)
+         cdef NumberFieldElement x = <NumberFieldElement>t.__new__(t)
+         x._parent = self._parent
+-        x.__fld_numerator = self.__fld_numerator
+-        x.__fld_denominator = self.__fld_denominator
++        x._fld_numerator = self._fld_numerator
++        x._fld_denominator = self._fld_denominator
+         return x
+ 
+     cdef number_field(self):
+@@ -317,20 +317,20 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             True
+         """
+         FieldElement.__init__(self, parent)
+-        self.__fld_numerator, self.__fld_denominator = parent.absolute_polynomial_ntl()
++        self._fld_numerator, self._fld_denominator = parent.absolute_polynomial_ntl()
+ 
+         cdef ZZ_c coeff
+         if isinstance(f, (int, Integer_sage)):
+             # set it up and exit immediately
+             # fast pathway
+             mpz_to_ZZ(&coeff, (<Integer>ZZ(f)).value)
+-            ZZX_SetCoeff( self.__numerator, 0, coeff )
+-            ZZ_conv_from_int( self.__denominator, 1 )
++            ZZX_SetCoeff( self._numerator, 0, coeff )
++            ZZ_conv_from_int( self._denominator, 1 )
+             return
+         elif isinstance(f, NumberFieldElement):
+             if type(self) is type(f):
+-                self.__numerator = (<NumberFieldElement>f).__numerator
+-                self.__denominator = (<NumberFieldElement>f).__denominator
++                self._numerator = (<NumberFieldElement>f)._numerator
++                self._denominator = (<NumberFieldElement>f)._denominator
+                 return
+             else:
+                 f = f.polynomial()
+@@ -342,11 +342,11 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+ 
+         cdef long i
+         den = f.denominator()
+-        mpz_to_ZZ(&self.__denominator, (<Integer>ZZ(den)).value)
++        mpz_to_ZZ(&self._denominator, (<Integer>ZZ(den)).value)
+         num = f * den
+         for i from 0 <= i <= num.degree():
+             mpz_to_ZZ(&coeff, (<Integer>ZZ(num[i])).value)
+-            ZZX_SetCoeff( self.__numerator, i, coeff )
++            ZZX_SetCoeff( self._numerator, i, coeff )
+ 
+     def _lift_cyclotomic_element(self, new_parent, bint check=True, int rel=0):
+         """
+@@ -417,17 +417,17 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef type t = type(self)
+         cdef NumberFieldElement x = <NumberFieldElement>t.__new__(t)
+         x._parent = <ParentWithBase>new_parent
+-        x.__fld_numerator, x.__fld_denominator = new_parent.polynomial_ntl()
+-        x.__denominator = self.__denominator
++        x._fld_numerator, x._fld_denominator = new_parent.polynomial_ntl()
++        x._denominator = self._denominator
+         cdef ZZX_c result
+         cdef ZZ_c tmp
+         cdef int i
+         cdef ntl_ZZX _num
+         cdef ntl_ZZ _den
+-        for i from 0 <= i <= ZZX_deg(self.__numerator):
+-            tmp = ZZX_coeff(self.__numerator, i)
++        for i from 0 <= i <= ZZX_deg(self._numerator):
++            tmp = ZZX_coeff(self._numerator, i)
+             ZZX_SetCoeff(result, i*rel, tmp)
+-        ZZX_rem(x.__numerator, result, x.__fld_numerator.x)
++        ZZX_rem(x._numerator, result, x._fld_numerator.x)
+         return x
+ 
+     def __reduce__(self):
+@@ -858,7 +858,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef int res
+ 
+         # fast equality check
+-        res = left.__numerator == _right.__numerator and left.__denominator == _right.__denominator
++        res = left._numerator == _right._numerator and left._denominator == _right._denominator
+         if res:
+             if op == Py_EQ or op == Py_GE or op == Py_LE:
+                 return True
+@@ -883,15 +883,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         if P._embedded_real:
+             mpz_init(ld)
+             mpz_init(rd)
+-            ZZ_to_mpz(ld, &left.__denominator)
+-            ZZ_to_mpz(rd, &_right.__denominator)
++            ZZ_to_mpz(ld, &left._denominator)
++            ZZ_to_mpz(rd, &_right._denominator)
+ 
+             v = <RealIntervalFieldElement> P._get_embedding_approx(0)
+             mpfi_init2(la, mpfi_get_prec(v.value))
+             mpfi_init2(ra, mpfi_get_prec(v.value))
+-            ZZX_evaluation_mpfi(la, left.__numerator, v.value)
++            ZZX_evaluation_mpfi(la, left._numerator, v.value)
+             mpfi_div_z(la, la, ld)
+-            ZZX_evaluation_mpfi(ra, _right.__numerator, v.value)
++            ZZX_evaluation_mpfi(ra, _right._numerator, v.value)
+             mpfi_div_z(ra, ra, rd)
+             while mpfr_greaterequal_p(&la.right, &ra.left) \
+                   and mpfr_greaterequal_p(&ra.right, &la.left):
+@@ -899,9 +899,9 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+                 v = <RealIntervalFieldElement> P._get_embedding_approx(i)
+                 mpfi_set_prec(la, mpfi_get_prec(v.value))
+                 mpfi_set_prec(ra, mpfi_get_prec(v.value))
+-                ZZX_evaluation_mpfi(la, left.__numerator, v.value)
++                ZZX_evaluation_mpfi(la, left._numerator, v.value)
+                 mpfi_div_z(la, la, ld)
+-                ZZX_evaluation_mpfi(ra, _right.__numerator, v.value)
++                ZZX_evaluation_mpfi(ra, _right._numerator, v.value)
+                 mpfi_div_z(ra, ra, rd)
+             if op == Py_LT or op == Py_LE:
+                 res = mpfr_less_p(&la.right, &ra.left)
+@@ -950,8 +950,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef Rational tmp_rational
+ 
+         # It seems like a simpler approach would be to simply generate
+-        # random integers for each coefficient of self.__numerator
+-        # and an integer for self.__denominator. However, this would
++        # random integers for each coefficient of self._numerator
++        # and an integer for self._denominator. However, this would
+         # generate things with a fairly fixed shape: in particular,
+         # we'd be very unlikely to get elements like 1/3*a^3 + 1/7,
+         # or anything where the denominators are actually unrelated
+@@ -965,19 +965,19 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+ 
+             # set the denominator
+             mpz_set_si(denom_temp.value, 1)
+-            mpz_to_ZZ(&self.__denominator, (<Integer>denom_temp).value)
+-            for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
++            mpz_to_ZZ(&self._denominator, (<Integer>denom_temp).value)
++            for i from 0 <= i < ZZX_deg(self._fld_numerator.x):
+                 tmp_integer = <Integer>(ZZ.random_element(x=num_bound,
+                                                    distribution=distribution))
+                 mpz_to_ZZ(&ntl_temp, (<Integer>tmp_integer).value)
+-                ZZX_SetCoeff(self.__numerator, i, ntl_temp)
++                ZZX_SetCoeff(self._numerator, i, ntl_temp)
+ 
+         else:
+             coeff_list = []
+             mpz_set_si(denom_temp.value, 1)
+             tmp_integer = Integer.__new__(Integer)
+ 
+-            for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
++            for i from 0 <= i < ZZX_deg(self._fld_numerator.x):
+                 tmp_rational = <Rational>(QQ.random_element(num_bound=num_bound,
+                                                             den_bound=den_bound,
+                                                             distribution=distribution))
+@@ -989,10 +989,10 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             # scale the numerators and set everything appropriately
+ 
+             # first, the denominator (easy)
+-            mpz_to_ZZ(&self.__denominator, (<Integer>denom_temp).value)
++            mpz_to_ZZ(&self._denominator, (<Integer>denom_temp).value)
+ 
+             # now the coefficients themselves.
+-            for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
++            for i from 0 <= i < ZZX_deg(self._fld_numerator.x):
+                 # calculate the new numerator. if our old entry is
+                 # p/q, and the lcm is k, it's just pk/q, which we
+                 # also know is integral -- so we can use mpz_divexact
+@@ -1006,7 +1006,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+                 # now set the coefficient of self
+                 mpz_to_ZZ(&ntl_temp, (<Integer>tmp_integer).value)
+ 
+-                ZZX_SetCoeff(self.__numerator, i, ntl_temp)
++                ZZX_SetCoeff(self._numerator, i, ntl_temp)
+ 
+         return 0  # No error
+ 
+@@ -1089,10 +1089,10 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: L.zero().sign()
+             0
+         """
+-        if ZZX_deg(self.__numerator) == -1:
++        if ZZX_deg(self._numerator) == -1:
+             return 0
+-        if ZZX_deg(self.__numerator) == 0:
+-            return ZZ_sign(ZZX_coeff(self.__numerator, 0))
++        if ZZX_deg(self._numerator) == 0:
++            return ZZ_sign(ZZX_coeff(self._numerator, 0))
+ 
+         if not (<number_field_base.NumberField> self._parent)._embedded_real:
+             raise TypeError("sign not well defined since no real embedding is specified")
+@@ -1153,12 +1153,12 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef RealIntervalFieldElement v
+ 
+ 
+-        if ZZX_deg(self.__numerator) <= 0:
++        if ZZX_deg(self._numerator) <= 0:
+             mpz_init(num)
+             mpz_init(den)
+ 
+-            ZZX_getitem_as_mpz(num, &self.__numerator, 0)
+-            ZZ_to_mpz(den, &self.__denominator)
++            ZZX_getitem_as_mpz(num, &self._numerator, 0)
++            ZZ_to_mpz(den, &self._denominator)
+ 
+             ans = PY_NEW(Integer)
+             mpz_fdiv_q(ans.value, num, den)
+@@ -1183,9 +1183,9 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         mpz_init(den)
+         mpfi_init2(a, mpfi_get_prec(v.value))
+ 
+-        ZZ_to_mpz(den, &self.__denominator)
++        ZZ_to_mpz(den, &self._denominator)
+ 
+-        ZZX_evaluation_mpfi(a, self.__numerator, v.value)
++        ZZX_evaluation_mpfi(a, self._numerator, v.value)
+         mpfi_div_z(a, a, den)
+ 
+         mpfr_floor(&a.left, &a.left)
+@@ -1197,7 +1197,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             v = <RealIntervalFieldElement> P._get_embedding_approx(i)
+ 
+             mpfi_set_prec(a, mpfi_get_prec(v.value))
+-            ZZX_evaluation_mpfi(a, self.__numerator, v.value)
++            ZZX_evaluation_mpfi(a, self._numerator, v.value)
+             mpfi_div_z(a, a, den)
+             mpfr_floor(&a.left ,&a.left)
+             mpfr_floor(&a.right, &a.right)
+@@ -1248,7 +1248,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             ...
+             TypeError: ceil not uniquely defined since no real embedding is specified
+         """
+-        if ZZX_deg(self.__numerator) <= 0:
++        if ZZX_deg(self._numerator) <= 0:
+             return self._rational_().ceil()
+ 
+         if not (<number_field_base.NumberField> self._parent)._embedded_real:
+@@ -1311,7 +1311,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             ...
+             TypeError: floor not uniquely defined since no real embedding is specified
+         """
+-        if ZZX_deg(self.__numerator) <= 0:
++        if ZZX_deg(self._numerator) <= 0:
+             return self._rational_().round()
+ 
+         return (self + QQ((1,2))).floor()
+@@ -2483,17 +2483,17 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef ZZ_c gcd
+         cdef ZZ_c t1
+         cdef ZZX_c t2
+-        if ZZ_IsOne(self.__denominator):
++        if ZZ_IsOne(self._denominator):
+             return
+-        ZZX_content(t1, self.__numerator)
+-        ZZ_GCD(gcd, t1, self.__denominator)
+-        if ZZ_sign(gcd) != ZZ_sign(self.__denominator):
++        ZZX_content(t1, self._numerator)
++        ZZ_GCD(gcd, t1, self._denominator)
++        if ZZ_sign(gcd) != ZZ_sign(self._denominator):
+             ZZ_negate(t1, gcd)
+             gcd = t1
+-        ZZX_div_ZZ(t2, self.__numerator, gcd)
+-        ZZ_div(t1, self.__denominator, gcd)
+-        self.__numerator = t2
+-        self.__denominator = t1
++        ZZX_div_ZZ(t2, self._numerator, gcd)
++        ZZ_div(t1, self._denominator, gcd)
++        self._numerator = t2
++        self._denominator = t1
+ 
+     cpdef _add_(self, right):
+         r"""
+@@ -2509,15 +2509,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef NumberFieldElement _right = right
+         cdef ZZ_c g, q1, q2
+         x = self._new()
+-        ZZ_GCD(g, self.__denominator, _right.__denominator)
+-        ZZ_div(q1, self.__denominator, g)
+-        ZZ_div(q2, _right.__denominator, g)
+-        ZZ_mul(x.__denominator, q1, q2)
+-        ZZ_mul(x.__denominator, x.__denominator, g)
++        ZZ_GCD(g, self._denominator, _right._denominator)
++        ZZ_div(q1, self._denominator, g)
++        ZZ_div(q2, _right._denominator, g)
++        ZZ_mul(x._denominator, q1, q2)
++        ZZ_mul(x._denominator, x._denominator, g)
+         cdef ZZX_c t1, t2
+-        ZZX_mul_ZZ(t1, self.__numerator, q2)
+-        ZZX_mul_ZZ(t2, _right.__numerator, q1)
+-        ZZX_add(x.__numerator, t1, t2)
++        ZZX_mul_ZZ(t1, self._numerator, q2)
++        ZZX_mul_ZZ(t2, _right._numerator, q1)
++        ZZX_add(x._numerator, t1, t2)
+         x._reduce_c_()
+         return x
+ 
+@@ -2534,15 +2534,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef NumberFieldElement _right = right
+         cdef ZZ_c g, q1, q2
+         x = self._new()
+-        ZZ_GCD(g, self.__denominator, _right.__denominator)
+-        ZZ_div(q1, self.__denominator, g)
+-        ZZ_div(q2, _right.__denominator, g)
+-        ZZ_mul(x.__denominator, q1, q2)
+-        ZZ_mul(x.__denominator, x.__denominator, g)
++        ZZ_GCD(g, self._denominator, _right._denominator)
++        ZZ_div(q1, self._denominator, g)
++        ZZ_div(q2, _right._denominator, g)
++        ZZ_mul(x._denominator, q1, q2)
++        ZZ_mul(x._denominator, x._denominator, g)
+         cdef ZZX_c t1, t2
+-        ZZX_mul_ZZ(t1, self.__numerator, q2)
+-        ZZX_mul_ZZ(t2, _right.__numerator, q1)
+-        ZZX_sub(x.__numerator, t1, t2)
++        ZZX_mul_ZZ(t1, self._numerator, q2)
++        ZZX_mul_ZZ(t2, _right._numerator, q1)
++        ZZX_sub(x._numerator, t1, t2)
+         x._reduce_c_()
+         return x
+ 
+@@ -2571,18 +2571,18 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         sig_on()
+         # MulMod doesn't handle non-monic polynomials.
+         # Therefore, we handle the non-monic case entirely separately.
+-        ZZ_mul(x.__denominator, self.__denominator, _right.__denominator)
+-        if ZZ_IsOne(ZZX_LeadCoeff(self.__fld_numerator.x)):
+-            ZZX_MulMod(x.__numerator, self.__numerator, _right.__numerator, self.__fld_numerator.x)
++        ZZ_mul(x._denominator, self._denominator, _right._denominator)
++        if ZZ_IsOne(ZZX_LeadCoeff(self._fld_numerator.x)):
++            ZZX_MulMod(x._numerator, self._numerator, _right._numerator, self._fld_numerator.x)
+         else:
+-            ZZX_mul(x.__numerator, self.__numerator, _right.__numerator)
+-            if ZZX_deg(x.__numerator) >= ZZX_deg(self.__fld_numerator.x):
+-                ZZX_mul_ZZ( x.__numerator, x.__numerator, self.__fld_denominator.x )
+-                ZZX_mul_ZZ( temp, self.__fld_numerator.x, x.__denominator )
+-                ZZ_power(temp1,ZZX_LeadCoeff(temp),ZZX_deg(x.__numerator)-ZZX_deg(self.__fld_numerator.x)+1)
+-                ZZX_PseudoRem(x.__numerator, x.__numerator, temp)
+-                ZZ_mul(x.__denominator, x.__denominator, self.__fld_denominator.x)
+-                ZZ_mul(x.__denominator, x.__denominator, temp1)
++            ZZX_mul(x._numerator, self._numerator, _right._numerator)
++            if ZZX_deg(x._numerator) >= ZZX_deg(self._fld_numerator.x):
++                ZZX_mul_ZZ( x._numerator, x._numerator, self._fld_denominator.x )
++                ZZX_mul_ZZ( temp, self._fld_numerator.x, x._denominator )
++                ZZ_power(temp1,ZZX_LeadCoeff(temp),ZZX_deg(x._numerator)-ZZX_deg(self._fld_numerator.x)+1)
++                ZZX_PseudoRem(x._numerator, x._numerator, temp)
++                ZZ_mul(x._denominator, x._denominator, self._fld_denominator.x)
++                ZZ_mul(x._denominator, x._denominator, temp1)
+         sig_off()
+         x._reduce_c_()
+         return x
+@@ -2704,7 +2704,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: bool(b + 1)
+             True
+         """
+-        return not IsZero_ZZX(self.__numerator)
++        return not IsZero_ZZX(self._numerator)
+ 
+     cpdef _neg_(self):
+         r"""
+@@ -2717,8 +2717,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         """
+         cdef NumberFieldElement x
+         x = self._new()
+-        ZZX_mul_long(x.__numerator, self.__numerator, -1)
+-        x.__denominator = self.__denominator
++        ZZX_mul_long(x._numerator, self._numerator, -1)
++        x._denominator = self._denominator
+         return x
+ 
+     cpdef _copy_for_parent(self, Parent parent):
+@@ -2738,8 +2738,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         """
+         cdef NumberFieldElement x
+         x = self._new()
+-        x.__numerator = self.__numerator
+-        x.__denominator = self.__denominator
++        x._numerator = self._numerator
++        x._denominator = self._denominator
+         x._set_parent(parent)
+         return x
+ 
+@@ -2826,7 +2826,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: L.<a> = K.extension(f)
+             sage: alpha = (a^8 + (zeta22^9 - zeta22^6 + 2*zeta22^4 + 33)*a^7)/(10**2555) #long time
+         """
+-        if IsZero_ZZX(self.__numerator):
++        if IsZero_ZZX(self._numerator):
+             raise ZeroDivisionError("number field element division by zero")
+         cdef NumberFieldElement x
+         cdef ZZX_c temp
+@@ -2835,8 +2835,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             # but may fail if NTL runs out of FFT primes.
+             x = self._new()
+             sig_on()
+-            ZZX_XGCD(x.__denominator, x.__numerator, temp, self.__numerator, self.__fld_numerator.x, 1)
+-            ZZX_mul_ZZ(x.__numerator, x.__numerator, self.__denominator)
++            ZZX_XGCD(x._denominator, x._numerator, temp, self._numerator, self._fld_numerator.x, 1)
++            ZZX_mul_ZZ(x._numerator, x._numerator, self._denominator)
+             x._reduce_c_()
+             sig_off()
+         except NTLError:
+@@ -2858,7 +2858,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: (2*I*I)._integer_()
+             -2
+         """
+-        if ZZX_deg(self.__numerator) >= 1:
++        if ZZX_deg(self._numerator) >= 1:
+             raise TypeError("Unable to coerce %s to an integer" % self)
+         return ZZ(self._rational_())
+ 
+@@ -2877,12 +2877,12 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: (I*I/2)._rational_()
+             -1/2
+         """
+-        if ZZX_deg(self.__numerator) >= 1:
++        if ZZX_deg(self._numerator) >= 1:
+             raise TypeError("Unable to coerce %s to a rational"%self)
+         cdef Integer num = Integer.__new__(Integer)
+-        ZZX_getitem_as_mpz(num.value, &self.__numerator, 0)
++        ZZX_getitem_as_mpz(num.value, &self._numerator, 0)
+         cdef Integer den = Integer.__new__(Integer)
+-        ZZ_to_mpz(den.value, &self.__denominator)
++        ZZ_to_mpz(den.value, &self._denominator)
+         return num / den
+ 
+     def _algebraic_(self, parent):
+@@ -3268,15 +3268,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef mpz_t z
+ 
+         mpz_init(z)
+-        ZZX_getitem_as_mpz(z, &self.__numerator, 0)
++        ZZX_getitem_as_mpz(z, &self._numerator, 0)
+         h = mpz_pythonhash(z)
+ 
+-        for i from 1 <= i <= ZZX_deg(self.__numerator):
+-            ZZX_getitem_as_mpz(z, &self.__numerator, i)
++        for i from 1 <= i <= ZZX_deg(self._numerator):
++            ZZX_getitem_as_mpz(z, &self._numerator, i)
+             # magic number below is floor(2^63 / (2+sqrt(2)))
+             h ^= mpz_pythonhash(z) + (<Py_hash_t> 2701463124188384701) + (h << 16) + (h >> 2)
+ 
+-        ZZ_to_mpz(z, &self.__denominator)
++        ZZ_to_mpz(z, &self._denominator)
+         # magic number below is floor((1+sqrt(5)) * 2^61)
+         h += (mpz_pythonhash(z) - 1) * (<Py_hash_t> 7461864723258187525)
+ 
+@@ -3305,12 +3305,12 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef int i
+         cdef mpz_t den
+         mpz_init(den)
+-        ZZ_to_mpz(den, &self.__denominator)
+-        cdef int size = ZZX_deg(self.__numerator) + 1
++        ZZ_to_mpz(den, &self._denominator)
++        cdef int size = ZZX_deg(self._numerator) + 1
+         cdef list coeffs = [None]*size
+         for i in range(size):
+             coeff = Rational.__new__(Rational)
+-            ZZX_getitem_as_mpz(mpq_numref(coeff.value), &self.__numerator, i)
++            ZZX_getitem_as_mpz(mpq_numref(coeff.value), &self._numerator, i)
+             mpz_set(mpq_denref(coeff.value), den)
+             mpq_canonicalize(coeff.value)
+             coeffs[i] = coeff
+@@ -3318,14 +3318,14 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         return coeffs
+ 
+     cdef void _ntl_coeff_as_mpz(self, mpz_t z, long i):
+-        if i > ZZX_deg(self.__numerator):
++        if i > ZZX_deg(self._numerator):
+             mpz_set_ui(z, 0)
+         else:
+-            ZZX_getitem_as_mpz(z, &self.__numerator, i)
++            ZZX_getitem_as_mpz(z, &self._numerator, i)
+ 
+     cdef void _ntl_denom_as_mpz(self, mpz_t z):
+         cdef Integer denom = Integer.__new__(Integer)
+-        ZZ_to_mpz(denom.value, &self.__denominator)
++        ZZ_to_mpz(denom.value, &self._denominator)
+         mpz_set(z, denom.value)
+ 
+     def denominator(self):
+@@ -3344,7 +3344,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             15
+         """
+         cdef Integer ans = Integer.__new__(Integer)
+-        ZZ_to_mpz(ans.value, &self.__denominator)
++        ZZ_to_mpz(ans.value, &self._denominator)
+         return ans
+ 
+     def _set_multiplicative_order(self, n):
+@@ -3474,8 +3474,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: a.is_one()
+             False
+         """
+-        return ZZX_IsOne(self.__numerator) == 1 and \
+-               ZZ_IsOne(self.__denominator) == 1
++        return ZZX_IsOne(self._numerator) == 1 and \
++               ZZ_IsOne(self._denominator) == 1
+ 
+     cpdef bint is_rational(self):
+         r"""
+@@ -3501,7 +3501,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: K(1/2).is_rational()
+             True
+         """
+-        return ZZX_deg(self.__numerator) <= 0
++        return ZZX_deg(self._numerator) <= 0
+ 
+     def is_integer(self):
+         r"""
+@@ -3527,7 +3527,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: K(1/2).is_integer()
+             False
+         """
+-        return ZZX_deg(self.__numerator) <= 0 and ZZ_IsOne(self.__denominator) == 1
++        return ZZX_deg(self._numerator) <= 0 and ZZ_IsOne(self._denominator) == 1
+ 
+     def trace(self, K=None):
+         r"""
+@@ -5322,8 +5322,8 @@ cdef class OrderElement_absolute(NumberFieldElement_absolute):
+         cdef OrderElement_absolute x = <OrderElement_absolute>t.__new__(t)
+         x._parent = self._parent
+         x._number_field = self._parent.number_field()
+-        x.__fld_numerator = self.__fld_numerator
+-        x.__fld_denominator = self.__fld_denominator
++        x._fld_numerator = self._fld_numerator
++        x._fld_denominator = self._fld_denominator
+         return x
+ 
+     cdef number_field(self):
+@@ -5443,8 +5443,8 @@ cdef class OrderElement_relative(NumberFieldElement_relative):
+         cdef OrderElement_relative x = <OrderElement_relative>t.__new__(t)
+         x._parent = self._parent
+         x._number_field = self._parent.number_field()
+-        x.__fld_numerator = self.__fld_numerator
+-        x.__fld_denominator = self.__fld_denominator
++        x._fld_numerator = self._fld_numerator
++        x._fld_denominator = self._fld_denominator
+         return x
+ 
+     def __invert__(self):
+diff --git a/src/sage/rings/number_field/number_field_element_quadratic.pyx b/src/sage/rings/number_field/number_field_element_quadratic.pyx
+index 0992e7cd527..c32f6aadd10 100644
+--- a/src/sage/rings/number_field/number_field_element_quadratic.pyx
++++ b/src/sage/rings/number_field/number_field_element_quadratic.pyx
+@@ -610,8 +610,8 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+         mpz_clear(tmp_mpz)
+ 
+         x._parent = <ParentWithBase>new_parent
+-        x.__fld_numerator, x.__fld_denominator = new_parent.polynomial_ntl()
+-        x.__denominator = elt_den
++        x._fld_numerator, x._fld_denominator = new_parent.polynomial_ntl()
++        x._denominator = elt_den
+         cdef ZZX_c result
+         cdef ZZ_c tmp
+         cdef int i
+@@ -621,7 +621,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+         for i from 0 <= i <= ZZX_deg(elt_num):
+             tmp = ZZX_coeff(elt_num, i)
+             ZZX_SetCoeff(result, i*rel, tmp)
+-        ZZX_rem(x.__numerator, result, _num.x)
++        ZZX_rem(x._numerator, result, _num.x)
+         (<NumberFieldElement_absolute>x)._reduce_c_()
+         return x
+ 
+@@ -1643,7 +1643,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+         return res
+ 
+ #################################################################################
+-# We must override everything that makes uses of self.__numerator/__denominator
++# We must override everything that makes uses of self._numerator/_denominator
+ #################################################################################
+ 
+     def __hash__(self):
+diff --git a/src/sage/rings/padics/CA_template.pxi b/src/sage/rings/padics/CA_template.pxi
+index a0a66c19621..d821b5c1576 100644
+--- a/src/sage/rings/padics/CA_template.pxi
++++ b/src/sage/rings/padics/CA_template.pxi
+@@ -1463,7 +1463,7 @@ cdef class pAdicCoercion_CA_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         ans._normalize()
+         return ans
+ 
+@@ -1516,7 +1516,7 @@ cdef class pAdicCoercion_CA_frac_field(RingHomomorphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+             pass
+         return ans
+ 
+@@ -1686,7 +1686,7 @@ cdef class pAdicConvert_CA_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 R = ans.value.base_ring()
+-                ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++                ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1741,7 +1741,7 @@ cdef class pAdicConvert_CA_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 R = ans.value.base_ring()
+-                ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++                ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/CR_template.pxi b/src/sage/rings/padics/CR_template.pxi
+index cb57bb2cb48..863c612587c 100644
+--- a/src/sage/rings/padics/CR_template.pxi
++++ b/src/sage/rings/padics/CR_template.pxi
+@@ -2184,7 +2184,7 @@ cdef class pAdicCoercion_CR_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -2241,7 +2241,7 @@ cdef class pAdicCoercion_CR_frac_field(RingHomomorphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     def section(self):
+@@ -2404,7 +2404,7 @@ cdef class pAdicConvert_CR_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -2463,7 +2463,7 @@ cdef class pAdicConvert_CR_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/FM_template.pxi b/src/sage/rings/padics/FM_template.pxi
+index ea7d4055660..f47200074ea 100644
+--- a/src/sage/rings/padics/FM_template.pxi
++++ b/src/sage/rings/padics/FM_template.pxi
+@@ -1227,7 +1227,7 @@ cdef class pAdicCoercion_FM_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1277,7 +1277,7 @@ cdef class pAdicCoercion_FM_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     def section(self):
+@@ -1435,7 +1435,7 @@ cdef class pAdicConvert_FM_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             R = ans.value.base_ring()
+-            ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++            ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1483,7 +1483,7 @@ cdef class pAdicConvert_FM_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             R = ans.value.base_ring()
+-            ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++            ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/FP_template.pxi b/src/sage/rings/padics/FP_template.pxi
+index 57ec619b278..c718c0a5f8d 100644
+--- a/src/sage/rings/padics/FP_template.pxi
++++ b/src/sage/rings/padics/FP_template.pxi
+@@ -1849,7 +1849,7 @@ cdef class pAdicCoercion_FP_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1903,7 +1903,7 @@ cdef class pAdicCoercion_FP_frac_field(RingHomomorphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     def section(self):
+@@ -2025,7 +2025,7 @@ cdef class pAdicConvert_FP_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -2081,7 +2081,7 @@ cdef class pAdicConvert_FP_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/pow_computer.pxd b/src/sage/rings/padics/pow_computer.pxd
+index 2a93e42254e..8766725882e 100644
+--- a/src/sage/rings/padics/pow_computer.pxd
++++ b/src/sage/rings/padics/pow_computer.pxd
+@@ -6,7 +6,7 @@ cdef class PowComputer_class(SageObject):
+     cdef Integer prime
+     cdef Integer p2 # floor(p/2)
+     cdef bint in_field
+-    cdef int __allocated
++    cdef int _allocated
+     cdef public object _prec_type
+ 
+     cdef long ram_prec_cap # = prec_cap * e
+diff --git a/src/sage/rings/padics/pow_computer.pyx b/src/sage/rings/padics/pow_computer.pyx
+index c2fa8031086..1c5bdf86897 100644
+--- a/src/sage/rings/padics/pow_computer.pyx
++++ b/src/sage/rings/padics/pow_computer.pyx
+@@ -65,7 +65,7 @@ cdef class PowComputer_class(SageObject):
+         sig_on()
+         mpz_init(self.temp_m)
+         sig_off()
+-        self.__allocated = 1
++        self._allocated = 1
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly=None, shift_seed=None):
+         """
+@@ -485,7 +485,7 @@ cdef class PowComputer_base(PowComputer_class):
+         finally:
+             sig_off()
+ 
+-        self.__allocated = 2
++        self._allocated = 2
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly=None, shift_seed=None):
+         """
+@@ -529,7 +529,7 @@ cdef class PowComputer_base(PowComputer_class):
+         """
+         cdef Py_ssize_t i
+ 
+-        if self.__allocated >= 2:
++        if self._allocated >= 2:
+             for i in range(self.cache_limit + 1):
+                 mpz_clear(self.small_powers[i])
+             mpz_clear(self.top_power)
+diff --git a/src/sage/rings/padics/pow_computer_flint.pyx b/src/sage/rings/padics/pow_computer_flint.pyx
+index 9f914defcc6..e521ea6e078 100644
+--- a/src/sage/rings/padics/pow_computer_flint.pyx
++++ b/src/sage/rings/padics/pow_computer_flint.pyx
+@@ -59,7 +59,7 @@ cdef class PowComputer_flint(PowComputer_class):
+         finally:
+             sig_off()
+ 
+-        self.__allocated = 4
++        self._allocated = 4
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly=None, shift_seed=None):
+         """
+@@ -87,7 +87,7 @@ cdef class PowComputer_flint(PowComputer_class):
+             sage: A = PowComputer_flint(5, 20, 20, 20, False)
+             sage: del A
+         """
+-        if self.__allocated >= 4:
++        if self._allocated >= 4:
+             fmpz_clear(self.fprime)
+             fmpz_clear(self.half_prime)
+             fmpz_clear(self._fpow_variable)
+@@ -208,7 +208,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+ 
+         """
+         cdef Polynomial_integer_dense_flint poly = _poly
+-        cdef long length = fmpz_poly_length(poly.__poly)
++        cdef long length = fmpz_poly_length(poly._poly)
+ 
+         cdef Py_ssize_t i
+ 
+@@ -251,7 +251,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         finally:
+             sig_off()
+ 
+-        self.__allocated = 8
++        self._allocated = 8
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, _poly, shift_seed=None):
+         """
+@@ -268,10 +268,10 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         PowComputer_flint.__init__(self, prime, cache_limit, prec_cap, ram_prec_cap, in_field, _poly, shift_seed)
+ 
+         cdef Polynomial_integer_dense_flint poly = _poly
+-        cdef long length = fmpz_poly_length(poly.__poly)
++        cdef long length = fmpz_poly_length(poly._poly)
+         self.deg = length - 1
+ 
+-        fmpz_poly_set(self.modulus, poly.__poly)
++        fmpz_poly_set(self.modulus, poly._poly)
+ 
+         cdef Py_ssize_t i
+         cdef fmpz* coeffs = self.modulus.coeffs
+@@ -296,7 +296,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         """
+         cdef Py_ssize_t i
+ 
+-        if self.__allocated >= 8:
++        if self._allocated >= 8:
+             fmpz_clear(self.q)
+             fmpz_poly_clear(self.modulus)
+             fmpz_poly_clear(self.powhelper_oneunit)
+@@ -427,9 +427,9 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         x = R.gen()
+         cdef Polynomial_integer_dense_flint ans = (<Polynomial_integer_dense_flint?>x)._new()
+         if _n is None:
+-            fmpz_poly_set(ans.__poly, self.modulus)
++            fmpz_poly_set(ans._poly, self.modulus)
+         else:
+-            fmpz_poly_set(ans.__poly, self.get_modulus(_n)[0])
++            fmpz_poly_set(ans._poly, self.get_modulus(_n)[0])
+         return ans
+ 
+     cdef _new_fmpz_poly(self, fmpz_poly_t value, var='x'):
+@@ -440,7 +440,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         R = ZZ[var]
+         x = R.gen()
+         cdef Polynomial_integer_dense_flint ans = (<Polynomial_integer_dense_flint?>x)._new()
+-        fmpz_poly_set(ans.__poly, value)
++        fmpz_poly_set(ans._poly, value)
+         return ans
+ 
+ cdef class PowComputer_flint_unram(PowComputer_flint_1step):
+@@ -501,7 +501,7 @@ cdef class PowComputer_flint_unram(PowComputer_flint_1step):
+         mpz_init(self.mpz_matmod)
+         sig_off()
+ 
+-        self.__allocated = 16
++        self._allocated = 16
+ 
+     def __dealloc__(self):
+         """
+@@ -515,7 +515,7 @@ cdef class PowComputer_flint_unram(PowComputer_flint_1step):
+             sage: del A
+ 
+         """
+-        if self.__allocated >= 16:
++        if self._allocated >= 16:
+             fmpz_clear(self.fmpz_ccmp)
+             fmpz_clear(self.fmpz_cval)
+             fmpz_clear(self.fmpz_cinv)
+diff --git a/src/sage/rings/padics/pow_computer_relative.pxd b/src/sage/rings/padics/pow_computer_relative.pxd
+index fc7d5b21f42..e0e5aa5600e 100644
+--- a/src/sage/rings/padics/pow_computer_relative.pxd
++++ b/src/sage/rings/padics/pow_computer_relative.pxd
+@@ -18,7 +18,7 @@ cdef class PowComputer_relative(PowComputer_class):
+     cdef Polynomial_generic_dense shift_rem
+     cdef Polynomial_generic_dense aliasing
+     # allow cached methods
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+     cdef unsigned long capdiv(self, unsigned long n)
+ 
+diff --git a/src/sage/rings/padics/pow_computer_relative.pyx b/src/sage/rings/padics/pow_computer_relative.pyx
+index 39051a681de..2253281bd35 100644
+--- a/src/sage/rings/padics/pow_computer_relative.pyx
++++ b/src/sage/rings/padics/pow_computer_relative.pyx
+@@ -69,7 +69,7 @@ cdef class PowComputer_relative(PowComputer_class):
+             sage: PC = PowComputer_relative_maker(3, 20, 20, 60, False, f, shift_seed, 'fixed-mod')
+ 
+         """
+-        self.__allocated = 4
++        self._allocated = 4
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly, shift_seed):
+         r"""
+diff --git a/src/sage/rings/polynomial/hilbert.pyx b/src/sage/rings/polynomial/hilbert.pyx
+index a1f70e0c983..d2abf325fd8 100644
+--- a/src/sage/rings/polynomial/hilbert.pyx
++++ b/src/sage/rings/polynomial/hilbert.pyx
+@@ -170,7 +170,7 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+     cdef int e
+     # First, the easiest cases:
+     if not D.Id: # The zero ideal
+-        fmpz_poly_set_coeff_si(fhs.__poly, 0, 1) # = PR(1)
++        fmpz_poly_set_coeff_si(fhs._poly, 0, 1) # = PR(1)
+         return True
+     cdef ETuple m = <ETuple>PyList_GET_ITEM(D.Id, len(D.Id)-1)
+     if m._nonzero == 0: # The one ideal
+@@ -183,18 +183,18 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+     if m._nonzero == 1 and m._data[1] == 1:
+         fmpz_poly_init(poly_tmp)
+         fmpz_poly_set_coeff_si(poly_tmp, 0, 1)
+-        fmpz_poly_set_coeff_si(fhs.__poly, 0, 1) # = PR(1)
++        fmpz_poly_set_coeff_si(fhs._poly, 0, 1) # = PR(1)
+         if w is None:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).unweighted_degree()
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         else:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).weighted_degree(w)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         fmpz_poly_clear(poly_tmp)
+         return True # PR.prod([(1-t**degree(m,w)) for m in D.Id])
+@@ -210,18 +210,18 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+         # The ideal is generated by some powers of single variables, i.e., it splits.
+         fmpz_poly_init(poly_tmp)
+         fmpz_poly_set_coeff_si(poly_tmp, 0, 1)
+-        fmpz_poly_set_coeff_si(fhs.__poly, 0, 1) # = PR(1)
++        fmpz_poly_set_coeff_si(fhs._poly, 0, 1) # = PR(1)
+         if w is None:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).unweighted_degree()
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         else:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).weighted_degree(w)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         fmpz_poly_clear(poly_tmp)
+         return True # PR.prod([(1-t**degree(m,w)) for m in D.Id])
+@@ -278,8 +278,8 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+                     fmpz_poly_mul(SecondSummand, SecondSummand, poly_tmp)
+                     fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         fmpz_poly_clear(poly_tmp)
+-        fmpz_poly_add(fhs.__poly, fhs.__poly, FirstSummand)
+-        fmpz_poly_add(fhs.__poly, fhs.__poly, SecondSummand)
++        fmpz_poly_add(fhs._poly, fhs._poly, FirstSummand)
++        fmpz_poly_add(fhs._poly, fhs._poly, SecondSummand)
+         fmpz_poly_clear(FirstSummand)
+         fmpz_poly_clear(SecondSummand)
+         return True
+@@ -532,11 +532,11 @@ def first_hilbert_series(I, grading=None, return_grading=False):
+                 if AN.Back.Right is None:
+                     AN = AN.Back
+                     #~ fhs *= AN.LMult
+-                    fmpz_poly_mul(fhs.__poly, fhs.__poly, AN.LMult)
++                    fmpz_poly_mul(fhs._poly, fhs._poly, AN.LMult)
+                     got_result = True
+                 else:
+-                    fmpz_poly_set(AN.Back.LeftFHS, fhs.__poly)
+-                    fmpz_poly_set_si(fhs.__poly, 0)
++                    fmpz_poly_set(AN.Back.LeftFHS, fhs._poly)
++                    fmpz_poly_set_si(fhs._poly, 0)
+                     AN = AN.Back.Right
+                     AN.Back.Left = None
+                     got_result = HilbertBaseCase(fhs, AN, w)
+@@ -545,8 +545,8 @@ def first_hilbert_series(I, grading=None, return_grading=False):
+                 AN.Right = None
+                 #~ fhs = AN.LMult*AN.LeftFHS + AN.RMult*fhs
+                 fmpz_poly_mul(AN.LMult, AN.LMult, AN.LeftFHS)
+-                fmpz_poly_mul(AN.RMult, AN.RMult, fhs.__poly)
+-                fmpz_poly_add(fhs.__poly, AN.LMult, AN.RMult)
++                fmpz_poly_mul(AN.RMult, AN.RMult, fhs._poly)
++                fmpz_poly_add(fhs._poly, AN.LMult, AN.RMult)
+                 got_result = True
+ 
+ def hilbert_poincare_series(I, grading=None):
+diff --git a/src/sage/rings/polynomial/laurent_polynomial.pxd b/src/sage/rings/polynomial/laurent_polynomial.pxd
+index 3648d6d1ed1..8e9107aeb47 100644
+--- a/src/sage/rings/polynomial/laurent_polynomial.pxd
++++ b/src/sage/rings/polynomial/laurent_polynomial.pxd
+@@ -12,6 +12,6 @@ cdef class LaurentPolynomial(CommutativeAlgebraElement):
+ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+     cdef ModuleElement __u
+     cdef long __n
+-    cpdef __normalize(self)
++    cpdef _normalize(self)
+     cpdef _unsafe_mutate(self, i, value)
+ 
+diff --git a/src/sage/rings/polynomial/laurent_polynomial.pyx b/src/sage/rings/polynomial/laurent_polynomial.pyx
+index 4be246c6688..cd79996eed7 100644
+--- a/src/sage/rings/polynomial/laurent_polynomial.pyx
++++ b/src/sage/rings/polynomial/laurent_polynomial.pyx
+@@ -366,7 +366,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         # self is that t^n * u:
+         self.__u = f
+         self.__n = n
+-        self.__normalize()
++        self._normalize()
+ 
+     def __reduce__(self):
+         """
+@@ -531,7 +531,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+             u = u.map_coefficients(base_map)
+         return codomain(u(x) * x**self.__n)
+ 
+-    cpdef __normalize(self):
++    cpdef _normalize(self):
+         r"""
+         A Laurent series is a pair `(u(t), n)`, where either `u = 0`
+         (to some precision) or `u` is a unit. This pair corresponds to
+@@ -763,7 +763,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+             ret = <LaurentPolynomial_univariate> self._new_c()
+             ret.__u = f
+             ret.__n = self.__n
+-            ret.__normalize()
++            ret._normalize()
+             return ret
+ 
+         return self.__u[i - self.__n]
+@@ -919,7 +919,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+                 R = self._parent.base_ring()
+                 coeffs = [value] + [R.zero() for _ in range(1,-j)] + self.__u.list()
+                 self.__u = self.__u._parent(coeffs)
+-        self.__normalize()
++        self._normalize()
+ 
+     cpdef _add_(self, right_m):
+         """
+@@ -972,7 +972,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (f1 + f2)
+         ret.__n = m
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     cpdef _sub_(self, right_m):
+@@ -1012,7 +1012,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (f1 - f2)
+         ret.__n = m
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def degree(self):
+@@ -1063,7 +1063,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (self.__u * right.__u)
+         ret.__n = self.__n + right.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     cpdef _rmul_(self, Element c):
+@@ -1079,7 +1079,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self.__u._rmul_(c)
+         ret.__n = self.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     cpdef _lmul_(self, Element c):
+@@ -1095,7 +1095,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self.__u._lmul_(c)
+         ret.__n = self.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def is_monomial(self):
+@@ -1175,7 +1175,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (self.__u // right.__u)
+         ret.__n = self.__n - right.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def shift(self, k):
+@@ -1287,7 +1287,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+             if self.__u.is_unit():
+                 ret.__u = self.__u.inverse_of_unit()
+                 ret.__n = -self.__n
+-                ret.__normalize()
++                ret._normalize()
+                 return ret
+             # Enlarge the ring so we can divide by the coefficient
+             R = self._parent.base_ring().fraction_field()
+@@ -1362,7 +1362,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = self.__u.gcd(b.__u)
+         ret.__n = min(self.__n, b.__n)
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     @coerce_binop
+@@ -1408,11 +1408,11 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ql = <LaurentPolynomial_univariate> self._new_c()
+         ql.__u = <ModuleElement> q
+         ql.__n = self.__n - right.__n
+-        ql.__normalize()
++        ql._normalize()
+         qr = <LaurentPolynomial_univariate> self._new_c()
+         qr.__u = <ModuleElement> r
+         qr.__n = self.__n
+-        qr.__normalize()
++        qr._normalize()
+         return ql, qr
+ 
+     cpdef _richcmp_(self, right_r, int op):
+@@ -1519,7 +1519,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self.__u.truncate(n - self.__n)
+         ret.__n = self.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def variable_name(self):
+@@ -1777,7 +1777,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+                 ret = <LaurentPolynomial_univariate> self._new_c()
+                 ret.__u = <ModuleElement> self._parent._R(u)
+                 ret.__n = self.__n
+-                ret.__normalize()
++                ret._normalize()
+                 return ret
+             except AttributeError:
+                 raise ValueError('cannot differentiate with respect to {}'.format(var))
+@@ -1792,7 +1792,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self._parent._R(a)
+         ret.__n = self.__n - 1
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def integral(self):
+@@ -1857,7 +1857,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> u
+         ret.__n = n + 1
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def __call__(self, *x, **kwds):
+@@ -1919,14 +1919,14 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         u = <LaurentPolynomial_univariate> self._new_c()
+         u.__u = pf.unit()
+         u.__n = self.__n
+-        u.__normalize()
++        u._normalize()
+ 
+         f = []
+         for t in pf:
+             d = <LaurentPolynomial_univariate> self._new_c()
+             d.__u = t[0]
+             d.__n = 0
+-            d.__normalize()
++            d._normalize()
+             if d.is_unit():
+                 u *= d ** t[1]
+             else:
+diff --git a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx
+index d796b7f8169..83c79c39843 100644
+--- a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx
++++ b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx
+@@ -375,7 +375,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+             ...
+             NotImplementedError: polynomials in -1 variables are not supported in Singular
+         """
+-        self.__ngens = n
++        self._ngens = n
+         self._ring = singular_ring_new(base_ring, n, names, order)
+         self._zero_element = new_MP(self, NULL)
+         cdef MPolynomial_libsingular one = new_MP(self, p_ISet(1, self._ring))
+@@ -1019,7 +1019,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+             Multivariate Polynomial Ring in x, y over Rational Field
+         """
+         varstr = ", ".join(char_to_str(rRingVar(i,self._ring))
+-                           for i in range(self.__ngens))
++                           for i in range(self._ngens))
+         return "Multivariate Polynomial Ring in %s over %s" % (varstr, self.base_ring())
+ 
+     def ngens(self):
+@@ -1037,7 +1037,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+             sage: P.ngens()                                                             # needs sage.rings.finite_rings
+             1000
+         """
+-        return int(self.__ngens)
++        return int(self._ngens)
+ 
+     def gen(self, int n=0):
+         """
+@@ -1065,7 +1065,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+         cdef poly *_p
+         cdef ring *_ring = self._ring
+ 
+-        if n < 0 or n >= self.__ngens:
++        if n < 0 or n >= self._ngens:
+             raise ValueError("Generator not defined.")
+ 
+         rChangeCurrRing(_ring)
+@@ -1494,7 +1494,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+         return unpickle_MPolynomialRing_libsingular, \
+             (self.base_ring(), self.variable_names(), self.term_order())
+ 
+-    def __temporarily_change_names(self, names, latex_names):
++    def _temporarily_change_names(self, names, latex_names):
+         """
+         This is used by the variable names context manager.
+ 
+diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd b/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd
+index fc81cf6d298..eb6f8b70917 100644
+--- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd
++++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd
+@@ -2,8 +2,8 @@ cimport sage.rings.ring
+ from sage.structure.parent cimport Parent
+ 
+ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+-    cdef object __ngens
+-    cdef object __term_order
++    cdef object _ngens
++    cdef object _term_order
+     cdef public object _has_singular
+     cdef public object _magma_gens
+     cdef public dict _magma_cache
+diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx
+index 1d3fbc60944..c8f66508cc2 100644
+--- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx
++++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx
+@@ -80,8 +80,8 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+             raise ValueError("Multivariate Polynomial Rings must "
+                              "have more than 0 variables.")
+         order = TermOrder(order, n)
+-        self.__ngens = n
+-        self.__term_order = order
++        self._ngens = n
++        self._term_order = order
+         self._has_singular = False  # cannot convert to Singular by default
+         self._magma_cache = {}
+         # Ring.__init__ already does assign the names.
+@@ -639,12 +639,12 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         lft = <MPolynomialRing_base>left
+         other = <MPolynomialRing_base>right
+ 
+-        lx = (lft.base_ring(), lft.__ngens,
++        lx = (lft.base_ring(), lft._ngens,
+               lft.variable_names(),
+-              lft.__term_order)
+-        rx = (other.base_ring(), other.__ngens,
++              lft._term_order)
++        rx = (other.base_ring(), other._ngens,
+               other.variable_names(),
+-              other.__term_order)
++              other._term_order)
+         return richcmp(lx, rx, op)
+ 
+     def _repr_(self):
+@@ -849,7 +849,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         return False
+ 
+     def term_order(self):
+-        return self.__term_order
++        return self._term_order
+ 
+     def characteristic(self):
+         """
+@@ -867,7 +867,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         return self.base_ring().characteristic()
+ 
+     def gen(self, n=0):
+-        if n < 0 or n >= self.__ngens:
++        if n < 0 or n >= self._ngens:
+             raise ValueError("Generator not defined.")
+         return self._gens[int(n)]
+ 
+@@ -927,7 +927,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         return self.base_ring().krull_dimension() + self.ngens()
+ 
+     def ngens(self):
+-        return self.__ngens
++        return self._ngens
+ 
+     def _monomial_order_function(self):
+         raise NotImplementedError
+diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pxd b/src/sage/rings/polynomial/ore_polynomial_element.pxd
+index 3a3fe0a0d54..aa36112ab90 100644
+--- a/src/sage/rings/polynomial/ore_polynomial_element.pxd
++++ b/src/sage/rings/polynomial/ore_polynomial_element.pxd
+@@ -33,7 +33,7 @@ cdef void lmul_gen(list A, Morphism m, d)
+ cdef class OrePolynomial_generic_dense(OrePolynomial):
+     cdef list _coeffs
+ 
+-    cdef void __normalize(self)
++    cdef void _normalize(self)
+     cpdef _add_(self, other)
+     cdef list _mul_list(self, list A)
+     cpdef _mul_(self, other)
+diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pyx b/src/sage/rings/polynomial/ore_polynomial_element.pyx
+index d67c63b6be8..be154ba8b1a 100644
+--- a/src/sage/rings/polynomial/ore_polynomial_element.pyx
++++ b/src/sage/rings/polynomial/ore_polynomial_element.pyx
+@@ -2269,7 +2269,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+         if isinstance(x, list):
+             if check:
+                 self._coeffs = [R(t) for t in x]
+-                self.__normalize()
++                self._normalize()
+             else:
+                 self._coeffs = x
+             return
+@@ -2288,7 +2288,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+             else:
+                 self._coeffs = [R(a, **kwds) for a in x.list()]
+                 if check:
+-                    self.__normalize()
++                    self._normalize()
+                 return
+ 
+         elif isinstance(x, int) and x == 0:
+@@ -2302,7 +2302,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+             x = [x]
+         if check:
+             self._coeffs = [R(z, **kwds) for z in x]
+-            self.__normalize()
++            self._normalize()
+         else:
+             self._coeffs = x
+ 
+@@ -2377,10 +2377,10 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+         f._parent = P
+         f._coeffs = coeffs
+         if check:
+-            f.__normalize()
++            f._normalize()
+         return f
+ 
+-    cdef void __normalize(self):
++    cdef void _normalize(self):
+         r"""
+         Remove higher order `0`-coefficients from the representation of ``self``.
+ 
+diff --git a/src/sage/rings/polynomial/pbori/pbori.pyx b/src/sage/rings/polynomial/pbori/pbori.pyx
+index 07cc696477a..314196faa14 100644
+--- a/src/sage/rings/polynomial/pbori/pbori.pyx
++++ b/src/sage/rings/polynomial/pbori/pbori.pyx
+@@ -547,7 +547,7 @@ cdef class BooleanPolynomialRing(BooleanPolynomialRing_base):
+         """
+         return tuple(new_BP_from_PBVar(self,
+                                        self._pbring.variable(self.pbind[i]))
+-                     for i in range(self.__ngens))
++                     for i in range(self._ngens))
+ 
+     def change_ring(self, base_ring=None, names=None, order=None):
+         """
+diff --git a/src/sage/rings/polynomial/plural.pxd b/src/sage/rings/polynomial/plural.pxd
+index 41db2a144e7..d3a46f6aa0d 100644
+--- a/src/sage/rings/polynomial/plural.pxd
++++ b/src/sage/rings/polynomial/plural.pxd
+@@ -13,10 +13,10 @@ cdef extern from *:
+     ctypedef long Py_hash_t
+ 
+ cdef class NCPolynomialRing_plural(Ring):
+-    cdef object __ngens
++    cdef object _ngens
+     cdef object _c
+     cdef object _d
+-    cdef object __term_order
++    cdef object _term_order
+     cdef public object _has_singular
+     cdef public object _magma_gens, _magma_cache
+ 
+diff --git a/src/sage/rings/polynomial/plural.pyx b/src/sage/rings/polynomial/plural.pyx
+index a647d68e08d..bc432611c89 100644
+--- a/src/sage/rings/polynomial/plural.pyx
++++ b/src/sage/rings/polynomial/plural.pyx
+@@ -336,8 +336,8 @@ cdef class NCPolynomialRing_plural(Ring):
+         self._ring = singular_ring_reference(rw._ring)
+         self._ring.ShortOut = 0
+ 
+-        self.__ngens = n
+-        self.__term_order = order
++        self._ngens = n
++        self._term_order = order
+ 
+         Ring.__init__(self, base_ring, names, category=category)
+         self._populate_coercion_lists_()
+@@ -673,7 +673,7 @@ cdef class NCPolynomialRing_plural(Ring):
+             sage: P.term_order()
+             Degree reverse lexicographic term order
+         """
+-        return self.__term_order
++        return self._term_order
+ 
+     def is_commutative(self):
+         """
+@@ -727,7 +727,7 @@ cdef class NCPolynomialRing_plural(Ring):
+         from sage.repl.rich_output.backend_base import BackendBase
+         from sage.repl.display.pretty_print import SagePrettyPrinter
+         varstr = ", ".join(char_to_str(rRingVar(i, self._ring))
+-                           for i in range(self.__ngens))
++                           for i in range(self._ngens))
+         backend = BackendBase()
+         relations = backend._apply_pretty_printer(SagePrettyPrinter,
+                                                   self.relations())
+@@ -830,7 +830,7 @@ cdef class NCPolynomialRing_plural(Ring):
+             sage: P.ngens()
+             3
+         """
+-        return int(self.__ngens)
++        return int(self._ngens)
+ 
+     def gen(self, int n=0):
+         """
+@@ -857,7 +857,7 @@ cdef class NCPolynomialRing_plural(Ring):
+         cdef poly *_p
+         cdef ring *_ring = self._ring
+ 
+-        if n < 0 or n >= self.__ngens:
++        if n < 0 or n >= self._ngens:
+             raise ValueError("Generator not defined.")
+ 
+         rChangeCurrRing(_ring)
+@@ -2352,7 +2352,7 @@ cdef class NCPolynomial_plural(RingElement):
+             except TypeError:
+                 x = (x,)
+ 
+-        if len(x) != (<NCPolynomialRing_plural>self._parent).__ngens:
++        if len(x) != (<NCPolynomialRing_plural>self._parent)._ngens:
+             raise TypeError("x must have length self.ngens()")
+ 
+         m = p_ISet(1,r)
+@@ -2890,8 +2890,8 @@ cpdef MPolynomialRing_libsingular new_CRing(RingWrap rw, base_ring):
+ 
+     self._ring.ShortOut = 0
+ 
+-    self.__ngens = rw.ngens()
+-    self.__term_order =  TermOrder(rw.ordering_string(), force=True)
++    self._ngens = rw.ngens()
++    self._term_order =  TermOrder(rw.ordering_string(), force=True)
+ 
+     ParentWithGens.__init__(self, base_ring, tuple(rw.var_names()),
+                             normalize=False)
+@@ -2962,8 +2962,8 @@ cpdef NCPolynomialRing_plural new_NRing(RingWrap rw, base_ring):
+ 
+     self._ring.ShortOut = 0
+ 
+-    self.__ngens = rw.ngens()
+-    self.__term_order =  TermOrder(rw.ordering_string(), force=True)
++    self._ngens = rw.ngens()
++    self._term_order =  TermOrder(rw.ordering_string(), force=True)
+ 
+     ParentWithGens.__init__(self, base_ring, rw.var_names())
+ #    self._populate_coercion_lists_()  # ???
+diff --git a/src/sage/rings/polynomial/polynomial_complex_arb.pxd b/src/sage/rings/polynomial/polynomial_complex_arb.pxd
+index aa4e2a1c0dc..e54d85e961b 100644
+--- a/src/sage/rings/polynomial/polynomial_complex_arb.pxd
++++ b/src/sage/rings/polynomial/polynomial_complex_arb.pxd
+@@ -2,5 +2,5 @@ from sage.libs.arb.acb_poly cimport *
+ from sage.rings.polynomial.polynomial_element cimport Polynomial
+ 
+ cdef class Polynomial_complex_arb(Polynomial):
+-    cdef acb_poly_struct[1] __poly # https://github.com/cython/cython/issues/1984
++    cdef acb_poly_struct[1] _poly # https://github.com/cython/cython/issues/1984
+     cdef Polynomial_complex_arb _new(self)
+diff --git a/src/sage/rings/polynomial/polynomial_complex_arb.pyx b/src/sage/rings/polynomial/polynomial_complex_arb.pyx
+index e51268b4b54..57c1a52ede4 100644
+--- a/src/sage/rings/polynomial/polynomial_complex_arb.pyx
++++ b/src/sage/rings/polynomial/polynomial_complex_arb.pyx
+@@ -75,7 +75,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: ComplexBallField(2)['y']()
+             0
+         """
+-        acb_poly_init(self.__poly)
++        acb_poly_init(self._poly)
+ 
+     def __dealloc__(self):
+         r"""
+@@ -84,7 +84,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: pol = CBF['x']()
+             sage: del pol
+         """
+-        acb_poly_clear(self.__poly)
++        acb_poly_clear(self._poly)
+ 
+     cdef Polynomial_complex_arb _new(self):
+         r"""
+@@ -140,49 +140,49 @@ cdef class Polynomial_complex_arb(Polynomial):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+ 
+         if is_gen:
+-            acb_poly_set_coeff_si(self.__poly, 1, 1)
++            acb_poly_set_coeff_si(self._poly, 1, 1)
+         elif x is None:
+-            acb_poly_zero(self.__poly)
++            acb_poly_zero(self._poly)
+         elif isinstance(x, Polynomial_complex_arb):
+-            acb_poly_set(self.__poly, (<Polynomial_complex_arb> x).__poly)
++            acb_poly_set(self._poly, (<Polynomial_complex_arb> x)._poly)
+         elif isinstance(x, ComplexBall):
+-            acb_poly_set_coeff_acb(self.__poly, 0, (<ComplexBall> x).value)
++            acb_poly_set_coeff_acb(self._poly, 0, (<ComplexBall> x).value)
+         else:
+             Coeff = parent.base_ring()
+             if isinstance(x, list):
+                 lst = <list> x
+                 length = len(lst)
+-                sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                 for i in range(length):
+                     ball = Coeff(lst[i])
+-                    acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                    acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             elif isinstance(x, tuple):
+                 tpl = <tuple> x
+                 length = len(tpl)
+-                sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                 for i in range(length):
+                     ball = Coeff(tpl[i])
+-                    acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                    acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             elif isinstance(x, Polynomial):
+                 pol = <Polynomial> x
+                 length = pol.degree() + 1
+-                sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                 for i in range(length):
+                     ball = Coeff(pol.get_unsafe(i))
+-                    acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                    acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             elif isinstance(x, dict):
+                 dct = <dict> x
+                 if len(dct) == 0:
+-                    acb_poly_zero(self.__poly)
++                    acb_poly_zero(self._poly)
+                 else:
+                     length = max(int(i) for i in dct) + 1
+-                    sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                    sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                     for i, c in dct.iteritems():
+                         ball = Coeff(c)
+-                        acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                        acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             else:
+                 ball = Coeff(x)
+-                acb_poly_set_coeff_acb(self.__poly, 0, ball.value)
++                acb_poly_set_coeff_acb(self._poly, 0, ball.value)
+ 
+     def __reduce__(self):
+         r"""
+@@ -219,12 +219,12 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: Pol([1, 0, 0, 0]).degree()
+             0
+         """
+-        return smallInteger(acb_poly_degree(self.__poly))
++        return smallInteger(acb_poly_degree(self._poly))
+ 
+     cdef get_unsafe(self, Py_ssize_t n):
+         cdef ComplexBall res = ComplexBall.__new__(ComplexBall)
+         res._parent = self._parent._base
+-        acb_poly_get_coeff_acb(res.value, self.__poly, n)
++        acb_poly_get_coeff_acb(res.value, self._poly, n)
+         return res
+ 
+     cpdef list list(self, bint copy=True):
+@@ -241,7 +241,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: Pol([0, 1, RBF(0, rad=.1), 0]).list()
+             [0, 1.000000000000000, [+/- 0.101]]
+         """
+-        cdef unsigned long length = acb_poly_length(self.__poly)
++        cdef unsigned long length = acb_poly_length(self._poly)
+         return [self.get_unsafe(n) for n in range(length)]
+ 
+     def __bool__(self):
+@@ -257,7 +257,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: bool(z)
+             True
+         """
+-        return acb_poly_length(self.__poly)
++        return acb_poly_length(self._poly)
+ 
+     # Ring and Euclidean arithmetic
+ 
+@@ -274,9 +274,9 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+         acb_poly_add(
+-                res.__poly,
+-                self.__poly,
+-                (<Polynomial_complex_arb> other).__poly,
++                res._poly,
++                self._poly,
++                (<Polynomial_complex_arb> other)._poly,
+                 prec(self))
+         sig_off()
+         return res
+@@ -293,7 +293,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         """
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_neg(res.__poly, self.__poly)
++        acb_poly_neg(res._poly, self._poly)
+         sig_off()
+         return res
+ 
+@@ -310,9 +310,9 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+         acb_poly_sub(
+-                res.__poly,
+-                self.__poly,
+-                (<Polynomial_complex_arb> other).__poly,
++                res._poly,
++                self._poly,
++                (<Polynomial_complex_arb> other)._poly,
+                 prec(self))
+         sig_off()
+         return res
+@@ -331,9 +331,9 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+         acb_poly_mul(
+-                res.__poly,
+-                self.__poly,
+-                (<Polynomial_complex_arb> other).__poly,
++                res._poly,
++                self._poly,
++                (<Polynomial_complex_arb> other)._poly,
+                 prec(self))
+         sig_off()
+         return res
+@@ -354,7 +354,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         """
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_scalar_mul(res.__poly, self.__poly, (<ComplexBall> a).value, prec(self))
++        acb_poly_scalar_mul(res._poly, self._poly, (<ComplexBall> a).value, prec(self))
+         sig_off()
+         return res
+ 
+@@ -409,8 +409,8 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb quo = self._new()
+         cdef Polynomial_complex_arb rem = self._new()
+         sig_on()
+-        cdef bint success = acb_poly_divrem(quo.__poly, rem.__poly, self.__poly,
+-                div.__poly, prec(self))
++        cdef bint success = acb_poly_divrem(quo._poly, rem._poly, self._poly,
++                div._poly, prec(self))
+         sig_off()
+         if success:
+             return quo, rem
+@@ -445,15 +445,15 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_set(res.__poly, self.__poly)
+-        acb_poly_truncate(res.__poly, n)
++        acb_poly_set(res._poly, self._poly)
++        acb_poly_truncate(res._poly, n)
+         sig_off()
+         return res
+ 
+     cdef _inplace_truncate(self, long n):
+         if n < 0:
+             n = 0
+-        acb_poly_truncate(self.__poly, n)
++        acb_poly_truncate(self._poly, n)
+         return self
+ 
+     def __lshift__(val, n):
+@@ -485,7 +485,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb self = (<Polynomial_complex_arb> val)
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_shift_left(res.__poly, self.__poly, n)
++        acb_poly_shift_left(res._poly, self._poly, n)
+         sig_off()
+         return res
+ 
+@@ -518,7 +518,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb self = (<Polynomial_complex_arb> val)
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_shift_right(res.__poly, self.__poly, n)
++        acb_poly_shift_right(res._poly, self._poly, n)
+         sig_off()
+         return res
+ 
+@@ -548,7 +548,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_mullow(res.__poly, self.__poly, my_other.__poly, n, prec(self))
++        acb_poly_mullow(res._poly, self._poly, my_other._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -576,7 +576,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_inv_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_inv_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -612,7 +612,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_pow_ui_trunc_binexp(res.__poly, self.__poly, expo, n, prec(self))
++        acb_poly_pow_ui_trunc_binexp(res._poly, self._poly, expo, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -648,7 +648,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_log_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_log_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -672,7 +672,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_exp_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_exp_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -697,7 +697,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_sqrt_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_sqrt_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -716,7 +716,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_gamma_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_gamma_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -735,7 +735,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_lgamma_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_lgamma_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -754,7 +754,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_rgamma_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_rgamma_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -784,7 +784,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_lambertw_series(res.__poly, self.__poly, _branch, 0, n, prec(self))
++        acb_poly_lambertw_series(res._poly, self._poly, _branch, 0, n, prec(self))
+         sig_off()
+         fmpz_clear(_branch)
+         return res
+@@ -814,7 +814,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef ComplexBall _a = <ComplexBall> (self._parent._base.coerce(a))
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_zeta_series(res.__poly, self.__poly, _a.value, deflate, n, prec(self))
++        acb_poly_zeta_series(res._poly, self._poly, _a.value, deflate, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -846,24 +846,24 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         cdef acb_poly_t self_ts, other_ts
+         cdef acb_ptr cc
+-        if acb_poly_length(other1.__poly) > 0:
+-            cc = acb_poly_get_coeff_ptr(other1.__poly, 0)
++        if acb_poly_length(other1._poly) > 0:
++            cc = acb_poly_get_coeff_ptr(other1._poly, 0)
+             if not acb_is_zero(cc):
+                 sig_on()
+                 try:
+                     acb_poly_init(self_ts)
+                     acb_poly_init(other_ts)
+-                    acb_poly_taylor_shift(self_ts, self.__poly, cc, prec(self))
+-                    acb_poly_set(other_ts, other1.__poly)
++                    acb_poly_taylor_shift(self_ts, self._poly, cc, prec(self))
++                    acb_poly_set(other_ts, other1._poly)
+                     acb_zero(acb_poly_get_coeff_ptr(other_ts, 0))
+-                    acb_poly_compose_series(res.__poly, self_ts, other_ts, n, prec(self))
++                    acb_poly_compose_series(res._poly, self_ts, other_ts, n, prec(self))
+                 finally:
+                     acb_poly_clear(other_ts)
+                     acb_poly_clear(self_ts)
+                     sig_off()
+                 return res
+         sig_on()
+-        acb_poly_compose_series(res.__poly, self.__poly, other1.__poly, n, prec(self))
++        acb_poly_compose_series(res._poly, self._poly, other1._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -895,12 +895,12 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         if n < 0:
+             n = 0
+-        if not acb_is_zero(acb_poly_get_coeff_ptr(self.__poly, 0)):
++        if not acb_is_zero(acb_poly_get_coeff_ptr(self._poly, 0)):
+             raise ValueError("the constant coefficient must be zero")
+-        if acb_contains_zero(acb_poly_get_coeff_ptr(self.__poly, 1)):
++        if acb_contains_zero(acb_poly_get_coeff_ptr(self._poly, 1)):
+             raise ValueError("the linear term must be nonzero")
+         sig_on()
+-        acb_poly_revert_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_revert_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -938,15 +938,15 @@ cdef class Polynomial_complex_arb(Polynomial):
+                 ball = ComplexBall.__new__(ComplexBall)
+                 ball._parent = self._parent._base
+                 sig_on()
+-                acb_poly_evaluate(ball.value, self.__poly,
++                acb_poly_evaluate(ball.value, self._poly,
+                         (<ComplexBall> point).value, prec(self))
+                 sig_off()
+                 return ball
+             elif isinstance(point, Polynomial_complex_arb):
+                 poly = (<Polynomial_complex_arb> point)._new()
+                 sig_on()
+-                acb_poly_compose(poly.__poly, self.__poly,
+-                        (<Polynomial_complex_arb> point).__poly, prec(self))
++                acb_poly_compose(poly._poly, self._poly,
++                        (<Polynomial_complex_arb> point)._poly, prec(self))
+                 sig_off()
+                 return poly
+             # TODO: perhaps add more special cases, e.g. for real ball,
+diff --git a/src/sage/rings/polynomial/polynomial_element.pxd b/src/sage/rings/polynomial/polynomial_element.pxd
+index 083f506b222..5dcbf4597d0 100644
+--- a/src/sage/rings/polynomial/polynomial_element.pxd
++++ b/src/sage/rings/polynomial/polynomial_element.pxd
+@@ -45,12 +45,12 @@ cdef class Polynomial(CommutativePolynomial):
+     cpdef _mul_(self, right)
+     cpdef _floordiv_(self, right)
+ 
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+ cdef class Polynomial_generic_dense(Polynomial):
+     cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P)
+-    cdef list __coeffs
+-    cdef int __normalize(self) except -1
++    cdef list _coeffs
++    cdef int _normalize(self) except -1
+     cpdef list list(self, bint copy=*)
+ 
+ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+diff --git a/src/sage/rings/polynomial/polynomial_element.pyx b/src/sage/rings/polynomial/polynomial_element.pyx
+index 4d4b9dd10f5..d1c802835ae 100644
+--- a/src/sage/rings/polynomial/polynomial_element.pyx
++++ b/src/sage/rings/polynomial/polynomial_element.pyx
+@@ -9800,7 +9800,7 @@ cdef class Polynomial(CommutativePolynomial):
+             0
+         """
+         # __getitem__ already returns a polynomial!!
+-        # We must not have check=False, since 0 must not have __coeffs = [0].
++        # We must not have check=False, since 0 must not have _coeffs = [0].
+         return <Polynomial>self._parent(self[:n])#, check=False)
+ 
+     cdef _inplace_truncate(self, long prec):
+@@ -11541,16 +11541,16 @@ cdef class Polynomial_generic_dense(Polynomial):
+     def __init__(self, parent, x=None, int check=1, is_gen=False, int construct=0, **kwds):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+         if x is None:
+-            self.__coeffs = []
++            self._coeffs = []
+             return
+ 
+         R = parent.base_ring()
+         if isinstance(x, (list, tuple)):
+             if check:
+-                self.__coeffs = [R(t) for t in x]
+-                self.__normalize()
++                self._coeffs = [R(t) for t in x]
++                self._normalize()
+             else:
+-                self.__coeffs = x
++                self._coeffs = x
+             return
+ 
+         if sage.rings.fraction_field_element.is_FractionFieldElement(x):
+@@ -11565,19 +11565,19 @@ cdef class Polynomial_generic_dense(Polynomial):
+             elif R.has_coerce_map_from((<Element>x)._parent):# is R or (<Element>x)._parent == R:
+                 try:
+                     if x.is_zero():
+-                        self.__coeffs = []
++                        self._coeffs = []
+                         return
+                 except (AttributeError, TypeError):
+                     pass
+                 x = [x]
+             else:
+-                self.__coeffs = [R(a, **kwds) for a in x.list(copy=False)]
++                self._coeffs = [R(a, **kwds) for a in x.list(copy=False)]
+                 if check:
+-                    self.__normalize()
++                    self._normalize()
+                 return
+ 
+         elif isinstance(x, int) and x == 0:
+-            self.__coeffs = []
++            self._coeffs = []
+             return
+ 
+         elif isinstance(x, dict):
+@@ -11593,16 +11593,16 @@ cdef class Polynomial_generic_dense(Polynomial):
+ #            else:
+ #                x = []    # zero polynomial
+         if check:
+-            self.__coeffs = [R(z, **kwds) for z in x]
+-            self.__normalize()
++            self._coeffs = [R(z, **kwds) for z in x]
++            self._normalize()
+         else:
+-            self.__coeffs = x
++            self._coeffs = x
+ 
+     cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P):
+         cdef type t = type(self)
+         cdef Polynomial_generic_dense f = <Polynomial_generic_dense>t.__new__(t)
+         f._parent = P
+-        f.__coeffs = coeffs
++        f._coeffs = coeffs
+         return f
+ 
+     cpdef Polynomial _new_constant_poly(self, a, Parent P):
+@@ -11644,10 +11644,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: type(f)
+             <class 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense'>
+         """
+-        return make_generic_polynomial, (self._parent, self.__coeffs)
++        return make_generic_polynomial, (self._parent, self._coeffs)
+ 
+     def __bool__(self):
+-        return bool(self.__coeffs)
++        return bool(self._coeffs)
+ 
+     cpdef bint is_term(self) except -1:
+         """
+@@ -11667,10 +11667,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: (1 + 3*x^5).is_term()
+             False
+         """
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return False
+ 
+-        for c in self.__coeffs[:-1]:
++        for c in self._coeffs[:-1]:
+             if c:
+                 return False
+         return True
+@@ -11682,9 +11682,9 @@ cdef class Polynomial_generic_dense(Polynomial):
+         Return the product ``self * term``, where ``term`` is a polynomial
+         with a single term.
+         """
+-        cdef Py_ssize_t d = len( (<Polynomial_generic_dense> term).__coeffs ) - 1
++        cdef Py_ssize_t d = len( (<Polynomial_generic_dense> term)._coeffs ) - 1
+         cdef Py_ssize_t i
+-        cdef list x = self.__coeffs
++        cdef list x = self._coeffs
+         cdef Py_ssize_t ell = len(x)
+         c = term.get_unsafe(d)
+         cdef list v = [self.base_ring().zero()] * (d + ell)
+@@ -11697,10 +11697,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+         cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
+         #if not v[len(v)-1]:
+         # "normalize" checks this anyway...
+-        res.__normalize()
++        res._normalize()
+         return res
+ 
+-    cdef int __normalize(self) except -1:
++    cdef int _normalize(self) except -1:
+         """
+         TESTS:
+ 
+@@ -11718,7 +11718,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+             ...
+             NotImplementedError: cannot check whether number is non-zero
+         """
+-        cdef list x = self.__coeffs
++        cdef list x = self._coeffs
+         cdef Py_ssize_t n = len(x) - 1
+         while n >= 0 and not x[n]:
+             del x[n]
+@@ -11747,7 +11747,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: f[:3]
+             40.0*x^2 + 10.0*x + 1.0
+         """
+-        return self.__coeffs[n]
++        return self._coeffs[n]
+ 
+     def _unsafe_mutate(self, n, value):
+         """
+@@ -11770,17 +11770,17 @@ cdef class Polynomial_generic_dense(Polynomial):
+         """
+         n = int(n)
+         value = self.base_ring()(value)
+-        if n >= 0 and n < len(self.__coeffs):
+-            self.__coeffs[n] = value
+-            if n == len(self.__coeffs) and value == 0:
+-                self.__normalize()
++        if n >= 0 and n < len(self._coeffs):
++            self._coeffs[n] = value
++            if n == len(self._coeffs) and value == 0:
++                self._normalize()
+         elif n < 0:
+             raise IndexError("polynomial coefficient index must be nonnegative")
+         elif value != 0:
+             zero = self.base_ring().zero()
+-            for _ in range(len(self.__coeffs), n):
+-                self.__coeffs.append(zero)
+-            self.__coeffs.append(value)
++            for _ in range(len(self._coeffs), n):
++                self._coeffs.append(zero)
++            self._coeffs.append(value)
+ 
+     def __floordiv__(self, right):
+         """
+@@ -11822,8 +11822,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+             return (<Polynomial_generic_dense>self)._floordiv_(<Polynomial_generic_dense>right)
+         P = parent(self)
+         d = P.base_ring()(right)
+-        cdef Polynomial_generic_dense res = (<Polynomial_generic_dense>self)._new_c([c // d for c in (<Polynomial_generic_dense>self).__coeffs], P)
+-        res.__normalize()
++        cdef Polynomial_generic_dense res = (<Polynomial_generic_dense>self)._new_c([c // d for c in (<Polynomial_generic_dense>self)._coeffs], P)
++        res._normalize()
+         return res
+ 
+     cpdef _add_(self, right):
+@@ -11839,8 +11839,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+         """
+         cdef Polynomial_generic_dense res
+         cdef Py_ssize_t check=0, i, min
+-        x = (<Polynomial_generic_dense>self).__coeffs
+-        y = (<Polynomial_generic_dense>right).__coeffs
++        x = (<Polynomial_generic_dense>self)._coeffs
++        y = (<Polynomial_generic_dense>right)._coeffs
+         if len(x) > len(y):
+             min = len(y)
+             high = x[min:]
+@@ -11852,7 +11852,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+         cdef list low = [x[i] + y[i] for i from 0 <= i < min]
+         if len(x) == len(y):
+             res = self._new_c(low, self._parent)
+-            res.__normalize()
++            res._normalize()
+             return res
+         else:
+             return self._new_c(low + high, self._parent)
+@@ -11860,8 +11860,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+     cpdef _sub_(self, right):
+         cdef Polynomial_generic_dense res
+         cdef Py_ssize_t check=0, i, min
+-        x = (<Polynomial_generic_dense>self).__coeffs
+-        y = (<Polynomial_generic_dense>right).__coeffs
++        x = (<Polynomial_generic_dense>self)._coeffs
++        y = (<Polynomial_generic_dense>right)._coeffs
+         if len(x) > len(y):
+             min = len(y)
+             high = x[min:]
+@@ -11873,33 +11873,33 @@ cdef class Polynomial_generic_dense(Polynomial):
+         low = [x[i] - y[i] for i from 0 <= i < min]
+         if len(x) == len(y):
+             res = self._new_c(low, self._parent)
+-            res.__normalize()
++            res._normalize()
+             return res
+         else:
+             return self._new_c(low + high, self._parent)
+ 
+     cpdef _rmul_(self, Element c):
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return self
+-        if c._parent is not (<Element>self.__coeffs[0])._parent:
+-            c = (<Element>self.__coeffs[0])._parent.coerce(c)
+-        v = [c * a for a in self.__coeffs]
++        if c._parent is not (<Element>self._coeffs[0])._parent:
++            c = (<Element>self._coeffs[0])._parent.coerce(c)
++        v = [c * a for a in self._coeffs]
+         cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
+         #if not v[len(v)-1]:
+         # "normalize" checks this anyway...
+-        res.__normalize()
++        res._normalize()
+         return res
+ 
+     cpdef _lmul_(self, Element c):
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return self
+-        if c._parent is not (<Element>self.__coeffs[0])._parent:
+-            c = (<Element>self.__coeffs[0])._parent.coerce(c)
+-        v = [a * c for a in self.__coeffs]
++        if c._parent is not (<Element>self._coeffs[0])._parent:
++            c = (<Element>self._coeffs[0])._parent.coerce(c)
++        v = [a * c for a in self._coeffs]
+         cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
+         #if not v[len(v)-1]:
+         # "normalize" checks this anyway...
+-        res.__normalize()
++        res._normalize()
+         return res
+ 
+     cpdef constant_coefficient(self):
+@@ -11916,10 +11916,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: f.constant_coefficient()
+             t
+         """
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return self.base_ring().zero()
+         else:
+-            return self.__coeffs[0]
++            return self._coeffs[0]
+ 
+     cpdef list list(self, bint copy=True):
+         """
+@@ -11934,9 +11934,9 @@ cdef class Polynomial_generic_dense(Polynomial):
+             [1, 9, 12, 8]
+         """
+         if copy:
+-            return list(self.__coeffs)
++            return list(self._coeffs)
+         else:
+-            return self.__coeffs
++            return self._coeffs
+ 
+     def degree(self, gen=None):
+         """
+@@ -11955,7 +11955,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+             <class 'sage.rings.integer.Integer'>
+ 
+         """
+-        return smallInteger(len(self.__coeffs) - 1)
++        return smallInteger(len(self._coeffs) - 1)
+ 
+     def shift(self, Py_ssize_t n):
+         r"""
+@@ -11993,13 +11993,13 @@ cdef class Polynomial_generic_dense(Polynomial):
+             return self
+         if n > 0:
+             output = [self.base_ring().zero()] * n
+-            output.extend(self.__coeffs)
++            output.extend(self._coeffs)
+             return self._new_c(output, self._parent)
+         if n < 0:
+-            if n > len(self.__coeffs) - 1:
++            if n > len(self._coeffs) - 1:
+                 return self._parent([])
+             else:
+-                return self._new_c(self.__coeffs[-int(n):], self._parent)
++                return self._new_c(self._coeffs[-int(n):], self._parent)
+ 
+     @coerce_binop
+     def quo_rem(self, other):
+@@ -12073,8 +12073,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+             return self, self
+ 
+         R = self._parent.base_ring()
+-        cdef list x = list((<Polynomial_generic_dense>self).__coeffs) # make a copy
+-        cdef list y = (<Polynomial_generic_dense>other).__coeffs
++        cdef list x = list((<Polynomial_generic_dense>self)._coeffs) # make a copy
++        cdef list y = (<Polynomial_generic_dense>other)._coeffs
+         cdef Py_ssize_t m = len(x)  # deg(self)=m-1
+         cdef Py_ssize_t n = len(y)  # deg(other)=n-1
+         if m < n:
+@@ -12135,18 +12135,18 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: type(f)
+             <class 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense'>
+         """
+-        l = len(self.__coeffs)
++        l = len(self._coeffs)
+         if n > l:
+             n = l
+-        while n > 0 and not self.__coeffs[n-1]:
++        while n > 0 and not self._coeffs[n-1]:
+             n -= 1
+-        return self._new_c(self.__coeffs[:n], self._parent)
++        return self._new_c(self._coeffs[:n], self._parent)
+ 
+     cdef _inplace_truncate(self, long n):
+-        if n < len(self.__coeffs):
+-            while n > 0 and not self.__coeffs[n-1]:
++        if n < len(self._coeffs):
++            while n > 0 and not self._coeffs[n-1]:
+                 n -= 1
+-        self.__coeffs = self.__coeffs[:n]
++        self._coeffs = self._coeffs[:n]
+         return self
+ 
+ def make_generic_polynomial(parent, coeffs):
+@@ -12305,7 +12305,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+ 
+     - Xavier Caruso (2013-03)
+     """
+-    cdef int __normalize(self) except -1:
++    cdef int _normalize(self) except -1:
+         r"""
+         TESTS::
+ 
+@@ -12316,7 +12316,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+             sage: S([1, R(0, 20)])                                                      # needs sage.rings.padics
+             O(5^20)*x + 1 + O(5^20)
+         """
+-        cdef list x = self.__coeffs
++        cdef list x = self._coeffs
+         cdef Py_ssize_t n = len(x) - 1
+         cdef RingElement c
+         while n >= 0:
+@@ -12376,7 +12376,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+ 
+         - Xavier Caruso (2013-03)
+         """
+-        coeffs = self.__coeffs
++        coeffs = self._coeffs
+         d = len(coeffs) - 1
+         while d >= 0:
+             c = coeffs[d]
+@@ -12420,7 +12420,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+ 
+         - Xavier Caruso (2013-03)
+         """
+-        return len(self.__coeffs) - 1
++        return len(self._coeffs) - 1
+ 
+ 
+ cdef class ConstantPolynomialSection(Map):
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd
+index 03c5cebbf09..b1b593d6a26 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd
+@@ -5,7 +5,7 @@ from sage.rings.integer cimport Integer
+ from sage.structure.parent cimport Parent
+ 
+ cdef class Polynomial_integer_dense_flint(Polynomial):
+-    cdef fmpz_poly_t __poly
++    cdef fmpz_poly_t _poly
+ 
+     cdef Polynomial_integer_dense_flint _new(self)
+     cpdef _unsafe_mutate(self, long n, value)
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx
+index e201ac843ad..194eb9263b2 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx
+@@ -99,14 +99,14 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         r"""
+         This calls the underlying FLINT fmpz_poly constructor
+         """
+-        fmpz_poly_init(self.__poly)
++        fmpz_poly_init(self._poly)
+ 
+ 
+     def __dealloc__(self):
+         r"""
+         calls the underlying FLINT fmpz_poly destructor
+         """
+-        fmpz_poly_clear(self.__poly)
++        fmpz_poly_clear(self._poly)
+ 
+     cdef Polynomial_integer_dense_flint _new(self):
+         r"""
+@@ -139,7 +139,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         x._is_gen = 0
+         if not isinstance(a, Integer):
+             a = ZZ(a)
+-        fmpz_poly_set_coeff_mpz(x.__poly, 0, (<Integer>a).value)
++        fmpz_poly_set_coeff_mpz(x._poly, 0, (<Integer>a).value)
+         return x
+ 
+     def __init__(self, parent, x=None, check=True, is_gen=False,
+@@ -224,8 +224,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         if isinstance(x, Polynomial):
+             if x.parent() is self.parent():
+                 sig_on()
+-                fmpz_poly_set(self.__poly,
+-                              (<Polynomial_integer_dense_flint>x).__poly)
++                fmpz_poly_set(self._poly,
++                              (<Polynomial_integer_dense_flint>x)._poly)
+                 sig_off()
+                 return
+             else:
+@@ -246,7 +246,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                     degree = i
+             try:
+                 sig_on()
+-                fmpz_poly_realloc(self.__poly, degree + 1)
++                fmpz_poly_realloc(self._poly, degree + 1)
+                 sig_off()
+             except RuntimeError:
+                 raise OverflowError("Cannot allocate memory!")
+@@ -255,13 +255,13 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 i = ii[0] if type(ii) is tuple else ii
+                 if is_small_python_int(a):
+                     sig_on()
+-                    fmpz_poly_set_coeff_si(self.__poly, i, a)
++                    fmpz_poly_set_coeff_si(self._poly, i, a)
+                     sig_off()
+                 else:
+                     if not isinstance(a, Integer):
+                         a = ZZ(a)
+                     sig_on()
+-                    fmpz_poly_set_coeff_mpz(self.__poly, i, (<Integer>a).value)
++                    fmpz_poly_set_coeff_mpz(self._poly, i, (<Integer>a).value)
+                     sig_off()
+             return
+ 
+@@ -270,7 +270,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             check = False
+ 
+         elif isinstance(x, ntl_ZZX):    # coercion from ntl.pyx object
+-            fmpz_poly_set_ZZX(self.__poly, (<ntl_ZZX>x).x)
++            fmpz_poly_set_ZZX(self._poly, (<ntl_ZZX>x).x)
+             return
+ 
+         elif isinstance(x, FractionFieldElement) and \
+@@ -278,8 +278,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if x.denominator() == 1:
+                 # fraction of the form f(x)/1
+                 sig_on()
+-                fmpz_poly_set(self.__poly,
+-                        (<Polynomial_integer_dense_flint>x.numerator()).__poly)
++                fmpz_poly_set(self._poly,
++                        (<Polynomial_integer_dense_flint>x.numerator())._poly)
+                 sig_off()
+                 return
+ 
+@@ -287,19 +287,19 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             x = [x]   # constant polynomials
+ 
+         sig_on()
+-        fmpz_poly_realloc(self.__poly, len(x))
++        fmpz_poly_realloc(self._poly, len(x))
+         sig_off()
+         for i from 0 <= i < len(x):
+             a = x[i]
+             if is_small_python_int(a):
+                 sig_on()
+-                fmpz_poly_set_coeff_si(self.__poly, i, a)
++                fmpz_poly_set_coeff_si(self._poly, i, a)
+                 sig_off()
+             else:
+                 if not isinstance(a, Integer):
+                     a = ZZ(a)
+                 sig_on()
+-                fmpz_poly_set_coeff_mpz(self.__poly, i, (<Integer>a).value)
++                fmpz_poly_set_coeff_mpz(self._poly, i, (<Integer>a).value)
+                 sig_off()
+ 
+     def _eval_mpfr_(self, RealNumber a):
+@@ -327,7 +327,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef RealNumber res = a._new()
+         sig_on()
+-        fmpz_poly_evaluation_mpfr(res.value, self.__poly, a.value)
++        fmpz_poly_evaluation_mpfr(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -357,7 +357,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef RealIntervalFieldElement res = a._new()
+         sig_on()
+-        fmpz_poly_evaluation_mpfi(res.value, self.__poly, a.value)
++        fmpz_poly_evaluation_mpfi(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -412,8 +412,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if isinstance(x, Polynomial_integer_dense_flint):
+                 f = self._new()
+                 sig_on()
+-                fmpz_poly_compose(f.__poly, self.__poly,
+-                                  (<Polynomial_integer_dense_flint> x0).__poly)
++                fmpz_poly_compose(f._poly, self._poly,
++                                  (<Polynomial_integer_dense_flint> x0)._poly)
+                 sig_off()
+                 return f
+             if is_small_python_int(x0):
+@@ -422,7 +422,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 fmpz_init(a_fmpz)
+                 fmpz_init(z_fmpz)
+                 fmpz_set_si(a_fmpz, PyInt_AS_LONG(x0))
+-                fmpz_poly_evaluate_fmpz(z_fmpz, self.__poly, a_fmpz)
++                fmpz_poly_evaluate_fmpz(z_fmpz, self._poly, a_fmpz)
+                 fmpz_get_mpz(z.value, z_fmpz)
+                 fmpz_clear(a_fmpz)
+                 fmpz_clear(z_fmpz)
+@@ -433,7 +433,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if isinstance(x0, Integer):
+                 a = <Integer> x0
+ 
+-                if fmpz_poly_length(self.__poly) == 0:
++                if fmpz_poly_length(self._poly) == 0:
+                     return ZZ.zero()
+                 if mpz_sgn(a.value) == 0:
+                     return self[0]
+@@ -444,7 +444,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 fmpz_init(a_fmpz)
+                 fmpz_init(z_fmpz)
+                 fmpz_set_mpz(a_fmpz, a.value)
+-                fmpz_poly_evaluate_fmpz(z_fmpz, self.__poly, a_fmpz)
++                fmpz_poly_evaluate_fmpz(z_fmpz, self._poly, a_fmpz)
+                 fmpz_get_mpz(z.value, z_fmpz)
+                 fmpz_clear(a_fmpz)
+                 fmpz_clear(z_fmpz)
+@@ -460,14 +460,14 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 arb_a = <RealBall> x0
+                 arb_z = arb_a._new()
+                 sig_on()
+-                arb_fmpz_poly_evaluate_arb(arb_z.value, self.__poly, arb_a.value, arb_a._parent._prec)
++                arb_fmpz_poly_evaluate_arb(arb_z.value, self._poly, arb_a.value, arb_a._parent._prec)
+                 sig_off()
+                 return arb_z
+             if isinstance(x0, ComplexBall):
+                 acb_a = <ComplexBall> x0
+                 acb_z = acb_a._new()
+                 sig_on()
+-                arb_fmpz_poly_evaluate_acb(acb_z.value, self.__poly, acb_a.value, acb_a._parent._prec)
++                arb_fmpz_poly_evaluate_acb(acb_z.value, self._poly, acb_a.value, acb_a._parent._prec)
+                 sig_off()
+                 return acb_z
+ 
+@@ -510,10 +510,10 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+         cdef fmpz_t c
+         fmpz_init(c)
+-        fmpz_poly_get_coeff_fmpz(c, self.__poly, fmpz_poly_degree(self.__poly))
++        fmpz_poly_get_coeff_fmpz(c, self._poly, fmpz_poly_degree(self._poly))
+         cdef int sign = fmpz_sgn(c)
+ 
+-        fmpz_poly_content(c, self.__poly)
++        fmpz_poly_content(c, self._poly)
+ 
+         cdef Integer z = Integer.__new__(Integer)
+         fmpz_get_mpz(z.value, c)
+@@ -561,7 +561,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             5*x^5 + 4*x^4 + 3*x^3 + 2*x^2 + x + 1
+         """
+         cdef Integer z = Integer.__new__(Integer)
+-        fmpz_poly_get_coeff_mpz(z.value, self.__poly, n)
++        fmpz_poly_get_coeff_mpz(z.value, self._poly, n)
+         return z
+ 
+     def _repr(self, name=None, bint latex=False):
+@@ -583,8 +583,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef long i
+         cdef Integer coef = Integer.__new__(Integer)
+         cdef list all = []
+-        for i from fmpz_poly_degree(self.__poly) >= i >= 0:
+-            fmpz_poly_get_coeff_mpz(coef.value, self.__poly, i)
++        for i from fmpz_poly_degree(self._poly) >= i >= 0:
++            fmpz_poly_get_coeff_mpz(coef.value, self._poly, i)
+             if coef:
+                 if coef > 0:
+                     sign_str = '+'
+@@ -649,8 +649,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_add(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_add(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -669,8 +669,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_sub(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_sub(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -688,7 +688,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_neg(x.__poly, self.__poly)
++        fmpz_poly_neg(x._poly, self._poly)
+         sig_off()
+         return x
+ 
+@@ -758,7 +758,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef Polynomial_integer_dense_flint rr = self._new()
+ 
+         sig_on()
+-        fmpz_poly_divrem(qq.__poly, rr.__poly, self.__poly, right.__poly)
++        fmpz_poly_divrem(qq._poly, rr._poly, self._poly, right._poly)
+         sig_off()
+         return qq, rr
+ 
+@@ -776,7 +776,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: x.is_zero()
+             False
+         """
+-        return (fmpz_poly_degree(self.__poly) == -1)
++        return (fmpz_poly_degree(self._poly) == -1)
+ 
+     cpdef bint is_one(self) except -1:
+         """
+@@ -792,7 +792,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: x.is_one()
+             False
+         """
+-        return fmpz_poly_is_one(self.__poly)
++        return fmpz_poly_is_one(self._poly)
+ 
+     def __bool__(self):
+         """
+@@ -808,7 +808,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: bool(x)
+             True
+         """
+-        return not (fmpz_poly_degree(self.__poly) == -1)
++        return not (fmpz_poly_degree(self._poly) == -1)
+ 
+     @coerce_binop
+     def gcd(self, right):
+@@ -831,8 +831,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             return self
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_gcd(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_gcd(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -941,8 +941,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         fmpz_init(r)
+ 
+         sig_on()
+-        fmpz_poly_xgcd(r, ss.__poly, tt.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_xgcd(r, ss._poly, tt._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         cdef Integer rr = Integer.__new__(Integer)
+         fmpz_get_mpz(rr.value, r)
+@@ -970,8 +970,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_mul(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_mul(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -1000,8 +1000,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_mullow(x.__poly, self.__poly,
+-                    (<Polynomial_integer_dense_flint>right).__poly,
++        fmpz_poly_mullow(x._poly, self._poly,
++                    (<Polynomial_integer_dense_flint>right)._poly,
+                     n)
+         sig_off()
+         return x
+@@ -1020,7 +1020,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_scalar_mul_mpz(x.__poly, self.__poly, (<Integer>right).value)
++        fmpz_poly_scalar_mul_mpz(x._poly, self._poly, (<Integer>right).value)
+         sig_off()
+         return x
+ 
+@@ -1038,7 +1038,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_scalar_mul_mpz(x.__poly, self.__poly, (<Integer>right).value)
++        fmpz_poly_scalar_mul_mpz(x._poly, self._poly, (<Integer>right).value)
+         sig_off()
+         return x
+ 
+@@ -1132,7 +1132,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             num = n.numerator()
+             den = n.denominator()
+ 
+-            if fmpz_poly_degree(self.__poly) == 0:
++            if fmpz_poly_degree(self._poly) == 0:
+                 return self.parent()(self[0].nth_root(den) ** num)
+ 
+             return self.nth_root(den) ** num
+@@ -1142,7 +1142,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+             if self.is_zero():
+                 if nn == 0:
+-                    fmpz_poly_set_coeff_si(res.__poly, 0, 1)
++                    fmpz_poly_set_coeff_si(res._poly, 0, 1)
+                     return res
+                 elif nn < 0:
+                     raise ZeroDivisionError("negative exponent in power of zero")
+@@ -1150,17 +1150,17 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                     return res
+             if nn < 0:
+                 sig_on()
+-                fmpz_poly_pow(res.__poly, self.__poly, -nn)
++                fmpz_poly_pow(res._poly, self._poly, -nn)
+                 sig_off()
+                 return ~res
+             else:
+                 if self is self._parent.gen():
+                     sig_on()
+-                    fmpz_poly_set_coeff_ui(res.__poly, nn, 1)
++                    fmpz_poly_set_coeff_ui(res._poly, nn, 1)
+                     sig_off()
+                 else:
+                     sig_on()
+-                    fmpz_poly_pow(res.__poly, self.__poly, nn)
++                    fmpz_poly_pow(res._poly, self._poly, nn)
+                     sig_off()
+                 return res
+ 
+@@ -1187,7 +1187,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+         cdef Polynomial_integer_dense_flint res
+         res = self._new()
+-        fmpz_poly_pow_trunc(res.__poly, self.__poly, n, prec)
++        fmpz_poly_pow_trunc(res._poly, self._poly, n, prec)
+         return res
+ 
+     def __floordiv__(Polynomial_integer_dense_flint self, right):
+@@ -1226,14 +1226,14 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 else:
+                     res = self._new()
+                     sig_on()
+-                    fmpz_poly_scalar_fdiv_mpz(res.__poly, self.__poly,
++                    fmpz_poly_scalar_fdiv_mpz(res._poly, self._poly,
+                             (<Integer> right).value)
+                     sig_off()
+                 return res
+             elif right in ZZ:
+                 res = self._new()
+                 sig_on()
+-                fmpz_poly_scalar_fdiv_mpz(res.__poly, self.__poly,
++                fmpz_poly_scalar_fdiv_mpz(res._poly, self._poly,
+                         (<Integer>ZZ(right)).value)
+                 sig_off()
+                 return res
+@@ -1248,7 +1248,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         else:
+             res = self._new()
+             sig_on()
+-            fmpz_poly_div(res.__poly, self.__poly, _right.__poly)
++            fmpz_poly_div(res._poly, self._poly, _right._poly)
+             sig_off()
+             return res
+ 
+@@ -1293,9 +1293,9 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         if prec <= 0:
+             raise ValueError("the precision must be positive, got {}".format(prec))
+ 
+-        if fmpz_poly_degree(self.__poly) == -1:
++        if fmpz_poly_degree(self._poly) == -1:
+             raise ValueError("constant term is zero")
+-        cdef fmpz_t c = fmpz_poly_get_coeff_ptr(self.__poly, 0)
++        cdef fmpz_t c = fmpz_poly_get_coeff_ptr(self._poly, 0)
+         if fmpz_cmp_si(c, 1) and fmpz_cmp_si(c, -1):
+             raise ValueError("constant term {} is not a unit".format(self[0]))
+ 
+@@ -1303,7 +1303,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         if prec <= 0:
+             return res
+         sig_on()
+-        fmpz_poly_inv_series(res.__poly, self.__poly, prec)
++        fmpz_poly_inv_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1331,16 +1331,16 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             raise IndexError("n must be >= 0")
+         if isinstance(value, int):
+             sig_on()
+-            fmpz_poly_set_coeff_si(self.__poly, n, value)
++            fmpz_poly_set_coeff_si(self._poly, n, value)
+             sig_off()
+         elif isinstance(value, Integer):
+             sig_on()
+-            fmpz_poly_set_coeff_mpz(self.__poly, n, (<Integer>value).value)
++            fmpz_poly_set_coeff_mpz(self._poly, n, (<Integer>value).value)
+             sig_off()
+         else:
+             value = Integer(value)
+             sig_on()
+-            fmpz_poly_set_coeff_mpz(self.__poly, n, (<Integer>value).value)
++            fmpz_poly_set_coeff_mpz(self._poly, n, (<Integer>value).value)
+             sig_off()
+ 
+     def real_root_intervals(self):
+@@ -1364,7 +1364,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+ ##     def __copy__(self):
+ ##         f = Polynomial_integer_dense(self.parent())
+-##         f.__poly = self.__poly.copy()
++##         f._poly = self._poly.copy()
+ ##         return f
+ 
+ 
+@@ -1391,7 +1391,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: type(x.degree())
+             <class 'sage.rings.integer.Integer'>
+         """
+-        return smallInteger(fmpz_poly_degree(self.__poly))
++        return smallInteger(fmpz_poly_degree(self._poly))
+ 
+     def pseudo_divrem(self, B):
+         r"""
+@@ -1426,7 +1426,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint Q = self._new(), R = self._new(), _B = B
+         cdef ulong d
+-        fmpz_poly_pseudo_divrem(Q.__poly, R.__poly, &d, self.__poly, _B.__poly)
++        fmpz_poly_pseudo_divrem(Q._poly, R._poly, &d, self._poly, _B._poly)
+         return Q, R, Integer(d)
+ 
+     def discriminant(self, proof=True):
+@@ -1460,7 +1460,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef ZZX_c ntl_poly
+         cdef ZZ_c* temp
+-        fmpz_poly_get_ZZX(ntl_poly, self.__poly)
++        fmpz_poly_get_ZZX(ntl_poly, self._poly)
+ 
+         temp = ZZX_discriminant(&ntl_poly, proof)
+         cdef Integer x = Integer.__new__(Integer)
+@@ -1531,12 +1531,12 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+             # the primitive part returned by FLINT has positive leading
+             # coefficient
+-            fmpz_poly_primitive_part(ppart, self.__poly)
++            fmpz_poly_primitive_part(ppart, self._poly)
+ 
+             fmpz_poly_get_ZZX(ntl_poly, ppart)
+             fmpz_poly_clear(ppart)
+         else:
+-            fmpz_poly_get_ZZX(ntl_poly, self.__poly)
++            fmpz_poly_get_ZZX(ntl_poly, self._poly)
+ 
+         # input is primitive, with positive leading coefficient
+         ZZX_squarefree_decomposition(&v, &e, &n, &ntl_poly)
+@@ -1544,7 +1544,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         F = []
+         for i from 0 <= i < n:
+             fac = self._new()
+-            fmpz_poly_set_ZZX(fac.__poly, v[i][0])
++            fmpz_poly_set_ZZX(fac._poly, v[i][0])
+             F.append( (fac,e[i]) )
+             del v[i]
+         sig_free(v)
+@@ -1582,9 +1582,9 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef ZZ_c content
+         cdef vec_pair_ZZX_long_c factors
+         cdef long i
+-        cdef int sig_me = fmpz_poly_degree(self.__poly)
++        cdef int sig_me = fmpz_poly_degree(self._poly)
+ 
+-        fmpz_poly_get_ZZX(ntl_poly, self.__poly)
++        fmpz_poly_get_ZZX(ntl_poly, self._poly)
+ 
+         if sig_me > 10:
+             sig_on()
+@@ -1603,13 +1603,13 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             fac_py = self._new()
+             fmpz_init(tcontent)
+             fmpz_set_ZZ(tcontent, content)
+-            fmpz_poly_set_coeff_fmpz(fac_py.__poly, 0, tcontent)
++            fmpz_poly_set_coeff_fmpz(fac_py._poly, 0, tcontent)
+             results.append( (fac_py,1) )
+             fmpz_clear(tcontent)
+ 
+         for i from 0 <= i < factors.length():
+             fac_py = self._new()
+-            fmpz_poly_set_ZZX(fac_py.__poly, factors.RawGet(i).a)
++            fmpz_poly_set_ZZX(fac_py._poly, factors.RawGet(i).a)
+             results.append( (fac_py,factors.RawGet(i).b) )
+         return Factorization(results, unit = unit)
+ 
+@@ -1639,7 +1639,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             (-1) * 2 * 3 * 5 * x
+         """
+         cdef int i
+-        cdef long deg = fmpz_poly_degree(self.__poly)
++        cdef long deg = fmpz_poly_degree(self._poly)
+         # it appears that pari has a window from about degrees 30 and 300
+         # in which it beats NTL.
+         c = self.content()
+@@ -1783,8 +1783,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef Integer x = Integer.__new__(Integer)
+ 
+         sig_on()
+-        fmpz_poly_resultant(res, self.__poly,
+-                (<Polynomial_integer_dense_flint>other).__poly)
++        fmpz_poly_resultant(res, self._poly,
++                (<Polynomial_integer_dense_flint>other)._poly)
+         sig_off()
+         fmpz_get_mpz(x.value, res)
+         fmpz_clear(res)
+@@ -1830,10 +1830,10 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if d != degree:
+                 raise ValueError("degree argument must be a non-negative integer, got %s" % degree)
+             # FLINT expects length
+-            fmpz_poly_reverse(res.__poly, self.__poly, d+1)
++            fmpz_poly_reverse(res._poly, self._poly, d+1)
+         else:
+-            fmpz_poly_reverse(res.__poly, self.__poly,
+-                    fmpz_poly_length(self.__poly))
++            fmpz_poly_reverse(res._poly, self._poly,
++                    fmpz_poly_length(self._poly))
+         return res
+ 
+     def revert_series(self, n):
+@@ -1867,7 +1867,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             raise ValueError("self must have constant coefficient 0 and a unit for coefficient {}^1".format(self.parent().gen()))
+ 
+         sig_on()
+-        fmpz_poly_revert_series(res.__poly, self.__poly, m)
++        fmpz_poly_revert_series(res._poly, self._poly, m)
+         sig_off()
+ 
+         return res
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd
+index a7c380b49a2..fcd907e1abe 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd
+@@ -2,6 +2,6 @@ from sage.libs.ntl.types cimport ZZX_c
+ from sage.rings.polynomial.polynomial_element cimport Polynomial
+ 
+ cdef class Polynomial_integer_dense_ntl(Polynomial):
+-    cdef ZZX_c __poly
++    cdef ZZX_c _poly
+ 
+     cdef Polynomial_integer_dense_ntl _new(self)
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx
+index e7b708bbc51..80a1726bb4e 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx
+@@ -172,7 +172,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         if isinstance(x, Polynomial):
+             if x.parent() is self.parent():
+                 # copy with NTL assignment operator
+-                self.__poly = (<Polynomial_integer_dense_ntl>x).__poly
++                self._poly = (<Polynomial_integer_dense_ntl>x)._poly
+                 return
+             else:
+                 # coerce coefficients into Sage integers
+@@ -191,17 +191,17 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+                     degree = i
+             if degree >= NTL_OVFBND:
+                 raise OverflowError("Dense NTL integer polynomials have a maximum degree of %s" % (NTL_OVFBND-1))
+-            ZZX_SetCoeff_long(self.__poly, degree, 1)
++            ZZX_SetCoeff_long(self._poly, degree, 1)
+             # now fill them in
+             for ii, a in x:
+                 i = ii[0] if type(ii) is tuple else ii
+                 if type(a) is int:
+-                    ZZX_SetCoeff_long(self.__poly, i, a)
++                    ZZX_SetCoeff_long(self._poly, i, a)
+                 else:
+                     if not isinstance(a, Integer):
+                         a = ZZ(a)
+                     mpz_to_ZZ(&y, (<Integer>a).value)
+-                    ZZX_SetCoeff(self.__poly, i, y)
++                    ZZX_SetCoeff(self._poly, i, y)
+             return
+ 
+         elif isinstance(x, pari_gen):
+@@ -210,14 +210,14 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+ 
+         elif isinstance(x, ntl_ZZX):    # coercion from ntl.pyx object
+             # copy with NTL assignment operator
+-            self.__poly = (<ntl_ZZX>x).x
++            self._poly = (<ntl_ZZX>x).x
+             return
+ 
+         elif isinstance(x, FractionFieldElement) and \
+                  isinstance(x.numerator(), Polynomial_integer_dense_ntl):
+             if x.denominator() == 1:
+                 # fraction of the form f(x)/1
+-                self.__poly = (<Polynomial_integer_dense_ntl>x.numerator()).__poly
++                self._poly = (<Polynomial_integer_dense_ntl>x.numerator())._poly
+                 return
+ 
+         elif not isinstance(x, (list, tuple)):
+@@ -229,12 +229,12 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         for i from 0 <= i < len(x):
+             a = x[i]
+             if type(a) is int:
+-                ZZX_SetCoeff_long(self.__poly, i, a)
++                ZZX_SetCoeff_long(self._poly, i, a)
+             else:
+                 if not isinstance(a, Integer):
+                     a = ZZ(a)
+                 mpz_to_ZZ(&y, (<Integer>a).value)
+-                ZZX_SetCoeff(self.__poly, i, y)
++                ZZX_SetCoeff(self._poly, i, y)
+ 
+ 
+     def content(self):
+@@ -259,7 +259,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef ZZ_c y
+         cdef Integer z = Integer.__new__(Integer)
+-        ZZX_content(y, self.__poly)
++        ZZX_content(y, self._poly)
+         ZZ_to_mpz(z.value, &y)
+         return z
+ 
+@@ -288,7 +288,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef RealNumber res = a._new()
+         sig_on()
+-        ZZX_evaluation_mpfr(res.value, self.__poly, a.value)
++        ZZX_evaluation_mpfr(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -318,7 +318,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef RealIntervalFieldElement res = a._new()
+         sig_on()
+-        ZZX_evaluation_mpfi(res.value, self.__poly, a.value)
++        ZZX_evaluation_mpfi(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -363,7 +363,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             5*x^5 + 4*x^4 + 3*x^3 + 2*x^2 + x + 1
+         """
+         cdef Integer z = Integer.__new__(Integer)
+-        ZZ_to_mpz(z.value, &self.__poly.rep.elts()[n])
++        ZZ_to_mpz(z.value, &self._poly.rep.elts()[n])
+         return z
+ 
+     def _repr(self, name=None, bint latex=False):
+@@ -380,15 +380,15 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             name = self.parent().variable_name()
+         cdef long i
+         cdef list all = []
+-        for i from ZZX_deg(self.__poly) >= i >= 0:
+-            sign = ZZ_sign(ZZX_coeff(self.__poly, i))
++        for i from ZZX_deg(self._poly) >= i >= 0:
++            sign = ZZ_sign(ZZX_coeff(self._poly, i))
+             if sign:
+                 if sign > 0:
+                     sign_str = '+'
+-                    coeff_str = ccrepr(self.__poly.rep.elts()[i])
++                    coeff_str = ccrepr(self._poly.rep.elts()[i])
+                 else:
+                     sign_str = '-'
+-                    coeff_str = ccrepr(self.__poly.rep.elts()[i])[1:]
++                    coeff_str = ccrepr(self._poly.rep.elts()[i])[1:]
+                 if i > 0:
+                     if coeff_str == '1':
+                         coeff_str = ''
+@@ -441,8 +441,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             -3*x^2 + 2*x + 7
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_add(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_ntl>right).__poly)
++        ZZX_add(x._poly, self._poly,
++                (<Polynomial_integer_dense_ntl>right)._poly)
+         return x
+ 
+ 
+@@ -459,8 +459,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             3*x^2 + 2*x - 5
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_sub(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_ntl>right).__poly)
++        ZZX_sub(x._poly, self._poly,
++                (<Polynomial_integer_dense_ntl>right)._poly)
+         return x
+ 
+ 
+@@ -476,7 +476,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             -2*x + 1
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_negate(x.__poly, self.__poly)
++        ZZX_negate(x._poly, self._poly)
+         return x
+ 
+ 
+@@ -533,10 +533,10 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef Polynomial_integer_dense_ntl _right = <Polynomial_integer_dense_ntl> right
+ 
+-        if ZZX_IsZero(_right.__poly):
++        if ZZX_IsZero(_right._poly):
+             raise ArithmeticError("division by zero polynomial")
+ 
+-        if ZZX_IsZero(self.__poly):
++        if ZZX_IsZero(self._poly):
+             return self, self
+ 
+         cdef ZZX_c *q
+@@ -545,19 +545,19 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef Polynomial_integer_dense_ntl rr = self._new()
+         cdef int divisible
+ 
+-        if ZZ_IsOne(ZZX_LeadCoeff(_right.__poly)):
++        if ZZ_IsOne(ZZX_LeadCoeff(_right._poly)):
+             # divisor is monic. Just do the division and remainder
+-            ZZX_quo_rem(&self.__poly, &_right.__poly, &r, &q)
+-            ZZX_swap(qq.__poly, q[0])
+-            ZZX_swap(rr.__poly, r[0])
++            ZZX_quo_rem(&self._poly, &_right._poly, &r, &q)
++            ZZX_swap(qq._poly, q[0])
++            ZZX_swap(rr._poly, r[0])
+             del q
+             del r
+         else:
+             # Non-monic divisor. Check whether it divides exactly.
+-            q = ZZX_div(&self.__poly, &_right.__poly, &divisible)
++            q = ZZX_div(&self._poly, &_right._poly, &divisible)
+             if divisible:
+                 # exactly divisible
+-                ZZX_swap(q[0], qq.__poly)
++                ZZX_swap(q[0], qq._poly)
+                 del q
+             else:
+                 # division failed: clean up and raise exception
+@@ -584,8 +584,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         # todo: we're doing an unnecessary copy here
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        cdef ZZX_c* temp = ZZX_gcd(&self.__poly, &(<Polynomial_integer_dense_ntl>right).__poly)
+-        x.__poly = temp[0]
++        cdef ZZX_c* temp = ZZX_gcd(&self._poly, &(<Polynomial_integer_dense_ntl>right)._poly)
++        x._poly = temp[0]
+         del temp
+         return x
+ 
+@@ -658,13 +658,13 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZX_c *t
+         cdef ZZ_c *r
+ 
+-        ZZX_xgcd(&self.__poly, &(<Polynomial_integer_dense_ntl>right).__poly, &r, &s, &t, 1)    # proof = 1
++        ZZX_xgcd(&self._poly, &(<Polynomial_integer_dense_ntl>right)._poly, &r, &s, &t, 1)    # proof = 1
+         cdef Integer rr = Integer.__new__(Integer)
+         ZZ_to_mpz(rr.value, r)
+         cdef Polynomial_integer_dense_ntl ss = self._new()
+         cdef Polynomial_integer_dense_ntl tt = self._new()
+-        ss.__poly = s[0]
+-        tt.__poly = t[0]
++        ss._poly = s[0]
++        tt._poly = t[0]
+         del r
+         del s
+         del t
+@@ -691,8 +691,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             x^3 - 10*x^2 + 32*x - 32
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_mul(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_ntl>right).__poly)
++        ZZX_mul(x._poly, self._poly,
++                (<Polynomial_integer_dense_ntl>right)._poly)
+         return x
+ 
+     cpdef _lmul_(self, Element right):
+@@ -711,7 +711,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZ_c _right
+ 
+         mpz_to_ZZ(&_right, (<Integer>right).value)
+-        ZZX_mul_ZZ(x.__poly, self.__poly, _right)
++        ZZX_mul_ZZ(x._poly, self._poly, _right)
+         return x
+ 
+     cpdef _rmul_(self, Element right):
+@@ -730,7 +730,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZ_c _right
+ 
+         mpz_to_ZZ(&_right, (<Integer>right).value)
+-        ZZX_mul_ZZ(x.__poly, self.__poly, _right)
++        ZZX_mul_ZZ(x._poly, self._poly, _right)
+         return x
+ 
+ 
+@@ -783,7 +783,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         value = Integer(value)
+         cdef ZZ_c y
+         mpz_to_ZZ(&y, (<Integer>value).value)
+-        ZZX_SetCoeff(self.__poly, n, y)
++        ZZX_SetCoeff(self._poly, n, y)
+ 
+ 
+     def real_root_intervals(self):
+@@ -805,7 +805,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+ 
+ ##     def __copy__(self):
+ ##         f = Polynomial_integer_dense(self.parent())
+-##         f.__poly = self.__poly.copy()
++##         f._poly = self._poly.copy()
+ ##         return f
+ 
+ 
+@@ -826,7 +826,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             sage: R(0).degree()
+             -1
+         """
+-        return ZZX_deg(self.__poly)
++        return ZZX_deg(self._poly)
+ 
+     def discriminant(self, proof=True):
+         r"""
+@@ -849,7 +849,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             sage: f.discriminant(proof=False)
+             -339
+         """
+-        cdef ZZ_c* temp = ZZX_discriminant(&self.__poly, proof)
++        cdef ZZ_c* temp = ZZX_discriminant(&self._poly, proof)
+         cdef Integer x = Integer.__new__(Integer)
+         ZZ_to_mpz(x.value, temp)
+         del temp
+@@ -904,11 +904,11 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef long* e
+         cdef long i, n
+         cdef Polynomial_integer_dense_ntl z
+-        ZZX_squarefree_decomposition(&v, &e, &n, &p.__poly)
++        ZZX_squarefree_decomposition(&v, &e, &n, &p._poly)
+         F = []
+         for i from 0 <= i < n:
+             z = self._new()
+-            z.__poly = v[i][0]
++            z._poly = v[i][0]
+             F.append((z, e[i]))
+             del v[i]
+         sig_free(v)
+@@ -950,24 +950,24 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZ_c content
+         cdef vec_pair_ZZX_long_c factors
+         cdef long i
+-        cdef int sig_me = ZZX_deg(self.__poly)
++        cdef int sig_me = ZZX_deg(self._poly)
+         if sig_me > 10:
+             sig_on()
+-        ZZX_factor(content, factors, self.__poly, 0, 0)
++        ZZX_factor(content, factors, self._poly, 0, 0)
+         if sig_me > 10:
+             sig_off()
+         results = []
+         unit = None
+         if not ZZ_IsOne(content):
+             fac_py = self._new()
+-            ZZX_SetCoeff(fac_py.__poly, 0, content)
+-            if ZZX_deg(fac_py.__poly) == 0 and ZZ_to_int(fac_py.__poly.rep.elts())==-1:
++            ZZX_SetCoeff(fac_py._poly, 0, content)
++            if ZZX_deg(fac_py._poly) == 0 and ZZ_to_int(fac_py._poly.rep.elts())==-1:
+                 unit = fac_py
+             else:
+                 results.append( (fac_py,1) )
+         for i from 0 <= i < factors.length():
+             fac_py = self._new()
+-            fac_py.__poly = factors.RawGet(i).a
++            fac_py._poly = factors.RawGet(i).a
+             results.append( (fac_py,factors.RawGet(i).b) )
+         return Factorization(results, unit = unit)
+ 
+@@ -996,7 +996,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             sage: f = -30*x; f.factor()
+             (-1) * 2 * 3 * 5 * x
+         """
+-        cdef int deg = ZZX_deg(self.__poly)
++        cdef int deg = ZZX_deg(self._poly)
+         # it appears that pari has a window from about degrees 30 and 300
+         # in which it beats NTL.
+         c = self.content()
+@@ -1131,7 +1131,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             True
+         """
+         cdef Polynomial_integer_dense_ntl _other = <Polynomial_integer_dense_ntl>(self.parent().coerce(other))
+-        cdef ZZ_c* temp = ZZX_resultant(&self.__poly, &_other.__poly, proof)
++        cdef ZZ_c* temp = ZZX_resultant(&self._poly, &_other._poly, proof)
+         cdef Integer x = Integer.__new__(Integer)
+         ZZ_to_mpz(x.value, temp)
+         del temp
+diff --git a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd
+index 264f05f3c0d..6934acfee8d 100644
+--- a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd
++++ b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd
+@@ -16,7 +16,7 @@ from sage.libs.ntl.lzz_pX cimport *
+ 
+ 
+ cdef class Polynomial_dense_mod_n(Polynomial):
+-    cdef object __poly
++    cdef object _poly
+     cdef object __singular
+ 
+ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n):
+diff --git a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx
+index 57468e3510f..d69d5e09018 100644
+--- a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx
++++ b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx
+@@ -105,19 +105,19 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+ 
+         if construct:
+             if isinstance(x, ZZ_pX):
+-                self.__poly = x
++                self._poly = x
+                 return
+-            self.__poly = ZZ_pX(x, parent.modulus())
++            self._poly = ZZ_pX(x, parent.modulus())
+             return
+ 
+-        self.__poly = ZZ_pX([], parent.modulus())
++        self._poly = ZZ_pX([], parent.modulus())
+ 
+         if x is None:
+             return         # leave initialized to 0 polynomial.
+ 
+         if isinstance(x, Polynomial):
+             if x.parent() == self.parent():
+-                self.__poly = (<Polynomial_dense_modn_ntl_zz>x).__poly.__copy__()
++                self._poly = (<Polynomial_dense_modn_ntl_zz>x)._poly.__copy__()
+                 return
+             else:
+                 R = parent.base_ring()
+@@ -130,7 +130,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+ 
+ 
+         elif isinstance(x, ZZX):
+-            self.__poly = x.copy()
++            self._poly = x.copy()
+             return
+ 
+         elif isinstance(x, pari_gen):
+@@ -142,7 +142,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             if x.denominator().is_unit():
+                 numer = x.numerator()
+                 denom = x.denominator().inverse_of_unit()
+-                x = numer.__poly * denom.__poly
++                x = numer._poly * denom._poly
+                 check = False
+             else:
+                 raise TypeError("Denominator not a unit.")
+@@ -154,13 +154,13 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             R = parent.base_ring()
+             x = [ZZ(R(a)) for a in x]
+ 
+-        self.__poly = ZZ_pX(x, parent.modulus())
++        self._poly = ZZ_pX(x, parent.modulus())
+ 
+     def __reduce__(self):
+         return make_element, (self.parent(), (self.list(), False, self.is_gen()))
+ 
+     def int_list(self):
+-        return eval(str(self.__poly).replace(' ',','))
++        return eval(str(self._poly).replace(' ',','))
+ 
+     def __pari__(self, variable=None):
+         """
+@@ -186,7 +186,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             You must call ``ntl.set_modulus(ntl.ZZ(n))`` before doing
+             arithmetic with this object!
+         """
+-        return self.__poly
++        return self._poly
+ 
+     cdef get_unsafe(self, Py_ssize_t n):
+         """
+@@ -203,13 +203,13 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             sage: f[:3]
+             13*x^2 + 10*x + 5
+         """
+-        return self._parent._base((<ntl_ZZ_pX> self.__poly)[n]._integer_())
++        return self._parent._base((<ntl_ZZ_pX> self._poly)[n]._integer_())
+ 
+     def _unsafe_mutate(self, n, value):
+         n = int(n)
+         if n < 0:
+             raise IndexError("n must be >= 0")
+-        self.__poly[n] = int(value)
++        self._poly[n] = int(value)
+ 
+     def _pow(self, n):
+         n = int(n)
+@@ -218,10 +218,10 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             return self.parent()(self[0]**n)
+         if n < 0:
+             return (~self)**(-n)
+-        return self.parent()(self.__poly**n, construct=True)
++        return self.parent()(self._poly**n, construct=True)
+ 
+     cpdef _add_(self, right):
+-        return self.parent()(self.__poly + (<Polynomial_dense_mod_n>right).__poly, construct=True)
++        return self.parent()(self._poly + (<Polynomial_dense_mod_n>right)._poly, construct=True)
+ 
+     cpdef _mul_(self, right):
+         """
+@@ -231,11 +231,11 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             sage: (x - 2)*(x^2 - 8*x + 16)
+             x^3 + 90*x^2 + 32*x + 68
+         """
+-        return self.parent()(self.__poly * (<Polynomial_dense_mod_n>right).__poly, construct=True)
++        return self.parent()(self._poly * (<Polynomial_dense_mod_n>right)._poly, construct=True)
+ 
+     cpdef _lmul_(self, Element c):
+         try:
+-            return self.parent()(ZZ_pX([c], self.parent().modulus()) * self.__poly, construct=True)
++            return self.parent()(ZZ_pX([c], self.parent().modulus()) * self._poly, construct=True)
+         except RuntimeError as msg: # should this really be a TypeError
+             raise TypeError(msg)
+ 
+@@ -245,7 +245,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+         Return a tuple ``(quotient, remainder)`` where ``self = quotient*other +
+         remainder``.
+         """
+-        v = self.__poly.quo_rem((<Polynomial_dense_mod_n>right).__poly)
++        v = self._poly.quo_rem((<Polynomial_dense_mod_n>right)._poly)
+         P = self.parent()
+         return (P(v[0], construct=True), P(v[1], construct=True) )
+ 
+@@ -281,11 +281,11 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+         """
+         if n == 0 or self.degree() < 0:
+             return self
+-        return self.parent()(self.__poly.left_shift(n),
++        return self.parent()(self._poly.left_shift(n),
+                              construct=True)
+ 
+     cpdef _sub_(self, right):
+-        return self.parent()(self.__poly - (<Polynomial_dense_mod_n>right).__poly, construct=True)
++        return self.parent()(self._poly - (<Polynomial_dense_mod_n>right)._poly, construct=True)
+ 
+     def __floordiv__(self, right):
+         q, _ = self.quo_rem(right)
+@@ -314,7 +314,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             sage: isinstance(x.degree(), Integer)
+             True
+         """
+-        return smallInteger(max(self.__poly.degree(), -1))
++        return smallInteger(max(self._poly.degree(), -1))
+ 
+     cpdef list list(self, bint copy=True):
+         """
+@@ -358,7 +358,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+         """
+         if self.is_gen():
+             raise TypeError("Cannot change the value of the generator.")
+-        self.__poly = ZZ_pX(v, self.parent().modulus())
++        self._poly = ZZ_pX(v, self.parent().modulus())
+ 
+     # Polynomial_singular_repr stuff, copied due to lack of multiple inheritance
+     def _singular_(self, singular=singular_default, force=False):
+@@ -654,8 +654,8 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n):
+                 return
+ 
+         Polynomial_dense_mod_n.__init__(self, parent, v, check=check, is_gen=is_gen, construct=construct)
+-        v = [a for a in self.__poly.list()]
+-        self.__poly = None # this will eventually go away
++        v = [a for a in self._poly.list()]
++        self._poly = None # this will eventually go away
+         cdef ntl_zz_pX ntl = ntl_zz_pX(v, parent.modulus()) # let it handle the hard work
+         self.x = ntl.x
+         self.c = ntl.c
+@@ -668,8 +668,8 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n):
+         # TODO: Get rid of this
+         Polynomial_dense_mod_n.ntl_set_directly(self, v)
+         # verbatim from __init__
+-        v = [int(a) for a in self.__poly.list()]
+-        self.__poly = None # this will eventually go away
++        v = [int(a) for a in self._poly.list()]
++        self._poly = None # this will eventually go away
+         cdef ntl_zz_pX ntl = ntl_zz_pX(v, self._parent.modulus()) # let it handle the hard work
+         self.x = ntl.x
+         self.c = ntl.c
+@@ -1241,8 +1241,8 @@ cdef class Polynomial_dense_modn_ntl_ZZ(Polynomial_dense_mod_n):
+                 return
+ 
+         Polynomial_dense_mod_n.__init__(self, parent, v, check=check, is_gen=is_gen, construct=construct)
+-        cdef ntl_ZZ_pX ntl = self.__poly
+-        self.__poly = None # this will eventually go away
++        cdef ntl_ZZ_pX ntl = self._poly
++        self._poly = None # this will eventually go away
+         self.x = ntl.x
+         self.c = ntl.c
+ 
+diff --git a/src/sage/rings/polynomial/polynomial_rational_flint.pxd b/src/sage/rings/polynomial/polynomial_rational_flint.pxd
+index 055d7842668..f4644f19d04 100644
+--- a/src/sage/rings/polynomial/polynomial_rational_flint.pxd
++++ b/src/sage/rings/polynomial/polynomial_rational_flint.pxd
+@@ -11,7 +11,7 @@ from sage.libs.flint.types cimport fmpq_poly_t
+ from sage.rings.polynomial.polynomial_element cimport Polynomial
+ 
+ cdef class Polynomial_rational_flint(Polynomial):
+-    cdef fmpq_poly_t __poly
++    cdef fmpq_poly_t _poly
+ 
+     cdef Polynomial_rational_flint _new(self)
+     cpdef _mod_(self, right)
+diff --git a/src/sage/rings/polynomial/polynomial_rational_flint.pyx b/src/sage/rings/polynomial/polynomial_rational_flint.pyx
+index d0dd15522e9..26d070ac77f 100644
+--- a/src/sage/rings/polynomial/polynomial_rational_flint.pyx
++++ b/src/sage/rings/polynomial/polynomial_rational_flint.pyx
+@@ -155,16 +155,16 @@ cdef class Polynomial_rational_flint(Polynomial):
+         res._parent = P
+         res._is_gen = <char>0
+         if isinstance(x, int):
+-            fmpq_poly_set_si(res.__poly, <int> x)
++            fmpq_poly_set_si(res._poly, <int> x)
+ 
+         elif isinstance(x, Integer):
+-            fmpq_poly_set_mpz(res.__poly, (<Integer> x).value)
++            fmpq_poly_set_mpz(res._poly, (<Integer> x).value)
+ 
+         elif isinstance(x, Rational):
+-            fmpq_poly_set_mpq(res.__poly, (<Rational> x).value)
++            fmpq_poly_set_mpq(res._poly, (<Rational> x).value)
+ 
+         else:
+-            fmpq_poly_set_si(res.__poly, int(x))
++            fmpq_poly_set_si(res._poly, int(x))
+         return res
+ 
+ 
+@@ -177,7 +177,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: R.<t> = QQ[]
+             sage: f = 2/3 * t - 7  #indirect doctest
+         """
+-        fmpq_poly_init(self.__poly)
++        fmpq_poly_init(self._poly)
+ 
+     def __dealloc__(self):
+         """
+@@ -189,7 +189,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: f = 1/3 * t
+             sage: del f
+         """
+-        fmpq_poly_clear(self.__poly)
++        fmpq_poly_clear(self._poly)
+ 
+     def __init__(self, parent, x=None, check=True, is_gen=False, construct=False):
+         """
+@@ -227,19 +227,19 @@ cdef class Polynomial_rational_flint(Polynomial):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+ 
+         if is_gen:
+-            fmpq_poly_set_coeff_si(self.__poly, 1, 1)
++            fmpq_poly_set_coeff_si(self._poly, 1, 1)
+ 
+         elif isinstance(x, Polynomial_rational_flint):
+-            fmpq_poly_set(self.__poly, (<Polynomial_rational_flint> x).__poly)
++            fmpq_poly_set(self._poly, (<Polynomial_rational_flint> x)._poly)
+ 
+         elif isinstance(x, int):
+-            fmpq_poly_set_si(self.__poly, <int> x)
++            fmpq_poly_set_si(self._poly, <int> x)
+ 
+         elif isinstance(x, Integer):
+-            fmpq_poly_set_mpz(self.__poly, (<Integer> x).value)
++            fmpq_poly_set_mpz(self._poly, (<Integer> x).value)
+ 
+         elif isinstance(x, Rational):
+-            fmpq_poly_set_mpq(self.__poly, (<Rational> x).value)
++            fmpq_poly_set_mpq(self._poly, (<Rational> x).value)
+ 
+         elif isinstance(x, list) or isinstance(x, tuple):
+ 
+@@ -257,7 +257,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             for deg from 0 <= deg < n:
+                 mpq_init(L2[deg])
+                 mpq_set(L2[deg], (<Rational> L1[deg]).value)
+-            fmpq_poly_set_array_mpq(self.__poly, L2, n)
++            fmpq_poly_set_array_mpq(self._poly, L2, n)
+             for deg from 0 <= deg < n:
+                 mpq_clear(L2[deg])
+             sig_free(L2)
+@@ -266,13 +266,13 @@ cdef class Polynomial_rational_flint(Polynomial):
+ #           deg = 0
+ #           for e in x:
+ #               c = Rational(e)
+-#               fmpq_poly_set_coeff_mpq(self.__poly, deg, c.value)
++#               fmpq_poly_set_coeff_mpq(self._poly, deg, c.value)
+ #               deg += 1
+ 
+         elif isinstance(x, dict):
+             for deg, e in x.iteritems():
+                 c = Rational(e)
+-                fmpq_poly_set_coeff_mpq(self.__poly, deg, c.value)
++                fmpq_poly_set_coeff_mpq(self._poly, deg, c.value)
+ 
+         elif isinstance(x, pari_gen):
+             k = self._parent.base_ring()
+@@ -281,7 +281,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+                                              is_gen=False, construct=construct)
+ 
+         elif isinstance(x, Polynomial_integer_dense_flint):
+-            fmpq_poly_set_fmpz_poly(self.__poly, (<Polynomial_integer_dense_flint>x).__poly)
++            fmpq_poly_set_fmpz_poly(self._poly, (<Polynomial_integer_dense_flint>x)._poly)
+ 
+         elif isinstance(x, Polynomial):
+             k = self._parent.base_ring()
+@@ -329,7 +329,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             True
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        fmpq_poly_set(res.__poly, self.__poly)
++        fmpq_poly_set(res._poly, self._poly)
+         return res
+ 
+     def _singular_(self, singular=singular_default):
+@@ -364,7 +364,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: g.list()
+             []
+         """
+-        cdef unsigned long length = fmpq_poly_length(self.__poly)
++        cdef unsigned long length = fmpq_poly_length(self._poly)
+         return [self.get_unsafe(n) for n in range(length)]
+ 
+     ###########################################################################
+@@ -392,7 +392,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: type(f.degree())
+             <class 'sage.rings.integer.Integer'>
+         """
+-        return smallInteger(fmpq_poly_degree(self.__poly))
++        return smallInteger(fmpq_poly_degree(self._poly))
+ 
+     cdef get_unsafe(self, Py_ssize_t n):
+         """
+@@ -413,7 +413,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             1/2*t^2 + t + 1
+         """
+         cdef Rational z = Rational.__new__(Rational)
+-        fmpq_poly_get_coeff_mpq(z.value, self.__poly, n)
++        fmpq_poly_get_coeff_mpq(z.value, self._poly, n)
+         return z
+ 
+     cpdef _unsafe_mutate(self, unsigned long n, value):
+@@ -434,24 +434,24 @@ cdef class Polynomial_rational_flint(Polynomial):
+         rely on this convention.  This method should be used only with the
+         utmost care.
+         """
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if isinstance(value, int):
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_si(self.__poly, n, value)
++            fmpq_poly_set_coeff_si(self._poly, n, value)
+             if do_sig: sig_off()
+         elif isinstance(value, Integer):
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_mpz(self.__poly, n, (<Integer> value).value)
++            fmpq_poly_set_coeff_mpz(self._poly, n, (<Integer> value).value)
+             if do_sig: sig_off()
+         elif isinstance(value, Rational):
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_mpq(self.__poly, n, (<Rational> value).value)
++            fmpq_poly_set_coeff_mpq(self._poly, n, (<Rational> value).value)
+             if do_sig: sig_off()
+         else:
+             value = Rational(value)
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_mpq(self.__poly, n, (<Rational> value).value)
++            fmpq_poly_set_coeff_mpq(self._poly, n, (<Rational> value).value)
+             if do_sig: sig_off()
+ 
+     def __call__(self, *x, **kwds):
+@@ -501,20 +501,20 @@ cdef class Polynomial_rational_flint(Polynomial):
+             if isinstance(a, Polynomial_rational_flint):
+                 f = (<Polynomial_rational_flint> a)._new()
+                 sig_str("FLINT exception")
+-                fmpq_poly_compose(f.__poly, self.__poly,
+-                    (<Polynomial_rational_flint> a).__poly)
++                fmpq_poly_compose(f._poly, self._poly,
++                    (<Polynomial_rational_flint> a)._poly)
+                 sig_off()
+                 return f
+             elif isinstance(a, Rational):
+                 r = Rational.__new__(Rational)
+                 sig_str("FLINT exception")
+-                fmpq_poly_evaluate_mpq(r.value, self.__poly, (<Rational> a).value)
++                fmpq_poly_evaluate_mpq(r.value, self._poly, (<Rational> a).value)
+                 sig_off()
+                 return r
+             elif isinstance(a, Integer):
+                 r = Rational.__new__(Rational)
+                 sig_str("FLINT exception")
+-                fmpq_poly_evaluate_mpz(r.value, self.__poly, (<Integer> a).value)
++                fmpq_poly_evaluate_mpz(r.value, self._poly, (<Integer> a).value)
+                 sig_off()
+                 return r
+             elif isinstance(a, int):
+@@ -523,7 +523,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+                 fmpz_init(tmpfz)
+                 fmpq_init(tmpfq)
+                 fmpz_set_si(tmpfz, PyInt_AS_LONG(a))
+-                fmpq_poly_evaluate_fmpz(tmpfq, self.__poly, tmpfz)
++                fmpq_poly_evaluate_fmpz(tmpfq, self._poly, tmpfz)
+                 fmpq_get_mpq(r.value, tmpfq)
+                 fmpq_clear(tmpfq)
+                 fmpz_clear(tmpfz)
+@@ -533,18 +533,18 @@ cdef class Polynomial_rational_flint(Polynomial):
+                 arb_a = <RealBall> a
+                 arb_z = arb_a._new()
+                 sig_on()
+-                _arb_fmpz_poly_evaluate_arb(arb_z.value, fmpq_poly_numref(self.__poly),
+-                        fmpq_poly_length(self.__poly), arb_a.value, arb_a._parent._prec)
+-                arb_div_fmpz(arb_z.value, arb_z.value, fmpq_poly_denref(self.__poly), arb_a._parent._prec)
++                _arb_fmpz_poly_evaluate_arb(arb_z.value, fmpq_poly_numref(self._poly),
++                        fmpq_poly_length(self._poly), arb_a.value, arb_a._parent._prec)
++                arb_div_fmpz(arb_z.value, arb_z.value, fmpq_poly_denref(self._poly), arb_a._parent._prec)
+                 sig_off()
+                 return arb_z
+             if isinstance(a, ComplexBall):
+                 acb_a = <ComplexBall> a
+                 acb_z = acb_a._new()
+                 sig_on()
+-                _arb_fmpz_poly_evaluate_acb(acb_z.value, fmpq_poly_numref(self.__poly),
+-                        fmpq_poly_length(self.__poly), acb_a.value, acb_a._parent._prec)
+-                acb_div_fmpz(acb_z.value, acb_z.value, fmpq_poly_denref(self.__poly), acb_a._parent._prec)
++                _arb_fmpz_poly_evaluate_acb(acb_z.value, fmpq_poly_numref(self._poly),
++                        fmpq_poly_length(self._poly), acb_a.value, acb_a._parent._prec)
++                acb_div_fmpz(acb_z.value, acb_z.value, fmpq_poly_denref(self._poly), acb_a._parent._prec)
+                 sig_off()
+                 return acb_z
+ 
+@@ -570,14 +570,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res
+         cdef bint do_sig
+ 
+-        if (n >= fmpq_poly_length(self.__poly)):
++        if (n >= fmpq_poly_length(self._poly)):
+             return self
+         else:
+             res = self._new()
+             if n > 0:
+-                do_sig = _do_sig(self.__poly)
++                do_sig = _do_sig(self._poly)
+                 if do_sig: sig_str("FLINT exception")
+-                fmpq_poly_get_slice(res.__poly, self.__poly, 0, n)
++                fmpq_poly_get_slice(res._poly, self._poly, 0, n)
+                 if do_sig: sig_off()
+             return res
+ 
+@@ -664,7 +664,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef bint do_sig
+ 
+         if degree is None:
+-            len = fmpq_poly_length(self.__poly)
++            len = fmpq_poly_length(self._poly)
+         else:
+             try:
+                 len = <unsigned long> (degree + 1)
+@@ -672,9 +672,9 @@ cdef class Polynomial_rational_flint(Polynomial):
+                 raise ValueError('degree must be convertible to long')
+ 
+         res = self._new()
+-        do_sig = _do_sig(self.__poly)
++        do_sig = _do_sig(self._poly)
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_reverse(res.__poly, self.__poly, len)
++        fmpq_poly_reverse(res._poly, self._poly, len)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -709,7 +709,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             raise ValueError("self must have constant coefficient 0 and a unit for coefficient {}^1".format(self.parent().gen()))
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_revert_series(res.__poly, self.__poly, m)
++        fmpq_poly_revert_series(res._poly, self._poly, m)
+         sig_off()
+ 
+         return res
+@@ -731,7 +731,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: R(0).is_zero()
+             True
+         """
+-        return fmpq_poly_is_zero(self.__poly)
++        return fmpq_poly_is_zero(self._poly)
+ 
+     cpdef bint is_one(self) except -1:
+         r"""
+@@ -751,7 +751,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: R([1,1]).is_one()
+             False
+         """
+-        return fmpq_poly_is_one(self.__poly)
++        return fmpq_poly_is_one(self._poly)
+ 
+     def __bool__(self):
+         """
+@@ -766,7 +766,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: bool(R(0))
+             False
+         """
+-        return not fmpq_poly_is_zero(self.__poly)
++        return not fmpq_poly_is_zero(self._poly)
+ 
+     ###########################################################################
+     # Shifting                                                                #
+@@ -794,14 +794,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res
+         cdef bint do_sig
+ 
+-        if k == 0 or fmpq_poly_is_zero(f.__poly):
++        if k == 0 or fmpq_poly_is_zero(f._poly):
+             return self
+         else:
+             res = f._new()
+-            do_sig = fmpq_poly_length(f.__poly) > 5000 or n > 5000
++            do_sig = fmpq_poly_length(f._poly) > 5000 or n > 5000
+ 
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_shift_left(res.__poly, f.__poly, k)
++            fmpq_poly_shift_left(res._poly, f._poly, k)
+             if do_sig: sig_off()
+             return res
+ 
+@@ -822,14 +822,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res
+         cdef bint do_sig
+ 
+-        if k == 0 or fmpq_poly_is_zero(f.__poly):
++        if k == 0 or fmpq_poly_is_zero(f._poly):
+             return self
+         else:
+             res = f._new()
+-            do_sig = _do_sig(f.__poly)
++            do_sig = _do_sig(f._poly)
+ 
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_shift_right(res.__poly, f.__poly, k)
++            fmpq_poly_shift_right(res._poly, f._poly, k)
+             if do_sig: sig_off()
+             return res
+ 
+@@ -858,10 +858,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_add(res.__poly, self.__poly, op2.__poly)
++        fmpq_poly_add(res._poly, self._poly, op2._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -886,10 +886,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_sub(res.__poly, self.__poly, op2.__poly)
++        fmpq_poly_sub(res._poly, self._poly, op2._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -912,10 +912,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             True
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_neg(res.__poly, self.__poly)
++        fmpq_poly_neg(res._poly, self._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -945,8 +945,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint rr = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_divrem(qq.__poly, rr.__poly, self.__poly,
+-                         (<Polynomial_rational_flint> right).__poly)
++        fmpq_poly_divrem(qq._poly, rr._poly, self._poly,
++                         (<Polynomial_rational_flint> right)._poly)
+         sig_off()
+         return qq, rr
+ 
+@@ -974,8 +974,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_gcd(res.__poly, self.__poly,
+-                (<Polynomial_rational_flint> right).__poly)
++        fmpq_poly_gcd(res._poly, self._poly,
++                (<Polynomial_rational_flint> right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1001,8 +1001,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_lcm(res.__poly, self.__poly,
+-                      (<Polynomial_rational_flint> right).__poly)
++        fmpq_poly_lcm(res._poly, self._poly,
++                      (<Polynomial_rational_flint> right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1043,7 +1043,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint t = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_xgcd(d.__poly, s.__poly, t.__poly, self.__poly, (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_xgcd(d._poly, s._poly, t._poly, self._poly, (<Polynomial_rational_flint>right)._poly)
+         sig_off()
+         return d, s, t
+ 
+@@ -1069,10 +1069,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_mul(res.__poly, self.__poly, op2.__poly)
++        fmpq_poly_mul(res._poly, self._poly, op2._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -1103,13 +1103,13 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if n <= 0:
+             raise ValueError("n must be > 0")
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_mullow(res.__poly, self.__poly, op2.__poly, n)
++        fmpq_poly_mullow(res._poly, self._poly, op2._poly, n)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -1125,10 +1125,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             9*t^3 - 6*t + 2
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_scalar_mul_mpq(res.__poly, self.__poly,
++        fmpq_poly_scalar_mul_mpq(res._poly, self._poly,
+                                  (<Rational> left).value)
+         if do_sig: sig_off()
+         return res
+@@ -1145,10 +1145,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             9*t^3 - 6*t + 2
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_scalar_mul_mpq(res.__poly, self.__poly,
++        fmpq_poly_scalar_mul_mpq(res._poly, self._poly,
+                                  (<Rational> right).value)
+         if do_sig: sig_off()
+         return res
+@@ -1272,27 +1272,27 @@ cdef class Polynomial_rational_flint(Polynomial):
+             num = r.numerator()
+             den = r.denominator()
+ 
+-            if fmpq_poly_degree(self.__poly) == 0:
++            if fmpq_poly_degree(self._poly) == 0:
+                 return self.parent()(self[0].nth_root(den) ** num)
+ 
+             return self.nth_root(den) ** num
+ 
+         else:
+             if n < 0:
+-                if fmpq_poly_is_zero(self.__poly):
++                if fmpq_poly_is_zero(self._poly):
+                     raise ZeroDivisionError("negative exponent in power of zero")
+                 res = self._new()
+                 sig_str("FLINT exception")
+-                fmpq_poly_pow(res.__poly, self.__poly, -n)
++                fmpq_poly_pow(res._poly, self._poly, -n)
+                 sig_off()
+                 return ~res
+             else:
+                 res = self._new()
+                 sig_str("FLINT exception")
+                 if self._is_gen:
+-                    fmpq_poly_set_coeff_si(res.__poly, n, 1)
++                    fmpq_poly_set_coeff_si(res._poly, n, 1)
+                 else:
+-                    fmpq_poly_pow(res.__poly, self.__poly, n)
++                    fmpq_poly_pow(res._poly, self._poly, n)
+                 sig_off()
+                 return res
+ 
+@@ -1328,10 +1328,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         if not isinstance(right, Polynomial_rational_flint):
+             if right in QQ:
+                 res = self._new()
+-                do_sig = _do_sig(self.__poly)
++                do_sig = _do_sig(self._poly)
+ 
+                 if do_sig: sig_str("FLINT exception")
+-                fmpq_poly_scalar_div_mpq(res.__poly, self.__poly,
++                fmpq_poly_scalar_div_mpq(res._poly, self._poly,
+                                                   (<Rational> QQ(right)).value)
+                 if do_sig: sig_off()
+                 return res
+@@ -1340,8 +1340,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+ 
+         res = self._new()
+         sig_str("FLINT exception")
+-        fmpq_poly_div(res.__poly, self.__poly,
+-                                     (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_div(res._poly, self._poly,
++                                     (<Polynomial_rational_flint>right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1381,15 +1381,15 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         if prec <= 0:
+             raise ValueError("the precision must be positive, got {}".format(prec))
+-        if fmpq_poly_degree(self.__poly) == -1 or \
+-           fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        if fmpq_poly_degree(self._poly) == -1 or \
++           fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term is zero")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         if prec <= 0:
+             return res
+         sig_on()
+-        fmpq_poly_inv_series(res.__poly, self.__poly, prec)
++        fmpq_poly_inv_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1423,8 +1423,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+ 
+         res = self._new()
+         sig_str("FLINT exception")
+-        fmpq_poly_rem(res.__poly, self.__poly,
+-                                     (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_rem(res._poly, self._poly,
++                                     (<Polynomial_rational_flint>right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1453,7 +1453,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+         Polynomial_integer_dense_flint.__init__(num, parent, x=None,
+                                     check=False, is_gen=False, construct=False)
+         sig_str("FLINT exception")
+-        fmpq_poly_get_numerator(num.__poly, self.__poly)
++        fmpq_poly_get_numerator(num._poly, self._poly)
+         sig_off()
+         return num
+ 
+@@ -1469,10 +1469,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             3
+         """
+         cdef Integer den = Integer.__new__(Integer)
+-        if fmpq_poly_denref(self.__poly) is NULL:
++        if fmpq_poly_denref(self._poly) is NULL:
+             mpz_set_ui(den.value, 1)
+         else:
+-            fmpz_get_mpz(den.value, <fmpz *> fmpq_poly_denref(self.__poly))
++            fmpz_get_mpz(den.value, <fmpz *> fmpq_poly_denref(self._poly))
+         return den
+ 
+     def _derivative(self, var = None):
+@@ -1517,10 +1517,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             raise ValueError("cannot differentiate with respect to {}".format(var))
+ 
+         der = self._new()
+-        do_sig = _do_sig(self.__poly)
++        do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_derivative(der.__poly, self.__poly)
++        fmpq_poly_derivative(der._poly, self._poly)
+         if do_sig: sig_off()
+         return der
+ 
+@@ -1574,8 +1574,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef fmpq_t t
+         fmpq_init(t)
+         sig_str("FLINT exception")
+-        fmpq_poly_resultant(t, self.__poly,
+-                            (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_resultant(t, self._poly,
++                            (<Polynomial_rational_flint>right)._poly)
+         fmpq_get_mpq(res.value, t)
+         sig_off()
+         fmpq_clear(t)
+@@ -1623,7 +1623,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+ 
+         """
+         cdef Polynomial_integer_dense_flint primitive
+-        cdef unsigned long length = fmpq_poly_length(self.__poly)
++        cdef unsigned long length = fmpq_poly_length(self._poly)
+ 
+         if length < 2:
+             return False
+@@ -1636,8 +1636,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+                              x=None, check=True, is_gen=False, construct=False)
+ 
+             sig_str("FLINT exception")
+-            fmpq_poly_get_numerator(primitive.__poly, self.__poly)
+-            fmpz_poly_primitive_part(primitive.__poly, primitive.__poly)
++            fmpq_poly_get_numerator(primitive._poly, self._poly)
++            fmpz_poly_primitive_part(primitive._poly, primitive._poly)
+             sig_off()
+             return primitive.is_irreducible()
+ 
+@@ -1669,14 +1669,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             ...
+             ValueError: constant term should be 1 in order to take logarithm
+         """
+-        if fmpq_poly_degree(self.__poly) == -1 or \
+-           fmpz_cmp(fmpq_poly_numref(self.__poly),
+-                    fmpq_poly_denref(self.__poly)):
++        if fmpq_poly_degree(self._poly) == -1 or \
++           fmpz_cmp(fmpq_poly_numref(self._poly),
++                    fmpq_poly_denref(self._poly)):
+             raise ValueError("constant term should be 1 in order to take logarithm")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_log_series(res.__poly, self.__poly, prec)
++        fmpq_poly_log_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1703,14 +1703,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.one()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take exponential")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_exp_series(res.__poly, self.__poly, prec)
++        fmpq_poly_exp_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1737,14 +1737,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take arctangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_atan_series(res.__poly, self.__poly, prec)
++        fmpq_poly_atan_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1768,14 +1768,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic arctangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_atanh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_atanh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1802,14 +1802,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take arcsine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_asin_series(res.__poly, self.__poly, prec)
++        fmpq_poly_asin_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1837,14 +1837,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic arcsine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_asinh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_asinh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1871,14 +1871,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take tangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_tan_series(res.__poly, self.__poly, prec)
++        fmpq_poly_tan_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1905,14 +1905,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take sine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_sin_series(res.__poly, self.__poly, prec)
++        fmpq_poly_sin_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1937,14 +1937,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take cosine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_cos_series(res.__poly, self.__poly, prec)
++        fmpq_poly_cos_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1969,14 +1969,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic sine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_sinh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_sinh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -2007,14 +2007,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.one()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic cosine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_cosh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_cosh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -2040,14 +2040,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic tangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_tanh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_tanh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+diff --git a/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx b/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx
+index fbe96d186c5..955f83468e4 100644
+--- a/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx
++++ b/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx
+@@ -116,7 +116,7 @@ cdef class PolynomialRealDense(Polynomial):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+         self._base_ring = parent._base
+         cdef Py_ssize_t i, degree
+-        cdef int prec = self._base_ring.__prec
++        cdef int prec = self._base_ring._prec
+         cdef mpfr_rnd_t rnd = self._base_ring.rnd
+         if x is None:
+             self._coeffs = <mpfr_t*>check_allocarray(1, sizeof(mpfr_t)) # degree zero
+@@ -227,7 +227,7 @@ cdef class PolynomialRealDense(Polynomial):
+ 
+     cdef PolynomialRealDense _new(self, Py_ssize_t degree):
+         cdef Py_ssize_t i
+-        cdef int prec = self._base_ring.__prec
++        cdef int prec = self._base_ring._prec
+         cdef PolynomialRealDense f = <PolynomialRealDense>PolynomialRealDense.__new__(PolynomialRealDense)
+         f._parent = self._parent
+         f._base_ring = self._base_ring
+@@ -501,7 +501,7 @@ cdef class PolynomialRealDense(Polynomial):
+         else:
+             f = left._new(left._degree + right._degree)
+         sig_on()
+-        mpfr_init2(tmp, left._base_ring.__prec)
++        mpfr_init2(tmp, left._base_ring._prec)
+         for i from 0 <= i <= f._degree:
+             # Yes, we could make this more efficient by initializing with
+             # a multiple of left rather than all zeros...
+@@ -661,7 +661,7 @@ cdef class PolynomialRealDense(Polynomial):
+         q = self._new(self._degree - other._degree)
+         # This is the standard division algorithm
+         sig_on()
+-        mpfr_init2(tmp, self._base_ring.__prec)
++        mpfr_init2(tmp, self._base_ring._prec)
+         for i from self._degree >= i >= other._degree:
+             mpfr_set(q._coeffs[i-other._degree], r._coeffs[i], rnd)
+             for j from 0 <= j < other._degree:
+@@ -725,7 +725,7 @@ cdef class PolynomialRealDense(Polynomial):
+         cdef RealNumber x = <RealNumber>xx
+         cdef RealNumber res
+ 
+-        if (<RealField_class>x._parent).__prec < self._base_ring.__prec:
++        if (<RealField_class>x._parent)._prec < self._base_ring._prec:
+             res = RealNumber(x._parent)
+         else:
+             res = RealNumber(self._base_ring)
+diff --git a/src/sage/rings/polynomial/polynomial_zmod_flint.pyx b/src/sage/rings/polynomial/polynomial_zmod_flint.pyx
+index 253ab949fcc..4c480673861 100644
+--- a/src/sage/rings/polynomial/polynomial_zmod_flint.pyx
++++ b/src/sage/rings/polynomial/polynomial_zmod_flint.pyx
+@@ -110,7 +110,7 @@ cdef class Polynomial_zmod_flint(Polynomial_template):
+             return
+         elif isinstance(x, Polynomial_integer_dense_flint):
+             Polynomial_template.__init__(self, parent, 0, check, is_gen, construct)
+-            self._set_fmpz_poly((<Polynomial_integer_dense_flint>x).__poly)
++            self._set_fmpz_poly((<Polynomial_integer_dense_flint>x)._poly)
+             return
+         else:
+             if isinstance(x, ntl_zz_pX):
+diff --git a/src/sage/rings/power_series_mpoly.pxd b/src/sage/rings/power_series_mpoly.pxd
+index f822ecc1227..d358ada1356 100644
+--- a/src/sage/rings/power_series_mpoly.pxd
++++ b/src/sage/rings/power_series_mpoly.pxd
+@@ -3,6 +3,6 @@ from .power_series_ring_element cimport PowerSeries
+ 
+ cdef class PowerSeries_mpoly(PowerSeries):
+     cdef ModuleElement __f
+-    cdef object __poly
++    cdef object _poly
+     cdef object __list
+     cdef bint _truncated
+diff --git a/src/sage/rings/power_series_mpoly.pyx b/src/sage/rings/power_series_mpoly.pyx
+index 0c901a3557b..be59294e75b 100644
+--- a/src/sage/rings/power_series_mpoly.pyx
++++ b/src/sage/rings/power_series_mpoly.pyx
+@@ -65,7 +65,7 @@ cdef class PowerSeries_mpoly(PowerSeries):
+ 
+     def __reduce__(self):
+         # do *not* delete old versions.
+-        return make_powerseries_mpoly_v0, (self._parent, self.__f, self._prec, self.__is_gen)
++        return make_powerseries_mpoly_v0, (self._parent, self.__f, self._prec, self._is_gen)
+ 
+     def __call__(self, *args, **kwds):
+         if len(kwds) == 0 and len(args) == 1:
+@@ -92,10 +92,10 @@ cdef class PowerSeries_mpoly(PowerSeries):
+         return self.__list
+ 
+     def polynomial(self):
+-        if self.__poly is None:
++        if self._poly is None:
+             S = self.parent()._mpoly_ring()
+-            self.__poly = self.__f.polynomial(S.gens()[-1])
+-        return self.__poly
++            self._poly = self.__f.polynomial(S.gens()[-1])
++        return self._poly
+ 
+     def _mpoly(self):
+         return self.__f
+diff --git a/src/sage/rings/power_series_poly.pyx b/src/sage/rings/power_series_poly.pyx
+index 7c93168d4b1..6cacab1f0c8 100644
+--- a/src/sage/rings/power_series_poly.pyx
++++ b/src/sage/rings/power_series_poly.pyx
+@@ -97,7 +97,7 @@ cdef class PowerSeries_poly(PowerSeries):
+             sage: f == loads(dumps(f)) # indirect doctest
+             True
+         """
+-        return self.__class__, (self._parent, self.__f, self._prec, self.__is_gen)
++        return self.__class__, (self._parent, self.__f, self._prec, self._is_gen)
+ 
+     def polynomial(self):
+         """
+diff --git a/src/sage/rings/power_series_ring_element.pxd b/src/sage/rings/power_series_ring_element.pxd
+index 067c4f3c6d4..e5c031ee147 100644
+--- a/src/sage/rings/power_series_ring_element.pxd
++++ b/src/sage/rings/power_series_ring_element.pxd
+@@ -1,7 +1,7 @@
+ from sage.structure.element cimport AlgebraElement, RingElement
+ 
+ cdef class PowerSeries(AlgebraElement):
+-    cdef char __is_gen
++    cdef char _is_gen
+     cdef _prec
+     cdef common_prec_c(self, PowerSeries other)
+     #_prec(self, RingElement right_r)
+diff --git a/src/sage/rings/power_series_ring_element.pyx b/src/sage/rings/power_series_ring_element.pyx
+index 54314d538ed..e5e2df79e1b 100644
+--- a/src/sage/rings/power_series_ring_element.pyx
++++ b/src/sage/rings/power_series_ring_element.pyx
+@@ -159,7 +159,7 @@ cdef class PowerSeries(AlgebraElement):
+              over Finite Field of size 3
+         """
+         AlgebraElement.__init__(self, parent)
+-        self.__is_gen = is_gen
++        self._is_gen = is_gen
+         self._prec = prec
+ 
+     def __hash__(self):
+@@ -234,7 +234,7 @@ cdef class PowerSeries(AlgebraElement):
+             sage: 1*t == t
+             True
+         """
+-        return bool(self.__is_gen)
++        return bool(self._is_gen)
+ 
+     def _im_gens_(self, codomain, im_gens, base_map=None):
+         """
+diff --git a/src/sage/rings/real_mpfi.pxd b/src/sage/rings/real_mpfi.pxd
+index 959a650aafc..4201788d198 100644
+--- a/src/sage/rings/real_mpfi.pxd
++++ b/src/sage/rings/real_mpfi.pxd
+@@ -11,7 +11,7 @@ from .real_mpfr cimport RealField_class
+ cdef class RealIntervalFieldElement(RingElement)  # forward decl
+ 
+ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+-    cdef mpfr_prec_t __prec
++    cdef mpfr_prec_t _prec
+     cdef bint sci_not
+     # Cache RealField instances for the lower, upper, and middle bounds.
+     # These have the same precision as the interval field;
+diff --git a/src/sage/rings/real_mpfi.pyx b/src/sage/rings/real_mpfi.pyx
+index 1193a14baff..509f6f63da0 100644
+--- a/src/sage/rings/real_mpfi.pyx
++++ b/src/sage/rings/real_mpfi.pyx
+@@ -526,7 +526,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         if prec < MPFR_PREC_MIN or prec > MPFR_PREC_MAX:
+             raise ValueError("prec (=%s) must be >= %s and <= %s." % (
+                 prec, MPFR_PREC_MIN, MPFR_PREC_MAX))
+-        self.__prec = prec
++        self._prec = prec
+         self.sci_not = sci_not
+         self.__lower_field = RealField(prec, sci_not, "RNDD")
+         self.__middle_field = RealField(prec, sci_not, "RNDN")
+@@ -598,7 +598,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         elif rnd == "RNDU":
+             return self.upper_field()
+         else:
+-            return RealField(self.__prec, self.sci_not, rnd)
++            return RealField(self._prec, self.sci_not, rnd)
+ 
+     def _repr_(self):
+         """
+@@ -611,7 +611,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RealIntervalField(200) # indirect doctest
+             Real Interval Field with 200 bits of precision
+         """
+-        s = "Real Interval Field with %s bits of precision"%self.__prec
++        s = "Real Interval Field with %s bits of precision"%self._prec
+         return s
+ 
+     def _latex_(self):
+@@ -802,7 +802,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RIF.has_coerce_map_from(float)
+             False
+         """
+-        prec = self.__prec
++        prec = self._prec
+ 
+         # Direct and efficient conversions
+         if S is ZZ or S is QQ:
+@@ -810,7 +810,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         if S is int or S is long:
+             return True
+         if isinstance(S, RealIntervalField_class):
+-            return (<RealIntervalField_class>S).__prec >= prec
++            return (<RealIntervalField_class>S)._prec >= prec
+         if isinstance(S, sage.rings.abc.NumberField_quadratic):
+             return S.discriminant() > 0
+ 
+@@ -844,7 +844,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         cdef RealIntervalField_class right
+         left = self
+         right = other  # to access C structure
+-        return richcmp(left.__prec, right.__prec, op)
++        return richcmp(left._prec, right._prec, op)
+ 
+     def __reduce__(self):
+         """
+@@ -856,7 +856,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: loads(dumps(R)) == R
+             True
+         """
+-        return __create__RealIntervalField_version0, (self.__prec, self.sci_not)
++        return __create__RealIntervalField_version0, (self._prec, self.sci_not)
+ 
+     def random_element(self, *args, **kwds):
+         """
+@@ -997,7 +997,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RealIntervalField(200).name()
+             'IntervalRealIntervalField200'
+         """
+-        return "IntervalRealIntervalField%s"%(self.__prec)
++        return "IntervalRealIntervalField%s"%(self._prec)
+ 
+     def __hash__(self):
+         """
+@@ -1023,7 +1023,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RealIntervalField(200).precision()
+             200
+         """
+-        return self.__prec
++        return self._prec
+ 
+     prec = precision
+ 
+@@ -1187,7 +1187,7 @@ cdef class RealIntervalFieldElement(RingElement):
+             sage: TestSuite(x).run(skip=["_test_eq", "_test_pickling"])
+         """
+         cdef RealIntervalField_class p = <RealIntervalField_class?>parent
+-        mpfi_init2(self.value, p.__prec)
++        mpfi_init2(self.value, p._prec)
+         self._parent = p
+ 
+     def __init__(self, parent, x, int base=10):
+@@ -1864,7 +1864,7 @@ cdef class RealIntervalFieldElement(RingElement):
+ 
+         cdef mp_exp_t self_exp
+         cdef mpz_t self_zz
+-        cdef mpfr_prec_t prec = (<RealIntervalField_class>self._parent).__prec
++        cdef mpfr_prec_t prec = (<RealIntervalField_class>self._parent)._prec
+         cdef char *zz_str
+         cdef size_t zz_str_maxlen
+ 
+@@ -2977,7 +2977,7 @@ cdef class RealIntervalFieldElement(RingElement):
+             sage: RealIntervalField(200)(2.1).precision()
+             200
+         """
+-        return (<RealIntervalField_class>self._parent).__prec
++        return (<RealIntervalField_class>self._parent)._prec
+ 
+     prec = precision
+ 
+diff --git a/src/sage/rings/real_mpfr.pxd b/src/sage/rings/real_mpfr.pxd
+index 3549eccfd03..dd18e87715b 100644
+--- a/src/sage/rings/real_mpfr.pxd
++++ b/src/sage/rings/real_mpfr.pxd
+@@ -9,7 +9,7 @@ from sage.libs.mpfr.types cimport mpfr_prec_t
+ cdef class RealNumber(sage.structure.element.RingElement)  # forward decl
+ 
+ cdef class RealField_class(sage.rings.abc.RealField):
+-    cdef mpfr_prec_t __prec
++    cdef mpfr_prec_t _prec
+     cdef bint sci_not
+     cdef mpfr_rnd_t rnd
+     cdef object rnd_str
+diff --git a/src/sage/rings/real_mpfr.pyx b/src/sage/rings/real_mpfr.pyx
+index ea7ff07a216..7440fadd265 100644
+--- a/src/sage/rings/real_mpfr.pyx
++++ b/src/sage/rings/real_mpfr.pyx
+@@ -524,7 +524,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+         if prec < MPFR_PREC_MIN or prec > MPFR_PREC_MAX:
+             raise ValueError("prec (=%s) must be >= %s and <= %s" % (
+                 prec, MPFR_PREC_MIN, MPFR_PREC_MAX))
+-        self.__prec = prec
++        self._prec = prec
+         self.sci_not = sci_not
+ 
+         self.rnd = <mpfr_rnd_t>rnd
+@@ -561,7 +561,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: RealField(17,rnd='RNDD') # indirect doctest
+             Real Field with 17 bits of precision and rounding RNDD
+         """
+-        s = "Real Field with %s bits of precision"%self.__prec
++        s = "Real Field with %s bits of precision"%self._prec
+         if self.rnd != MPFR_RNDN:
+             s = s + " and rounding %s"%(self.rnd_str)
+         return s
+@@ -733,13 +733,13 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             return ZZtoRR(ZZ, self)
+         elif S is QQ:
+             return QQtoRR(QQ, self)
+-        elif (S is RDF or S is float) and self.__prec <= 53:
++        elif (S is RDF or S is float) and self._prec <= 53:
+             return double_toRR(S, self)
+         elif S is long:
+             return int_toRR(long, self)
+         elif S is int:
+             return int_toRR(int, self)
+-        elif isinstance(S, RealField_class) and S.prec() >= self.__prec:
++        elif isinstance(S, RealField_class) and S.prec() >= self._prec:
+             return RRtoRR(S, self)
+         elif QQ.has_coerce_map_from(S):
+             return QQtoRR(QQ, self) * QQ._internal_coerce_map_from(S)
+@@ -786,7 +786,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             return NotImplemented
+ 
+         _other = <RealField_class>other  # to access C structure
+-        return (self.__prec == _other.__prec and
++        return (self._prec == _other._prec and
+                 self.rnd == _other.rnd) == (op == Py_EQ)
+ 
+     def __reduce__(self):
+@@ -799,7 +799,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: loads(dumps(R)) == R
+             True
+         """
+-        return __create__RealField_version0, (self.__prec, self.sci_not, self.rnd_str)
++        return __create__RealField_version0, (self._prec, self.sci_not, self.rnd_str)
+ 
+     def construction(self):
+         r"""
+@@ -968,7 +968,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: RealField(100,rnd='RNDU').name()
+             'RealField100_2'
+         """
+-        return "RealField%s_%s"%(self.__prec,self.rnd)
++        return "RealField%s_%s"%(self._prec,self.rnd)
+ 
+     def __hash__(self):
+         """
+@@ -995,7 +995,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: RealField(20).precision()
+             20
+         """
+-        return Integer(self.__prec)
++        return Integer(self._prec)
+ 
+     prec=precision # an alias
+ 
+@@ -1031,7 +1031,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: R.to_prec(300)
+             Real Field with 300 bits of precision and rounding RNDZ
+         """
+-        if prec == self.__prec:
++        if prec == self._prec:
+             return self
+         else:
+             return RealField(prec, self.sci_not, self.rnd)
+@@ -1052,7 +1052,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             0.88622692545275801364908374167057259139877473
+         """
+         cdef RealNumber x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD: sig_on()
+         # The docs for mpfr_free_cache say "Free the cache used by
+         # the functions computing constants if needed (currently
+         # mpfr_const_log2, mpfr_const_pi and mpfr_const_euler)", so
+@@ -1062,7 +1062,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+         # functions, but this free is needed for them too!
+         mpfr_free_cache()
+         mpfr_const_pi(x.value, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def euler_constant(self):
+@@ -1091,10 +1091,10 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             0.91596559417721901505460351493
+         """
+         cdef RealNumber x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_free_cache()
+         mpfr_const_catalan(x.value, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log2(self):
+@@ -1111,10 +1111,10 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             0.69314718055994530941723212146
+         """
+         cdef RealNumber x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_free_cache()
+         mpfr_const_log2(x.value, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def random_element(self, min=-1, max=1, distribution=None):
+@@ -1181,9 +1181,9 @@ cdef class RealField_class(sage.rings.abc.RealField):
+         if n < 0:
+             raise ArithmeticError("n must be nonnegative")
+         x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_on()
+         mpfr_fac_ui(x.value, n, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def rounding_mode(self):
+@@ -1346,7 +1346,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             NaN
+         """
+         cdef RealField_class p = <RealField_class?>parent
+-        mpfr_init2(self.value, p.__prec)
++        mpfr_init2(self.value, p._prec)
+         self._parent = p
+ 
+     def __init__(self, parent, x=0, int base=10):
+@@ -1446,7 +1446,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             sage: numpy.array([1.000000000000000000000000000000000000]).dtype           # optional - numpy
+             dtype('O')
+         """
+-        if (<RealField_class>self._parent).__prec <= 53:
++        if (<RealField_class>self._parent)._prec <= 53:
+             return numpy_double_interface
+         else:
+             return numpy_object_interface
+@@ -2075,7 +2075,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             # This avoids the confusion a lot of people have with the last
+             # 1-2 binary digits being wrong due to rounding coming from
+             # representing numbers in binary.
+-            digits = <size_t>(((<RealField_class>self._parent).__prec - 1) * M_LN2_LN10)
++            digits = <size_t>(((<RealField_class>self._parent)._prec - 1) * M_LN2_LN10)
+             if digits < 2:
+                 digits = 2
+ 
+@@ -2303,7 +2303,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if sgn == 0:
+             return z
+ 
+-        cdef mpfr_prec_t prec = (<RealField_class>self._parent).__prec
++        cdef mpfr_prec_t prec = (<RealField_class>self._parent)._prec
+ 
+         if mpfr_inf_p(self.value):
+             mpz_set_ui(z.value, EXP_MAX+1-EXP_MIN)
+@@ -2757,7 +2757,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             sage: RealField(101)(-1).precision()
+             101
+         """
+-        return Integer((<RealField_class>self._parent).__prec)
++        return Integer((<RealField_class>self._parent)._prec)
+ 
+     prec = precision # alias
+ 
+@@ -3364,7 +3364,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         cdef unsigned long wordsize = sizeof(long)*8
+ 
+         cdef mpfr_prec_t prec
+-        prec = (<RealField_class>self._parent).__prec
++        prec = (<RealField_class>self._parent)._prec
+ 
+         # We round up the precision to the nearest multiple of wordsize.
+         cdef int rounded_prec
+@@ -3699,7 +3699,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         from .real_mpfi import RealIntervalField
+ 
+         cdef mpfr_rnd_t rnd = (<RealField_class>self._parent).rnd
+-        cdef mpfr_prec_t prec = (<RealField_class>self._parent).__prec
++        cdef mpfr_prec_t prec = (<RealField_class>self._parent)._prec
+ 
+         cdef RealNumber low, high
+         cdef int odd
+@@ -4249,9 +4249,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         cdef RealNumber x
+         if mpfr_cmp_ui(self.value, 0) >= 0:
+             x = self._new()
+-            if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_on()
++            if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_on()
+             mpfr_sqrt(x.value, self.value, (<RealField_class>self._parent).rnd)
+-            if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_off()
++            if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_off()
+             if all:
+                 if x.is_zero():
+                     return [x]
+@@ -4295,12 +4295,12 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             -1.42108547152020e-14
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_on()
+         mpfr_cbrt(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+-    def __pow(self, RealNumber exponent):
++    def _pow(self, RealNumber exponent):
+         """
+         Compute ``self`` raised to the power of exponent, rounded in the
+         direction specified by the parent of ``self``.
+@@ -4309,7 +4309,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+ 
+             sage: R = RealField(30)
+             sage: a = R('1.23456')
+-            sage: a.__pow(20.0)
++            sage: a._pow(20.0)
+             67.646297
+         """
+         cdef RealNumber x
+@@ -4435,9 +4435,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+                 return self._complex_number_().log(base)
+         if base is None or base == 'e':
+             x = self._new()
+-            if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++            if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+             mpfr_log(x.value, self.value, (<RealField_class>self._parent).rnd)
+-            if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++            if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+             return x
+         elif base == 10:
+             return self.log10()
+@@ -4476,9 +4476,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if self < 0:
+             return self._complex_number_().log(2)
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_log2(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log10(self):
+@@ -4513,9 +4513,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if self < 0:
+             return self._complex_number_().log(10)
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_log10(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log1p(self):
+@@ -4562,9 +4562,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if self < -1:
+             return (self+1.0)._complex_number_().log()
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_log1p(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def exp(self):
+@@ -4620,9 +4620,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             1.89117248253021e-10
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_exp2(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def exp10(self):
+@@ -4648,9 +4648,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             5.01187233627276e-33
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_exp10(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def expm1(self):
+@@ -4672,9 +4672,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             1.00000000000000e-16
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_expm1(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def eint(self):
+@@ -4694,9 +4694,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             -0.219383934395520
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_eint(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         return x
+ 
+     def cos(self):
+@@ -5125,9 +5125,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             _other = self._parent(other)
+ 
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > 10000: sig_on()
++        if (<RealField_class>self._parent)._prec > 10000: sig_on()
+         mpfr_agm(x.value, self.value, _other.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > 10000: sig_off()
++        if (<RealField_class>self._parent)._prec > 10000: sig_off()
+         return x
+ 
+     def erf(self):
+@@ -5280,9 +5280,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             0.886226925452758
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_gamma(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log_gamma(self):
+@@ -5306,10 +5306,10 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         cdef RealNumber x = self._new()
+         parent = (<RealField_class>self._parent)
+         if not mpfr_sgn(self.value) < 0:
+-            if parent.__prec > SIG_PREC_THRESHOLD:
++            if parent._prec > SIG_PREC_THRESHOLD:
+                 sig_on()
+             mpfr_lngamma(x.value, self.value, parent.rnd)
+-            if parent.__prec > SIG_PREC_THRESHOLD:
++            if parent._prec > SIG_PREC_THRESHOLD:
+                 sig_off()
+             return x
+         from sage.libs.mpmath.utils import call
+@@ -5534,7 +5534,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+ 
+         cdef RealField_class fld = <RealField_class>self._parent
+ 
+-        if algorithm == 0 and n <= 10000 / fld.__prec:
++        if algorithm == 0 and n <= 10000 / fld._prec:
+             # This is a rough estimate for when it is probably
+             # faster to call mpfr directly.  (This is a pretty
+             # good estimate on one particular machine, a
+@@ -5639,7 +5639,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+ 
+         from .real_mpfi import RealIntervalField
+ 
+-        cdef mpfr_prec_t prec = fld.__prec + 10
++        cdef mpfr_prec_t prec = fld._prec + 10
+ 
+         cdef RealNumber lower
+         cdef RealNumber upper
+diff --git a/src/sage/rings/ring.pxd b/src/sage/rings/ring.pxd
+index 9384f39f258..1322697688f 100644
+--- a/src/sage/rings/ring.pxd
++++ b/src/sage/rings/ring.pxd
+@@ -7,7 +7,7 @@ cdef class Ring(ParentWithGens):
+     cdef public object _one_element
+     cdef public object _zero_ideal
+     cdef public object _unit_ideal
+-    cdef public object __ideal_monoid
++    cdef public object _ideal_monoid
+ 
+ 
+ cdef class CommutativeRing(Ring):
+diff --git a/src/sage/rings/ring.pyx b/src/sage/rings/ring.pyx
+index 4cba2c9ba7f..8acf4383270 100644
+--- a/src/sage/rings/ring.pyx
++++ b/src/sage/rings/ring.pyx
+@@ -325,12 +325,12 @@ cdef class Ring(ParentWithGens):
+              by the ideal (x*y + y*z, x*x + x*y - y*x - y*y)
+ 
+         """
+-        if self.__ideal_monoid is not None:
+-            return self.__ideal_monoid
++        if self._ideal_monoid is not None:
++            return self._ideal_monoid
+         else:
+             from sage.rings.noncommutative_ideals import IdealMonoid_nc
+             M = IdealMonoid_nc(self)
+-            self.__ideal_monoid = M
++            self._ideal_monoid = M
+             return M
+ 
+     def ideal(self, *args, **kwds):
+@@ -1106,12 +1106,12 @@ cdef class Ring(ParentWithGens):
+             sage: R.<x>=QQ[]; R.ideal_monoid()
+             Monoid of ideals of Univariate Polynomial Ring in x over Rational Field
+         """
+-        if self.__ideal_monoid is not None:
+-            return self.__ideal_monoid
++        if self._ideal_monoid is not None:
++            return self._ideal_monoid
+         else:
+             from sage.rings.ideal_monoid import IdealMonoid
+             M = IdealMonoid(self)
+-            self.__ideal_monoid = M
++            self._ideal_monoid = M
+             return M
+ 
+     @cached_method
+@@ -1345,12 +1345,12 @@ cdef class CommutativeRing(Ring):
+             sage: R.<x>=QQ[]; R.ideal_monoid()
+             Monoid of ideals of Univariate Polynomial Ring in x over Rational Field
+         """
+-        if self.__ideal_monoid is not None:
+-            return self.__ideal_monoid
++        if self._ideal_monoid is not None:
++            return self._ideal_monoid
+         else:
+             from sage.rings.ideal_monoid import IdealMonoid
+             M = IdealMonoid(self)
+-            self.__ideal_monoid = M
++            self._ideal_monoid = M
+             return M
+ 
+     def extension(self, poly, name=None, names=None, **kwds):
+diff --git a/src/sage/schemes/elliptic_curves/mod_sym_num.pyx b/src/sage/schemes/elliptic_curves/mod_sym_num.pyx
+index 65742f28d72..296a6b5d075 100644
+--- a/src/sage/schemes/elliptic_curves/mod_sym_num.pyx
++++ b/src/sage/schemes/elliptic_curves/mod_sym_num.pyx
+@@ -730,7 +730,7 @@ cdef class ModularSymbolNumerical:
+         double _eps_plus, _eps_minus, _eps_unitary_plus, _eps_unitary_minus
+         public RealNumber _om1, _om2
+         object _E, _epsQs, _Mt, _Epari
+-        public dict __cached_methods
++        public dict _cached_methods
+         Rational _twist_q
+         Integer _D
+         int _global_sign
+@@ -785,7 +785,7 @@ cdef class ModularSymbolNumerical:
+         self._set_epsQs()
+         self._initialise_an_coefficients()
+         self._set_den_bounds()
+-        self.__cached_methods = {}
++        self._cached_methods = {}
+ 
+         # self.nc_sums = Integer(0)
+         # self.nc_direct = Integer(0)
+@@ -1357,7 +1357,7 @@ cdef class ModularSymbolNumerical:
+             sage: M(0)
+             1/5
+         """
+-        cadi = self.__cached_methods
++        cadi = self._cached_methods
+         for me in cadi:
+             cadi[me].clear_cache()
+ 
+@@ -1833,7 +1833,7 @@ cdef class ModularSymbolNumerical:
+ 
+         # if called with a previous (m,z,eps) but a larger eps,
+         # return the cached value
+-        cac = self.__cached_methods['_kappa'].cache
++        cac = self._cached_methods['_kappa'].cache
+         for ke in cac:
+             mm, zz, eeps = ke[0]
+             if mm == m and zz == z:
+@@ -2746,16 +2746,16 @@ cdef class ModularSymbolNumerical:
+             sage: ms = ModularSymbolNumerical(E)
+             sage: ms.manin_symbol(4,17)
+             1
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache # random
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache # random
+             {((1, 5, 1), ()): 1,
+             ((1, 15, 1), ()): -1,
+             ((1, 22, 1), ()): -1,
+             ((1, 32, 1), ()): 1}
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache[(1,15,1),()]
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache[(1,15,1),()]
+             -1
+             sage: ms.manin_symbol(4+17,-4)
+             0
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache # random
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache # random
+             {((1, 4, 1), ()): 0,
+             ((1, 5, 1), ()): 1,
+             ((1, 8, 1), ()): 1,
+@@ -2768,7 +2768,7 @@ cdef class ModularSymbolNumerical:
+             ((1, 29, 1), ()): 1,
+             ((1, 32, 1), ()): 1,
+             ((1, 33, 1), ()): 0}
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache[ (1,23,1), () ]
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache[ (1,23,1), () ]
+             -1
+         """
+         cdef:
+@@ -2903,7 +2903,7 @@ cdef class ModularSymbolNumerical:
+         #        "(%s :%s)"%(un, vn), level=3)
+ 
+         # is it already in the cache ?
+-        c = self.__cached_methods
++        c = self._cached_methods
+         if "_manin_symbol_with_cache" in c:
+             c = c["_manin_symbol_with_cache"]
+             if c.is_in_cache(un,vn,sign):
+@@ -2919,7 +2919,7 @@ cdef class ModularSymbolNumerical:
+         # we get for free additional values of Manin
+         # symbols that we cache, too.
+         # This sets 6 values in average
+-        c = self.__cached_methods["_manin_symbol_with_cache"]
++        c = self._cached_methods["_manin_symbol_with_cache"]
+ 
+         # (-v:u) = - (u:v)
+         oi = proj_normalise(self._N_E, -v, u, &un, &vn)
+diff --git a/src/sage/sets/set_from_iterator.py b/src/sage/sets/set_from_iterator.py
+index c47bb76920b..11f12e6d5ea 100644
+--- a/src/sage/sets/set_from_iterator.py
++++ b/src/sage/sets/set_from_iterator.py
+@@ -214,12 +214,12 @@ def __reduce__(self):
+             True
+         """
+         return (EnumeratedSetFromIterator,
+-                (self._func,                            # func
+-                 getattr(self, '_args', None),          # args
+-                 getattr(self, '_kwds', None),          # kwds
+-                 getattr(self, '__custom_name', None),  # name
+-                 self.category(),                       # category
+-                 hasattr(self, '_cache'))               # cache
++                (self._func,                    # func
++                 getattr(self, '_args', None),  # args
++                 getattr(self, '_kwds', None),  # kwds
++                 self.get_custom_name(),        # name
++                 self.category(),               # category
++                 hasattr(self, '_cache'))       # cache
+                 )
+ 
+     def _repr_(self):
+diff --git a/src/sage/structure/category_object.pxd b/src/sage/structure/category_object.pxd
+index ff3088ae9b6..83d3d4967d4 100644
+--- a/src/sage/structure/category_object.pxd
++++ b/src/sage/structure/category_object.pxd
+@@ -13,7 +13,7 @@ from sage.structure.sage_object cimport SageObject
+ cpdef check_default_category(default_category, category)
+ 
+ cdef class CategoryObject(SageObject):
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+     cdef _category
+     cdef public _base
+     cdef public _names
+diff --git a/src/sage/structure/category_object.pyx b/src/sage/structure/category_object.pyx
+index 3859f24095a..b6a7eaecb5b 100644
+--- a/src/sage/structure/category_object.pyx
++++ b/src/sage/structure/category_object.pyx
+@@ -113,7 +113,7 @@ cdef class CategoryObject(SageObject):
+             self._init_category_(category)
+ 
+     def __cinit__(self):
+-        self.__cached_methods = {}
++        self._cached_methods = {}
+         self._hash_value = -1
+ 
+     def _init_category_(self, category):
+@@ -491,7 +491,7 @@ cdef class CategoryObject(SageObject):
+         """
+         return self.variable_names()[0]
+ 
+-    def __temporarily_change_names(self, names, latex_names):
++    def _temporarily_change_names(self, names, latex_names):
+         """
+         This is used by the variable names context manager.
+ 
+@@ -844,7 +844,7 @@ cdef class CategoryObject(SageObject):
+         # Lookup a method or attribute from the category abstract classes.
+         # See __getattr__ above for documentation.
+         try:
+-            return self.__cached_methods[name]
++            return self._cached_methods[name]
+         except KeyError:
+             if self._category is None:
+                 # Usually, this will just raise AttributeError in
+@@ -854,7 +854,7 @@ cdef class CategoryObject(SageObject):
+                 cls = self._category.parent_class
+ 
+             attr = getattr_from_other_class(self, cls, name)
+-            self.__cached_methods[name] = attr
++            self._cached_methods[name] = attr
+             return attr
+ 
+     def __dir__(self):
+diff --git a/src/sage/structure/element.pxd b/src/sage/structure/element.pxd
+index 79e86d8a5c3..20c556b985e 100644
+--- a/src/sage/structure/element.pxd
++++ b/src/sage/structure/element.pxd
+@@ -176,7 +176,7 @@ cdef class Element(SageObject):
+ 
+ 
+ cdef class ElementWithCachedMethod(Element):
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+ cdef class ModuleElement(Element)       # forward declaration
+ 
+diff --git a/src/sage/structure/element.pyx b/src/sage/structure/element.pyx
+index ab6ee157a94..36da1c0cc12 100644
+--- a/src/sage/structure/element.pyx
++++ b/src/sage/structure/element.pyx
+@@ -379,6 +379,7 @@ cdef class Element(SageObject):
+     .. automethod:: __mod__
+     """
+     @cython.binding(False)
++    @cython.always_allow_keywords(False)
+     def __getmetaclass__(_):
+         from sage.misc.inherit_comparison import InheritComparisonMetaclass
+         return InheritComparisonMetaclass
+@@ -2356,18 +2357,18 @@ cdef class ElementWithCachedMethod(Element):
+             True
+         """
+         try:
+-            return self.__cached_methods[name]
++            return self._cached_methods[name]
+         except KeyError:
+             attr = getattr_from_other_class(self,
+                                         self._parent.category().element_class,
+                                         name)
+-            self.__cached_methods[name] = attr
++            self._cached_methods[name] = attr
+             return attr
+         except TypeError:
+             attr = getattr_from_other_class(self,
+                                         self._parent.category().element_class,
+                                         name)
+-            self.__cached_methods = {name : attr}
++            self._cached_methods = {name : attr}
+             return attr
+ 
+ 
+diff --git a/src/sage/structure/parent_gens.pyx b/src/sage/structure/parent_gens.pyx
+index ab531314458..cc6ffaace21 100644
+--- a/src/sage/structure/parent_gens.pyx
++++ b/src/sage/structure/parent_gens.pyx
+@@ -371,7 +371,7 @@ cdef class localvars:
+             self._latex_names = latex_names
+ 
+     def __enter__(self):
+-        self._orig = self._obj.__temporarily_change_names(self._names, self._latex_names)
++        self._orig = self._obj._temporarily_change_names(self._names, self._latex_names)
+ 
+     def __exit__(self, type, value, traceback):
+-        self._obj.__temporarily_change_names(self._orig[0], self._orig[1])
++        self._obj._temporarily_change_names(self._orig[0], self._orig[1])
+diff --git a/src/sage/structure/sage_object.pyx b/src/sage/structure/sage_object.pyx
+index 8474142eaa1..10000aef394 100644
+--- a/src/sage/structure/sage_object.pyx
++++ b/src/sage/structure/sage_object.pyx
+@@ -69,6 +69,8 @@ cdef class SageObject:
+         r"""
+         Change self so it prints as x, where x is a string.
+ 
++        If x is ``None``, the existing custom name is removed.
++
+         .. NOTE::
+ 
+            This is *only* supported for Python classes that derive
+@@ -91,6 +93,9 @@ cdef class SageObject:
+             sage: h.rename('x^300 + ...')
+             sage: h
+             x^300 + ...
++            sage: g.rename(None)
++            sage: g
++            x^3 + x - 5
+ 
+         Real numbers are not Python classes, so rename is not supported::
+ 
+@@ -110,15 +115,16 @@ cdef class SageObject:
+            a lot of memory.
+ 
+            To support them for a specific class, add a
+-           ``cdef public __custom_name`` attribute.
++           ``cdef public _SageObject__custom_name`` attribute.
+         """
+         if x is None:
+-            #if hasattr(self, '__custom_name'):
+-            # that's tested in reset_name anyway...
+             self.reset_name()
+         else:
+             try:
+-                self.__custom_name = str(x)
++                # TODO: after dropping support for Cython < 3.0.0, all
++                # the self._SageObject__custom_name in this class can be
++                # changed to self.__custom_name
++                self._SageObject__custom_name = str(x)
+             except AttributeError:
+                 raise NotImplementedError("object does not support renaming: %s" % self)
+ 
+@@ -138,8 +144,30 @@ cdef class SageObject:
+             sage: P
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if hasattr(self, '__custom_name'):
+-            del self.__custom_name
++        if hasattr(self, '_SageObject__custom_name'):
++            del self._SageObject__custom_name
++
++    def get_custom_name(self):
++        """
++        Return the custom name of this object, or ``None`` if it is not
++        renamed.
++
++        EXAMPLES::
++
++            sage: P.<x> = QQ[]
++            sage: P.get_custom_name() is None
++            True
++            sage: P.rename('A polynomial ring')
++            sage: P.get_custom_name()
++            'A polynomial ring'
++            sage: P.reset_name()
++            sage: P.get_custom_name() is None
++            True
++        """
++        try:
++            return self._SageObject__custom_name
++        except AttributeError:
++            return None
+ 
+     def __repr__(self):
+         """
+@@ -181,7 +209,7 @@ cdef class SageObject:
+             <sage.structure.sage_object.SageObject object at ...>
+         """
+         try:
+-            name = self.__custom_name
++            name = self._SageObject__custom_name
+             if name is not None:
+                 return name
+         except AttributeError:
+diff --git a/src/sage/topology/simplicial_set.py b/src/sage/topology/simplicial_set.py
+index 42cc3f77780..3ee14ae2da8 100644
+--- a/src/sage/topology/simplicial_set.py
++++ b/src/sage/topology/simplicial_set.py
+@@ -570,13 +570,12 @@ def __lt__(self, other):
+             return True
+         if self.degeneracies() and other.degeneracies() and self.degeneracies() != other.degeneracies():
+             return self.degeneracies() < other.degeneracies()
+-        if hasattr(self.nondegenerate(), '__custom_name'):
+-            if hasattr(other.nondegenerate(), '__custom_name'):
+-                return str(self) < str(other)
++        if self.nondegenerate().get_custom_name() is not None:
++            if other.nondegenerate().get_custom_name() is not None:
++                return self.nondegenerate().get_custom_name() < other.nondegenerate().get_custom_name()
+             return True
+ 
+-        if (hasattr(other, '__custom_name')
+-                or hasattr(other.nondegenerate(), '__custom_name')):
++        if other.nondegenerate().get_custom_name() is not None:
+             return False
+         return id(self) < id(other)
+ 
+@@ -793,8 +792,8 @@ def __copy__(self):
+         # dimension, the degeneracies, and the name (with a prime
+         # added).
+         sigma = AbstractSimplex(self._dim, degeneracies=self.degeneracies())
+-        if hasattr(self, '__custom_name'):
+-            sigma.rename(str(self) + "'")
++        if self.get_custom_name() is not None:
++            sigma.rename(self.get_custom_name() + "'")
+         return sigma
+ 
+     def __deepcopy__(self, memo):
+@@ -839,8 +838,8 @@ def __deepcopy__(self, memo):
+             return memo[underlying].apply_degeneracies(*degens)
+         except KeyError:
+             sigma = AbstractSimplex(underlying._dim)
+-            if hasattr(underlying, '__custom_name'):
+-                sigma.rename(str(self) + "'")
++            if underlying.get_custom_name() is not None:
++                sigma.rename(underlying.get_custom_name() + "'")
+             memo[underlying] = sigma
+             return sigma.apply_degeneracies(*degens)
+ 
+@@ -896,12 +895,12 @@ def _latex_(self):
+         """
+         if self._latex_name is not None:
+             return self._latex_name
+-        if hasattr(self, '__custom_name'):
+-            return str(self)
++        if self.get_custom_name() is not None:
++            return self.get_custom_name()
+         if self.nondegenerate()._latex_name is not None:
+             simplex = self.nondegenerate()._latex_name
+-        elif hasattr(self.nondegenerate(), '__custom_name'):
+-            simplex = str(self.nondegenerate())
++        elif self.nondegenerate().get_custom_name() is not None:
++            simplex = self.nondegenerate().get_custom_name()
+         else:
+             simplex = "\\Delta^{{{}}}".format(self._dim)
+         if self.degeneracies():
+diff --git a/src/sage/topology/simplicial_set_constructions.py b/src/sage/topology/simplicial_set_constructions.py
+index ae98821df8a..3a217286ac5 100644
+--- a/src/sage/topology/simplicial_set_constructions.py
++++ b/src/sage/topology/simplicial_set_constructions.py
+@@ -176,8 +176,7 @@ def __init__(self, data, ambient=None):
+         else:
+             SimplicialSet_finite.__init__(self, data)
+         if self == ambient:
+-            if hasattr(ambient, '__custom_name'):
+-                self.rename(str(ambient))
++            self.rename(ambient.get_custom_name())
+             self._latex_name = latex(ambient)
+         # When constructing the inclusion map, we do not need to check
+         # the validity of the morphism, and more importantly, we
diff --git a/srcpkgs/sagemath/patches/build-cython3.patch b/srcpkgs/sagemath/patches/build-cython3.patch
new file mode 100644
index 0000000000000..57d1ade89fc77
--- /dev/null
+++ b/srcpkgs/sagemath/patches/build-cython3.patch
@@ -0,0 +1,44 @@
+diff --git a/src/sage/ext/stdsage.pxd b/src/sage/ext/stdsage.pxd
+index 15abe13b7cd..e2bf7434f35 100644
+--- a/src/sage/ext/stdsage.pxd
++++ b/src/sage/ext/stdsage.pxd
+@@ -10,7 +10,7 @@ Standard C helper code for Cython modules
+ #                  http://www.gnu.org/licenses/
+ #*****************************************************************************
+ 
+-from cpython.object cimport Py_TYPE, PyTypeObject
++from cpython.object cimport Py_TYPE, PyTypeObject, PyObject
+ 
+ 
+ cdef inline PY_NEW(type t):
+@@ -19,7 +19,7 @@ cdef inline PY_NEW(type t):
+     :class:`Integer` where we change ``tp_new`` at runtime (Cython
+     optimizations assume that ``tp_new`` doesn't change).
+     """
+-    return (<PyTypeObject*>t).tp_new(t, <object>NULL, <object>NULL)
++    return (<PyTypeObject*>t).tp_new(t, <PyObject*>NULL, <PyObject*>NULL)
+ 
+ 
+ cdef inline void PY_SET_TP_NEW(type dst, type src):
+diff --git a/src/sage_setup/cython_options.py b/src/sage_setup/cython_options.py
+index 086aa070ca9..9725ce0e1af 100644
+--- a/src/sage_setup/cython_options.py
++++ b/src/sage_setup/cython_options.py
+@@ -10,13 +10,17 @@ def compiler_directives(profile: bool):
+         auto_pickle=False,
+         # Do not create __test__ dictionary automatically from docstrings
+         autotestdict=False,
++        binding=False,
++        c_api_binop_methods=True,
+         # Do not check for division by 0 (this is about 35% quicker than with check)
+         cdivision=True,
++        cpow=True,
+         # Embed a textual copy of the call signature in the docstring (to support tools like IPython)
+         embedsignature=True,
+         fast_getattr=True,
+         # Use Python 3 (including source code semantics) for module compilation
+         language_level="3",
++        legacy_implicit_noexcept=True,
+         # Enable support for late includes (make declarations in Cython code available to C include files)
+         preliminary_late_includes_cy28=True,
+         # Add hooks for Python profilers into the compiled C code
diff --git a/srcpkgs/sagemath/patches/fix-doctest-cython3.patch b/srcpkgs/sagemath/patches/fix-doctest-cython3.patch
new file mode 100644
index 0000000000000..4cff1fb1828db
--- /dev/null
+++ b/srcpkgs/sagemath/patches/fix-doctest-cython3.patch
@@ -0,0 +1,207 @@
+diff --git a/src/doc/en/thematic_tutorials/coercion_and_categories.rst b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+index de2349a9a3f..bb23331c151 100644
+--- a/src/doc/en/thematic_tutorials/coercion_and_categories.rst
++++ b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+@@ -105,7 +105,7 @@ it makes sense to build on top of the base class
+ This base class provides a lot more methods than a general parent::
+ 
+     sage: [p for p in dir(Field) if p not in dir(Parent)]
+-    ['__fraction_field',
++    ['_CommutativeRing__fraction_field',
+      '__iter__',
+      '__len__',
+      '__rxor__',
+diff --git a/src/sage/arith/srange.pyx b/src/sage/arith/srange.pyx
+index 156e548a11a..132cf93d085 100644
+--- a/src/sage/arith/srange.pyx
++++ b/src/sage/arith/srange.pyx
+@@ -84,7 +84,7 @@ def xsrange(start, end=None, step=1, universe=None, *, coerce=True, bint include
+     EXAMPLES::
+ 
+         sage: xsrange(10)
+-        <generator object at 0x...>
++        <...generator object at 0x...>
+         sage: for i in xsrange(1,5):
+         ....:     print(i)
+         1
+diff --git a/src/sage/combinat/sloane_functions.py b/src/sage/combinat/sloane_functions.py
+index c3cf9299093..e5c99b71fe7 100644
+--- a/src/sage/combinat/sloane_functions.py
++++ b/src/sage/combinat/sloane_functions.py
+@@ -9169,7 +9169,7 @@ class Sloane(SageObject):
+         ::
+ 
+             sage: sloane.__repr__
+-            <method-wrapper '__repr__' of Sloane object at 0x...>
++            <built-in method __repr__ of Sloane object at 0x...>
+             sage: sloane.__name__
+             Traceback (most recent call last):
+             ...
+diff --git a/src/sage/misc/cachefunc.pyx b/src/sage/misc/cachefunc.pyx
+index 8aa30a85272..2b1d38c12b9 100644
+--- a/src/sage/misc/cachefunc.pyx
++++ b/src/sage/misc/cachefunc.pyx
+@@ -50,7 +50,7 @@ be used::
+     sage: cython('''cpdef test_funct(x): return -x''')                          # optional - sage.misc.cython
+     sage: wrapped_funct = cached_function(test_funct, name='wrapped_funct')     # optional - sage.misc.cython
+     sage: wrapped_funct                                                         # optional - sage.misc.cython
+-    Cached version of <built-in function test_funct>
++    Cached version of <cyfunction test_funct at ...>
+     sage: wrapped_funct.__name__                                                # optional - sage.misc.cython
+     'wrapped_funct'
+     sage: wrapped_funct(5)                                                      # optional - sage.misc.cython
+@@ -82,9 +82,9 @@ approach is still needed for cpdef methods::
+     sage: cython(os.linesep.join(cython_code))                                  # optional - sage.misc.cython
+     sage: O = MyClass()                                                         # optional - sage.misc.cython
+     sage: O.direct_method                                                       # optional - sage.misc.cython
+-    Cached version of <method 'direct_method' of '...MyClass' objects>
++    Cached version of <cyfunction MyClass.direct_method at ...>
+     sage: O.wrapped_method                                                      # optional - sage.misc.cython
+-    Cached version of <built-in function test_meth>
++    Cached version of <cyfunction test_meth at ...>
+     sage: O.wrapped_method.__name__                                             # optional - sage.misc.cython
+     'wrapped_method'
+     sage: O.wrapped_method(5)                                                   # optional - sage.misc.cython
+@@ -270,6 +270,7 @@ Introspection works::
+         "some doc for a wrapped cython method"
+         return -x
+     sage: print(sage_getsource(O.direct_method))                                # optional - sage.misc.cython
++    @cached_method
+     def direct_method(self, x):
+         "Some doc for direct method"
+         return 2*x
+diff --git a/src/sage/misc/lazy_import.pyx b/src/sage/misc/lazy_import.pyx
+index c33a1e74efd..7fc73407ace 100644
+--- a/src/sage/misc/lazy_import.pyx
++++ b/src/sage/misc/lazy_import.pyx
+@@ -1095,7 +1095,7 @@ def lazy_import(module, names, as_=None, *,
+         sage: from sage.features import PythonModule
+         sage: lazy_import('ppl', 'equation', feature=PythonModule('ppl', spkg='pplpy', type='standard'))
+         sage: equation
+-        <built-in function equation>
++        <cyfunction equation at ...>
+         sage: lazy_import('PyNormaliz', 'NmzListConeProperties', feature=PythonModule('PyNormaliz', spkg='pynormaliz'))  # optional - pynormaliz
+         sage: NmzListConeProperties  # optional - pynormaliz
+         <built-in function NmzListConeProperties>
+diff --git a/src/sage/misc/lazy_list.pyx b/src/sage/misc/lazy_list.pyx
+index ba62c446b69..cd750933860 100644
+--- a/src/sage/misc/lazy_list.pyx
++++ b/src/sage/misc/lazy_list.pyx
+@@ -678,7 +678,7 @@ cdef class lazy_list_generic():
+             sage: from itertools import count
+             sage: from sage.misc.lazy_list import lazy_list
+             sage: iter(lazy_list(count()))
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+ 
+         ::
+ 
+diff --git a/src/sage/misc/sageinspect.py b/src/sage/misc/sageinspect.py
+index ce5e9987027..df8e6bf89ac 100644
+--- a/src/sage/misc/sageinspect.py
++++ b/src/sage/misc/sageinspect.py
+@@ -76,8 +76,8 @@ Cython functions::
+     sage: sage_getdoc(sage.rings.rational.make_rational).lstrip()
+     'Make a rational number ...'
+ 
+-    sage: sage_getsource(sage.rings.rational.make_rational)[4:]
+-    'make_rational(s):...'
++    sage: sage_getsource(sage.rings.rational.make_rational)
++    '@cython.binding(True)\ndef make_rational(s):...'
+ 
+ Python functions::
+ 
+diff --git a/src/sage/modules/free_module_element.pyx b/src/sage/modules/free_module_element.pyx
+index d5e8256b68c..c9af9bcbdf7 100644
+--- a/src/sage/modules/free_module_element.pyx
++++ b/src/sage/modules/free_module_element.pyx
+@@ -1634,7 +1634,7 @@ cdef class FreeModuleElement(Vector):   # abstract base class
+ 
+             sage: v = vector([1,2/3,pi])
+             sage: v.items()
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: list(v.items())
+             [(0, 1), (1, 2/3), (2, pi)]
+ 
+diff --git a/src/sage/rings/finite_rings/finite_field_base.pyx b/src/sage/rings/finite_rings/finite_field_base.pyx
+index 7e2eed91153..3a6db8995c6 100644
+--- a/src/sage/rings/finite_rings/finite_field_base.pyx
++++ b/src/sage/rings/finite_rings/finite_field_base.pyx
+@@ -328,7 +328,7 @@ cdef class FiniteField(Field):
+             sage: p = next_prime(2^64)
+             sage: k.<a> = FiniteField(p^2, impl="pari")
+             sage: it = iter(k); it
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: [next(it) for i in range(10)]
+             [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+ 
+diff --git a/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx b/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx
+index 41951687939..c6b67cba5fb 100644
+--- a/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx
++++ b/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx
+@@ -629,7 +629,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense):
+             sage: S.<x> = k['x',Frob]
+             sage: a = x^4 + 2*t*x^3 + 3*t^2*x^2 + (t^2 + t + 1)*x + 4*t + 3
+             sage: iter = a.right_irreducible_divisors(); iter
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+             sage: next(iter)   # random
+             x + 2*t^2 + 4*t + 4
+             sage: next(iter)   # random
+@@ -664,7 +664,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense):
+             sage: S.<x> = k['x',Frob]
+             sage: a = x^4 + 2*t*x^3 + 3*t^2*x^2 + (t^2 + t + 1)*x + 4*t + 3
+             sage: iter = a.left_irreducible_divisors(); iter
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+             sage: next(iter)  # random
+             x + 3*t + 3
+             sage: next(iter)  # random
+@@ -1052,7 +1052,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense):
+             sage: S.<x> = k['x',Frob]
+             sage: a = x^3 + (t^2 + 1)*x^2 + (2*t + 3)*x + t^2 + t + 2
+             sage: iter = a.factorizations(); iter
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+             sage: next(iter)   # random
+             (x + 3*t^2 + 4*t) * (x + 2*t^2) * (x + 4*t^2 + 4*t + 2)
+             sage: next(iter)   # random
+diff --git a/src/sage/structure/coerce_dict.pyx b/src/sage/structure/coerce_dict.pyx
+index a2e8443084c..ef86c6af35c 100644
+--- a/src/sage/structure/coerce_dict.pyx
++++ b/src/sage/structure/coerce_dict.pyx
+@@ -777,7 +777,7 @@ cdef class MonoDict:
+             sage: L[1] = None
+             sage: L[2] = True
+             sage: L.items()
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: sorted(L.items())
+             [(1, None), (2, True)]
+         """
+@@ -1452,7 +1452,7 @@ cdef class TripleDict:
+             sage: L = TripleDict()
+             sage: L[1,2,3] = None
+             sage: L.items()
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: list(L.items())
+             [((1, 2, 3), None)]
+         """
+diff --git a/src/sage/tests/cmdline.py b/src/sage/tests/cmdline.py
+index ad0c44aa274..f14cd2db768 100644
+--- a/src/sage/tests/cmdline.py
++++ b/src/sage/tests/cmdline.py
+@@ -491,9 +491,8 @@ def test_executable(args, input="", timeout=100.0, pydebug_ignore_warnings=False
+ 
+         sage: (out, err, ret) = test_executable(["sage", "--cython"])
+         sage: print(err)
+-        Cython (http://cython.org) is a compiler for code written in the
+-        Cython language.  Cython is based on Pyrex by Greg Ewing.
+         ...
++        cython: error: cython: Need at least one source file
+ 
+         sage: def has_tty():
+         ....:     try:
diff --git a/srcpkgs/sagemath/patches/get_patches b/srcpkgs/sagemath/patches/get_patches
index c2c5aa1c7eccd..8d50f9a3cd3b3 100755
--- a/srcpkgs/sagemath/patches/get_patches
+++ b/srcpkgs/sagemath/patches/get_patches
@@ -12,7 +12,7 @@ esac
 # get_pr <PR number> <description> [ext]
 get_pr() {
 	pr=$1
-	desc=$(echo "$2" | sed -e 's/ /_/g')
+	desc=$(echo "$2" | tr ' /' '_-')
 	ext=${3-diff}
 	$DO wget "$URL_BASE_PR$pr.$ext" -O "$pr-$desc.patch"
 }
@@ -24,6 +24,9 @@ cd $(dirname "$0")
 #get_pr  36018   "singular 4.3.2p4" # included in #35934
 get_pr  36046   "fix memory leak"
 
-# positive review
+# merged in 10.2.beta1
 get_pr  35934   "singular 4.3.2p7"
+get_pr  36109   "prepare for cython 3.0" # included in #36110
+
+# positive review
 get_pr  36006   "gmp 6.3.0"
diff --git a/srcpkgs/sagemath/template b/srcpkgs/sagemath/template
index 019ad37cb3a70..5d30bb0bfc163 100644
--- a/srcpkgs/sagemath/template
+++ b/srcpkgs/sagemath/template
@@ -1,12 +1,12 @@
 # Template file for 'sagemath'
 pkgname=sagemath
 version=10.1
-revision=2
+revision=3
 build_wrksrc=pkgs/sagemath-standard
 build_style=python3-module
 _bindir=/usr/lib/sagemath/$version/bin
 make_install_args="--install-scripts=$_bindir"
-hostmakedepends="m4 pkg-config python3-Cython0.29 python3-Jinja2
+hostmakedepends="m4 pkg-config python3-Cython python3-Jinja2
  python3-pkgconfig python3-setuptools"
 makedepends="arb-devel boost-devel brial-devel cliquer-devel ecl eclib-devel
  ecm-devel fflas-ffpack flintlib-devel gap-devel gd-devel giac-devel glpk-devel
@@ -18,7 +18,7 @@ makedepends="arb-devel boost-devel brial-devel cliquer-devel ecl eclib-devel
 depends="eclib-devel fflas-ffpack flintlib-devel gcc-fortran gd-devel
  gfan giac gsl-devel gzip libpng-devel linbox-devel m4ri-devel maxima-ecl
  mpfr-devel nauty ntl-devel palp pari-devel pari-elldata-small pari-galdata
- pari-galpol-small pari-seadata-small pkg-config python3-Cython0.29 python3-cypari2
+ pari-galpol-small pari-seadata-small pkg-config python3-Cython python3-cypari2
  python3-cysignals python3-devel python3-fpylll python3-ipython python3-lrcalc
  python3-ipython_ipykernel python3-jupyter_ipywidgets python3-matplotlib
  python3-memory_allocator python3-networkx python3-pip python3-pkgconfig

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
                   ` (6 preceding siblings ...)
  2023-09-05 11:57 ` [PR PATCH] [Updated] " tornaria
@ 2023-09-06 14:50 ` ahesford
  2023-09-07  1:32 ` ahesford
                   ` (8 subsequent siblings)
  16 siblings, 0 replies; 18+ messages in thread
From: ahesford @ 2023-09-06 14:50 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 854 bytes --]

New comment by ahesford on void-packages repository

https://github.com/void-linux/void-packages/pull/45887#issuecomment-1708523022

Comment:
[I thought I already posted a response, but it seems lost to the ether.]

I understand that Sage built with Cython 0.29 is broken with Cython 3.0, but my point was that you can easily swap between installed Cython versions to test a locally built Sage with these patches. 

The general policy for patches is that they should be limited to critical fixes in advance of an official release or correct an incompatibility introduced by our own packaging choices (*e.g.*, to support special aspects of our cross building). New features, even when merged upstream, should wait until an official release introduces them. This is particularly true here, where the patches to add support are more than 9k lines long.

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
                   ` (7 preceding siblings ...)
  2023-09-06 14:50 ` ahesford
@ 2023-09-07  1:32 ` ahesford
  2023-09-09 15:33 ` tornaria
                   ` (7 subsequent siblings)
  16 siblings, 0 replies; 18+ messages in thread
From: ahesford @ 2023-09-07  1:32 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 349 bytes --]

New comment by ahesford on void-packages repository

https://github.com/void-linux/void-packages/pull/45887#issuecomment-1709334226

Comment:
After an out-of-band discussion about this PR, I am less concerned about carrying these patches. That said, is there any argument in favor of just bumping `sagemath` to 10.2.beta1 rather than patching 10.1?

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
                   ` (8 preceding siblings ...)
  2023-09-07  1:32 ` ahesford
@ 2023-09-09 15:33 ` tornaria
  2023-09-11  0:02 ` ahesford
                   ` (6 subsequent siblings)
  16 siblings, 0 replies; 18+ messages in thread
From: tornaria @ 2023-09-09 15:33 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 1474 bytes --]

New comment by tornaria on void-packages repository

https://github.com/void-linux/void-packages/pull/45887#issuecomment-1712538236

Comment:
> After an out-of-band discussion about this PR, I am less concerned about carrying these patches.

After thinking it thoroughly I don't think there is a rush to have sagemath with cython 3 merged (even if I believe the patches to be pretty safe). Since nothing in the repo depends on `python-Cython`, there is no conflict at all in that sagemath depends on `python-Cython0.29`. Functionally there should be no difference (for the time being... cython 3 unlocks some features that will eventually be used in sagemath).

I'm happy to either close or move to draft this PR. In any case this will stay available for whoever needs to run sagemath on cython3.

> That said, is there any argument in favor of just bumping `sagemath` to 10.2.beta1 rather than patching 10.1?

We've tried to stick with releases rather than betas. The problem with betas is that sometimes there are features that are "half-merged" so I wouldn't be confident. I much prefer cherry-picking PRs that have been already merged and beta-released. I also try to only use patches I personally review (the 9k lines patch I actually read line by line and positive review myself).

OTOH, sometimes I consider having some package "sagemath-next" which previews the future sagemath (carrying the latest beta / rc) in a way that it can coexist with "sagemath".

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
                   ` (9 preceding siblings ...)
  2023-09-09 15:33 ` tornaria
@ 2023-09-11  0:02 ` ahesford
  2023-10-09 21:55 ` [PR PATCH] [Updated] " tornaria
                   ` (5 subsequent siblings)
  16 siblings, 0 replies; 18+ messages in thread
From: ahesford @ 2023-09-11  0:02 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 336 bytes --]

New comment by ahesford on void-packages repository

https://github.com/void-linux/void-packages/pull/45887#issuecomment-1712978436

Comment:
In that case, we can mark this draft and move it to 10.2 when ready. In the meantime, if a compelling need to jump to Cython 3 arises sooner, we will have this ready to go in its current state.

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PR PATCH] [Updated] sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
                   ` (10 preceding siblings ...)
  2023-09-11  0:02 ` ahesford
@ 2023-10-09 21:55 ` tornaria
  2023-10-09 22:01 ` tornaria
                   ` (4 subsequent siblings)
  16 siblings, 0 replies; 18+ messages in thread
From: tornaria @ 2023-10-09 21:55 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 2442 bytes --]

There is an updated pull request by tornaria against master on the void-packages repository

https://github.com/tornaria/void-packages sagemath-cython3
https://github.com/void-linux/void-packages/pull/45887

sagemath: use cython 3
#### Testing the changes
- I tested the changes in this PR: **briefly**

Since https://github.com/sagemath/sage/pull/36109 was merged upstream, it's now almost trivial to build sagemath with cython 3. This PR is pretty straightforward to understand:

 - commit 7f8e6514ffa54449a80e01fbae7f9355a7739a46 rebuilds `python3-pplpy` using cython 3. Nothing fancy here and this commit was already tested and only dropped since it turned out it had to be built with the same version of cython as sagemath itself.
 - commit df0d21871ce850efea3fc01f19a3d9e8c0d5f0d4 is just adding a few patches to sagemath, switching to cython 3, and bumping.

Description of added patches:
1. patch `36109-00pre.patch`: this is hand picked trivial patch that allows us to apply https://github.com/sagemath/sage/pull/36109 cleanly on 10.1 (since that PR is based on 10.1.beta0). All changes are comments!
2. patch `36109-prepare_for_cython_3.0.patch`: this is long, taken verbatim from https://github.com/sagemath/sage/pull/36109.diff, and is already merged.
3. patch `build-cython3.patch`: this is 2 lines changed plus 4 legacy build options added to cython setup.
4. patch `fix-doctest-cython3.patch`: this is a few fixes in doctests to accomodate minor changes in cython output (`__repr__` for cython classes, functions, and generators).

CC: @ahesford 

<!--
#### New package
- This new package conforms to the [package requirements](https://github.com/void-linux/void-packages/blob/master/CONTRIBUTING.md#package-requirements): **YES**|**NO**
-->

<!-- Note: If the build is likely to take more than 2 hours, please add ci skip tag as described in
https://github.com/void-linux/void-packages/blob/master/CONTRIBUTING.md#continuous-integration
and test at least one native build and, if supported, at least one cross build.
Ignore this section if this PR is not skipping CI.
-->
<!--
#### Local build testing
- I built this PR locally for my native architecture, (ARCH-LIBC)
- I built this PR locally for these architectures (if supported. mark crossbuilds):
  - aarch64-musl
  - armv7l
  - armv6l-musl
-->


A patch file from https://github.com/void-linux/void-packages/pull/45887.patch is attached

[-- Warning: decoded text below may be mangled, UTF-8 assumed --]
[-- Attachment #2: github-pr-sagemath-cython3-45887.patch --]
[-- Type: text/x-diff, Size: 463113 bytes --]

From 4bd82079fac86efab1e42cc7e1e9704a5fed7c91 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gonzalo=20Tornar=C3=ADa?= <tornaria@cmat.edu.uy>
Date: Wed, 19 Jul 2023 21:04:33 -0300
Subject: [PATCH 1/2] python3-pplpy: update to 0.8.9, use cython 3.

---
 srcpkgs/python3-pplpy/template | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/srcpkgs/python3-pplpy/template b/srcpkgs/python3-pplpy/template
index fe6b08dba40f2..d7a31aeab2023 100644
--- a/srcpkgs/python3-pplpy/template
+++ b/srcpkgs/python3-pplpy/template
@@ -1,19 +1,19 @@
 # Template file for 'python3-pplpy'
 pkgname=python3-pplpy
-version=0.8.7
-revision=4
+version=0.8.9
+revision=1
 build_style=python3-module
-hostmakedepends="python3-setuptools python3-Cython0.29"
+hostmakedepends="python3-setuptools python3-Cython"
 makedepends="python3-cysignals python3-gmpy2 python3-devel gmp-devel
  gmpxx-devel ppl-devel mpfr-devel libmpc-devel pari-devel"
 depends="python3"
 short_desc="Python wrapper to the C++ Parma Polyhedra Library (PPL)"
 maintainer="Gonzalo Tornaría <tornaria@cmat.edu.uy>"
 license="GPL-3.0-or-later"
-homepage="https://gitlab.com/videlec/pplpy"
-changelog="https://gitlab.com/videlec/pplpy/-/raw/master/CHANGES.txt"
+homepage="https://github.com/sagemath/pplpy"
+changelog="https://raw.githubusercontent.com/sagemath/pplpy/master/CHANGES.txt"
 distfiles="${PYPI_SITE}/p/pplpy/pplpy-${version}.tar.gz"
-checksum=500bd0f4ae1a76956fae7fcba77854f5ec3e64fce76803664983763c3f2bd8bd
+checksum=db7a3b571d6ef053f75137975e947c3a1c1e45a30bab90eaf215b4e5cc15797e
 
 do_check() {
 	PYTHONPATH=$(cd build/lib* && pwd) python3 setup.py test

From 74c6a6906783ba3dd6e86cf44e5e674bd9c36585 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gonzalo=20Tornar=C3=ADa?= <tornaria@cmat.edu.uy>
Date: Tue, 29 Aug 2023 22:14:49 -0300
Subject: [PATCH 2/2] sagemath: use cython 3.0

---
 srcpkgs/sagemath/patches/36109-00pre.patch    |   50 +
 .../36109-prepare_for_cython_3.0.patch        | 9995 +++++++++++++++++
 srcpkgs/sagemath/patches/build-cython3.patch  |   44 +
 .../patches/fix-doctest-cython3.patch         |  207 +
 srcpkgs/sagemath/patches/get_patches          |    3 +-
 srcpkgs/sagemath/template                     |    6 +-
 6 files changed, 10301 insertions(+), 4 deletions(-)
 create mode 100644 srcpkgs/sagemath/patches/36109-00pre.patch
 create mode 100644 srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch
 create mode 100644 srcpkgs/sagemath/patches/build-cython3.patch
 create mode 100644 srcpkgs/sagemath/patches/fix-doctest-cython3.patch

diff --git a/srcpkgs/sagemath/patches/36109-00pre.patch b/srcpkgs/sagemath/patches/36109-00pre.patch
new file mode 100644
index 0000000000000..0a30d622f0f62
--- /dev/null
+++ b/srcpkgs/sagemath/patches/36109-00pre.patch
@@ -0,0 +1,50 @@
+Pre-patch so that PR #36109 applies cleanly on top of 10.1
+
+diff --git a/src/sage/categories/hopf_algebras_with_basis.py b/src/sage/categories/hopf_algebras_with_basis.py
+index ea401896ca0..29b6f48a86f 100644
+--- a/src/sage/categories/hopf_algebras_with_basis.py
++++ b/src/sage/categories/hopf_algebras_with_basis.py
+@@ -33,11 +33,11 @@ class HopfAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
+     We now show how to use a simple Hopf algebra, namely the group algebra of the dihedral group
+     (see also AlgebrasWithBasis)::
+ 
+-        sage: A = C.example(); A                                                        # optional - sage.groups
++        sage: A = C.example(); A                                                        # needs sage.groups
+         An example of Hopf algebra with basis: the group algebra of the
+          Dihedral group of order 6 as a permutation group over Rational Field
+-        sage: A.__custom_name = "A"                                                     # optional - sage.groups
+-        sage: A.category()                                                              # optional - sage.groups
++        sage: A.__custom_name = "A"                                                     # needs sage.groups
++        sage: A.category()                                                              # needs sage.groups
+         Category of finite dimensional hopf algebras with basis over Rational Field
+ 
+         sage: A.one_basis()                                                             # optional - sage.groups
+diff --git a/src/sage/categories/modules_with_basis.py b/src/sage/categories/modules_with_basis.py
+index 85a0d50239a..c0e29886b5f 100644
+--- a/src/sage/categories/modules_with_basis.py
++++ b/src/sage/categories/modules_with_basis.py
+@@ -66,9 +66,9 @@ class ModulesWithBasis(CategoryWithAxiom_over_base_ring):
+ 
+     Let `X` and `Y` be two modules with basis. We can build `Hom(X,Y)`::
+ 
+-        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.__custom_name = "X"             # optional - sage.modules
+-        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.__custom_name = "Y"             # optional - sage.modules
+-        sage: H = Hom(X, Y); H                                                          # optional - sage.modules
++        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.__custom_name = "X"             # needs sage.modules
++        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.__custom_name = "Y"             # needs sage.modules
++        sage: H = Hom(X, Y); H                                                          # needs sage.modules
+         Set of Morphisms from X to Y
+          in Category of finite dimensional vector spaces with basis over Rational Field
+ 
+diff --git a/src/sage/misc/cachefunc.pyx b/src/sage/misc/cachefunc.pyx
+index dac4c684f47..9b2916e547d 100644
+--- a/src/sage/misc/cachefunc.pyx
++++ b/src/sage/misc/cachefunc.pyx
+@@ -297,6 +297,7 @@ methods of extension classes, as long as they either support attribute assignmen
+ or have a public attribute of type ``<dict>`` called ``__cached_methods``. The
+ latter is easy::
+ 
++    sage: # needs sage.misc.cython
+     sage: cython_code = [
+     ....: "from sage.misc.cachefunc import cached_method",
+     ....: "cdef class MyClass:",
diff --git a/srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch b/srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch
new file mode 100644
index 0000000000000..93390f7eef992
--- /dev/null
+++ b/srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch
@@ -0,0 +1,9995 @@
+diff --git a/src/doc/en/thematic_tutorials/coercion_and_categories.rst b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+index 4efe68a2617..de2349a9a3f 100644
+--- a/src/doc/en/thematic_tutorials/coercion_and_categories.rst
++++ b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+@@ -106,7 +106,6 @@ This base class provides a lot more methods than a general parent::
+ 
+     sage: [p for p in dir(Field) if p not in dir(Parent)]
+     ['__fraction_field',
+-     '__ideal_monoid',
+      '__iter__',
+      '__len__',
+      '__rxor__',
+@@ -119,6 +118,7 @@ This base class provides a lot more methods than a general parent::
+      '_default_category',
+      '_gens',
+      '_ideal_class_',
++     '_ideal_monoid',
+      '_latex_names',
+      '_list',
+      '_one_element',
+diff --git a/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst b/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst
+index 51aec989810..553a946c4d8 100644
+--- a/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst
++++ b/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst
+@@ -298,7 +298,7 @@ http://docs.python.org/library/ for a complete list. ::
+         sage: el
+         bla
+         sage: el.__dict__
+-        {'__custom_name': 'bla', 'value': 42}
++        {'_SageObject__custom_name': 'bla', 'value': 42}
+ 
+     Lots of Sage objects are not Python objects but compiled Cython
+     objects. Python sees them as builtin objects and you do not have
+diff --git a/src/sage/algebras/letterplace/free_algebra_letterplace.pxd b/src/sage/algebras/letterplace/free_algebra_letterplace.pxd
+index d1d162c3b40..47a7275aba0 100644
+--- a/src/sage/algebras/letterplace/free_algebra_letterplace.pxd
++++ b/src/sage/algebras/letterplace/free_algebra_letterplace.pxd
+@@ -20,16 +20,15 @@ cdef class FreeAlgebra_letterplace_libsingular():
+     cdef ring* _lp_ring
+     cdef MPolynomialRing_libsingular _commutative_ring
+     cdef MPolynomialRing_libsingular _lp_ring_internal
+-    cdef object __ngens
++    cdef object _ngens
+ 
+ cdef class FreeAlgebra_letterplace(Algebra):
+     cdef MPolynomialRing_libsingular _commutative_ring
+     cdef MPolynomialRing_libsingular _current_ring
+     cdef int _degbound
+-    cdef int __ngens
++    cdef int _ngens
+     cdef int _nb_slackvars
+     cdef object __monoid
+-    cdef public object __custom_name
+     cdef str exponents_to_string(self, E)
+     cdef str exponents_to_latex(self, E)
+     cdef tuple _degrees
+diff --git a/src/sage/algebras/letterplace/free_algebra_letterplace.pyx b/src/sage/algebras/letterplace/free_algebra_letterplace.pyx
+index e9c70c9de29..53f0dfdea6d 100644
+--- a/src/sage/algebras/letterplace/free_algebra_letterplace.pyx
++++ b/src/sage/algebras/letterplace/free_algebra_letterplace.pyx
+@@ -255,7 +255,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+         """
+         if not isinstance(R, MPolynomialRing_libsingular):
+             raise TypeError("a letterplace algebra must be provided by a polynomial ring of type %s" % MPolynomialRing_libsingular)
+-        self.__ngens = R.ngens()
++        self._ngens = R.ngens()
+         if degrees is None:
+             varnames = R.variable_names()
+             self._nb_slackvars = 0
+@@ -269,12 +269,12 @@ cdef class FreeAlgebra_letterplace(Algebra):
+         self._current_ring = make_letterplace_ring(R, 1)
+         self._degbound = 1
+         if degrees is None:
+-            self._degrees = tuple([int(1)] * self.__ngens)
++            self._degrees = tuple([int(1)] * self._ngens)
+         else:
+             if (not isinstance(degrees, (tuple, list))) \
+-                    or len(degrees) != self.__ngens - self._nb_slackvars \
++                    or len(degrees) != self._ngens - self._nb_slackvars \
+                     or any(i <= 0 for i in degrees):
+-                raise TypeError("the generator degrees must be given by a list or tuple of %d positive integers" % (self.__ngens - 1))
++                raise TypeError("the generator degrees must be given by a list or tuple of %d positive integers" % (self._ngens - 1))
+             self._degrees = tuple([int(i) for i in degrees])
+             self.set_degbound(max(self._degrees))
+         self._populate_coercion_lists_(coerce_list=[base_ring])
+@@ -305,7 +305,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F.ngens()
+             3
+         """
+-        return self.__ngens - self._nb_slackvars
++        return self._ngens - self._nb_slackvars
+ 
+     def gen(self, i):
+         """
+@@ -327,17 +327,17 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F.gen(2)
+             c
+         """
+-        if i >= self.__ngens - self._nb_slackvars:
+-            raise ValueError("this free algebra only has %d generators" % (self.__ngens - self._nb_slackvars))
++        if i >= self._ngens - self._nb_slackvars:
++            raise ValueError("this free algebra only has %d generators" % (self._ngens - self._nb_slackvars))
+         if self._gens is not None:
+             return self._gens[i]
+         deg = self._degrees[i]
+         # self.set_degbound(deg)
+         p = self._current_ring.gen(i)
+         cdef int n
+-        cdef int j = self.__ngens - 1
++        cdef int j = self._ngens - 1
+         for n in range(1, deg):
+-            j += self.__ngens
++            j += self._ngens
+             p *= self._current_ring.gen(j)
+         return FreeAlgebraElement_letterplace(self, p)
+ 
+@@ -413,7 +413,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: FreeAlgebra(QQ, implementation='letterplace', names=['x']).is_commutative()
+             True
+         """
+-        return self.__ngens - self._nb_slackvars <= 1
++        return self._ngens - self._nb_slackvars <= 1
+ 
+     def is_field(self, proof=True):
+         """
+@@ -430,7 +430,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F.is_field()
+             False
+         """
+-        return (not (self.__ngens - self._nb_slackvars)) and self._base.is_field(proof=proof)
++        return (not (self._ngens - self._nb_slackvars)) and self._base.is_field(proof=proof)
+ 
+     def _repr_(self):
+         """
+@@ -446,7 +446,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F
+             Free Associative Unital Algebra on 3 generators (x, y, z) over Rational Field
+         """
+-        return "Free Associative Unital Algebra on %d generators %s over %s" % (self.__ngens - self._nb_slackvars, self.gens(), self._base)
++        return "Free Associative Unital Algebra on %d generators %s over %s" % (self._ngens - self._nb_slackvars, self.gens(), self._base)
+ 
+     def _latex_(self):
+         r"""
+@@ -586,7 +586,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+               generated free abelian monoid.
+               In principle, this is correct, but it is not implemented, yet.>
+         """
+-        cdef int ngens = self.__ngens
++        cdef int ngens = self._ngens
+         cdef int nblocks = len(E) // ngens
+         cdef int i, j, base, exp, var_ind
+         cdef list out = []
+@@ -618,7 +618,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: latex(-(a*b*(z+1)-c)^2)     # indirect doctest
+             \left(2 z + 1\right) a b a b + \left(z + 1\right) a b c + \left(z + 1\right) c a b - c c
+         """
+-        cdef int ngens = self.__ngens
++        cdef int ngens = self._ngens
+         cdef int nblocks = len(E) // ngens
+         cdef int i, j, base, exp, var_ind
+         cdef list out = []
+@@ -678,7 +678,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+         cdef list out = []
+         C = self.current_ring()
+         cdef FreeAlgebraElement_letterplace x
+-        ngens = self.__ngens
++        ngens = self._ngens
+         cdef list G = [C(x._poly) for x in g]
+         from sage.groups.perm_gps.permgroup_named import CyclicPermutationGroup
+         CG = CyclicPermutationGroup(C.ngens())
+@@ -811,7 +811,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             l = len(e)
+             break
+         cdef dict out = {}
+-        self.set_degbound(l // self.__ngens)
++        self.set_degbound(l // self._ngens)
+         cdef Py_ssize_t n = self._current_ring.ngens()
+         for e, c in D.iteritems():
+             out[tuple(e) + (0,) * (n - l)] = c
+@@ -896,7 +896,7 @@ cdef class FreeAlgebra_letterplace_libsingular():
+         self._commutative_ring = commutative_ring
+ 
+     def __init__(self, commutative_ring, degbound):
+-        self.__ngens = commutative_ring.ngens() * degbound
++        self._ngens = commutative_ring.ngens() * degbound
+ 
+     def __dealloc__(self):
+         r"""
+diff --git a/src/sage/algebras/quatalg/quaternion_algebra_element.pyx b/src/sage/algebras/quatalg/quaternion_algebra_element.pyx
+index f6e87440fe9..8cb7e848fd0 100644
+--- a/src/sage/algebras/quatalg/quaternion_algebra_element.pyx
++++ b/src/sage/algebras/quatalg/quaternion_algebra_element.pyx
+@@ -1700,15 +1700,15 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra
+             x, y, z, w = v
+         cdef NumberFieldElement a = <NumberFieldElement>(parent._base(parent._a))
+         cdef NumberFieldElement b = <NumberFieldElement>(parent._base(parent._b))
+-        fmpz_poly_set_ZZX(self.x, (<NumberFieldElement>x).__numerator)
+-        fmpz_poly_set_ZZX(self.y, (<NumberFieldElement>y).__numerator)
+-        fmpz_poly_set_ZZX(self.z, (<NumberFieldElement>z).__numerator)
+-        fmpz_poly_set_ZZX(self.w, (<NumberFieldElement>w).__numerator)
++        fmpz_poly_set_ZZX(self.x, (<NumberFieldElement>x)._numerator)
++        fmpz_poly_set_ZZX(self.y, (<NumberFieldElement>y)._numerator)
++        fmpz_poly_set_ZZX(self.z, (<NumberFieldElement>z)._numerator)
++        fmpz_poly_set_ZZX(self.w, (<NumberFieldElement>w)._numerator)
+ 
+-        ZZ_to_mpz(T1, &(<NumberFieldElement>x).__denominator)
+-        ZZ_to_mpz(T2, &(<NumberFieldElement>y).__denominator)
+-        ZZ_to_mpz(t3, &(<NumberFieldElement>z).__denominator)
+-        ZZ_to_mpz(t4, &(<NumberFieldElement>w).__denominator)
++        ZZ_to_mpz(T1, &(<NumberFieldElement>x)._denominator)
++        ZZ_to_mpz(T2, &(<NumberFieldElement>y)._denominator)
++        ZZ_to_mpz(t3, &(<NumberFieldElement>z)._denominator)
++        ZZ_to_mpz(t4, &(<NumberFieldElement>w)._denominator)
+ 
+         mpz_lcm(self.d, T1, T2)
+         mpz_lcm(self.d, self.d, t3)
+@@ -1724,10 +1724,10 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra
+         fmpz_poly_scalar_mul_mpz(self.z, self.z, t3)
+         fmpz_poly_scalar_mul_mpz(self.w, self.w, t4)
+ 
+-        fmpz_poly_set_ZZX(self.a, a.__numerator)     # we will assume that the denominator of a and b are 1
+-        fmpz_poly_set_ZZX(self.b, b.__numerator)
++        fmpz_poly_set_ZZX(self.a, a._numerator)     # we will assume that the denominator of a and b are 1
++        fmpz_poly_set_ZZX(self.b, b._numerator)
+ 
+-        fmpz_poly_set_ZZX(self.modulus, (<NumberFieldElement>x).__fld_numerator.x)  # and same for the modulus
++        fmpz_poly_set_ZZX(self.modulus, (<NumberFieldElement>x)._fld_numerator.x)  # and same for the modulus
+ 
+     def __getitem__(self, int i):
+         """
+@@ -1756,17 +1756,17 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra
+         cdef NumberFieldElement item = el._new()
+ 
+         if i == 0:
+-            fmpz_poly_get_ZZX(item.__numerator, self.x)
++            fmpz_poly_get_ZZX(item._numerator, self.x)
+         elif i == 1:
+-            fmpz_poly_get_ZZX(item.__numerator, self.y)
++            fmpz_poly_get_ZZX(item._numerator, self.y)
+         elif i == 2:
+-            fmpz_poly_get_ZZX(item.__numerator, self.z)
++            fmpz_poly_get_ZZX(item._numerator, self.z)
+         elif i == 3:
+-            fmpz_poly_get_ZZX(item.__numerator, self.w)
++            fmpz_poly_get_ZZX(item._numerator, self.w)
+         else:
+             raise IndexError("quaternion element index out of range")
+ 
+-        mpz_to_ZZ(&item.__denominator, self.d)
++        mpz_to_ZZ(&item._denominator, self.d)
+ 
+         return item
+ 
+diff --git a/src/sage/categories/hopf_algebras_with_basis.py b/src/sage/categories/hopf_algebras_with_basis.py
+index 1be964cb6c9..615fc4eae06 100644
+--- a/src/sage/categories/hopf_algebras_with_basis.py
++++ b/src/sage/categories/hopf_algebras_with_basis.py
+@@ -36,7 +36,7 @@ class HopfAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
+         sage: A = C.example(); A                                                        # needs sage.groups
+         An example of Hopf algebra with basis: the group algebra of the
+          Dihedral group of order 6 as a permutation group over Rational Field
+-        sage: A.__custom_name = "A"                                                     # needs sage.groups
++        sage: A.rename("A")                                                             # needs sage.groups
+         sage: A.category()                                                              # needs sage.groups
+         Category of finite dimensional hopf algebras with basis over Rational Field
+ 
+diff --git a/src/sage/categories/modules_with_basis.py b/src/sage/categories/modules_with_basis.py
+index 65fd47cb890..fc1857f0c8e 100644
+--- a/src/sage/categories/modules_with_basis.py
++++ b/src/sage/categories/modules_with_basis.py
+@@ -66,8 +66,8 @@ class ModulesWithBasis(CategoryWithAxiom_over_base_ring):
+ 
+     Let `X` and `Y` be two modules with basis. We can build `Hom(X,Y)`::
+ 
+-        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.__custom_name = "X"             # needs sage.modules
+-        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.__custom_name = "Y"             # needs sage.modules
++        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.rename("X")                     # needs sage.modules
++        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.rename("Y")                     # needs sage.modules
+         sage: H = Hom(X, Y); H                                                          # needs sage.modules
+         Set of Morphisms from X to Y
+          in Category of finite dimensional vector spaces with basis over Rational Field
+diff --git a/src/sage/combinat/cluster_complex.py b/src/sage/combinat/cluster_complex.py
+index edc4f235aeb..e263d983887 100644
+--- a/src/sage/combinat/cluster_complex.py
++++ b/src/sage/combinat/cluster_complex.py
+@@ -222,10 +222,6 @@ def __init__(self, W, k, coxeter_element, algorithm):
+         self._W = W
+         self._w0 = w
+         self._k = k
+-        if k == 1:
+-            self.__custom_name = 'Cluster complex'
+-        else:
+-            self.__custom_name = 'Multi-cluster complex'
+ 
+         self.set_immutable()
+ 
+@@ -271,7 +267,10 @@ def _repr_(self):
+             sage: ClusterComplex(['A', 2])._repr_()
+             "Cluster complex of type ['A', 2] with 5 vertices and 5 facets"
+         """
+-        name = self.__custom_name
++        if self._k == 1:
++            name = 'Cluster complex'
++        else:
++            name = 'Multi-cluster complex'
+         name += (' of type %s with %s vertices and %s facets'
+                  % (self.cartan_type(), len(self.vertices()),
+                     len(self._facets)))
+diff --git a/src/sage/combinat/integer_lists/base.pxd b/src/sage/combinat/integer_lists/base.pxd
+index ecb5550a9cf..3d373a64fe0 100644
+--- a/src/sage/combinat/integer_lists/base.pxd
++++ b/src/sage/combinat/integer_lists/base.pxd
+@@ -12,4 +12,4 @@ cdef class IntegerListsBackend():
+     cdef readonly min_part, max_part
+     cdef readonly min_slope, max_slope
+     cdef readonly Envelope floor, ceiling
+-    cdef public dict __cached_methods  # Support cached_method
++    cdef public dict _cached_methods  # Support cached_method
+diff --git a/src/sage/combinat/subword_complex.py b/src/sage/combinat/subword_complex.py
+index b7489bdf754..de7eefe946e 100644
+--- a/src/sage/combinat/subword_complex.py
++++ b/src/sage/combinat/subword_complex.py
+@@ -1131,7 +1131,6 @@ def __init__(self, Q, w, algorithm="inductive"):
+         SimplicialComplex.__init__(self, maximal_faces=Fs,
+                                    maximality_check=False,
+                                    category=cat)
+-        self.__custom_name = 'Subword complex'
+         self._W = W
+         try:
+             T = W.coxeter_matrix().coxeter_type()
+diff --git a/src/sage/cpython/cython_metaclass.h b/src/sage/cpython/cython_metaclass.h
+index da06ab75a6b..ecf7f973c3e 100644
+--- a/src/sage/cpython/cython_metaclass.h
++++ b/src/sage/cpython/cython_metaclass.h
+@@ -52,6 +52,16 @@ static CYTHON_INLINE int Sage_PyType_Ready(PyTypeObject* t)
+     if (r < 0)
+         return r;
+ 
++#if PY_VERSION_HEX >= 0x03050000
++    // Cython 3 sets Py_TPFLAGS_HEAPTYPE before calling PyType_Ready,
++    // and resets just after the call. We need to reset it earlier,
++    // since otherwise the call to metaclass.__init__ below may have
++    // illegal memory accesses.
++    // See also:
++    // https://github.com/cython/cython/issues/3603
++    t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE;
++#endif
++
+     /* Set or get metaclass (the type of t) */
+     PyTypeObject* metaclass;
+ 
+diff --git a/src/sage/cpython/cython_metaclass.pyx b/src/sage/cpython/cython_metaclass.pyx
+index a8fe853661d..a8fa92fc1a8 100644
+--- a/src/sage/cpython/cython_metaclass.pyx
++++ b/src/sage/cpython/cython_metaclass.pyx
+@@ -19,13 +19,16 @@ file if you are using one).
+ 
+ In the extension type (a.k.a. ``cdef class``) for which you want to
+ define a metaclass, define a method ``__getmetaclass__`` with a single
+-unused argument. This method should return a type to be used as
++unused argument, and turn off the Cython directive
++``always_allow_keywords``. This method should return a type to be used as
+ metaclass:
+ 
+ .. code-block:: cython
+ 
++    cimport cython
+     cimport sage.cpython.cython_metaclass
+     cdef class MyCustomType():
++        @cython.always_allow_keywords(False)
+         def __getmetaclass__(_):
+             from foo import MyMetaclass
+             return MyMetaclass
+@@ -63,8 +66,10 @@ EXAMPLES::
+ 
+     sage: cython(                                                                       # needs sage.misc.cython
+     ....: '''
++    ....: cimport cython
+     ....: cimport sage.cpython.cython_metaclass
+     ....: cdef class MyCustomType():
++    ....:     @cython.always_allow_keywords(False)
+     ....:     def __getmetaclass__(_):
+     ....:         class MyMetaclass(type):
+     ....:             def __init__(*args):
+@@ -101,8 +106,10 @@ returns a non-type::
+ 
+     sage: cython(                                                                       # needs sage.misc.cython
+     ....: '''
++    ....: cimport cython
+     ....: cimport sage.cpython.cython_metaclass
+     ....: cdef class MyCustomType():
++    ....:     @cython.always_allow_keywords(False)
+     ....:     def __getmetaclass__(_):
+     ....:         return 2
+     ....: ''')
+diff --git a/src/sage/cpython/getattr.pyx b/src/sage/cpython/getattr.pyx
+index 3f603b98040..16f649c083d 100644
+--- a/src/sage/cpython/getattr.pyx
++++ b/src/sage/cpython/getattr.pyx
+@@ -271,7 +271,7 @@ cpdef getattr_from_other_class(self, cls, name):
+ 
+     Caveat: lazy attributes work with extension types only
+     if they allow attribute assignment or have a public attribute
+-    ``__cached_methods`` of type ``<dict>``. This condition
++    ``_cached_methods`` of type ``<dict>``. This condition
+     is satisfied, e.g., by any class that is derived from
+     :class:`Parent`::
+ 
+diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd
+index bdd49225ff2..030c9defa45 100644
+--- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd
++++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd
+@@ -8,7 +8,7 @@ from .polyhedron_face_lattice           cimport PolyhedronFaceLattice
+ 
+ @cython.final
+ cdef class CombinatorialPolyhedron(SageObject):
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+     # Do not assume any of those attributes to be initialized, use the corresponding methods instead.
+     cdef tuple _Vrep                       # the names of VRep, if they exist
+diff --git a/src/sage/groups/perm_gps/permgroup_element.pxd b/src/sage/groups/perm_gps/permgroup_element.pxd
+index a2ac8f20eaa..0a584745f96 100644
+--- a/src/sage/groups/perm_gps/permgroup_element.pxd
++++ b/src/sage/groups/perm_gps/permgroup_element.pxd
+@@ -22,7 +22,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement):
+     cpdef PermutationGroupElement _generate_new_GAP(self, old)
+     cpdef _gap_list(self)
+     cpdef domain(self)
+-    cdef public __custom_name
++    cdef public _SageObject__custom_name
+     cpdef list _act_on_list_on_position(self, list x)
+     cpdef ClonableIntArray _act_on_array_on_position(self, ClonableIntArray x)
+     cpdef ETuple _act_on_etuple_on_position(self, ETuple x)
+diff --git a/src/sage/interfaces/interface.py b/src/sage/interfaces/interface.py
+index f8237d3ad94..3180113c9c7 100644
+--- a/src/sage/interfaces/interface.py
++++ b/src/sage/interfaces/interface.py
+@@ -1169,11 +1169,8 @@ def __repr__(self):
+             s = cr
+         else:
+             s = self._repr_()
+-        if self._name in s:
+-            try:
+-                s = s.replace(self._name, getattr(self, '__custom_name'))
+-            except AttributeError:
+-                pass
++        if self._name in s and self.get_custom_name() is not None:
++            s = s.replace(self._name, self.get_custom_name())
+         if cr:
+             self._cached_repr = s
+         return s
+diff --git a/src/sage/interfaces/singular.py b/src/sage/interfaces/singular.py
+index 4b5c76e2bfa..705fa6f66e1 100644
+--- a/src/sage/interfaces/singular.py
++++ b/src/sage/interfaces/singular.py
+@@ -1400,8 +1400,8 @@ def _repr_(self):
+         """
+         s = super(SingularElement, self)._repr_()
+         if self._name in s:
+-            if (not hasattr(self, "__custom_name")) and self.type() == 'matrix':
+-                s = self.parent().eval('pmat(%s,20)'%(self.name()))
++            if self.get_custom_name() is None and self.type() == 'matrix':
++                s = self.parent().eval('pmat(%s,20)' % (self.name()))
+         return s
+ 
+     def __copy__(self):
+diff --git a/src/sage/libs/arb/arith.pyx b/src/sage/libs/arb/arith.pyx
+index d885f97b238..3b32fe7e8ed 100644
+--- a/src/sage/libs/arb/arith.pyx
++++ b/src/sage/libs/arb/arith.pyx
+@@ -81,5 +81,5 @@ def hilbert_class_polynomial(D):
+     cdef long n = D
+     cdef Polynomial_integer_dense_flint poly
+     poly = PolynomialRing(ZZ, "x", implementation="FLINT")()
+-    acb_modular_hilbert_class_poly(poly.__poly, n)
++    acb_modular_hilbert_class_poly(poly._poly, n)
+     return poly
+diff --git a/src/sage/libs/coxeter3/coxeter.pxd b/src/sage/libs/coxeter3/coxeter.pxd
+index 9d5cb2a3f5d..dbd2b8a61c6 100644
+--- a/src/sage/libs/coxeter3/coxeter.pxd
++++ b/src/sage/libs/coxeter3/coxeter.pxd
+@@ -29,6 +29,3 @@ cdef class CoxGroupElement:
+     cdef CoxGroup _parent_group
+     cdef CoxGroupElement _new(self)
+     cpdef CoxGroup parent_group(self)
+-
+-cdef class CoxGraph:
+-    cdef c_CoxGraph x
+diff --git a/src/sage/libs/gap/element.pyx b/src/sage/libs/gap/element.pyx
+index 1dc53c81f67..478caf9f9d0 100644
+--- a/src/sage/libs/gap/element.pyx
++++ b/src/sage/libs/gap/element.pyx
+@@ -720,7 +720,7 @@ cdef class GapElement(RingElement):
+             ...
+             AttributeError: 'some_name' does not define a GAP function
+         """
+-        if name in ('__dict__', '_getAttributeNames', '__custom_name', 'keys'):
++        if name in ('__dict__', '_getAttributeNames', '_SageObject__custom_name', 'keys'):
+             raise AttributeError('Python special name, not a GAP function.')
+         try:
+             proxy = make_GapElement_MethodProxy\
+diff --git a/src/sage/libs/gap/gap_includes.pxd b/src/sage/libs/gap/gap_includes.pxd
+index 840b8a0042e..1ed4378a6c7 100644
+--- a/src/sage/libs/gap/gap_includes.pxd
++++ b/src/sage/libs/gap/gap_includes.pxd
+@@ -144,3 +144,18 @@ cdef extern from "gap/stringobj.h" nogil:
+     bint IS_STRING(Obj obj)
+     bint IsStringConv(Obj obj)
+     Obj NEW_STRING(Int)
++
++
++cdef extern from "<structmember.h>" nogil:
++    """
++    /* Hack: Cython 3.0 automatically includes <structmember.h>, which
++     * defines several macros that collides with enum definitions in
++     * gap/objects.h. We need to include the header explicitly and
++     * undefine these macros.
++     */
++    #undef T_INT
++    #undef T_STRING
++    #undef T_CHAR
++    #undef T_BOOL
++    """
++    pass
+diff --git a/src/sage/libs/lcalc/lcalc_Lfunction.pxd b/src/sage/libs/lcalc/lcalc_Lfunction.pxd
+index 5edf0844f3e..1d595180a6f 100644
+--- a/src/sage/libs/lcalc/lcalc_Lfunction.pxd
++++ b/src/sage/libs/lcalc/lcalc_Lfunction.pxd
+@@ -99,19 +99,19 @@ cdef extern from "lcalc_sage.h":
+ ################
+ 
+ # strange bug, I can't compile without this trick ???
+-# it's only used in __typedN
++# it's only used in _typedN
+ ctypedef double Double
+ 
+ cdef class Lfunction:
+     cdef void *thisptr
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r)
+-    cdef c_Complex __value(self,c_Complex s,int derivative)
+-    cdef c_Complex __hardy_z_function(self,c_Complex s)
+-    cdef int __compute_rank(self)
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r)
++    cdef c_Complex _value(self,c_Complex s,int derivative)
++    cdef c_Complex _hardy_z_function(self,c_Complex s)
++    cdef int _compute_rank(self)
+     #strange bug, replacing Double with double gives me a compile error
+-    cdef Double __typedN(self, double T)
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize,doublevec *result)
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec* result)
++    cdef Double _typedN(self, double T)
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize,doublevec *result)
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec* result)
+ 
+     cdef str _repr
+ 
+diff --git a/src/sage/libs/lcalc/lcalc_Lfunction.pyx b/src/sage/libs/lcalc/lcalc_Lfunction.pyx
+index 6e9005c502b..7b871ed049f 100644
+--- a/src/sage/libs/lcalc/lcalc_Lfunction.pyx
++++ b/src/sage/libs/lcalc/lcalc_Lfunction.pyx
+@@ -99,7 +99,7 @@ cdef class Lfunction:
+             tmpc=CCC(residue[i])
+             r[i+1] = new_Complex(mpfr_get_d(tmpc.__re, MPFR_RNDN), mpfr_get_d(tmpc.__im, MPFR_RNDN))
+ 
+-        self.__init_fun(NAME, what_type, dirichlet_coefficient, Period, q,  w,  A, g, l, n_poles, p, r)
++        self._init_fun(NAME, what_type, dirichlet_coefficient, Period, q,  w,  A, g, l, n_poles, p, r)
+ 
+         if name:
+             name += ': '
+@@ -180,7 +180,7 @@ cdef class Lfunction:
+         """
+         cdef ComplexNumber complexified_s = CCC(s)
+         cdef c_Complex z = new_Complex(mpfr_get_d(complexified_s.__re, MPFR_RNDN), mpfr_get_d(complexified_s.__im, MPFR_RNDN))
+-        cdef c_Complex result = self.__value(z, derivative)
++        cdef c_Complex result = self._value(z, derivative)
+         return CCC(result.real(),result.imag())
+ 
+     def hardy_z_function(self, s):
+@@ -223,7 +223,7 @@ cdef class Lfunction:
+         #This takes s -> .5 + I*s
+         cdef ComplexNumber complexified_s = CCC(0.5)+ CCC(0,1)*CCC(s)
+         cdef c_Complex z = new_Complex(mpfr_get_d(complexified_s.__re, MPFR_RNDN), mpfr_get_d(complexified_s.__im, MPFR_RNDN))
+-        cdef c_Complex result = self.__hardy_z_function(z)
++        cdef c_Complex result = self._hardy_z_function(z)
+         return CCC(result.real(),result.imag())
+ 
+ 
+@@ -249,9 +249,9 @@ cdef class Lfunction:
+             3
+ 
+         """
+-        return self.__compute_rank()
++        return self._compute_rank()
+ 
+-    def __N(self, T):
++    def _N(self, T):
+         """
+         Compute the number of zeroes upto height `T` using the formula for
+         `N(T)` with the error of `S(T)`. Please do not use this. It is only
+@@ -262,12 +262,12 @@ cdef class Lfunction:
+             sage: from sage.libs.lcalc.lcalc_Lfunction import *
+             sage: chi = DirichletGroup(5)[2] #This is a quadratic character
+             sage: L=Lfunction_from_character(chi, type="complex")
+-            sage: L.__N(10) # abs tol 1e-8
++            sage: L._N(10) # abs tol 1e-8
+             4.0
+         """
+         cdef RealNumber real_T=RRR(T)
+         cdef double double_T = mpfr_get_d(real_T.value, MPFR_RNDN)
+-        cdef double res_d = self.__typedN(double_T)
++        cdef double res_d = self._typedN(double_T)
+         return RRR(res_d)
+ 
+     def find_zeros(self, T1, T2, stepsize):
+@@ -323,7 +323,7 @@ cdef class Lfunction:
+         cdef RealNumber real_T2 = RRR(T2)
+         cdef RealNumber real_stepsize = RRR(stepsize)
+         sig_on()
+-        self.__find_zeros_v( mpfr_get_d(real_T1.value, MPFR_RNDN), mpfr_get_d(real_T2.value, MPFR_RNDN), mpfr_get_d(real_stepsize.value, MPFR_RNDN),&result)
++        self._find_zeros_v( mpfr_get_d(real_T1.value, MPFR_RNDN), mpfr_get_d(real_T2.value, MPFR_RNDN), mpfr_get_d(real_stepsize.value, MPFR_RNDN),&result)
+         sig_off()
+         i=result.size()
+         returnvalue = []
+@@ -399,7 +399,7 @@ cdef class Lfunction:
+         cdef const char* message_stamp = ""
+         cdef doublevec result
+         sig_on()
+-        self.__find_zeros(count, start, max_refine, rank, message_stamp, &result)
++        self._find_zeros(count, start, max_refine, rank, message_stamp, &result)
+         sig_off()
+         returnvalue = []
+         for i in range(result.size()):
+@@ -408,25 +408,25 @@ cdef class Lfunction:
+         return returnvalue
+ 
+     # Needs to be overriden
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         raise NotImplementedError
+ 
+-    cdef c_Complex __value(self,c_Complex s,int derivative):
++    cdef c_Complex _value(self,c_Complex s,int derivative):
+         raise NotImplementedError
+ 
+-    cdef c_Complex __hardy_z_function(self,c_Complex s):
++    cdef c_Complex _hardy_z_function(self,c_Complex s):
+         raise NotImplementedError
+ 
+-    cdef int __compute_rank(self):
++    cdef int _compute_rank(self):
+         raise NotImplementedError
+ 
+-    cdef double __typedN(self,double T):
++    cdef double _typedN(self,double T):
+         raise NotImplementedError
+ 
+-    cdef void __find_zeros_v(self,double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self,double T1, double T2, double stepsize, doublevec *result):
+         raise NotImplementedError
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         raise NotImplementedError
+ 
+ ##############################################################################
+@@ -497,7 +497,7 @@ cdef class Lfunction_I(Lfunction):
+         self._repr += " with integer Dirichlet coefficients"
+ 
+     # override
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         cdef int N = len(dirichlet_coeff)
+         cdef Integer tmpi
+         cdef int * coeffs = new_ints(N+1) #lcalc ignores 0the coefficient
+@@ -507,22 +507,22 @@ cdef class Lfunction_I(Lfunction):
+         self.thisptr=new_c_Lfunction_I(NAME, what_type,  N, coeffs, Period, q,  w,  A, g, l, n_poles, p, r)
+         del_ints(coeffs)
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_I *>(self.thisptr)).value(s, derivative, "pure")
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_I *>(self.thisptr)).value(s, 0, "rotated pure")
+ 
+-    cdef int __compute_rank(self):
++    cdef int _compute_rank(self):
+         return (<c_Lfunction_I *>(self.thisptr)).compute_rank()
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_I *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_I *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_I *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     # debug tools
+@@ -633,7 +633,7 @@ cdef class Lfunction_D(Lfunction):
+         self._repr += " with real Dirichlet coefficients"
+ 
+     # override
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         cdef int i
+         cdef RealNumber tmpr
+         cdef int N = len(dirichlet_coeff)
+@@ -644,23 +644,23 @@ cdef class Lfunction_D(Lfunction):
+         self.thisptr=new_c_Lfunction_D(NAME, what_type,  N, coeffs, Period, q,  w,  A, g, l, n_poles, p, r)
+         del_doubles(coeffs)
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_D *>(self.thisptr)).value(s, derivative, "pure")
+ 
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_D *>(self.thisptr)).value(s, 0, "rotated pure")
+ 
+-    cdef inline int __compute_rank(self):
++    cdef inline int _compute_rank(self):
+         return (<c_Lfunction_D *>(self.thisptr)).compute_rank()
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_D *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_D *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start,double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start,double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_D *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     # debug tools
+@@ -773,7 +773,7 @@ cdef class Lfunction_C:
+         self._repr += " with complex Dirichlet coefficients"
+ 
+     # override
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         cdef int i
+         cdef int N = len(dirichlet_coeff)
+         cdef ComplexNumber tmpc
+@@ -788,24 +788,24 @@ cdef class Lfunction_C:
+ 
+         del_Complexes(coeffs)
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_C *>(self.thisptr)).value(s, derivative, "pure")
+ 
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_C *>(self.thisptr)).value(s, 0,"rotated pure")
+ 
+-    cdef inline int __compute_rank(self):
++    cdef inline int _compute_rank(self):
+         return (<c_Lfunction_C *>(self.thisptr)).compute_rank()
+ 
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_C *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_C *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_C *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     # debug tools
+@@ -873,24 +873,24 @@ cdef class Lfunction_Zeta(Lfunction):
+         self.thisptr = new_c_Lfunction_Zeta()
+         self._repr = "The Riemann zeta function"
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_Zeta *>(self.thisptr)).value(s, derivative, "pure")
+ 
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_Zeta *>(self.thisptr)).value(s, 0, "rotated pure")
+ 
+-    cdef inline int __compute_rank(self):
++    cdef inline int _compute_rank(self):
+         return (<c_Lfunction_Zeta *>(self.thisptr)).compute_rank()
+ 
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_Zeta *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_Zeta *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_Zeta *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     def __dealloc__(self):
+diff --git a/src/sage/libs/linkages/padics/Polynomial_ram.pxi b/src/sage/libs/linkages/padics/Polynomial_ram.pxi
+index 1ac51f1211f..e0584ecb8ad 100644
+--- a/src/sage/libs/linkages/padics/Polynomial_ram.pxi
++++ b/src/sage/libs/linkages/padics/Polynomial_ram.pxi
+@@ -55,16 +55,16 @@ cdef inline bint creduce(celement out, celement a, long prec, PowComputer_ prime
+     """
+     cdef celement ared = a % prime_pow.modulus
+     if ared is a and out is not a:
+-        out.__coeffs = ared.__coeffs[:]
++        out._coeffs = ared._coeffs[:]
+     else:
+-        out.__coeffs = ared.__coeffs
++        out._coeffs = ared._coeffs
+     cdef long coeff_prec = prec / prime_pow.e + 1
+     cdef long break_pt = prec % prime_pow.e
+-    for i in range(len(out.__coeffs)):
++    for i in range(len(out._coeffs)):
+         if i == break_pt:
+             coeff_prec -= 1
+-        out.__coeffs[i] = out.__coeffs[i].add_bigoh(coeff_prec)
+-    out.__normalize()
++        out._coeffs[i] = out._coeffs[i].add_bigoh(coeff_prec)
++    out._normalize()
+     return out == 0
+ 
+ cdef inline bint creduce_small(celement out, celement a, long prec, PowComputer_ prime_pow) except -1:
+@@ -116,7 +116,7 @@ cdef inline long cvaluation(celement a, long prec, PowComputer_ prime_pow) excep
+     higher.
+ 
+     """
+-    C = a.__coeffs
++    C = a._coeffs
+     if not C:
+         return prec
+     cdef long ret = maxordp
+@@ -161,7 +161,7 @@ cdef inline int cshift(celement shifted, celement rem, celement a, long n, long
+         v = cvaluation(a, prec, prime_pow)
+         notrunc = (v >= -n)
+     if notrunc:
+-        rem.__coeffs = []
++        rem._coeffs = []
+         return cshift_notrunc(shifted, a, n, prec, prime_pow, reduce_afterward)
+     if v > 0:
+         b = prime_pow.poly_ring(0)
+@@ -185,7 +185,7 @@ cdef inline int cshift(celement shifted, celement rem, celement a, long n, long
+     if reduce_afterward:
+         creduce(shifted, a, prec, prime_pow)
+     else:
+-        shifted.__coeffs = a.__coeffs[:]
++        shifted._coeffs = a._coeffs[:]
+ 
+ cdef inline int cshift_notrunc(celement out, celement a, long n, long prec, PowComputer_ prime_pow, bint reduce_afterward) except -1:
+     r"""
+@@ -236,7 +236,7 @@ cdef inline int cshift_notrunc(celement out, celement a, long n, long prec, PowC
+     if reduce_afterward:
+         creduce(out, a, prec, prime_pow)
+     else:
+-        out.__coeffs = a.__coeffs[:]
++        out._coeffs = a._coeffs[:]
+ 
+ cdef inline int cinvert(celement out, celement a, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -253,7 +253,7 @@ cdef inline int cinvert(celement out, celement a, long prec, PowComputer_ prime_
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = prime_pow.invert(a, prec).__coeffs
++    out._coeffs = prime_pow.invert(a, prec)._coeffs
+     creduce(out, out, prec, prime_pow)
+ 
+ cdef inline int cdivunit(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+@@ -335,7 +335,7 @@ cdef inline cexpansion_next(celement value, expansion_mode mode, long curpower,
+     # the following is specific to the ramified over unramified case.
+     modp_rep, term = value[0]._modp_rep(mode == smallest_mode)
+     if term:
+-        value.__coeffs[0] -= modp_rep
++        value._coeffs[0] -= modp_rep
+     cshift_notrunc(value, value, -1, curpower, prime_pow, False)
+     return term
+ 
+@@ -354,10 +354,10 @@ cdef inline cexpansion_getitem(celement value, long m, PowComputer_ prime_pow):
+     while m >= 0:
+         modp_rep, term = value[0]._modp_rep()
+         if m:
+-            if len(value.__coeffs):
+-                value.__coeffs[0] -= modp_rep
++            if len(value._coeffs):
++                value._coeffs[0] -= modp_rep
+             else:
+-                value.__coeffs.append(-modp_rep)
++                value._coeffs.append(-modp_rep)
+             cshift_notrunc(value, value, -1, 1, prime_pow, False)
+         m -= 1
+     return term
+@@ -379,9 +379,9 @@ cdef int cteichmuller(celement out, celement value, long prec, PowComputer_ prim
+ 
+     """
+     if value[0].valuation() > 0:
+-        out.__coeffs = []
++        out._coeffs = []
+     else:
+-        out.__coeffs = [value[0].parent().teichmuller(value[0])]
++        out._coeffs = [value[0].parent().teichmuller(value[0])]
+ 
+ cdef list ccoefficients(celement x, long valshift, long prec, PowComputer_ prime_pow):
+     """
+diff --git a/src/sage/libs/linkages/padics/Polynomial_shared.pxi b/src/sage/libs/linkages/padics/Polynomial_shared.pxi
+index 495dc6b0848..367bbc2f33d 100644
+--- a/src/sage/libs/linkages/padics/Polynomial_shared.pxi
++++ b/src/sage/libs/linkages/padics/Polynomial_shared.pxi
+@@ -106,7 +106,7 @@ cdef inline int ccmp(celement a, celement b, long prec, bint reduce_a, bint redu
+     if not (reduce_a or reduce_b):
+         return 0 if a == b else 1
+     csub(prime_pow.tmp_ccmp_a, a, b, prec, prime_pow)
+-    coeffs = prime_pow.tmp_ccmp_a.__coeffs
++    coeffs = prime_pow.tmp_ccmp_a._coeffs
+     cdef long i, coeff_prec, break_pt
+     if prime_pow.e == 1:
+         for i in range(prime_pow.tmp_ccmp_a.degree()+1):
+@@ -186,9 +186,9 @@ cdef inline int cneg(celement out, celement a, long prec, PowComputer_ prime_pow
+     """
+     cdef celement ma = -a
+     if ma is a:
+-        out.__coeffs = ma.__coeffs[:]
++        out._coeffs = ma._coeffs[:]
+     else:
+-        out.__coeffs = ma.__coeffs
++        out._coeffs = ma._coeffs
+ 
+ cdef inline int cadd(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -211,9 +211,9 @@ cdef inline int cadd(celement out, celement a, celement b, long prec, PowCompute
+     """
+     cdef celement sm = a + b
+     if sm is a or sm is b:
+-        out.__coeffs = sm.__coeffs[:]
++        out._coeffs = sm._coeffs[:]
+     else:
+-        out.__coeffs = sm.__coeffs
++        out._coeffs = sm._coeffs
+ 
+ cdef inline int csub(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -236,9 +236,9 @@ cdef inline int csub(celement out, celement a, celement b, long prec, PowCompute
+     """
+     cdef celement df = a - b
+     if df is a or df is b:
+-        out.__coeffs = df.__coeffs[:]
++        out._coeffs = df._coeffs[:]
+     else:
+-        out.__coeffs = df.__coeffs
++        out._coeffs = df._coeffs
+ 
+ cdef inline int cmul(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -261,9 +261,9 @@ cdef inline int cmul(celement out, celement a, celement b, long prec, PowCompute
+     """
+     cdef celement pd = a*b
+     if pd is a or pd is b:
+-        out.__coeffs = pd.__coeffs[:]
++        out._coeffs = pd._coeffs[:]
+     else:
+-        out.__coeffs = pd.__coeffs
++        out._coeffs = pd._coeffs
+ 
+ cdef inline int csetone(celement out, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -276,7 +276,7 @@ cdef inline int csetone(celement out, PowComputer_ prime_pow) except -1:
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = [prime_pow.base_ring(1)]
++    out._coeffs = [prime_pow.base_ring(1)]
+ 
+ cdef inline int csetzero(celement out, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -289,7 +289,7 @@ cdef inline int csetzero(celement out, PowComputer_ prime_pow) except -1:
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = []
++    out._coeffs = []
+ 
+ cdef inline bint cisone(celement a, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -330,7 +330,7 @@ cdef inline int ccopy(celement out, celement a, PowComputer_ prime_pow) except -
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = a.__coeffs[:]
++    out._coeffs = a._coeffs[:]
+ 
+ cdef inline cpickle(celement a, PowComputer_ prime_pow):
+     r"""
+@@ -343,7 +343,7 @@ cdef inline cpickle(celement a, PowComputer_ prime_pow):
+     - ``prime_pow`` the ``PowComputer`` for the ring
+ 
+     """
+-    return a.__coeffs
++    return a._coeffs
+ 
+ cdef inline int cunpickle(celement out, x, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -358,7 +358,7 @@ cdef inline int cunpickle(celement out, x, PowComputer_ prime_pow) except -1:
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = x
++    out._coeffs = x
+ 
+ cdef inline long chash(celement a, long ordp, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -413,9 +413,9 @@ cdef int cconv(celement out, x, long prec, long valshift, PowComputer_ prime_pow
+     else:
+         xx = prime_pow.poly_ring(x)
+     if xx is x:
+-        out.__coeffs = xx.__coeffs[:]
++        out._coeffs = xx._coeffs[:]
+     else:
+-        out.__coeffs = xx.__coeffs
++        out._coeffs = xx._coeffs
+     if valshift > 0:
+         cshift_notrunc(out, out, -valshift, prec, prime_pow, True)
+     elif valshift == 0:
+@@ -458,12 +458,12 @@ cdef inline long cconv_mpz_t(celement out, mpz_t x, long prec, bint absolute, Po
+     mpz_set(n.value, x)
+ 
+     if n:
+-        out.__coeffs = [prime_pow.base_ring(n)]
++        out._coeffs = [prime_pow.base_ring(n)]
+         if not absolute:
+             valuation = cremove(out, out, prec, prime_pow)
+         creduce(out, out, prec, prime_pow)
+     else:
+-        out.__coeffs = []
++        out._coeffs = []
+ 
+     return valuation
+ 
+@@ -492,12 +492,12 @@ cdef inline int cconv_mpz_t_out(mpz_t out, celement x, long valshift, long prec,
+     else:
+         prime_pow.powhelper_cconv_out = x
+ 
+-    if len(prime_pow.powhelper_cconv_out.__coeffs) == 0:
++    if len(prime_pow.powhelper_cconv_out._coeffs) == 0:
+         mpz_set_ui(out, 0)
+-    elif len(prime_pow.powhelper_cconv_out.__coeffs) == 1:
++    elif len(prime_pow.powhelper_cconv_out._coeffs) == 1:
+         # recursively let the underlying polynomial convert the constant
+         # coefficient to an integer (if possible)
+-        n = ZZ(prime_pow.powhelper_cconv_out.__coeffs[0])
++        n = ZZ(prime_pow.powhelper_cconv_out._coeffs[0])
+         mpz_set(out, n.value)
+     else:
+         raise ValueError("cannot convert to integer")
+@@ -532,7 +532,7 @@ cdef inline long cconv_mpq_t(celement out, mpq_t x, long prec, bint absolute, Po
+     """
+     cdef Rational r = PY_NEW(Rational)
+     mpq_set(r.value, x)
+-    out.__coeffs = [prime_pow.base_ring(r)]
++    out._coeffs = [prime_pow.base_ring(r)]
+ 
+     if not absolute:
+         return cremove(out, out, prec, prime_pow)
+@@ -565,12 +565,12 @@ cdef inline int cconv_mpq_t_out(mpq_t out, celement x, long valshift, long prec,
+     else:
+         prime_pow.powhelper_cconv_out = x
+ 
+-    if len(prime_pow.powhelper_cconv_out.__coeffs) == 0:
++    if len(prime_pow.powhelper_cconv_out._coeffs) == 0:
+         mpq_set_ui(out, 0, 1)
+-    elif len(prime_pow.powhelper_cconv_out.__coeffs) == 1:
++    elif len(prime_pow.powhelper_cconv_out._coeffs) == 1:
+         # recursively let the underlying polynomial convert the constant
+         # coefficient to a rational (if possible)
+-        c = QQ(prime_pow.powhelper_cconv_out.__coeffs[0])
++        c = QQ(prime_pow.powhelper_cconv_out._coeffs[0])
+         mpq_set(out, c.value)
+     else:
+         raise ValueError("cannot convert to rational")
+diff --git a/src/sage/libs/ntl/ntl_lzz_p.pyx b/src/sage/libs/ntl/ntl_lzz_p.pyx
+index 161d0782bc2..af86b9bcf69 100644
+--- a/src/sage/libs/ntl/ntl_lzz_p.pyx
++++ b/src/sage/libs/ntl/ntl_lzz_p.pyx
+@@ -89,19 +89,19 @@ cdef class ntl_zz_p():
+         #self.c.restore_c()   ## This was done in __new__
+ 
+         if isinstance(a, IntegerMod_int):
+-            if (self.c.p == (<IntegerMod_int>a).__modulus.int32): ## this is slow
++            if (self.c.p == (<IntegerMod_int>a)._modulus.int32): ## this is slow
+                 self.x = (<IntegerMod_int>a).ivalue
+             else:
+                 raise ValueError("Mismatched modulus for converting to zz_p.")
+ 
+         elif isinstance(a, IntegerMod_int64):
+-            if (self.c.p == (<IntegerMod_int64>a).__modulus.int64): ## this is slow
++            if (self.c.p == (<IntegerMod_int64>a)._modulus.int64): ## this is slow
+                 self.x = (<IntegerMod_int64>a).ivalue
+             else:
+                 raise ValueError("Mismatched modulus for converting to zz_p.")
+ 
+         elif isinstance(a, IntegerMod_gmp):
+-            if (p_sage == (<IntegerMod_gmp>a).__modulus.sageInteger): ## this is slow
++            if (p_sage == (<IntegerMod_gmp>a)._modulus.sageInteger): ## this is slow
+                 self.x = mpz_get_si((<IntegerMod_gmp>a).value)
+             else:
+                 raise ValueError("Mismatched modulus for converting to zz_p.")
+diff --git a/src/sage/libs/ntl/ntl_lzz_pX.pyx b/src/sage/libs/ntl/ntl_lzz_pX.pyx
+index 24b503a9a62..7d19cc55e37 100644
+--- a/src/sage/libs/ntl/ntl_lzz_pX.pyx
++++ b/src/sage/libs/ntl/ntl_lzz_pX.pyx
+@@ -108,17 +108,17 @@ cdef class ntl_zz_pX():
+             a = ls[i]
+ 
+             if isinstance(a, IntegerMod_int):
+-                if (self.c.p == (<IntegerMod_int>a).__modulus.int32): ## this is slow
++                if (self.c.p == (<IntegerMod_int>a)._modulus.int32): ## this is slow
+                     zz_pX_SetCoeff_long(self.x, i, (<IntegerMod_int>a).ivalue)
+                 else:
+                     raise ValueError("Mismatched modulus for converting to zz_pX.")
+             elif isinstance(a, IntegerMod_int64):
+-                if (self.c.p == (<IntegerMod_int64>a).__modulus.int64): ## this is slow
++                if (self.c.p == (<IntegerMod_int64>a)._modulus.int64): ## this is slow
+                     zz_pX_SetCoeff_long(self.x, i, (<IntegerMod_int64>a).ivalue)
+                 else:
+                     raise ValueError("Mismatched modulus for converting to zz_pX.")
+             elif isinstance(a, IntegerMod_gmp):
+-                if (p_sage == (<IntegerMod_gmp>a).__modulus.sageInteger): ## this is slow
++                if (p_sage == (<IntegerMod_gmp>a)._modulus.sageInteger): ## this is slow
+                     zz_pX_SetCoeff_long(self.x, i, mpz_get_si((<IntegerMod_gmp>a).value))
+                 else:
+                     raise ValueError("Mismatched modulus for converting to zz_pX.")
+diff --git a/src/sage/matrix/matrix_complex_ball_dense.pyx b/src/sage/matrix/matrix_complex_ball_dense.pyx
+index 9e14079c6d4..47ca41070fa 100644
+--- a/src/sage/matrix/matrix_complex_ball_dense.pyx
++++ b/src/sage/matrix/matrix_complex_ball_dense.pyx
+@@ -664,7 +664,7 @@ cdef class Matrix_complex_ball_dense(Matrix_dense):
+         Pol = polynomial_ring_constructor._single_variate(self.base_ring(), var)
+         cdef Polynomial_complex_arb res = Polynomial_complex_arb(Pol)
+         sig_on()
+-        acb_mat_charpoly(res.__poly, self.value, prec(self))
++        acb_mat_charpoly(res._poly, self.value, prec(self))
+         sig_off()
+         return res
+ 
+diff --git a/src/sage/matrix/matrix_cyclo_dense.pyx b/src/sage/matrix/matrix_cyclo_dense.pyx
+index 15ff6394951..f1ed9af8403 100644
+--- a/src/sage/matrix/matrix_cyclo_dense.pyx
++++ b/src/sage/matrix/matrix_cyclo_dense.pyx
+@@ -396,11 +396,11 @@ cdef class Matrix_cyclo_dense(Matrix_dense):
+             # Now set k-th entry of x's numerator to tmp
+             fmpz_get_mpz(tmp, ftmp)
+             mpz_to_ZZ(&coeff, tmp)
+-            ZZX_SetCoeff(x.__numerator, k, coeff)
++            ZZX_SetCoeff(x._numerator, k, coeff)
+ 
+         # Set the denominator of x to denom.
+         fmpz_get_mpz(tmp, denom)
+-        mpz_to_ZZ(&x.__denominator, tmp)
++        mpz_to_ZZ(&x._denominator, tmp)
+         fmpz_clear(denom)
+         mpz_clear(tmp)
+         fmpz_clear(ftmp)
+diff --git a/src/sage/matrix/matrix_integer_dense.pyx b/src/sage/matrix/matrix_integer_dense.pyx
+index 9c509104967..8088350577c 100644
+--- a/src/sage/matrix/matrix_integer_dense.pyx
++++ b/src/sage/matrix/matrix_integer_dense.pyx
+@@ -1371,12 +1371,12 @@ cdef class Matrix_integer_dense(Matrix_dense):
+         if algorithm == 'flint':
+             g = (<Polynomial_integer_dense_flint> PolynomialRing(ZZ, names=var).gen())._new()
+             sig_on()
+-            fmpz_mat_charpoly(g.__poly, self._matrix)
++            fmpz_mat_charpoly(g._poly, self._matrix)
+             sig_off()
+         elif algorithm == 'linbox':
+             g = (<Polynomial_integer_dense_flint> PolynomialRing(ZZ, names=var).gen())._new()
+             sig_on()
+-            linbox_fmpz_mat_charpoly(g.__poly, self._matrix)
++            linbox_fmpz_mat_charpoly(g._poly, self._matrix)
+             sig_off()
+         elif algorithm == 'generic':
+             g = Matrix_dense.charpoly(self, var)
+@@ -1460,7 +1460,7 @@ cdef class Matrix_integer_dense(Matrix_dense):
+         if algorithm == 'linbox':
+             g = (<Polynomial_integer_dense_flint> PolynomialRing(ZZ, names=var).gen())._new()
+             sig_on()
+-            linbox_fmpz_mat_minpoly(g.__poly, self._matrix)
++            linbox_fmpz_mat_minpoly(g._poly, self._matrix)
+             sig_off()
+         elif algorithm == 'generic':
+             g = Matrix_dense.minpoly(self, var)
+diff --git a/src/sage/matrix/matrix_integer_sparse.pyx b/src/sage/matrix/matrix_integer_sparse.pyx
+index a41677c7b6a..83d5ee42fbe 100644
+--- a/src/sage/matrix/matrix_integer_sparse.pyx
++++ b/src/sage/matrix/matrix_integer_sparse.pyx
+@@ -869,10 +869,10 @@ cdef class Matrix_integer_sparse(Matrix_sparse):
+         sig_off()
+ 
+         cdef size_t i
+-        fmpz_poly_fit_length(g.__poly, p.size())
++        fmpz_poly_fit_length(g._poly, p.size())
+         for i in range(p.size()):
+-            fmpz_poly_set_coeff_mpz(g.__poly, i, p[0][i].get_mpz_const())
+-        _fmpz_poly_set_length(g.__poly, p.size())
++            fmpz_poly_set_coeff_mpz(g._poly, i, p[0][i].get_mpz_const())
++        _fmpz_poly_set_length(g._poly, p.size())
+ 
+         del M
+         del p
+@@ -968,10 +968,10 @@ cdef class Matrix_integer_sparse(Matrix_sparse):
+         sig_off()
+ 
+         cdef size_t i
+-        fmpz_poly_fit_length(g.__poly, p.size())
++        fmpz_poly_fit_length(g._poly, p.size())
+         for i in range(p.size()):
+-            fmpz_poly_set_coeff_mpz(g.__poly, i, p[0][i].get_mpz_const())
+-        _fmpz_poly_set_length(g.__poly, p.size())
++            fmpz_poly_set_coeff_mpz(g._poly, i, p[0][i].get_mpz_const())
++        _fmpz_poly_set_length(g._poly, p.size())
+ 
+         del M
+         del p
+diff --git a/src/sage/matroids/basis_exchange_matroid.pxd b/src/sage/matroids/basis_exchange_matroid.pxd
+index aec3bb54c42..28cc7ad868c 100644
+--- a/src/sage/matroids/basis_exchange_matroid.pxd
++++ b/src/sage/matroids/basis_exchange_matroid.pxd
+@@ -15,13 +15,13 @@ cdef class BasisExchangeMatroid(Matroid):
+     cdef _weak_invariant_var, _strong_invariant_var, _heuristic_invariant_var
+     cdef SetSystem _weak_partition_var, _strong_partition_var, _heuristic_partition_var
+ 
+-    cdef __relabel(self, l)
++    cdef _relabel(self, l)
+ 
+-    cdef __pack(self, bitset_t, X)
++    cdef _pack(self, bitset_t, X)
+     cdef __unpack(self, bitset_t)
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1
+-    cdef int __exchange(self, long x, long y) except -1
+-    cdef int __move(self, bitset_t X, bitset_t Y) except -1
++    cdef bint _is_exchange_pair(self, long x, long y) except -1
++    cdef int _exchange(self, long x, long y) except -1
++    cdef int _move(self, bitset_t X, bitset_t Y) except -1
+     cdef __fundamental_cocircuit(self, bitset_t, long x)
+     cdef __fundamental_circuit(self, bitset_t, long y)
+ 
+@@ -30,7 +30,7 @@ cdef class BasisExchangeMatroid(Matroid):
+     cdef __closure(self, bitset_t, bitset_t)
+     cdef __max_coindependent(self, bitset_t, bitset_t)
+     cdef __cocircuit(self, bitset_t, bitset_t)
+-    cdef __coclosure(self, bitset_t, bitset_t)
++    cdef _coclosure_internal(self, bitset_t, bitset_t)
+ 
+     cdef __augment(self, bitset_t, bitset_t, bitset_t)
+     cdef bint __is_independent(self, bitset_t F) except -1
+diff --git a/src/sage/matroids/basis_exchange_matroid.pyx b/src/sage/matroids/basis_exchange_matroid.pyx
+index 90d10842d46..015fa8b8df3 100644
+--- a/src/sage/matroids/basis_exchange_matroid.pyx
++++ b/src/sage/matroids/basis_exchange_matroid.pyx
+@@ -57,10 +57,10 @@ cdef class BasisExchangeMatroid(Matroid):
+ 
+     This base exchange graph is not stored as such, but should be provided
+     implicitly by the child class in the form of two methods
+-    ``__is_exchange_pair(x, y)`` and ``__exchange(x, y)``, as well as an
++    ``_is_exchange_pair(x, y)`` and ``_exchange(x, y)``, as well as an
+     initial basis. At any moment, BasisExchangeMatroid keeps a current basis
+-    `B`. The method ``__is_exchange_pair(x, y)`` should return a boolean
+-    indicating whether `B - x + y` is a basis. The method ``__exchange(x, y)``
++    `B`. The method ``_is_exchange_pair(x, y)`` should return a boolean
++    indicating whether `B - x + y` is a basis. The method ``_exchange(x, y)``
+     is called when the current basis `B` is replaced by said `B-x + y`. It is
+     up to the child class to update its internal data structure to make
+     information relative to the new basis more accessible. For instance, a
+@@ -81,16 +81,16 @@ cdef class BasisExchangeMatroid(Matroid):
+     - :class:`BasisMatroid <sage.matroids.basis_matroid.BasisMatroid>`: keeps
+       a list of all bases.
+ 
+-        - ``__is_exchange_pair(x, y)`` reduces to a query whether `B - x + y`
++        - ``_is_exchange_pair(x, y)`` reduces to a query whether `B - x + y`
+           is a basis.
+-        - ``__exchange(x, y)`` has no work to do.
++        - ``_exchange(x, y)`` has no work to do.
+ 
+     - :class:`LinearMatroid <sage.matroids.linear_matroid.LinearMatroid>`:
+       keeps a matrix representation `A` of the matroid so that `A[B] = I`.
+ 
+-        - ``__is_exchange_pair(x, y)`` reduces to testing whether `A[r, y]`
++        - ``_is_exchange_pair(x, y)`` reduces to testing whether `A[r, y]`
+           is nonzero, where `A[r, x]=1`.
+-        - ``__exchange(x, y)`` should modify the matrix so that `A[B - x + y]`
++        - ``_exchange(x, y)`` should modify the matrix so that `A[B - x + y]`
+           becomes `I`, which means pivoting on `A[r, y]`.
+ 
+     - ``TransversalMatroid`` (not yet implemented): If `A` is a set of subsets
+@@ -100,17 +100,17 @@ cdef class BasisExchangeMatroid(Matroid):
+       edge `(A_i,e)` if `e` is in the subset `A_i`. At any time you keep a
+       maximum matching `M` of `G` covering the current basis `B`.
+ 
+-        - ``__is_exchange_pair(x, y)`` checks for the existence of an
++        - ``_is_exchange_pair(x, y)`` checks for the existence of an
+           `M`-alternating path `P` from `y` to `x`.
+-        - ``__exchange(x, y)`` replaces `M` by the symmetric difference of
++        - ``_exchange(x, y)`` replaces `M` by the symmetric difference of
+           `M` and `E(P)`.
+ 
+     - ``AlgebraicMatroid`` (not yet implemented): keeps a list of polynomials
+       in variables `E - B + e` for each variable `e` in `B`.
+ 
+-        - ``__is_exchange_pair(x, y)`` checks whether the polynomial that
++        - ``_is_exchange_pair(x, y)`` checks whether the polynomial that
+           relates `y` to `E-B` uses `x`.
+-        - ``__exchange(x, y)`` make new list of polynomials by computing
++        - ``_exchange(x, y)`` make new list of polynomials by computing
+           resultants.
+ 
+     All but the first of the above matroids are algebraic, and all
+@@ -139,7 +139,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         This initializer sets up a correspondence between elements of
+         ``groundset`` and ``range(len(groundset))``. ``BasisExchangeMatroid``
+         uses this correspondence for encoding of subsets of the groundset as
+-        bitpacked sets of integers --- see ``__pack()`` and ``__unpack()``. In
++        bitpacked sets of integers --- see ``_pack()`` and ``__unpack()``. In
+         general, methods of ``BasisExchangeMatroid`` having a name starting
+         with two underscores deal with such encoded subsets.
+ 
+@@ -180,7 +180,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             self._idx[self._E[i]] = i
+ 
+         if basis is not None:
+-            self.__pack(self._current_basis, frozenset(basis))
++            self._pack(self._current_basis, frozenset(basis))
+ 
+     def __dealloc__(self):
+         bitset_free(self._current_basis)
+@@ -191,7 +191,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_free(self._output)
+         bitset_free(self._temp)
+ 
+-    cdef __relabel(self, l):
++    cdef _relabel(self, l):
+         """
+         Relabel each element `e` as `l[e]`, where `l` is a given injective map.
+ 
+@@ -231,7 +231,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             self._heuristic_partition_var._relabel(l)
+ 
+     # the engine
+-    cdef __pack(self, bitset_t I, F):
++    cdef _pack(self, bitset_t I, F):
+         """
+         Encode a subset F of the groundset into a bitpacked set of integers
+         """
+@@ -252,21 +252,21 @@ cdef class BasisExchangeMatroid(Matroid):
+         return frozenset(F)
+ 
+     # this method needs to be overridden by child class
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         """
+         Test if current_basis-x + y is a basis
+         """
+         raise NotImplementedError
+ 
+     # if this method is overridden by a child class, the child class needs to call this method
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         """
+         put current_basis <-- current_basis-x + y
+         """
+         bitset_discard(self._current_basis, x)
+         bitset_add(self._current_basis, y)
+ 
+-    cdef int __move(self, bitset_t X, bitset_t Y) except -1:
++    cdef int _move(self, bitset_t X, bitset_t Y) except -1:
+         """
+         Change current_basis to minimize intersection with ``X``, maximize intersection with ``Y``.
+         """
+@@ -275,8 +275,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         while x >= 0:
+             y = bitset_first(Y)
+             while y >= 0:
+-                if self.__is_exchange_pair(x, y):
+-                    self.__exchange(x, y)
++                if self._is_exchange_pair(x, y):
++                    self._exchange(x, y)
+                     bitset_discard(Y, y)
+                     bitset_discard(X, x)
+                     if bitset_isempty(Y):
+@@ -295,7 +295,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_complement(self._temp, self._current_basis)
+         y = bitset_first(self._temp)
+         while y >= 0:
+-            if self.__is_exchange_pair(x, y):
++            if self._is_exchange_pair(x, y):
+                 bitset_add(C, y)
+             y = bitset_next(self._temp, y + 1)
+         bitset_add(C, x)
+@@ -308,7 +308,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_clear(C)
+         x = bitset_first(self._current_basis)
+         while x >= 0:
+-            if self.__is_exchange_pair(x, y):
++            if self._is_exchange_pair(x, y):
+                 bitset_add(C, x)
+             x = bitset_next(self._current_basis, x + 1)
+         bitset_add(C, y)
+@@ -319,7 +319,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, F)
+         bitset_difference(self._outside, F, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_intersection(R, self._current_basis, F)
+ 
+     cdef __circuit(self, bitset_t R, bitset_t F):
+@@ -335,8 +335,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         while y >= 0:
+             x = bitset_first(self._inside)
+             while x >= 0:
+-                if self.__is_exchange_pair(x, y):
+-                    self.__exchange(x, y)
++                if self._is_exchange_pair(x, y):
++                    self._exchange(x, y)
+                     bitset_discard(self._outside, y)
+                     bitset_discard(self._inside, x)
+                     if bitset_isempty(self._outside):
+@@ -355,7 +355,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, F)
+         bitset_difference(self._outside, F, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_set_first_n(R, self._groundset_size)
+         cdef long x = bitset_first(self._inside)
+         while x >= 0:
+@@ -370,7 +370,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_difference(R, F, self._current_basis)
+ 
+     cdef __cocircuit(self, bitset_t R, bitset_t F):
+@@ -387,8 +387,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         while x >= 0:
+             y = bitset_first(self._outside)
+             while y >= 0:
+-                if self.__is_exchange_pair(x, y):
+-                    self.__exchange(x, y)
++                if self._is_exchange_pair(x, y):
++                    self._exchange(x, y)
+                     bitset_discard(self._outside, y)
+                     bitset_discard(self._inside, x)
+                     if bitset_isempty(self._inside):
+@@ -401,14 +401,14 @@ cdef class BasisExchangeMatroid(Matroid):
+                 return
+             x = bitset_next(self._inside, x + 1)
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``closure``.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_set_first_n(R, self._groundset_size)
+         cdef long y = bitset_first(self._outside)
+         while y >= 0:
+@@ -422,10 +422,10 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, X)
+         bitset_difference(self._outside, X, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_difference(self._inside, self._inside, Y)
+         bitset_difference(self._outside, Y, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_intersection(R, self._current_basis, Y)
+ 
+     cdef bint __is_independent(self, bitset_t F) except -1:
+@@ -434,7 +434,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, F)
+         bitset_difference(self._outside, F, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         return bitset_isempty(self._outside)
+ 
+     cdef __move_current_basis(self, bitset_t X, bitset_t Y):
+@@ -443,21 +443,21 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, X)
+         bitset_difference(self._outside, X, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_intersection(self._inside, self._current_basis, Y)
+         bitset_complement(self._outside, self._current_basis)
+         bitset_difference(self._outside, self._outside, Y)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+     # functions for derived classes and for parent class
+     cdef bint _set_current_basis(self, F):
+         """
+         Set _current_basis to subset of the groundset ``F``.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         bitset_difference(self._inside, self._current_basis, self._input)
+         bitset_difference(self._outside, self._input, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         return bitset_isempty(self._outside) and bitset_isempty(self._inside)
+ 
+     # groundset and full_rank
+@@ -630,8 +630,8 @@ cdef class BasisExchangeMatroid(Matroid):
+             ['b', 'c', 'e', 'f']
+ 
+         """
+-        self.__pack(self._input, X)
+-        self.__pack(self._input2, Y)
++        self._pack(self._input, X)
++        self._pack(self._input2, Y)
+         self.__move_current_basis(self._input, self._input2)
+ 
+     cpdef _max_independent(self, F):
+@@ -661,7 +661,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.max_independent>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_independent(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -692,7 +692,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.rank>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_independent(self._output, self._input)
+         return bitset_len(self._output)
+ 
+@@ -729,7 +729,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             the input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.circuit>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__circuit(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -754,7 +754,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             sage: sorted(M._fundamental_circuit('abcd', 'e'))
+             ['a', 'b', 'c', 'e']
+         """
+-        self.__pack(self._input, B)
++        self._pack(self._input, B)
+         bitset_clear(self._input2)
+         self.__move_current_basis(self._input, self._input2)
+         self.__fundamental_circuit(self._output, self._idx[e])
+@@ -787,7 +787,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             :meth:`<sage.matroids.matroid.Matroid.closure>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__closure(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -818,7 +818,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.max_coindependent>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_coindependent(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -848,7 +848,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.corank>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_coindependent(self._output, self._input)
+         return bitset_len(self._output)
+ 
+@@ -885,7 +885,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.cocircuit>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__cocircuit(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -910,7 +910,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             sage: sorted(M._fundamental_cocircuit('efgh', 'e'))
+             ['b', 'c', 'd', 'e']
+         """
+-        self.__pack(self._input, B)
++        self._pack(self._input, B)
+         bitset_clear(self._input2)
+         self.__move_current_basis(self._input, self._input2)
+         self.__fundamental_cocircuit(self._output, self._idx[e])
+@@ -943,8 +943,8 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.coclosure>`.
+ 
+         """
+-        self.__pack(self._input, F)
+-        self.__coclosure(self._output, self._input)
++        self._pack(self._input, F)
++        self._coclosure_internal(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+     cpdef _augment(self, X, Y):
+@@ -973,8 +973,8 @@ cdef class BasisExchangeMatroid(Matroid):
+             ['e', 'f', 'g']
+ 
+         """
+-        self.__pack(self._input, X)
+-        self.__pack(self._input2, Y)
++        self._pack(self._input, X)
++        self._pack(self._input2, Y)
+         self.__augment(self._output, self._input, self._input2)
+         return self.__unpack(self._output)
+ 
+@@ -1006,7 +1006,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             the input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.is_independent>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         return self.__is_independent(self._input)
+ 
+     # connectivity
+@@ -1142,8 +1142,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         cdef bitset_t SS, TT
+         bitset_init(SS, self._groundset_size)
+         bitset_init(TT, self._groundset_size)
+-        self.__pack(SS,S)
+-        self.__pack(TT,T)
++        self._pack(SS,S)
++        self._pack(TT,T)
+         #F = set(self.groundset()) - (S | T)
+         cdef bitset_t F, I
+         bitset_init(F, self._groundset_size)
+@@ -1421,7 +1421,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         Rcoflats = SetSystem(self._E)
+         i = 0
+         bitset_clear(todo[0])
+-        self.__coclosure(coflats[0], todo[0])
++        self._coclosure_internal(coflats[0], todo[0])
+         bitset_complement(todo[0], coflats[0])
+         self._coflats_rec(Rcoflats, r, coflats, todo, 0, 0)
+         for i in range(r + 1):
+@@ -1443,7 +1443,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         while e >= 0:
+             bitset_copy(self._input, coflats[i])
+             bitset_add(self._input, e)
+-            self.__coclosure(coflats[i + 1], self._input)
++            self._coclosure_internal(coflats[i + 1], self._input)
+             bitset_difference(todo[i], todo[i], coflats[i + 1])
+             bitset_difference(todo[i + 1], coflats[i + 1], coflats[i])
+             if bitset_first(todo[i + 1]) == e:
+@@ -2397,7 +2397,7 @@ cdef class BasisExchangeMatroid(Matroid):
+                 # Set current basis to Y
+                 bitset_difference(self._inside, self._current_basis, BB._subsets[pointerY])
+                 bitset_difference(self._outside, BB._subsets[pointerY], self._current_basis)
+-                self.__move(self._inside, self._outside)
++                self._move(self._inside, self._outside)
+                 if not bitset_eq(self._current_basis, BB._subsets[pointerY]):
+                     # We failed to set the current basis to Y through basis exchanges.
+                     # Therefore, the exchange axioms are violated!
+@@ -2409,7 +2409,7 @@ cdef class BasisExchangeMatroid(Matroid):
+                     foundpair = False
+                     y = bitset_first(self._input2)
+                     while y >= 0:  # for y in Y-X
+-                        if self.__is_exchange_pair(y, x):
++                        if self._is_exchange_pair(y, x):
+                             foundpair = True
+                             y = -1
+                         else:
+diff --git a/src/sage/matroids/basis_matroid.pyx b/src/sage/matroids/basis_matroid.pyx
+index 3ac43112627..c1b6e9b04c8 100644
+--- a/src/sage/matroids/basis_matroid.pyx
++++ b/src/sage/matroids/basis_matroid.pyx
+@@ -219,7 +219,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+                     raise ValueError("basis has wrong cardinality.")
+                 if not b.issubset(self._groundset):
+                     raise ValueError("basis is not a subset of the groundset")
+-                self.__pack(self._b, b)
++                self._pack(self._b, b)
+                 i = set_to_index(self._b)
+                 if not bitset_in(self._bb, i):
+                     self._bcount += 1
+@@ -234,7 +234,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+                         raise ValueError("nonbasis has wrong cardinality")
+                     if not b.issubset(self._groundset):
+                         raise ValueError("nonbasis is not a subset of the groundset")
+-                    self.__pack(self._b, b)
++                    self._pack(self._b, b)
+                     i = set_to_index(self._b)
+                     if bitset_in(self._bb, i):
+                         self._bcount -= 1
+@@ -263,7 +263,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+ 
+     # support for parent BasisExchangeMatroid
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:      # test if current_basis-x + y is a basis
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:      # test if current_basis-x + y is a basis
+         """
+         Test if `B-e + f` is a basis of the current matroid.
+ 
+@@ -326,7 +326,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+             sage: M._is_basis(set(['a', 'b', 'c', 'd']))
+             False
+         """
+-        self.__pack(self._b, X)
++        self._pack(self._b, X)
+         return bitset_in(self._bb, set_to_index(self._b))
+ 
+     # dual and minors
+@@ -557,7 +557,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+ 
+         """
+         M = BasisMatroid(M=self)
+-        M.__relabel(l)
++        M._relabel(l)
+         return M
+ 
+     # enumeration
+@@ -1177,7 +1177,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+ 
+         """
+         N = BasisMatroid(M=self)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo=None):
+@@ -1201,7 +1201,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+         if memo is None:
+             memo = {}
+         N = BasisMatroid(M=self)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __reduce__(self):
+@@ -1230,7 +1230,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+         """
+         import sage.matroids.unpickling
+         BB = bitset_pickle(self._bb)
+-        data = (self._E, self._matroid_rank, getattr(self, '__custom_name'), BB)
++        data = (self._E, self._matroid_rank, self.get_custom_name(), BB)
+         version = 0
+         return sage.matroids.unpickling.unpickle_basis_matroid, (version, data)
+ 
+diff --git a/src/sage/matroids/circuit_closures_matroid.pyx b/src/sage/matroids/circuit_closures_matroid.pyx
+index 402822b2dc6..4e79b0575e2 100644
+--- a/src/sage/matroids/circuit_closures_matroid.pyx
++++ b/src/sage/matroids/circuit_closures_matroid.pyx
+@@ -513,8 +513,7 @@ cdef class CircuitClosuresMatroid(Matroid):
+         N._groundset = self._groundset
+         N._circuit_closures = self._circuit_closures
+         N._matroid_rank = self._matroid_rank
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo=None):
+@@ -539,8 +538,7 @@ cdef class CircuitClosuresMatroid(Matroid):
+         from copy import deepcopy
+         # Since matroids are immutable, N cannot reference itself in correct code, so no need to worry about the recursion.
+         N = CircuitClosuresMatroid(groundset=deepcopy(self._groundset, memo), circuit_closures=deepcopy(self._circuit_closures, memo))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -570,7 +568,7 @@ cdef class CircuitClosuresMatroid(Matroid):
+              4: {{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}}}
+         """
+         import sage.matroids.unpickling
+-        data = (self._groundset, self._circuit_closures, getattr(self, '__custom_name'))
++        data = (self._groundset, self._circuit_closures, self.get_custom_name())
+         version = 0
+         return sage.matroids.unpickling.unpickle_circuit_closures_matroid, (version, data)
+ 
+diff --git a/src/sage/matroids/dual_matroid.py b/src/sage/matroids/dual_matroid.py
+index 804e43f035b..da6639827e4 100644
+--- a/src/sage/matroids/dual_matroid.py
++++ b/src/sage/matroids/dual_matroid.py
+@@ -519,9 +519,7 @@ def __copy__(self):
+ 
+         """
+         N = DualMatroid(self._matroid)
+-        if getattr(self, '__custom_name') is not None:
+-            # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -543,10 +541,7 @@ def __deepcopy__(self, memo={}):
+         """
+         from copy import deepcopy
+         N = DualMatroid(deepcopy(self._matroid, memo))
+-        if getattr(self, '__custom_name') is not None:
+-            # because of name wrangling, this is not caught by the
+-            # default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -575,6 +570,6 @@ def __reduce__(self):
+              4: {{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}}}'
+         """
+         import sage.matroids.unpickling
+-        data = (self._matroid, getattr(self, '__custom_name'))
++        data = (self._matroid, self.get_custom_name())
+         version = 0
+         return sage.matroids.unpickling.unpickle_dual_matroid, (version, data)
+diff --git a/src/sage/matroids/graphic_matroid.py b/src/sage/matroids/graphic_matroid.py
+index 5216ef11517..c727dc54e52 100644
+--- a/src/sage/matroids/graphic_matroid.py
++++ b/src/sage/matroids/graphic_matroid.py
+@@ -481,8 +481,7 @@ def __copy__(self):
+             False
+         """
+         N = GraphicMatroid(self._G)
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -502,8 +501,7 @@ def __deepcopy__(self, memo={}):
+         """
+         # The only real difference between this and __copy__() is the memo
+         N = GraphicMatroid(deepcopy(self._G, memo))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -519,7 +517,7 @@ def __reduce__(self):
+             Graphic matroid of rank 9 on 15 elements
+         """
+         from .unpickling import unpickle_graphic_matroid
+-        data = (self._G, getattr(self, '__custom_name'))
++        data = (self._G, self.get_custom_name())
+         version = 0
+         return unpickle_graphic_matroid, (version, data)
+ 
+diff --git a/src/sage/matroids/linear_matroid.pxd b/src/sage/matroids/linear_matroid.pxd
+index 014c8aef57d..9aebd446b68 100644
+--- a/src/sage/matroids/linear_matroid.pxd
++++ b/src/sage/matroids/linear_matroid.pxd
+@@ -15,7 +15,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+     cpdef characteristic(self)
+ 
+     cdef list _setup_internal_representation(self, matrix, reduced_matrix, ring, keep_initial_representation)
+-    cdef __exchange_value(self, long x, long y)
++    cdef _exchange_value_internal(self, long x, long y)
+ 
+     cpdef representation(self, B=*, reduced=*, labels=*, order=*, lift_map=*)
+     cpdef _current_rows_cols(self, B=*)
+diff --git a/src/sage/matroids/linear_matroid.pyx b/src/sage/matroids/linear_matroid.pyx
+index 61452e80c48..36f563aa433 100644
+--- a/src/sage/matroids/linear_matroid.pyx
++++ b/src/sage/matroids/linear_matroid.pyx
+@@ -391,13 +391,13 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         """
+         return characteristic(self._A)
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return self._A.is_nonzero(self._prow[x], self._prow[y])
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         """
+         Put element indexed by ``x`` into basis, taking out element ``y``.
+         Assumptions are that this is a valid basis exchange.
+@@ -420,9 +420,9 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         self._A.set_unsafe(px, py, pivi)
+         self._prow[y] = px
+         self._prow[x] = py
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -605,7 +605,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+                     self._representation = self._basic_representation(B)
+                 A = self._representation
+             else:
+-                B = self.__subset(B)
++                B = self._subset_internal(B)
+                 A = self._basic_representation(B)
+             A = A.matrix_from_rows_and_columns(range(A.nrows()), order_idx)
+             if lift_map is None:
+@@ -622,7 +622,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+             if B is None:
+                 B = frozenset(self.basis())
+             else:
+-                B = self.__subset(B)
++                B = self._subset_internal(B)
+             A = self._reduced_representation(B)
+             R, C = self._current_rows_cols()
+             Ri = []
+@@ -1493,7 +1493,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+             sage: M._exchange_value(1, 3)
+             4
+         """
+-        return self.__exchange_value(self._idx[e], self._idx[f])
++        return self._exchange_value_internal(self._idx[e], self._idx[f])
+ 
+     cpdef fundamental_cycle(self, B, e):
+         """
+@@ -2909,7 +2909,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = LinearMatroid(groundset=rows + cols, reduced_matrix=self._A)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -2930,7 +2930,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = LinearMatroid(groundset=deepcopy(rows + cols, memo), reduced_matrix=deepcopy(self._A, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -2979,7 +2979,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+             rows, cols = self._current_rows_cols()
+             gs = rows + cols
+             reduced = True
+-        data = (A, gs, reduced, getattr(self, '__custom_name'))
++        data = (A, gs, reduced, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_linear_matroid, (version, data)
+ 
+ # Binary matroid
+@@ -3152,20 +3152,20 @@ cdef class BinaryMatroid(LinearMatroid):
+         """
+         return 2
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<BinaryMatrix>self._A).is_nonzero(self._prow[x], y)
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         r"""
+         Replace ``self.basis() with ``self.basis() - x + y``. Internal method, does no checks.
+         """
+         cdef long p = self._prow[x]
+         self._A.pivot(p, y)   # Not a Sage matrix operation
+         self._prow[y] = p
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+     cdef  __fundamental_cocircuit(self, bitset_t C, long x):
+         r"""
+@@ -3173,18 +3173,18 @@ cdef class BinaryMatroid(LinearMatroid):
+         """
+         bitset_copy(C, (<BinaryMatrix>self._A)._M[self._prow[x]])
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``coclosure``.
+ 
+-        This function overrides the internal function BasisExchangeMatroid.__coclosure() of the parent class.
++        This function overrides the internal function BasisExchangeMatroid._coclosure_internal() of the parent class.
+         The implementation should be more efficient for BinaryMatroid, due to the fact that in this class,
+         __fundamental_cocircuit is much faster than __fundamental_circuit.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+         bitset_copy(R, F)
+         bitset_difference(self._inside, self._current_basis, F)
+@@ -3196,7 +3196,7 @@ cdef class BinaryMatroid(LinearMatroid):
+                 bitset_add(R, y)
+             y = bitset_next(self._inside, y + 1)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -3964,7 +3964,7 @@ cdef class BinaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = BinaryMatroid(groundset=self._E, matrix=self._A, basis=basis)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -3989,7 +3989,7 @@ cdef class BinaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = BinaryMatroid(groundset=deepcopy(self._E, memo), matrix=deepcopy(self._A, memo), basis=deepcopy(basis, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -4047,7 +4047,7 @@ cdef class BinaryMatroid(LinearMatroid):
+             A = self._A
+             # current basis ordered so matrix cols form identity matrix:
+             basis = self._current_rows_cols()[0]
+-        data = (A, gs, basis, getattr(self, '__custom_name'))
++        data = (A, gs, basis, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_binary_matroid, (version, data)
+ 
+ cdef class TernaryMatroid(LinearMatroid):
+@@ -4220,20 +4220,20 @@ cdef class TernaryMatroid(LinearMatroid):
+         """
+         return 3
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<TernaryMatrix>self._A).is_nonzero(self._prow[x], y)
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         r"""
+         Replace ``self.basis() with ``self.basis() - x + y``. Internal method, does no checks.
+         """
+         cdef long p = self._prow[x]
+         self._A.pivot(p, y)   # Not a Sage matrix operation
+         self._prow[y] = p
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+     cdef  __fundamental_cocircuit(self, bitset_t C, long x):
+         r"""
+@@ -4241,18 +4241,18 @@ cdef class TernaryMatroid(LinearMatroid):
+         """
+         bitset_copy(C, (<TernaryMatrix>self._A)._M0[self._prow[x]])
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``coclosure``.
+ 
+-        This function overrides the internal function BasisExchangeMatroid.__coclosure() of the parent class.
++        This function overrides the internal function BasisExchangeMatroid._coclosure_internal() of the parent class.
+         The implementation should be more efficient for TernaryMatroid, due to the fact that in this class,
+         __fundamental_cocircuit is much faster than __fundamental_circuit.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+         bitset_copy(R, F)
+         bitset_difference(self._inside, self._current_basis, F)
+@@ -4264,7 +4264,7 @@ cdef class TernaryMatroid(LinearMatroid):
+                 bitset_add(R, y)
+             y = bitset_next(self._inside, y + 1)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -4858,7 +4858,7 @@ cdef class TernaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = TernaryMatroid(groundset=self._E, matrix=self._A, basis=basis)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -4883,7 +4883,7 @@ cdef class TernaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = TernaryMatroid(groundset=deepcopy(self._E, memo), matrix=deepcopy(self._A, memo), basis=deepcopy(basis, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -4945,7 +4945,7 @@ cdef class TernaryMatroid(LinearMatroid):
+             A = self._A
+             # current basis ordered so matrix cols form identity matrix:
+             basis = self._current_rows_cols()[0]
+-        data = (A, gs, basis, getattr(self, '__custom_name'))
++        data = (A, gs, basis, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_ternary_matroid, (version, data)
+ 
+ # Quaternary Matroids
+@@ -5122,20 +5122,20 @@ cdef class QuaternaryMatroid(LinearMatroid):
+         """
+         return 2
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<QuaternaryMatrix>self._A).is_nonzero(self._prow[x], y)
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         r"""
+         Replace ``self.basis() with ``self.basis() - x + y``. Internal method, does no checks.
+         """
+         cdef long p = self._prow[x]
+         self._A.pivot(p, y)   # Not a Sage matrix operation
+         self._prow[y] = p
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+     cdef  __fundamental_cocircuit(self, bitset_t C, long x):
+         r"""
+@@ -5143,18 +5143,18 @@ cdef class QuaternaryMatroid(LinearMatroid):
+         """
+         bitset_union(C, (<QuaternaryMatrix>self._A)._M0[self._prow[x]], (<QuaternaryMatrix>self._A)._M1[self._prow[x]])
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``coclosure``.
+ 
+-        This function overrides the internal function BasisExchangeMatroid.__coclosure() of the parent class.
++        This function overrides the internal function BasisExchangeMatroid._coclosure_internal() of the parent class.
+         The implementation should be more efficient for QuaternaryMatroid, due to the fact that in this class,
+         __fundamental_cocircuit is much faster than __fundamental_circuit.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+         bitset_copy(R, F)
+         bitset_difference(self._inside, self._current_basis, F)
+@@ -5166,7 +5166,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+                 bitset_add(R, y)
+             y = bitset_next(self._inside, y + 1)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -5589,7 +5589,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = QuaternaryMatroid(groundset=self._E, matrix=self._A, basis=basis)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -5614,7 +5614,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = QuaternaryMatroid(groundset=deepcopy(self._E, memo), matrix=deepcopy(self._A, memo), basis=deepcopy(basis, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -5672,7 +5672,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+             A = self._A
+             # current basis ordered so matrix cols form identity matrix:
+             basis = self._current_rows_cols()[0]
+-        data = (A, gs, basis, getattr(self, '__custom_name'))
++        data = (A, gs, basis, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_quaternary_matroid, (version, data)
+ 
+ # Regular Matroids
+@@ -5838,13 +5838,13 @@ cdef class RegularMatroid(LinearMatroid):
+         """
+         return 0
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<PlusMinusOneMatrix>self._A).is_nonzero(self._prow[x], self._prow[y])
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         """
+         Put element indexed by ``x`` into basis, taking out element ``y``. Assumptions are that this is a valid basis exchange.
+ 
+@@ -5867,9 +5867,9 @@ cdef class RegularMatroid(LinearMatroid):
+         (<PlusMinusOneMatrix>self._A).set(px, py, pivi)   # Not a Sage matrix operation
+         self._prow[y] = px
+         self._prow[x] = py
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+ 
+@@ -6524,7 +6524,7 @@ cdef class RegularMatroid(LinearMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = RegularMatroid(groundset=rows + cols, reduced_matrix=self._A)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -6544,7 +6544,7 @@ cdef class RegularMatroid(LinearMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = RegularMatroid(groundset=deepcopy(rows + cols, memo), reduced_matrix=deepcopy(self._A, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -6593,5 +6593,5 @@ cdef class RegularMatroid(LinearMatroid):
+             rows, cols = self._current_rows_cols()
+             gs = rows + cols
+             reduced = True
+-        data = (A, gs, reduced, getattr(self, '__custom_name'))
++        data = (A, gs, reduced, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_regular_matroid, (version, data)
+diff --git a/src/sage/matroids/matroid.pxd b/src/sage/matroids/matroid.pxd
+index fe6c07e3b71..e9ddfec96ae 100644
+--- a/src/sage/matroids/matroid.pxd
++++ b/src/sage/matroids/matroid.pxd
+@@ -1,8 +1,7 @@
+ from sage.structure.sage_object cimport SageObject
+ 
+ cdef class Matroid(SageObject):
+-    cdef public __custom_name
+-    cdef public _custom_name
++    cdef public _SageObject__custom_name
+     cdef public _cached_info
+     cdef int _stored_full_rank
+     cdef int _stored_size
+@@ -37,7 +36,7 @@ cdef class Matroid(SageObject):
+     cpdef _line_length(self, F)
+     cpdef _extension(self, element, hyperplanes)
+ 
+-    cdef inline __subset(self, X):
++    cdef inline _subset_internal(self, X):
+         """
+         Convert ``X`` to a ``frozenset`` and check that it is a subset
+         of the groundset.
+diff --git a/src/sage/matroids/matroid.pyx b/src/sage/matroids/matroid.pyx
+index dcee87ea49c..8ac5ec3f678 100644
+--- a/src/sage/matroids/matroid.pyx
++++ b/src/sage/matroids/matroid.pyx
+@@ -1307,7 +1307,7 @@ cdef class Matroid(SageObject):
+             TypeError: 'sage.rings.integer.Integer' object is not iterable
+         """
+         # Call corresponding Cython method
+-        return self.__subset(X)
++        return self._subset_internal(X)
+ 
+     def _subset_all(self, X):
+         """
+@@ -1374,7 +1374,7 @@ cdef class Matroid(SageObject):
+         """
+         if X is None:
+             return self.full_rank()
+-        return self._rank(self.__subset(X))
++        return self._rank(self._subset_internal(X))
+ 
+     cpdef full_rank(self):
+         r"""
+@@ -1453,7 +1453,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._max_independent(self.__subset(X))
++        return self._max_independent(self._subset_internal(X))
+ 
+     cpdef circuit(self, X=None):
+         """
+@@ -1558,7 +1558,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._closure(self.__subset(X))
++        return self._closure(self._subset_internal(X))
+ 
+     cpdef k_closure(self, X, k):
+         r"""
+@@ -1597,7 +1597,7 @@ cdef class Matroid(SageObject):
+             sage: sorted(M.k_closure({0,1}, 4))
+             [0, 1, 4]
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         cdef int cur
+         cdef frozenset S, cl
+         cur = 0
+@@ -1644,7 +1644,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         Y = self.__subset_all(Y)
+         return self._augment(X, Y.difference(X))
+ 
+@@ -1781,7 +1781,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._max_coindependent(self.__subset(X))
++        return self._max_coindependent(self._subset_internal(X))
+ 
+     cpdef coclosure(self, X):
+         """
+@@ -1813,7 +1813,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._coclosure(self.__subset(X))
++        return self._coclosure(self._subset_internal(X))
+ 
+     cpdef cocircuit(self, X=None):
+         """
+@@ -1947,7 +1947,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_independent(self.__subset(X))
++        return self._is_independent(self._subset_internal(X))
+ 
+     cpdef is_dependent(self, X):
+         r"""
+@@ -1973,7 +1973,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return not self._is_independent(self.__subset(X))
++        return not self._is_independent(self._subset_internal(X))
+ 
+     cpdef is_basis(self, X):
+         r"""
+@@ -1999,7 +1999,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         if len(X) != self.full_rank():
+             return False
+         return self._is_basis(X)
+@@ -2035,7 +2035,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_closed(self.__subset(X))
++        return self._is_closed(self._subset_internal(X))
+ 
+     cpdef is_subset_k_closed(self, X, int k):
+         r"""
+@@ -2118,7 +2118,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_circuit(self.__subset(X))
++        return self._is_circuit(self._subset_internal(X))
+ 
+     cpdef coloops(self):
+         r"""
+@@ -2178,7 +2178,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_coindependent(self.__subset(X))
++        return self._is_coindependent(self._subset_internal(X))
+ 
+     cpdef is_codependent(self, X):
+         r"""
+@@ -2211,7 +2211,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return not self._is_coindependent(self.__subset(X))
++        return not self._is_coindependent(self._subset_internal(X))
+ 
+     cpdef is_cobasis(self, X):
+         r"""
+@@ -2245,7 +2245,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         if len(X) != self.full_corank():
+             return False
+         return self._is_cobasis(X)
+@@ -2282,7 +2282,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_cocircuit(self.__subset(X))
++        return self._is_cocircuit(self._subset_internal(X))
+ 
+     cpdef is_coclosed(self, X):
+         r"""
+@@ -2315,7 +2315,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_coclosed(self.__subset(X))
++        return self._is_coclosed(self._subset_internal(X))
+ 
+     # verification
+ 
+@@ -4868,10 +4868,10 @@ cdef class Matroid(SageObject):
+             sage: M.connectivity('ab', 'cd')
+             2
+         """
+-        S = self.__subset(S)
++        S = self._subset_internal(S)
+         if T is None:
+             return self._rank(S) + self._rank(self.groundset()-S) - self.full_rank()
+-        T = self.__subset(T)
++        T = self._subset_internal(T)
+         if S.intersection(T):
+             raise ValueError("S and T are not disjoint")
+         return len(self._link(S, T)[0]) - self.full_rank() + self._rank(S) + self._rank(T)
+@@ -4956,8 +4956,8 @@ cdef class Matroid(SageObject):
+             sage: N.connectivity(S)
+             2
+         """
+-        S = self.__subset(S)
+-        T = self.__subset(T)
++        S = self._subset_internal(S)
++        T = self._subset_internal(T)
+         if not S.isdisjoint(T):
+             raise ValueError("S and T are not disjoint")
+         return self._link(S, T)
+diff --git a/src/sage/matroids/minor_matroid.py b/src/sage/matroids/minor_matroid.py
+index c0e756917f5..98856348ac1 100644
+--- a/src/sage/matroids/minor_matroid.py
++++ b/src/sage/matroids/minor_matroid.py
+@@ -486,8 +486,7 @@ def __copy__(self):
+             True
+         """
+         N = MinorMatroid(self._matroid, self._contractions, self._deletions)
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -512,8 +511,7 @@ def __deepcopy__(self, memo={}):
+         from copy import deepcopy
+         # Since matroids are immutable, N cannot reference itself in correct code, so no need to worry about the recursion.
+         N = MinorMatroid(deepcopy(self._matroid, memo), deepcopy(self._contractions, memo), deepcopy(self._deletions, memo))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -534,6 +532,6 @@ def __reduce__(self):
+              4: {{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}}}
+         """
+         import sage.matroids.unpickling
+-        data = (self._matroid, self._contractions, self._deletions, getattr(self, '__custom_name'))
++        data = (self._matroid, self._contractions, self._deletions, self.get_custom_name())
+         version = 0
+         return sage.matroids.unpickling.unpickle_minor_matroid, (version, data)
+diff --git a/src/sage/matroids/rank_matroid.py b/src/sage/matroids/rank_matroid.py
+index 4633ff0a792..6c4e9470ada 100644
+--- a/src/sage/matroids/rank_matroid.py
++++ b/src/sage/matroids/rank_matroid.py
+@@ -267,9 +267,7 @@ def __copy__(self):
+         N = RankMatroid(groundset=[], rank_function=None)
+         N._groundset = self._groundset
+         N._rank_function = self._rank_function
+-        if getattr(self, '__custom_name') is not None:
+-            # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -293,8 +291,7 @@ def __deepcopy__(self, memo={}):
+         from copy import deepcopy
+         # Since matroids are immutable, N cannot reference itself in correct code, so no need to worry about the recursion.
+         N = RankMatroid(groundset=deepcopy(self._groundset), rank_function=deepcopy(self._rank_function))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+diff --git a/src/sage/misc/cachefunc.pxd b/src/sage/misc/cachefunc.pxd
+index d3cc677dece..8e5d9dfa42a 100644
+--- a/src/sage/misc/cachefunc.pxd
++++ b/src/sage/misc/cachefunc.pxd
+@@ -5,7 +5,7 @@ cpdef cache_key(o)
+ 
+ cdef class CachedFunction():
+     cdef public str __name__
+-    cdef public str __module__
++    cdef public str __cached_module__
+     cdef ArgumentFixer _argument_fixer
+     cdef public f
+     cdef public cache  # not always of type <dict>
+@@ -20,7 +20,7 @@ cdef class CachedFunction():
+ cdef class CachedMethod():
+     cdef str _cache_name
+     cdef public str __name__
+-    cdef public str __module__
++    cdef public str __cached_module__
+     cdef CachedFunction _cachedfunc
+     cdef Py_ssize_t nargs
+     cpdef _get_instance_cache(self, inst)
+diff --git a/src/sage/misc/cachefunc.pyx b/src/sage/misc/cachefunc.pyx
+index a307c33e32b..8aa30a85272 100644
+--- a/src/sage/misc/cachefunc.pyx
++++ b/src/sage/misc/cachefunc.pyx
+@@ -60,7 +60,7 @@ be used::
+ 
+ We can proceed similarly for cached methods of Cython classes,
+ provided that they allow attribute assignment or have a public
+-attribute ``__cached_methods`` of type ``<dict>``. Since
++attribute ``_cached_methods`` of type ``<dict>``. Since
+ :trac:`11115`, this is the case for all classes inheriting from
+ :class:`~sage.structure.parent.Parent`. See below for a more explicit
+ example. By :trac:`12951`, cached methods of extension classes can
+@@ -301,14 +301,14 @@ ought to be chosen. A typical example is
+ 
+ By :trac:`12951`, the cached_method decorator is also supported on non-c(p)def
+ methods of extension classes, as long as they either support attribute assignment
+-or have a public attribute of type ``<dict>`` called ``__cached_methods``. The
++or have a public attribute of type ``<dict>`` called ``_cached_methods``. The
+ latter is easy::
+ 
+     sage: # needs sage.misc.cython
+     sage: cython_code = [
+     ....: "from sage.misc.cachefunc import cached_method",
+     ....: "cdef class MyClass:",
+-    ....: "    cdef public dict __cached_methods",
++    ....: "    cdef public dict _cached_methods",
+     ....: "    @cached_method",
+     ....: "    def f(self, a,b):",
+     ....: "        return a*b"]
+@@ -774,13 +774,17 @@ cdef class CachedFunction():
+         else:
+             self.__name__ = f.__name__
+         try:
+-            self.__module__ = f.__module__
++            self.__cached_module__ = f.__module__
+         except AttributeError:
+-            self.__module__ = f.__objclass__.__module__
++            self.__cached_module__ = f.__objclass__.__module__
+         if argument_fixer is not None: # it is None unless the argument fixer
+                                        # was known previously. See #15038.
+             self._argument_fixer = argument_fixer
+ 
++    @property
++    def __module__(self):
++        return self.__cached_module__
++
+     cdef get_key_args_kwds(self, tuple args, dict kwds):
+         """
+         Return the key in the cache to be used when ``args`` and
+@@ -841,7 +845,7 @@ cdef class CachedFunction():
+             sage: loads(dumps(hilbert_class_polynomial)) is hilbert_class_polynomial  #indirect doctest                 # needs sage.schemes
+             True
+         """
+-        return _cached_function_unpickle, (self.__module__, self.__name__, self.cache)
++        return _cached_function_unpickle, (self.__cached_module__, self.__name__, self.cache)
+ 
+     #########
+     ## Introspection
+@@ -2019,7 +2023,7 @@ cdef class CachedMethodCaller(CachedFunction):
+         This getter attempts to assign a bound method as an
+         attribute to the given instance. If this is not
+         possible (for example, for some extension classes),
+-        it is attempted to find an attribute ``__cached_methods``,
++        it is attempted to find an attribute ``_cached_methods``,
+         and store/retrieve the bound method there. In that
+         way, cached methods can be implemented for extension
+         classes deriving from :class:`~sage.structure.parent.Parent`
+@@ -2085,7 +2089,7 @@ cdef class CachedMethodCaller(CachedFunction):
+         """
+         # This is for Parents or Elements that do not allow attribute assignment
+         try:
+-            return (<dict>inst.__cached_methods)[self._cachedmethod._cachedfunc.__name__]
++            return (<dict>inst._cached_methods)[self._cachedmethod._cachedfunc.__name__]
+         except (AttributeError, TypeError, KeyError):
+             pass
+ 
+@@ -2100,10 +2104,10 @@ cdef class CachedMethodCaller(CachedFunction):
+         except AttributeError:
+             pass
+         try:
+-            if inst.__cached_methods is None:
+-                inst.__cached_methods = {self._cachedmethod._cachedfunc.__name__ : Caller}
++            if inst._cached_methods is None:
++                inst._cached_methods = {self._cachedmethod._cachedfunc.__name__ : Caller}
+             else:
+-                (<dict>inst.__cached_methods)[self._cachedmethod._cachedfunc.__name__] = Caller
++                (<dict>inst._cached_methods)[self._cachedmethod._cachedfunc.__name__] = Caller
+         except AttributeError:
+             pass
+         return Caller
+@@ -2421,7 +2425,7 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
+         This getter attempts to assign a bound method as an
+         attribute to the given instance. If this is not
+         possible (for example, for some extension classes),
+-        it is attempted to find an attribute ``__cached_methods``,
++        it is attempted to find an attribute ``_cached_methods``,
+         and store/retrieve the bound method there. In that
+         way, cached methods can be implemented for extension
+         classes deriving from :class:`~sage.structure.parent.Parent`
+@@ -2472,7 +2476,7 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
+         """
+         # This is for Parents or Elements that do not allow attribute assignment
+         try:
+-            return (<dict>inst.__cached_methods)[self.__name__]
++            return (<dict>inst._cached_methods)[self.__name__]
+         except (AttributeError, TypeError, KeyError):
+             pass
+         Caller = CachedMethodCallerNoArgs(inst, self.f, name=self.__name__, do_pickle=self.do_pickle)
+@@ -2482,10 +2486,10 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
+         except AttributeError:
+             pass
+         try:
+-            if inst.__cached_methods is None:
+-                inst.__cached_methods = {self.__name__ : Caller}
++            if inst._cached_methods is None:
++                inst._cached_methods = {self.__name__ : Caller}
+             else:
+-                (<dict>inst.__cached_methods)[self.__name__] = Caller
++                (<dict>inst._cached_methods)[self.__name__] = Caller
+         except AttributeError:
+             pass
+         return Caller
+@@ -2698,7 +2702,11 @@ cdef class CachedMethod():
+         self._cache_name = '_cache__' + (name or f.__name__)
+         self._cachedfunc = CachedFunction(f, classmethod=True, name=name, key=key, do_pickle=do_pickle)
+         self.__name__ = self._cachedfunc.__name__
+-        self.__module__ = self._cachedfunc.__module__
++        self.__cached_module__ = self._cachedfunc.__module__
++
++    @property
++    def __module__(self):
++        return self.__cached_module__
+ 
+     def __call__(self, inst, *args, **kwds):
+         """
+@@ -2828,7 +2836,7 @@ cdef class CachedMethod():
+         except AttributeError:
+             name = self.__name__
+         try:
+-            return (<dict>inst.__cached_methods)[name]
++            return (<dict>inst._cached_methods)[name]
+         except (AttributeError, TypeError, KeyError):
+             pass
+         # Apparently we need to construct the caller.
+@@ -2840,8 +2848,6 @@ cdef class CachedMethod():
+                 try:
+                     if METH_NOARGS&PyCFunction_GetFlags(f.__get__(inst,cls)):
+                         self.nargs = 1
+-                    else:
+-                        self.nargs = 2
+                 except Exception:
+                     pass
+             if self.nargs == 0:
+@@ -2864,10 +2870,10 @@ cdef class CachedMethod():
+         except AttributeError:
+             pass
+         try:
+-            if inst.__cached_methods is None:
+-                inst.__cached_methods = {name : Caller}
++            if inst._cached_methods is None:
++                inst._cached_methods = {name : Caller}
+             else:
+-                (<dict>inst.__cached_methods)[name] = Caller
++                (<dict>inst._cached_methods)[name] = Caller
+         except AttributeError:
+             pass
+         return Caller
+@@ -2965,12 +2971,12 @@ cdef class CachedSpecialMethod(CachedMethod):
+                 D = inst.__dict__
+             except (TypeError, AttributeError):
+                 try:
+-                    D = inst.__cached_methods
++                    D = inst._cached_methods
+                 except (TypeError, AttributeError):
+-                    raise TypeError("For a cached special method, either attribute assignment or a public '__cached_methods' attribute of type <dict> is needed")
++                    raise TypeError("For a cached special method, either attribute assignment or a public '_cached_methods' attribute of type <dict> is needed")
+             if D is None:
+-                # This can only happen in the case of __cached_methods
+-                D = inst.__cached_methods = {}
++                # This can only happen in the case of _cached_methods
++                D = inst._cached_methods = {}
+             else:
+                 try:
+                     return D[name]
+@@ -3298,13 +3304,13 @@ cdef class CachedInParentMethod(CachedMethod):
+             return P.__dict__.setdefault(self._cache_name, default)
+         except AttributeError:
+             pass
+-        if not hasattr(P,'__cached_methods'):
++        if not hasattr(P,'_cached_methods'):
+             raise TypeError("The parent of this element does not allow attribute assignment\n" +
+                             "    and does not descend from the Parent base class.\n" +
+                             "    Cannot use CachedInParentMethod.")
+-        if P.__cached_methods is None:
+-            P.__cached_methods = {}
+-        return (<dict>P.__cached_methods).setdefault(self._cache_name, default)
++        if P._cached_methods is None:
++            P._cached_methods = {}
++        return (<dict>P._cached_methods).setdefault(self._cache_name, default)
+ 
+     def __get__(self, inst, cls):
+         """
+diff --git a/src/sage/misc/cython.py b/src/sage/misc/cython.py
+index f4083f3909b..5f83f585c3a 100644
+--- a/src/sage/misc/cython.py
++++ b/src/sage/misc/cython.py
+@@ -646,9 +646,9 @@ def compile_and_load(code, **kwds):
+         ....:     cdef Polynomial_rational_flint res = f._new()
+         ....:     cdef unsigned long k
+         ....:     cdef Rational z = Rational(0)
+-        ....:     for k in range(fmpq_poly_length(f.__poly)):
+-        ....:         fmpq_poly_get_coeff_mpq(z.value, f.__poly, k)
+-        ....:         fmpq_poly_set_coeff_mpq(res.__poly, n*k, z.value)
++        ....:     for k in range(fmpq_poly_length(f._poly)):
++        ....:         fmpq_poly_get_coeff_mpq(z.value, f._poly, k)
++        ....:         fmpq_poly_set_coeff_mpq(res._poly, n*k, z.value)
+         ....:     return res
+         ....: '''
+         sage: module = compile_and_load(code)  # long time
+diff --git a/src/sage/misc/fpickle.pyx b/src/sage/misc/fpickle.pyx
+index 9f80a8f31aa..37c26e431ba 100644
+--- a/src/sage/misc/fpickle.pyx
++++ b/src/sage/misc/fpickle.pyx
+@@ -124,10 +124,12 @@ def call_pickled_function(fpargs):
+ def pickleMethod(method):
+     'support function for copyreg to pickle method refs'
+ 
+-    # Note: On Python 3 there is no .im_class but we can get the instance's
+-    # class through .__self__.__class__
+-    cls = getattr(method, 'im_class', method.__self__.__class__)
+-    return (unpickleMethod, (method.__func__.__name__, method.__self__, cls))
++    if isinstance(method.__self__, type):
++        # This is a class method, so get it from the type directly
++        return (getattr, (method.__self__, method.__func__.__name__))
++    else:
++        cls = method.__self__.__class__
++        return (unpickleMethod, (method.__func__.__name__, method.__self__, cls))
+ 
+ 
+ def unpickleMethod(im_name,
+@@ -139,10 +141,7 @@ def unpickleMethod(im_name,
+         if __self__ is None:
+             return unbound
+ 
+-        # Note: On Python 2 "unbound methods" are just functions, so they don't
+-        # have a __func__
+-        bound = types.MethodType(getattr(unbound, '__func__', unbound),
+-                                 __self__)
++        bound = types.MethodType(unbound, __self__)
+         return bound
+     except AttributeError:
+         assert __self__ is not None, "No recourse: no instance to guess from."
+@@ -150,11 +149,8 @@ def unpickleMethod(im_name,
+         # changed around since we pickled this method, we may still be
+         # able to get it by looking on the instance's current class.
+         unbound = getattr(__self__.__class__, im_name)
+-        if __self__ is None:
+-            return unbound
+ 
+-        bound = types.MethodType(getattr(unbound, '__func__', unbound),
+-                                 __self__)
++        bound = types.MethodType(unbound, __self__)
+         return bound
+ 
+ 
+diff --git a/src/sage/misc/inherit_comparison.pyx b/src/sage/misc/inherit_comparison.pyx
+index f046f5fb8ce..aa97f664496 100644
+--- a/src/sage/misc/inherit_comparison.pyx
++++ b/src/sage/misc/inherit_comparison.pyx
+@@ -54,6 +54,8 @@ cdef class InheritComparisonMetaclass(type):
+         sage: # needs sage.misc.cython
+         sage: cython(
+         ....: '''
++        ....: cimport cython
++        ....:
+         ....: from sage.misc.inherit_comparison cimport InheritComparisonMetaclass
+         ....:
+         ....: cdef class Base():
+@@ -66,6 +68,7 @@ cdef class InheritComparisonMetaclass(type):
+         ....:         return 1
+         ....:
+         ....: cdef class DerivedWithRichcmp(Base):
++        ....:     @cython.always_allow_keywords(False)
+         ....:     def __getmetaclass__(_):
+         ....:         from sage.misc.inherit_comparison import InheritComparisonMetaclass
+         ....:         return InheritComparisonMetaclass
+diff --git a/src/sage/misc/lazy_attribute.pyx b/src/sage/misc/lazy_attribute.pyx
+index 82a0f90b775..bdbec3b3ba1 100644
+--- a/src/sage/misc/lazy_attribute.pyx
++++ b/src/sage/misc/lazy_attribute.pyx
+@@ -111,12 +111,12 @@ cdef class _lazy_attribute():
+         if a is None: # when doing cls.x for cls a class and x a lazy attribute
+             return self
+         try:
+-            # __cached_methods is supposed to be a public Cython attribute.
++            # _cached_methods is supposed to be a public Cython attribute.
+             # Apparently, these are *not* subject to name mangling.
+-            CM = getattr(a, '__cached_methods')
++            CM = getattr(a, '_cached_methods')
+             if CM is None:
+                 CM = {}
+-                setattr(a, '__cached_methods', CM)
++                setattr(a, '_cached_methods', CM)
+         except AttributeError as msg:
+             CM = None
+         if CM is not None:
+diff --git a/src/sage/misc/lazy_list.pyx b/src/sage/misc/lazy_list.pyx
+index c1fa0250a95..ba62c446b69 100644
+--- a/src/sage/misc/lazy_list.pyx
++++ b/src/sage/misc/lazy_list.pyx
+@@ -1059,7 +1059,11 @@ cdef class lazy_list_from_function(lazy_list_generic):
+             step         1
+         """
+         while len(self.cache) <= i:
+-            self.cache.append(self.callable(len(self.cache)))
++            try:
++                value = self.callable(len(self.cache))
++            except StopIteration:
++                return 1
++            self.cache.append(value)
+ 
+     def __reduce__(self):
+         r"""
+diff --git a/src/sage/misc/sageinspect.py b/src/sage/misc/sageinspect.py
+index 3dd0cc0a45b..ce5e9987027 100644
+--- a/src/sage/misc/sageinspect.py
++++ b/src/sage/misc/sageinspect.py
+@@ -224,7 +224,11 @@ def isclassinstance(obj):
+     return (not inspect.isclass(obj) and
+             hasattr(obj, '__class__') and
+             hasattr(obj.__class__, '__module__') and
+-            obj.__class__.__module__ not in builtin_mods)
++            obj.__class__.__module__ not in builtin_mods and
++            # Starting with Cython 3, Cython's builtin types have __module__ set
++            # to the shared module names like _cython_3_0_0.
++            not (isinstance(obj.__class__.__module__, str) and
++                 obj.__class__.__module__.startswith('_cython_')))
+ 
+ 
+ # Parse strings of form "File: sage/rings/rational.pyx (starting at line 1080)"
+diff --git a/src/sage/misc/session.pyx b/src/sage/misc/session.pyx
+index de649f80425..31454dac993 100644
+--- a/src/sage/misc/session.pyx
++++ b/src/sage/misc/session.pyx
+@@ -80,6 +80,8 @@ from sage.misc.persist import load, save, loads, dumps
+ 
+ state_at_init = None
+ 
++CythonFunctionType = type(lambda: None)
++
+ def init(state=None):
+     """
+     Initialize some dictionaries needed by the :func:`show_identifiers`,
+@@ -311,7 +313,7 @@ def save_session(name='sage_session', verbose=False):
+     for k in show_identifiers(hidden = True):
+         try:
+             x = state[k]
+-            if isinstance(x, (types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType, type)):
++            if isinstance(x, (types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType, CythonFunctionType, type)):
+                 raise TypeError('{} is a function, method, class or type'.format(k))
+ 
+             # We attempt to pickle *and* unpickle every variable to
+diff --git a/src/sage/modular/modsym/p1list.pxd b/src/sage/modular/modsym/p1list.pxd
+index cc24a33139b..b66f28b8ad6 100644
+--- a/src/sage/modular/modsym/p1list.pxd
++++ b/src/sage/modular/modsym/p1list.pxd
+@@ -21,7 +21,7 @@ cdef class P1List:
+     # Here we use a pointer to a function, so the if logic
+     # for normalizing an element does not need to be used
+     # every time the user calls the normalize function.
+-    cdef int (*__normalize)(int N, int u, int v,
++    cdef int (*_normalize)(int N, int u, int v,
+                             int* uu, int* vv, int* ss,
+                             int compute_s) except -1
+     cpdef index(self, int u, int v)
+diff --git a/src/sage/modular/modsym/p1list.pyx b/src/sage/modular/modsym/p1list.pyx
+index 111d408cee4..30a8f7471dd 100644
+--- a/src/sage/modular/modsym/p1list.pyx
++++ b/src/sage/modular/modsym/p1list.pyx
+@@ -723,10 +723,10 @@ cdef class P1List():
+         self.__N = N
+         if N <= 46340:
+             self.__list = p1list_int(N)
+-            self.__normalize = c_p1_normalize_int
++            self._normalize = c_p1_normalize_int
+         elif N <= 2147483647:
+             self.__list = p1list_llong(N)
+-            self.__normalize = c_p1_normalize_llong
++            self._normalize = c_p1_normalize_llong
+         else:
+             raise OverflowError("p1list not defined for such large N.")
+         self.__list.sort()
+@@ -921,7 +921,7 @@ cdef class P1List():
+         """
+         cdef int u, v, uu, vv, ss
+         u,v = self.__list[i]
+-        self.__normalize(self.__N, -u, v, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, -u, v, &uu, &vv, &ss, 0)
+         _, j = search(self.__list, (uu,vv))
+         return j
+ 
+@@ -954,7 +954,7 @@ cdef class P1List():
+         """
+         cdef int u, v, uu, vv, ss
+         u,v = self.__list[i]
+-        self.__normalize(self.__N, -v, u, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, -v, u, &uu, &vv, &ss, 0)
+         _, j = search(self.__list, (uu,vv))
+         return j
+ 
+@@ -987,7 +987,7 @@ cdef class P1List():
+         """
+         cdef int u, v, uu, vv, ss
+         u,v = self.__list[i]
+-        self.__normalize(self.__N, v, -u-v, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, v, -u-v, &uu, &vv, &ss, 0)
+         _, j = search(self.__list, (uu,vv))
+         return j
+ 
+@@ -1153,7 +1153,7 @@ cdef class P1List():
+             True
+         """
+         cdef int uu, vv, ss
+-        self.__normalize(self.__N, u, v, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, u, v, &uu, &vv, &ss, 0)
+         return (uu,vv)
+ 
+     def normalize_with_scalar(self, int u, int v):
+@@ -1186,7 +1186,7 @@ cdef class P1List():
+             True
+         """
+         cdef int uu, vv, ss
+-        self.__normalize(self.__N, u, v, &uu, &vv, &ss, 1)
++        self._normalize(self.__N, u, v, &uu, &vv, &ss, 1)
+         return (uu, vv, ss)
+ 
+     def N(self):
+diff --git a/src/sage/numerical/gauss_legendre.pyx b/src/sage/numerical/gauss_legendre.pyx
+index 5325797c7aa..96708c5b1ac 100644
+--- a/src/sage/numerical/gauss_legendre.pyx
++++ b/src/sage/numerical/gauss_legendre.pyx
+@@ -117,8 +117,8 @@ def nodes_uncached(degree, prec):
+         raise ValueError("degree=%s not supported (degree must be 3 or even)" % degree)
+     R = RealField(int(prec*3/2))
+     Rout = RealField(prec)
+-    mpfr_init2(u,R.__prec)
+-    mpfr_init2(v,R.__prec)
++    mpfr_init2(u,R._prec)
++    mpfr_init2(v,R._prec)
+     ZERO = R.zero()
+     ONE = R.one()
+     HALF = ONE/2
+diff --git a/src/sage/numerical/linear_functions.pyx b/src/sage/numerical/linear_functions.pyx
+index 5549ff436f5..f3fc6fe419c 100644
+--- a/src/sage/numerical/linear_functions.pyx
++++ b/src/sage/numerical/linear_functions.pyx
+@@ -1579,7 +1579,10 @@ cdef class LinearConstraint(LinearFunctionOrConstraint):
+         while True:
+             yield (lhs, rhs)
+             lhs = rhs
+-            rhs = next(term_iter)
++            try:
++                rhs = next(term_iter)
++            except StopIteration:
++                return
+ 
+     def inequalities(self):
+         """
+@@ -1612,7 +1615,10 @@ cdef class LinearConstraint(LinearFunctionOrConstraint):
+         while True:
+             yield (lhs, rhs)
+             lhs = rhs
+-            rhs = next(term_iter)
++            try:
++                rhs = next(term_iter)
++            except StopIteration:
++                return
+ 
+     def _repr_(self):
+         r"""
+diff --git a/src/sage/quivers/representation.py b/src/sage/quivers/representation.py
+index 9c11eb8ad0e..db82cbd7c86 100644
+--- a/src/sage/quivers/representation.py
++++ b/src/sage/quivers/representation.py
+@@ -1297,10 +1297,7 @@ def copy(self):
+             sage: v.get_element(1)
+             (1, 0)
+         """
+-        if hasattr(self, '__custom_name'):
+-            name = self.__custom_name
+-        else:
+-            name = None
++        name = self.get_custom_name()
+         return self.parent()(self._elems.copy(), name)
+ 
+ ####################################################################
+diff --git a/src/sage/rings/complex_arb.pyx b/src/sage/rings/complex_arb.pyx
+index ef432c1e945..95e615f3ee6 100644
+--- a/src/sage/rings/complex_arb.pyx
++++ b/src/sage/rings/complex_arb.pyx
+@@ -874,7 +874,7 @@ class ComplexBallField(UniqueRepresentation, sage.rings.abc.ComplexBallField):
+         cdef RealBall rb
+         cdef ComplexBall cb
+         acb_poly_init(rounded_poly)
+-        cdef long deg = acb_poly_degree(poly.__poly)
++        cdef long deg = acb_poly_degree(poly._poly)
+         if deg < 0:
+             raise ArithmeticError("taking the roots of the zero polynomial")
+         cdef acb_ptr roots = _acb_vec_init(deg)
+@@ -883,7 +883,7 @@ class ComplexBallField(UniqueRepresentation, sage.rings.abc.ComplexBallField):
+             while ((isolated < deg or any(acb_rel_accuracy_bits(&roots[i]) < tgtprec
+                                         for i in range(deg)))
+                 and prec < maxprec):
+-                acb_poly_set_round(rounded_poly, poly.__poly, prec)
++                acb_poly_set_round(rounded_poly, poly._poly, prec)
+                 maxiter = min(max(deg, 32), prec)
+                 if (prec == initial_prec):
+                     isolated = acb_poly_find_roots(roots, rounded_poly, NULL, maxiter, prec)
+diff --git a/src/sage/rings/complex_mpc.pxd b/src/sage/rings/complex_mpc.pxd
+index 762c38afbdc..f7d8cb9492c 100644
+--- a/src/sage/rings/complex_mpc.pxd
++++ b/src/sage/rings/complex_mpc.pxd
+@@ -11,7 +11,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+     cpdef _mul_(self, other)
+ 
+ cdef class MPComplexField_class(sage.rings.ring.Field):
+-    cdef readonly int __prec
++    cdef readonly int _prec
+     cdef mpc_rnd_t __rnd
+     cdef object __rnd_str
+     cdef object __real_field
+diff --git a/src/sage/rings/complex_mpc.pyx b/src/sage/rings/complex_mpc.pyx
+index b3681ff724f..c847a9302b5 100644
+--- a/src/sage/rings/complex_mpc.pyx
++++ b/src/sage/rings/complex_mpc.pyx
+@@ -307,7 +307,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+         if prec < mpfr_prec_min() or prec > mpfr_prec_max():
+             raise ValueError("prec (=%s) must be >= %s and <= %s." % (
+                 prec, mpfr_prec_min(), mpfr_prec_max()))
+-        self.__prec = prec
++        self._prec = prec
+         if not isinstance(rnd, str):
+             raise TypeError("rnd must be a string")
+         try:
+@@ -331,7 +331,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+         cdef MPComplexNumber z
+         z = MPComplexNumber.__new__(MPComplexNumber)
+         z._parent = self
+-        mpc_init2(z.value, self.__prec)
++        mpc_init2(z.value, self._prec)
+         z.init = 1
+         return z
+ 
+@@ -344,7 +344,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: MPComplexField(200, 'RNDDU') # indirect doctest
+             Complex Field with 200 bits of precision and rounding RNDDU
+         """
+-        s = "Complex Field with %s bits of precision"%self.__prec
++        s = "Complex Field with %s bits of precision"%self._prec
+         if self.__rnd != MPC_RNDNN:
+             s = s + " and rounding %s"%(self.__rnd_str)
+         return s
+@@ -465,13 +465,13 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+         if RR.has_coerce_map_from(S):
+             return self._coerce_map_via([RR], S)
+ 
+-        if isinstance(S, MPComplexField_class) and S.prec() >= self.__prec:
++        if isinstance(S, MPComplexField_class) and S.prec() >= self._prec:
+             #FIXME: What map when rounding modes differ but prec is the same ?
+             #       How to provide commutativity of morphisms ?
+             #       Change _cmp_ when done
+             return MPCtoMPC(S, self)
+ 
+-        if isinstance(S, ComplexField_class) and S.prec() >= self.__prec:
++        if isinstance(S, ComplexField_class) and S.prec() >= self._prec:
+             return CCtoMPC(S, self)
+ 
+         late_import()
+@@ -490,7 +490,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: loads(dumps(C)) == C
+             True
+         """
+-        return __create__MPComplexField_version0, (self.__prec, self.__rnd_str)
++        return __create__MPComplexField_version0, (self._prec, self.__rnd_str)
+ 
+     def __richcmp__(left, right, int op):
+         """
+@@ -513,7 +513,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+ 
+         cdef MPComplexField_class s = <MPComplexField_class>left
+         cdef MPComplexField_class o = <MPComplexField_class>right
+-        return richcmp(s.__prec, o.__prec, op)
++        return richcmp(s._prec, o._prec, op)
+ 
+     def gen(self, n=0):
+         """
+@@ -604,7 +604,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: C = MPComplexField(10, 'RNDNZ'); C.name()
+             'MPComplexField10_RNDNZ'
+         """
+-        return "MPComplexField%s_%s"%(self.__prec, self.__rnd_str)
++        return "MPComplexField%s_%s"%(self._prec, self.__rnd_str)
+ 
+     def __hash__(self):
+         """
+@@ -629,7 +629,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: MPComplexField(22).prec()
+             22
+         """
+-        return self.__prec
++        return self._prec
+ 
+     def rounding_mode(self):
+         """
+@@ -707,7 +707,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+         cdef MPComplexNumber z
+         z = MPComplexNumber.__new__(MPComplexNumber)
+         z._parent = self._parent
+-        mpc_init2(z.value, (<MPComplexField_class>self._parent).__prec)
++        mpc_init2(z.value, (<MPComplexField_class>self._parent)._prec)
+         z.init = 1
+         return z
+ 
+@@ -760,7 +760,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+         if parent is None:
+             raise TypeError
+         self._parent = parent
+-        mpc_init2(self.value, parent.__prec)
++        mpc_init2(self.value, parent._prec)
+         self.init = 1
+         if x is None: return
+         self._set(x, y, base)
+@@ -1010,7 +1010,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+             sage: i.prec()
+             2000
+         """
+-        return <MPComplexField_class>(self._parent).__prec
++        return <MPComplexField_class>(self._parent)._prec
+ 
+     def real(self):
+         """
+@@ -1571,26 +1571,6 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+         mpc_norm(x.value, self.value, (<RealField_class>x._parent).rnd)
+         return x
+ 
+-    def __rtruediv__(self, left):
+-        r"""
+-        Returns the quotient of ``left`` with ``self``, that is: ``left/self``
+-        as a complex number.
+-
+-        INPUT:
+-
+-        - ``left`` -- a complex number
+-
+-        EXAMPLES::
+-
+-            sage: MPC = MPComplexField()
+-            sage: a = MPC(2, 2)
+-            sage: a.__rtruediv__(MPC(1))
+-            0.250000000000000 - 0.250000000000000*I
+-            sage: MPC(1)/a
+-            0.250000000000000 - 0.250000000000000*I
+-        """
+-        return MPComplexNumber(self._parent, left)/self
+-
+     def __pow__(self, right, modulus):
+         """
+         Compute ``self`` raised to the power of exponent, rounded in
+@@ -2347,7 +2327,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+ 
+         cdef mpc_rnd_t rnd = (<MPComplexField_class>(self._parent)).__rnd
+ 
+-        cdef int prec = self._parent.__prec
++        cdef int prec = self._parent._prec
+ 
+         if optimal or algorithm == "principal":
+             if not isinstance(right, MPComplexNumber) or (<MPComplexNumber>right)._parent is not self._parent:
+diff --git a/src/sage/rings/complex_mpfr.pyx b/src/sage/rings/complex_mpfr.pyx
+index 33d73d81b12..61f2cadc8e4 100644
+--- a/src/sage/rings/complex_mpfr.pyx
++++ b/src/sage/rings/complex_mpfr.pyx
+@@ -1658,28 +1658,6 @@ cdef class ComplexNumber(sage.structure.element.FieldElement):
+         mpfr_clear(right_nm)
+         return x
+ 
+-    def __rtruediv__(self, left):
+-        r"""
+-        Return the quotient of left with ``self``, that is:
+-
+-        ``left/self``
+-
+-        as a complex number.
+-
+-        INPUT:
+-
+-        - ``left`` -- a complex number to divide by ``self``
+-
+-        EXAMPLES::
+-
+-            sage: a = ComplexNumber(2,0)
+-            sage: a.__rtruediv__(CC(1))
+-            0.500000000000000
+-            sage: CC(1)/a
+-            0.500000000000000
+-        """
+-        return ComplexNumber(self._parent, left)/self
+-
+     def __pow__(self, right, modulus):
+         r"""
+         Raise ``self`` to the ``right`` exponent.
+diff --git a/src/sage/rings/finite_rings/integer_mod.pxd b/src/sage/rings/finite_rings/integer_mod.pxd
+index 1e3cb81c148..351ffa25e1b 100644
+--- a/src/sage/rings/finite_rings/integer_mod.pxd
++++ b/src/sage/rings/finite_rings/integer_mod.pxd
+@@ -20,7 +20,7 @@ cdef class NativeIntStruct:
+ 
+ 
+ cdef class IntegerMod_abstract(FiniteRingElement):
+-    cdef NativeIntStruct __modulus
++    cdef NativeIntStruct _modulus
+     cdef _new_c_from_long(self, long value)
+     cdef IntegerMod_abstract _new_c_fast(self, unsigned long value)
+     cdef void set_from_mpz(self, mpz_t value)
+diff --git a/src/sage/rings/finite_rings/integer_mod.pyx b/src/sage/rings/finite_rings/integer_mod.pyx
+index b9461bd362e..d64ba5af84f 100644
+--- a/src/sage/rings/finite_rings/integer_mod.pyx
++++ b/src/sage/rings/finite_rings/integer_mod.pyx
+@@ -361,7 +361,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             ZeroDivisionError: inverse of Mod(4, 30) does not exist
+         """
+         self._parent = parent
+-        self.__modulus = parent._pyx_order
++        self._modulus = parent._pyx_order
+ 
+         if value is None:
+             return
+@@ -373,7 +373,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         if isinstance(value, Integer):
+             z = <Integer>value
+         elif isinstance(value, rational.Rational):
+-            z = value % self.__modulus.sageInteger
++            z = value % self._modulus.sageInteger
+         elif integer_check_long_py(value, &longval, &err) and not err:
+             self.set_from_long(longval)
+             return
+@@ -388,7 +388,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+                     value = py_scalar_to_element(value)
+                 if isinstance(value, Element) and value.parent().is_exact():
+                     value = sage.rings.rational_field.QQ(value)
+-                    z = value % self.__modulus.sageInteger
++                    z = value % self._modulus.sageInteger
+                 else:
+                     raise
+         self.set_from_mpz(z.value)
+@@ -397,7 +397,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         cdef type t = type(self)
+         x = <IntegerMod_abstract>t.__new__(t)
+         x._parent = self._parent
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x.set_from_ulong_fast(value)
+         return x
+ 
+@@ -405,7 +405,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         cdef type t = type(self)
+         cdef IntegerMod_abstract x = <IntegerMod_abstract>t.__new__(t)
+         x._parent = self._parent
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x.set_from_long(value)
+         return x
+ 
+@@ -529,17 +529,17 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         """
+         if self.is_zero():
+             return True
+-        m = self.__modulus.sageInteger.exact_log(2) + 1
++        m = self._modulus.sageInteger.exact_log(2) + 1
+         return (self**m).is_zero()
+ 
+     #################################################################
+     # Interfaces
+     #################################################################
+     def _pari_init_(self):
+-        return 'Mod(%s,%s)'%(str(self), self.__modulus.sageInteger)
++        return 'Mod(%s,%s)'%(str(self), self._modulus.sageInteger)
+ 
+     def __pari__(self):
+-        return self.lift().__pari__().Mod(self.__modulus.sageInteger)
++        return self.lift().__pari__().Mod(self._modulus.sageInteger)
+ 
+     def _gap_init_(self):
+         r"""
+@@ -558,7 +558,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             sage: gap(Mod(4, 48))
+             ZmodnZObj( 4, 48 )
+         """
+-        return '%s*One(ZmodnZ(%s))' % (self, self.__modulus.sageInteger)
++        return '%s*One(ZmodnZ(%s))' % (self, self._modulus.sageInteger)
+ 
+     def _magma_init_(self, magma):
+         """
+@@ -869,7 +869,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             sage: Mod(3,17).modulus()
+             17
+         """
+-        return self.__modulus.sageInteger
++        return self._modulus.sageInteger
+ 
+     def charpoly(self, var='x'):
+         """
+@@ -1229,7 +1229,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+                 modulus = R.gen()**2 - R(self)
+                 if self._parent.is_field():
+                     from .finite_field_constructor import FiniteField
+-                    Q = FiniteField(self.__modulus.sageInteger**2, y, modulus)
++                    Q = FiniteField(self._modulus.sageInteger**2, y, modulus)
+                 else:
+                     R = self.parent()['x']
+                     Q = R.quotient(modulus, names=(y,))
+@@ -1250,7 +1250,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             if all and e > 1 and not self.is_unit():
+                 if self.is_zero():
+                     # All multiples of p^ciel(e/2) vanish
+-                    return [self._parent(x) for x in range(0, self.__modulus.sageInteger, p**((e+1)/2))]
++                    return [self._parent(x) for x in range(0, self._modulus.sageInteger, p**((e+1)/2))]
+                 else:
+                     z = self.lift()
+                     val = z.valuation(p)/2  # square => valuation is even
+@@ -1272,7 +1272,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+                     p_exp = p**exp
+                     w = [self._parent(a.lift() * p_val + b)
+                             for a in u.sqrt(all=True)
+-                            for b in range(0, self.__modulus.sageInteger, p_exp)]
++                            for b in range(0, self._modulus.sageInteger, p_exp)]
+                     if p == 2:
+                         w = list(set(w))
+                     w.sort()
+@@ -1624,7 +1624,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         despite the possibly probabilistic nature of the underlying
+         algorithm.
+         """
+-        if self.lift() > self.__modulus.sageInteger >> 1:
++        if self.lift() > self._modulus.sageInteger >> 1:
+             return -self
+         return self
+ 
+@@ -1705,27 +1705,27 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         cdef int_fast64_t new_modulus
+         if not isinstance(self, IntegerMod_gmp) and not isinstance(other, IntegerMod_gmp):
+ 
+-            if other.__modulus.int64 == 1: return self
+-            new_modulus = self.__modulus.int64 * other.__modulus.int64
++            if other._modulus.int64 == 1: return self
++            new_modulus = self._modulus.int64 * other._modulus.int64
+             if new_modulus < INTEGER_MOD_INT32_LIMIT:
+-                return self.__crt(other)
++                return self._crt(other)
+ 
+             elif new_modulus < INTEGER_MOD_INT64_LIMIT:
+                 if not isinstance(self, IntegerMod_int64):
+                     self = IntegerMod_int64(self._parent, self.lift())
+                 if not isinstance(other, IntegerMod_int64):
+                     other = IntegerMod_int64(other._parent, other.lift())
+-                return self.__crt(other)
++                return self._crt(other)
+ 
+         if not isinstance(self, IntegerMod_gmp):
+-            if self.__modulus.int64 == 1: return other
++            if self._modulus.int64 == 1: return other
+             self = IntegerMod_gmp(self._parent, self.lift())
+ 
+         if not isinstance(other, IntegerMod_gmp):
+-            if other.__modulus.int64 == 1: return self
++            if other._modulus.int64 == 1: return self
+             other = IntegerMod_gmp(other._parent, other.lift())
+ 
+-        return self.__crt(other)
++        return self._crt(other)
+ 
+     def additive_order(self):
+         r"""
+@@ -1742,7 +1742,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             sage: Integers(90308402384902)(2).additive_order()
+             45154201192451
+         """
+-        n = self.__modulus.sageInteger
++        n = self._modulus.sageInteger
+         return sage.rings.integer.Integer(n // self.lift().gcd(n))
+ 
+     def is_primitive_root(self):
+@@ -1856,7 +1856,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             return sage.rings.integer.Integer(self.__pari__().znorder())
+         except PariError:
+             raise ArithmeticError("multiplicative order of %s not defined since it is not a unit modulo %s"%(
+-                self, self.__modulus.sageInteger))
++                self, self._modulus.sageInteger))
+ 
+     def valuation(self, p):
+         """
+@@ -1905,7 +1905,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             2
+ 
+         """
+-        p=self.__modulus.sageInteger.gcd(p)
++        p=self._modulus.sageInteger.gcd(p)
+         if p==1:
+             raise ValueError("Valuation with respect to a unit is not defined.")
+         r = 0
+@@ -1913,7 +1913,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         while not (self % power): # self % power == 0
+             r += 1
+             power *= p
+-            if not power.divides(self.__modulus.sageInteger):
++            if not power.divides(self._modulus.sageInteger):
+                 from sage.rings.infinity import infinity
+                 return infinity
+         return r
+@@ -1980,7 +1980,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+     cdef IntegerMod_gmp _new_c(self):
+         cdef IntegerMod_gmp x
+         x = IntegerMod_gmp.__new__(IntegerMod_gmp)
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x._parent = self._parent
+         return x
+ 
+@@ -1989,7 +1989,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+ 
+     cdef void set_from_mpz(self, mpz_t value):
+         cdef sage.rings.integer.Integer modulus
+-        modulus = self.__modulus.sageInteger
++        modulus = self._modulus.sageInteger
+         mpz_mod(self.value, value, modulus.value)
+ 
+     cdef void set_from_long(self, long value):
+@@ -2001,7 +2001,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             1
+         """
+         mpz_set_si(self.value, value)
+-        mpz_mod(self.value, self.value, self.__modulus.sageInteger.value)
++        mpz_mod(self.value, self.value, self._modulus.sageInteger.value)
+ 
+     cdef void set_from_ulong_fast(self, unsigned long value):
+         mpz_set_ui(self.value, value)
+@@ -2071,7 +2071,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             x = self._new_c()
+             if k > 0:
+                 mpz_mul_2exp(x.value, self.value, k)
+-                mpz_fdiv_r(x.value, x.value, self.__modulus.sageInteger.value)
++                mpz_fdiv_r(x.value, x.value, self._modulus.sageInteger.value)
+             else:
+                 mpz_fdiv_q_2exp(x.value, self.value, -k)
+             return x
+@@ -2132,12 +2132,12 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         """
+         return self.lift().gcd(self.modulus()) == 1
+ 
+-    def __crt(IntegerMod_gmp self, IntegerMod_gmp other):
++    def _crt(IntegerMod_gmp self, IntegerMod_gmp other):
+         cdef IntegerMod_gmp lift, x
+         cdef sage.rings.integer.Integer modulus, other_modulus
+ 
+-        modulus = self.__modulus.sageInteger
+-        other_modulus = other.__modulus.sageInteger
++        modulus = self._modulus.sageInteger
++        other_modulus = other._modulus.sageInteger
+         from .integer_mod_ring import IntegerModRing
+         lift = IntegerMod_gmp(IntegerModRing(modulus*other_modulus))
+         try:
+@@ -2188,8 +2188,8 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+         mpz_add(x.value, self.value, (<IntegerMod_gmp>right).value)
+-        if mpz_cmp(x.value, self.__modulus.sageInteger.value)  >= 0:
+-            mpz_sub(x.value, x.value, self.__modulus.sageInteger.value)
++        if mpz_cmp(x.value, self._modulus.sageInteger.value)  >= 0:
++            mpz_sub(x.value, x.value, self._modulus.sageInteger.value)
+         return x
+ 
+     cpdef _sub_(self, right):
+@@ -2204,7 +2204,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         x = self._new_c()
+         mpz_sub(x.value, self.value, (<IntegerMod_gmp>right).value)
+         if mpz_sgn(x.value) == -1:
+-            mpz_add(x.value, x.value, self.__modulus.sageInteger.value)
++            mpz_add(x.value, x.value, self._modulus.sageInteger.value)
+         return x
+ 
+     cpdef _neg_(self):
+@@ -2220,7 +2220,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             return self
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+-        mpz_sub(x.value, self.__modulus.sageInteger.value, self.value)
++        mpz_sub(x.value, self._modulus.sageInteger.value, self.value)
+         return x
+ 
+     cpdef _mul_(self, right):
+@@ -2234,7 +2234,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+         mpz_mul(x.value, self.value,  (<IntegerMod_gmp>right).value)
+-        mpz_fdiv_r(x.value, x.value, self.__modulus.sageInteger.value)
++        mpz_fdiv_r(x.value, x.value, self._modulus.sageInteger.value)
+         return x
+ 
+     cpdef _div_(self, right):
+@@ -2310,7 +2310,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         cdef IntegerMod_gmp x = self._new_c()
+         sig_on()
+         try:
+-            mpz_pow_helper(x.value, self.value, exp, self.__modulus.sageInteger.value)
++            mpz_pow_helper(x.value, self.value, exp, self._modulus.sageInteger.value)
+         finally:
+             sig_off()
+         return x
+@@ -2331,12 +2331,12 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             ZeroDivisionError: inverse of Mod(2, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000) does not exist
+         """
+         if self.is_zero():
+-            raise ZeroDivisionError(f"inverse of Mod(0, {self.__modulus.sageInteger}) does not exist")
++            raise ZeroDivisionError(f"inverse of Mod(0, {self._modulus.sageInteger}) does not exist")
+ 
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+-        if not mpz_invert(x.value, self.value, self.__modulus.sageInteger.value):
+-            raise ZeroDivisionError(f"inverse of Mod({self}, {self.__modulus.sageInteger}) does not exist")
++        if not mpz_invert(x.value, self.value, self._modulus.sageInteger.value):
++            raise ZeroDivisionError(f"inverse of Mod({self}, {self._modulus.sageInteger}) does not exist")
+         return x
+ 
+     def lift(IntegerMod_gmp self):
+@@ -2391,10 +2391,10 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         """
+         cdef IntegerMod_gmp ans = self._new_c()
+         sig_on()
+-        mpz_gcd(ans.value, self.value, self.__modulus.sageInteger.value)
++        mpz_gcd(ans.value, self.value, self._modulus.sageInteger.value)
+         mpz_gcd(ans.value, ans.value, other.value)
+         sig_off()
+-        if mpz_cmp(ans.value, self.__modulus.sageInteger.value) == 0:
++        if mpz_cmp(ans.value, self._modulus.sageInteger.value) == 0:
+             # self = other = 0
+             mpz_set_ui(ans.value, 0)
+         return ans
+@@ -2422,30 +2422,30 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+     """
+ 
+     cdef IntegerMod_int _new_c(self, int_fast32_t value):
+-        if self.__modulus.table is not None:
+-            return self.__modulus.table[value]
++        if self._modulus.table is not None:
++            return self._modulus.table[value]
+         cdef IntegerMod_int x = IntegerMod_int.__new__(IntegerMod_int)
+         x._parent = self._parent
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x.ivalue = value
+         return x
+ 
+     cdef void set_from_mpz(self, mpz_t value):
+-        self.ivalue = mpz_fdiv_ui(value, self.__modulus.int32)
++        self.ivalue = mpz_fdiv_ui(value, self._modulus.int32)
+ 
+     cdef void set_from_long(self, long value):
+-        self.ivalue = value % self.__modulus.int32
++        self.ivalue = value % self._modulus.int32
+         if self.ivalue < 0:
+-            self.ivalue += self.__modulus.int32
++            self.ivalue += self._modulus.int32
+ 
+     cdef void set_from_ulong_fast(self, unsigned long value):
+         self.ivalue = value
+ 
+     cdef void set_from_int(IntegerMod_int self, int_fast32_t ivalue):
+         if ivalue < 0:
+-            self.ivalue = self.__modulus.int32 + (ivalue % self.__modulus.int32)
+-        elif ivalue >= self.__modulus.int32:
+-            self.ivalue = ivalue % self.__modulus.int32
++            self.ivalue = self._modulus.int32 + (ivalue % self._modulus.int32)
++        elif ivalue >= self._modulus.int32:
++            self.ivalue = ivalue % self._modulus.int32
+         else:
+             self.ivalue = ivalue
+ 
+@@ -2490,7 +2490,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: Zmod(1).one().is_one()
+             True
+         """
+-        return self.ivalue == 1 or self.__modulus.int32 == 1
++        return self.ivalue == 1 or self._modulus.int32 == 1
+ 
+     def __bool__(IntegerMod_int self):
+         """
+@@ -2519,9 +2519,9 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: a.is_unit()
+             False
+         """
+-        return gcd_int(self.ivalue, self.__modulus.int32) == 1
++        return gcd_int(self.ivalue, self._modulus.int32) == 1
+ 
+-    def __crt(IntegerMod_int self, IntegerMod_int other):
++    def _crt(IntegerMod_int self, IntegerMod_int other):
+         """
+         Use the Chinese Remainder Theorem to find an element of the
+         integers modulo the product of the moduli that reduces to self and
+@@ -2543,11 +2543,11 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         cdef int_fast32_t x
+ 
+         from .integer_mod_ring import IntegerModRing
+-        lift = IntegerMod_int(IntegerModRing(self.__modulus.int32 * other.__modulus.int32))
++        lift = IntegerMod_int(IntegerModRing(self._modulus.int32 * other._modulus.int32))
+ 
+         try:
+-            x = (other.ivalue - self.ivalue % other.__modulus.int32) * mod_inverse_int(self.__modulus.int32, other.__modulus.int32)
+-            lift.set_from_int( x * self.__modulus.int32 + self.ivalue )
++            x = (other.ivalue - self.ivalue % other._modulus.int32) * mod_inverse_int(self._modulus.int32, other._modulus.int32)
++            lift.set_from_int( x * self._modulus.int32 + self.ivalue )
+             return lift
+         except ZeroDivisionError:
+             raise ZeroDivisionError("moduli must be coprime")
+@@ -2586,8 +2586,8 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         """
+         cdef int_fast32_t x
+         x = self.ivalue + (<IntegerMod_int>right).ivalue
+-        if x >= self.__modulus.int32:
+-            x = x - self.__modulus.int32
++        if x >= self._modulus.int32:
++            x = x - self._modulus.int32
+         return self._new_c(x)
+ 
+     cpdef _sub_(self, right):
+@@ -2601,7 +2601,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         cdef int_fast32_t x
+         x = self.ivalue - (<IntegerMod_int>right).ivalue
+         if x < 0:
+-            x = x + self.__modulus.int32
++            x = x + self._modulus.int32
+         return self._new_c(x)
+ 
+     cpdef _neg_(self):
+@@ -2615,7 +2615,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         """
+         if self.ivalue == 0:
+             return self
+-        return self._new_c(self.__modulus.int32 - self.ivalue)
++        return self._new_c(self._modulus.int32 - self.ivalue)
+ 
+     cpdef _mul_(self, right):
+         """
+@@ -2625,7 +2625,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: R(7) * R(8)
+             6
+         """
+-        return self._new_c((self.ivalue * (<IntegerMod_int>right).ivalue) % self.__modulus.int32)
++        return self._new_c((self.ivalue * (<IntegerMod_int>right).ivalue) % self._modulus.int32)
+ 
+     cpdef _div_(self, right):
+         """
+@@ -2635,16 +2635,16 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: R(2)/3
+             4
+         """
+-        if self.__modulus.inverses is not None:
+-            right_inverse = self.__modulus.inverses[(<IntegerMod_int>right).ivalue]
++        if self._modulus.inverses is not None:
++            right_inverse = self._modulus.inverses[(<IntegerMod_int>right).ivalue]
+             if right_inverse is None:
+-                raise ZeroDivisionError(f"inverse of Mod({right}, {self.__modulus.sageInteger}) does not exist")
++                raise ZeroDivisionError(f"inverse of Mod({right}, {self._modulus.sageInteger}) does not exist")
+             else:
+-                return self._new_c((self.ivalue * (<IntegerMod_int>right_inverse).ivalue) % self.__modulus.int32)
++                return self._new_c((self.ivalue * (<IntegerMod_int>right_inverse).ivalue) % self._modulus.int32)
+ 
+         cdef int_fast32_t x
+-        x = self.ivalue * mod_inverse_int((<IntegerMod_int>right).ivalue, self.__modulus.int32)
+-        return self._new_c(x% self.__modulus.int32)
++        x = self.ivalue * mod_inverse_int((<IntegerMod_int>right).ivalue, self._modulus.int32)
++        return self._new_c(x% self._modulus.int32)
+ 
+     def __int__(IntegerMod_int self):
+         """
+@@ -2739,7 +2739,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         if k == 0:
+             return self
+         elif k > 0:
+-            return self._new_c((self.ivalue << k) % self.__modulus.int32)
++            return self._new_c((self.ivalue << k) % self._modulus.int32)
+         else:
+             return self._new_c(self.ivalue >> (-k))
+ 
+@@ -2802,7 +2802,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sig_on()
+             try:
+                 mpz_init(res_mpz)
+-                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self.__modulus.sageInteger.value)
++                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self._modulus.sageInteger.value)
+                 res = mpz_get_ui(res_mpz)
+                 mpz_clear(res_mpz)
+             finally:
+@@ -2811,12 +2811,12 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+ 
+         if long_exp == 0 and self.ivalue == 0:
+             # Return 0 if the modulus is 1, otherwise return 1.
+-            return self._new_c(self.__modulus.int32 != 1)
++            return self._new_c(self._modulus.int32 != 1)
+         cdef bint invert = False
+         if long_exp < 0:
+             invert = True
+             long_exp = -long_exp
+-        res = mod_pow_int(self.ivalue, long_exp, self.__modulus.int32)
++        res = mod_pow_int(self.ivalue, long_exp, self._modulus.int32)
+         if invert:
+             return ~self._new_c(res)
+         else:
+@@ -2833,14 +2833,14 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: Mod(0,1)^-1
+             0
+         """
+-        if self.__modulus.inverses is not None:
+-            x = self.__modulus.inverses[self.ivalue]
++        if self._modulus.inverses is not None:
++            x = self._modulus.inverses[self.ivalue]
+             if x is None:
+-                raise ZeroDivisionError(f"inverse of Mod({self}, {self.__modulus.sageInteger}) does not exist")
++                raise ZeroDivisionError(f"inverse of Mod({self}, {self._modulus.sageInteger}) does not exist")
+             else:
+                 return x
+         else:
+-            return self._new_c(mod_inverse_int(self.ivalue, self.__modulus.int32))
++            return self._new_c(mod_inverse_int(self.ivalue, self._modulus.int32))
+ 
+     def lift(IntegerMod_int self):
+         """
+@@ -3006,15 +3006,15 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: GF(103)(-1).sqrt(extend=False, all=True)
+             []
+         """
+-        cdef int_fast32_t i, n = self.__modulus.int32
++        cdef int_fast32_t i, n = self._modulus.int32
+         if n > 100:
+             moduli = self._parent.factored_order()
+         # Unless the modulus is tiny, test to see if we're in the really
+         # easy case of n prime, n = 3 mod 4.
+         if n > 100 and n % 4 == 3 and len(moduli) == 1 and moduli[0][1] == 1:
+-            if jacobi_int(self.ivalue, self.__modulus.int32) == 1:
++            if jacobi_int(self.ivalue, self._modulus.int32) == 1:
+                 # it's a non-zero square, sqrt(a) = a^(p+1)/4
+-                i = mod_pow_int(self.ivalue, (self.__modulus.int32+1)/4, n)
++                i = mod_pow_int(self.ivalue, (self._modulus.int32+1)/4, n)
+                 if i > n / 2:
+                     i = n - i
+                 if all:
+@@ -3049,7 +3049,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         This function returns `x` or `-x`, whichever has a
+         positive representative in `-n/2 < x \leq n/2`.
+         """
+-        if self.ivalue > self.__modulus.int32 / 2:
++        if self.ivalue > self._modulus.int32 / 2:
+             return -self
+         return self
+ 
+@@ -3082,9 +3082,9 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: mod(0,1).gcd(mod(0,1))
+             0
+         """
+-        cdef int_fast32_t g = gcd_int(self.ivalue, self.__modulus.int32)
++        cdef int_fast32_t g = gcd_int(self.ivalue, self._modulus.int32)
+         g = gcd_int(g, other.ivalue)
+-        if g == self.__modulus.int32: # self = other = 0
++        if g == self._modulus.int32: # self = other = 0
+             g = 0
+         return self._new_c(g)
+ 
+@@ -3256,27 +3256,27 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+     cdef IntegerMod_int64 _new_c(self, int_fast64_t value):
+         cdef IntegerMod_int64 x
+         x = IntegerMod_int64.__new__(IntegerMod_int64)
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x._parent = self._parent
+         x.ivalue = value
+         return x
+ 
+     cdef void set_from_mpz(self, mpz_t value):
+-        self.ivalue = mpz_fdiv_ui(value, self.__modulus.int64)
++        self.ivalue = mpz_fdiv_ui(value, self._modulus.int64)
+ 
+     cdef void set_from_long(self, long value):
+-        self.ivalue = value % self.__modulus.int64
++        self.ivalue = value % self._modulus.int64
+         if self.ivalue < 0:
+-            self.ivalue += self.__modulus.int64
++            self.ivalue += self._modulus.int64
+ 
+     cdef void set_from_ulong_fast(self, unsigned long value):
+         self.ivalue = value
+ 
+     cdef void set_from_int(IntegerMod_int64 self, int_fast64_t ivalue):
+         if ivalue < 0:
+-            self.ivalue = self.__modulus.int64 + (ivalue % self.__modulus.int64) # Is ivalue % self.__modulus.int64 actually negative?
+-        elif ivalue >= self.__modulus.int64:
+-            self.ivalue = ivalue % self.__modulus.int64
++            self.ivalue = self._modulus.int64 + (ivalue % self._modulus.int64) # Is ivalue % self._modulus.int64 actually negative?
++        elif ivalue >= self._modulus.int64:
++            self.ivalue = ivalue % self._modulus.int64
+         else:
+             self.ivalue = ivalue
+ 
+@@ -3344,9 +3344,9 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: mod(25, 5^10).is_unit()
+             False
+         """
+-        return gcd_int64(self.ivalue, self.__modulus.int64) == 1
++        return gcd_int64(self.ivalue, self._modulus.int64) == 1
+ 
+-    def __crt(IntegerMod_int64 self, IntegerMod_int64 other):
++    def _crt(IntegerMod_int64 self, IntegerMod_int64 other):
+         """
+         Use the Chinese Remainder Theorem to find an element of the
+         integers modulo the product of the moduli that reduces to self and
+@@ -3379,11 +3379,11 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         cdef int_fast64_t x
+ 
+         from .integer_mod_ring import IntegerModRing
+-        lift = IntegerMod_int64(IntegerModRing(self.__modulus.int64 * other.__modulus.int64))
++        lift = IntegerMod_int64(IntegerModRing(self._modulus.int64 * other._modulus.int64))
+ 
+         try:
+-            x = (other.ivalue - self.ivalue % other.__modulus.int64) * mod_inverse_int64(self.__modulus.int64, other.__modulus.int64)
+-            lift.set_from_int( x * self.__modulus.int64 + self.ivalue )
++            x = (other.ivalue - self.ivalue % other._modulus.int64) * mod_inverse_int64(self._modulus.int64, other._modulus.int64)
++            lift.set_from_int( x * self._modulus.int64 + self.ivalue )
+             return lift
+         except ZeroDivisionError:
+             raise ZeroDivisionError("moduli must be coprime")
+@@ -3422,8 +3422,8 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         """
+         cdef int_fast64_t x
+         x = self.ivalue + (<IntegerMod_int64>right).ivalue
+-        if x >= self.__modulus.int64:
+-            x = x - self.__modulus.int64
++        if x >= self._modulus.int64:
++            x = x - self._modulus.int64
+         return self._new_c(x)
+ 
+     cpdef _sub_(self, right):
+@@ -3437,7 +3437,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         cdef int_fast64_t x
+         x = self.ivalue - (<IntegerMod_int64>right).ivalue
+         if x < 0:
+-            x = x + self.__modulus.int64
++            x = x + self._modulus.int64
+         return self._new_c(x)
+ 
+     cpdef _neg_(self):
+@@ -3451,7 +3451,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         """
+         if self.ivalue == 0:
+             return self
+-        return self._new_c(self.__modulus.int64 - self.ivalue)
++        return self._new_c(self._modulus.int64 - self.ivalue)
+ 
+     cpdef _mul_(self, right):
+         """
+@@ -3461,7 +3461,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: R(700) * R(800)
+             60000
+         """
+-        return self._new_c((self.ivalue * (<IntegerMod_int64>right).ivalue) % self.__modulus.int64)
++        return self._new_c((self.ivalue * (<IntegerMod_int64>right).ivalue) % self._modulus.int64)
+ 
+ 
+     cpdef _div_(self, right):
+@@ -3473,7 +3473,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             33334
+         """
+         return self._new_c((self.ivalue * mod_inverse_int64((<IntegerMod_int64>right).ivalue,
+-                                   self.__modulus.int64) ) % self.__modulus.int64)
++                                   self._modulus.int64) ) % self._modulus.int64)
+ 
+     def __int__(IntegerMod_int64 self):
+         return self.ivalue
+@@ -3559,7 +3559,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         if k == 0:
+             return self
+         elif k > 0:
+-            return self._new_c((self.ivalue << k) % self.__modulus.int64)
++            return self._new_c((self.ivalue << k) % self._modulus.int64)
+         else:
+             return self._new_c(self.ivalue >> (-k))
+ 
+@@ -3633,7 +3633,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sig_on()
+             try:
+                 mpz_init(res_mpz)
+-                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self.__modulus.sageInteger.value)
++                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self._modulus.sageInteger.value)
+                 res = mpz_get_ui(res_mpz)
+                 mpz_clear(res_mpz)
+             finally:
+@@ -3642,14 +3642,14 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+ 
+         if long_exp == 0 and self.ivalue == 0:
+             # Return 0 if the modulus is 1, otherwise return 1.
+-            return self._new_c(self.__modulus.int64 != 1)
++            return self._new_c(self._modulus.int64 != 1)
+         cdef bint invert = False
+         if long_exp < 0:
+             invert = True
+             long_exp = -long_exp
+-        res = mod_pow_int64(self.ivalue, long_exp, self.__modulus.int64)
++        res = mod_pow_int64(self.ivalue, long_exp, self._modulus.int64)
+         if invert:
+-            return self._new_c(mod_inverse_int64(res, self.__modulus.int64))
++            return self._new_c(mod_inverse_int64(res, self._modulus.int64))
+         else:
+             return self._new_c(res)
+ 
+@@ -3666,7 +3666,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: a
+             7
+         """
+-        return self._new_c(mod_inverse_int64(self.ivalue, self.__modulus.int64))
++        return self._new_c(mod_inverse_int64(self.ivalue, self._modulus.int64))
+ 
+     def lift(IntegerMod_int64 self):
+         """
+@@ -3715,7 +3715,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         This function returns `x` or `-x`, whichever has a
+         positive representative in `-n/2 < x \leq n/2`.
+         """
+-        if self.ivalue > self.__modulus.int64 / 2:
++        if self.ivalue > self._modulus.int64 / 2:
+             return -self
+         return self
+ 
+@@ -3738,9 +3738,9 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: mod(0,17^5).gcd(mod(0,17^5))
+             0
+         """
+-        cdef int_fast64_t g = gcd_int64(self.ivalue, self.__modulus.int64)
++        cdef int_fast64_t g = gcd_int64(self.ivalue, self._modulus.int64)
+         g = gcd_int64(g, other.ivalue)
+-        if g == self.__modulus.int64: # self = other = 0
++        if g == self._modulus.int64: # self = other = 0
+             g = 0
+         return self._new_c(g)
+ 
+diff --git a/src/sage/rings/fraction_field_FpT.pyx b/src/sage/rings/fraction_field_FpT.pyx
+index 0a25191a11c..c9bb5d5a384 100644
+--- a/src/sage/rings/fraction_field_FpT.pyx
++++ b/src/sage/rings/fraction_field_FpT.pyx
+@@ -1650,7 +1650,7 @@ cdef class FpT_Fp_section(Section):
+                 raise ValueError("not constant")
+         ans = IntegerMod_int.__new__(IntegerMod_int)
+         ans._parent = self.codomain()
+-        ans.__modulus = ans._parent._pyx_order
++        ans._modulus = ans._parent._pyx_order
+         if nmod_poly_get_coeff_ui(x._denom, 0) != 1:
+             normalize(x._numer, x._denom, self.p)
+         ans.ivalue = nmod_poly_get_coeff_ui(x._numer, 0)
+diff --git a/src/sage/rings/fraction_field_element.pyx b/src/sage/rings/fraction_field_element.pyx
+index 11a2b646d35..75e47af1299 100644
+--- a/src/sage/rings/fraction_field_element.pyx
++++ b/src/sage/rings/fraction_field_element.pyx
+@@ -78,8 +78,8 @@ cdef class FractionFieldElement(FieldElement):
+         sage: F.one().quo_rem(F.one())
+         (1, 0)
+     """
+-    cdef object __numerator
+-    cdef object __denominator
++    cdef object _numerator
++    cdef object _denominator
+     cdef bint _is_reduced
+ 
+     def __init__(self, parent, numerator, denominator=1,
+@@ -108,17 +108,17 @@ cdef class FractionFieldElement(FieldElement):
+         """
+         FieldElement.__init__(self, parent)
+         if coerce:
+-            self.__numerator   = parent.ring()(numerator)
+-            self.__denominator = parent.ring()(denominator)
++            self._numerator   = parent.ring()(numerator)
++            self._denominator = parent.ring()(denominator)
+         else:
+-            self.__numerator   = numerator
+-            self.__denominator = denominator
++            self._numerator   = numerator
++            self._denominator = denominator
+         if reduce and parent.is_exact():
+             try:
+                 self.reduce()
+             except ArithmeticError:
+                 pass
+-        if self.__denominator.is_zero():
++        if self._denominator.is_zero():
+             raise ZeroDivisionError("fraction field element division by zero")
+ 
+     def _im_gens_(self, codomain, im_gens, base_map=None):
+@@ -154,8 +154,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: phi(i/a)                                                              # optional - sage.rings.number_field
+             ((-i))/b
+         """
+-        nnum = codomain.coerce(self.__numerator._im_gens_(codomain, im_gens, base_map=base_map))
+-        nden = codomain.coerce(self.__denominator._im_gens_(codomain, im_gens, base_map=base_map))
++        nnum = codomain.coerce(self._numerator._im_gens_(codomain, im_gens, base_map=base_map))
++        nden = codomain.coerce(self._denominator._im_gens_(codomain, im_gens, base_map=base_map))
+         return codomain.coerce(nnum/nden)
+ 
+     cpdef reduce(self):
+@@ -191,10 +191,10 @@ cdef class FractionFieldElement(FieldElement):
+         if self._is_reduced:
+             return
+         try:
+-            g = self.__numerator.gcd(self.__denominator)
++            g = self._numerator.gcd(self._denominator)
+             if not g.is_unit():
+-                self.__numerator //= g
+-                self.__denominator //= g
++                self._numerator //= g
++                self._denominator //= g
+             self._is_reduced = True
+         except AttributeError:
+             raise ArithmeticError("unable to reduce because lack of gcd or quo_rem algorithm")
+@@ -202,14 +202,14 @@ cdef class FractionFieldElement(FieldElement):
+             raise ArithmeticError("unable to reduce because gcd algorithm doesn't work on input")
+         except NotImplementedError:
+             raise ArithmeticError("unable to reduce because gcd algorithm not implemented on input")
+-        if not self.__denominator.is_one() and self.__denominator.is_unit():
++        if not self._denominator.is_one() and self._denominator.is_unit():
+             try:
+-                inv = self.__denominator.inverse_of_unit()
++                inv = self._denominator.inverse_of_unit()
+             except Exception:
+                 pass
+             else:
+-                self.__numerator *= inv
+-                self.__denominator = self.__denominator.parent().one()
++                self._numerator *= inv
++                self._denominator = self._denominator.parent().one()
+ 
+     def __copy__(self):
+         """
+@@ -223,8 +223,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: copy(f)
+             (x + y)/y
+         """
+-        return self.__class__(self._parent, self.__numerator,
+-                self.__denominator, coerce=False, reduce=False)
++        return self.__class__(self._parent, self._numerator,
++                self._denominator, coerce=False, reduce=False)
+ 
+     def numerator(self):
+         """
+@@ -238,7 +238,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f.numerator()
+             x + y
+         """
+-        return self.__numerator
++        return self._numerator
+ 
+     def denominator(self):
+         """
+@@ -252,7 +252,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f.denominator()
+             y
+         """
+-        return self.__denominator
++        return self._denominator
+ 
+ 
+     def is_square(self,root=False):
+@@ -399,10 +399,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: ((x+1)/(x^2+1)).subs({x: 1})                                          # optional - sage.rings.number_field
+             1
+         """
+-        if self.__denominator.is_one():
++        if self._denominator.is_one():
+             # Handle this case even over rings that don't support reduction, to
+             # avoid breaking existing code that carelessly mixes p and p/1
+-            return hash(self.__numerator)
++            return hash(self._numerator)
+         if self._parent.is_exact():
+             # May fail; let the exception propagate then.
+             # (In contrast, over inexact rings, we hash unreduced fractions
+@@ -413,8 +413,8 @@ cdef class FractionFieldElement(FieldElement):
+             # issues even if we didn't...)
+             self.reduce()
+         # Same algorithm as for elements of QQ
+-        n = hash(self.__numerator)
+-        d = hash(self.__denominator)
++        n = hash(self._numerator)
++        d = hash(self._denominator)
+         if d == 1:
+             return n
+         else:
+@@ -443,7 +443,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: h(x0=1)
+             (-2*x1*x2 + x1 + 1)/(x1 + x2)
+         """
+-        return self.__numerator(*x, **kwds) / self.__denominator(*x, **kwds)
++        return self._numerator(*x, **kwds) / self._denominator(*x, **kwds)
+ 
+     def _is_atomic(self):
+         """
+@@ -456,7 +456,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f._is_atomic()
+             False
+         """
+-        return self.__numerator._is_atomic() and self.__denominator._is_atomic()
++        return self._numerator._is_atomic() and self._denominator._is_atomic()
+ 
+     def _repr_(self):
+         """
+@@ -476,13 +476,13 @@ cdef class FractionFieldElement(FieldElement):
+         """
+         if self.is_zero():
+             return "0"
+-        s = "%s" % self.__numerator
+-        if self.__denominator != 1:
+-            denom_string = str( self.__denominator )
+-            if self.__denominator._is_atomic() and not ('*' in denom_string or '/' in denom_string):
+-                s = "%s/%s"%(self.__numerator._coeff_repr(no_space=False),denom_string)
++        s = "%s" % self._numerator
++        if self._denominator != 1:
++            denom_string = str( self._denominator )
++            if self._denominator._is_atomic() and not ('*' in denom_string or '/' in denom_string):
++                s = "%s/%s"%(self._numerator._coeff_repr(no_space=False),denom_string)
+             else:
+-                s = "%s/(%s)"%(self.__numerator._coeff_repr(no_space=False),denom_string)
++                s = "%s/(%s)"%(self._numerator._coeff_repr(no_space=False),denom_string)
+         return s
+ 
+     def _latex_(self):
+@@ -518,10 +518,10 @@ cdef class FractionFieldElement(FieldElement):
+         """
+         if self.is_zero():
+             return "0"
+-        if self.__denominator == 1:
+-            return latex.latex(self.__numerator)
+-        return "\\frac{%s}{%s}"%(latex.latex(self.__numerator),
+-                                 latex.latex(self.__denominator))
++        if self._denominator == 1:
++            return latex.latex(self._numerator)
++        return "\\frac{%s}{%s}"%(latex.latex(self._numerator),
++                                 latex.latex(self._denominator))
+ 
+     def _magma_init_(self, magma):
+         """
+@@ -577,10 +577,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: t - 1/t # indirect doctest                                            # optional - sage.rings.finite_rings
+             (t^2 + 6)/t
+         """
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         if (rnum.is_zero()):
+             return <FractionFieldElement> right
+@@ -602,7 +602,7 @@ cdef class FractionFieldElement(FieldElement):
+                             self._parent.ring().one(), coerce=False,
+                             reduce=False)
+                     else:
+-                        tden = self.__denominator * sden
++                        tden = self._denominator * sden
+                         e    = tnum.gcd(d)
+                         if not e.is_unit():
+                             tnum = tnum // e
+@@ -624,10 +624,10 @@ cdef class FractionFieldElement(FieldElement):
+             except TypeError:
+                 pass
+ 
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         return self.__class__(self._parent, rnum*sden + rden*snum, rden*sden,
+             coerce=False, reduce=False)
+@@ -652,10 +652,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: a * b # indirect doctest                                              # optional - sage.rings.finite_rings
+             3/(t + 1)
+         """
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         if (rnum.is_zero() or snum.is_zero()):
+             return self._parent.zero()
+@@ -689,10 +689,10 @@ cdef class FractionFieldElement(FieldElement):
+             except TypeError:
+                 pass
+ 
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         return self.__class__(self._parent, rnum * snum, rden * sden,
+             coerce=False, reduce=False)
+@@ -717,8 +717,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: a/b
+             (x*z - x + z - 1)/(z - 3)
+         """
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         if snum.is_zero():
+             raise ZeroDivisionError("fraction field element division by zero")
+@@ -743,10 +743,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: int(K(.5))
+             0
+         """
+-        if self.__denominator != 1:
++        if self._denominator != 1:
+             self.reduce()
+-        if self.__denominator == 1:
+-            return int(self.__numerator)
++        if self._denominator == 1:
++            return int(self._numerator)
+         else:
+             raise TypeError("denominator must equal 1")
+ 
+@@ -758,7 +758,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: float(x/x + y/y)
+             2.0
+         """
+-        return float(self.__numerator) / float(self.__denominator)
++        return float(self._numerator) / float(self._denominator)
+ 
+     def __complex__(self):
+         """
+@@ -768,7 +768,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: complex(x/(I*x) + (I*y)/y)
+             0j
+         """
+-        return complex(self.__numerator) / complex(self.__denominator)
++        return complex(self._numerator) / complex(self._denominator)
+ 
+     def _rational_(self):
+         r"""
+@@ -822,12 +822,12 @@ cdef class FractionFieldElement(FieldElement):
+             sage: A(C(u))                                                               # optional - sage.rings.number_field
+             u
+         """
+-        if self.__denominator.is_one():
+-            return R(self.__numerator)
++        if self._denominator.is_one():
++            return R(self._numerator)
+         else:
+             self.reduce()
+-            num = R(self.__numerator)
+-            inv_den = R(self.__denominator).inverse_of_unit()
++            num = R(self._numerator)
++            inv_den = R(self._denominator).inverse_of_unit()
+             return num * inv_den
+ 
+     _real_double_ = _conversion
+@@ -847,7 +847,7 @@ cdef class FractionFieldElement(FieldElement):
+         Returns self raised to the `right^{th}` power.
+ 
+         Note that we need to check whether or not right is negative so we
+-        don't set ``__numerator`` or ``__denominator`` to an element of the
++        don't set ``_numerator`` or ``_denominator`` to an element of the
+         fraction field instead of the underlying ring.
+ 
+         EXAMPLES::
+@@ -876,8 +876,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: ((x+y)/(x-y))^0
+             1
+         """
+-        snum = (<FractionFieldElement> self).__numerator
+-        sden = (<FractionFieldElement> self).__denominator
++        snum = (<FractionFieldElement> self)._numerator
++        sden = (<FractionFieldElement> self)._denominator
+         if right == 0:
+             R = self.parent().ring()
+             return self.__class__(self.parent(),
+@@ -904,7 +904,7 @@ cdef class FractionFieldElement(FieldElement):
+             (4*t^2 + 4*t)/(t + 2)
+         """
+         return self.__class__(self._parent,
+-            -self.__numerator, self.__denominator,
++            -self._numerator, self._denominator,
+             coerce=False, reduce=False)
+ 
+     def __abs__(self):
+@@ -915,7 +915,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: abs(FractionFieldElement(QQ, -2, 3, coerce=False))
+             2/3
+         """
+-        return abs(self.__numerator) / abs(self.__denominator)
++        return abs(self._numerator) / abs(self._denominator)
+ 
+     def __invert__(self):
+         """
+@@ -929,7 +929,7 @@ cdef class FractionFieldElement(FieldElement):
+         if self.is_zero():
+             raise ZeroDivisionError("Cannot invert 0")
+         return self.__class__(self._parent,
+-            self.__denominator, self.__numerator, coerce=False, reduce=False)
++            self._denominator, self._numerator, coerce=False, reduce=False)
+ 
+     cpdef _richcmp_(self, other, int op):
+         """
+@@ -951,10 +951,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: 1 > y
+             False
+         """
+-        return richcmp(self.__numerator *
+-                       (<FractionFieldElement>other).__denominator,
+-                       self.__denominator *
+-                       (<FractionFieldElement>other).__numerator, op)
++        return richcmp(self._numerator *
++                       (<FractionFieldElement>other)._denominator,
++                       self._denominator *
++                       (<FractionFieldElement>other)._numerator, op)
+ 
+     def valuation(self, v=None):
+         """
+@@ -972,7 +972,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f.valuation(x^2 + 1)
+             1
+         """
+-        return self.__numerator.valuation(v) - self.__denominator.valuation(v)
++        return self._numerator.valuation(v) - self._denominator.valuation(v)
+ 
+     def __bool__(self):
+         """
+@@ -991,7 +991,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: bool(1/x)
+             True
+         """
+-        return not self.__numerator.is_zero()
++        return not self._numerator.is_zero()
+ 
+     def is_zero(self):
+         """
+@@ -1010,7 +1010,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: u.parent() is F
+             True
+         """
+-        return self.__numerator.is_zero()
++        return self._numerator.is_zero()
+ 
+     def is_one(self):
+         """
+@@ -1025,7 +1025,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: (x/y).is_one()
+             False
+         """
+-        return self.__numerator == self.__denominator
++        return self._numerator == self._denominator
+ 
+     def _symbolic_(self, ring):
+         """
+@@ -1044,7 +1044,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: symbolic_expression(elt)                                              # optional - sage.symbolic
+             2/3*(x + y)/(x - y)
+         """
+-        return ring(self.__numerator)/ring(self.__denominator)
++        return ring(self._numerator)/ring(self._denominator)
+ 
+     def __reduce__(self):
+         """
+@@ -1058,7 +1058,7 @@ cdef class FractionFieldElement(FieldElement):
+             True
+         """
+         return (make_element,
+-                (self._parent, self.__numerator, self.__denominator))
++                (self._parent, self._numerator, self._denominator))
+ 
+     def _evaluate_polynomial(self, pol):
+         """
+@@ -1170,9 +1170,9 @@ cdef class FractionFieldElement_1poly_field(FractionFieldElement):
+         """
+         See :meth:`reduce`.
+         """
+-        invlc = ~self.__denominator.leading_coefficient()
+-        self.__denominator = self.__denominator.monic()
+-        self.__numerator *= invlc
++        invlc = ~self._denominator.leading_coefficient()
++        self._denominator = self._denominator.monic()
++        self._numerator *= invlc
+ 
+     def is_integral(self):
+         """
+diff --git a/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py b/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py
+index a27e75f5fce..74ef125fb6a 100644
+--- a/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py
++++ b/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py
+@@ -804,8 +804,8 @@ def _latex_(self):
+             \phi
+             sage: phi.reset_name()
+         """
+-        if hasattr(self, '__custom_name'):
+-            return latex_variable_name(getattr(self, '__custom_name'))
++        if self.get_custom_name() is not None:
++            return latex_variable_name(self.get_custom_name())
+         else:
+             return f'\\phi: {latex(self._function_ring.gen())} \\mapsto ' \
+                    f'{latex(self._gen)}'
+diff --git a/src/sage/rings/laurent_series_ring_element.pxd b/src/sage/rings/laurent_series_ring_element.pxd
+index d190645ce52..8df5a92c9e7 100644
+--- a/src/sage/rings/laurent_series_ring_element.pxd
++++ b/src/sage/rings/laurent_series_ring_element.pxd
+@@ -4,7 +4,7 @@ cdef class LaurentSeries(AlgebraElement):
+     cdef ModuleElement __u
+     cdef long __n
+ 
+-    cdef __normalize(self)
++    cdef _normalize(self)
+     cpdef _add_(self, other)
+     cpdef _mul_(self, other)
+ 
+diff --git a/src/sage/rings/laurent_series_ring_element.pyx b/src/sage/rings/laurent_series_ring_element.pyx
+index 8e950478045..9bef72396b7 100644
+--- a/src/sage/rings/laurent_series_ring_element.pyx
++++ b/src/sage/rings/laurent_series_ring_element.pyx
+@@ -302,7 +302,7 @@ cdef class LaurentSeries(AlgebraElement):
+         x = im_gens[0]
+         return codomain(self.__u._im_gens_(codomain, im_gens, base_map=base_map) * x**self.__n)
+ 
+-    cdef __normalize(self):
++    cdef _normalize(self):
+         r"""
+         A Laurent series is a pair (u(t), n), where either u=0 (to some
+         precision) or u is a unit. This pair corresponds to
+@@ -725,7 +725,7 @@ cdef class LaurentSeries(AlgebraElement):
+                 R = self._parent.base_ring()
+                 coeffs = [value] + [R(0) for _ in range(1,-j)] + self.__u.list()
+                 self.__u = self.__u._parent(coeffs)
+-        self.__normalize()
++        self._normalize()
+ 
+     cpdef _add_(self, right_m):
+         """
+diff --git a/src/sage/rings/morphism.pxd b/src/sage/rings/morphism.pxd
+index ea6089f29b4..4b8e8d052df 100644
+--- a/src/sage/rings/morphism.pxd
++++ b/src/sage/rings/morphism.pxd
+@@ -14,7 +14,7 @@ cdef class RingMap_lift(RingMap):
+ 
+ cdef class RingHomomorphism(RingMap):
+     cdef Morphism _lift
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+ cdef class RingHomomorphism_im_gens(RingHomomorphism):
+     cdef _im_gens
+diff --git a/src/sage/rings/number_field/number_field_element.pxd b/src/sage/rings/number_field/number_field_element.pxd
+index 9b6917223a0..c3d8a8b4a4b 100644
+--- a/src/sage/rings/number_field/number_field_element.pxd
++++ b/src/sage/rings/number_field/number_field_element.pxd
+@@ -11,12 +11,12 @@ from sage.libs.ntl.ntl_ZZ cimport ntl_ZZ
+ 
+ 
+ cdef class NumberFieldElement(NumberFieldElement_base):
+-    cdef ZZX_c __numerator
+-    cdef ZZ_c __denominator
++    cdef ZZX_c _numerator
++    cdef ZZ_c _denominator
+     # Pointers to the defining polynomial (with numerator) for the field.
+     # I keep these as pointers for arithmetic speed.
+-    cdef ntl_ZZX __fld_numerator
+-    cdef ntl_ZZ __fld_denominator
++    cdef ntl_ZZX _fld_numerator
++    cdef ntl_ZZ _fld_denominator
+     cdef object __multiplicative_order
+     cdef object __pari
+     cdef object __matrix
+diff --git a/src/sage/rings/number_field/number_field_element.pyx b/src/sage/rings/number_field/number_field_element.pyx
+index 27e33ad5be0..d44fc55b70c 100644
+--- a/src/sage/rings/number_field/number_field_element.pyx
++++ b/src/sage/rings/number_field/number_field_element.pyx
+@@ -218,8 +218,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef type t = type(self)
+         cdef NumberFieldElement x = <NumberFieldElement>t.__new__(t)
+         x._parent = self._parent
+-        x.__fld_numerator = self.__fld_numerator
+-        x.__fld_denominator = self.__fld_denominator
++        x._fld_numerator = self._fld_numerator
++        x._fld_denominator = self._fld_denominator
+         return x
+ 
+     cdef number_field(self):
+@@ -317,20 +317,20 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             True
+         """
+         FieldElement.__init__(self, parent)
+-        self.__fld_numerator, self.__fld_denominator = parent.absolute_polynomial_ntl()
++        self._fld_numerator, self._fld_denominator = parent.absolute_polynomial_ntl()
+ 
+         cdef ZZ_c coeff
+         if isinstance(f, (int, Integer_sage)):
+             # set it up and exit immediately
+             # fast pathway
+             mpz_to_ZZ(&coeff, (<Integer>ZZ(f)).value)
+-            ZZX_SetCoeff( self.__numerator, 0, coeff )
+-            ZZ_conv_from_int( self.__denominator, 1 )
++            ZZX_SetCoeff( self._numerator, 0, coeff )
++            ZZ_conv_from_int( self._denominator, 1 )
+             return
+         elif isinstance(f, NumberFieldElement):
+             if type(self) is type(f):
+-                self.__numerator = (<NumberFieldElement>f).__numerator
+-                self.__denominator = (<NumberFieldElement>f).__denominator
++                self._numerator = (<NumberFieldElement>f)._numerator
++                self._denominator = (<NumberFieldElement>f)._denominator
+                 return
+             else:
+                 f = f.polynomial()
+@@ -342,11 +342,11 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+ 
+         cdef long i
+         den = f.denominator()
+-        mpz_to_ZZ(&self.__denominator, (<Integer>ZZ(den)).value)
++        mpz_to_ZZ(&self._denominator, (<Integer>ZZ(den)).value)
+         num = f * den
+         for i from 0 <= i <= num.degree():
+             mpz_to_ZZ(&coeff, (<Integer>ZZ(num[i])).value)
+-            ZZX_SetCoeff( self.__numerator, i, coeff )
++            ZZX_SetCoeff( self._numerator, i, coeff )
+ 
+     def _lift_cyclotomic_element(self, new_parent, bint check=True, int rel=0):
+         """
+@@ -417,17 +417,17 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef type t = type(self)
+         cdef NumberFieldElement x = <NumberFieldElement>t.__new__(t)
+         x._parent = <ParentWithBase>new_parent
+-        x.__fld_numerator, x.__fld_denominator = new_parent.polynomial_ntl()
+-        x.__denominator = self.__denominator
++        x._fld_numerator, x._fld_denominator = new_parent.polynomial_ntl()
++        x._denominator = self._denominator
+         cdef ZZX_c result
+         cdef ZZ_c tmp
+         cdef int i
+         cdef ntl_ZZX _num
+         cdef ntl_ZZ _den
+-        for i from 0 <= i <= ZZX_deg(self.__numerator):
+-            tmp = ZZX_coeff(self.__numerator, i)
++        for i from 0 <= i <= ZZX_deg(self._numerator):
++            tmp = ZZX_coeff(self._numerator, i)
+             ZZX_SetCoeff(result, i*rel, tmp)
+-        ZZX_rem(x.__numerator, result, x.__fld_numerator.x)
++        ZZX_rem(x._numerator, result, x._fld_numerator.x)
+         return x
+ 
+     def __reduce__(self):
+@@ -858,7 +858,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef int res
+ 
+         # fast equality check
+-        res = left.__numerator == _right.__numerator and left.__denominator == _right.__denominator
++        res = left._numerator == _right._numerator and left._denominator == _right._denominator
+         if res:
+             if op == Py_EQ or op == Py_GE or op == Py_LE:
+                 return True
+@@ -883,15 +883,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         if P._embedded_real:
+             mpz_init(ld)
+             mpz_init(rd)
+-            ZZ_to_mpz(ld, &left.__denominator)
+-            ZZ_to_mpz(rd, &_right.__denominator)
++            ZZ_to_mpz(ld, &left._denominator)
++            ZZ_to_mpz(rd, &_right._denominator)
+ 
+             v = <RealIntervalFieldElement> P._get_embedding_approx(0)
+             mpfi_init2(la, mpfi_get_prec(v.value))
+             mpfi_init2(ra, mpfi_get_prec(v.value))
+-            ZZX_evaluation_mpfi(la, left.__numerator, v.value)
++            ZZX_evaluation_mpfi(la, left._numerator, v.value)
+             mpfi_div_z(la, la, ld)
+-            ZZX_evaluation_mpfi(ra, _right.__numerator, v.value)
++            ZZX_evaluation_mpfi(ra, _right._numerator, v.value)
+             mpfi_div_z(ra, ra, rd)
+             while mpfr_greaterequal_p(&la.right, &ra.left) \
+                   and mpfr_greaterequal_p(&ra.right, &la.left):
+@@ -899,9 +899,9 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+                 v = <RealIntervalFieldElement> P._get_embedding_approx(i)
+                 mpfi_set_prec(la, mpfi_get_prec(v.value))
+                 mpfi_set_prec(ra, mpfi_get_prec(v.value))
+-                ZZX_evaluation_mpfi(la, left.__numerator, v.value)
++                ZZX_evaluation_mpfi(la, left._numerator, v.value)
+                 mpfi_div_z(la, la, ld)
+-                ZZX_evaluation_mpfi(ra, _right.__numerator, v.value)
++                ZZX_evaluation_mpfi(ra, _right._numerator, v.value)
+                 mpfi_div_z(ra, ra, rd)
+             if op == Py_LT or op == Py_LE:
+                 res = mpfr_less_p(&la.right, &ra.left)
+@@ -950,8 +950,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef Rational tmp_rational
+ 
+         # It seems like a simpler approach would be to simply generate
+-        # random integers for each coefficient of self.__numerator
+-        # and an integer for self.__denominator. However, this would
++        # random integers for each coefficient of self._numerator
++        # and an integer for self._denominator. However, this would
+         # generate things with a fairly fixed shape: in particular,
+         # we'd be very unlikely to get elements like 1/3*a^3 + 1/7,
+         # or anything where the denominators are actually unrelated
+@@ -965,19 +965,19 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+ 
+             # set the denominator
+             mpz_set_si(denom_temp.value, 1)
+-            mpz_to_ZZ(&self.__denominator, (<Integer>denom_temp).value)
+-            for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
++            mpz_to_ZZ(&self._denominator, (<Integer>denom_temp).value)
++            for i from 0 <= i < ZZX_deg(self._fld_numerator.x):
+                 tmp_integer = <Integer>(ZZ.random_element(x=num_bound,
+                                                    distribution=distribution))
+                 mpz_to_ZZ(&ntl_temp, (<Integer>tmp_integer).value)
+-                ZZX_SetCoeff(self.__numerator, i, ntl_temp)
++                ZZX_SetCoeff(self._numerator, i, ntl_temp)
+ 
+         else:
+             coeff_list = []
+             mpz_set_si(denom_temp.value, 1)
+             tmp_integer = Integer.__new__(Integer)
+ 
+-            for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
++            for i from 0 <= i < ZZX_deg(self._fld_numerator.x):
+                 tmp_rational = <Rational>(QQ.random_element(num_bound=num_bound,
+                                                             den_bound=den_bound,
+                                                             distribution=distribution))
+@@ -989,10 +989,10 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             # scale the numerators and set everything appropriately
+ 
+             # first, the denominator (easy)
+-            mpz_to_ZZ(&self.__denominator, (<Integer>denom_temp).value)
++            mpz_to_ZZ(&self._denominator, (<Integer>denom_temp).value)
+ 
+             # now the coefficients themselves.
+-            for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
++            for i from 0 <= i < ZZX_deg(self._fld_numerator.x):
+                 # calculate the new numerator. if our old entry is
+                 # p/q, and the lcm is k, it's just pk/q, which we
+                 # also know is integral -- so we can use mpz_divexact
+@@ -1006,7 +1006,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+                 # now set the coefficient of self
+                 mpz_to_ZZ(&ntl_temp, (<Integer>tmp_integer).value)
+ 
+-                ZZX_SetCoeff(self.__numerator, i, ntl_temp)
++                ZZX_SetCoeff(self._numerator, i, ntl_temp)
+ 
+         return 0  # No error
+ 
+@@ -1089,10 +1089,10 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: L.zero().sign()
+             0
+         """
+-        if ZZX_deg(self.__numerator) == -1:
++        if ZZX_deg(self._numerator) == -1:
+             return 0
+-        if ZZX_deg(self.__numerator) == 0:
+-            return ZZ_sign(ZZX_coeff(self.__numerator, 0))
++        if ZZX_deg(self._numerator) == 0:
++            return ZZ_sign(ZZX_coeff(self._numerator, 0))
+ 
+         if not (<number_field_base.NumberField> self._parent)._embedded_real:
+             raise TypeError("sign not well defined since no real embedding is specified")
+@@ -1153,12 +1153,12 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef RealIntervalFieldElement v
+ 
+ 
+-        if ZZX_deg(self.__numerator) <= 0:
++        if ZZX_deg(self._numerator) <= 0:
+             mpz_init(num)
+             mpz_init(den)
+ 
+-            ZZX_getitem_as_mpz(num, &self.__numerator, 0)
+-            ZZ_to_mpz(den, &self.__denominator)
++            ZZX_getitem_as_mpz(num, &self._numerator, 0)
++            ZZ_to_mpz(den, &self._denominator)
+ 
+             ans = PY_NEW(Integer)
+             mpz_fdiv_q(ans.value, num, den)
+@@ -1183,9 +1183,9 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         mpz_init(den)
+         mpfi_init2(a, mpfi_get_prec(v.value))
+ 
+-        ZZ_to_mpz(den, &self.__denominator)
++        ZZ_to_mpz(den, &self._denominator)
+ 
+-        ZZX_evaluation_mpfi(a, self.__numerator, v.value)
++        ZZX_evaluation_mpfi(a, self._numerator, v.value)
+         mpfi_div_z(a, a, den)
+ 
+         mpfr_floor(&a.left, &a.left)
+@@ -1197,7 +1197,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             v = <RealIntervalFieldElement> P._get_embedding_approx(i)
+ 
+             mpfi_set_prec(a, mpfi_get_prec(v.value))
+-            ZZX_evaluation_mpfi(a, self.__numerator, v.value)
++            ZZX_evaluation_mpfi(a, self._numerator, v.value)
+             mpfi_div_z(a, a, den)
+             mpfr_floor(&a.left ,&a.left)
+             mpfr_floor(&a.right, &a.right)
+@@ -1248,7 +1248,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             ...
+             TypeError: ceil not uniquely defined since no real embedding is specified
+         """
+-        if ZZX_deg(self.__numerator) <= 0:
++        if ZZX_deg(self._numerator) <= 0:
+             return self._rational_().ceil()
+ 
+         if not (<number_field_base.NumberField> self._parent)._embedded_real:
+@@ -1311,7 +1311,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             ...
+             TypeError: floor not uniquely defined since no real embedding is specified
+         """
+-        if ZZX_deg(self.__numerator) <= 0:
++        if ZZX_deg(self._numerator) <= 0:
+             return self._rational_().round()
+ 
+         return (self + QQ((1,2))).floor()
+@@ -2483,17 +2483,17 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef ZZ_c gcd
+         cdef ZZ_c t1
+         cdef ZZX_c t2
+-        if ZZ_IsOne(self.__denominator):
++        if ZZ_IsOne(self._denominator):
+             return
+-        ZZX_content(t1, self.__numerator)
+-        ZZ_GCD(gcd, t1, self.__denominator)
+-        if ZZ_sign(gcd) != ZZ_sign(self.__denominator):
++        ZZX_content(t1, self._numerator)
++        ZZ_GCD(gcd, t1, self._denominator)
++        if ZZ_sign(gcd) != ZZ_sign(self._denominator):
+             ZZ_negate(t1, gcd)
+             gcd = t1
+-        ZZX_div_ZZ(t2, self.__numerator, gcd)
+-        ZZ_div(t1, self.__denominator, gcd)
+-        self.__numerator = t2
+-        self.__denominator = t1
++        ZZX_div_ZZ(t2, self._numerator, gcd)
++        ZZ_div(t1, self._denominator, gcd)
++        self._numerator = t2
++        self._denominator = t1
+ 
+     cpdef _add_(self, right):
+         r"""
+@@ -2509,15 +2509,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef NumberFieldElement _right = right
+         cdef ZZ_c g, q1, q2
+         x = self._new()
+-        ZZ_GCD(g, self.__denominator, _right.__denominator)
+-        ZZ_div(q1, self.__denominator, g)
+-        ZZ_div(q2, _right.__denominator, g)
+-        ZZ_mul(x.__denominator, q1, q2)
+-        ZZ_mul(x.__denominator, x.__denominator, g)
++        ZZ_GCD(g, self._denominator, _right._denominator)
++        ZZ_div(q1, self._denominator, g)
++        ZZ_div(q2, _right._denominator, g)
++        ZZ_mul(x._denominator, q1, q2)
++        ZZ_mul(x._denominator, x._denominator, g)
+         cdef ZZX_c t1, t2
+-        ZZX_mul_ZZ(t1, self.__numerator, q2)
+-        ZZX_mul_ZZ(t2, _right.__numerator, q1)
+-        ZZX_add(x.__numerator, t1, t2)
++        ZZX_mul_ZZ(t1, self._numerator, q2)
++        ZZX_mul_ZZ(t2, _right._numerator, q1)
++        ZZX_add(x._numerator, t1, t2)
+         x._reduce_c_()
+         return x
+ 
+@@ -2534,15 +2534,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef NumberFieldElement _right = right
+         cdef ZZ_c g, q1, q2
+         x = self._new()
+-        ZZ_GCD(g, self.__denominator, _right.__denominator)
+-        ZZ_div(q1, self.__denominator, g)
+-        ZZ_div(q2, _right.__denominator, g)
+-        ZZ_mul(x.__denominator, q1, q2)
+-        ZZ_mul(x.__denominator, x.__denominator, g)
++        ZZ_GCD(g, self._denominator, _right._denominator)
++        ZZ_div(q1, self._denominator, g)
++        ZZ_div(q2, _right._denominator, g)
++        ZZ_mul(x._denominator, q1, q2)
++        ZZ_mul(x._denominator, x._denominator, g)
+         cdef ZZX_c t1, t2
+-        ZZX_mul_ZZ(t1, self.__numerator, q2)
+-        ZZX_mul_ZZ(t2, _right.__numerator, q1)
+-        ZZX_sub(x.__numerator, t1, t2)
++        ZZX_mul_ZZ(t1, self._numerator, q2)
++        ZZX_mul_ZZ(t2, _right._numerator, q1)
++        ZZX_sub(x._numerator, t1, t2)
+         x._reduce_c_()
+         return x
+ 
+@@ -2571,18 +2571,18 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         sig_on()
+         # MulMod doesn't handle non-monic polynomials.
+         # Therefore, we handle the non-monic case entirely separately.
+-        ZZ_mul(x.__denominator, self.__denominator, _right.__denominator)
+-        if ZZ_IsOne(ZZX_LeadCoeff(self.__fld_numerator.x)):
+-            ZZX_MulMod(x.__numerator, self.__numerator, _right.__numerator, self.__fld_numerator.x)
++        ZZ_mul(x._denominator, self._denominator, _right._denominator)
++        if ZZ_IsOne(ZZX_LeadCoeff(self._fld_numerator.x)):
++            ZZX_MulMod(x._numerator, self._numerator, _right._numerator, self._fld_numerator.x)
+         else:
+-            ZZX_mul(x.__numerator, self.__numerator, _right.__numerator)
+-            if ZZX_deg(x.__numerator) >= ZZX_deg(self.__fld_numerator.x):
+-                ZZX_mul_ZZ( x.__numerator, x.__numerator, self.__fld_denominator.x )
+-                ZZX_mul_ZZ( temp, self.__fld_numerator.x, x.__denominator )
+-                ZZ_power(temp1,ZZX_LeadCoeff(temp),ZZX_deg(x.__numerator)-ZZX_deg(self.__fld_numerator.x)+1)
+-                ZZX_PseudoRem(x.__numerator, x.__numerator, temp)
+-                ZZ_mul(x.__denominator, x.__denominator, self.__fld_denominator.x)
+-                ZZ_mul(x.__denominator, x.__denominator, temp1)
++            ZZX_mul(x._numerator, self._numerator, _right._numerator)
++            if ZZX_deg(x._numerator) >= ZZX_deg(self._fld_numerator.x):
++                ZZX_mul_ZZ( x._numerator, x._numerator, self._fld_denominator.x )
++                ZZX_mul_ZZ( temp, self._fld_numerator.x, x._denominator )
++                ZZ_power(temp1,ZZX_LeadCoeff(temp),ZZX_deg(x._numerator)-ZZX_deg(self._fld_numerator.x)+1)
++                ZZX_PseudoRem(x._numerator, x._numerator, temp)
++                ZZ_mul(x._denominator, x._denominator, self._fld_denominator.x)
++                ZZ_mul(x._denominator, x._denominator, temp1)
+         sig_off()
+         x._reduce_c_()
+         return x
+@@ -2704,7 +2704,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: bool(b + 1)
+             True
+         """
+-        return not IsZero_ZZX(self.__numerator)
++        return not IsZero_ZZX(self._numerator)
+ 
+     cpdef _neg_(self):
+         r"""
+@@ -2717,8 +2717,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         """
+         cdef NumberFieldElement x
+         x = self._new()
+-        ZZX_mul_long(x.__numerator, self.__numerator, -1)
+-        x.__denominator = self.__denominator
++        ZZX_mul_long(x._numerator, self._numerator, -1)
++        x._denominator = self._denominator
+         return x
+ 
+     cpdef _copy_for_parent(self, Parent parent):
+@@ -2738,8 +2738,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         """
+         cdef NumberFieldElement x
+         x = self._new()
+-        x.__numerator = self.__numerator
+-        x.__denominator = self.__denominator
++        x._numerator = self._numerator
++        x._denominator = self._denominator
+         x._set_parent(parent)
+         return x
+ 
+@@ -2826,7 +2826,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: L.<a> = K.extension(f)
+             sage: alpha = (a^8 + (zeta22^9 - zeta22^6 + 2*zeta22^4 + 33)*a^7)/(10**2555) #long time
+         """
+-        if IsZero_ZZX(self.__numerator):
++        if IsZero_ZZX(self._numerator):
+             raise ZeroDivisionError("number field element division by zero")
+         cdef NumberFieldElement x
+         cdef ZZX_c temp
+@@ -2835,8 +2835,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             # but may fail if NTL runs out of FFT primes.
+             x = self._new()
+             sig_on()
+-            ZZX_XGCD(x.__denominator, x.__numerator, temp, self.__numerator, self.__fld_numerator.x, 1)
+-            ZZX_mul_ZZ(x.__numerator, x.__numerator, self.__denominator)
++            ZZX_XGCD(x._denominator, x._numerator, temp, self._numerator, self._fld_numerator.x, 1)
++            ZZX_mul_ZZ(x._numerator, x._numerator, self._denominator)
+             x._reduce_c_()
+             sig_off()
+         except NTLError:
+@@ -2858,7 +2858,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: (2*I*I)._integer_()
+             -2
+         """
+-        if ZZX_deg(self.__numerator) >= 1:
++        if ZZX_deg(self._numerator) >= 1:
+             raise TypeError("Unable to coerce %s to an integer" % self)
+         return ZZ(self._rational_())
+ 
+@@ -2877,12 +2877,12 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: (I*I/2)._rational_()
+             -1/2
+         """
+-        if ZZX_deg(self.__numerator) >= 1:
++        if ZZX_deg(self._numerator) >= 1:
+             raise TypeError("Unable to coerce %s to a rational"%self)
+         cdef Integer num = Integer.__new__(Integer)
+-        ZZX_getitem_as_mpz(num.value, &self.__numerator, 0)
++        ZZX_getitem_as_mpz(num.value, &self._numerator, 0)
+         cdef Integer den = Integer.__new__(Integer)
+-        ZZ_to_mpz(den.value, &self.__denominator)
++        ZZ_to_mpz(den.value, &self._denominator)
+         return num / den
+ 
+     def _algebraic_(self, parent):
+@@ -3268,15 +3268,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef mpz_t z
+ 
+         mpz_init(z)
+-        ZZX_getitem_as_mpz(z, &self.__numerator, 0)
++        ZZX_getitem_as_mpz(z, &self._numerator, 0)
+         h = mpz_pythonhash(z)
+ 
+-        for i from 1 <= i <= ZZX_deg(self.__numerator):
+-            ZZX_getitem_as_mpz(z, &self.__numerator, i)
++        for i from 1 <= i <= ZZX_deg(self._numerator):
++            ZZX_getitem_as_mpz(z, &self._numerator, i)
+             # magic number below is floor(2^63 / (2+sqrt(2)))
+             h ^= mpz_pythonhash(z) + (<Py_hash_t> 2701463124188384701) + (h << 16) + (h >> 2)
+ 
+-        ZZ_to_mpz(z, &self.__denominator)
++        ZZ_to_mpz(z, &self._denominator)
+         # magic number below is floor((1+sqrt(5)) * 2^61)
+         h += (mpz_pythonhash(z) - 1) * (<Py_hash_t> 7461864723258187525)
+ 
+@@ -3305,12 +3305,12 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef int i
+         cdef mpz_t den
+         mpz_init(den)
+-        ZZ_to_mpz(den, &self.__denominator)
+-        cdef int size = ZZX_deg(self.__numerator) + 1
++        ZZ_to_mpz(den, &self._denominator)
++        cdef int size = ZZX_deg(self._numerator) + 1
+         cdef list coeffs = [None]*size
+         for i in range(size):
+             coeff = Rational.__new__(Rational)
+-            ZZX_getitem_as_mpz(mpq_numref(coeff.value), &self.__numerator, i)
++            ZZX_getitem_as_mpz(mpq_numref(coeff.value), &self._numerator, i)
+             mpz_set(mpq_denref(coeff.value), den)
+             mpq_canonicalize(coeff.value)
+             coeffs[i] = coeff
+@@ -3318,14 +3318,14 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         return coeffs
+ 
+     cdef void _ntl_coeff_as_mpz(self, mpz_t z, long i):
+-        if i > ZZX_deg(self.__numerator):
++        if i > ZZX_deg(self._numerator):
+             mpz_set_ui(z, 0)
+         else:
+-            ZZX_getitem_as_mpz(z, &self.__numerator, i)
++            ZZX_getitem_as_mpz(z, &self._numerator, i)
+ 
+     cdef void _ntl_denom_as_mpz(self, mpz_t z):
+         cdef Integer denom = Integer.__new__(Integer)
+-        ZZ_to_mpz(denom.value, &self.__denominator)
++        ZZ_to_mpz(denom.value, &self._denominator)
+         mpz_set(z, denom.value)
+ 
+     def denominator(self):
+@@ -3344,7 +3344,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             15
+         """
+         cdef Integer ans = Integer.__new__(Integer)
+-        ZZ_to_mpz(ans.value, &self.__denominator)
++        ZZ_to_mpz(ans.value, &self._denominator)
+         return ans
+ 
+     def _set_multiplicative_order(self, n):
+@@ -3474,8 +3474,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: a.is_one()
+             False
+         """
+-        return ZZX_IsOne(self.__numerator) == 1 and \
+-               ZZ_IsOne(self.__denominator) == 1
++        return ZZX_IsOne(self._numerator) == 1 and \
++               ZZ_IsOne(self._denominator) == 1
+ 
+     cpdef bint is_rational(self):
+         r"""
+@@ -3501,7 +3501,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: K(1/2).is_rational()
+             True
+         """
+-        return ZZX_deg(self.__numerator) <= 0
++        return ZZX_deg(self._numerator) <= 0
+ 
+     def is_integer(self):
+         r"""
+@@ -3527,7 +3527,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: K(1/2).is_integer()
+             False
+         """
+-        return ZZX_deg(self.__numerator) <= 0 and ZZ_IsOne(self.__denominator) == 1
++        return ZZX_deg(self._numerator) <= 0 and ZZ_IsOne(self._denominator) == 1
+ 
+     def trace(self, K=None):
+         r"""
+@@ -5322,8 +5322,8 @@ cdef class OrderElement_absolute(NumberFieldElement_absolute):
+         cdef OrderElement_absolute x = <OrderElement_absolute>t.__new__(t)
+         x._parent = self._parent
+         x._number_field = self._parent.number_field()
+-        x.__fld_numerator = self.__fld_numerator
+-        x.__fld_denominator = self.__fld_denominator
++        x._fld_numerator = self._fld_numerator
++        x._fld_denominator = self._fld_denominator
+         return x
+ 
+     cdef number_field(self):
+@@ -5443,8 +5443,8 @@ cdef class OrderElement_relative(NumberFieldElement_relative):
+         cdef OrderElement_relative x = <OrderElement_relative>t.__new__(t)
+         x._parent = self._parent
+         x._number_field = self._parent.number_field()
+-        x.__fld_numerator = self.__fld_numerator
+-        x.__fld_denominator = self.__fld_denominator
++        x._fld_numerator = self._fld_numerator
++        x._fld_denominator = self._fld_denominator
+         return x
+ 
+     def __invert__(self):
+diff --git a/src/sage/rings/number_field/number_field_element_quadratic.pyx b/src/sage/rings/number_field/number_field_element_quadratic.pyx
+index 0992e7cd527..c32f6aadd10 100644
+--- a/src/sage/rings/number_field/number_field_element_quadratic.pyx
++++ b/src/sage/rings/number_field/number_field_element_quadratic.pyx
+@@ -610,8 +610,8 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+         mpz_clear(tmp_mpz)
+ 
+         x._parent = <ParentWithBase>new_parent
+-        x.__fld_numerator, x.__fld_denominator = new_parent.polynomial_ntl()
+-        x.__denominator = elt_den
++        x._fld_numerator, x._fld_denominator = new_parent.polynomial_ntl()
++        x._denominator = elt_den
+         cdef ZZX_c result
+         cdef ZZ_c tmp
+         cdef int i
+@@ -621,7 +621,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+         for i from 0 <= i <= ZZX_deg(elt_num):
+             tmp = ZZX_coeff(elt_num, i)
+             ZZX_SetCoeff(result, i*rel, tmp)
+-        ZZX_rem(x.__numerator, result, _num.x)
++        ZZX_rem(x._numerator, result, _num.x)
+         (<NumberFieldElement_absolute>x)._reduce_c_()
+         return x
+ 
+@@ -1643,7 +1643,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+         return res
+ 
+ #################################################################################
+-# We must override everything that makes uses of self.__numerator/__denominator
++# We must override everything that makes uses of self._numerator/_denominator
+ #################################################################################
+ 
+     def __hash__(self):
+diff --git a/src/sage/rings/padics/CA_template.pxi b/src/sage/rings/padics/CA_template.pxi
+index a0a66c19621..d821b5c1576 100644
+--- a/src/sage/rings/padics/CA_template.pxi
++++ b/src/sage/rings/padics/CA_template.pxi
+@@ -1463,7 +1463,7 @@ cdef class pAdicCoercion_CA_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         ans._normalize()
+         return ans
+ 
+@@ -1516,7 +1516,7 @@ cdef class pAdicCoercion_CA_frac_field(RingHomomorphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+             pass
+         return ans
+ 
+@@ -1686,7 +1686,7 @@ cdef class pAdicConvert_CA_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 R = ans.value.base_ring()
+-                ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++                ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1741,7 +1741,7 @@ cdef class pAdicConvert_CA_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 R = ans.value.base_ring()
+-                ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++                ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/CR_template.pxi b/src/sage/rings/padics/CR_template.pxi
+index cb57bb2cb48..863c612587c 100644
+--- a/src/sage/rings/padics/CR_template.pxi
++++ b/src/sage/rings/padics/CR_template.pxi
+@@ -2184,7 +2184,7 @@ cdef class pAdicCoercion_CR_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -2241,7 +2241,7 @@ cdef class pAdicCoercion_CR_frac_field(RingHomomorphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     def section(self):
+@@ -2404,7 +2404,7 @@ cdef class pAdicConvert_CR_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -2463,7 +2463,7 @@ cdef class pAdicConvert_CR_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/FM_template.pxi b/src/sage/rings/padics/FM_template.pxi
+index ea7d4055660..f47200074ea 100644
+--- a/src/sage/rings/padics/FM_template.pxi
++++ b/src/sage/rings/padics/FM_template.pxi
+@@ -1227,7 +1227,7 @@ cdef class pAdicCoercion_FM_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1277,7 +1277,7 @@ cdef class pAdicCoercion_FM_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     def section(self):
+@@ -1435,7 +1435,7 @@ cdef class pAdicConvert_FM_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             R = ans.value.base_ring()
+-            ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++            ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1483,7 +1483,7 @@ cdef class pAdicConvert_FM_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             R = ans.value.base_ring()
+-            ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++            ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/FP_template.pxi b/src/sage/rings/padics/FP_template.pxi
+index 57ec619b278..c718c0a5f8d 100644
+--- a/src/sage/rings/padics/FP_template.pxi
++++ b/src/sage/rings/padics/FP_template.pxi
+@@ -1849,7 +1849,7 @@ cdef class pAdicCoercion_FP_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1903,7 +1903,7 @@ cdef class pAdicCoercion_FP_frac_field(RingHomomorphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     def section(self):
+@@ -2025,7 +2025,7 @@ cdef class pAdicConvert_FP_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -2081,7 +2081,7 @@ cdef class pAdicConvert_FP_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/pow_computer.pxd b/src/sage/rings/padics/pow_computer.pxd
+index 2a93e42254e..8766725882e 100644
+--- a/src/sage/rings/padics/pow_computer.pxd
++++ b/src/sage/rings/padics/pow_computer.pxd
+@@ -6,7 +6,7 @@ cdef class PowComputer_class(SageObject):
+     cdef Integer prime
+     cdef Integer p2 # floor(p/2)
+     cdef bint in_field
+-    cdef int __allocated
++    cdef int _allocated
+     cdef public object _prec_type
+ 
+     cdef long ram_prec_cap # = prec_cap * e
+diff --git a/src/sage/rings/padics/pow_computer.pyx b/src/sage/rings/padics/pow_computer.pyx
+index c2fa8031086..1c5bdf86897 100644
+--- a/src/sage/rings/padics/pow_computer.pyx
++++ b/src/sage/rings/padics/pow_computer.pyx
+@@ -65,7 +65,7 @@ cdef class PowComputer_class(SageObject):
+         sig_on()
+         mpz_init(self.temp_m)
+         sig_off()
+-        self.__allocated = 1
++        self._allocated = 1
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly=None, shift_seed=None):
+         """
+@@ -485,7 +485,7 @@ cdef class PowComputer_base(PowComputer_class):
+         finally:
+             sig_off()
+ 
+-        self.__allocated = 2
++        self._allocated = 2
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly=None, shift_seed=None):
+         """
+@@ -529,7 +529,7 @@ cdef class PowComputer_base(PowComputer_class):
+         """
+         cdef Py_ssize_t i
+ 
+-        if self.__allocated >= 2:
++        if self._allocated >= 2:
+             for i in range(self.cache_limit + 1):
+                 mpz_clear(self.small_powers[i])
+             mpz_clear(self.top_power)
+diff --git a/src/sage/rings/padics/pow_computer_flint.pyx b/src/sage/rings/padics/pow_computer_flint.pyx
+index 9f914defcc6..e521ea6e078 100644
+--- a/src/sage/rings/padics/pow_computer_flint.pyx
++++ b/src/sage/rings/padics/pow_computer_flint.pyx
+@@ -59,7 +59,7 @@ cdef class PowComputer_flint(PowComputer_class):
+         finally:
+             sig_off()
+ 
+-        self.__allocated = 4
++        self._allocated = 4
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly=None, shift_seed=None):
+         """
+@@ -87,7 +87,7 @@ cdef class PowComputer_flint(PowComputer_class):
+             sage: A = PowComputer_flint(5, 20, 20, 20, False)
+             sage: del A
+         """
+-        if self.__allocated >= 4:
++        if self._allocated >= 4:
+             fmpz_clear(self.fprime)
+             fmpz_clear(self.half_prime)
+             fmpz_clear(self._fpow_variable)
+@@ -208,7 +208,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+ 
+         """
+         cdef Polynomial_integer_dense_flint poly = _poly
+-        cdef long length = fmpz_poly_length(poly.__poly)
++        cdef long length = fmpz_poly_length(poly._poly)
+ 
+         cdef Py_ssize_t i
+ 
+@@ -251,7 +251,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         finally:
+             sig_off()
+ 
+-        self.__allocated = 8
++        self._allocated = 8
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, _poly, shift_seed=None):
+         """
+@@ -268,10 +268,10 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         PowComputer_flint.__init__(self, prime, cache_limit, prec_cap, ram_prec_cap, in_field, _poly, shift_seed)
+ 
+         cdef Polynomial_integer_dense_flint poly = _poly
+-        cdef long length = fmpz_poly_length(poly.__poly)
++        cdef long length = fmpz_poly_length(poly._poly)
+         self.deg = length - 1
+ 
+-        fmpz_poly_set(self.modulus, poly.__poly)
++        fmpz_poly_set(self.modulus, poly._poly)
+ 
+         cdef Py_ssize_t i
+         cdef fmpz* coeffs = self.modulus.coeffs
+@@ -296,7 +296,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         """
+         cdef Py_ssize_t i
+ 
+-        if self.__allocated >= 8:
++        if self._allocated >= 8:
+             fmpz_clear(self.q)
+             fmpz_poly_clear(self.modulus)
+             fmpz_poly_clear(self.powhelper_oneunit)
+@@ -427,9 +427,9 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         x = R.gen()
+         cdef Polynomial_integer_dense_flint ans = (<Polynomial_integer_dense_flint?>x)._new()
+         if _n is None:
+-            fmpz_poly_set(ans.__poly, self.modulus)
++            fmpz_poly_set(ans._poly, self.modulus)
+         else:
+-            fmpz_poly_set(ans.__poly, self.get_modulus(_n)[0])
++            fmpz_poly_set(ans._poly, self.get_modulus(_n)[0])
+         return ans
+ 
+     cdef _new_fmpz_poly(self, fmpz_poly_t value, var='x'):
+@@ -440,7 +440,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         R = ZZ[var]
+         x = R.gen()
+         cdef Polynomial_integer_dense_flint ans = (<Polynomial_integer_dense_flint?>x)._new()
+-        fmpz_poly_set(ans.__poly, value)
++        fmpz_poly_set(ans._poly, value)
+         return ans
+ 
+ cdef class PowComputer_flint_unram(PowComputer_flint_1step):
+@@ -501,7 +501,7 @@ cdef class PowComputer_flint_unram(PowComputer_flint_1step):
+         mpz_init(self.mpz_matmod)
+         sig_off()
+ 
+-        self.__allocated = 16
++        self._allocated = 16
+ 
+     def __dealloc__(self):
+         """
+@@ -515,7 +515,7 @@ cdef class PowComputer_flint_unram(PowComputer_flint_1step):
+             sage: del A
+ 
+         """
+-        if self.__allocated >= 16:
++        if self._allocated >= 16:
+             fmpz_clear(self.fmpz_ccmp)
+             fmpz_clear(self.fmpz_cval)
+             fmpz_clear(self.fmpz_cinv)
+diff --git a/src/sage/rings/padics/pow_computer_relative.pxd b/src/sage/rings/padics/pow_computer_relative.pxd
+index fc7d5b21f42..e0e5aa5600e 100644
+--- a/src/sage/rings/padics/pow_computer_relative.pxd
++++ b/src/sage/rings/padics/pow_computer_relative.pxd
+@@ -18,7 +18,7 @@ cdef class PowComputer_relative(PowComputer_class):
+     cdef Polynomial_generic_dense shift_rem
+     cdef Polynomial_generic_dense aliasing
+     # allow cached methods
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+     cdef unsigned long capdiv(self, unsigned long n)
+ 
+diff --git a/src/sage/rings/padics/pow_computer_relative.pyx b/src/sage/rings/padics/pow_computer_relative.pyx
+index 39051a681de..2253281bd35 100644
+--- a/src/sage/rings/padics/pow_computer_relative.pyx
++++ b/src/sage/rings/padics/pow_computer_relative.pyx
+@@ -69,7 +69,7 @@ cdef class PowComputer_relative(PowComputer_class):
+             sage: PC = PowComputer_relative_maker(3, 20, 20, 60, False, f, shift_seed, 'fixed-mod')
+ 
+         """
+-        self.__allocated = 4
++        self._allocated = 4
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly, shift_seed):
+         r"""
+diff --git a/src/sage/rings/polynomial/hilbert.pyx b/src/sage/rings/polynomial/hilbert.pyx
+index a1f70e0c983..d2abf325fd8 100644
+--- a/src/sage/rings/polynomial/hilbert.pyx
++++ b/src/sage/rings/polynomial/hilbert.pyx
+@@ -170,7 +170,7 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+     cdef int e
+     # First, the easiest cases:
+     if not D.Id: # The zero ideal
+-        fmpz_poly_set_coeff_si(fhs.__poly, 0, 1) # = PR(1)
++        fmpz_poly_set_coeff_si(fhs._poly, 0, 1) # = PR(1)
+         return True
+     cdef ETuple m = <ETuple>PyList_GET_ITEM(D.Id, len(D.Id)-1)
+     if m._nonzero == 0: # The one ideal
+@@ -183,18 +183,18 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+     if m._nonzero == 1 and m._data[1] == 1:
+         fmpz_poly_init(poly_tmp)
+         fmpz_poly_set_coeff_si(poly_tmp, 0, 1)
+-        fmpz_poly_set_coeff_si(fhs.__poly, 0, 1) # = PR(1)
++        fmpz_poly_set_coeff_si(fhs._poly, 0, 1) # = PR(1)
+         if w is None:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).unweighted_degree()
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         else:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).weighted_degree(w)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         fmpz_poly_clear(poly_tmp)
+         return True # PR.prod([(1-t**degree(m,w)) for m in D.Id])
+@@ -210,18 +210,18 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+         # The ideal is generated by some powers of single variables, i.e., it splits.
+         fmpz_poly_init(poly_tmp)
+         fmpz_poly_set_coeff_si(poly_tmp, 0, 1)
+-        fmpz_poly_set_coeff_si(fhs.__poly, 0, 1) # = PR(1)
++        fmpz_poly_set_coeff_si(fhs._poly, 0, 1) # = PR(1)
+         if w is None:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).unweighted_degree()
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         else:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).weighted_degree(w)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         fmpz_poly_clear(poly_tmp)
+         return True # PR.prod([(1-t**degree(m,w)) for m in D.Id])
+@@ -278,8 +278,8 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+                     fmpz_poly_mul(SecondSummand, SecondSummand, poly_tmp)
+                     fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         fmpz_poly_clear(poly_tmp)
+-        fmpz_poly_add(fhs.__poly, fhs.__poly, FirstSummand)
+-        fmpz_poly_add(fhs.__poly, fhs.__poly, SecondSummand)
++        fmpz_poly_add(fhs._poly, fhs._poly, FirstSummand)
++        fmpz_poly_add(fhs._poly, fhs._poly, SecondSummand)
+         fmpz_poly_clear(FirstSummand)
+         fmpz_poly_clear(SecondSummand)
+         return True
+@@ -532,11 +532,11 @@ def first_hilbert_series(I, grading=None, return_grading=False):
+                 if AN.Back.Right is None:
+                     AN = AN.Back
+                     #~ fhs *= AN.LMult
+-                    fmpz_poly_mul(fhs.__poly, fhs.__poly, AN.LMult)
++                    fmpz_poly_mul(fhs._poly, fhs._poly, AN.LMult)
+                     got_result = True
+                 else:
+-                    fmpz_poly_set(AN.Back.LeftFHS, fhs.__poly)
+-                    fmpz_poly_set_si(fhs.__poly, 0)
++                    fmpz_poly_set(AN.Back.LeftFHS, fhs._poly)
++                    fmpz_poly_set_si(fhs._poly, 0)
+                     AN = AN.Back.Right
+                     AN.Back.Left = None
+                     got_result = HilbertBaseCase(fhs, AN, w)
+@@ -545,8 +545,8 @@ def first_hilbert_series(I, grading=None, return_grading=False):
+                 AN.Right = None
+                 #~ fhs = AN.LMult*AN.LeftFHS + AN.RMult*fhs
+                 fmpz_poly_mul(AN.LMult, AN.LMult, AN.LeftFHS)
+-                fmpz_poly_mul(AN.RMult, AN.RMult, fhs.__poly)
+-                fmpz_poly_add(fhs.__poly, AN.LMult, AN.RMult)
++                fmpz_poly_mul(AN.RMult, AN.RMult, fhs._poly)
++                fmpz_poly_add(fhs._poly, AN.LMult, AN.RMult)
+                 got_result = True
+ 
+ def hilbert_poincare_series(I, grading=None):
+diff --git a/src/sage/rings/polynomial/laurent_polynomial.pxd b/src/sage/rings/polynomial/laurent_polynomial.pxd
+index 3648d6d1ed1..8e9107aeb47 100644
+--- a/src/sage/rings/polynomial/laurent_polynomial.pxd
++++ b/src/sage/rings/polynomial/laurent_polynomial.pxd
+@@ -12,6 +12,6 @@ cdef class LaurentPolynomial(CommutativeAlgebraElement):
+ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+     cdef ModuleElement __u
+     cdef long __n
+-    cpdef __normalize(self)
++    cpdef _normalize(self)
+     cpdef _unsafe_mutate(self, i, value)
+ 
+diff --git a/src/sage/rings/polynomial/laurent_polynomial.pyx b/src/sage/rings/polynomial/laurent_polynomial.pyx
+index 4be246c6688..cd79996eed7 100644
+--- a/src/sage/rings/polynomial/laurent_polynomial.pyx
++++ b/src/sage/rings/polynomial/laurent_polynomial.pyx
+@@ -366,7 +366,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         # self is that t^n * u:
+         self.__u = f
+         self.__n = n
+-        self.__normalize()
++        self._normalize()
+ 
+     def __reduce__(self):
+         """
+@@ -531,7 +531,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+             u = u.map_coefficients(base_map)
+         return codomain(u(x) * x**self.__n)
+ 
+-    cpdef __normalize(self):
++    cpdef _normalize(self):
+         r"""
+         A Laurent series is a pair `(u(t), n)`, where either `u = 0`
+         (to some precision) or `u` is a unit. This pair corresponds to
+@@ -763,7 +763,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+             ret = <LaurentPolynomial_univariate> self._new_c()
+             ret.__u = f
+             ret.__n = self.__n
+-            ret.__normalize()
++            ret._normalize()
+             return ret
+ 
+         return self.__u[i - self.__n]
+@@ -919,7 +919,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+                 R = self._parent.base_ring()
+                 coeffs = [value] + [R.zero() for _ in range(1,-j)] + self.__u.list()
+                 self.__u = self.__u._parent(coeffs)
+-        self.__normalize()
++        self._normalize()
+ 
+     cpdef _add_(self, right_m):
+         """
+@@ -972,7 +972,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (f1 + f2)
+         ret.__n = m
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     cpdef _sub_(self, right_m):
+@@ -1012,7 +1012,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (f1 - f2)
+         ret.__n = m
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def degree(self):
+@@ -1063,7 +1063,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (self.__u * right.__u)
+         ret.__n = self.__n + right.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     cpdef _rmul_(self, Element c):
+@@ -1079,7 +1079,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self.__u._rmul_(c)
+         ret.__n = self.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     cpdef _lmul_(self, Element c):
+@@ -1095,7 +1095,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self.__u._lmul_(c)
+         ret.__n = self.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def is_monomial(self):
+@@ -1175,7 +1175,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (self.__u // right.__u)
+         ret.__n = self.__n - right.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def shift(self, k):
+@@ -1287,7 +1287,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+             if self.__u.is_unit():
+                 ret.__u = self.__u.inverse_of_unit()
+                 ret.__n = -self.__n
+-                ret.__normalize()
++                ret._normalize()
+                 return ret
+             # Enlarge the ring so we can divide by the coefficient
+             R = self._parent.base_ring().fraction_field()
+@@ -1362,7 +1362,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = self.__u.gcd(b.__u)
+         ret.__n = min(self.__n, b.__n)
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     @coerce_binop
+@@ -1408,11 +1408,11 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ql = <LaurentPolynomial_univariate> self._new_c()
+         ql.__u = <ModuleElement> q
+         ql.__n = self.__n - right.__n
+-        ql.__normalize()
++        ql._normalize()
+         qr = <LaurentPolynomial_univariate> self._new_c()
+         qr.__u = <ModuleElement> r
+         qr.__n = self.__n
+-        qr.__normalize()
++        qr._normalize()
+         return ql, qr
+ 
+     cpdef _richcmp_(self, right_r, int op):
+@@ -1519,7 +1519,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self.__u.truncate(n - self.__n)
+         ret.__n = self.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def variable_name(self):
+@@ -1777,7 +1777,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+                 ret = <LaurentPolynomial_univariate> self._new_c()
+                 ret.__u = <ModuleElement> self._parent._R(u)
+                 ret.__n = self.__n
+-                ret.__normalize()
++                ret._normalize()
+                 return ret
+             except AttributeError:
+                 raise ValueError('cannot differentiate with respect to {}'.format(var))
+@@ -1792,7 +1792,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self._parent._R(a)
+         ret.__n = self.__n - 1
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def integral(self):
+@@ -1857,7 +1857,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> u
+         ret.__n = n + 1
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def __call__(self, *x, **kwds):
+@@ -1919,14 +1919,14 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         u = <LaurentPolynomial_univariate> self._new_c()
+         u.__u = pf.unit()
+         u.__n = self.__n
+-        u.__normalize()
++        u._normalize()
+ 
+         f = []
+         for t in pf:
+             d = <LaurentPolynomial_univariate> self._new_c()
+             d.__u = t[0]
+             d.__n = 0
+-            d.__normalize()
++            d._normalize()
+             if d.is_unit():
+                 u *= d ** t[1]
+             else:
+diff --git a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx
+index d796b7f8169..83c79c39843 100644
+--- a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx
++++ b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx
+@@ -375,7 +375,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+             ...
+             NotImplementedError: polynomials in -1 variables are not supported in Singular
+         """
+-        self.__ngens = n
++        self._ngens = n
+         self._ring = singular_ring_new(base_ring, n, names, order)
+         self._zero_element = new_MP(self, NULL)
+         cdef MPolynomial_libsingular one = new_MP(self, p_ISet(1, self._ring))
+@@ -1019,7 +1019,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+             Multivariate Polynomial Ring in x, y over Rational Field
+         """
+         varstr = ", ".join(char_to_str(rRingVar(i,self._ring))
+-                           for i in range(self.__ngens))
++                           for i in range(self._ngens))
+         return "Multivariate Polynomial Ring in %s over %s" % (varstr, self.base_ring())
+ 
+     def ngens(self):
+@@ -1037,7 +1037,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+             sage: P.ngens()                                                             # needs sage.rings.finite_rings
+             1000
+         """
+-        return int(self.__ngens)
++        return int(self._ngens)
+ 
+     def gen(self, int n=0):
+         """
+@@ -1065,7 +1065,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+         cdef poly *_p
+         cdef ring *_ring = self._ring
+ 
+-        if n < 0 or n >= self.__ngens:
++        if n < 0 or n >= self._ngens:
+             raise ValueError("Generator not defined.")
+ 
+         rChangeCurrRing(_ring)
+@@ -1494,7 +1494,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+         return unpickle_MPolynomialRing_libsingular, \
+             (self.base_ring(), self.variable_names(), self.term_order())
+ 
+-    def __temporarily_change_names(self, names, latex_names):
++    def _temporarily_change_names(self, names, latex_names):
+         """
+         This is used by the variable names context manager.
+ 
+diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd b/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd
+index fc81cf6d298..eb6f8b70917 100644
+--- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd
++++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd
+@@ -2,8 +2,8 @@ cimport sage.rings.ring
+ from sage.structure.parent cimport Parent
+ 
+ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+-    cdef object __ngens
+-    cdef object __term_order
++    cdef object _ngens
++    cdef object _term_order
+     cdef public object _has_singular
+     cdef public object _magma_gens
+     cdef public dict _magma_cache
+diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx
+index 1d3fbc60944..c8f66508cc2 100644
+--- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx
++++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx
+@@ -80,8 +80,8 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+             raise ValueError("Multivariate Polynomial Rings must "
+                              "have more than 0 variables.")
+         order = TermOrder(order, n)
+-        self.__ngens = n
+-        self.__term_order = order
++        self._ngens = n
++        self._term_order = order
+         self._has_singular = False  # cannot convert to Singular by default
+         self._magma_cache = {}
+         # Ring.__init__ already does assign the names.
+@@ -639,12 +639,12 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         lft = <MPolynomialRing_base>left
+         other = <MPolynomialRing_base>right
+ 
+-        lx = (lft.base_ring(), lft.__ngens,
++        lx = (lft.base_ring(), lft._ngens,
+               lft.variable_names(),
+-              lft.__term_order)
+-        rx = (other.base_ring(), other.__ngens,
++              lft._term_order)
++        rx = (other.base_ring(), other._ngens,
+               other.variable_names(),
+-              other.__term_order)
++              other._term_order)
+         return richcmp(lx, rx, op)
+ 
+     def _repr_(self):
+@@ -849,7 +849,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         return False
+ 
+     def term_order(self):
+-        return self.__term_order
++        return self._term_order
+ 
+     def characteristic(self):
+         """
+@@ -867,7 +867,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         return self.base_ring().characteristic()
+ 
+     def gen(self, n=0):
+-        if n < 0 or n >= self.__ngens:
++        if n < 0 or n >= self._ngens:
+             raise ValueError("Generator not defined.")
+         return self._gens[int(n)]
+ 
+@@ -927,7 +927,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         return self.base_ring().krull_dimension() + self.ngens()
+ 
+     def ngens(self):
+-        return self.__ngens
++        return self._ngens
+ 
+     def _monomial_order_function(self):
+         raise NotImplementedError
+diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pxd b/src/sage/rings/polynomial/ore_polynomial_element.pxd
+index 3a3fe0a0d54..aa36112ab90 100644
+--- a/src/sage/rings/polynomial/ore_polynomial_element.pxd
++++ b/src/sage/rings/polynomial/ore_polynomial_element.pxd
+@@ -33,7 +33,7 @@ cdef void lmul_gen(list A, Morphism m, d)
+ cdef class OrePolynomial_generic_dense(OrePolynomial):
+     cdef list _coeffs
+ 
+-    cdef void __normalize(self)
++    cdef void _normalize(self)
+     cpdef _add_(self, other)
+     cdef list _mul_list(self, list A)
+     cpdef _mul_(self, other)
+diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pyx b/src/sage/rings/polynomial/ore_polynomial_element.pyx
+index d67c63b6be8..be154ba8b1a 100644
+--- a/src/sage/rings/polynomial/ore_polynomial_element.pyx
++++ b/src/sage/rings/polynomial/ore_polynomial_element.pyx
+@@ -2269,7 +2269,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+         if isinstance(x, list):
+             if check:
+                 self._coeffs = [R(t) for t in x]
+-                self.__normalize()
++                self._normalize()
+             else:
+                 self._coeffs = x
+             return
+@@ -2288,7 +2288,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+             else:
+                 self._coeffs = [R(a, **kwds) for a in x.list()]
+                 if check:
+-                    self.__normalize()
++                    self._normalize()
+                 return
+ 
+         elif isinstance(x, int) and x == 0:
+@@ -2302,7 +2302,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+             x = [x]
+         if check:
+             self._coeffs = [R(z, **kwds) for z in x]
+-            self.__normalize()
++            self._normalize()
+         else:
+             self._coeffs = x
+ 
+@@ -2377,10 +2377,10 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+         f._parent = P
+         f._coeffs = coeffs
+         if check:
+-            f.__normalize()
++            f._normalize()
+         return f
+ 
+-    cdef void __normalize(self):
++    cdef void _normalize(self):
+         r"""
+         Remove higher order `0`-coefficients from the representation of ``self``.
+ 
+diff --git a/src/sage/rings/polynomial/pbori/pbori.pyx b/src/sage/rings/polynomial/pbori/pbori.pyx
+index 07cc696477a..314196faa14 100644
+--- a/src/sage/rings/polynomial/pbori/pbori.pyx
++++ b/src/sage/rings/polynomial/pbori/pbori.pyx
+@@ -547,7 +547,7 @@ cdef class BooleanPolynomialRing(BooleanPolynomialRing_base):
+         """
+         return tuple(new_BP_from_PBVar(self,
+                                        self._pbring.variable(self.pbind[i]))
+-                     for i in range(self.__ngens))
++                     for i in range(self._ngens))
+ 
+     def change_ring(self, base_ring=None, names=None, order=None):
+         """
+diff --git a/src/sage/rings/polynomial/plural.pxd b/src/sage/rings/polynomial/plural.pxd
+index 41db2a144e7..d3a46f6aa0d 100644
+--- a/src/sage/rings/polynomial/plural.pxd
++++ b/src/sage/rings/polynomial/plural.pxd
+@@ -13,10 +13,10 @@ cdef extern from *:
+     ctypedef long Py_hash_t
+ 
+ cdef class NCPolynomialRing_plural(Ring):
+-    cdef object __ngens
++    cdef object _ngens
+     cdef object _c
+     cdef object _d
+-    cdef object __term_order
++    cdef object _term_order
+     cdef public object _has_singular
+     cdef public object _magma_gens, _magma_cache
+ 
+diff --git a/src/sage/rings/polynomial/plural.pyx b/src/sage/rings/polynomial/plural.pyx
+index a647d68e08d..bc432611c89 100644
+--- a/src/sage/rings/polynomial/plural.pyx
++++ b/src/sage/rings/polynomial/plural.pyx
+@@ -336,8 +336,8 @@ cdef class NCPolynomialRing_plural(Ring):
+         self._ring = singular_ring_reference(rw._ring)
+         self._ring.ShortOut = 0
+ 
+-        self.__ngens = n
+-        self.__term_order = order
++        self._ngens = n
++        self._term_order = order
+ 
+         Ring.__init__(self, base_ring, names, category=category)
+         self._populate_coercion_lists_()
+@@ -673,7 +673,7 @@ cdef class NCPolynomialRing_plural(Ring):
+             sage: P.term_order()
+             Degree reverse lexicographic term order
+         """
+-        return self.__term_order
++        return self._term_order
+ 
+     def is_commutative(self):
+         """
+@@ -727,7 +727,7 @@ cdef class NCPolynomialRing_plural(Ring):
+         from sage.repl.rich_output.backend_base import BackendBase
+         from sage.repl.display.pretty_print import SagePrettyPrinter
+         varstr = ", ".join(char_to_str(rRingVar(i, self._ring))
+-                           for i in range(self.__ngens))
++                           for i in range(self._ngens))
+         backend = BackendBase()
+         relations = backend._apply_pretty_printer(SagePrettyPrinter,
+                                                   self.relations())
+@@ -830,7 +830,7 @@ cdef class NCPolynomialRing_plural(Ring):
+             sage: P.ngens()
+             3
+         """
+-        return int(self.__ngens)
++        return int(self._ngens)
+ 
+     def gen(self, int n=0):
+         """
+@@ -857,7 +857,7 @@ cdef class NCPolynomialRing_plural(Ring):
+         cdef poly *_p
+         cdef ring *_ring = self._ring
+ 
+-        if n < 0 or n >= self.__ngens:
++        if n < 0 or n >= self._ngens:
+             raise ValueError("Generator not defined.")
+ 
+         rChangeCurrRing(_ring)
+@@ -2352,7 +2352,7 @@ cdef class NCPolynomial_plural(RingElement):
+             except TypeError:
+                 x = (x,)
+ 
+-        if len(x) != (<NCPolynomialRing_plural>self._parent).__ngens:
++        if len(x) != (<NCPolynomialRing_plural>self._parent)._ngens:
+             raise TypeError("x must have length self.ngens()")
+ 
+         m = p_ISet(1,r)
+@@ -2890,8 +2890,8 @@ cpdef MPolynomialRing_libsingular new_CRing(RingWrap rw, base_ring):
+ 
+     self._ring.ShortOut = 0
+ 
+-    self.__ngens = rw.ngens()
+-    self.__term_order =  TermOrder(rw.ordering_string(), force=True)
++    self._ngens = rw.ngens()
++    self._term_order =  TermOrder(rw.ordering_string(), force=True)
+ 
+     ParentWithGens.__init__(self, base_ring, tuple(rw.var_names()),
+                             normalize=False)
+@@ -2962,8 +2962,8 @@ cpdef NCPolynomialRing_plural new_NRing(RingWrap rw, base_ring):
+ 
+     self._ring.ShortOut = 0
+ 
+-    self.__ngens = rw.ngens()
+-    self.__term_order =  TermOrder(rw.ordering_string(), force=True)
++    self._ngens = rw.ngens()
++    self._term_order =  TermOrder(rw.ordering_string(), force=True)
+ 
+     ParentWithGens.__init__(self, base_ring, rw.var_names())
+ #    self._populate_coercion_lists_()  # ???
+diff --git a/src/sage/rings/polynomial/polynomial_complex_arb.pxd b/src/sage/rings/polynomial/polynomial_complex_arb.pxd
+index aa4e2a1c0dc..e54d85e961b 100644
+--- a/src/sage/rings/polynomial/polynomial_complex_arb.pxd
++++ b/src/sage/rings/polynomial/polynomial_complex_arb.pxd
+@@ -2,5 +2,5 @@ from sage.libs.arb.acb_poly cimport *
+ from sage.rings.polynomial.polynomial_element cimport Polynomial
+ 
+ cdef class Polynomial_complex_arb(Polynomial):
+-    cdef acb_poly_struct[1] __poly # https://github.com/cython/cython/issues/1984
++    cdef acb_poly_struct[1] _poly # https://github.com/cython/cython/issues/1984
+     cdef Polynomial_complex_arb _new(self)
+diff --git a/src/sage/rings/polynomial/polynomial_complex_arb.pyx b/src/sage/rings/polynomial/polynomial_complex_arb.pyx
+index e51268b4b54..57c1a52ede4 100644
+--- a/src/sage/rings/polynomial/polynomial_complex_arb.pyx
++++ b/src/sage/rings/polynomial/polynomial_complex_arb.pyx
+@@ -75,7 +75,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: ComplexBallField(2)['y']()
+             0
+         """
+-        acb_poly_init(self.__poly)
++        acb_poly_init(self._poly)
+ 
+     def __dealloc__(self):
+         r"""
+@@ -84,7 +84,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: pol = CBF['x']()
+             sage: del pol
+         """
+-        acb_poly_clear(self.__poly)
++        acb_poly_clear(self._poly)
+ 
+     cdef Polynomial_complex_arb _new(self):
+         r"""
+@@ -140,49 +140,49 @@ cdef class Polynomial_complex_arb(Polynomial):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+ 
+         if is_gen:
+-            acb_poly_set_coeff_si(self.__poly, 1, 1)
++            acb_poly_set_coeff_si(self._poly, 1, 1)
+         elif x is None:
+-            acb_poly_zero(self.__poly)
++            acb_poly_zero(self._poly)
+         elif isinstance(x, Polynomial_complex_arb):
+-            acb_poly_set(self.__poly, (<Polynomial_complex_arb> x).__poly)
++            acb_poly_set(self._poly, (<Polynomial_complex_arb> x)._poly)
+         elif isinstance(x, ComplexBall):
+-            acb_poly_set_coeff_acb(self.__poly, 0, (<ComplexBall> x).value)
++            acb_poly_set_coeff_acb(self._poly, 0, (<ComplexBall> x).value)
+         else:
+             Coeff = parent.base_ring()
+             if isinstance(x, list):
+                 lst = <list> x
+                 length = len(lst)
+-                sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                 for i in range(length):
+                     ball = Coeff(lst[i])
+-                    acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                    acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             elif isinstance(x, tuple):
+                 tpl = <tuple> x
+                 length = len(tpl)
+-                sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                 for i in range(length):
+                     ball = Coeff(tpl[i])
+-                    acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                    acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             elif isinstance(x, Polynomial):
+                 pol = <Polynomial> x
+                 length = pol.degree() + 1
+-                sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                 for i in range(length):
+                     ball = Coeff(pol.get_unsafe(i))
+-                    acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                    acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             elif isinstance(x, dict):
+                 dct = <dict> x
+                 if len(dct) == 0:
+-                    acb_poly_zero(self.__poly)
++                    acb_poly_zero(self._poly)
+                 else:
+                     length = max(int(i) for i in dct) + 1
+-                    sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                    sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                     for i, c in dct.iteritems():
+                         ball = Coeff(c)
+-                        acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                        acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             else:
+                 ball = Coeff(x)
+-                acb_poly_set_coeff_acb(self.__poly, 0, ball.value)
++                acb_poly_set_coeff_acb(self._poly, 0, ball.value)
+ 
+     def __reduce__(self):
+         r"""
+@@ -219,12 +219,12 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: Pol([1, 0, 0, 0]).degree()
+             0
+         """
+-        return smallInteger(acb_poly_degree(self.__poly))
++        return smallInteger(acb_poly_degree(self._poly))
+ 
+     cdef get_unsafe(self, Py_ssize_t n):
+         cdef ComplexBall res = ComplexBall.__new__(ComplexBall)
+         res._parent = self._parent._base
+-        acb_poly_get_coeff_acb(res.value, self.__poly, n)
++        acb_poly_get_coeff_acb(res.value, self._poly, n)
+         return res
+ 
+     cpdef list list(self, bint copy=True):
+@@ -241,7 +241,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: Pol([0, 1, RBF(0, rad=.1), 0]).list()
+             [0, 1.000000000000000, [+/- 0.101]]
+         """
+-        cdef unsigned long length = acb_poly_length(self.__poly)
++        cdef unsigned long length = acb_poly_length(self._poly)
+         return [self.get_unsafe(n) for n in range(length)]
+ 
+     def __bool__(self):
+@@ -257,7 +257,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: bool(z)
+             True
+         """
+-        return acb_poly_length(self.__poly)
++        return acb_poly_length(self._poly)
+ 
+     # Ring and Euclidean arithmetic
+ 
+@@ -274,9 +274,9 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+         acb_poly_add(
+-                res.__poly,
+-                self.__poly,
+-                (<Polynomial_complex_arb> other).__poly,
++                res._poly,
++                self._poly,
++                (<Polynomial_complex_arb> other)._poly,
+                 prec(self))
+         sig_off()
+         return res
+@@ -293,7 +293,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         """
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_neg(res.__poly, self.__poly)
++        acb_poly_neg(res._poly, self._poly)
+         sig_off()
+         return res
+ 
+@@ -310,9 +310,9 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+         acb_poly_sub(
+-                res.__poly,
+-                self.__poly,
+-                (<Polynomial_complex_arb> other).__poly,
++                res._poly,
++                self._poly,
++                (<Polynomial_complex_arb> other)._poly,
+                 prec(self))
+         sig_off()
+         return res
+@@ -331,9 +331,9 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+         acb_poly_mul(
+-                res.__poly,
+-                self.__poly,
+-                (<Polynomial_complex_arb> other).__poly,
++                res._poly,
++                self._poly,
++                (<Polynomial_complex_arb> other)._poly,
+                 prec(self))
+         sig_off()
+         return res
+@@ -354,7 +354,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         """
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_scalar_mul(res.__poly, self.__poly, (<ComplexBall> a).value, prec(self))
++        acb_poly_scalar_mul(res._poly, self._poly, (<ComplexBall> a).value, prec(self))
+         sig_off()
+         return res
+ 
+@@ -409,8 +409,8 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb quo = self._new()
+         cdef Polynomial_complex_arb rem = self._new()
+         sig_on()
+-        cdef bint success = acb_poly_divrem(quo.__poly, rem.__poly, self.__poly,
+-                div.__poly, prec(self))
++        cdef bint success = acb_poly_divrem(quo._poly, rem._poly, self._poly,
++                div._poly, prec(self))
+         sig_off()
+         if success:
+             return quo, rem
+@@ -445,15 +445,15 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_set(res.__poly, self.__poly)
+-        acb_poly_truncate(res.__poly, n)
++        acb_poly_set(res._poly, self._poly)
++        acb_poly_truncate(res._poly, n)
+         sig_off()
+         return res
+ 
+     cdef _inplace_truncate(self, long n):
+         if n < 0:
+             n = 0
+-        acb_poly_truncate(self.__poly, n)
++        acb_poly_truncate(self._poly, n)
+         return self
+ 
+     def __lshift__(val, n):
+@@ -485,7 +485,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb self = (<Polynomial_complex_arb> val)
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_shift_left(res.__poly, self.__poly, n)
++        acb_poly_shift_left(res._poly, self._poly, n)
+         sig_off()
+         return res
+ 
+@@ -518,7 +518,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb self = (<Polynomial_complex_arb> val)
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_shift_right(res.__poly, self.__poly, n)
++        acb_poly_shift_right(res._poly, self._poly, n)
+         sig_off()
+         return res
+ 
+@@ -548,7 +548,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_mullow(res.__poly, self.__poly, my_other.__poly, n, prec(self))
++        acb_poly_mullow(res._poly, self._poly, my_other._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -576,7 +576,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_inv_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_inv_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -612,7 +612,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_pow_ui_trunc_binexp(res.__poly, self.__poly, expo, n, prec(self))
++        acb_poly_pow_ui_trunc_binexp(res._poly, self._poly, expo, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -648,7 +648,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_log_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_log_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -672,7 +672,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_exp_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_exp_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -697,7 +697,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_sqrt_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_sqrt_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -716,7 +716,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_gamma_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_gamma_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -735,7 +735,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_lgamma_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_lgamma_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -754,7 +754,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_rgamma_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_rgamma_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -784,7 +784,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_lambertw_series(res.__poly, self.__poly, _branch, 0, n, prec(self))
++        acb_poly_lambertw_series(res._poly, self._poly, _branch, 0, n, prec(self))
+         sig_off()
+         fmpz_clear(_branch)
+         return res
+@@ -814,7 +814,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef ComplexBall _a = <ComplexBall> (self._parent._base.coerce(a))
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_zeta_series(res.__poly, self.__poly, _a.value, deflate, n, prec(self))
++        acb_poly_zeta_series(res._poly, self._poly, _a.value, deflate, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -846,24 +846,24 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         cdef acb_poly_t self_ts, other_ts
+         cdef acb_ptr cc
+-        if acb_poly_length(other1.__poly) > 0:
+-            cc = acb_poly_get_coeff_ptr(other1.__poly, 0)
++        if acb_poly_length(other1._poly) > 0:
++            cc = acb_poly_get_coeff_ptr(other1._poly, 0)
+             if not acb_is_zero(cc):
+                 sig_on()
+                 try:
+                     acb_poly_init(self_ts)
+                     acb_poly_init(other_ts)
+-                    acb_poly_taylor_shift(self_ts, self.__poly, cc, prec(self))
+-                    acb_poly_set(other_ts, other1.__poly)
++                    acb_poly_taylor_shift(self_ts, self._poly, cc, prec(self))
++                    acb_poly_set(other_ts, other1._poly)
+                     acb_zero(acb_poly_get_coeff_ptr(other_ts, 0))
+-                    acb_poly_compose_series(res.__poly, self_ts, other_ts, n, prec(self))
++                    acb_poly_compose_series(res._poly, self_ts, other_ts, n, prec(self))
+                 finally:
+                     acb_poly_clear(other_ts)
+                     acb_poly_clear(self_ts)
+                     sig_off()
+                 return res
+         sig_on()
+-        acb_poly_compose_series(res.__poly, self.__poly, other1.__poly, n, prec(self))
++        acb_poly_compose_series(res._poly, self._poly, other1._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -895,12 +895,12 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         if n < 0:
+             n = 0
+-        if not acb_is_zero(acb_poly_get_coeff_ptr(self.__poly, 0)):
++        if not acb_is_zero(acb_poly_get_coeff_ptr(self._poly, 0)):
+             raise ValueError("the constant coefficient must be zero")
+-        if acb_contains_zero(acb_poly_get_coeff_ptr(self.__poly, 1)):
++        if acb_contains_zero(acb_poly_get_coeff_ptr(self._poly, 1)):
+             raise ValueError("the linear term must be nonzero")
+         sig_on()
+-        acb_poly_revert_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_revert_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -938,15 +938,15 @@ cdef class Polynomial_complex_arb(Polynomial):
+                 ball = ComplexBall.__new__(ComplexBall)
+                 ball._parent = self._parent._base
+                 sig_on()
+-                acb_poly_evaluate(ball.value, self.__poly,
++                acb_poly_evaluate(ball.value, self._poly,
+                         (<ComplexBall> point).value, prec(self))
+                 sig_off()
+                 return ball
+             elif isinstance(point, Polynomial_complex_arb):
+                 poly = (<Polynomial_complex_arb> point)._new()
+                 sig_on()
+-                acb_poly_compose(poly.__poly, self.__poly,
+-                        (<Polynomial_complex_arb> point).__poly, prec(self))
++                acb_poly_compose(poly._poly, self._poly,
++                        (<Polynomial_complex_arb> point)._poly, prec(self))
+                 sig_off()
+                 return poly
+             # TODO: perhaps add more special cases, e.g. for real ball,
+diff --git a/src/sage/rings/polynomial/polynomial_element.pxd b/src/sage/rings/polynomial/polynomial_element.pxd
+index 083f506b222..5dcbf4597d0 100644
+--- a/src/sage/rings/polynomial/polynomial_element.pxd
++++ b/src/sage/rings/polynomial/polynomial_element.pxd
+@@ -45,12 +45,12 @@ cdef class Polynomial(CommutativePolynomial):
+     cpdef _mul_(self, right)
+     cpdef _floordiv_(self, right)
+ 
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+ cdef class Polynomial_generic_dense(Polynomial):
+     cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P)
+-    cdef list __coeffs
+-    cdef int __normalize(self) except -1
++    cdef list _coeffs
++    cdef int _normalize(self) except -1
+     cpdef list list(self, bint copy=*)
+ 
+ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+diff --git a/src/sage/rings/polynomial/polynomial_element.pyx b/src/sage/rings/polynomial/polynomial_element.pyx
+index 4d4b9dd10f5..d1c802835ae 100644
+--- a/src/sage/rings/polynomial/polynomial_element.pyx
++++ b/src/sage/rings/polynomial/polynomial_element.pyx
+@@ -9800,7 +9800,7 @@ cdef class Polynomial(CommutativePolynomial):
+             0
+         """
+         # __getitem__ already returns a polynomial!!
+-        # We must not have check=False, since 0 must not have __coeffs = [0].
++        # We must not have check=False, since 0 must not have _coeffs = [0].
+         return <Polynomial>self._parent(self[:n])#, check=False)
+ 
+     cdef _inplace_truncate(self, long prec):
+@@ -11541,16 +11541,16 @@ cdef class Polynomial_generic_dense(Polynomial):
+     def __init__(self, parent, x=None, int check=1, is_gen=False, int construct=0, **kwds):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+         if x is None:
+-            self.__coeffs = []
++            self._coeffs = []
+             return
+ 
+         R = parent.base_ring()
+         if isinstance(x, (list, tuple)):
+             if check:
+-                self.__coeffs = [R(t) for t in x]
+-                self.__normalize()
++                self._coeffs = [R(t) for t in x]
++                self._normalize()
+             else:
+-                self.__coeffs = x
++                self._coeffs = x
+             return
+ 
+         if sage.rings.fraction_field_element.is_FractionFieldElement(x):
+@@ -11565,19 +11565,19 @@ cdef class Polynomial_generic_dense(Polynomial):
+             elif R.has_coerce_map_from((<Element>x)._parent):# is R or (<Element>x)._parent == R:
+                 try:
+                     if x.is_zero():
+-                        self.__coeffs = []
++                        self._coeffs = []
+                         return
+                 except (AttributeError, TypeError):
+                     pass
+                 x = [x]
+             else:
+-                self.__coeffs = [R(a, **kwds) for a in x.list(copy=False)]
++                self._coeffs = [R(a, **kwds) for a in x.list(copy=False)]
+                 if check:
+-                    self.__normalize()
++                    self._normalize()
+                 return
+ 
+         elif isinstance(x, int) and x == 0:
+-            self.__coeffs = []
++            self._coeffs = []
+             return
+ 
+         elif isinstance(x, dict):
+@@ -11593,16 +11593,16 @@ cdef class Polynomial_generic_dense(Polynomial):
+ #            else:
+ #                x = []    # zero polynomial
+         if check:
+-            self.__coeffs = [R(z, **kwds) for z in x]
+-            self.__normalize()
++            self._coeffs = [R(z, **kwds) for z in x]
++            self._normalize()
+         else:
+-            self.__coeffs = x
++            self._coeffs = x
+ 
+     cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P):
+         cdef type t = type(self)
+         cdef Polynomial_generic_dense f = <Polynomial_generic_dense>t.__new__(t)
+         f._parent = P
+-        f.__coeffs = coeffs
++        f._coeffs = coeffs
+         return f
+ 
+     cpdef Polynomial _new_constant_poly(self, a, Parent P):
+@@ -11644,10 +11644,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: type(f)
+             <class 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense'>
+         """
+-        return make_generic_polynomial, (self._parent, self.__coeffs)
++        return make_generic_polynomial, (self._parent, self._coeffs)
+ 
+     def __bool__(self):
+-        return bool(self.__coeffs)
++        return bool(self._coeffs)
+ 
+     cpdef bint is_term(self) except -1:
+         """
+@@ -11667,10 +11667,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: (1 + 3*x^5).is_term()
+             False
+         """
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return False
+ 
+-        for c in self.__coeffs[:-1]:
++        for c in self._coeffs[:-1]:
+             if c:
+                 return False
+         return True
+@@ -11682,9 +11682,9 @@ cdef class Polynomial_generic_dense(Polynomial):
+         Return the product ``self * term``, where ``term`` is a polynomial
+         with a single term.
+         """
+-        cdef Py_ssize_t d = len( (<Polynomial_generic_dense> term).__coeffs ) - 1
++        cdef Py_ssize_t d = len( (<Polynomial_generic_dense> term)._coeffs ) - 1
+         cdef Py_ssize_t i
+-        cdef list x = self.__coeffs
++        cdef list x = self._coeffs
+         cdef Py_ssize_t ell = len(x)
+         c = term.get_unsafe(d)
+         cdef list v = [self.base_ring().zero()] * (d + ell)
+@@ -11697,10 +11697,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+         cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
+         #if not v[len(v)-1]:
+         # "normalize" checks this anyway...
+-        res.__normalize()
++        res._normalize()
+         return res
+ 
+-    cdef int __normalize(self) except -1:
++    cdef int _normalize(self) except -1:
+         """
+         TESTS:
+ 
+@@ -11718,7 +11718,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+             ...
+             NotImplementedError: cannot check whether number is non-zero
+         """
+-        cdef list x = self.__coeffs
++        cdef list x = self._coeffs
+         cdef Py_ssize_t n = len(x) - 1
+         while n >= 0 and not x[n]:
+             del x[n]
+@@ -11747,7 +11747,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: f[:3]
+             40.0*x^2 + 10.0*x + 1.0
+         """
+-        return self.__coeffs[n]
++        return self._coeffs[n]
+ 
+     def _unsafe_mutate(self, n, value):
+         """
+@@ -11770,17 +11770,17 @@ cdef class Polynomial_generic_dense(Polynomial):
+         """
+         n = int(n)
+         value = self.base_ring()(value)
+-        if n >= 0 and n < len(self.__coeffs):
+-            self.__coeffs[n] = value
+-            if n == len(self.__coeffs) and value == 0:
+-                self.__normalize()
++        if n >= 0 and n < len(self._coeffs):
++            self._coeffs[n] = value
++            if n == len(self._coeffs) and value == 0:
++                self._normalize()
+         elif n < 0:
+             raise IndexError("polynomial coefficient index must be nonnegative")
+         elif value != 0:
+             zero = self.base_ring().zero()
+-            for _ in range(len(self.__coeffs), n):
+-                self.__coeffs.append(zero)
+-            self.__coeffs.append(value)
++            for _ in range(len(self._coeffs), n):
++                self._coeffs.append(zero)
++            self._coeffs.append(value)
+ 
+     def __floordiv__(self, right):
+         """
+@@ -11822,8 +11822,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+             return (<Polynomial_generic_dense>self)._floordiv_(<Polynomial_generic_dense>right)
+         P = parent(self)
+         d = P.base_ring()(right)
+-        cdef Polynomial_generic_dense res = (<Polynomial_generic_dense>self)._new_c([c // d for c in (<Polynomial_generic_dense>self).__coeffs], P)
+-        res.__normalize()
++        cdef Polynomial_generic_dense res = (<Polynomial_generic_dense>self)._new_c([c // d for c in (<Polynomial_generic_dense>self)._coeffs], P)
++        res._normalize()
+         return res
+ 
+     cpdef _add_(self, right):
+@@ -11839,8 +11839,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+         """
+         cdef Polynomial_generic_dense res
+         cdef Py_ssize_t check=0, i, min
+-        x = (<Polynomial_generic_dense>self).__coeffs
+-        y = (<Polynomial_generic_dense>right).__coeffs
++        x = (<Polynomial_generic_dense>self)._coeffs
++        y = (<Polynomial_generic_dense>right)._coeffs
+         if len(x) > len(y):
+             min = len(y)
+             high = x[min:]
+@@ -11852,7 +11852,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+         cdef list low = [x[i] + y[i] for i from 0 <= i < min]
+         if len(x) == len(y):
+             res = self._new_c(low, self._parent)
+-            res.__normalize()
++            res._normalize()
+             return res
+         else:
+             return self._new_c(low + high, self._parent)
+@@ -11860,8 +11860,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+     cpdef _sub_(self, right):
+         cdef Polynomial_generic_dense res
+         cdef Py_ssize_t check=0, i, min
+-        x = (<Polynomial_generic_dense>self).__coeffs
+-        y = (<Polynomial_generic_dense>right).__coeffs
++        x = (<Polynomial_generic_dense>self)._coeffs
++        y = (<Polynomial_generic_dense>right)._coeffs
+         if len(x) > len(y):
+             min = len(y)
+             high = x[min:]
+@@ -11873,33 +11873,33 @@ cdef class Polynomial_generic_dense(Polynomial):
+         low = [x[i] - y[i] for i from 0 <= i < min]
+         if len(x) == len(y):
+             res = self._new_c(low, self._parent)
+-            res.__normalize()
++            res._normalize()
+             return res
+         else:
+             return self._new_c(low + high, self._parent)
+ 
+     cpdef _rmul_(self, Element c):
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return self
+-        if c._parent is not (<Element>self.__coeffs[0])._parent:
+-            c = (<Element>self.__coeffs[0])._parent.coerce(c)
+-        v = [c * a for a in self.__coeffs]
++        if c._parent is not (<Element>self._coeffs[0])._parent:
++            c = (<Element>self._coeffs[0])._parent.coerce(c)
++        v = [c * a for a in self._coeffs]
+         cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
+         #if not v[len(v)-1]:
+         # "normalize" checks this anyway...
+-        res.__normalize()
++        res._normalize()
+         return res
+ 
+     cpdef _lmul_(self, Element c):
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return self
+-        if c._parent is not (<Element>self.__coeffs[0])._parent:
+-            c = (<Element>self.__coeffs[0])._parent.coerce(c)
+-        v = [a * c for a in self.__coeffs]
++        if c._parent is not (<Element>self._coeffs[0])._parent:
++            c = (<Element>self._coeffs[0])._parent.coerce(c)
++        v = [a * c for a in self._coeffs]
+         cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
+         #if not v[len(v)-1]:
+         # "normalize" checks this anyway...
+-        res.__normalize()
++        res._normalize()
+         return res
+ 
+     cpdef constant_coefficient(self):
+@@ -11916,10 +11916,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: f.constant_coefficient()
+             t
+         """
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return self.base_ring().zero()
+         else:
+-            return self.__coeffs[0]
++            return self._coeffs[0]
+ 
+     cpdef list list(self, bint copy=True):
+         """
+@@ -11934,9 +11934,9 @@ cdef class Polynomial_generic_dense(Polynomial):
+             [1, 9, 12, 8]
+         """
+         if copy:
+-            return list(self.__coeffs)
++            return list(self._coeffs)
+         else:
+-            return self.__coeffs
++            return self._coeffs
+ 
+     def degree(self, gen=None):
+         """
+@@ -11955,7 +11955,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+             <class 'sage.rings.integer.Integer'>
+ 
+         """
+-        return smallInteger(len(self.__coeffs) - 1)
++        return smallInteger(len(self._coeffs) - 1)
+ 
+     def shift(self, Py_ssize_t n):
+         r"""
+@@ -11993,13 +11993,13 @@ cdef class Polynomial_generic_dense(Polynomial):
+             return self
+         if n > 0:
+             output = [self.base_ring().zero()] * n
+-            output.extend(self.__coeffs)
++            output.extend(self._coeffs)
+             return self._new_c(output, self._parent)
+         if n < 0:
+-            if n > len(self.__coeffs) - 1:
++            if n > len(self._coeffs) - 1:
+                 return self._parent([])
+             else:
+-                return self._new_c(self.__coeffs[-int(n):], self._parent)
++                return self._new_c(self._coeffs[-int(n):], self._parent)
+ 
+     @coerce_binop
+     def quo_rem(self, other):
+@@ -12073,8 +12073,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+             return self, self
+ 
+         R = self._parent.base_ring()
+-        cdef list x = list((<Polynomial_generic_dense>self).__coeffs) # make a copy
+-        cdef list y = (<Polynomial_generic_dense>other).__coeffs
++        cdef list x = list((<Polynomial_generic_dense>self)._coeffs) # make a copy
++        cdef list y = (<Polynomial_generic_dense>other)._coeffs
+         cdef Py_ssize_t m = len(x)  # deg(self)=m-1
+         cdef Py_ssize_t n = len(y)  # deg(other)=n-1
+         if m < n:
+@@ -12135,18 +12135,18 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: type(f)
+             <class 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense'>
+         """
+-        l = len(self.__coeffs)
++        l = len(self._coeffs)
+         if n > l:
+             n = l
+-        while n > 0 and not self.__coeffs[n-1]:
++        while n > 0 and not self._coeffs[n-1]:
+             n -= 1
+-        return self._new_c(self.__coeffs[:n], self._parent)
++        return self._new_c(self._coeffs[:n], self._parent)
+ 
+     cdef _inplace_truncate(self, long n):
+-        if n < len(self.__coeffs):
+-            while n > 0 and not self.__coeffs[n-1]:
++        if n < len(self._coeffs):
++            while n > 0 and not self._coeffs[n-1]:
+                 n -= 1
+-        self.__coeffs = self.__coeffs[:n]
++        self._coeffs = self._coeffs[:n]
+         return self
+ 
+ def make_generic_polynomial(parent, coeffs):
+@@ -12305,7 +12305,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+ 
+     - Xavier Caruso (2013-03)
+     """
+-    cdef int __normalize(self) except -1:
++    cdef int _normalize(self) except -1:
+         r"""
+         TESTS::
+ 
+@@ -12316,7 +12316,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+             sage: S([1, R(0, 20)])                                                      # needs sage.rings.padics
+             O(5^20)*x + 1 + O(5^20)
+         """
+-        cdef list x = self.__coeffs
++        cdef list x = self._coeffs
+         cdef Py_ssize_t n = len(x) - 1
+         cdef RingElement c
+         while n >= 0:
+@@ -12376,7 +12376,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+ 
+         - Xavier Caruso (2013-03)
+         """
+-        coeffs = self.__coeffs
++        coeffs = self._coeffs
+         d = len(coeffs) - 1
+         while d >= 0:
+             c = coeffs[d]
+@@ -12420,7 +12420,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+ 
+         - Xavier Caruso (2013-03)
+         """
+-        return len(self.__coeffs) - 1
++        return len(self._coeffs) - 1
+ 
+ 
+ cdef class ConstantPolynomialSection(Map):
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd
+index 03c5cebbf09..b1b593d6a26 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd
+@@ -5,7 +5,7 @@ from sage.rings.integer cimport Integer
+ from sage.structure.parent cimport Parent
+ 
+ cdef class Polynomial_integer_dense_flint(Polynomial):
+-    cdef fmpz_poly_t __poly
++    cdef fmpz_poly_t _poly
+ 
+     cdef Polynomial_integer_dense_flint _new(self)
+     cpdef _unsafe_mutate(self, long n, value)
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx
+index e201ac843ad..194eb9263b2 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx
+@@ -99,14 +99,14 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         r"""
+         This calls the underlying FLINT fmpz_poly constructor
+         """
+-        fmpz_poly_init(self.__poly)
++        fmpz_poly_init(self._poly)
+ 
+ 
+     def __dealloc__(self):
+         r"""
+         calls the underlying FLINT fmpz_poly destructor
+         """
+-        fmpz_poly_clear(self.__poly)
++        fmpz_poly_clear(self._poly)
+ 
+     cdef Polynomial_integer_dense_flint _new(self):
+         r"""
+@@ -139,7 +139,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         x._is_gen = 0
+         if not isinstance(a, Integer):
+             a = ZZ(a)
+-        fmpz_poly_set_coeff_mpz(x.__poly, 0, (<Integer>a).value)
++        fmpz_poly_set_coeff_mpz(x._poly, 0, (<Integer>a).value)
+         return x
+ 
+     def __init__(self, parent, x=None, check=True, is_gen=False,
+@@ -224,8 +224,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         if isinstance(x, Polynomial):
+             if x.parent() is self.parent():
+                 sig_on()
+-                fmpz_poly_set(self.__poly,
+-                              (<Polynomial_integer_dense_flint>x).__poly)
++                fmpz_poly_set(self._poly,
++                              (<Polynomial_integer_dense_flint>x)._poly)
+                 sig_off()
+                 return
+             else:
+@@ -246,7 +246,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                     degree = i
+             try:
+                 sig_on()
+-                fmpz_poly_realloc(self.__poly, degree + 1)
++                fmpz_poly_realloc(self._poly, degree + 1)
+                 sig_off()
+             except RuntimeError:
+                 raise OverflowError("Cannot allocate memory!")
+@@ -255,13 +255,13 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 i = ii[0] if type(ii) is tuple else ii
+                 if is_small_python_int(a):
+                     sig_on()
+-                    fmpz_poly_set_coeff_si(self.__poly, i, a)
++                    fmpz_poly_set_coeff_si(self._poly, i, a)
+                     sig_off()
+                 else:
+                     if not isinstance(a, Integer):
+                         a = ZZ(a)
+                     sig_on()
+-                    fmpz_poly_set_coeff_mpz(self.__poly, i, (<Integer>a).value)
++                    fmpz_poly_set_coeff_mpz(self._poly, i, (<Integer>a).value)
+                     sig_off()
+             return
+ 
+@@ -270,7 +270,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             check = False
+ 
+         elif isinstance(x, ntl_ZZX):    # coercion from ntl.pyx object
+-            fmpz_poly_set_ZZX(self.__poly, (<ntl_ZZX>x).x)
++            fmpz_poly_set_ZZX(self._poly, (<ntl_ZZX>x).x)
+             return
+ 
+         elif isinstance(x, FractionFieldElement) and \
+@@ -278,8 +278,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if x.denominator() == 1:
+                 # fraction of the form f(x)/1
+                 sig_on()
+-                fmpz_poly_set(self.__poly,
+-                        (<Polynomial_integer_dense_flint>x.numerator()).__poly)
++                fmpz_poly_set(self._poly,
++                        (<Polynomial_integer_dense_flint>x.numerator())._poly)
+                 sig_off()
+                 return
+ 
+@@ -287,19 +287,19 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             x = [x]   # constant polynomials
+ 
+         sig_on()
+-        fmpz_poly_realloc(self.__poly, len(x))
++        fmpz_poly_realloc(self._poly, len(x))
+         sig_off()
+         for i from 0 <= i < len(x):
+             a = x[i]
+             if is_small_python_int(a):
+                 sig_on()
+-                fmpz_poly_set_coeff_si(self.__poly, i, a)
++                fmpz_poly_set_coeff_si(self._poly, i, a)
+                 sig_off()
+             else:
+                 if not isinstance(a, Integer):
+                     a = ZZ(a)
+                 sig_on()
+-                fmpz_poly_set_coeff_mpz(self.__poly, i, (<Integer>a).value)
++                fmpz_poly_set_coeff_mpz(self._poly, i, (<Integer>a).value)
+                 sig_off()
+ 
+     def _eval_mpfr_(self, RealNumber a):
+@@ -327,7 +327,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef RealNumber res = a._new()
+         sig_on()
+-        fmpz_poly_evaluation_mpfr(res.value, self.__poly, a.value)
++        fmpz_poly_evaluation_mpfr(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -357,7 +357,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef RealIntervalFieldElement res = a._new()
+         sig_on()
+-        fmpz_poly_evaluation_mpfi(res.value, self.__poly, a.value)
++        fmpz_poly_evaluation_mpfi(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -412,8 +412,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if isinstance(x, Polynomial_integer_dense_flint):
+                 f = self._new()
+                 sig_on()
+-                fmpz_poly_compose(f.__poly, self.__poly,
+-                                  (<Polynomial_integer_dense_flint> x0).__poly)
++                fmpz_poly_compose(f._poly, self._poly,
++                                  (<Polynomial_integer_dense_flint> x0)._poly)
+                 sig_off()
+                 return f
+             if is_small_python_int(x0):
+@@ -422,7 +422,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 fmpz_init(a_fmpz)
+                 fmpz_init(z_fmpz)
+                 fmpz_set_si(a_fmpz, PyInt_AS_LONG(x0))
+-                fmpz_poly_evaluate_fmpz(z_fmpz, self.__poly, a_fmpz)
++                fmpz_poly_evaluate_fmpz(z_fmpz, self._poly, a_fmpz)
+                 fmpz_get_mpz(z.value, z_fmpz)
+                 fmpz_clear(a_fmpz)
+                 fmpz_clear(z_fmpz)
+@@ -433,7 +433,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if isinstance(x0, Integer):
+                 a = <Integer> x0
+ 
+-                if fmpz_poly_length(self.__poly) == 0:
++                if fmpz_poly_length(self._poly) == 0:
+                     return ZZ.zero()
+                 if mpz_sgn(a.value) == 0:
+                     return self[0]
+@@ -444,7 +444,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 fmpz_init(a_fmpz)
+                 fmpz_init(z_fmpz)
+                 fmpz_set_mpz(a_fmpz, a.value)
+-                fmpz_poly_evaluate_fmpz(z_fmpz, self.__poly, a_fmpz)
++                fmpz_poly_evaluate_fmpz(z_fmpz, self._poly, a_fmpz)
+                 fmpz_get_mpz(z.value, z_fmpz)
+                 fmpz_clear(a_fmpz)
+                 fmpz_clear(z_fmpz)
+@@ -460,14 +460,14 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 arb_a = <RealBall> x0
+                 arb_z = arb_a._new()
+                 sig_on()
+-                arb_fmpz_poly_evaluate_arb(arb_z.value, self.__poly, arb_a.value, arb_a._parent._prec)
++                arb_fmpz_poly_evaluate_arb(arb_z.value, self._poly, arb_a.value, arb_a._parent._prec)
+                 sig_off()
+                 return arb_z
+             if isinstance(x0, ComplexBall):
+                 acb_a = <ComplexBall> x0
+                 acb_z = acb_a._new()
+                 sig_on()
+-                arb_fmpz_poly_evaluate_acb(acb_z.value, self.__poly, acb_a.value, acb_a._parent._prec)
++                arb_fmpz_poly_evaluate_acb(acb_z.value, self._poly, acb_a.value, acb_a._parent._prec)
+                 sig_off()
+                 return acb_z
+ 
+@@ -510,10 +510,10 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+         cdef fmpz_t c
+         fmpz_init(c)
+-        fmpz_poly_get_coeff_fmpz(c, self.__poly, fmpz_poly_degree(self.__poly))
++        fmpz_poly_get_coeff_fmpz(c, self._poly, fmpz_poly_degree(self._poly))
+         cdef int sign = fmpz_sgn(c)
+ 
+-        fmpz_poly_content(c, self.__poly)
++        fmpz_poly_content(c, self._poly)
+ 
+         cdef Integer z = Integer.__new__(Integer)
+         fmpz_get_mpz(z.value, c)
+@@ -561,7 +561,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             5*x^5 + 4*x^4 + 3*x^3 + 2*x^2 + x + 1
+         """
+         cdef Integer z = Integer.__new__(Integer)
+-        fmpz_poly_get_coeff_mpz(z.value, self.__poly, n)
++        fmpz_poly_get_coeff_mpz(z.value, self._poly, n)
+         return z
+ 
+     def _repr(self, name=None, bint latex=False):
+@@ -583,8 +583,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef long i
+         cdef Integer coef = Integer.__new__(Integer)
+         cdef list all = []
+-        for i from fmpz_poly_degree(self.__poly) >= i >= 0:
+-            fmpz_poly_get_coeff_mpz(coef.value, self.__poly, i)
++        for i from fmpz_poly_degree(self._poly) >= i >= 0:
++            fmpz_poly_get_coeff_mpz(coef.value, self._poly, i)
+             if coef:
+                 if coef > 0:
+                     sign_str = '+'
+@@ -649,8 +649,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_add(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_add(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -669,8 +669,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_sub(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_sub(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -688,7 +688,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_neg(x.__poly, self.__poly)
++        fmpz_poly_neg(x._poly, self._poly)
+         sig_off()
+         return x
+ 
+@@ -758,7 +758,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef Polynomial_integer_dense_flint rr = self._new()
+ 
+         sig_on()
+-        fmpz_poly_divrem(qq.__poly, rr.__poly, self.__poly, right.__poly)
++        fmpz_poly_divrem(qq._poly, rr._poly, self._poly, right._poly)
+         sig_off()
+         return qq, rr
+ 
+@@ -776,7 +776,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: x.is_zero()
+             False
+         """
+-        return (fmpz_poly_degree(self.__poly) == -1)
++        return (fmpz_poly_degree(self._poly) == -1)
+ 
+     cpdef bint is_one(self) except -1:
+         """
+@@ -792,7 +792,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: x.is_one()
+             False
+         """
+-        return fmpz_poly_is_one(self.__poly)
++        return fmpz_poly_is_one(self._poly)
+ 
+     def __bool__(self):
+         """
+@@ -808,7 +808,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: bool(x)
+             True
+         """
+-        return not (fmpz_poly_degree(self.__poly) == -1)
++        return not (fmpz_poly_degree(self._poly) == -1)
+ 
+     @coerce_binop
+     def gcd(self, right):
+@@ -831,8 +831,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             return self
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_gcd(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_gcd(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -941,8 +941,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         fmpz_init(r)
+ 
+         sig_on()
+-        fmpz_poly_xgcd(r, ss.__poly, tt.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_xgcd(r, ss._poly, tt._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         cdef Integer rr = Integer.__new__(Integer)
+         fmpz_get_mpz(rr.value, r)
+@@ -970,8 +970,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_mul(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_mul(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -1000,8 +1000,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_mullow(x.__poly, self.__poly,
+-                    (<Polynomial_integer_dense_flint>right).__poly,
++        fmpz_poly_mullow(x._poly, self._poly,
++                    (<Polynomial_integer_dense_flint>right)._poly,
+                     n)
+         sig_off()
+         return x
+@@ -1020,7 +1020,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_scalar_mul_mpz(x.__poly, self.__poly, (<Integer>right).value)
++        fmpz_poly_scalar_mul_mpz(x._poly, self._poly, (<Integer>right).value)
+         sig_off()
+         return x
+ 
+@@ -1038,7 +1038,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_scalar_mul_mpz(x.__poly, self.__poly, (<Integer>right).value)
++        fmpz_poly_scalar_mul_mpz(x._poly, self._poly, (<Integer>right).value)
+         sig_off()
+         return x
+ 
+@@ -1132,7 +1132,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             num = n.numerator()
+             den = n.denominator()
+ 
+-            if fmpz_poly_degree(self.__poly) == 0:
++            if fmpz_poly_degree(self._poly) == 0:
+                 return self.parent()(self[0].nth_root(den) ** num)
+ 
+             return self.nth_root(den) ** num
+@@ -1142,7 +1142,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+             if self.is_zero():
+                 if nn == 0:
+-                    fmpz_poly_set_coeff_si(res.__poly, 0, 1)
++                    fmpz_poly_set_coeff_si(res._poly, 0, 1)
+                     return res
+                 elif nn < 0:
+                     raise ZeroDivisionError("negative exponent in power of zero")
+@@ -1150,17 +1150,17 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                     return res
+             if nn < 0:
+                 sig_on()
+-                fmpz_poly_pow(res.__poly, self.__poly, -nn)
++                fmpz_poly_pow(res._poly, self._poly, -nn)
+                 sig_off()
+                 return ~res
+             else:
+                 if self is self._parent.gen():
+                     sig_on()
+-                    fmpz_poly_set_coeff_ui(res.__poly, nn, 1)
++                    fmpz_poly_set_coeff_ui(res._poly, nn, 1)
+                     sig_off()
+                 else:
+                     sig_on()
+-                    fmpz_poly_pow(res.__poly, self.__poly, nn)
++                    fmpz_poly_pow(res._poly, self._poly, nn)
+                     sig_off()
+                 return res
+ 
+@@ -1187,7 +1187,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+         cdef Polynomial_integer_dense_flint res
+         res = self._new()
+-        fmpz_poly_pow_trunc(res.__poly, self.__poly, n, prec)
++        fmpz_poly_pow_trunc(res._poly, self._poly, n, prec)
+         return res
+ 
+     def __floordiv__(Polynomial_integer_dense_flint self, right):
+@@ -1226,14 +1226,14 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 else:
+                     res = self._new()
+                     sig_on()
+-                    fmpz_poly_scalar_fdiv_mpz(res.__poly, self.__poly,
++                    fmpz_poly_scalar_fdiv_mpz(res._poly, self._poly,
+                             (<Integer> right).value)
+                     sig_off()
+                 return res
+             elif right in ZZ:
+                 res = self._new()
+                 sig_on()
+-                fmpz_poly_scalar_fdiv_mpz(res.__poly, self.__poly,
++                fmpz_poly_scalar_fdiv_mpz(res._poly, self._poly,
+                         (<Integer>ZZ(right)).value)
+                 sig_off()
+                 return res
+@@ -1248,7 +1248,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         else:
+             res = self._new()
+             sig_on()
+-            fmpz_poly_div(res.__poly, self.__poly, _right.__poly)
++            fmpz_poly_div(res._poly, self._poly, _right._poly)
+             sig_off()
+             return res
+ 
+@@ -1293,9 +1293,9 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         if prec <= 0:
+             raise ValueError("the precision must be positive, got {}".format(prec))
+ 
+-        if fmpz_poly_degree(self.__poly) == -1:
++        if fmpz_poly_degree(self._poly) == -1:
+             raise ValueError("constant term is zero")
+-        cdef fmpz_t c = fmpz_poly_get_coeff_ptr(self.__poly, 0)
++        cdef fmpz_t c = fmpz_poly_get_coeff_ptr(self._poly, 0)
+         if fmpz_cmp_si(c, 1) and fmpz_cmp_si(c, -1):
+             raise ValueError("constant term {} is not a unit".format(self[0]))
+ 
+@@ -1303,7 +1303,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         if prec <= 0:
+             return res
+         sig_on()
+-        fmpz_poly_inv_series(res.__poly, self.__poly, prec)
++        fmpz_poly_inv_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1331,16 +1331,16 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             raise IndexError("n must be >= 0")
+         if isinstance(value, int):
+             sig_on()
+-            fmpz_poly_set_coeff_si(self.__poly, n, value)
++            fmpz_poly_set_coeff_si(self._poly, n, value)
+             sig_off()
+         elif isinstance(value, Integer):
+             sig_on()
+-            fmpz_poly_set_coeff_mpz(self.__poly, n, (<Integer>value).value)
++            fmpz_poly_set_coeff_mpz(self._poly, n, (<Integer>value).value)
+             sig_off()
+         else:
+             value = Integer(value)
+             sig_on()
+-            fmpz_poly_set_coeff_mpz(self.__poly, n, (<Integer>value).value)
++            fmpz_poly_set_coeff_mpz(self._poly, n, (<Integer>value).value)
+             sig_off()
+ 
+     def real_root_intervals(self):
+@@ -1364,7 +1364,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+ ##     def __copy__(self):
+ ##         f = Polynomial_integer_dense(self.parent())
+-##         f.__poly = self.__poly.copy()
++##         f._poly = self._poly.copy()
+ ##         return f
+ 
+ 
+@@ -1391,7 +1391,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: type(x.degree())
+             <class 'sage.rings.integer.Integer'>
+         """
+-        return smallInteger(fmpz_poly_degree(self.__poly))
++        return smallInteger(fmpz_poly_degree(self._poly))
+ 
+     def pseudo_divrem(self, B):
+         r"""
+@@ -1426,7 +1426,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint Q = self._new(), R = self._new(), _B = B
+         cdef ulong d
+-        fmpz_poly_pseudo_divrem(Q.__poly, R.__poly, &d, self.__poly, _B.__poly)
++        fmpz_poly_pseudo_divrem(Q._poly, R._poly, &d, self._poly, _B._poly)
+         return Q, R, Integer(d)
+ 
+     def discriminant(self, proof=True):
+@@ -1460,7 +1460,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef ZZX_c ntl_poly
+         cdef ZZ_c* temp
+-        fmpz_poly_get_ZZX(ntl_poly, self.__poly)
++        fmpz_poly_get_ZZX(ntl_poly, self._poly)
+ 
+         temp = ZZX_discriminant(&ntl_poly, proof)
+         cdef Integer x = Integer.__new__(Integer)
+@@ -1531,12 +1531,12 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+             # the primitive part returned by FLINT has positive leading
+             # coefficient
+-            fmpz_poly_primitive_part(ppart, self.__poly)
++            fmpz_poly_primitive_part(ppart, self._poly)
+ 
+             fmpz_poly_get_ZZX(ntl_poly, ppart)
+             fmpz_poly_clear(ppart)
+         else:
+-            fmpz_poly_get_ZZX(ntl_poly, self.__poly)
++            fmpz_poly_get_ZZX(ntl_poly, self._poly)
+ 
+         # input is primitive, with positive leading coefficient
+         ZZX_squarefree_decomposition(&v, &e, &n, &ntl_poly)
+@@ -1544,7 +1544,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         F = []
+         for i from 0 <= i < n:
+             fac = self._new()
+-            fmpz_poly_set_ZZX(fac.__poly, v[i][0])
++            fmpz_poly_set_ZZX(fac._poly, v[i][0])
+             F.append( (fac,e[i]) )
+             del v[i]
+         sig_free(v)
+@@ -1582,9 +1582,9 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef ZZ_c content
+         cdef vec_pair_ZZX_long_c factors
+         cdef long i
+-        cdef int sig_me = fmpz_poly_degree(self.__poly)
++        cdef int sig_me = fmpz_poly_degree(self._poly)
+ 
+-        fmpz_poly_get_ZZX(ntl_poly, self.__poly)
++        fmpz_poly_get_ZZX(ntl_poly, self._poly)
+ 
+         if sig_me > 10:
+             sig_on()
+@@ -1603,13 +1603,13 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             fac_py = self._new()
+             fmpz_init(tcontent)
+             fmpz_set_ZZ(tcontent, content)
+-            fmpz_poly_set_coeff_fmpz(fac_py.__poly, 0, tcontent)
++            fmpz_poly_set_coeff_fmpz(fac_py._poly, 0, tcontent)
+             results.append( (fac_py,1) )
+             fmpz_clear(tcontent)
+ 
+         for i from 0 <= i < factors.length():
+             fac_py = self._new()
+-            fmpz_poly_set_ZZX(fac_py.__poly, factors.RawGet(i).a)
++            fmpz_poly_set_ZZX(fac_py._poly, factors.RawGet(i).a)
+             results.append( (fac_py,factors.RawGet(i).b) )
+         return Factorization(results, unit = unit)
+ 
+@@ -1639,7 +1639,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             (-1) * 2 * 3 * 5 * x
+         """
+         cdef int i
+-        cdef long deg = fmpz_poly_degree(self.__poly)
++        cdef long deg = fmpz_poly_degree(self._poly)
+         # it appears that pari has a window from about degrees 30 and 300
+         # in which it beats NTL.
+         c = self.content()
+@@ -1783,8 +1783,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef Integer x = Integer.__new__(Integer)
+ 
+         sig_on()
+-        fmpz_poly_resultant(res, self.__poly,
+-                (<Polynomial_integer_dense_flint>other).__poly)
++        fmpz_poly_resultant(res, self._poly,
++                (<Polynomial_integer_dense_flint>other)._poly)
+         sig_off()
+         fmpz_get_mpz(x.value, res)
+         fmpz_clear(res)
+@@ -1830,10 +1830,10 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if d != degree:
+                 raise ValueError("degree argument must be a non-negative integer, got %s" % degree)
+             # FLINT expects length
+-            fmpz_poly_reverse(res.__poly, self.__poly, d+1)
++            fmpz_poly_reverse(res._poly, self._poly, d+1)
+         else:
+-            fmpz_poly_reverse(res.__poly, self.__poly,
+-                    fmpz_poly_length(self.__poly))
++            fmpz_poly_reverse(res._poly, self._poly,
++                    fmpz_poly_length(self._poly))
+         return res
+ 
+     def revert_series(self, n):
+@@ -1867,7 +1867,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             raise ValueError("self must have constant coefficient 0 and a unit for coefficient {}^1".format(self.parent().gen()))
+ 
+         sig_on()
+-        fmpz_poly_revert_series(res.__poly, self.__poly, m)
++        fmpz_poly_revert_series(res._poly, self._poly, m)
+         sig_off()
+ 
+         return res
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd
+index a7c380b49a2..fcd907e1abe 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd
+@@ -2,6 +2,6 @@ from sage.libs.ntl.types cimport ZZX_c
+ from sage.rings.polynomial.polynomial_element cimport Polynomial
+ 
+ cdef class Polynomial_integer_dense_ntl(Polynomial):
+-    cdef ZZX_c __poly
++    cdef ZZX_c _poly
+ 
+     cdef Polynomial_integer_dense_ntl _new(self)
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx
+index e7b708bbc51..80a1726bb4e 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx
+@@ -172,7 +172,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         if isinstance(x, Polynomial):
+             if x.parent() is self.parent():
+                 # copy with NTL assignment operator
+-                self.__poly = (<Polynomial_integer_dense_ntl>x).__poly
++                self._poly = (<Polynomial_integer_dense_ntl>x)._poly
+                 return
+             else:
+                 # coerce coefficients into Sage integers
+@@ -191,17 +191,17 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+                     degree = i
+             if degree >= NTL_OVFBND:
+                 raise OverflowError("Dense NTL integer polynomials have a maximum degree of %s" % (NTL_OVFBND-1))
+-            ZZX_SetCoeff_long(self.__poly, degree, 1)
++            ZZX_SetCoeff_long(self._poly, degree, 1)
+             # now fill them in
+             for ii, a in x:
+                 i = ii[0] if type(ii) is tuple else ii
+                 if type(a) is int:
+-                    ZZX_SetCoeff_long(self.__poly, i, a)
++                    ZZX_SetCoeff_long(self._poly, i, a)
+                 else:
+                     if not isinstance(a, Integer):
+                         a = ZZ(a)
+                     mpz_to_ZZ(&y, (<Integer>a).value)
+-                    ZZX_SetCoeff(self.__poly, i, y)
++                    ZZX_SetCoeff(self._poly, i, y)
+             return
+ 
+         elif isinstance(x, pari_gen):
+@@ -210,14 +210,14 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+ 
+         elif isinstance(x, ntl_ZZX):    # coercion from ntl.pyx object
+             # copy with NTL assignment operator
+-            self.__poly = (<ntl_ZZX>x).x
++            self._poly = (<ntl_ZZX>x).x
+             return
+ 
+         elif isinstance(x, FractionFieldElement) and \
+                  isinstance(x.numerator(), Polynomial_integer_dense_ntl):
+             if x.denominator() == 1:
+                 # fraction of the form f(x)/1
+-                self.__poly = (<Polynomial_integer_dense_ntl>x.numerator()).__poly
++                self._poly = (<Polynomial_integer_dense_ntl>x.numerator())._poly
+                 return
+ 
+         elif not isinstance(x, (list, tuple)):
+@@ -229,12 +229,12 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         for i from 0 <= i < len(x):
+             a = x[i]
+             if type(a) is int:
+-                ZZX_SetCoeff_long(self.__poly, i, a)
++                ZZX_SetCoeff_long(self._poly, i, a)
+             else:
+                 if not isinstance(a, Integer):
+                     a = ZZ(a)
+                 mpz_to_ZZ(&y, (<Integer>a).value)
+-                ZZX_SetCoeff(self.__poly, i, y)
++                ZZX_SetCoeff(self._poly, i, y)
+ 
+ 
+     def content(self):
+@@ -259,7 +259,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef ZZ_c y
+         cdef Integer z = Integer.__new__(Integer)
+-        ZZX_content(y, self.__poly)
++        ZZX_content(y, self._poly)
+         ZZ_to_mpz(z.value, &y)
+         return z
+ 
+@@ -288,7 +288,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef RealNumber res = a._new()
+         sig_on()
+-        ZZX_evaluation_mpfr(res.value, self.__poly, a.value)
++        ZZX_evaluation_mpfr(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -318,7 +318,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef RealIntervalFieldElement res = a._new()
+         sig_on()
+-        ZZX_evaluation_mpfi(res.value, self.__poly, a.value)
++        ZZX_evaluation_mpfi(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -363,7 +363,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             5*x^5 + 4*x^4 + 3*x^3 + 2*x^2 + x + 1
+         """
+         cdef Integer z = Integer.__new__(Integer)
+-        ZZ_to_mpz(z.value, &self.__poly.rep.elts()[n])
++        ZZ_to_mpz(z.value, &self._poly.rep.elts()[n])
+         return z
+ 
+     def _repr(self, name=None, bint latex=False):
+@@ -380,15 +380,15 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             name = self.parent().variable_name()
+         cdef long i
+         cdef list all = []
+-        for i from ZZX_deg(self.__poly) >= i >= 0:
+-            sign = ZZ_sign(ZZX_coeff(self.__poly, i))
++        for i from ZZX_deg(self._poly) >= i >= 0:
++            sign = ZZ_sign(ZZX_coeff(self._poly, i))
+             if sign:
+                 if sign > 0:
+                     sign_str = '+'
+-                    coeff_str = ccrepr(self.__poly.rep.elts()[i])
++                    coeff_str = ccrepr(self._poly.rep.elts()[i])
+                 else:
+                     sign_str = '-'
+-                    coeff_str = ccrepr(self.__poly.rep.elts()[i])[1:]
++                    coeff_str = ccrepr(self._poly.rep.elts()[i])[1:]
+                 if i > 0:
+                     if coeff_str == '1':
+                         coeff_str = ''
+@@ -441,8 +441,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             -3*x^2 + 2*x + 7
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_add(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_ntl>right).__poly)
++        ZZX_add(x._poly, self._poly,
++                (<Polynomial_integer_dense_ntl>right)._poly)
+         return x
+ 
+ 
+@@ -459,8 +459,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             3*x^2 + 2*x - 5
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_sub(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_ntl>right).__poly)
++        ZZX_sub(x._poly, self._poly,
++                (<Polynomial_integer_dense_ntl>right)._poly)
+         return x
+ 
+ 
+@@ -476,7 +476,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             -2*x + 1
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_negate(x.__poly, self.__poly)
++        ZZX_negate(x._poly, self._poly)
+         return x
+ 
+ 
+@@ -533,10 +533,10 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef Polynomial_integer_dense_ntl _right = <Polynomial_integer_dense_ntl> right
+ 
+-        if ZZX_IsZero(_right.__poly):
++        if ZZX_IsZero(_right._poly):
+             raise ArithmeticError("division by zero polynomial")
+ 
+-        if ZZX_IsZero(self.__poly):
++        if ZZX_IsZero(self._poly):
+             return self, self
+ 
+         cdef ZZX_c *q
+@@ -545,19 +545,19 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef Polynomial_integer_dense_ntl rr = self._new()
+         cdef int divisible
+ 
+-        if ZZ_IsOne(ZZX_LeadCoeff(_right.__poly)):
++        if ZZ_IsOne(ZZX_LeadCoeff(_right._poly)):
+             # divisor is monic. Just do the division and remainder
+-            ZZX_quo_rem(&self.__poly, &_right.__poly, &r, &q)
+-            ZZX_swap(qq.__poly, q[0])
+-            ZZX_swap(rr.__poly, r[0])
++            ZZX_quo_rem(&self._poly, &_right._poly, &r, &q)
++            ZZX_swap(qq._poly, q[0])
++            ZZX_swap(rr._poly, r[0])
+             del q
+             del r
+         else:
+             # Non-monic divisor. Check whether it divides exactly.
+-            q = ZZX_div(&self.__poly, &_right.__poly, &divisible)
++            q = ZZX_div(&self._poly, &_right._poly, &divisible)
+             if divisible:
+                 # exactly divisible
+-                ZZX_swap(q[0], qq.__poly)
++                ZZX_swap(q[0], qq._poly)
+                 del q
+             else:
+                 # division failed: clean up and raise exception
+@@ -584,8 +584,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         # todo: we're doing an unnecessary copy here
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        cdef ZZX_c* temp = ZZX_gcd(&self.__poly, &(<Polynomial_integer_dense_ntl>right).__poly)
+-        x.__poly = temp[0]
++        cdef ZZX_c* temp = ZZX_gcd(&self._poly, &(<Polynomial_integer_dense_ntl>right)._poly)
++        x._poly = temp[0]
+         del temp
+         return x
+ 
+@@ -658,13 +658,13 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZX_c *t
+         cdef ZZ_c *r
+ 
+-        ZZX_xgcd(&self.__poly, &(<Polynomial_integer_dense_ntl>right).__poly, &r, &s, &t, 1)    # proof = 1
++        ZZX_xgcd(&self._poly, &(<Polynomial_integer_dense_ntl>right)._poly, &r, &s, &t, 1)    # proof = 1
+         cdef Integer rr = Integer.__new__(Integer)
+         ZZ_to_mpz(rr.value, r)
+         cdef Polynomial_integer_dense_ntl ss = self._new()
+         cdef Polynomial_integer_dense_ntl tt = self._new()
+-        ss.__poly = s[0]
+-        tt.__poly = t[0]
++        ss._poly = s[0]
++        tt._poly = t[0]
+         del r
+         del s
+         del t
+@@ -691,8 +691,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             x^3 - 10*x^2 + 32*x - 32
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_mul(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_ntl>right).__poly)
++        ZZX_mul(x._poly, self._poly,
++                (<Polynomial_integer_dense_ntl>right)._poly)
+         return x
+ 
+     cpdef _lmul_(self, Element right):
+@@ -711,7 +711,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZ_c _right
+ 
+         mpz_to_ZZ(&_right, (<Integer>right).value)
+-        ZZX_mul_ZZ(x.__poly, self.__poly, _right)
++        ZZX_mul_ZZ(x._poly, self._poly, _right)
+         return x
+ 
+     cpdef _rmul_(self, Element right):
+@@ -730,7 +730,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZ_c _right
+ 
+         mpz_to_ZZ(&_right, (<Integer>right).value)
+-        ZZX_mul_ZZ(x.__poly, self.__poly, _right)
++        ZZX_mul_ZZ(x._poly, self._poly, _right)
+         return x
+ 
+ 
+@@ -783,7 +783,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         value = Integer(value)
+         cdef ZZ_c y
+         mpz_to_ZZ(&y, (<Integer>value).value)
+-        ZZX_SetCoeff(self.__poly, n, y)
++        ZZX_SetCoeff(self._poly, n, y)
+ 
+ 
+     def real_root_intervals(self):
+@@ -805,7 +805,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+ 
+ ##     def __copy__(self):
+ ##         f = Polynomial_integer_dense(self.parent())
+-##         f.__poly = self.__poly.copy()
++##         f._poly = self._poly.copy()
+ ##         return f
+ 
+ 
+@@ -826,7 +826,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             sage: R(0).degree()
+             -1
+         """
+-        return ZZX_deg(self.__poly)
++        return ZZX_deg(self._poly)
+ 
+     def discriminant(self, proof=True):
+         r"""
+@@ -849,7 +849,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             sage: f.discriminant(proof=False)
+             -339
+         """
+-        cdef ZZ_c* temp = ZZX_discriminant(&self.__poly, proof)
++        cdef ZZ_c* temp = ZZX_discriminant(&self._poly, proof)
+         cdef Integer x = Integer.__new__(Integer)
+         ZZ_to_mpz(x.value, temp)
+         del temp
+@@ -904,11 +904,11 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef long* e
+         cdef long i, n
+         cdef Polynomial_integer_dense_ntl z
+-        ZZX_squarefree_decomposition(&v, &e, &n, &p.__poly)
++        ZZX_squarefree_decomposition(&v, &e, &n, &p._poly)
+         F = []
+         for i from 0 <= i < n:
+             z = self._new()
+-            z.__poly = v[i][0]
++            z._poly = v[i][0]
+             F.append((z, e[i]))
+             del v[i]
+         sig_free(v)
+@@ -950,24 +950,24 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZ_c content
+         cdef vec_pair_ZZX_long_c factors
+         cdef long i
+-        cdef int sig_me = ZZX_deg(self.__poly)
++        cdef int sig_me = ZZX_deg(self._poly)
+         if sig_me > 10:
+             sig_on()
+-        ZZX_factor(content, factors, self.__poly, 0, 0)
++        ZZX_factor(content, factors, self._poly, 0, 0)
+         if sig_me > 10:
+             sig_off()
+         results = []
+         unit = None
+         if not ZZ_IsOne(content):
+             fac_py = self._new()
+-            ZZX_SetCoeff(fac_py.__poly, 0, content)
+-            if ZZX_deg(fac_py.__poly) == 0 and ZZ_to_int(fac_py.__poly.rep.elts())==-1:
++            ZZX_SetCoeff(fac_py._poly, 0, content)
++            if ZZX_deg(fac_py._poly) == 0 and ZZ_to_int(fac_py._poly.rep.elts())==-1:
+                 unit = fac_py
+             else:
+                 results.append( (fac_py,1) )
+         for i from 0 <= i < factors.length():
+             fac_py = self._new()
+-            fac_py.__poly = factors.RawGet(i).a
++            fac_py._poly = factors.RawGet(i).a
+             results.append( (fac_py,factors.RawGet(i).b) )
+         return Factorization(results, unit = unit)
+ 
+@@ -996,7 +996,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             sage: f = -30*x; f.factor()
+             (-1) * 2 * 3 * 5 * x
+         """
+-        cdef int deg = ZZX_deg(self.__poly)
++        cdef int deg = ZZX_deg(self._poly)
+         # it appears that pari has a window from about degrees 30 and 300
+         # in which it beats NTL.
+         c = self.content()
+@@ -1131,7 +1131,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             True
+         """
+         cdef Polynomial_integer_dense_ntl _other = <Polynomial_integer_dense_ntl>(self.parent().coerce(other))
+-        cdef ZZ_c* temp = ZZX_resultant(&self.__poly, &_other.__poly, proof)
++        cdef ZZ_c* temp = ZZX_resultant(&self._poly, &_other._poly, proof)
+         cdef Integer x = Integer.__new__(Integer)
+         ZZ_to_mpz(x.value, temp)
+         del temp
+diff --git a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd
+index 264f05f3c0d..6934acfee8d 100644
+--- a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd
++++ b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd
+@@ -16,7 +16,7 @@ from sage.libs.ntl.lzz_pX cimport *
+ 
+ 
+ cdef class Polynomial_dense_mod_n(Polynomial):
+-    cdef object __poly
++    cdef object _poly
+     cdef object __singular
+ 
+ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n):
+diff --git a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx
+index 57468e3510f..d69d5e09018 100644
+--- a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx
++++ b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx
+@@ -105,19 +105,19 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+ 
+         if construct:
+             if isinstance(x, ZZ_pX):
+-                self.__poly = x
++                self._poly = x
+                 return
+-            self.__poly = ZZ_pX(x, parent.modulus())
++            self._poly = ZZ_pX(x, parent.modulus())
+             return
+ 
+-        self.__poly = ZZ_pX([], parent.modulus())
++        self._poly = ZZ_pX([], parent.modulus())
+ 
+         if x is None:
+             return         # leave initialized to 0 polynomial.
+ 
+         if isinstance(x, Polynomial):
+             if x.parent() == self.parent():
+-                self.__poly = (<Polynomial_dense_modn_ntl_zz>x).__poly.__copy__()
++                self._poly = (<Polynomial_dense_modn_ntl_zz>x)._poly.__copy__()
+                 return
+             else:
+                 R = parent.base_ring()
+@@ -130,7 +130,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+ 
+ 
+         elif isinstance(x, ZZX):
+-            self.__poly = x.copy()
++            self._poly = x.copy()
+             return
+ 
+         elif isinstance(x, pari_gen):
+@@ -142,7 +142,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             if x.denominator().is_unit():
+                 numer = x.numerator()
+                 denom = x.denominator().inverse_of_unit()
+-                x = numer.__poly * denom.__poly
++                x = numer._poly * denom._poly
+                 check = False
+             else:
+                 raise TypeError("Denominator not a unit.")
+@@ -154,13 +154,13 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             R = parent.base_ring()
+             x = [ZZ(R(a)) for a in x]
+ 
+-        self.__poly = ZZ_pX(x, parent.modulus())
++        self._poly = ZZ_pX(x, parent.modulus())
+ 
+     def __reduce__(self):
+         return make_element, (self.parent(), (self.list(), False, self.is_gen()))
+ 
+     def int_list(self):
+-        return eval(str(self.__poly).replace(' ',','))
++        return eval(str(self._poly).replace(' ',','))
+ 
+     def __pari__(self, variable=None):
+         """
+@@ -186,7 +186,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             You must call ``ntl.set_modulus(ntl.ZZ(n))`` before doing
+             arithmetic with this object!
+         """
+-        return self.__poly
++        return self._poly
+ 
+     cdef get_unsafe(self, Py_ssize_t n):
+         """
+@@ -203,13 +203,13 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             sage: f[:3]
+             13*x^2 + 10*x + 5
+         """
+-        return self._parent._base((<ntl_ZZ_pX> self.__poly)[n]._integer_())
++        return self._parent._base((<ntl_ZZ_pX> self._poly)[n]._integer_())
+ 
+     def _unsafe_mutate(self, n, value):
+         n = int(n)
+         if n < 0:
+             raise IndexError("n must be >= 0")
+-        self.__poly[n] = int(value)
++        self._poly[n] = int(value)
+ 
+     def _pow(self, n):
+         n = int(n)
+@@ -218,10 +218,10 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             return self.parent()(self[0]**n)
+         if n < 0:
+             return (~self)**(-n)
+-        return self.parent()(self.__poly**n, construct=True)
++        return self.parent()(self._poly**n, construct=True)
+ 
+     cpdef _add_(self, right):
+-        return self.parent()(self.__poly + (<Polynomial_dense_mod_n>right).__poly, construct=True)
++        return self.parent()(self._poly + (<Polynomial_dense_mod_n>right)._poly, construct=True)
+ 
+     cpdef _mul_(self, right):
+         """
+@@ -231,11 +231,11 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             sage: (x - 2)*(x^2 - 8*x + 16)
+             x^3 + 90*x^2 + 32*x + 68
+         """
+-        return self.parent()(self.__poly * (<Polynomial_dense_mod_n>right).__poly, construct=True)
++        return self.parent()(self._poly * (<Polynomial_dense_mod_n>right)._poly, construct=True)
+ 
+     cpdef _lmul_(self, Element c):
+         try:
+-            return self.parent()(ZZ_pX([c], self.parent().modulus()) * self.__poly, construct=True)
++            return self.parent()(ZZ_pX([c], self.parent().modulus()) * self._poly, construct=True)
+         except RuntimeError as msg: # should this really be a TypeError
+             raise TypeError(msg)
+ 
+@@ -245,7 +245,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+         Return a tuple ``(quotient, remainder)`` where ``self = quotient*other +
+         remainder``.
+         """
+-        v = self.__poly.quo_rem((<Polynomial_dense_mod_n>right).__poly)
++        v = self._poly.quo_rem((<Polynomial_dense_mod_n>right)._poly)
+         P = self.parent()
+         return (P(v[0], construct=True), P(v[1], construct=True) )
+ 
+@@ -281,11 +281,11 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+         """
+         if n == 0 or self.degree() < 0:
+             return self
+-        return self.parent()(self.__poly.left_shift(n),
++        return self.parent()(self._poly.left_shift(n),
+                              construct=True)
+ 
+     cpdef _sub_(self, right):
+-        return self.parent()(self.__poly - (<Polynomial_dense_mod_n>right).__poly, construct=True)
++        return self.parent()(self._poly - (<Polynomial_dense_mod_n>right)._poly, construct=True)
+ 
+     def __floordiv__(self, right):
+         q, _ = self.quo_rem(right)
+@@ -314,7 +314,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             sage: isinstance(x.degree(), Integer)
+             True
+         """
+-        return smallInteger(max(self.__poly.degree(), -1))
++        return smallInteger(max(self._poly.degree(), -1))
+ 
+     cpdef list list(self, bint copy=True):
+         """
+@@ -358,7 +358,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+         """
+         if self.is_gen():
+             raise TypeError("Cannot change the value of the generator.")
+-        self.__poly = ZZ_pX(v, self.parent().modulus())
++        self._poly = ZZ_pX(v, self.parent().modulus())
+ 
+     # Polynomial_singular_repr stuff, copied due to lack of multiple inheritance
+     def _singular_(self, singular=singular_default, force=False):
+@@ -654,8 +654,8 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n):
+                 return
+ 
+         Polynomial_dense_mod_n.__init__(self, parent, v, check=check, is_gen=is_gen, construct=construct)
+-        v = [a for a in self.__poly.list()]
+-        self.__poly = None # this will eventually go away
++        v = [a for a in self._poly.list()]
++        self._poly = None # this will eventually go away
+         cdef ntl_zz_pX ntl = ntl_zz_pX(v, parent.modulus()) # let it handle the hard work
+         self.x = ntl.x
+         self.c = ntl.c
+@@ -668,8 +668,8 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n):
+         # TODO: Get rid of this
+         Polynomial_dense_mod_n.ntl_set_directly(self, v)
+         # verbatim from __init__
+-        v = [int(a) for a in self.__poly.list()]
+-        self.__poly = None # this will eventually go away
++        v = [int(a) for a in self._poly.list()]
++        self._poly = None # this will eventually go away
+         cdef ntl_zz_pX ntl = ntl_zz_pX(v, self._parent.modulus()) # let it handle the hard work
+         self.x = ntl.x
+         self.c = ntl.c
+@@ -1241,8 +1241,8 @@ cdef class Polynomial_dense_modn_ntl_ZZ(Polynomial_dense_mod_n):
+                 return
+ 
+         Polynomial_dense_mod_n.__init__(self, parent, v, check=check, is_gen=is_gen, construct=construct)
+-        cdef ntl_ZZ_pX ntl = self.__poly
+-        self.__poly = None # this will eventually go away
++        cdef ntl_ZZ_pX ntl = self._poly
++        self._poly = None # this will eventually go away
+         self.x = ntl.x
+         self.c = ntl.c
+ 
+diff --git a/src/sage/rings/polynomial/polynomial_rational_flint.pxd b/src/sage/rings/polynomial/polynomial_rational_flint.pxd
+index 055d7842668..f4644f19d04 100644
+--- a/src/sage/rings/polynomial/polynomial_rational_flint.pxd
++++ b/src/sage/rings/polynomial/polynomial_rational_flint.pxd
+@@ -11,7 +11,7 @@ from sage.libs.flint.types cimport fmpq_poly_t
+ from sage.rings.polynomial.polynomial_element cimport Polynomial
+ 
+ cdef class Polynomial_rational_flint(Polynomial):
+-    cdef fmpq_poly_t __poly
++    cdef fmpq_poly_t _poly
+ 
+     cdef Polynomial_rational_flint _new(self)
+     cpdef _mod_(self, right)
+diff --git a/src/sage/rings/polynomial/polynomial_rational_flint.pyx b/src/sage/rings/polynomial/polynomial_rational_flint.pyx
+index d0dd15522e9..26d070ac77f 100644
+--- a/src/sage/rings/polynomial/polynomial_rational_flint.pyx
++++ b/src/sage/rings/polynomial/polynomial_rational_flint.pyx
+@@ -155,16 +155,16 @@ cdef class Polynomial_rational_flint(Polynomial):
+         res._parent = P
+         res._is_gen = <char>0
+         if isinstance(x, int):
+-            fmpq_poly_set_si(res.__poly, <int> x)
++            fmpq_poly_set_si(res._poly, <int> x)
+ 
+         elif isinstance(x, Integer):
+-            fmpq_poly_set_mpz(res.__poly, (<Integer> x).value)
++            fmpq_poly_set_mpz(res._poly, (<Integer> x).value)
+ 
+         elif isinstance(x, Rational):
+-            fmpq_poly_set_mpq(res.__poly, (<Rational> x).value)
++            fmpq_poly_set_mpq(res._poly, (<Rational> x).value)
+ 
+         else:
+-            fmpq_poly_set_si(res.__poly, int(x))
++            fmpq_poly_set_si(res._poly, int(x))
+         return res
+ 
+ 
+@@ -177,7 +177,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: R.<t> = QQ[]
+             sage: f = 2/3 * t - 7  #indirect doctest
+         """
+-        fmpq_poly_init(self.__poly)
++        fmpq_poly_init(self._poly)
+ 
+     def __dealloc__(self):
+         """
+@@ -189,7 +189,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: f = 1/3 * t
+             sage: del f
+         """
+-        fmpq_poly_clear(self.__poly)
++        fmpq_poly_clear(self._poly)
+ 
+     def __init__(self, parent, x=None, check=True, is_gen=False, construct=False):
+         """
+@@ -227,19 +227,19 @@ cdef class Polynomial_rational_flint(Polynomial):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+ 
+         if is_gen:
+-            fmpq_poly_set_coeff_si(self.__poly, 1, 1)
++            fmpq_poly_set_coeff_si(self._poly, 1, 1)
+ 
+         elif isinstance(x, Polynomial_rational_flint):
+-            fmpq_poly_set(self.__poly, (<Polynomial_rational_flint> x).__poly)
++            fmpq_poly_set(self._poly, (<Polynomial_rational_flint> x)._poly)
+ 
+         elif isinstance(x, int):
+-            fmpq_poly_set_si(self.__poly, <int> x)
++            fmpq_poly_set_si(self._poly, <int> x)
+ 
+         elif isinstance(x, Integer):
+-            fmpq_poly_set_mpz(self.__poly, (<Integer> x).value)
++            fmpq_poly_set_mpz(self._poly, (<Integer> x).value)
+ 
+         elif isinstance(x, Rational):
+-            fmpq_poly_set_mpq(self.__poly, (<Rational> x).value)
++            fmpq_poly_set_mpq(self._poly, (<Rational> x).value)
+ 
+         elif isinstance(x, list) or isinstance(x, tuple):
+ 
+@@ -257,7 +257,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             for deg from 0 <= deg < n:
+                 mpq_init(L2[deg])
+                 mpq_set(L2[deg], (<Rational> L1[deg]).value)
+-            fmpq_poly_set_array_mpq(self.__poly, L2, n)
++            fmpq_poly_set_array_mpq(self._poly, L2, n)
+             for deg from 0 <= deg < n:
+                 mpq_clear(L2[deg])
+             sig_free(L2)
+@@ -266,13 +266,13 @@ cdef class Polynomial_rational_flint(Polynomial):
+ #           deg = 0
+ #           for e in x:
+ #               c = Rational(e)
+-#               fmpq_poly_set_coeff_mpq(self.__poly, deg, c.value)
++#               fmpq_poly_set_coeff_mpq(self._poly, deg, c.value)
+ #               deg += 1
+ 
+         elif isinstance(x, dict):
+             for deg, e in x.iteritems():
+                 c = Rational(e)
+-                fmpq_poly_set_coeff_mpq(self.__poly, deg, c.value)
++                fmpq_poly_set_coeff_mpq(self._poly, deg, c.value)
+ 
+         elif isinstance(x, pari_gen):
+             k = self._parent.base_ring()
+@@ -281,7 +281,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+                                              is_gen=False, construct=construct)
+ 
+         elif isinstance(x, Polynomial_integer_dense_flint):
+-            fmpq_poly_set_fmpz_poly(self.__poly, (<Polynomial_integer_dense_flint>x).__poly)
++            fmpq_poly_set_fmpz_poly(self._poly, (<Polynomial_integer_dense_flint>x)._poly)
+ 
+         elif isinstance(x, Polynomial):
+             k = self._parent.base_ring()
+@@ -329,7 +329,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             True
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        fmpq_poly_set(res.__poly, self.__poly)
++        fmpq_poly_set(res._poly, self._poly)
+         return res
+ 
+     def _singular_(self, singular=singular_default):
+@@ -364,7 +364,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: g.list()
+             []
+         """
+-        cdef unsigned long length = fmpq_poly_length(self.__poly)
++        cdef unsigned long length = fmpq_poly_length(self._poly)
+         return [self.get_unsafe(n) for n in range(length)]
+ 
+     ###########################################################################
+@@ -392,7 +392,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: type(f.degree())
+             <class 'sage.rings.integer.Integer'>
+         """
+-        return smallInteger(fmpq_poly_degree(self.__poly))
++        return smallInteger(fmpq_poly_degree(self._poly))
+ 
+     cdef get_unsafe(self, Py_ssize_t n):
+         """
+@@ -413,7 +413,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             1/2*t^2 + t + 1
+         """
+         cdef Rational z = Rational.__new__(Rational)
+-        fmpq_poly_get_coeff_mpq(z.value, self.__poly, n)
++        fmpq_poly_get_coeff_mpq(z.value, self._poly, n)
+         return z
+ 
+     cpdef _unsafe_mutate(self, unsigned long n, value):
+@@ -434,24 +434,24 @@ cdef class Polynomial_rational_flint(Polynomial):
+         rely on this convention.  This method should be used only with the
+         utmost care.
+         """
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if isinstance(value, int):
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_si(self.__poly, n, value)
++            fmpq_poly_set_coeff_si(self._poly, n, value)
+             if do_sig: sig_off()
+         elif isinstance(value, Integer):
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_mpz(self.__poly, n, (<Integer> value).value)
++            fmpq_poly_set_coeff_mpz(self._poly, n, (<Integer> value).value)
+             if do_sig: sig_off()
+         elif isinstance(value, Rational):
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_mpq(self.__poly, n, (<Rational> value).value)
++            fmpq_poly_set_coeff_mpq(self._poly, n, (<Rational> value).value)
+             if do_sig: sig_off()
+         else:
+             value = Rational(value)
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_mpq(self.__poly, n, (<Rational> value).value)
++            fmpq_poly_set_coeff_mpq(self._poly, n, (<Rational> value).value)
+             if do_sig: sig_off()
+ 
+     def __call__(self, *x, **kwds):
+@@ -501,20 +501,20 @@ cdef class Polynomial_rational_flint(Polynomial):
+             if isinstance(a, Polynomial_rational_flint):
+                 f = (<Polynomial_rational_flint> a)._new()
+                 sig_str("FLINT exception")
+-                fmpq_poly_compose(f.__poly, self.__poly,
+-                    (<Polynomial_rational_flint> a).__poly)
++                fmpq_poly_compose(f._poly, self._poly,
++                    (<Polynomial_rational_flint> a)._poly)
+                 sig_off()
+                 return f
+             elif isinstance(a, Rational):
+                 r = Rational.__new__(Rational)
+                 sig_str("FLINT exception")
+-                fmpq_poly_evaluate_mpq(r.value, self.__poly, (<Rational> a).value)
++                fmpq_poly_evaluate_mpq(r.value, self._poly, (<Rational> a).value)
+                 sig_off()
+                 return r
+             elif isinstance(a, Integer):
+                 r = Rational.__new__(Rational)
+                 sig_str("FLINT exception")
+-                fmpq_poly_evaluate_mpz(r.value, self.__poly, (<Integer> a).value)
++                fmpq_poly_evaluate_mpz(r.value, self._poly, (<Integer> a).value)
+                 sig_off()
+                 return r
+             elif isinstance(a, int):
+@@ -523,7 +523,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+                 fmpz_init(tmpfz)
+                 fmpq_init(tmpfq)
+                 fmpz_set_si(tmpfz, PyInt_AS_LONG(a))
+-                fmpq_poly_evaluate_fmpz(tmpfq, self.__poly, tmpfz)
++                fmpq_poly_evaluate_fmpz(tmpfq, self._poly, tmpfz)
+                 fmpq_get_mpq(r.value, tmpfq)
+                 fmpq_clear(tmpfq)
+                 fmpz_clear(tmpfz)
+@@ -533,18 +533,18 @@ cdef class Polynomial_rational_flint(Polynomial):
+                 arb_a = <RealBall> a
+                 arb_z = arb_a._new()
+                 sig_on()
+-                _arb_fmpz_poly_evaluate_arb(arb_z.value, fmpq_poly_numref(self.__poly),
+-                        fmpq_poly_length(self.__poly), arb_a.value, arb_a._parent._prec)
+-                arb_div_fmpz(arb_z.value, arb_z.value, fmpq_poly_denref(self.__poly), arb_a._parent._prec)
++                _arb_fmpz_poly_evaluate_arb(arb_z.value, fmpq_poly_numref(self._poly),
++                        fmpq_poly_length(self._poly), arb_a.value, arb_a._parent._prec)
++                arb_div_fmpz(arb_z.value, arb_z.value, fmpq_poly_denref(self._poly), arb_a._parent._prec)
+                 sig_off()
+                 return arb_z
+             if isinstance(a, ComplexBall):
+                 acb_a = <ComplexBall> a
+                 acb_z = acb_a._new()
+                 sig_on()
+-                _arb_fmpz_poly_evaluate_acb(acb_z.value, fmpq_poly_numref(self.__poly),
+-                        fmpq_poly_length(self.__poly), acb_a.value, acb_a._parent._prec)
+-                acb_div_fmpz(acb_z.value, acb_z.value, fmpq_poly_denref(self.__poly), acb_a._parent._prec)
++                _arb_fmpz_poly_evaluate_acb(acb_z.value, fmpq_poly_numref(self._poly),
++                        fmpq_poly_length(self._poly), acb_a.value, acb_a._parent._prec)
++                acb_div_fmpz(acb_z.value, acb_z.value, fmpq_poly_denref(self._poly), acb_a._parent._prec)
+                 sig_off()
+                 return acb_z
+ 
+@@ -570,14 +570,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res
+         cdef bint do_sig
+ 
+-        if (n >= fmpq_poly_length(self.__poly)):
++        if (n >= fmpq_poly_length(self._poly)):
+             return self
+         else:
+             res = self._new()
+             if n > 0:
+-                do_sig = _do_sig(self.__poly)
++                do_sig = _do_sig(self._poly)
+                 if do_sig: sig_str("FLINT exception")
+-                fmpq_poly_get_slice(res.__poly, self.__poly, 0, n)
++                fmpq_poly_get_slice(res._poly, self._poly, 0, n)
+                 if do_sig: sig_off()
+             return res
+ 
+@@ -664,7 +664,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef bint do_sig
+ 
+         if degree is None:
+-            len = fmpq_poly_length(self.__poly)
++            len = fmpq_poly_length(self._poly)
+         else:
+             try:
+                 len = <unsigned long> (degree + 1)
+@@ -672,9 +672,9 @@ cdef class Polynomial_rational_flint(Polynomial):
+                 raise ValueError('degree must be convertible to long')
+ 
+         res = self._new()
+-        do_sig = _do_sig(self.__poly)
++        do_sig = _do_sig(self._poly)
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_reverse(res.__poly, self.__poly, len)
++        fmpq_poly_reverse(res._poly, self._poly, len)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -709,7 +709,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             raise ValueError("self must have constant coefficient 0 and a unit for coefficient {}^1".format(self.parent().gen()))
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_revert_series(res.__poly, self.__poly, m)
++        fmpq_poly_revert_series(res._poly, self._poly, m)
+         sig_off()
+ 
+         return res
+@@ -731,7 +731,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: R(0).is_zero()
+             True
+         """
+-        return fmpq_poly_is_zero(self.__poly)
++        return fmpq_poly_is_zero(self._poly)
+ 
+     cpdef bint is_one(self) except -1:
+         r"""
+@@ -751,7 +751,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: R([1,1]).is_one()
+             False
+         """
+-        return fmpq_poly_is_one(self.__poly)
++        return fmpq_poly_is_one(self._poly)
+ 
+     def __bool__(self):
+         """
+@@ -766,7 +766,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: bool(R(0))
+             False
+         """
+-        return not fmpq_poly_is_zero(self.__poly)
++        return not fmpq_poly_is_zero(self._poly)
+ 
+     ###########################################################################
+     # Shifting                                                                #
+@@ -794,14 +794,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res
+         cdef bint do_sig
+ 
+-        if k == 0 or fmpq_poly_is_zero(f.__poly):
++        if k == 0 or fmpq_poly_is_zero(f._poly):
+             return self
+         else:
+             res = f._new()
+-            do_sig = fmpq_poly_length(f.__poly) > 5000 or n > 5000
++            do_sig = fmpq_poly_length(f._poly) > 5000 or n > 5000
+ 
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_shift_left(res.__poly, f.__poly, k)
++            fmpq_poly_shift_left(res._poly, f._poly, k)
+             if do_sig: sig_off()
+             return res
+ 
+@@ -822,14 +822,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res
+         cdef bint do_sig
+ 
+-        if k == 0 or fmpq_poly_is_zero(f.__poly):
++        if k == 0 or fmpq_poly_is_zero(f._poly):
+             return self
+         else:
+             res = f._new()
+-            do_sig = _do_sig(f.__poly)
++            do_sig = _do_sig(f._poly)
+ 
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_shift_right(res.__poly, f.__poly, k)
++            fmpq_poly_shift_right(res._poly, f._poly, k)
+             if do_sig: sig_off()
+             return res
+ 
+@@ -858,10 +858,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_add(res.__poly, self.__poly, op2.__poly)
++        fmpq_poly_add(res._poly, self._poly, op2._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -886,10 +886,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_sub(res.__poly, self.__poly, op2.__poly)
++        fmpq_poly_sub(res._poly, self._poly, op2._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -912,10 +912,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             True
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_neg(res.__poly, self.__poly)
++        fmpq_poly_neg(res._poly, self._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -945,8 +945,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint rr = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_divrem(qq.__poly, rr.__poly, self.__poly,
+-                         (<Polynomial_rational_flint> right).__poly)
++        fmpq_poly_divrem(qq._poly, rr._poly, self._poly,
++                         (<Polynomial_rational_flint> right)._poly)
+         sig_off()
+         return qq, rr
+ 
+@@ -974,8 +974,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_gcd(res.__poly, self.__poly,
+-                (<Polynomial_rational_flint> right).__poly)
++        fmpq_poly_gcd(res._poly, self._poly,
++                (<Polynomial_rational_flint> right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1001,8 +1001,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_lcm(res.__poly, self.__poly,
+-                      (<Polynomial_rational_flint> right).__poly)
++        fmpq_poly_lcm(res._poly, self._poly,
++                      (<Polynomial_rational_flint> right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1043,7 +1043,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint t = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_xgcd(d.__poly, s.__poly, t.__poly, self.__poly, (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_xgcd(d._poly, s._poly, t._poly, self._poly, (<Polynomial_rational_flint>right)._poly)
+         sig_off()
+         return d, s, t
+ 
+@@ -1069,10 +1069,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_mul(res.__poly, self.__poly, op2.__poly)
++        fmpq_poly_mul(res._poly, self._poly, op2._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -1103,13 +1103,13 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if n <= 0:
+             raise ValueError("n must be > 0")
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_mullow(res.__poly, self.__poly, op2.__poly, n)
++        fmpq_poly_mullow(res._poly, self._poly, op2._poly, n)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -1125,10 +1125,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             9*t^3 - 6*t + 2
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_scalar_mul_mpq(res.__poly, self.__poly,
++        fmpq_poly_scalar_mul_mpq(res._poly, self._poly,
+                                  (<Rational> left).value)
+         if do_sig: sig_off()
+         return res
+@@ -1145,10 +1145,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             9*t^3 - 6*t + 2
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_scalar_mul_mpq(res.__poly, self.__poly,
++        fmpq_poly_scalar_mul_mpq(res._poly, self._poly,
+                                  (<Rational> right).value)
+         if do_sig: sig_off()
+         return res
+@@ -1272,27 +1272,27 @@ cdef class Polynomial_rational_flint(Polynomial):
+             num = r.numerator()
+             den = r.denominator()
+ 
+-            if fmpq_poly_degree(self.__poly) == 0:
++            if fmpq_poly_degree(self._poly) == 0:
+                 return self.parent()(self[0].nth_root(den) ** num)
+ 
+             return self.nth_root(den) ** num
+ 
+         else:
+             if n < 0:
+-                if fmpq_poly_is_zero(self.__poly):
++                if fmpq_poly_is_zero(self._poly):
+                     raise ZeroDivisionError("negative exponent in power of zero")
+                 res = self._new()
+                 sig_str("FLINT exception")
+-                fmpq_poly_pow(res.__poly, self.__poly, -n)
++                fmpq_poly_pow(res._poly, self._poly, -n)
+                 sig_off()
+                 return ~res
+             else:
+                 res = self._new()
+                 sig_str("FLINT exception")
+                 if self._is_gen:
+-                    fmpq_poly_set_coeff_si(res.__poly, n, 1)
++                    fmpq_poly_set_coeff_si(res._poly, n, 1)
+                 else:
+-                    fmpq_poly_pow(res.__poly, self.__poly, n)
++                    fmpq_poly_pow(res._poly, self._poly, n)
+                 sig_off()
+                 return res
+ 
+@@ -1328,10 +1328,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         if not isinstance(right, Polynomial_rational_flint):
+             if right in QQ:
+                 res = self._new()
+-                do_sig = _do_sig(self.__poly)
++                do_sig = _do_sig(self._poly)
+ 
+                 if do_sig: sig_str("FLINT exception")
+-                fmpq_poly_scalar_div_mpq(res.__poly, self.__poly,
++                fmpq_poly_scalar_div_mpq(res._poly, self._poly,
+                                                   (<Rational> QQ(right)).value)
+                 if do_sig: sig_off()
+                 return res
+@@ -1340,8 +1340,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+ 
+         res = self._new()
+         sig_str("FLINT exception")
+-        fmpq_poly_div(res.__poly, self.__poly,
+-                                     (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_div(res._poly, self._poly,
++                                     (<Polynomial_rational_flint>right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1381,15 +1381,15 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         if prec <= 0:
+             raise ValueError("the precision must be positive, got {}".format(prec))
+-        if fmpq_poly_degree(self.__poly) == -1 or \
+-           fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        if fmpq_poly_degree(self._poly) == -1 or \
++           fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term is zero")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         if prec <= 0:
+             return res
+         sig_on()
+-        fmpq_poly_inv_series(res.__poly, self.__poly, prec)
++        fmpq_poly_inv_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1423,8 +1423,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+ 
+         res = self._new()
+         sig_str("FLINT exception")
+-        fmpq_poly_rem(res.__poly, self.__poly,
+-                                     (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_rem(res._poly, self._poly,
++                                     (<Polynomial_rational_flint>right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1453,7 +1453,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+         Polynomial_integer_dense_flint.__init__(num, parent, x=None,
+                                     check=False, is_gen=False, construct=False)
+         sig_str("FLINT exception")
+-        fmpq_poly_get_numerator(num.__poly, self.__poly)
++        fmpq_poly_get_numerator(num._poly, self._poly)
+         sig_off()
+         return num
+ 
+@@ -1469,10 +1469,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             3
+         """
+         cdef Integer den = Integer.__new__(Integer)
+-        if fmpq_poly_denref(self.__poly) is NULL:
++        if fmpq_poly_denref(self._poly) is NULL:
+             mpz_set_ui(den.value, 1)
+         else:
+-            fmpz_get_mpz(den.value, <fmpz *> fmpq_poly_denref(self.__poly))
++            fmpz_get_mpz(den.value, <fmpz *> fmpq_poly_denref(self._poly))
+         return den
+ 
+     def _derivative(self, var = None):
+@@ -1517,10 +1517,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             raise ValueError("cannot differentiate with respect to {}".format(var))
+ 
+         der = self._new()
+-        do_sig = _do_sig(self.__poly)
++        do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_derivative(der.__poly, self.__poly)
++        fmpq_poly_derivative(der._poly, self._poly)
+         if do_sig: sig_off()
+         return der
+ 
+@@ -1574,8 +1574,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef fmpq_t t
+         fmpq_init(t)
+         sig_str("FLINT exception")
+-        fmpq_poly_resultant(t, self.__poly,
+-                            (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_resultant(t, self._poly,
++                            (<Polynomial_rational_flint>right)._poly)
+         fmpq_get_mpq(res.value, t)
+         sig_off()
+         fmpq_clear(t)
+@@ -1623,7 +1623,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+ 
+         """
+         cdef Polynomial_integer_dense_flint primitive
+-        cdef unsigned long length = fmpq_poly_length(self.__poly)
++        cdef unsigned long length = fmpq_poly_length(self._poly)
+ 
+         if length < 2:
+             return False
+@@ -1636,8 +1636,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+                              x=None, check=True, is_gen=False, construct=False)
+ 
+             sig_str("FLINT exception")
+-            fmpq_poly_get_numerator(primitive.__poly, self.__poly)
+-            fmpz_poly_primitive_part(primitive.__poly, primitive.__poly)
++            fmpq_poly_get_numerator(primitive._poly, self._poly)
++            fmpz_poly_primitive_part(primitive._poly, primitive._poly)
+             sig_off()
+             return primitive.is_irreducible()
+ 
+@@ -1669,14 +1669,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             ...
+             ValueError: constant term should be 1 in order to take logarithm
+         """
+-        if fmpq_poly_degree(self.__poly) == -1 or \
+-           fmpz_cmp(fmpq_poly_numref(self.__poly),
+-                    fmpq_poly_denref(self.__poly)):
++        if fmpq_poly_degree(self._poly) == -1 or \
++           fmpz_cmp(fmpq_poly_numref(self._poly),
++                    fmpq_poly_denref(self._poly)):
+             raise ValueError("constant term should be 1 in order to take logarithm")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_log_series(res.__poly, self.__poly, prec)
++        fmpq_poly_log_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1703,14 +1703,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.one()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take exponential")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_exp_series(res.__poly, self.__poly, prec)
++        fmpq_poly_exp_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1737,14 +1737,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take arctangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_atan_series(res.__poly, self.__poly, prec)
++        fmpq_poly_atan_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1768,14 +1768,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic arctangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_atanh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_atanh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1802,14 +1802,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take arcsine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_asin_series(res.__poly, self.__poly, prec)
++        fmpq_poly_asin_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1837,14 +1837,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic arcsine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_asinh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_asinh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1871,14 +1871,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take tangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_tan_series(res.__poly, self.__poly, prec)
++        fmpq_poly_tan_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1905,14 +1905,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take sine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_sin_series(res.__poly, self.__poly, prec)
++        fmpq_poly_sin_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1937,14 +1937,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take cosine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_cos_series(res.__poly, self.__poly, prec)
++        fmpq_poly_cos_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1969,14 +1969,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic sine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_sinh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_sinh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -2007,14 +2007,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.one()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic cosine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_cosh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_cosh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -2040,14 +2040,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic tangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_tanh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_tanh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+diff --git a/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx b/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx
+index fbe96d186c5..955f83468e4 100644
+--- a/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx
++++ b/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx
+@@ -116,7 +116,7 @@ cdef class PolynomialRealDense(Polynomial):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+         self._base_ring = parent._base
+         cdef Py_ssize_t i, degree
+-        cdef int prec = self._base_ring.__prec
++        cdef int prec = self._base_ring._prec
+         cdef mpfr_rnd_t rnd = self._base_ring.rnd
+         if x is None:
+             self._coeffs = <mpfr_t*>check_allocarray(1, sizeof(mpfr_t)) # degree zero
+@@ -227,7 +227,7 @@ cdef class PolynomialRealDense(Polynomial):
+ 
+     cdef PolynomialRealDense _new(self, Py_ssize_t degree):
+         cdef Py_ssize_t i
+-        cdef int prec = self._base_ring.__prec
++        cdef int prec = self._base_ring._prec
+         cdef PolynomialRealDense f = <PolynomialRealDense>PolynomialRealDense.__new__(PolynomialRealDense)
+         f._parent = self._parent
+         f._base_ring = self._base_ring
+@@ -501,7 +501,7 @@ cdef class PolynomialRealDense(Polynomial):
+         else:
+             f = left._new(left._degree + right._degree)
+         sig_on()
+-        mpfr_init2(tmp, left._base_ring.__prec)
++        mpfr_init2(tmp, left._base_ring._prec)
+         for i from 0 <= i <= f._degree:
+             # Yes, we could make this more efficient by initializing with
+             # a multiple of left rather than all zeros...
+@@ -661,7 +661,7 @@ cdef class PolynomialRealDense(Polynomial):
+         q = self._new(self._degree - other._degree)
+         # This is the standard division algorithm
+         sig_on()
+-        mpfr_init2(tmp, self._base_ring.__prec)
++        mpfr_init2(tmp, self._base_ring._prec)
+         for i from self._degree >= i >= other._degree:
+             mpfr_set(q._coeffs[i-other._degree], r._coeffs[i], rnd)
+             for j from 0 <= j < other._degree:
+@@ -725,7 +725,7 @@ cdef class PolynomialRealDense(Polynomial):
+         cdef RealNumber x = <RealNumber>xx
+         cdef RealNumber res
+ 
+-        if (<RealField_class>x._parent).__prec < self._base_ring.__prec:
++        if (<RealField_class>x._parent)._prec < self._base_ring._prec:
+             res = RealNumber(x._parent)
+         else:
+             res = RealNumber(self._base_ring)
+diff --git a/src/sage/rings/polynomial/polynomial_zmod_flint.pyx b/src/sage/rings/polynomial/polynomial_zmod_flint.pyx
+index 253ab949fcc..4c480673861 100644
+--- a/src/sage/rings/polynomial/polynomial_zmod_flint.pyx
++++ b/src/sage/rings/polynomial/polynomial_zmod_flint.pyx
+@@ -110,7 +110,7 @@ cdef class Polynomial_zmod_flint(Polynomial_template):
+             return
+         elif isinstance(x, Polynomial_integer_dense_flint):
+             Polynomial_template.__init__(self, parent, 0, check, is_gen, construct)
+-            self._set_fmpz_poly((<Polynomial_integer_dense_flint>x).__poly)
++            self._set_fmpz_poly((<Polynomial_integer_dense_flint>x)._poly)
+             return
+         else:
+             if isinstance(x, ntl_zz_pX):
+diff --git a/src/sage/rings/power_series_mpoly.pxd b/src/sage/rings/power_series_mpoly.pxd
+index f822ecc1227..d358ada1356 100644
+--- a/src/sage/rings/power_series_mpoly.pxd
++++ b/src/sage/rings/power_series_mpoly.pxd
+@@ -3,6 +3,6 @@ from .power_series_ring_element cimport PowerSeries
+ 
+ cdef class PowerSeries_mpoly(PowerSeries):
+     cdef ModuleElement __f
+-    cdef object __poly
++    cdef object _poly
+     cdef object __list
+     cdef bint _truncated
+diff --git a/src/sage/rings/power_series_mpoly.pyx b/src/sage/rings/power_series_mpoly.pyx
+index 0c901a3557b..be59294e75b 100644
+--- a/src/sage/rings/power_series_mpoly.pyx
++++ b/src/sage/rings/power_series_mpoly.pyx
+@@ -65,7 +65,7 @@ cdef class PowerSeries_mpoly(PowerSeries):
+ 
+     def __reduce__(self):
+         # do *not* delete old versions.
+-        return make_powerseries_mpoly_v0, (self._parent, self.__f, self._prec, self.__is_gen)
++        return make_powerseries_mpoly_v0, (self._parent, self.__f, self._prec, self._is_gen)
+ 
+     def __call__(self, *args, **kwds):
+         if len(kwds) == 0 and len(args) == 1:
+@@ -92,10 +92,10 @@ cdef class PowerSeries_mpoly(PowerSeries):
+         return self.__list
+ 
+     def polynomial(self):
+-        if self.__poly is None:
++        if self._poly is None:
+             S = self.parent()._mpoly_ring()
+-            self.__poly = self.__f.polynomial(S.gens()[-1])
+-        return self.__poly
++            self._poly = self.__f.polynomial(S.gens()[-1])
++        return self._poly
+ 
+     def _mpoly(self):
+         return self.__f
+diff --git a/src/sage/rings/power_series_poly.pyx b/src/sage/rings/power_series_poly.pyx
+index 7c93168d4b1..6cacab1f0c8 100644
+--- a/src/sage/rings/power_series_poly.pyx
++++ b/src/sage/rings/power_series_poly.pyx
+@@ -97,7 +97,7 @@ cdef class PowerSeries_poly(PowerSeries):
+             sage: f == loads(dumps(f)) # indirect doctest
+             True
+         """
+-        return self.__class__, (self._parent, self.__f, self._prec, self.__is_gen)
++        return self.__class__, (self._parent, self.__f, self._prec, self._is_gen)
+ 
+     def polynomial(self):
+         """
+diff --git a/src/sage/rings/power_series_ring_element.pxd b/src/sage/rings/power_series_ring_element.pxd
+index 067c4f3c6d4..e5c031ee147 100644
+--- a/src/sage/rings/power_series_ring_element.pxd
++++ b/src/sage/rings/power_series_ring_element.pxd
+@@ -1,7 +1,7 @@
+ from sage.structure.element cimport AlgebraElement, RingElement
+ 
+ cdef class PowerSeries(AlgebraElement):
+-    cdef char __is_gen
++    cdef char _is_gen
+     cdef _prec
+     cdef common_prec_c(self, PowerSeries other)
+     #_prec(self, RingElement right_r)
+diff --git a/src/sage/rings/power_series_ring_element.pyx b/src/sage/rings/power_series_ring_element.pyx
+index 54314d538ed..e5e2df79e1b 100644
+--- a/src/sage/rings/power_series_ring_element.pyx
++++ b/src/sage/rings/power_series_ring_element.pyx
+@@ -159,7 +159,7 @@ cdef class PowerSeries(AlgebraElement):
+              over Finite Field of size 3
+         """
+         AlgebraElement.__init__(self, parent)
+-        self.__is_gen = is_gen
++        self._is_gen = is_gen
+         self._prec = prec
+ 
+     def __hash__(self):
+@@ -234,7 +234,7 @@ cdef class PowerSeries(AlgebraElement):
+             sage: 1*t == t
+             True
+         """
+-        return bool(self.__is_gen)
++        return bool(self._is_gen)
+ 
+     def _im_gens_(self, codomain, im_gens, base_map=None):
+         """
+diff --git a/src/sage/rings/real_mpfi.pxd b/src/sage/rings/real_mpfi.pxd
+index 959a650aafc..4201788d198 100644
+--- a/src/sage/rings/real_mpfi.pxd
++++ b/src/sage/rings/real_mpfi.pxd
+@@ -11,7 +11,7 @@ from .real_mpfr cimport RealField_class
+ cdef class RealIntervalFieldElement(RingElement)  # forward decl
+ 
+ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+-    cdef mpfr_prec_t __prec
++    cdef mpfr_prec_t _prec
+     cdef bint sci_not
+     # Cache RealField instances for the lower, upper, and middle bounds.
+     # These have the same precision as the interval field;
+diff --git a/src/sage/rings/real_mpfi.pyx b/src/sage/rings/real_mpfi.pyx
+index 1193a14baff..509f6f63da0 100644
+--- a/src/sage/rings/real_mpfi.pyx
++++ b/src/sage/rings/real_mpfi.pyx
+@@ -526,7 +526,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         if prec < MPFR_PREC_MIN or prec > MPFR_PREC_MAX:
+             raise ValueError("prec (=%s) must be >= %s and <= %s." % (
+                 prec, MPFR_PREC_MIN, MPFR_PREC_MAX))
+-        self.__prec = prec
++        self._prec = prec
+         self.sci_not = sci_not
+         self.__lower_field = RealField(prec, sci_not, "RNDD")
+         self.__middle_field = RealField(prec, sci_not, "RNDN")
+@@ -598,7 +598,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         elif rnd == "RNDU":
+             return self.upper_field()
+         else:
+-            return RealField(self.__prec, self.sci_not, rnd)
++            return RealField(self._prec, self.sci_not, rnd)
+ 
+     def _repr_(self):
+         """
+@@ -611,7 +611,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RealIntervalField(200) # indirect doctest
+             Real Interval Field with 200 bits of precision
+         """
+-        s = "Real Interval Field with %s bits of precision"%self.__prec
++        s = "Real Interval Field with %s bits of precision"%self._prec
+         return s
+ 
+     def _latex_(self):
+@@ -802,7 +802,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RIF.has_coerce_map_from(float)
+             False
+         """
+-        prec = self.__prec
++        prec = self._prec
+ 
+         # Direct and efficient conversions
+         if S is ZZ or S is QQ:
+@@ -810,7 +810,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         if S is int or S is long:
+             return True
+         if isinstance(S, RealIntervalField_class):
+-            return (<RealIntervalField_class>S).__prec >= prec
++            return (<RealIntervalField_class>S)._prec >= prec
+         if isinstance(S, sage.rings.abc.NumberField_quadratic):
+             return S.discriminant() > 0
+ 
+@@ -844,7 +844,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         cdef RealIntervalField_class right
+         left = self
+         right = other  # to access C structure
+-        return richcmp(left.__prec, right.__prec, op)
++        return richcmp(left._prec, right._prec, op)
+ 
+     def __reduce__(self):
+         """
+@@ -856,7 +856,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: loads(dumps(R)) == R
+             True
+         """
+-        return __create__RealIntervalField_version0, (self.__prec, self.sci_not)
++        return __create__RealIntervalField_version0, (self._prec, self.sci_not)
+ 
+     def random_element(self, *args, **kwds):
+         """
+@@ -997,7 +997,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RealIntervalField(200).name()
+             'IntervalRealIntervalField200'
+         """
+-        return "IntervalRealIntervalField%s"%(self.__prec)
++        return "IntervalRealIntervalField%s"%(self._prec)
+ 
+     def __hash__(self):
+         """
+@@ -1023,7 +1023,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RealIntervalField(200).precision()
+             200
+         """
+-        return self.__prec
++        return self._prec
+ 
+     prec = precision
+ 
+@@ -1187,7 +1187,7 @@ cdef class RealIntervalFieldElement(RingElement):
+             sage: TestSuite(x).run(skip=["_test_eq", "_test_pickling"])
+         """
+         cdef RealIntervalField_class p = <RealIntervalField_class?>parent
+-        mpfi_init2(self.value, p.__prec)
++        mpfi_init2(self.value, p._prec)
+         self._parent = p
+ 
+     def __init__(self, parent, x, int base=10):
+@@ -1864,7 +1864,7 @@ cdef class RealIntervalFieldElement(RingElement):
+ 
+         cdef mp_exp_t self_exp
+         cdef mpz_t self_zz
+-        cdef mpfr_prec_t prec = (<RealIntervalField_class>self._parent).__prec
++        cdef mpfr_prec_t prec = (<RealIntervalField_class>self._parent)._prec
+         cdef char *zz_str
+         cdef size_t zz_str_maxlen
+ 
+@@ -2977,7 +2977,7 @@ cdef class RealIntervalFieldElement(RingElement):
+             sage: RealIntervalField(200)(2.1).precision()
+             200
+         """
+-        return (<RealIntervalField_class>self._parent).__prec
++        return (<RealIntervalField_class>self._parent)._prec
+ 
+     prec = precision
+ 
+diff --git a/src/sage/rings/real_mpfr.pxd b/src/sage/rings/real_mpfr.pxd
+index 3549eccfd03..dd18e87715b 100644
+--- a/src/sage/rings/real_mpfr.pxd
++++ b/src/sage/rings/real_mpfr.pxd
+@@ -9,7 +9,7 @@ from sage.libs.mpfr.types cimport mpfr_prec_t
+ cdef class RealNumber(sage.structure.element.RingElement)  # forward decl
+ 
+ cdef class RealField_class(sage.rings.abc.RealField):
+-    cdef mpfr_prec_t __prec
++    cdef mpfr_prec_t _prec
+     cdef bint sci_not
+     cdef mpfr_rnd_t rnd
+     cdef object rnd_str
+diff --git a/src/sage/rings/real_mpfr.pyx b/src/sage/rings/real_mpfr.pyx
+index ea7ff07a216..7440fadd265 100644
+--- a/src/sage/rings/real_mpfr.pyx
++++ b/src/sage/rings/real_mpfr.pyx
+@@ -524,7 +524,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+         if prec < MPFR_PREC_MIN or prec > MPFR_PREC_MAX:
+             raise ValueError("prec (=%s) must be >= %s and <= %s" % (
+                 prec, MPFR_PREC_MIN, MPFR_PREC_MAX))
+-        self.__prec = prec
++        self._prec = prec
+         self.sci_not = sci_not
+ 
+         self.rnd = <mpfr_rnd_t>rnd
+@@ -561,7 +561,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: RealField(17,rnd='RNDD') # indirect doctest
+             Real Field with 17 bits of precision and rounding RNDD
+         """
+-        s = "Real Field with %s bits of precision"%self.__prec
++        s = "Real Field with %s bits of precision"%self._prec
+         if self.rnd != MPFR_RNDN:
+             s = s + " and rounding %s"%(self.rnd_str)
+         return s
+@@ -733,13 +733,13 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             return ZZtoRR(ZZ, self)
+         elif S is QQ:
+             return QQtoRR(QQ, self)
+-        elif (S is RDF or S is float) and self.__prec <= 53:
++        elif (S is RDF or S is float) and self._prec <= 53:
+             return double_toRR(S, self)
+         elif S is long:
+             return int_toRR(long, self)
+         elif S is int:
+             return int_toRR(int, self)
+-        elif isinstance(S, RealField_class) and S.prec() >= self.__prec:
++        elif isinstance(S, RealField_class) and S.prec() >= self._prec:
+             return RRtoRR(S, self)
+         elif QQ.has_coerce_map_from(S):
+             return QQtoRR(QQ, self) * QQ._internal_coerce_map_from(S)
+@@ -786,7 +786,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             return NotImplemented
+ 
+         _other = <RealField_class>other  # to access C structure
+-        return (self.__prec == _other.__prec and
++        return (self._prec == _other._prec and
+                 self.rnd == _other.rnd) == (op == Py_EQ)
+ 
+     def __reduce__(self):
+@@ -799,7 +799,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: loads(dumps(R)) == R
+             True
+         """
+-        return __create__RealField_version0, (self.__prec, self.sci_not, self.rnd_str)
++        return __create__RealField_version0, (self._prec, self.sci_not, self.rnd_str)
+ 
+     def construction(self):
+         r"""
+@@ -968,7 +968,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: RealField(100,rnd='RNDU').name()
+             'RealField100_2'
+         """
+-        return "RealField%s_%s"%(self.__prec,self.rnd)
++        return "RealField%s_%s"%(self._prec,self.rnd)
+ 
+     def __hash__(self):
+         """
+@@ -995,7 +995,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: RealField(20).precision()
+             20
+         """
+-        return Integer(self.__prec)
++        return Integer(self._prec)
+ 
+     prec=precision # an alias
+ 
+@@ -1031,7 +1031,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: R.to_prec(300)
+             Real Field with 300 bits of precision and rounding RNDZ
+         """
+-        if prec == self.__prec:
++        if prec == self._prec:
+             return self
+         else:
+             return RealField(prec, self.sci_not, self.rnd)
+@@ -1052,7 +1052,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             0.88622692545275801364908374167057259139877473
+         """
+         cdef RealNumber x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD: sig_on()
+         # The docs for mpfr_free_cache say "Free the cache used by
+         # the functions computing constants if needed (currently
+         # mpfr_const_log2, mpfr_const_pi and mpfr_const_euler)", so
+@@ -1062,7 +1062,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+         # functions, but this free is needed for them too!
+         mpfr_free_cache()
+         mpfr_const_pi(x.value, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def euler_constant(self):
+@@ -1091,10 +1091,10 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             0.91596559417721901505460351493
+         """
+         cdef RealNumber x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_free_cache()
+         mpfr_const_catalan(x.value, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log2(self):
+@@ -1111,10 +1111,10 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             0.69314718055994530941723212146
+         """
+         cdef RealNumber x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_free_cache()
+         mpfr_const_log2(x.value, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def random_element(self, min=-1, max=1, distribution=None):
+@@ -1181,9 +1181,9 @@ cdef class RealField_class(sage.rings.abc.RealField):
+         if n < 0:
+             raise ArithmeticError("n must be nonnegative")
+         x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_on()
+         mpfr_fac_ui(x.value, n, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def rounding_mode(self):
+@@ -1346,7 +1346,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             NaN
+         """
+         cdef RealField_class p = <RealField_class?>parent
+-        mpfr_init2(self.value, p.__prec)
++        mpfr_init2(self.value, p._prec)
+         self._parent = p
+ 
+     def __init__(self, parent, x=0, int base=10):
+@@ -1446,7 +1446,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             sage: numpy.array([1.000000000000000000000000000000000000]).dtype           # optional - numpy
+             dtype('O')
+         """
+-        if (<RealField_class>self._parent).__prec <= 53:
++        if (<RealField_class>self._parent)._prec <= 53:
+             return numpy_double_interface
+         else:
+             return numpy_object_interface
+@@ -2075,7 +2075,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             # This avoids the confusion a lot of people have with the last
+             # 1-2 binary digits being wrong due to rounding coming from
+             # representing numbers in binary.
+-            digits = <size_t>(((<RealField_class>self._parent).__prec - 1) * M_LN2_LN10)
++            digits = <size_t>(((<RealField_class>self._parent)._prec - 1) * M_LN2_LN10)
+             if digits < 2:
+                 digits = 2
+ 
+@@ -2303,7 +2303,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if sgn == 0:
+             return z
+ 
+-        cdef mpfr_prec_t prec = (<RealField_class>self._parent).__prec
++        cdef mpfr_prec_t prec = (<RealField_class>self._parent)._prec
+ 
+         if mpfr_inf_p(self.value):
+             mpz_set_ui(z.value, EXP_MAX+1-EXP_MIN)
+@@ -2757,7 +2757,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             sage: RealField(101)(-1).precision()
+             101
+         """
+-        return Integer((<RealField_class>self._parent).__prec)
++        return Integer((<RealField_class>self._parent)._prec)
+ 
+     prec = precision # alias
+ 
+@@ -3364,7 +3364,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         cdef unsigned long wordsize = sizeof(long)*8
+ 
+         cdef mpfr_prec_t prec
+-        prec = (<RealField_class>self._parent).__prec
++        prec = (<RealField_class>self._parent)._prec
+ 
+         # We round up the precision to the nearest multiple of wordsize.
+         cdef int rounded_prec
+@@ -3699,7 +3699,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         from .real_mpfi import RealIntervalField
+ 
+         cdef mpfr_rnd_t rnd = (<RealField_class>self._parent).rnd
+-        cdef mpfr_prec_t prec = (<RealField_class>self._parent).__prec
++        cdef mpfr_prec_t prec = (<RealField_class>self._parent)._prec
+ 
+         cdef RealNumber low, high
+         cdef int odd
+@@ -4249,9 +4249,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         cdef RealNumber x
+         if mpfr_cmp_ui(self.value, 0) >= 0:
+             x = self._new()
+-            if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_on()
++            if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_on()
+             mpfr_sqrt(x.value, self.value, (<RealField_class>self._parent).rnd)
+-            if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_off()
++            if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_off()
+             if all:
+                 if x.is_zero():
+                     return [x]
+@@ -4295,12 +4295,12 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             -1.42108547152020e-14
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_on()
+         mpfr_cbrt(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+-    def __pow(self, RealNumber exponent):
++    def _pow(self, RealNumber exponent):
+         """
+         Compute ``self`` raised to the power of exponent, rounded in the
+         direction specified by the parent of ``self``.
+@@ -4309,7 +4309,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+ 
+             sage: R = RealField(30)
+             sage: a = R('1.23456')
+-            sage: a.__pow(20.0)
++            sage: a._pow(20.0)
+             67.646297
+         """
+         cdef RealNumber x
+@@ -4435,9 +4435,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+                 return self._complex_number_().log(base)
+         if base is None or base == 'e':
+             x = self._new()
+-            if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++            if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+             mpfr_log(x.value, self.value, (<RealField_class>self._parent).rnd)
+-            if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++            if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+             return x
+         elif base == 10:
+             return self.log10()
+@@ -4476,9 +4476,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if self < 0:
+             return self._complex_number_().log(2)
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_log2(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log10(self):
+@@ -4513,9 +4513,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if self < 0:
+             return self._complex_number_().log(10)
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_log10(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log1p(self):
+@@ -4562,9 +4562,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if self < -1:
+             return (self+1.0)._complex_number_().log()
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_log1p(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def exp(self):
+@@ -4620,9 +4620,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             1.89117248253021e-10
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_exp2(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def exp10(self):
+@@ -4648,9 +4648,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             5.01187233627276e-33
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_exp10(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def expm1(self):
+@@ -4672,9 +4672,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             1.00000000000000e-16
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_expm1(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def eint(self):
+@@ -4694,9 +4694,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             -0.219383934395520
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_eint(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         return x
+ 
+     def cos(self):
+@@ -5125,9 +5125,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             _other = self._parent(other)
+ 
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > 10000: sig_on()
++        if (<RealField_class>self._parent)._prec > 10000: sig_on()
+         mpfr_agm(x.value, self.value, _other.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > 10000: sig_off()
++        if (<RealField_class>self._parent)._prec > 10000: sig_off()
+         return x
+ 
+     def erf(self):
+@@ -5280,9 +5280,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             0.886226925452758
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_gamma(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log_gamma(self):
+@@ -5306,10 +5306,10 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         cdef RealNumber x = self._new()
+         parent = (<RealField_class>self._parent)
+         if not mpfr_sgn(self.value) < 0:
+-            if parent.__prec > SIG_PREC_THRESHOLD:
++            if parent._prec > SIG_PREC_THRESHOLD:
+                 sig_on()
+             mpfr_lngamma(x.value, self.value, parent.rnd)
+-            if parent.__prec > SIG_PREC_THRESHOLD:
++            if parent._prec > SIG_PREC_THRESHOLD:
+                 sig_off()
+             return x
+         from sage.libs.mpmath.utils import call
+@@ -5534,7 +5534,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+ 
+         cdef RealField_class fld = <RealField_class>self._parent
+ 
+-        if algorithm == 0 and n <= 10000 / fld.__prec:
++        if algorithm == 0 and n <= 10000 / fld._prec:
+             # This is a rough estimate for when it is probably
+             # faster to call mpfr directly.  (This is a pretty
+             # good estimate on one particular machine, a
+@@ -5639,7 +5639,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+ 
+         from .real_mpfi import RealIntervalField
+ 
+-        cdef mpfr_prec_t prec = fld.__prec + 10
++        cdef mpfr_prec_t prec = fld._prec + 10
+ 
+         cdef RealNumber lower
+         cdef RealNumber upper
+diff --git a/src/sage/rings/ring.pxd b/src/sage/rings/ring.pxd
+index 9384f39f258..1322697688f 100644
+--- a/src/sage/rings/ring.pxd
++++ b/src/sage/rings/ring.pxd
+@@ -7,7 +7,7 @@ cdef class Ring(ParentWithGens):
+     cdef public object _one_element
+     cdef public object _zero_ideal
+     cdef public object _unit_ideal
+-    cdef public object __ideal_monoid
++    cdef public object _ideal_monoid
+ 
+ 
+ cdef class CommutativeRing(Ring):
+diff --git a/src/sage/rings/ring.pyx b/src/sage/rings/ring.pyx
+index 4cba2c9ba7f..8acf4383270 100644
+--- a/src/sage/rings/ring.pyx
++++ b/src/sage/rings/ring.pyx
+@@ -325,12 +325,12 @@ cdef class Ring(ParentWithGens):
+              by the ideal (x*y + y*z, x*x + x*y - y*x - y*y)
+ 
+         """
+-        if self.__ideal_monoid is not None:
+-            return self.__ideal_monoid
++        if self._ideal_monoid is not None:
++            return self._ideal_monoid
+         else:
+             from sage.rings.noncommutative_ideals import IdealMonoid_nc
+             M = IdealMonoid_nc(self)
+-            self.__ideal_monoid = M
++            self._ideal_monoid = M
+             return M
+ 
+     def ideal(self, *args, **kwds):
+@@ -1106,12 +1106,12 @@ cdef class Ring(ParentWithGens):
+             sage: R.<x>=QQ[]; R.ideal_monoid()
+             Monoid of ideals of Univariate Polynomial Ring in x over Rational Field
+         """
+-        if self.__ideal_monoid is not None:
+-            return self.__ideal_monoid
++        if self._ideal_monoid is not None:
++            return self._ideal_monoid
+         else:
+             from sage.rings.ideal_monoid import IdealMonoid
+             M = IdealMonoid(self)
+-            self.__ideal_monoid = M
++            self._ideal_monoid = M
+             return M
+ 
+     @cached_method
+@@ -1345,12 +1345,12 @@ cdef class CommutativeRing(Ring):
+             sage: R.<x>=QQ[]; R.ideal_monoid()
+             Monoid of ideals of Univariate Polynomial Ring in x over Rational Field
+         """
+-        if self.__ideal_monoid is not None:
+-            return self.__ideal_monoid
++        if self._ideal_monoid is not None:
++            return self._ideal_monoid
+         else:
+             from sage.rings.ideal_monoid import IdealMonoid
+             M = IdealMonoid(self)
+-            self.__ideal_monoid = M
++            self._ideal_monoid = M
+             return M
+ 
+     def extension(self, poly, name=None, names=None, **kwds):
+diff --git a/src/sage/schemes/elliptic_curves/mod_sym_num.pyx b/src/sage/schemes/elliptic_curves/mod_sym_num.pyx
+index 65742f28d72..296a6b5d075 100644
+--- a/src/sage/schemes/elliptic_curves/mod_sym_num.pyx
++++ b/src/sage/schemes/elliptic_curves/mod_sym_num.pyx
+@@ -730,7 +730,7 @@ cdef class ModularSymbolNumerical:
+         double _eps_plus, _eps_minus, _eps_unitary_plus, _eps_unitary_minus
+         public RealNumber _om1, _om2
+         object _E, _epsQs, _Mt, _Epari
+-        public dict __cached_methods
++        public dict _cached_methods
+         Rational _twist_q
+         Integer _D
+         int _global_sign
+@@ -785,7 +785,7 @@ cdef class ModularSymbolNumerical:
+         self._set_epsQs()
+         self._initialise_an_coefficients()
+         self._set_den_bounds()
+-        self.__cached_methods = {}
++        self._cached_methods = {}
+ 
+         # self.nc_sums = Integer(0)
+         # self.nc_direct = Integer(0)
+@@ -1357,7 +1357,7 @@ cdef class ModularSymbolNumerical:
+             sage: M(0)
+             1/5
+         """
+-        cadi = self.__cached_methods
++        cadi = self._cached_methods
+         for me in cadi:
+             cadi[me].clear_cache()
+ 
+@@ -1833,7 +1833,7 @@ cdef class ModularSymbolNumerical:
+ 
+         # if called with a previous (m,z,eps) but a larger eps,
+         # return the cached value
+-        cac = self.__cached_methods['_kappa'].cache
++        cac = self._cached_methods['_kappa'].cache
+         for ke in cac:
+             mm, zz, eeps = ke[0]
+             if mm == m and zz == z:
+@@ -2746,16 +2746,16 @@ cdef class ModularSymbolNumerical:
+             sage: ms = ModularSymbolNumerical(E)
+             sage: ms.manin_symbol(4,17)
+             1
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache # random
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache # random
+             {((1, 5, 1), ()): 1,
+             ((1, 15, 1), ()): -1,
+             ((1, 22, 1), ()): -1,
+             ((1, 32, 1), ()): 1}
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache[(1,15,1),()]
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache[(1,15,1),()]
+             -1
+             sage: ms.manin_symbol(4+17,-4)
+             0
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache # random
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache # random
+             {((1, 4, 1), ()): 0,
+             ((1, 5, 1), ()): 1,
+             ((1, 8, 1), ()): 1,
+@@ -2768,7 +2768,7 @@ cdef class ModularSymbolNumerical:
+             ((1, 29, 1), ()): 1,
+             ((1, 32, 1), ()): 1,
+             ((1, 33, 1), ()): 0}
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache[ (1,23,1), () ]
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache[ (1,23,1), () ]
+             -1
+         """
+         cdef:
+@@ -2903,7 +2903,7 @@ cdef class ModularSymbolNumerical:
+         #        "(%s :%s)"%(un, vn), level=3)
+ 
+         # is it already in the cache ?
+-        c = self.__cached_methods
++        c = self._cached_methods
+         if "_manin_symbol_with_cache" in c:
+             c = c["_manin_symbol_with_cache"]
+             if c.is_in_cache(un,vn,sign):
+@@ -2919,7 +2919,7 @@ cdef class ModularSymbolNumerical:
+         # we get for free additional values of Manin
+         # symbols that we cache, too.
+         # This sets 6 values in average
+-        c = self.__cached_methods["_manin_symbol_with_cache"]
++        c = self._cached_methods["_manin_symbol_with_cache"]
+ 
+         # (-v:u) = - (u:v)
+         oi = proj_normalise(self._N_E, -v, u, &un, &vn)
+diff --git a/src/sage/sets/set_from_iterator.py b/src/sage/sets/set_from_iterator.py
+index c47bb76920b..11f12e6d5ea 100644
+--- a/src/sage/sets/set_from_iterator.py
++++ b/src/sage/sets/set_from_iterator.py
+@@ -214,12 +214,12 @@ def __reduce__(self):
+             True
+         """
+         return (EnumeratedSetFromIterator,
+-                (self._func,                            # func
+-                 getattr(self, '_args', None),          # args
+-                 getattr(self, '_kwds', None),          # kwds
+-                 getattr(self, '__custom_name', None),  # name
+-                 self.category(),                       # category
+-                 hasattr(self, '_cache'))               # cache
++                (self._func,                    # func
++                 getattr(self, '_args', None),  # args
++                 getattr(self, '_kwds', None),  # kwds
++                 self.get_custom_name(),        # name
++                 self.category(),               # category
++                 hasattr(self, '_cache'))       # cache
+                 )
+ 
+     def _repr_(self):
+diff --git a/src/sage/structure/category_object.pxd b/src/sage/structure/category_object.pxd
+index ff3088ae9b6..83d3d4967d4 100644
+--- a/src/sage/structure/category_object.pxd
++++ b/src/sage/structure/category_object.pxd
+@@ -13,7 +13,7 @@ from sage.structure.sage_object cimport SageObject
+ cpdef check_default_category(default_category, category)
+ 
+ cdef class CategoryObject(SageObject):
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+     cdef _category
+     cdef public _base
+     cdef public _names
+diff --git a/src/sage/structure/category_object.pyx b/src/sage/structure/category_object.pyx
+index 3859f24095a..b6a7eaecb5b 100644
+--- a/src/sage/structure/category_object.pyx
++++ b/src/sage/structure/category_object.pyx
+@@ -113,7 +113,7 @@ cdef class CategoryObject(SageObject):
+             self._init_category_(category)
+ 
+     def __cinit__(self):
+-        self.__cached_methods = {}
++        self._cached_methods = {}
+         self._hash_value = -1
+ 
+     def _init_category_(self, category):
+@@ -491,7 +491,7 @@ cdef class CategoryObject(SageObject):
+         """
+         return self.variable_names()[0]
+ 
+-    def __temporarily_change_names(self, names, latex_names):
++    def _temporarily_change_names(self, names, latex_names):
+         """
+         This is used by the variable names context manager.
+ 
+@@ -844,7 +844,7 @@ cdef class CategoryObject(SageObject):
+         # Lookup a method or attribute from the category abstract classes.
+         # See __getattr__ above for documentation.
+         try:
+-            return self.__cached_methods[name]
++            return self._cached_methods[name]
+         except KeyError:
+             if self._category is None:
+                 # Usually, this will just raise AttributeError in
+@@ -854,7 +854,7 @@ cdef class CategoryObject(SageObject):
+                 cls = self._category.parent_class
+ 
+             attr = getattr_from_other_class(self, cls, name)
+-            self.__cached_methods[name] = attr
++            self._cached_methods[name] = attr
+             return attr
+ 
+     def __dir__(self):
+diff --git a/src/sage/structure/element.pxd b/src/sage/structure/element.pxd
+index 79e86d8a5c3..20c556b985e 100644
+--- a/src/sage/structure/element.pxd
++++ b/src/sage/structure/element.pxd
+@@ -176,7 +176,7 @@ cdef class Element(SageObject):
+ 
+ 
+ cdef class ElementWithCachedMethod(Element):
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+ cdef class ModuleElement(Element)       # forward declaration
+ 
+diff --git a/src/sage/structure/element.pyx b/src/sage/structure/element.pyx
+index ab6ee157a94..36da1c0cc12 100644
+--- a/src/sage/structure/element.pyx
++++ b/src/sage/structure/element.pyx
+@@ -379,6 +379,7 @@ cdef class Element(SageObject):
+     .. automethod:: __mod__
+     """
+     @cython.binding(False)
++    @cython.always_allow_keywords(False)
+     def __getmetaclass__(_):
+         from sage.misc.inherit_comparison import InheritComparisonMetaclass
+         return InheritComparisonMetaclass
+@@ -2356,18 +2357,18 @@ cdef class ElementWithCachedMethod(Element):
+             True
+         """
+         try:
+-            return self.__cached_methods[name]
++            return self._cached_methods[name]
+         except KeyError:
+             attr = getattr_from_other_class(self,
+                                         self._parent.category().element_class,
+                                         name)
+-            self.__cached_methods[name] = attr
++            self._cached_methods[name] = attr
+             return attr
+         except TypeError:
+             attr = getattr_from_other_class(self,
+                                         self._parent.category().element_class,
+                                         name)
+-            self.__cached_methods = {name : attr}
++            self._cached_methods = {name : attr}
+             return attr
+ 
+ 
+diff --git a/src/sage/structure/parent_gens.pyx b/src/sage/structure/parent_gens.pyx
+index ab531314458..cc6ffaace21 100644
+--- a/src/sage/structure/parent_gens.pyx
++++ b/src/sage/structure/parent_gens.pyx
+@@ -371,7 +371,7 @@ cdef class localvars:
+             self._latex_names = latex_names
+ 
+     def __enter__(self):
+-        self._orig = self._obj.__temporarily_change_names(self._names, self._latex_names)
++        self._orig = self._obj._temporarily_change_names(self._names, self._latex_names)
+ 
+     def __exit__(self, type, value, traceback):
+-        self._obj.__temporarily_change_names(self._orig[0], self._orig[1])
++        self._obj._temporarily_change_names(self._orig[0], self._orig[1])
+diff --git a/src/sage/structure/sage_object.pyx b/src/sage/structure/sage_object.pyx
+index 8474142eaa1..10000aef394 100644
+--- a/src/sage/structure/sage_object.pyx
++++ b/src/sage/structure/sage_object.pyx
+@@ -69,6 +69,8 @@ cdef class SageObject:
+         r"""
+         Change self so it prints as x, where x is a string.
+ 
++        If x is ``None``, the existing custom name is removed.
++
+         .. NOTE::
+ 
+            This is *only* supported for Python classes that derive
+@@ -91,6 +93,9 @@ cdef class SageObject:
+             sage: h.rename('x^300 + ...')
+             sage: h
+             x^300 + ...
++            sage: g.rename(None)
++            sage: g
++            x^3 + x - 5
+ 
+         Real numbers are not Python classes, so rename is not supported::
+ 
+@@ -110,15 +115,16 @@ cdef class SageObject:
+            a lot of memory.
+ 
+            To support them for a specific class, add a
+-           ``cdef public __custom_name`` attribute.
++           ``cdef public _SageObject__custom_name`` attribute.
+         """
+         if x is None:
+-            #if hasattr(self, '__custom_name'):
+-            # that's tested in reset_name anyway...
+             self.reset_name()
+         else:
+             try:
+-                self.__custom_name = str(x)
++                # TODO: after dropping support for Cython < 3.0.0, all
++                # the self._SageObject__custom_name in this class can be
++                # changed to self.__custom_name
++                self._SageObject__custom_name = str(x)
+             except AttributeError:
+                 raise NotImplementedError("object does not support renaming: %s" % self)
+ 
+@@ -138,8 +144,30 @@ cdef class SageObject:
+             sage: P
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if hasattr(self, '__custom_name'):
+-            del self.__custom_name
++        if hasattr(self, '_SageObject__custom_name'):
++            del self._SageObject__custom_name
++
++    def get_custom_name(self):
++        """
++        Return the custom name of this object, or ``None`` if it is not
++        renamed.
++
++        EXAMPLES::
++
++            sage: P.<x> = QQ[]
++            sage: P.get_custom_name() is None
++            True
++            sage: P.rename('A polynomial ring')
++            sage: P.get_custom_name()
++            'A polynomial ring'
++            sage: P.reset_name()
++            sage: P.get_custom_name() is None
++            True
++        """
++        try:
++            return self._SageObject__custom_name
++        except AttributeError:
++            return None
+ 
+     def __repr__(self):
+         """
+@@ -181,7 +209,7 @@ cdef class SageObject:
+             <sage.structure.sage_object.SageObject object at ...>
+         """
+         try:
+-            name = self.__custom_name
++            name = self._SageObject__custom_name
+             if name is not None:
+                 return name
+         except AttributeError:
+diff --git a/src/sage/topology/simplicial_set.py b/src/sage/topology/simplicial_set.py
+index 42cc3f77780..3ee14ae2da8 100644
+--- a/src/sage/topology/simplicial_set.py
++++ b/src/sage/topology/simplicial_set.py
+@@ -570,13 +570,12 @@ def __lt__(self, other):
+             return True
+         if self.degeneracies() and other.degeneracies() and self.degeneracies() != other.degeneracies():
+             return self.degeneracies() < other.degeneracies()
+-        if hasattr(self.nondegenerate(), '__custom_name'):
+-            if hasattr(other.nondegenerate(), '__custom_name'):
+-                return str(self) < str(other)
++        if self.nondegenerate().get_custom_name() is not None:
++            if other.nondegenerate().get_custom_name() is not None:
++                return self.nondegenerate().get_custom_name() < other.nondegenerate().get_custom_name()
+             return True
+ 
+-        if (hasattr(other, '__custom_name')
+-                or hasattr(other.nondegenerate(), '__custom_name')):
++        if other.nondegenerate().get_custom_name() is not None:
+             return False
+         return id(self) < id(other)
+ 
+@@ -793,8 +792,8 @@ def __copy__(self):
+         # dimension, the degeneracies, and the name (with a prime
+         # added).
+         sigma = AbstractSimplex(self._dim, degeneracies=self.degeneracies())
+-        if hasattr(self, '__custom_name'):
+-            sigma.rename(str(self) + "'")
++        if self.get_custom_name() is not None:
++            sigma.rename(self.get_custom_name() + "'")
+         return sigma
+ 
+     def __deepcopy__(self, memo):
+@@ -839,8 +838,8 @@ def __deepcopy__(self, memo):
+             return memo[underlying].apply_degeneracies(*degens)
+         except KeyError:
+             sigma = AbstractSimplex(underlying._dim)
+-            if hasattr(underlying, '__custom_name'):
+-                sigma.rename(str(self) + "'")
++            if underlying.get_custom_name() is not None:
++                sigma.rename(underlying.get_custom_name() + "'")
+             memo[underlying] = sigma
+             return sigma.apply_degeneracies(*degens)
+ 
+@@ -896,12 +895,12 @@ def _latex_(self):
+         """
+         if self._latex_name is not None:
+             return self._latex_name
+-        if hasattr(self, '__custom_name'):
+-            return str(self)
++        if self.get_custom_name() is not None:
++            return self.get_custom_name()
+         if self.nondegenerate()._latex_name is not None:
+             simplex = self.nondegenerate()._latex_name
+-        elif hasattr(self.nondegenerate(), '__custom_name'):
+-            simplex = str(self.nondegenerate())
++        elif self.nondegenerate().get_custom_name() is not None:
++            simplex = self.nondegenerate().get_custom_name()
+         else:
+             simplex = "\\Delta^{{{}}}".format(self._dim)
+         if self.degeneracies():
+diff --git a/src/sage/topology/simplicial_set_constructions.py b/src/sage/topology/simplicial_set_constructions.py
+index ae98821df8a..3a217286ac5 100644
+--- a/src/sage/topology/simplicial_set_constructions.py
++++ b/src/sage/topology/simplicial_set_constructions.py
+@@ -176,8 +176,7 @@ def __init__(self, data, ambient=None):
+         else:
+             SimplicialSet_finite.__init__(self, data)
+         if self == ambient:
+-            if hasattr(ambient, '__custom_name'):
+-                self.rename(str(ambient))
++            self.rename(ambient.get_custom_name())
+             self._latex_name = latex(ambient)
+         # When constructing the inclusion map, we do not need to check
+         # the validity of the morphism, and more importantly, we
diff --git a/srcpkgs/sagemath/patches/build-cython3.patch b/srcpkgs/sagemath/patches/build-cython3.patch
new file mode 100644
index 0000000000000..57d1ade89fc77
--- /dev/null
+++ b/srcpkgs/sagemath/patches/build-cython3.patch
@@ -0,0 +1,44 @@
+diff --git a/src/sage/ext/stdsage.pxd b/src/sage/ext/stdsage.pxd
+index 15abe13b7cd..e2bf7434f35 100644
+--- a/src/sage/ext/stdsage.pxd
++++ b/src/sage/ext/stdsage.pxd
+@@ -10,7 +10,7 @@ Standard C helper code for Cython modules
+ #                  http://www.gnu.org/licenses/
+ #*****************************************************************************
+ 
+-from cpython.object cimport Py_TYPE, PyTypeObject
++from cpython.object cimport Py_TYPE, PyTypeObject, PyObject
+ 
+ 
+ cdef inline PY_NEW(type t):
+@@ -19,7 +19,7 @@ cdef inline PY_NEW(type t):
+     :class:`Integer` where we change ``tp_new`` at runtime (Cython
+     optimizations assume that ``tp_new`` doesn't change).
+     """
+-    return (<PyTypeObject*>t).tp_new(t, <object>NULL, <object>NULL)
++    return (<PyTypeObject*>t).tp_new(t, <PyObject*>NULL, <PyObject*>NULL)
+ 
+ 
+ cdef inline void PY_SET_TP_NEW(type dst, type src):
+diff --git a/src/sage_setup/cython_options.py b/src/sage_setup/cython_options.py
+index 086aa070ca9..9725ce0e1af 100644
+--- a/src/sage_setup/cython_options.py
++++ b/src/sage_setup/cython_options.py
+@@ -10,13 +10,17 @@ def compiler_directives(profile: bool):
+         auto_pickle=False,
+         # Do not create __test__ dictionary automatically from docstrings
+         autotestdict=False,
++        binding=False,
++        c_api_binop_methods=True,
+         # Do not check for division by 0 (this is about 35% quicker than with check)
+         cdivision=True,
++        cpow=True,
+         # Embed a textual copy of the call signature in the docstring (to support tools like IPython)
+         embedsignature=True,
+         fast_getattr=True,
+         # Use Python 3 (including source code semantics) for module compilation
+         language_level="3",
++        legacy_implicit_noexcept=True,
+         # Enable support for late includes (make declarations in Cython code available to C include files)
+         preliminary_late_includes_cy28=True,
+         # Add hooks for Python profilers into the compiled C code
diff --git a/srcpkgs/sagemath/patches/fix-doctest-cython3.patch b/srcpkgs/sagemath/patches/fix-doctest-cython3.patch
new file mode 100644
index 0000000000000..4cff1fb1828db
--- /dev/null
+++ b/srcpkgs/sagemath/patches/fix-doctest-cython3.patch
@@ -0,0 +1,207 @@
+diff --git a/src/doc/en/thematic_tutorials/coercion_and_categories.rst b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+index de2349a9a3f..bb23331c151 100644
+--- a/src/doc/en/thematic_tutorials/coercion_and_categories.rst
++++ b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+@@ -105,7 +105,7 @@ it makes sense to build on top of the base class
+ This base class provides a lot more methods than a general parent::
+ 
+     sage: [p for p in dir(Field) if p not in dir(Parent)]
+-    ['__fraction_field',
++    ['_CommutativeRing__fraction_field',
+      '__iter__',
+      '__len__',
+      '__rxor__',
+diff --git a/src/sage/arith/srange.pyx b/src/sage/arith/srange.pyx
+index 156e548a11a..132cf93d085 100644
+--- a/src/sage/arith/srange.pyx
++++ b/src/sage/arith/srange.pyx
+@@ -84,7 +84,7 @@ def xsrange(start, end=None, step=1, universe=None, *, coerce=True, bint include
+     EXAMPLES::
+ 
+         sage: xsrange(10)
+-        <generator object at 0x...>
++        <...generator object at 0x...>
+         sage: for i in xsrange(1,5):
+         ....:     print(i)
+         1
+diff --git a/src/sage/combinat/sloane_functions.py b/src/sage/combinat/sloane_functions.py
+index c3cf9299093..e5c99b71fe7 100644
+--- a/src/sage/combinat/sloane_functions.py
++++ b/src/sage/combinat/sloane_functions.py
+@@ -9169,7 +9169,7 @@ class Sloane(SageObject):
+         ::
+ 
+             sage: sloane.__repr__
+-            <method-wrapper '__repr__' of Sloane object at 0x...>
++            <built-in method __repr__ of Sloane object at 0x...>
+             sage: sloane.__name__
+             Traceback (most recent call last):
+             ...
+diff --git a/src/sage/misc/cachefunc.pyx b/src/sage/misc/cachefunc.pyx
+index 8aa30a85272..2b1d38c12b9 100644
+--- a/src/sage/misc/cachefunc.pyx
++++ b/src/sage/misc/cachefunc.pyx
+@@ -50,7 +50,7 @@ be used::
+     sage: cython('''cpdef test_funct(x): return -x''')                          # optional - sage.misc.cython
+     sage: wrapped_funct = cached_function(test_funct, name='wrapped_funct')     # optional - sage.misc.cython
+     sage: wrapped_funct                                                         # optional - sage.misc.cython
+-    Cached version of <built-in function test_funct>
++    Cached version of <cyfunction test_funct at ...>
+     sage: wrapped_funct.__name__                                                # optional - sage.misc.cython
+     'wrapped_funct'
+     sage: wrapped_funct(5)                                                      # optional - sage.misc.cython
+@@ -82,9 +82,9 @@ approach is still needed for cpdef methods::
+     sage: cython(os.linesep.join(cython_code))                                  # optional - sage.misc.cython
+     sage: O = MyClass()                                                         # optional - sage.misc.cython
+     sage: O.direct_method                                                       # optional - sage.misc.cython
+-    Cached version of <method 'direct_method' of '...MyClass' objects>
++    Cached version of <cyfunction MyClass.direct_method at ...>
+     sage: O.wrapped_method                                                      # optional - sage.misc.cython
+-    Cached version of <built-in function test_meth>
++    Cached version of <cyfunction test_meth at ...>
+     sage: O.wrapped_method.__name__                                             # optional - sage.misc.cython
+     'wrapped_method'
+     sage: O.wrapped_method(5)                                                   # optional - sage.misc.cython
+@@ -270,6 +270,7 @@ Introspection works::
+         "some doc for a wrapped cython method"
+         return -x
+     sage: print(sage_getsource(O.direct_method))                                # optional - sage.misc.cython
++    @cached_method
+     def direct_method(self, x):
+         "Some doc for direct method"
+         return 2*x
+diff --git a/src/sage/misc/lazy_import.pyx b/src/sage/misc/lazy_import.pyx
+index c33a1e74efd..7fc73407ace 100644
+--- a/src/sage/misc/lazy_import.pyx
++++ b/src/sage/misc/lazy_import.pyx
+@@ -1095,7 +1095,7 @@ def lazy_import(module, names, as_=None, *,
+         sage: from sage.features import PythonModule
+         sage: lazy_import('ppl', 'equation', feature=PythonModule('ppl', spkg='pplpy', type='standard'))
+         sage: equation
+-        <built-in function equation>
++        <cyfunction equation at ...>
+         sage: lazy_import('PyNormaliz', 'NmzListConeProperties', feature=PythonModule('PyNormaliz', spkg='pynormaliz'))  # optional - pynormaliz
+         sage: NmzListConeProperties  # optional - pynormaliz
+         <built-in function NmzListConeProperties>
+diff --git a/src/sage/misc/lazy_list.pyx b/src/sage/misc/lazy_list.pyx
+index ba62c446b69..cd750933860 100644
+--- a/src/sage/misc/lazy_list.pyx
++++ b/src/sage/misc/lazy_list.pyx
+@@ -678,7 +678,7 @@ cdef class lazy_list_generic():
+             sage: from itertools import count
+             sage: from sage.misc.lazy_list import lazy_list
+             sage: iter(lazy_list(count()))
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+ 
+         ::
+ 
+diff --git a/src/sage/misc/sageinspect.py b/src/sage/misc/sageinspect.py
+index ce5e9987027..df8e6bf89ac 100644
+--- a/src/sage/misc/sageinspect.py
++++ b/src/sage/misc/sageinspect.py
+@@ -76,8 +76,8 @@ Cython functions::
+     sage: sage_getdoc(sage.rings.rational.make_rational).lstrip()
+     'Make a rational number ...'
+ 
+-    sage: sage_getsource(sage.rings.rational.make_rational)[4:]
+-    'make_rational(s):...'
++    sage: sage_getsource(sage.rings.rational.make_rational)
++    '@cython.binding(True)\ndef make_rational(s):...'
+ 
+ Python functions::
+ 
+diff --git a/src/sage/modules/free_module_element.pyx b/src/sage/modules/free_module_element.pyx
+index d5e8256b68c..c9af9bcbdf7 100644
+--- a/src/sage/modules/free_module_element.pyx
++++ b/src/sage/modules/free_module_element.pyx
+@@ -1634,7 +1634,7 @@ cdef class FreeModuleElement(Vector):   # abstract base class
+ 
+             sage: v = vector([1,2/3,pi])
+             sage: v.items()
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: list(v.items())
+             [(0, 1), (1, 2/3), (2, pi)]
+ 
+diff --git a/src/sage/rings/finite_rings/finite_field_base.pyx b/src/sage/rings/finite_rings/finite_field_base.pyx
+index 7e2eed91153..3a6db8995c6 100644
+--- a/src/sage/rings/finite_rings/finite_field_base.pyx
++++ b/src/sage/rings/finite_rings/finite_field_base.pyx
+@@ -328,7 +328,7 @@ cdef class FiniteField(Field):
+             sage: p = next_prime(2^64)
+             sage: k.<a> = FiniteField(p^2, impl="pari")
+             sage: it = iter(k); it
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: [next(it) for i in range(10)]
+             [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+ 
+diff --git a/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx b/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx
+index 41951687939..c6b67cba5fb 100644
+--- a/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx
++++ b/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx
+@@ -629,7 +629,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense):
+             sage: S.<x> = k['x',Frob]
+             sage: a = x^4 + 2*t*x^3 + 3*t^2*x^2 + (t^2 + t + 1)*x + 4*t + 3
+             sage: iter = a.right_irreducible_divisors(); iter
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+             sage: next(iter)   # random
+             x + 2*t^2 + 4*t + 4
+             sage: next(iter)   # random
+@@ -664,7 +664,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense):
+             sage: S.<x> = k['x',Frob]
+             sage: a = x^4 + 2*t*x^3 + 3*t^2*x^2 + (t^2 + t + 1)*x + 4*t + 3
+             sage: iter = a.left_irreducible_divisors(); iter
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+             sage: next(iter)  # random
+             x + 3*t + 3
+             sage: next(iter)  # random
+@@ -1052,7 +1052,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense):
+             sage: S.<x> = k['x',Frob]
+             sage: a = x^3 + (t^2 + 1)*x^2 + (2*t + 3)*x + t^2 + t + 2
+             sage: iter = a.factorizations(); iter
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+             sage: next(iter)   # random
+             (x + 3*t^2 + 4*t) * (x + 2*t^2) * (x + 4*t^2 + 4*t + 2)
+             sage: next(iter)   # random
+diff --git a/src/sage/structure/coerce_dict.pyx b/src/sage/structure/coerce_dict.pyx
+index a2e8443084c..ef86c6af35c 100644
+--- a/src/sage/structure/coerce_dict.pyx
++++ b/src/sage/structure/coerce_dict.pyx
+@@ -777,7 +777,7 @@ cdef class MonoDict:
+             sage: L[1] = None
+             sage: L[2] = True
+             sage: L.items()
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: sorted(L.items())
+             [(1, None), (2, True)]
+         """
+@@ -1452,7 +1452,7 @@ cdef class TripleDict:
+             sage: L = TripleDict()
+             sage: L[1,2,3] = None
+             sage: L.items()
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: list(L.items())
+             [((1, 2, 3), None)]
+         """
+diff --git a/src/sage/tests/cmdline.py b/src/sage/tests/cmdline.py
+index ad0c44aa274..f14cd2db768 100644
+--- a/src/sage/tests/cmdline.py
++++ b/src/sage/tests/cmdline.py
+@@ -491,9 +491,8 @@ def test_executable(args, input="", timeout=100.0, pydebug_ignore_warnings=False
+ 
+         sage: (out, err, ret) = test_executable(["sage", "--cython"])
+         sage: print(err)
+-        Cython (http://cython.org) is a compiler for code written in the
+-        Cython language.  Cython is based on Pyrex by Greg Ewing.
+         ...
++        cython: error: cython: Need at least one source file
+ 
+         sage: def has_tty():
+         ....:     try:
diff --git a/srcpkgs/sagemath/patches/get_patches b/srcpkgs/sagemath/patches/get_patches
index 95a6963432948..64ffe14d15eb5 100755
--- a/srcpkgs/sagemath/patches/get_patches
+++ b/srcpkgs/sagemath/patches/get_patches
@@ -12,7 +12,7 @@ esac
 # get_pr <PR number> <description> [ext]
 get_pr() {
 	pr=$1
-	desc=$(echo "$2" | sed -e 's/ /_/g')
+	desc=$(echo "$2" | tr ' /' '_-')
 	ext=${3-diff}
 	$DO wget "$URL_BASE_PR$pr.$ext" -O "$pr-$desc.patch"
 }
@@ -26,6 +26,7 @@ get_pr  36046   "fix memory leak"
 
 # merged in 10.2.beta1
 get_pr  35934   "singular 4.3.2p7"
+get_pr  36109   "prepare for cython 3.0" # included in #36110
 
 # merged in 10.2.beta2
 get_pr  36006   "gmp 6.3.0"
diff --git a/srcpkgs/sagemath/template b/srcpkgs/sagemath/template
index a80d8b7187ece..ba8bd94d835d6 100644
--- a/srcpkgs/sagemath/template
+++ b/srcpkgs/sagemath/template
@@ -1,12 +1,12 @@
 # Template file for 'sagemath'
 pkgname=sagemath
 version=10.1
-revision=4
+revision=5
 build_wrksrc=pkgs/sagemath-standard
 build_style=python3-module
 _bindir=/usr/lib/sagemath/$version/bin
 make_install_args="--install-scripts=$_bindir"
-hostmakedepends="m4 pkg-config python3-Cython0.29 python3-Jinja2
+hostmakedepends="m4 pkg-config python3-Cython python3-Jinja2
  python3-pkgconfig python3-setuptools"
 makedepends="arb-devel boost-devel brial-devel cliquer-devel ecl eclib-devel
  ecm-devel fflas-ffpack flintlib-devel gap-devel gd-devel giac-devel glpk-devel
@@ -18,7 +18,7 @@ makedepends="arb-devel boost-devel brial-devel cliquer-devel ecl eclib-devel
 depends="eclib-devel fflas-ffpack flintlib-devel gcc-fortran gd-devel
  gfan giac gsl-devel gzip libpng-devel linbox-devel m4ri-devel maxima-ecl
  mpfr-devel nauty ntl-devel palp pari-devel pari-elldata-small pari-galdata
- pari-galpol-small pari-seadata-small pkg-config python3-Cython0.29 python3-cypari2
+ pari-galpol-small pari-seadata-small pkg-config python3-Cython python3-cypari2
  python3-cysignals python3-devel python3-fpylll python3-ipython python3-lrcalc
  python3-ipython_ipykernel python3-jupyter_ipywidgets python3-matplotlib
  python3-memory_allocator python3-networkx python3-pip python3-pkgconfig

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
                   ` (11 preceding siblings ...)
  2023-10-09 21:55 ` [PR PATCH] [Updated] " tornaria
@ 2023-10-09 22:01 ` tornaria
  2023-10-10 12:42 ` [PR PATCH] [Updated] " tornaria
                   ` (3 subsequent siblings)
  16 siblings, 0 replies; 18+ messages in thread
From: tornaria @ 2023-10-09 22:01 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 398 bytes --]

New comment by tornaria on void-packages repository

https://github.com/void-linux/void-packages/pull/45887#issuecomment-1753944784

Comment:
Updated for python 3.12.

Note: in principle we won't be merging this. When sagemath 10.2 is released, it will move to cython 3. But the current betas of sagemath 10.2 need cython 3 to build so it's easier if the system sagemath also runs with cython 3.

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PR PATCH] [Updated] sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
                   ` (12 preceding siblings ...)
  2023-10-09 22:01 ` tornaria
@ 2023-10-10 12:42 ` tornaria
  2023-10-10 12:43 ` tornaria
                   ` (2 subsequent siblings)
  16 siblings, 0 replies; 18+ messages in thread
From: tornaria @ 2023-10-10 12:42 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 2442 bytes --]

There is an updated pull request by tornaria against master on the void-packages repository

https://github.com/tornaria/void-packages sagemath-cython3
https://github.com/void-linux/void-packages/pull/45887

sagemath: use cython 3
#### Testing the changes
- I tested the changes in this PR: **briefly**

Since https://github.com/sagemath/sage/pull/36109 was merged upstream, it's now almost trivial to build sagemath with cython 3. This PR is pretty straightforward to understand:

 - commit 7f8e6514ffa54449a80e01fbae7f9355a7739a46 rebuilds `python3-pplpy` using cython 3. Nothing fancy here and this commit was already tested and only dropped since it turned out it had to be built with the same version of cython as sagemath itself.
 - commit df0d21871ce850efea3fc01f19a3d9e8c0d5f0d4 is just adding a few patches to sagemath, switching to cython 3, and bumping.

Description of added patches:
1. patch `36109-00pre.patch`: this is hand picked trivial patch that allows us to apply https://github.com/sagemath/sage/pull/36109 cleanly on 10.1 (since that PR is based on 10.1.beta0). All changes are comments!
2. patch `36109-prepare_for_cython_3.0.patch`: this is long, taken verbatim from https://github.com/sagemath/sage/pull/36109.diff, and is already merged.
3. patch `build-cython3.patch`: this is 2 lines changed plus 4 legacy build options added to cython setup.
4. patch `fix-doctest-cython3.patch`: this is a few fixes in doctests to accomodate minor changes in cython output (`__repr__` for cython classes, functions, and generators).

CC: @ahesford 

<!--
#### New package
- This new package conforms to the [package requirements](https://github.com/void-linux/void-packages/blob/master/CONTRIBUTING.md#package-requirements): **YES**|**NO**
-->

<!-- Note: If the build is likely to take more than 2 hours, please add ci skip tag as described in
https://github.com/void-linux/void-packages/blob/master/CONTRIBUTING.md#continuous-integration
and test at least one native build and, if supported, at least one cross build.
Ignore this section if this PR is not skipping CI.
-->
<!--
#### Local build testing
- I built this PR locally for my native architecture, (ARCH-LIBC)
- I built this PR locally for these architectures (if supported. mark crossbuilds):
  - aarch64-musl
  - armv7l
  - armv6l-musl
-->


A patch file from https://github.com/void-linux/void-packages/pull/45887.patch is attached

[-- Warning: decoded text below may be mangled, UTF-8 assumed --]
[-- Attachment #2: github-pr-sagemath-cython3-45887.patch --]
[-- Type: text/x-diff, Size: 471130 bytes --]

From 685eabf68060217b379a5f3d07d6e09f34e5c909 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gonzalo=20Tornar=C3=ADa?= <tornaria@cmat.edu.uy>
Date: Tue, 10 Oct 2023 08:51:25 -0300
Subject: [PATCH 1/3] python3-Cython: fix memory leak + debug output for
 generators

https://github.com/cython/cython/pull/5690
https://github.com/cython/cython/pull/5725

Both are merged in cython 3.0.3, however that release breaks scipy.
---
 srcpkgs/python3-Cython/patches/5690.patch | 138 ++++++++++++++++++++++
 srcpkgs/python3-Cython/patches/5725.patch |  49 ++++++++
 srcpkgs/python3-Cython/template           |   2 +-
 3 files changed, 188 insertions(+), 1 deletion(-)
 create mode 100644 srcpkgs/python3-Cython/patches/5690.patch
 create mode 100644 srcpkgs/python3-Cython/patches/5725.patch

diff --git a/srcpkgs/python3-Cython/patches/5690.patch b/srcpkgs/python3-Cython/patches/5690.patch
new file mode 100644
index 0000000000000..b3a515c3f40f4
--- /dev/null
+++ b/srcpkgs/python3-Cython/patches/5690.patch
@@ -0,0 +1,138 @@
+Taken from https://github.com/cython/cython/pull/5690
+
+From d0139394794c207956c972e90ce59f33ef1fd709 Mon Sep 17 00:00:00 2001
+From: Oleksandr Pavlyk <oleksandr.pavlyk@intel.com>
+Date: Fri, 8 Sep 2023 14:30:06 -0500
+Subject: [PATCH 1/4] Skip building trees for nodes with invalid tag name
+
+This change attempts to exclude arguments with invalid tag names
+from being inserted into the TreeBuilder
+---
+ Cython/Debugger/DebugWriter.py | 18 ++++++++++++++----
+ 1 file changed, 14 insertions(+), 4 deletions(-)
+
+diff --git a/Cython/Debugger/DebugWriter.py b/Cython/Debugger/DebugWriter.py
+index 8b1fb75b027..dbe7cf55671 100644
+--- a/Cython/Debugger/DebugWriter.py
++++ b/Cython/Debugger/DebugWriter.py
+@@ -20,6 +20,13 @@
+ from ..Compiler import Errors
+ 
+ 
++def is_valid_tag(name):
++    if hasattr(name, "startswith"):
++        if name.startswith(".") and name[1:].isnumeric():
++            return False
++    return True
++
++
+ class CythonDebugWriter(object):
+     """
+     Class to output debugging information for cygdb
+@@ -39,14 +46,17 @@ def __init__(self, output_dir):
+         self.start('cython_debug', attrs=dict(version='1.0'))
+ 
+     def start(self, name, attrs=None):
+-        self.tb.start(name, attrs or {})
++        if is_valid_tag(name):
++            self.tb.start(name, attrs or {})
+ 
+     def end(self, name):
+-        self.tb.end(name)
++        if is_valid_tag(name):
++            self.tb.end(name)
+ 
+     def add_entry(self, name, **attrs):
+-        self.tb.start(name, attrs)
+-        self.tb.end(name)
++        if is_valid_tag(name):
++            self.tb.start(name, attrs)
++            self.tb.end(name)
+ 
+     def serialize(self):
+         self.tb.end('Module')
+
+From 1ea76c1adc3f5ab003a6ad9513ce25e5e7620388 Mon Sep 17 00:00:00 2001
+From: Oleksandr Pavlyk <oleksandr.pavlyk@intel.com>
+Date: Fri, 8 Sep 2023 15:18:21 -0500
+Subject: [PATCH 2/4] Use type checking is is_valid_tag for efficiency
+
+Documented the purpose of is_valid_tag function in its docstring.
+---
+ Cython/Debugger/DebugWriter.py | 10 +++++++++-
+ 1 file changed, 9 insertions(+), 1 deletion(-)
+
+diff --git a/Cython/Debugger/DebugWriter.py b/Cython/Debugger/DebugWriter.py
+index dbe7cf55671..57ada84ac2e 100644
+--- a/Cython/Debugger/DebugWriter.py
++++ b/Cython/Debugger/DebugWriter.py
+@@ -18,10 +18,18 @@
+             etree = None
+ 
+ from ..Compiler import Errors
++from ..Compiler.StringEncoding import EncodedString
+ 
+ 
+ def is_valid_tag(name):
+-    if hasattr(name, "startswith"):
++    """
++    Names like '.0' are used internally for arguments
++    to functions creating generator expressions,
++    however they are not identifiers. 
++
++    See gh-5552
++    """
++    if isinstance(name, EncodedString):
+         if name.startswith(".") and name[1:].isnumeric():
+             return False
+     return True
+
+From 4f0cf58ef1176af6c66e492428b78a4da37c41dc Mon Sep 17 00:00:00 2001
+From: scoder <stefan_ml@behnel.de>
+Date: Sat, 9 Sep 2023 11:28:47 +0200
+Subject: [PATCH 3/4] Fix minor issues.
+
+---
+ Cython/Debugger/DebugWriter.py | 4 ++--
+ 1 file changed, 2 insertions(+), 2 deletions(-)
+
+diff --git a/Cython/Debugger/DebugWriter.py b/Cython/Debugger/DebugWriter.py
+index 57ada84ac2e..46db48a6bd8 100644
+--- a/Cython/Debugger/DebugWriter.py
++++ b/Cython/Debugger/DebugWriter.py
+@@ -27,10 +27,10 @@ def is_valid_tag(name):
+     to functions creating generator expressions,
+     however they are not identifiers. 
+ 
+-    See gh-5552
++    See https://github.com/cython/cython/issues/5552
+     """
+     if isinstance(name, EncodedString):
+-        if name.startswith(".") and name[1:].isnumeric():
++        if name.startswith(".") and name[1:].isdecimal():
+             return False
+     return True
+ 
+
+From 0d13568946f5865a55340db09310accd2323f6bf Mon Sep 17 00:00:00 2001
+From: scoder <stefan_ml@behnel.de>
+Date: Sat, 9 Sep 2023 12:22:21 +0200
+Subject: [PATCH 4/4] Remove trailing whitespace.
+
+---
+ Cython/Debugger/DebugWriter.py | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/Cython/Debugger/DebugWriter.py b/Cython/Debugger/DebugWriter.py
+index 46db48a6bd8..2c3c310fc64 100644
+--- a/Cython/Debugger/DebugWriter.py
++++ b/Cython/Debugger/DebugWriter.py
+@@ -25,7 +25,7 @@ def is_valid_tag(name):
+     """
+     Names like '.0' are used internally for arguments
+     to functions creating generator expressions,
+-    however they are not identifiers. 
++    however they are not identifiers.
+ 
+     See https://github.com/cython/cython/issues/5552
+     """
diff --git a/srcpkgs/python3-Cython/patches/5725.patch b/srcpkgs/python3-Cython/patches/5725.patch
new file mode 100644
index 0000000000000..e2f811fe0e020
--- /dev/null
+++ b/srcpkgs/python3-Cython/patches/5725.patch
@@ -0,0 +1,49 @@
+Taken from https://github.com/cython/cython/pull/5725
+
+From c38b320764bd2a7c089b332e0a3d27ec87b725d1 Mon Sep 17 00:00:00 2001
+From: yut23 <yut23@gvljohnsons.com>
+Date: Mon, 25 Sep 2023 16:34:50 -0400
+Subject: [PATCH 1/2] Release references to traceback objects in Python 3.12+
+
+Fixes: #5724
+---
+ Cython/Utility/Exceptions.c | 2 ++
+ 1 file changed, 2 insertions(+)
+
+diff --git a/Cython/Utility/Exceptions.c b/Cython/Utility/Exceptions.c
+index 20dc7faf3a8..a4416462500 100644
+--- a/Cython/Utility/Exceptions.c
++++ b/Cython/Utility/Exceptions.c
+@@ -190,6 +190,8 @@ static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObjec
+     tmp_value = tstate->current_exception;
+     tstate->current_exception = value;
+     Py_XDECREF(tmp_value);
++    Py_XDECREF(tb);
++    Py_XDECREF(type);
+ #else
+     PyObject *tmp_type, *tmp_value, *tmp_tb;
+     tmp_type = tstate->curexc_type;
+
+From d8b71ef8ccb5ef114a77ce499f192f121060ca02 Mon Sep 17 00:00:00 2001
+From: scoder <stefan_ml@behnel.de>
+Date: Tue, 26 Sep 2023 11:08:24 +0200
+Subject: [PATCH 2/2] Remove now-unused "unused" marker.
+
+---
+ Cython/Utility/Exceptions.c | 3 +--
+ 1 file changed, 1 insertion(+), 2 deletions(-)
+
+diff --git a/Cython/Utility/Exceptions.c b/Cython/Utility/Exceptions.c
+index a4416462500..2144594ba53 100644
+--- a/Cython/Utility/Exceptions.c
++++ b/Cython/Utility/Exceptions.c
+@@ -190,8 +189,8 @@ static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObjec
+     tmp_value = tstate->current_exception;
+     tstate->current_exception = value;
+     Py_XDECREF(tmp_value);
+-    Py_XDECREF(tb);
+     Py_XDECREF(type);
++    Py_XDECREF(tb);
+ #else
+     PyObject *tmp_type, *tmp_value, *tmp_tb;
+     tmp_type = tstate->curexc_type;
diff --git a/srcpkgs/python3-Cython/template b/srcpkgs/python3-Cython/template
index f297933592545..782de6ad66468 100644
--- a/srcpkgs/python3-Cython/template
+++ b/srcpkgs/python3-Cython/template
@@ -1,7 +1,7 @@
 # Template file for 'python3-Cython'
 pkgname=python3-Cython
 version=3.0.2
-revision=3
+revision=4
 build_style=python3-module
 hostmakedepends="python3-setuptools"
 makedepends="python3-devel"

From 25fbd4228a6974713c98f21fb71a406c79881f18 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gonzalo=20Tornar=C3=ADa?= <tornaria@cmat.edu.uy>
Date: Wed, 19 Jul 2023 21:04:33 -0300
Subject: [PATCH 2/3] python3-pplpy: update to 0.8.9, use cython 3.

---
 srcpkgs/python3-pplpy/template | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/srcpkgs/python3-pplpy/template b/srcpkgs/python3-pplpy/template
index fe6b08dba40f2..d7a31aeab2023 100644
--- a/srcpkgs/python3-pplpy/template
+++ b/srcpkgs/python3-pplpy/template
@@ -1,19 +1,19 @@
 # Template file for 'python3-pplpy'
 pkgname=python3-pplpy
-version=0.8.7
-revision=4
+version=0.8.9
+revision=1
 build_style=python3-module
-hostmakedepends="python3-setuptools python3-Cython0.29"
+hostmakedepends="python3-setuptools python3-Cython"
 makedepends="python3-cysignals python3-gmpy2 python3-devel gmp-devel
  gmpxx-devel ppl-devel mpfr-devel libmpc-devel pari-devel"
 depends="python3"
 short_desc="Python wrapper to the C++ Parma Polyhedra Library (PPL)"
 maintainer="Gonzalo Tornaría <tornaria@cmat.edu.uy>"
 license="GPL-3.0-or-later"
-homepage="https://gitlab.com/videlec/pplpy"
-changelog="https://gitlab.com/videlec/pplpy/-/raw/master/CHANGES.txt"
+homepage="https://github.com/sagemath/pplpy"
+changelog="https://raw.githubusercontent.com/sagemath/pplpy/master/CHANGES.txt"
 distfiles="${PYPI_SITE}/p/pplpy/pplpy-${version}.tar.gz"
-checksum=500bd0f4ae1a76956fae7fcba77854f5ec3e64fce76803664983763c3f2bd8bd
+checksum=db7a3b571d6ef053f75137975e947c3a1c1e45a30bab90eaf215b4e5cc15797e
 
 do_check() {
 	PYTHONPATH=$(cd build/lib* && pwd) python3 setup.py test

From d26636f0694abe2560f4128c6e7d32ff3a588c03 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gonzalo=20Tornar=C3=ADa?= <tornaria@cmat.edu.uy>
Date: Tue, 29 Aug 2023 22:14:49 -0300
Subject: [PATCH 3/3] sagemath: use cython 3.0

---
 srcpkgs/sagemath/patches/36109-00pre.patch    |   50 +
 .../36109-prepare_for_cython_3.0.patch        | 9995 +++++++++++++++++
 srcpkgs/sagemath/patches/build-cython3.patch  |   44 +
 .../patches/fix-doctest-cython3.patch         |  207 +
 srcpkgs/sagemath/patches/get_patches          |    3 +-
 srcpkgs/sagemath/template                     |    6 +-
 6 files changed, 10301 insertions(+), 4 deletions(-)
 create mode 100644 srcpkgs/sagemath/patches/36109-00pre.patch
 create mode 100644 srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch
 create mode 100644 srcpkgs/sagemath/patches/build-cython3.patch
 create mode 100644 srcpkgs/sagemath/patches/fix-doctest-cython3.patch

diff --git a/srcpkgs/sagemath/patches/36109-00pre.patch b/srcpkgs/sagemath/patches/36109-00pre.patch
new file mode 100644
index 0000000000000..0a30d622f0f62
--- /dev/null
+++ b/srcpkgs/sagemath/patches/36109-00pre.patch
@@ -0,0 +1,50 @@
+Pre-patch so that PR #36109 applies cleanly on top of 10.1
+
+diff --git a/src/sage/categories/hopf_algebras_with_basis.py b/src/sage/categories/hopf_algebras_with_basis.py
+index ea401896ca0..29b6f48a86f 100644
+--- a/src/sage/categories/hopf_algebras_with_basis.py
++++ b/src/sage/categories/hopf_algebras_with_basis.py
+@@ -33,11 +33,11 @@ class HopfAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
+     We now show how to use a simple Hopf algebra, namely the group algebra of the dihedral group
+     (see also AlgebrasWithBasis)::
+ 
+-        sage: A = C.example(); A                                                        # optional - sage.groups
++        sage: A = C.example(); A                                                        # needs sage.groups
+         An example of Hopf algebra with basis: the group algebra of the
+          Dihedral group of order 6 as a permutation group over Rational Field
+-        sage: A.__custom_name = "A"                                                     # optional - sage.groups
+-        sage: A.category()                                                              # optional - sage.groups
++        sage: A.__custom_name = "A"                                                     # needs sage.groups
++        sage: A.category()                                                              # needs sage.groups
+         Category of finite dimensional hopf algebras with basis over Rational Field
+ 
+         sage: A.one_basis()                                                             # optional - sage.groups
+diff --git a/src/sage/categories/modules_with_basis.py b/src/sage/categories/modules_with_basis.py
+index 85a0d50239a..c0e29886b5f 100644
+--- a/src/sage/categories/modules_with_basis.py
++++ b/src/sage/categories/modules_with_basis.py
+@@ -66,9 +66,9 @@ class ModulesWithBasis(CategoryWithAxiom_over_base_ring):
+ 
+     Let `X` and `Y` be two modules with basis. We can build `Hom(X,Y)`::
+ 
+-        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.__custom_name = "X"             # optional - sage.modules
+-        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.__custom_name = "Y"             # optional - sage.modules
+-        sage: H = Hom(X, Y); H                                                          # optional - sage.modules
++        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.__custom_name = "X"             # needs sage.modules
++        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.__custom_name = "Y"             # needs sage.modules
++        sage: H = Hom(X, Y); H                                                          # needs sage.modules
+         Set of Morphisms from X to Y
+          in Category of finite dimensional vector spaces with basis over Rational Field
+ 
+diff --git a/src/sage/misc/cachefunc.pyx b/src/sage/misc/cachefunc.pyx
+index dac4c684f47..9b2916e547d 100644
+--- a/src/sage/misc/cachefunc.pyx
++++ b/src/sage/misc/cachefunc.pyx
+@@ -297,6 +297,7 @@ methods of extension classes, as long as they either support attribute assignmen
+ or have a public attribute of type ``<dict>`` called ``__cached_methods``. The
+ latter is easy::
+ 
++    sage: # needs sage.misc.cython
+     sage: cython_code = [
+     ....: "from sage.misc.cachefunc import cached_method",
+     ....: "cdef class MyClass:",
diff --git a/srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch b/srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch
new file mode 100644
index 0000000000000..93390f7eef992
--- /dev/null
+++ b/srcpkgs/sagemath/patches/36109-prepare_for_cython_3.0.patch
@@ -0,0 +1,9995 @@
+diff --git a/src/doc/en/thematic_tutorials/coercion_and_categories.rst b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+index 4efe68a2617..de2349a9a3f 100644
+--- a/src/doc/en/thematic_tutorials/coercion_and_categories.rst
++++ b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+@@ -106,7 +106,6 @@ This base class provides a lot more methods than a general parent::
+ 
+     sage: [p for p in dir(Field) if p not in dir(Parent)]
+     ['__fraction_field',
+-     '__ideal_monoid',
+      '__iter__',
+      '__len__',
+      '__rxor__',
+@@ -119,6 +118,7 @@ This base class provides a lot more methods than a general parent::
+      '_default_category',
+      '_gens',
+      '_ideal_class_',
++     '_ideal_monoid',
+      '_latex_names',
+      '_list',
+      '_one_element',
+diff --git a/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst b/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst
+index 51aec989810..553a946c4d8 100644
+--- a/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst
++++ b/src/doc/en/thematic_tutorials/tutorial-objects-and-classes.rst
+@@ -298,7 +298,7 @@ http://docs.python.org/library/ for a complete list. ::
+         sage: el
+         bla
+         sage: el.__dict__
+-        {'__custom_name': 'bla', 'value': 42}
++        {'_SageObject__custom_name': 'bla', 'value': 42}
+ 
+     Lots of Sage objects are not Python objects but compiled Cython
+     objects. Python sees them as builtin objects and you do not have
+diff --git a/src/sage/algebras/letterplace/free_algebra_letterplace.pxd b/src/sage/algebras/letterplace/free_algebra_letterplace.pxd
+index d1d162c3b40..47a7275aba0 100644
+--- a/src/sage/algebras/letterplace/free_algebra_letterplace.pxd
++++ b/src/sage/algebras/letterplace/free_algebra_letterplace.pxd
+@@ -20,16 +20,15 @@ cdef class FreeAlgebra_letterplace_libsingular():
+     cdef ring* _lp_ring
+     cdef MPolynomialRing_libsingular _commutative_ring
+     cdef MPolynomialRing_libsingular _lp_ring_internal
+-    cdef object __ngens
++    cdef object _ngens
+ 
+ cdef class FreeAlgebra_letterplace(Algebra):
+     cdef MPolynomialRing_libsingular _commutative_ring
+     cdef MPolynomialRing_libsingular _current_ring
+     cdef int _degbound
+-    cdef int __ngens
++    cdef int _ngens
+     cdef int _nb_slackvars
+     cdef object __monoid
+-    cdef public object __custom_name
+     cdef str exponents_to_string(self, E)
+     cdef str exponents_to_latex(self, E)
+     cdef tuple _degrees
+diff --git a/src/sage/algebras/letterplace/free_algebra_letterplace.pyx b/src/sage/algebras/letterplace/free_algebra_letterplace.pyx
+index e9c70c9de29..53f0dfdea6d 100644
+--- a/src/sage/algebras/letterplace/free_algebra_letterplace.pyx
++++ b/src/sage/algebras/letterplace/free_algebra_letterplace.pyx
+@@ -255,7 +255,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+         """
+         if not isinstance(R, MPolynomialRing_libsingular):
+             raise TypeError("a letterplace algebra must be provided by a polynomial ring of type %s" % MPolynomialRing_libsingular)
+-        self.__ngens = R.ngens()
++        self._ngens = R.ngens()
+         if degrees is None:
+             varnames = R.variable_names()
+             self._nb_slackvars = 0
+@@ -269,12 +269,12 @@ cdef class FreeAlgebra_letterplace(Algebra):
+         self._current_ring = make_letterplace_ring(R, 1)
+         self._degbound = 1
+         if degrees is None:
+-            self._degrees = tuple([int(1)] * self.__ngens)
++            self._degrees = tuple([int(1)] * self._ngens)
+         else:
+             if (not isinstance(degrees, (tuple, list))) \
+-                    or len(degrees) != self.__ngens - self._nb_slackvars \
++                    or len(degrees) != self._ngens - self._nb_slackvars \
+                     or any(i <= 0 for i in degrees):
+-                raise TypeError("the generator degrees must be given by a list or tuple of %d positive integers" % (self.__ngens - 1))
++                raise TypeError("the generator degrees must be given by a list or tuple of %d positive integers" % (self._ngens - 1))
+             self._degrees = tuple([int(i) for i in degrees])
+             self.set_degbound(max(self._degrees))
+         self._populate_coercion_lists_(coerce_list=[base_ring])
+@@ -305,7 +305,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F.ngens()
+             3
+         """
+-        return self.__ngens - self._nb_slackvars
++        return self._ngens - self._nb_slackvars
+ 
+     def gen(self, i):
+         """
+@@ -327,17 +327,17 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F.gen(2)
+             c
+         """
+-        if i >= self.__ngens - self._nb_slackvars:
+-            raise ValueError("this free algebra only has %d generators" % (self.__ngens - self._nb_slackvars))
++        if i >= self._ngens - self._nb_slackvars:
++            raise ValueError("this free algebra only has %d generators" % (self._ngens - self._nb_slackvars))
+         if self._gens is not None:
+             return self._gens[i]
+         deg = self._degrees[i]
+         # self.set_degbound(deg)
+         p = self._current_ring.gen(i)
+         cdef int n
+-        cdef int j = self.__ngens - 1
++        cdef int j = self._ngens - 1
+         for n in range(1, deg):
+-            j += self.__ngens
++            j += self._ngens
+             p *= self._current_ring.gen(j)
+         return FreeAlgebraElement_letterplace(self, p)
+ 
+@@ -413,7 +413,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: FreeAlgebra(QQ, implementation='letterplace', names=['x']).is_commutative()
+             True
+         """
+-        return self.__ngens - self._nb_slackvars <= 1
++        return self._ngens - self._nb_slackvars <= 1
+ 
+     def is_field(self, proof=True):
+         """
+@@ -430,7 +430,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F.is_field()
+             False
+         """
+-        return (not (self.__ngens - self._nb_slackvars)) and self._base.is_field(proof=proof)
++        return (not (self._ngens - self._nb_slackvars)) and self._base.is_field(proof=proof)
+ 
+     def _repr_(self):
+         """
+@@ -446,7 +446,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: F
+             Free Associative Unital Algebra on 3 generators (x, y, z) over Rational Field
+         """
+-        return "Free Associative Unital Algebra on %d generators %s over %s" % (self.__ngens - self._nb_slackvars, self.gens(), self._base)
++        return "Free Associative Unital Algebra on %d generators %s over %s" % (self._ngens - self._nb_slackvars, self.gens(), self._base)
+ 
+     def _latex_(self):
+         r"""
+@@ -586,7 +586,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+               generated free abelian monoid.
+               In principle, this is correct, but it is not implemented, yet.>
+         """
+-        cdef int ngens = self.__ngens
++        cdef int ngens = self._ngens
+         cdef int nblocks = len(E) // ngens
+         cdef int i, j, base, exp, var_ind
+         cdef list out = []
+@@ -618,7 +618,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             sage: latex(-(a*b*(z+1)-c)^2)     # indirect doctest
+             \left(2 z + 1\right) a b a b + \left(z + 1\right) a b c + \left(z + 1\right) c a b - c c
+         """
+-        cdef int ngens = self.__ngens
++        cdef int ngens = self._ngens
+         cdef int nblocks = len(E) // ngens
+         cdef int i, j, base, exp, var_ind
+         cdef list out = []
+@@ -678,7 +678,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+         cdef list out = []
+         C = self.current_ring()
+         cdef FreeAlgebraElement_letterplace x
+-        ngens = self.__ngens
++        ngens = self._ngens
+         cdef list G = [C(x._poly) for x in g]
+         from sage.groups.perm_gps.permgroup_named import CyclicPermutationGroup
+         CG = CyclicPermutationGroup(C.ngens())
+@@ -811,7 +811,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
+             l = len(e)
+             break
+         cdef dict out = {}
+-        self.set_degbound(l // self.__ngens)
++        self.set_degbound(l // self._ngens)
+         cdef Py_ssize_t n = self._current_ring.ngens()
+         for e, c in D.iteritems():
+             out[tuple(e) + (0,) * (n - l)] = c
+@@ -896,7 +896,7 @@ cdef class FreeAlgebra_letterplace_libsingular():
+         self._commutative_ring = commutative_ring
+ 
+     def __init__(self, commutative_ring, degbound):
+-        self.__ngens = commutative_ring.ngens() * degbound
++        self._ngens = commutative_ring.ngens() * degbound
+ 
+     def __dealloc__(self):
+         r"""
+diff --git a/src/sage/algebras/quatalg/quaternion_algebra_element.pyx b/src/sage/algebras/quatalg/quaternion_algebra_element.pyx
+index f6e87440fe9..8cb7e848fd0 100644
+--- a/src/sage/algebras/quatalg/quaternion_algebra_element.pyx
++++ b/src/sage/algebras/quatalg/quaternion_algebra_element.pyx
+@@ -1700,15 +1700,15 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra
+             x, y, z, w = v
+         cdef NumberFieldElement a = <NumberFieldElement>(parent._base(parent._a))
+         cdef NumberFieldElement b = <NumberFieldElement>(parent._base(parent._b))
+-        fmpz_poly_set_ZZX(self.x, (<NumberFieldElement>x).__numerator)
+-        fmpz_poly_set_ZZX(self.y, (<NumberFieldElement>y).__numerator)
+-        fmpz_poly_set_ZZX(self.z, (<NumberFieldElement>z).__numerator)
+-        fmpz_poly_set_ZZX(self.w, (<NumberFieldElement>w).__numerator)
++        fmpz_poly_set_ZZX(self.x, (<NumberFieldElement>x)._numerator)
++        fmpz_poly_set_ZZX(self.y, (<NumberFieldElement>y)._numerator)
++        fmpz_poly_set_ZZX(self.z, (<NumberFieldElement>z)._numerator)
++        fmpz_poly_set_ZZX(self.w, (<NumberFieldElement>w)._numerator)
+ 
+-        ZZ_to_mpz(T1, &(<NumberFieldElement>x).__denominator)
+-        ZZ_to_mpz(T2, &(<NumberFieldElement>y).__denominator)
+-        ZZ_to_mpz(t3, &(<NumberFieldElement>z).__denominator)
+-        ZZ_to_mpz(t4, &(<NumberFieldElement>w).__denominator)
++        ZZ_to_mpz(T1, &(<NumberFieldElement>x)._denominator)
++        ZZ_to_mpz(T2, &(<NumberFieldElement>y)._denominator)
++        ZZ_to_mpz(t3, &(<NumberFieldElement>z)._denominator)
++        ZZ_to_mpz(t4, &(<NumberFieldElement>w)._denominator)
+ 
+         mpz_lcm(self.d, T1, T2)
+         mpz_lcm(self.d, self.d, t3)
+@@ -1724,10 +1724,10 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra
+         fmpz_poly_scalar_mul_mpz(self.z, self.z, t3)
+         fmpz_poly_scalar_mul_mpz(self.w, self.w, t4)
+ 
+-        fmpz_poly_set_ZZX(self.a, a.__numerator)     # we will assume that the denominator of a and b are 1
+-        fmpz_poly_set_ZZX(self.b, b.__numerator)
++        fmpz_poly_set_ZZX(self.a, a._numerator)     # we will assume that the denominator of a and b are 1
++        fmpz_poly_set_ZZX(self.b, b._numerator)
+ 
+-        fmpz_poly_set_ZZX(self.modulus, (<NumberFieldElement>x).__fld_numerator.x)  # and same for the modulus
++        fmpz_poly_set_ZZX(self.modulus, (<NumberFieldElement>x)._fld_numerator.x)  # and same for the modulus
+ 
+     def __getitem__(self, int i):
+         """
+@@ -1756,17 +1756,17 @@ cdef class QuaternionAlgebraElement_number_field(QuaternionAlgebraElement_abstra
+         cdef NumberFieldElement item = el._new()
+ 
+         if i == 0:
+-            fmpz_poly_get_ZZX(item.__numerator, self.x)
++            fmpz_poly_get_ZZX(item._numerator, self.x)
+         elif i == 1:
+-            fmpz_poly_get_ZZX(item.__numerator, self.y)
++            fmpz_poly_get_ZZX(item._numerator, self.y)
+         elif i == 2:
+-            fmpz_poly_get_ZZX(item.__numerator, self.z)
++            fmpz_poly_get_ZZX(item._numerator, self.z)
+         elif i == 3:
+-            fmpz_poly_get_ZZX(item.__numerator, self.w)
++            fmpz_poly_get_ZZX(item._numerator, self.w)
+         else:
+             raise IndexError("quaternion element index out of range")
+ 
+-        mpz_to_ZZ(&item.__denominator, self.d)
++        mpz_to_ZZ(&item._denominator, self.d)
+ 
+         return item
+ 
+diff --git a/src/sage/categories/hopf_algebras_with_basis.py b/src/sage/categories/hopf_algebras_with_basis.py
+index 1be964cb6c9..615fc4eae06 100644
+--- a/src/sage/categories/hopf_algebras_with_basis.py
++++ b/src/sage/categories/hopf_algebras_with_basis.py
+@@ -36,7 +36,7 @@ class HopfAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
+         sage: A = C.example(); A                                                        # needs sage.groups
+         An example of Hopf algebra with basis: the group algebra of the
+          Dihedral group of order 6 as a permutation group over Rational Field
+-        sage: A.__custom_name = "A"                                                     # needs sage.groups
++        sage: A.rename("A")                                                             # needs sage.groups
+         sage: A.category()                                                              # needs sage.groups
+         Category of finite dimensional hopf algebras with basis over Rational Field
+ 
+diff --git a/src/sage/categories/modules_with_basis.py b/src/sage/categories/modules_with_basis.py
+index 65fd47cb890..fc1857f0c8e 100644
+--- a/src/sage/categories/modules_with_basis.py
++++ b/src/sage/categories/modules_with_basis.py
+@@ -66,8 +66,8 @@ class ModulesWithBasis(CategoryWithAxiom_over_base_ring):
+ 
+     Let `X` and `Y` be two modules with basis. We can build `Hom(X,Y)`::
+ 
+-        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.__custom_name = "X"             # needs sage.modules
+-        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.__custom_name = "Y"             # needs sage.modules
++        sage: X = CombinatorialFreeModule(QQ, [1,2]); X.rename("X")                     # needs sage.modules
++        sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.rename("Y")                     # needs sage.modules
+         sage: H = Hom(X, Y); H                                                          # needs sage.modules
+         Set of Morphisms from X to Y
+          in Category of finite dimensional vector spaces with basis over Rational Field
+diff --git a/src/sage/combinat/cluster_complex.py b/src/sage/combinat/cluster_complex.py
+index edc4f235aeb..e263d983887 100644
+--- a/src/sage/combinat/cluster_complex.py
++++ b/src/sage/combinat/cluster_complex.py
+@@ -222,10 +222,6 @@ def __init__(self, W, k, coxeter_element, algorithm):
+         self._W = W
+         self._w0 = w
+         self._k = k
+-        if k == 1:
+-            self.__custom_name = 'Cluster complex'
+-        else:
+-            self.__custom_name = 'Multi-cluster complex'
+ 
+         self.set_immutable()
+ 
+@@ -271,7 +267,10 @@ def _repr_(self):
+             sage: ClusterComplex(['A', 2])._repr_()
+             "Cluster complex of type ['A', 2] with 5 vertices and 5 facets"
+         """
+-        name = self.__custom_name
++        if self._k == 1:
++            name = 'Cluster complex'
++        else:
++            name = 'Multi-cluster complex'
+         name += (' of type %s with %s vertices and %s facets'
+                  % (self.cartan_type(), len(self.vertices()),
+                     len(self._facets)))
+diff --git a/src/sage/combinat/integer_lists/base.pxd b/src/sage/combinat/integer_lists/base.pxd
+index ecb5550a9cf..3d373a64fe0 100644
+--- a/src/sage/combinat/integer_lists/base.pxd
++++ b/src/sage/combinat/integer_lists/base.pxd
+@@ -12,4 +12,4 @@ cdef class IntegerListsBackend():
+     cdef readonly min_part, max_part
+     cdef readonly min_slope, max_slope
+     cdef readonly Envelope floor, ceiling
+-    cdef public dict __cached_methods  # Support cached_method
++    cdef public dict _cached_methods  # Support cached_method
+diff --git a/src/sage/combinat/subword_complex.py b/src/sage/combinat/subword_complex.py
+index b7489bdf754..de7eefe946e 100644
+--- a/src/sage/combinat/subword_complex.py
++++ b/src/sage/combinat/subword_complex.py
+@@ -1131,7 +1131,6 @@ def __init__(self, Q, w, algorithm="inductive"):
+         SimplicialComplex.__init__(self, maximal_faces=Fs,
+                                    maximality_check=False,
+                                    category=cat)
+-        self.__custom_name = 'Subword complex'
+         self._W = W
+         try:
+             T = W.coxeter_matrix().coxeter_type()
+diff --git a/src/sage/cpython/cython_metaclass.h b/src/sage/cpython/cython_metaclass.h
+index da06ab75a6b..ecf7f973c3e 100644
+--- a/src/sage/cpython/cython_metaclass.h
++++ b/src/sage/cpython/cython_metaclass.h
+@@ -52,6 +52,16 @@ static CYTHON_INLINE int Sage_PyType_Ready(PyTypeObject* t)
+     if (r < 0)
+         return r;
+ 
++#if PY_VERSION_HEX >= 0x03050000
++    // Cython 3 sets Py_TPFLAGS_HEAPTYPE before calling PyType_Ready,
++    // and resets just after the call. We need to reset it earlier,
++    // since otherwise the call to metaclass.__init__ below may have
++    // illegal memory accesses.
++    // See also:
++    // https://github.com/cython/cython/issues/3603
++    t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE;
++#endif
++
+     /* Set or get metaclass (the type of t) */
+     PyTypeObject* metaclass;
+ 
+diff --git a/src/sage/cpython/cython_metaclass.pyx b/src/sage/cpython/cython_metaclass.pyx
+index a8fe853661d..a8fa92fc1a8 100644
+--- a/src/sage/cpython/cython_metaclass.pyx
++++ b/src/sage/cpython/cython_metaclass.pyx
+@@ -19,13 +19,16 @@ file if you are using one).
+ 
+ In the extension type (a.k.a. ``cdef class``) for which you want to
+ define a metaclass, define a method ``__getmetaclass__`` with a single
+-unused argument. This method should return a type to be used as
++unused argument, and turn off the Cython directive
++``always_allow_keywords``. This method should return a type to be used as
+ metaclass:
+ 
+ .. code-block:: cython
+ 
++    cimport cython
+     cimport sage.cpython.cython_metaclass
+     cdef class MyCustomType():
++        @cython.always_allow_keywords(False)
+         def __getmetaclass__(_):
+             from foo import MyMetaclass
+             return MyMetaclass
+@@ -63,8 +66,10 @@ EXAMPLES::
+ 
+     sage: cython(                                                                       # needs sage.misc.cython
+     ....: '''
++    ....: cimport cython
+     ....: cimport sage.cpython.cython_metaclass
+     ....: cdef class MyCustomType():
++    ....:     @cython.always_allow_keywords(False)
+     ....:     def __getmetaclass__(_):
+     ....:         class MyMetaclass(type):
+     ....:             def __init__(*args):
+@@ -101,8 +106,10 @@ returns a non-type::
+ 
+     sage: cython(                                                                       # needs sage.misc.cython
+     ....: '''
++    ....: cimport cython
+     ....: cimport sage.cpython.cython_metaclass
+     ....: cdef class MyCustomType():
++    ....:     @cython.always_allow_keywords(False)
+     ....:     def __getmetaclass__(_):
+     ....:         return 2
+     ....: ''')
+diff --git a/src/sage/cpython/getattr.pyx b/src/sage/cpython/getattr.pyx
+index 3f603b98040..16f649c083d 100644
+--- a/src/sage/cpython/getattr.pyx
++++ b/src/sage/cpython/getattr.pyx
+@@ -271,7 +271,7 @@ cpdef getattr_from_other_class(self, cls, name):
+ 
+     Caveat: lazy attributes work with extension types only
+     if they allow attribute assignment or have a public attribute
+-    ``__cached_methods`` of type ``<dict>``. This condition
++    ``_cached_methods`` of type ``<dict>``. This condition
+     is satisfied, e.g., by any class that is derived from
+     :class:`Parent`::
+ 
+diff --git a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd
+index bdd49225ff2..030c9defa45 100644
+--- a/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd
++++ b/src/sage/geometry/polyhedron/combinatorial_polyhedron/base.pxd
+@@ -8,7 +8,7 @@ from .polyhedron_face_lattice           cimport PolyhedronFaceLattice
+ 
+ @cython.final
+ cdef class CombinatorialPolyhedron(SageObject):
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+     # Do not assume any of those attributes to be initialized, use the corresponding methods instead.
+     cdef tuple _Vrep                       # the names of VRep, if they exist
+diff --git a/src/sage/groups/perm_gps/permgroup_element.pxd b/src/sage/groups/perm_gps/permgroup_element.pxd
+index a2ac8f20eaa..0a584745f96 100644
+--- a/src/sage/groups/perm_gps/permgroup_element.pxd
++++ b/src/sage/groups/perm_gps/permgroup_element.pxd
+@@ -22,7 +22,7 @@ cdef class PermutationGroupElement(MultiplicativeGroupElement):
+     cpdef PermutationGroupElement _generate_new_GAP(self, old)
+     cpdef _gap_list(self)
+     cpdef domain(self)
+-    cdef public __custom_name
++    cdef public _SageObject__custom_name
+     cpdef list _act_on_list_on_position(self, list x)
+     cpdef ClonableIntArray _act_on_array_on_position(self, ClonableIntArray x)
+     cpdef ETuple _act_on_etuple_on_position(self, ETuple x)
+diff --git a/src/sage/interfaces/interface.py b/src/sage/interfaces/interface.py
+index f8237d3ad94..3180113c9c7 100644
+--- a/src/sage/interfaces/interface.py
++++ b/src/sage/interfaces/interface.py
+@@ -1169,11 +1169,8 @@ def __repr__(self):
+             s = cr
+         else:
+             s = self._repr_()
+-        if self._name in s:
+-            try:
+-                s = s.replace(self._name, getattr(self, '__custom_name'))
+-            except AttributeError:
+-                pass
++        if self._name in s and self.get_custom_name() is not None:
++            s = s.replace(self._name, self.get_custom_name())
+         if cr:
+             self._cached_repr = s
+         return s
+diff --git a/src/sage/interfaces/singular.py b/src/sage/interfaces/singular.py
+index 4b5c76e2bfa..705fa6f66e1 100644
+--- a/src/sage/interfaces/singular.py
++++ b/src/sage/interfaces/singular.py
+@@ -1400,8 +1400,8 @@ def _repr_(self):
+         """
+         s = super(SingularElement, self)._repr_()
+         if self._name in s:
+-            if (not hasattr(self, "__custom_name")) and self.type() == 'matrix':
+-                s = self.parent().eval('pmat(%s,20)'%(self.name()))
++            if self.get_custom_name() is None and self.type() == 'matrix':
++                s = self.parent().eval('pmat(%s,20)' % (self.name()))
+         return s
+ 
+     def __copy__(self):
+diff --git a/src/sage/libs/arb/arith.pyx b/src/sage/libs/arb/arith.pyx
+index d885f97b238..3b32fe7e8ed 100644
+--- a/src/sage/libs/arb/arith.pyx
++++ b/src/sage/libs/arb/arith.pyx
+@@ -81,5 +81,5 @@ def hilbert_class_polynomial(D):
+     cdef long n = D
+     cdef Polynomial_integer_dense_flint poly
+     poly = PolynomialRing(ZZ, "x", implementation="FLINT")()
+-    acb_modular_hilbert_class_poly(poly.__poly, n)
++    acb_modular_hilbert_class_poly(poly._poly, n)
+     return poly
+diff --git a/src/sage/libs/coxeter3/coxeter.pxd b/src/sage/libs/coxeter3/coxeter.pxd
+index 9d5cb2a3f5d..dbd2b8a61c6 100644
+--- a/src/sage/libs/coxeter3/coxeter.pxd
++++ b/src/sage/libs/coxeter3/coxeter.pxd
+@@ -29,6 +29,3 @@ cdef class CoxGroupElement:
+     cdef CoxGroup _parent_group
+     cdef CoxGroupElement _new(self)
+     cpdef CoxGroup parent_group(self)
+-
+-cdef class CoxGraph:
+-    cdef c_CoxGraph x
+diff --git a/src/sage/libs/gap/element.pyx b/src/sage/libs/gap/element.pyx
+index 1dc53c81f67..478caf9f9d0 100644
+--- a/src/sage/libs/gap/element.pyx
++++ b/src/sage/libs/gap/element.pyx
+@@ -720,7 +720,7 @@ cdef class GapElement(RingElement):
+             ...
+             AttributeError: 'some_name' does not define a GAP function
+         """
+-        if name in ('__dict__', '_getAttributeNames', '__custom_name', 'keys'):
++        if name in ('__dict__', '_getAttributeNames', '_SageObject__custom_name', 'keys'):
+             raise AttributeError('Python special name, not a GAP function.')
+         try:
+             proxy = make_GapElement_MethodProxy\
+diff --git a/src/sage/libs/gap/gap_includes.pxd b/src/sage/libs/gap/gap_includes.pxd
+index 840b8a0042e..1ed4378a6c7 100644
+--- a/src/sage/libs/gap/gap_includes.pxd
++++ b/src/sage/libs/gap/gap_includes.pxd
+@@ -144,3 +144,18 @@ cdef extern from "gap/stringobj.h" nogil:
+     bint IS_STRING(Obj obj)
+     bint IsStringConv(Obj obj)
+     Obj NEW_STRING(Int)
++
++
++cdef extern from "<structmember.h>" nogil:
++    """
++    /* Hack: Cython 3.0 automatically includes <structmember.h>, which
++     * defines several macros that collides with enum definitions in
++     * gap/objects.h. We need to include the header explicitly and
++     * undefine these macros.
++     */
++    #undef T_INT
++    #undef T_STRING
++    #undef T_CHAR
++    #undef T_BOOL
++    """
++    pass
+diff --git a/src/sage/libs/lcalc/lcalc_Lfunction.pxd b/src/sage/libs/lcalc/lcalc_Lfunction.pxd
+index 5edf0844f3e..1d595180a6f 100644
+--- a/src/sage/libs/lcalc/lcalc_Lfunction.pxd
++++ b/src/sage/libs/lcalc/lcalc_Lfunction.pxd
+@@ -99,19 +99,19 @@ cdef extern from "lcalc_sage.h":
+ ################
+ 
+ # strange bug, I can't compile without this trick ???
+-# it's only used in __typedN
++# it's only used in _typedN
+ ctypedef double Double
+ 
+ cdef class Lfunction:
+     cdef void *thisptr
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r)
+-    cdef c_Complex __value(self,c_Complex s,int derivative)
+-    cdef c_Complex __hardy_z_function(self,c_Complex s)
+-    cdef int __compute_rank(self)
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r)
++    cdef c_Complex _value(self,c_Complex s,int derivative)
++    cdef c_Complex _hardy_z_function(self,c_Complex s)
++    cdef int _compute_rank(self)
+     #strange bug, replacing Double with double gives me a compile error
+-    cdef Double __typedN(self, double T)
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize,doublevec *result)
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec* result)
++    cdef Double _typedN(self, double T)
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize,doublevec *result)
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec* result)
+ 
+     cdef str _repr
+ 
+diff --git a/src/sage/libs/lcalc/lcalc_Lfunction.pyx b/src/sage/libs/lcalc/lcalc_Lfunction.pyx
+index 6e9005c502b..7b871ed049f 100644
+--- a/src/sage/libs/lcalc/lcalc_Lfunction.pyx
++++ b/src/sage/libs/lcalc/lcalc_Lfunction.pyx
+@@ -99,7 +99,7 @@ cdef class Lfunction:
+             tmpc=CCC(residue[i])
+             r[i+1] = new_Complex(mpfr_get_d(tmpc.__re, MPFR_RNDN), mpfr_get_d(tmpc.__im, MPFR_RNDN))
+ 
+-        self.__init_fun(NAME, what_type, dirichlet_coefficient, Period, q,  w,  A, g, l, n_poles, p, r)
++        self._init_fun(NAME, what_type, dirichlet_coefficient, Period, q,  w,  A, g, l, n_poles, p, r)
+ 
+         if name:
+             name += ': '
+@@ -180,7 +180,7 @@ cdef class Lfunction:
+         """
+         cdef ComplexNumber complexified_s = CCC(s)
+         cdef c_Complex z = new_Complex(mpfr_get_d(complexified_s.__re, MPFR_RNDN), mpfr_get_d(complexified_s.__im, MPFR_RNDN))
+-        cdef c_Complex result = self.__value(z, derivative)
++        cdef c_Complex result = self._value(z, derivative)
+         return CCC(result.real(),result.imag())
+ 
+     def hardy_z_function(self, s):
+@@ -223,7 +223,7 @@ cdef class Lfunction:
+         #This takes s -> .5 + I*s
+         cdef ComplexNumber complexified_s = CCC(0.5)+ CCC(0,1)*CCC(s)
+         cdef c_Complex z = new_Complex(mpfr_get_d(complexified_s.__re, MPFR_RNDN), mpfr_get_d(complexified_s.__im, MPFR_RNDN))
+-        cdef c_Complex result = self.__hardy_z_function(z)
++        cdef c_Complex result = self._hardy_z_function(z)
+         return CCC(result.real(),result.imag())
+ 
+ 
+@@ -249,9 +249,9 @@ cdef class Lfunction:
+             3
+ 
+         """
+-        return self.__compute_rank()
++        return self._compute_rank()
+ 
+-    def __N(self, T):
++    def _N(self, T):
+         """
+         Compute the number of zeroes upto height `T` using the formula for
+         `N(T)` with the error of `S(T)`. Please do not use this. It is only
+@@ -262,12 +262,12 @@ cdef class Lfunction:
+             sage: from sage.libs.lcalc.lcalc_Lfunction import *
+             sage: chi = DirichletGroup(5)[2] #This is a quadratic character
+             sage: L=Lfunction_from_character(chi, type="complex")
+-            sage: L.__N(10) # abs tol 1e-8
++            sage: L._N(10) # abs tol 1e-8
+             4.0
+         """
+         cdef RealNumber real_T=RRR(T)
+         cdef double double_T = mpfr_get_d(real_T.value, MPFR_RNDN)
+-        cdef double res_d = self.__typedN(double_T)
++        cdef double res_d = self._typedN(double_T)
+         return RRR(res_d)
+ 
+     def find_zeros(self, T1, T2, stepsize):
+@@ -323,7 +323,7 @@ cdef class Lfunction:
+         cdef RealNumber real_T2 = RRR(T2)
+         cdef RealNumber real_stepsize = RRR(stepsize)
+         sig_on()
+-        self.__find_zeros_v( mpfr_get_d(real_T1.value, MPFR_RNDN), mpfr_get_d(real_T2.value, MPFR_RNDN), mpfr_get_d(real_stepsize.value, MPFR_RNDN),&result)
++        self._find_zeros_v( mpfr_get_d(real_T1.value, MPFR_RNDN), mpfr_get_d(real_T2.value, MPFR_RNDN), mpfr_get_d(real_stepsize.value, MPFR_RNDN),&result)
+         sig_off()
+         i=result.size()
+         returnvalue = []
+@@ -399,7 +399,7 @@ cdef class Lfunction:
+         cdef const char* message_stamp = ""
+         cdef doublevec result
+         sig_on()
+-        self.__find_zeros(count, start, max_refine, rank, message_stamp, &result)
++        self._find_zeros(count, start, max_refine, rank, message_stamp, &result)
+         sig_off()
+         returnvalue = []
+         for i in range(result.size()):
+@@ -408,25 +408,25 @@ cdef class Lfunction:
+         return returnvalue
+ 
+     # Needs to be overriden
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         raise NotImplementedError
+ 
+-    cdef c_Complex __value(self,c_Complex s,int derivative):
++    cdef c_Complex _value(self,c_Complex s,int derivative):
+         raise NotImplementedError
+ 
+-    cdef c_Complex __hardy_z_function(self,c_Complex s):
++    cdef c_Complex _hardy_z_function(self,c_Complex s):
+         raise NotImplementedError
+ 
+-    cdef int __compute_rank(self):
++    cdef int _compute_rank(self):
+         raise NotImplementedError
+ 
+-    cdef double __typedN(self,double T):
++    cdef double _typedN(self,double T):
+         raise NotImplementedError
+ 
+-    cdef void __find_zeros_v(self,double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self,double T1, double T2, double stepsize, doublevec *result):
+         raise NotImplementedError
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         raise NotImplementedError
+ 
+ ##############################################################################
+@@ -497,7 +497,7 @@ cdef class Lfunction_I(Lfunction):
+         self._repr += " with integer Dirichlet coefficients"
+ 
+     # override
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         cdef int N = len(dirichlet_coeff)
+         cdef Integer tmpi
+         cdef int * coeffs = new_ints(N+1) #lcalc ignores 0the coefficient
+@@ -507,22 +507,22 @@ cdef class Lfunction_I(Lfunction):
+         self.thisptr=new_c_Lfunction_I(NAME, what_type,  N, coeffs, Period, q,  w,  A, g, l, n_poles, p, r)
+         del_ints(coeffs)
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_I *>(self.thisptr)).value(s, derivative, "pure")
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_I *>(self.thisptr)).value(s, 0, "rotated pure")
+ 
+-    cdef int __compute_rank(self):
++    cdef int _compute_rank(self):
+         return (<c_Lfunction_I *>(self.thisptr)).compute_rank()
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_I *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_I *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_I *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     # debug tools
+@@ -633,7 +633,7 @@ cdef class Lfunction_D(Lfunction):
+         self._repr += " with real Dirichlet coefficients"
+ 
+     # override
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         cdef int i
+         cdef RealNumber tmpr
+         cdef int N = len(dirichlet_coeff)
+@@ -644,23 +644,23 @@ cdef class Lfunction_D(Lfunction):
+         self.thisptr=new_c_Lfunction_D(NAME, what_type,  N, coeffs, Period, q,  w,  A, g, l, n_poles, p, r)
+         del_doubles(coeffs)
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_D *>(self.thisptr)).value(s, derivative, "pure")
+ 
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_D *>(self.thisptr)).value(s, 0, "rotated pure")
+ 
+-    cdef inline int __compute_rank(self):
++    cdef inline int _compute_rank(self):
+         return (<c_Lfunction_D *>(self.thisptr)).compute_rank()
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_D *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_D *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start,double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start,double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_D *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     # debug tools
+@@ -773,7 +773,7 @@ cdef class Lfunction_C:
+         self._repr += " with complex Dirichlet coefficients"
+ 
+     # override
+-    cdef void __init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
++    cdef void _init_fun(self, char *NAME, int what_type, dirichlet_coeff, long long Period, double q,  c_Complex w, int A, double *g, c_Complex *l, int n_poles, c_Complex *p, c_Complex *r):
+         cdef int i
+         cdef int N = len(dirichlet_coeff)
+         cdef ComplexNumber tmpc
+@@ -788,24 +788,24 @@ cdef class Lfunction_C:
+ 
+         del_Complexes(coeffs)
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_C *>(self.thisptr)).value(s, derivative, "pure")
+ 
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_C *>(self.thisptr)).value(s, 0,"rotated pure")
+ 
+-    cdef inline int __compute_rank(self):
++    cdef inline int _compute_rank(self):
+         return (<c_Lfunction_C *>(self.thisptr)).compute_rank()
+ 
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_C *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_C *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_C *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     # debug tools
+@@ -873,24 +873,24 @@ cdef class Lfunction_Zeta(Lfunction):
+         self.thisptr = new_c_Lfunction_Zeta()
+         self._repr = "The Riemann zeta function"
+ 
+-    cdef inline c_Complex __value(self,c_Complex s,int derivative):
++    cdef inline c_Complex _value(self,c_Complex s,int derivative):
+         return (<c_Lfunction_Zeta *>(self.thisptr)).value(s, derivative, "pure")
+ 
+ 
+-    cdef inline c_Complex __hardy_z_function(self,c_Complex s):
++    cdef inline c_Complex _hardy_z_function(self,c_Complex s):
+         return (<c_Lfunction_Zeta *>(self.thisptr)).value(s, 0, "rotated pure")
+ 
+-    cdef inline int __compute_rank(self):
++    cdef inline int _compute_rank(self):
+         return (<c_Lfunction_Zeta *>(self.thisptr)).compute_rank()
+ 
+ 
+-    cdef void __find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
++    cdef void _find_zeros_v(self, double T1, double T2, double stepsize, doublevec *result):
+         (<c_Lfunction_Zeta *>self.thisptr).find_zeros_v(T1,T2,stepsize,result[0])
+ 
+-    cdef double __typedN(self, double T):
++    cdef double _typedN(self, double T):
+         return (<c_Lfunction_Zeta *>self.thisptr).N(T)
+ 
+-    cdef int __find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
++    cdef int _find_zeros(self, long count, long start, double max_refine, int rank, const char* message_stamp, doublevec *result):
+         (<c_Lfunction_Zeta *>self.thisptr).find_zeros(count, start, max_refine, rank, message_stamp, result)
+ 
+     def __dealloc__(self):
+diff --git a/src/sage/libs/linkages/padics/Polynomial_ram.pxi b/src/sage/libs/linkages/padics/Polynomial_ram.pxi
+index 1ac51f1211f..e0584ecb8ad 100644
+--- a/src/sage/libs/linkages/padics/Polynomial_ram.pxi
++++ b/src/sage/libs/linkages/padics/Polynomial_ram.pxi
+@@ -55,16 +55,16 @@ cdef inline bint creduce(celement out, celement a, long prec, PowComputer_ prime
+     """
+     cdef celement ared = a % prime_pow.modulus
+     if ared is a and out is not a:
+-        out.__coeffs = ared.__coeffs[:]
++        out._coeffs = ared._coeffs[:]
+     else:
+-        out.__coeffs = ared.__coeffs
++        out._coeffs = ared._coeffs
+     cdef long coeff_prec = prec / prime_pow.e + 1
+     cdef long break_pt = prec % prime_pow.e
+-    for i in range(len(out.__coeffs)):
++    for i in range(len(out._coeffs)):
+         if i == break_pt:
+             coeff_prec -= 1
+-        out.__coeffs[i] = out.__coeffs[i].add_bigoh(coeff_prec)
+-    out.__normalize()
++        out._coeffs[i] = out._coeffs[i].add_bigoh(coeff_prec)
++    out._normalize()
+     return out == 0
+ 
+ cdef inline bint creduce_small(celement out, celement a, long prec, PowComputer_ prime_pow) except -1:
+@@ -116,7 +116,7 @@ cdef inline long cvaluation(celement a, long prec, PowComputer_ prime_pow) excep
+     higher.
+ 
+     """
+-    C = a.__coeffs
++    C = a._coeffs
+     if not C:
+         return prec
+     cdef long ret = maxordp
+@@ -161,7 +161,7 @@ cdef inline int cshift(celement shifted, celement rem, celement a, long n, long
+         v = cvaluation(a, prec, prime_pow)
+         notrunc = (v >= -n)
+     if notrunc:
+-        rem.__coeffs = []
++        rem._coeffs = []
+         return cshift_notrunc(shifted, a, n, prec, prime_pow, reduce_afterward)
+     if v > 0:
+         b = prime_pow.poly_ring(0)
+@@ -185,7 +185,7 @@ cdef inline int cshift(celement shifted, celement rem, celement a, long n, long
+     if reduce_afterward:
+         creduce(shifted, a, prec, prime_pow)
+     else:
+-        shifted.__coeffs = a.__coeffs[:]
++        shifted._coeffs = a._coeffs[:]
+ 
+ cdef inline int cshift_notrunc(celement out, celement a, long n, long prec, PowComputer_ prime_pow, bint reduce_afterward) except -1:
+     r"""
+@@ -236,7 +236,7 @@ cdef inline int cshift_notrunc(celement out, celement a, long n, long prec, PowC
+     if reduce_afterward:
+         creduce(out, a, prec, prime_pow)
+     else:
+-        out.__coeffs = a.__coeffs[:]
++        out._coeffs = a._coeffs[:]
+ 
+ cdef inline int cinvert(celement out, celement a, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -253,7 +253,7 @@ cdef inline int cinvert(celement out, celement a, long prec, PowComputer_ prime_
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = prime_pow.invert(a, prec).__coeffs
++    out._coeffs = prime_pow.invert(a, prec)._coeffs
+     creduce(out, out, prec, prime_pow)
+ 
+ cdef inline int cdivunit(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+@@ -335,7 +335,7 @@ cdef inline cexpansion_next(celement value, expansion_mode mode, long curpower,
+     # the following is specific to the ramified over unramified case.
+     modp_rep, term = value[0]._modp_rep(mode == smallest_mode)
+     if term:
+-        value.__coeffs[0] -= modp_rep
++        value._coeffs[0] -= modp_rep
+     cshift_notrunc(value, value, -1, curpower, prime_pow, False)
+     return term
+ 
+@@ -354,10 +354,10 @@ cdef inline cexpansion_getitem(celement value, long m, PowComputer_ prime_pow):
+     while m >= 0:
+         modp_rep, term = value[0]._modp_rep()
+         if m:
+-            if len(value.__coeffs):
+-                value.__coeffs[0] -= modp_rep
++            if len(value._coeffs):
++                value._coeffs[0] -= modp_rep
+             else:
+-                value.__coeffs.append(-modp_rep)
++                value._coeffs.append(-modp_rep)
+             cshift_notrunc(value, value, -1, 1, prime_pow, False)
+         m -= 1
+     return term
+@@ -379,9 +379,9 @@ cdef int cteichmuller(celement out, celement value, long prec, PowComputer_ prim
+ 
+     """
+     if value[0].valuation() > 0:
+-        out.__coeffs = []
++        out._coeffs = []
+     else:
+-        out.__coeffs = [value[0].parent().teichmuller(value[0])]
++        out._coeffs = [value[0].parent().teichmuller(value[0])]
+ 
+ cdef list ccoefficients(celement x, long valshift, long prec, PowComputer_ prime_pow):
+     """
+diff --git a/src/sage/libs/linkages/padics/Polynomial_shared.pxi b/src/sage/libs/linkages/padics/Polynomial_shared.pxi
+index 495dc6b0848..367bbc2f33d 100644
+--- a/src/sage/libs/linkages/padics/Polynomial_shared.pxi
++++ b/src/sage/libs/linkages/padics/Polynomial_shared.pxi
+@@ -106,7 +106,7 @@ cdef inline int ccmp(celement a, celement b, long prec, bint reduce_a, bint redu
+     if not (reduce_a or reduce_b):
+         return 0 if a == b else 1
+     csub(prime_pow.tmp_ccmp_a, a, b, prec, prime_pow)
+-    coeffs = prime_pow.tmp_ccmp_a.__coeffs
++    coeffs = prime_pow.tmp_ccmp_a._coeffs
+     cdef long i, coeff_prec, break_pt
+     if prime_pow.e == 1:
+         for i in range(prime_pow.tmp_ccmp_a.degree()+1):
+@@ -186,9 +186,9 @@ cdef inline int cneg(celement out, celement a, long prec, PowComputer_ prime_pow
+     """
+     cdef celement ma = -a
+     if ma is a:
+-        out.__coeffs = ma.__coeffs[:]
++        out._coeffs = ma._coeffs[:]
+     else:
+-        out.__coeffs = ma.__coeffs
++        out._coeffs = ma._coeffs
+ 
+ cdef inline int cadd(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -211,9 +211,9 @@ cdef inline int cadd(celement out, celement a, celement b, long prec, PowCompute
+     """
+     cdef celement sm = a + b
+     if sm is a or sm is b:
+-        out.__coeffs = sm.__coeffs[:]
++        out._coeffs = sm._coeffs[:]
+     else:
+-        out.__coeffs = sm.__coeffs
++        out._coeffs = sm._coeffs
+ 
+ cdef inline int csub(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -236,9 +236,9 @@ cdef inline int csub(celement out, celement a, celement b, long prec, PowCompute
+     """
+     cdef celement df = a - b
+     if df is a or df is b:
+-        out.__coeffs = df.__coeffs[:]
++        out._coeffs = df._coeffs[:]
+     else:
+-        out.__coeffs = df.__coeffs
++        out._coeffs = df._coeffs
+ 
+ cdef inline int cmul(celement out, celement a, celement b, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -261,9 +261,9 @@ cdef inline int cmul(celement out, celement a, celement b, long prec, PowCompute
+     """
+     cdef celement pd = a*b
+     if pd is a or pd is b:
+-        out.__coeffs = pd.__coeffs[:]
++        out._coeffs = pd._coeffs[:]
+     else:
+-        out.__coeffs = pd.__coeffs
++        out._coeffs = pd._coeffs
+ 
+ cdef inline int csetone(celement out, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -276,7 +276,7 @@ cdef inline int csetone(celement out, PowComputer_ prime_pow) except -1:
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = [prime_pow.base_ring(1)]
++    out._coeffs = [prime_pow.base_ring(1)]
+ 
+ cdef inline int csetzero(celement out, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -289,7 +289,7 @@ cdef inline int csetzero(celement out, PowComputer_ prime_pow) except -1:
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = []
++    out._coeffs = []
+ 
+ cdef inline bint cisone(celement a, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -330,7 +330,7 @@ cdef inline int ccopy(celement out, celement a, PowComputer_ prime_pow) except -
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = a.__coeffs[:]
++    out._coeffs = a._coeffs[:]
+ 
+ cdef inline cpickle(celement a, PowComputer_ prime_pow):
+     r"""
+@@ -343,7 +343,7 @@ cdef inline cpickle(celement a, PowComputer_ prime_pow):
+     - ``prime_pow`` the ``PowComputer`` for the ring
+ 
+     """
+-    return a.__coeffs
++    return a._coeffs
+ 
+ cdef inline int cunpickle(celement out, x, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -358,7 +358,7 @@ cdef inline int cunpickle(celement out, x, PowComputer_ prime_pow) except -1:
+     - ``prime_pow`` -- the ``PowComputer`` for the ring
+ 
+     """
+-    out.__coeffs = x
++    out._coeffs = x
+ 
+ cdef inline long chash(celement a, long ordp, long prec, PowComputer_ prime_pow) except -1:
+     r"""
+@@ -413,9 +413,9 @@ cdef int cconv(celement out, x, long prec, long valshift, PowComputer_ prime_pow
+     else:
+         xx = prime_pow.poly_ring(x)
+     if xx is x:
+-        out.__coeffs = xx.__coeffs[:]
++        out._coeffs = xx._coeffs[:]
+     else:
+-        out.__coeffs = xx.__coeffs
++        out._coeffs = xx._coeffs
+     if valshift > 0:
+         cshift_notrunc(out, out, -valshift, prec, prime_pow, True)
+     elif valshift == 0:
+@@ -458,12 +458,12 @@ cdef inline long cconv_mpz_t(celement out, mpz_t x, long prec, bint absolute, Po
+     mpz_set(n.value, x)
+ 
+     if n:
+-        out.__coeffs = [prime_pow.base_ring(n)]
++        out._coeffs = [prime_pow.base_ring(n)]
+         if not absolute:
+             valuation = cremove(out, out, prec, prime_pow)
+         creduce(out, out, prec, prime_pow)
+     else:
+-        out.__coeffs = []
++        out._coeffs = []
+ 
+     return valuation
+ 
+@@ -492,12 +492,12 @@ cdef inline int cconv_mpz_t_out(mpz_t out, celement x, long valshift, long prec,
+     else:
+         prime_pow.powhelper_cconv_out = x
+ 
+-    if len(prime_pow.powhelper_cconv_out.__coeffs) == 0:
++    if len(prime_pow.powhelper_cconv_out._coeffs) == 0:
+         mpz_set_ui(out, 0)
+-    elif len(prime_pow.powhelper_cconv_out.__coeffs) == 1:
++    elif len(prime_pow.powhelper_cconv_out._coeffs) == 1:
+         # recursively let the underlying polynomial convert the constant
+         # coefficient to an integer (if possible)
+-        n = ZZ(prime_pow.powhelper_cconv_out.__coeffs[0])
++        n = ZZ(prime_pow.powhelper_cconv_out._coeffs[0])
+         mpz_set(out, n.value)
+     else:
+         raise ValueError("cannot convert to integer")
+@@ -532,7 +532,7 @@ cdef inline long cconv_mpq_t(celement out, mpq_t x, long prec, bint absolute, Po
+     """
+     cdef Rational r = PY_NEW(Rational)
+     mpq_set(r.value, x)
+-    out.__coeffs = [prime_pow.base_ring(r)]
++    out._coeffs = [prime_pow.base_ring(r)]
+ 
+     if not absolute:
+         return cremove(out, out, prec, prime_pow)
+@@ -565,12 +565,12 @@ cdef inline int cconv_mpq_t_out(mpq_t out, celement x, long valshift, long prec,
+     else:
+         prime_pow.powhelper_cconv_out = x
+ 
+-    if len(prime_pow.powhelper_cconv_out.__coeffs) == 0:
++    if len(prime_pow.powhelper_cconv_out._coeffs) == 0:
+         mpq_set_ui(out, 0, 1)
+-    elif len(prime_pow.powhelper_cconv_out.__coeffs) == 1:
++    elif len(prime_pow.powhelper_cconv_out._coeffs) == 1:
+         # recursively let the underlying polynomial convert the constant
+         # coefficient to a rational (if possible)
+-        c = QQ(prime_pow.powhelper_cconv_out.__coeffs[0])
++        c = QQ(prime_pow.powhelper_cconv_out._coeffs[0])
+         mpq_set(out, c.value)
+     else:
+         raise ValueError("cannot convert to rational")
+diff --git a/src/sage/libs/ntl/ntl_lzz_p.pyx b/src/sage/libs/ntl/ntl_lzz_p.pyx
+index 161d0782bc2..af86b9bcf69 100644
+--- a/src/sage/libs/ntl/ntl_lzz_p.pyx
++++ b/src/sage/libs/ntl/ntl_lzz_p.pyx
+@@ -89,19 +89,19 @@ cdef class ntl_zz_p():
+         #self.c.restore_c()   ## This was done in __new__
+ 
+         if isinstance(a, IntegerMod_int):
+-            if (self.c.p == (<IntegerMod_int>a).__modulus.int32): ## this is slow
++            if (self.c.p == (<IntegerMod_int>a)._modulus.int32): ## this is slow
+                 self.x = (<IntegerMod_int>a).ivalue
+             else:
+                 raise ValueError("Mismatched modulus for converting to zz_p.")
+ 
+         elif isinstance(a, IntegerMod_int64):
+-            if (self.c.p == (<IntegerMod_int64>a).__modulus.int64): ## this is slow
++            if (self.c.p == (<IntegerMod_int64>a)._modulus.int64): ## this is slow
+                 self.x = (<IntegerMod_int64>a).ivalue
+             else:
+                 raise ValueError("Mismatched modulus for converting to zz_p.")
+ 
+         elif isinstance(a, IntegerMod_gmp):
+-            if (p_sage == (<IntegerMod_gmp>a).__modulus.sageInteger): ## this is slow
++            if (p_sage == (<IntegerMod_gmp>a)._modulus.sageInteger): ## this is slow
+                 self.x = mpz_get_si((<IntegerMod_gmp>a).value)
+             else:
+                 raise ValueError("Mismatched modulus for converting to zz_p.")
+diff --git a/src/sage/libs/ntl/ntl_lzz_pX.pyx b/src/sage/libs/ntl/ntl_lzz_pX.pyx
+index 24b503a9a62..7d19cc55e37 100644
+--- a/src/sage/libs/ntl/ntl_lzz_pX.pyx
++++ b/src/sage/libs/ntl/ntl_lzz_pX.pyx
+@@ -108,17 +108,17 @@ cdef class ntl_zz_pX():
+             a = ls[i]
+ 
+             if isinstance(a, IntegerMod_int):
+-                if (self.c.p == (<IntegerMod_int>a).__modulus.int32): ## this is slow
++                if (self.c.p == (<IntegerMod_int>a)._modulus.int32): ## this is slow
+                     zz_pX_SetCoeff_long(self.x, i, (<IntegerMod_int>a).ivalue)
+                 else:
+                     raise ValueError("Mismatched modulus for converting to zz_pX.")
+             elif isinstance(a, IntegerMod_int64):
+-                if (self.c.p == (<IntegerMod_int64>a).__modulus.int64): ## this is slow
++                if (self.c.p == (<IntegerMod_int64>a)._modulus.int64): ## this is slow
+                     zz_pX_SetCoeff_long(self.x, i, (<IntegerMod_int64>a).ivalue)
+                 else:
+                     raise ValueError("Mismatched modulus for converting to zz_pX.")
+             elif isinstance(a, IntegerMod_gmp):
+-                if (p_sage == (<IntegerMod_gmp>a).__modulus.sageInteger): ## this is slow
++                if (p_sage == (<IntegerMod_gmp>a)._modulus.sageInteger): ## this is slow
+                     zz_pX_SetCoeff_long(self.x, i, mpz_get_si((<IntegerMod_gmp>a).value))
+                 else:
+                     raise ValueError("Mismatched modulus for converting to zz_pX.")
+diff --git a/src/sage/matrix/matrix_complex_ball_dense.pyx b/src/sage/matrix/matrix_complex_ball_dense.pyx
+index 9e14079c6d4..47ca41070fa 100644
+--- a/src/sage/matrix/matrix_complex_ball_dense.pyx
++++ b/src/sage/matrix/matrix_complex_ball_dense.pyx
+@@ -664,7 +664,7 @@ cdef class Matrix_complex_ball_dense(Matrix_dense):
+         Pol = polynomial_ring_constructor._single_variate(self.base_ring(), var)
+         cdef Polynomial_complex_arb res = Polynomial_complex_arb(Pol)
+         sig_on()
+-        acb_mat_charpoly(res.__poly, self.value, prec(self))
++        acb_mat_charpoly(res._poly, self.value, prec(self))
+         sig_off()
+         return res
+ 
+diff --git a/src/sage/matrix/matrix_cyclo_dense.pyx b/src/sage/matrix/matrix_cyclo_dense.pyx
+index 15ff6394951..f1ed9af8403 100644
+--- a/src/sage/matrix/matrix_cyclo_dense.pyx
++++ b/src/sage/matrix/matrix_cyclo_dense.pyx
+@@ -396,11 +396,11 @@ cdef class Matrix_cyclo_dense(Matrix_dense):
+             # Now set k-th entry of x's numerator to tmp
+             fmpz_get_mpz(tmp, ftmp)
+             mpz_to_ZZ(&coeff, tmp)
+-            ZZX_SetCoeff(x.__numerator, k, coeff)
++            ZZX_SetCoeff(x._numerator, k, coeff)
+ 
+         # Set the denominator of x to denom.
+         fmpz_get_mpz(tmp, denom)
+-        mpz_to_ZZ(&x.__denominator, tmp)
++        mpz_to_ZZ(&x._denominator, tmp)
+         fmpz_clear(denom)
+         mpz_clear(tmp)
+         fmpz_clear(ftmp)
+diff --git a/src/sage/matrix/matrix_integer_dense.pyx b/src/sage/matrix/matrix_integer_dense.pyx
+index 9c509104967..8088350577c 100644
+--- a/src/sage/matrix/matrix_integer_dense.pyx
++++ b/src/sage/matrix/matrix_integer_dense.pyx
+@@ -1371,12 +1371,12 @@ cdef class Matrix_integer_dense(Matrix_dense):
+         if algorithm == 'flint':
+             g = (<Polynomial_integer_dense_flint> PolynomialRing(ZZ, names=var).gen())._new()
+             sig_on()
+-            fmpz_mat_charpoly(g.__poly, self._matrix)
++            fmpz_mat_charpoly(g._poly, self._matrix)
+             sig_off()
+         elif algorithm == 'linbox':
+             g = (<Polynomial_integer_dense_flint> PolynomialRing(ZZ, names=var).gen())._new()
+             sig_on()
+-            linbox_fmpz_mat_charpoly(g.__poly, self._matrix)
++            linbox_fmpz_mat_charpoly(g._poly, self._matrix)
+             sig_off()
+         elif algorithm == 'generic':
+             g = Matrix_dense.charpoly(self, var)
+@@ -1460,7 +1460,7 @@ cdef class Matrix_integer_dense(Matrix_dense):
+         if algorithm == 'linbox':
+             g = (<Polynomial_integer_dense_flint> PolynomialRing(ZZ, names=var).gen())._new()
+             sig_on()
+-            linbox_fmpz_mat_minpoly(g.__poly, self._matrix)
++            linbox_fmpz_mat_minpoly(g._poly, self._matrix)
+             sig_off()
+         elif algorithm == 'generic':
+             g = Matrix_dense.minpoly(self, var)
+diff --git a/src/sage/matrix/matrix_integer_sparse.pyx b/src/sage/matrix/matrix_integer_sparse.pyx
+index a41677c7b6a..83d5ee42fbe 100644
+--- a/src/sage/matrix/matrix_integer_sparse.pyx
++++ b/src/sage/matrix/matrix_integer_sparse.pyx
+@@ -869,10 +869,10 @@ cdef class Matrix_integer_sparse(Matrix_sparse):
+         sig_off()
+ 
+         cdef size_t i
+-        fmpz_poly_fit_length(g.__poly, p.size())
++        fmpz_poly_fit_length(g._poly, p.size())
+         for i in range(p.size()):
+-            fmpz_poly_set_coeff_mpz(g.__poly, i, p[0][i].get_mpz_const())
+-        _fmpz_poly_set_length(g.__poly, p.size())
++            fmpz_poly_set_coeff_mpz(g._poly, i, p[0][i].get_mpz_const())
++        _fmpz_poly_set_length(g._poly, p.size())
+ 
+         del M
+         del p
+@@ -968,10 +968,10 @@ cdef class Matrix_integer_sparse(Matrix_sparse):
+         sig_off()
+ 
+         cdef size_t i
+-        fmpz_poly_fit_length(g.__poly, p.size())
++        fmpz_poly_fit_length(g._poly, p.size())
+         for i in range(p.size()):
+-            fmpz_poly_set_coeff_mpz(g.__poly, i, p[0][i].get_mpz_const())
+-        _fmpz_poly_set_length(g.__poly, p.size())
++            fmpz_poly_set_coeff_mpz(g._poly, i, p[0][i].get_mpz_const())
++        _fmpz_poly_set_length(g._poly, p.size())
+ 
+         del M
+         del p
+diff --git a/src/sage/matroids/basis_exchange_matroid.pxd b/src/sage/matroids/basis_exchange_matroid.pxd
+index aec3bb54c42..28cc7ad868c 100644
+--- a/src/sage/matroids/basis_exchange_matroid.pxd
++++ b/src/sage/matroids/basis_exchange_matroid.pxd
+@@ -15,13 +15,13 @@ cdef class BasisExchangeMatroid(Matroid):
+     cdef _weak_invariant_var, _strong_invariant_var, _heuristic_invariant_var
+     cdef SetSystem _weak_partition_var, _strong_partition_var, _heuristic_partition_var
+ 
+-    cdef __relabel(self, l)
++    cdef _relabel(self, l)
+ 
+-    cdef __pack(self, bitset_t, X)
++    cdef _pack(self, bitset_t, X)
+     cdef __unpack(self, bitset_t)
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1
+-    cdef int __exchange(self, long x, long y) except -1
+-    cdef int __move(self, bitset_t X, bitset_t Y) except -1
++    cdef bint _is_exchange_pair(self, long x, long y) except -1
++    cdef int _exchange(self, long x, long y) except -1
++    cdef int _move(self, bitset_t X, bitset_t Y) except -1
+     cdef __fundamental_cocircuit(self, bitset_t, long x)
+     cdef __fundamental_circuit(self, bitset_t, long y)
+ 
+@@ -30,7 +30,7 @@ cdef class BasisExchangeMatroid(Matroid):
+     cdef __closure(self, bitset_t, bitset_t)
+     cdef __max_coindependent(self, bitset_t, bitset_t)
+     cdef __cocircuit(self, bitset_t, bitset_t)
+-    cdef __coclosure(self, bitset_t, bitset_t)
++    cdef _coclosure_internal(self, bitset_t, bitset_t)
+ 
+     cdef __augment(self, bitset_t, bitset_t, bitset_t)
+     cdef bint __is_independent(self, bitset_t F) except -1
+diff --git a/src/sage/matroids/basis_exchange_matroid.pyx b/src/sage/matroids/basis_exchange_matroid.pyx
+index 90d10842d46..015fa8b8df3 100644
+--- a/src/sage/matroids/basis_exchange_matroid.pyx
++++ b/src/sage/matroids/basis_exchange_matroid.pyx
+@@ -57,10 +57,10 @@ cdef class BasisExchangeMatroid(Matroid):
+ 
+     This base exchange graph is not stored as such, but should be provided
+     implicitly by the child class in the form of two methods
+-    ``__is_exchange_pair(x, y)`` and ``__exchange(x, y)``, as well as an
++    ``_is_exchange_pair(x, y)`` and ``_exchange(x, y)``, as well as an
+     initial basis. At any moment, BasisExchangeMatroid keeps a current basis
+-    `B`. The method ``__is_exchange_pair(x, y)`` should return a boolean
+-    indicating whether `B - x + y` is a basis. The method ``__exchange(x, y)``
++    `B`. The method ``_is_exchange_pair(x, y)`` should return a boolean
++    indicating whether `B - x + y` is a basis. The method ``_exchange(x, y)``
+     is called when the current basis `B` is replaced by said `B-x + y`. It is
+     up to the child class to update its internal data structure to make
+     information relative to the new basis more accessible. For instance, a
+@@ -81,16 +81,16 @@ cdef class BasisExchangeMatroid(Matroid):
+     - :class:`BasisMatroid <sage.matroids.basis_matroid.BasisMatroid>`: keeps
+       a list of all bases.
+ 
+-        - ``__is_exchange_pair(x, y)`` reduces to a query whether `B - x + y`
++        - ``_is_exchange_pair(x, y)`` reduces to a query whether `B - x + y`
+           is a basis.
+-        - ``__exchange(x, y)`` has no work to do.
++        - ``_exchange(x, y)`` has no work to do.
+ 
+     - :class:`LinearMatroid <sage.matroids.linear_matroid.LinearMatroid>`:
+       keeps a matrix representation `A` of the matroid so that `A[B] = I`.
+ 
+-        - ``__is_exchange_pair(x, y)`` reduces to testing whether `A[r, y]`
++        - ``_is_exchange_pair(x, y)`` reduces to testing whether `A[r, y]`
+           is nonzero, where `A[r, x]=1`.
+-        - ``__exchange(x, y)`` should modify the matrix so that `A[B - x + y]`
++        - ``_exchange(x, y)`` should modify the matrix so that `A[B - x + y]`
+           becomes `I`, which means pivoting on `A[r, y]`.
+ 
+     - ``TransversalMatroid`` (not yet implemented): If `A` is a set of subsets
+@@ -100,17 +100,17 @@ cdef class BasisExchangeMatroid(Matroid):
+       edge `(A_i,e)` if `e` is in the subset `A_i`. At any time you keep a
+       maximum matching `M` of `G` covering the current basis `B`.
+ 
+-        - ``__is_exchange_pair(x, y)`` checks for the existence of an
++        - ``_is_exchange_pair(x, y)`` checks for the existence of an
+           `M`-alternating path `P` from `y` to `x`.
+-        - ``__exchange(x, y)`` replaces `M` by the symmetric difference of
++        - ``_exchange(x, y)`` replaces `M` by the symmetric difference of
+           `M` and `E(P)`.
+ 
+     - ``AlgebraicMatroid`` (not yet implemented): keeps a list of polynomials
+       in variables `E - B + e` for each variable `e` in `B`.
+ 
+-        - ``__is_exchange_pair(x, y)`` checks whether the polynomial that
++        - ``_is_exchange_pair(x, y)`` checks whether the polynomial that
+           relates `y` to `E-B` uses `x`.
+-        - ``__exchange(x, y)`` make new list of polynomials by computing
++        - ``_exchange(x, y)`` make new list of polynomials by computing
+           resultants.
+ 
+     All but the first of the above matroids are algebraic, and all
+@@ -139,7 +139,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         This initializer sets up a correspondence between elements of
+         ``groundset`` and ``range(len(groundset))``. ``BasisExchangeMatroid``
+         uses this correspondence for encoding of subsets of the groundset as
+-        bitpacked sets of integers --- see ``__pack()`` and ``__unpack()``. In
++        bitpacked sets of integers --- see ``_pack()`` and ``__unpack()``. In
+         general, methods of ``BasisExchangeMatroid`` having a name starting
+         with two underscores deal with such encoded subsets.
+ 
+@@ -180,7 +180,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             self._idx[self._E[i]] = i
+ 
+         if basis is not None:
+-            self.__pack(self._current_basis, frozenset(basis))
++            self._pack(self._current_basis, frozenset(basis))
+ 
+     def __dealloc__(self):
+         bitset_free(self._current_basis)
+@@ -191,7 +191,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_free(self._output)
+         bitset_free(self._temp)
+ 
+-    cdef __relabel(self, l):
++    cdef _relabel(self, l):
+         """
+         Relabel each element `e` as `l[e]`, where `l` is a given injective map.
+ 
+@@ -231,7 +231,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             self._heuristic_partition_var._relabel(l)
+ 
+     # the engine
+-    cdef __pack(self, bitset_t I, F):
++    cdef _pack(self, bitset_t I, F):
+         """
+         Encode a subset F of the groundset into a bitpacked set of integers
+         """
+@@ -252,21 +252,21 @@ cdef class BasisExchangeMatroid(Matroid):
+         return frozenset(F)
+ 
+     # this method needs to be overridden by child class
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         """
+         Test if current_basis-x + y is a basis
+         """
+         raise NotImplementedError
+ 
+     # if this method is overridden by a child class, the child class needs to call this method
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         """
+         put current_basis <-- current_basis-x + y
+         """
+         bitset_discard(self._current_basis, x)
+         bitset_add(self._current_basis, y)
+ 
+-    cdef int __move(self, bitset_t X, bitset_t Y) except -1:
++    cdef int _move(self, bitset_t X, bitset_t Y) except -1:
+         """
+         Change current_basis to minimize intersection with ``X``, maximize intersection with ``Y``.
+         """
+@@ -275,8 +275,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         while x >= 0:
+             y = bitset_first(Y)
+             while y >= 0:
+-                if self.__is_exchange_pair(x, y):
+-                    self.__exchange(x, y)
++                if self._is_exchange_pair(x, y):
++                    self._exchange(x, y)
+                     bitset_discard(Y, y)
+                     bitset_discard(X, x)
+                     if bitset_isempty(Y):
+@@ -295,7 +295,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_complement(self._temp, self._current_basis)
+         y = bitset_first(self._temp)
+         while y >= 0:
+-            if self.__is_exchange_pair(x, y):
++            if self._is_exchange_pair(x, y):
+                 bitset_add(C, y)
+             y = bitset_next(self._temp, y + 1)
+         bitset_add(C, x)
+@@ -308,7 +308,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_clear(C)
+         x = bitset_first(self._current_basis)
+         while x >= 0:
+-            if self.__is_exchange_pair(x, y):
++            if self._is_exchange_pair(x, y):
+                 bitset_add(C, x)
+             x = bitset_next(self._current_basis, x + 1)
+         bitset_add(C, y)
+@@ -319,7 +319,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, F)
+         bitset_difference(self._outside, F, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_intersection(R, self._current_basis, F)
+ 
+     cdef __circuit(self, bitset_t R, bitset_t F):
+@@ -335,8 +335,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         while y >= 0:
+             x = bitset_first(self._inside)
+             while x >= 0:
+-                if self.__is_exchange_pair(x, y):
+-                    self.__exchange(x, y)
++                if self._is_exchange_pair(x, y):
++                    self._exchange(x, y)
+                     bitset_discard(self._outside, y)
+                     bitset_discard(self._inside, x)
+                     if bitset_isempty(self._outside):
+@@ -355,7 +355,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, F)
+         bitset_difference(self._outside, F, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_set_first_n(R, self._groundset_size)
+         cdef long x = bitset_first(self._inside)
+         while x >= 0:
+@@ -370,7 +370,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_difference(R, F, self._current_basis)
+ 
+     cdef __cocircuit(self, bitset_t R, bitset_t F):
+@@ -387,8 +387,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         while x >= 0:
+             y = bitset_first(self._outside)
+             while y >= 0:
+-                if self.__is_exchange_pair(x, y):
+-                    self.__exchange(x, y)
++                if self._is_exchange_pair(x, y):
++                    self._exchange(x, y)
+                     bitset_discard(self._outside, y)
+                     bitset_discard(self._inside, x)
+                     if bitset_isempty(self._inside):
+@@ -401,14 +401,14 @@ cdef class BasisExchangeMatroid(Matroid):
+                 return
+             x = bitset_next(self._inside, x + 1)
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``closure``.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_set_first_n(R, self._groundset_size)
+         cdef long y = bitset_first(self._outside)
+         while y >= 0:
+@@ -422,10 +422,10 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, X)
+         bitset_difference(self._outside, X, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_difference(self._inside, self._inside, Y)
+         bitset_difference(self._outside, Y, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_intersection(R, self._current_basis, Y)
+ 
+     cdef bint __is_independent(self, bitset_t F) except -1:
+@@ -434,7 +434,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, F)
+         bitset_difference(self._outside, F, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         return bitset_isempty(self._outside)
+ 
+     cdef __move_current_basis(self, bitset_t X, bitset_t Y):
+@@ -443,21 +443,21 @@ cdef class BasisExchangeMatroid(Matroid):
+         """
+         bitset_difference(self._inside, self._current_basis, X)
+         bitset_difference(self._outside, X, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         bitset_intersection(self._inside, self._current_basis, Y)
+         bitset_complement(self._outside, self._current_basis)
+         bitset_difference(self._outside, self._outside, Y)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+     # functions for derived classes and for parent class
+     cdef bint _set_current_basis(self, F):
+         """
+         Set _current_basis to subset of the groundset ``F``.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         bitset_difference(self._inside, self._current_basis, self._input)
+         bitset_difference(self._outside, self._input, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+         return bitset_isempty(self._outside) and bitset_isempty(self._inside)
+ 
+     # groundset and full_rank
+@@ -630,8 +630,8 @@ cdef class BasisExchangeMatroid(Matroid):
+             ['b', 'c', 'e', 'f']
+ 
+         """
+-        self.__pack(self._input, X)
+-        self.__pack(self._input2, Y)
++        self._pack(self._input, X)
++        self._pack(self._input2, Y)
+         self.__move_current_basis(self._input, self._input2)
+ 
+     cpdef _max_independent(self, F):
+@@ -661,7 +661,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.max_independent>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_independent(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -692,7 +692,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.rank>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_independent(self._output, self._input)
+         return bitset_len(self._output)
+ 
+@@ -729,7 +729,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             the input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.circuit>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__circuit(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -754,7 +754,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             sage: sorted(M._fundamental_circuit('abcd', 'e'))
+             ['a', 'b', 'c', 'e']
+         """
+-        self.__pack(self._input, B)
++        self._pack(self._input, B)
+         bitset_clear(self._input2)
+         self.__move_current_basis(self._input, self._input2)
+         self.__fundamental_circuit(self._output, self._idx[e])
+@@ -787,7 +787,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             :meth:`<sage.matroids.matroid.Matroid.closure>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__closure(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -818,7 +818,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.max_coindependent>`.
+ 
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_coindependent(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -848,7 +848,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.corank>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__max_coindependent(self._output, self._input)
+         return bitset_len(self._output)
+ 
+@@ -885,7 +885,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.cocircuit>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         self.__cocircuit(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+@@ -910,7 +910,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             sage: sorted(M._fundamental_cocircuit('efgh', 'e'))
+             ['b', 'c', 'd', 'e']
+         """
+-        self.__pack(self._input, B)
++        self._pack(self._input, B)
+         bitset_clear(self._input2)
+         self.__move_current_basis(self._input, self._input2)
+         self.__fundamental_cocircuit(self._output, self._idx[e])
+@@ -943,8 +943,8 @@ cdef class BasisExchangeMatroid(Matroid):
+             see :meth:`<sage.matroids.matroid.Matroid.coclosure>`.
+ 
+         """
+-        self.__pack(self._input, F)
+-        self.__coclosure(self._output, self._input)
++        self._pack(self._input, F)
++        self._coclosure_internal(self._output, self._input)
+         return self.__unpack(self._output)
+ 
+     cpdef _augment(self, X, Y):
+@@ -973,8 +973,8 @@ cdef class BasisExchangeMatroid(Matroid):
+             ['e', 'f', 'g']
+ 
+         """
+-        self.__pack(self._input, X)
+-        self.__pack(self._input2, Y)
++        self._pack(self._input, X)
++        self._pack(self._input2, Y)
+         self.__augment(self._output, self._input, self._input2)
+         return self.__unpack(self._output)
+ 
+@@ -1006,7 +1006,7 @@ cdef class BasisExchangeMatroid(Matroid):
+             the input is indeed a subset of the ground set,
+             see :meth:`<sage.matroids.matroid.Matroid.is_independent>`.
+         """
+-        self.__pack(self._input, F)
++        self._pack(self._input, F)
+         return self.__is_independent(self._input)
+ 
+     # connectivity
+@@ -1142,8 +1142,8 @@ cdef class BasisExchangeMatroid(Matroid):
+         cdef bitset_t SS, TT
+         bitset_init(SS, self._groundset_size)
+         bitset_init(TT, self._groundset_size)
+-        self.__pack(SS,S)
+-        self.__pack(TT,T)
++        self._pack(SS,S)
++        self._pack(TT,T)
+         #F = set(self.groundset()) - (S | T)
+         cdef bitset_t F, I
+         bitset_init(F, self._groundset_size)
+@@ -1421,7 +1421,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         Rcoflats = SetSystem(self._E)
+         i = 0
+         bitset_clear(todo[0])
+-        self.__coclosure(coflats[0], todo[0])
++        self._coclosure_internal(coflats[0], todo[0])
+         bitset_complement(todo[0], coflats[0])
+         self._coflats_rec(Rcoflats, r, coflats, todo, 0, 0)
+         for i in range(r + 1):
+@@ -1443,7 +1443,7 @@ cdef class BasisExchangeMatroid(Matroid):
+         while e >= 0:
+             bitset_copy(self._input, coflats[i])
+             bitset_add(self._input, e)
+-            self.__coclosure(coflats[i + 1], self._input)
++            self._coclosure_internal(coflats[i + 1], self._input)
+             bitset_difference(todo[i], todo[i], coflats[i + 1])
+             bitset_difference(todo[i + 1], coflats[i + 1], coflats[i])
+             if bitset_first(todo[i + 1]) == e:
+@@ -2397,7 +2397,7 @@ cdef class BasisExchangeMatroid(Matroid):
+                 # Set current basis to Y
+                 bitset_difference(self._inside, self._current_basis, BB._subsets[pointerY])
+                 bitset_difference(self._outside, BB._subsets[pointerY], self._current_basis)
+-                self.__move(self._inside, self._outside)
++                self._move(self._inside, self._outside)
+                 if not bitset_eq(self._current_basis, BB._subsets[pointerY]):
+                     # We failed to set the current basis to Y through basis exchanges.
+                     # Therefore, the exchange axioms are violated!
+@@ -2409,7 +2409,7 @@ cdef class BasisExchangeMatroid(Matroid):
+                     foundpair = False
+                     y = bitset_first(self._input2)
+                     while y >= 0:  # for y in Y-X
+-                        if self.__is_exchange_pair(y, x):
++                        if self._is_exchange_pair(y, x):
+                             foundpair = True
+                             y = -1
+                         else:
+diff --git a/src/sage/matroids/basis_matroid.pyx b/src/sage/matroids/basis_matroid.pyx
+index 3ac43112627..c1b6e9b04c8 100644
+--- a/src/sage/matroids/basis_matroid.pyx
++++ b/src/sage/matroids/basis_matroid.pyx
+@@ -219,7 +219,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+                     raise ValueError("basis has wrong cardinality.")
+                 if not b.issubset(self._groundset):
+                     raise ValueError("basis is not a subset of the groundset")
+-                self.__pack(self._b, b)
++                self._pack(self._b, b)
+                 i = set_to_index(self._b)
+                 if not bitset_in(self._bb, i):
+                     self._bcount += 1
+@@ -234,7 +234,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+                         raise ValueError("nonbasis has wrong cardinality")
+                     if not b.issubset(self._groundset):
+                         raise ValueError("nonbasis is not a subset of the groundset")
+-                    self.__pack(self._b, b)
++                    self._pack(self._b, b)
+                     i = set_to_index(self._b)
+                     if bitset_in(self._bb, i):
+                         self._bcount -= 1
+@@ -263,7 +263,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+ 
+     # support for parent BasisExchangeMatroid
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:      # test if current_basis-x + y is a basis
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:      # test if current_basis-x + y is a basis
+         """
+         Test if `B-e + f` is a basis of the current matroid.
+ 
+@@ -326,7 +326,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+             sage: M._is_basis(set(['a', 'b', 'c', 'd']))
+             False
+         """
+-        self.__pack(self._b, X)
++        self._pack(self._b, X)
+         return bitset_in(self._bb, set_to_index(self._b))
+ 
+     # dual and minors
+@@ -557,7 +557,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+ 
+         """
+         M = BasisMatroid(M=self)
+-        M.__relabel(l)
++        M._relabel(l)
+         return M
+ 
+     # enumeration
+@@ -1177,7 +1177,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+ 
+         """
+         N = BasisMatroid(M=self)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo=None):
+@@ -1201,7 +1201,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+         if memo is None:
+             memo = {}
+         N = BasisMatroid(M=self)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __reduce__(self):
+@@ -1230,7 +1230,7 @@ cdef class BasisMatroid(BasisExchangeMatroid):
+         """
+         import sage.matroids.unpickling
+         BB = bitset_pickle(self._bb)
+-        data = (self._E, self._matroid_rank, getattr(self, '__custom_name'), BB)
++        data = (self._E, self._matroid_rank, self.get_custom_name(), BB)
+         version = 0
+         return sage.matroids.unpickling.unpickle_basis_matroid, (version, data)
+ 
+diff --git a/src/sage/matroids/circuit_closures_matroid.pyx b/src/sage/matroids/circuit_closures_matroid.pyx
+index 402822b2dc6..4e79b0575e2 100644
+--- a/src/sage/matroids/circuit_closures_matroid.pyx
++++ b/src/sage/matroids/circuit_closures_matroid.pyx
+@@ -513,8 +513,7 @@ cdef class CircuitClosuresMatroid(Matroid):
+         N._groundset = self._groundset
+         N._circuit_closures = self._circuit_closures
+         N._matroid_rank = self._matroid_rank
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo=None):
+@@ -539,8 +538,7 @@ cdef class CircuitClosuresMatroid(Matroid):
+         from copy import deepcopy
+         # Since matroids are immutable, N cannot reference itself in correct code, so no need to worry about the recursion.
+         N = CircuitClosuresMatroid(groundset=deepcopy(self._groundset, memo), circuit_closures=deepcopy(self._circuit_closures, memo))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -570,7 +568,7 @@ cdef class CircuitClosuresMatroid(Matroid):
+              4: {{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}}}
+         """
+         import sage.matroids.unpickling
+-        data = (self._groundset, self._circuit_closures, getattr(self, '__custom_name'))
++        data = (self._groundset, self._circuit_closures, self.get_custom_name())
+         version = 0
+         return sage.matroids.unpickling.unpickle_circuit_closures_matroid, (version, data)
+ 
+diff --git a/src/sage/matroids/dual_matroid.py b/src/sage/matroids/dual_matroid.py
+index 804e43f035b..da6639827e4 100644
+--- a/src/sage/matroids/dual_matroid.py
++++ b/src/sage/matroids/dual_matroid.py
+@@ -519,9 +519,7 @@ def __copy__(self):
+ 
+         """
+         N = DualMatroid(self._matroid)
+-        if getattr(self, '__custom_name') is not None:
+-            # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -543,10 +541,7 @@ def __deepcopy__(self, memo={}):
+         """
+         from copy import deepcopy
+         N = DualMatroid(deepcopy(self._matroid, memo))
+-        if getattr(self, '__custom_name') is not None:
+-            # because of name wrangling, this is not caught by the
+-            # default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -575,6 +570,6 @@ def __reduce__(self):
+              4: {{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}}}'
+         """
+         import sage.matroids.unpickling
+-        data = (self._matroid, getattr(self, '__custom_name'))
++        data = (self._matroid, self.get_custom_name())
+         version = 0
+         return sage.matroids.unpickling.unpickle_dual_matroid, (version, data)
+diff --git a/src/sage/matroids/graphic_matroid.py b/src/sage/matroids/graphic_matroid.py
+index 5216ef11517..c727dc54e52 100644
+--- a/src/sage/matroids/graphic_matroid.py
++++ b/src/sage/matroids/graphic_matroid.py
+@@ -481,8 +481,7 @@ def __copy__(self):
+             False
+         """
+         N = GraphicMatroid(self._G)
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -502,8 +501,7 @@ def __deepcopy__(self, memo={}):
+         """
+         # The only real difference between this and __copy__() is the memo
+         N = GraphicMatroid(deepcopy(self._G, memo))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -519,7 +517,7 @@ def __reduce__(self):
+             Graphic matroid of rank 9 on 15 elements
+         """
+         from .unpickling import unpickle_graphic_matroid
+-        data = (self._G, getattr(self, '__custom_name'))
++        data = (self._G, self.get_custom_name())
+         version = 0
+         return unpickle_graphic_matroid, (version, data)
+ 
+diff --git a/src/sage/matroids/linear_matroid.pxd b/src/sage/matroids/linear_matroid.pxd
+index 014c8aef57d..9aebd446b68 100644
+--- a/src/sage/matroids/linear_matroid.pxd
++++ b/src/sage/matroids/linear_matroid.pxd
+@@ -15,7 +15,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+     cpdef characteristic(self)
+ 
+     cdef list _setup_internal_representation(self, matrix, reduced_matrix, ring, keep_initial_representation)
+-    cdef __exchange_value(self, long x, long y)
++    cdef _exchange_value_internal(self, long x, long y)
+ 
+     cpdef representation(self, B=*, reduced=*, labels=*, order=*, lift_map=*)
+     cpdef _current_rows_cols(self, B=*)
+diff --git a/src/sage/matroids/linear_matroid.pyx b/src/sage/matroids/linear_matroid.pyx
+index 61452e80c48..36f563aa433 100644
+--- a/src/sage/matroids/linear_matroid.pyx
++++ b/src/sage/matroids/linear_matroid.pyx
+@@ -391,13 +391,13 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         """
+         return characteristic(self._A)
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return self._A.is_nonzero(self._prow[x], self._prow[y])
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         """
+         Put element indexed by ``x`` into basis, taking out element ``y``.
+         Assumptions are that this is a valid basis exchange.
+@@ -420,9 +420,9 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         self._A.set_unsafe(px, py, pivi)
+         self._prow[y] = px
+         self._prow[x] = py
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -605,7 +605,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+                     self._representation = self._basic_representation(B)
+                 A = self._representation
+             else:
+-                B = self.__subset(B)
++                B = self._subset_internal(B)
+                 A = self._basic_representation(B)
+             A = A.matrix_from_rows_and_columns(range(A.nrows()), order_idx)
+             if lift_map is None:
+@@ -622,7 +622,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+             if B is None:
+                 B = frozenset(self.basis())
+             else:
+-                B = self.__subset(B)
++                B = self._subset_internal(B)
+             A = self._reduced_representation(B)
+             R, C = self._current_rows_cols()
+             Ri = []
+@@ -1493,7 +1493,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+             sage: M._exchange_value(1, 3)
+             4
+         """
+-        return self.__exchange_value(self._idx[e], self._idx[f])
++        return self._exchange_value_internal(self._idx[e], self._idx[f])
+ 
+     cpdef fundamental_cycle(self, B, e):
+         """
+@@ -2909,7 +2909,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = LinearMatroid(groundset=rows + cols, reduced_matrix=self._A)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -2930,7 +2930,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = LinearMatroid(groundset=deepcopy(rows + cols, memo), reduced_matrix=deepcopy(self._A, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -2979,7 +2979,7 @@ cdef class LinearMatroid(BasisExchangeMatroid):
+             rows, cols = self._current_rows_cols()
+             gs = rows + cols
+             reduced = True
+-        data = (A, gs, reduced, getattr(self, '__custom_name'))
++        data = (A, gs, reduced, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_linear_matroid, (version, data)
+ 
+ # Binary matroid
+@@ -3152,20 +3152,20 @@ cdef class BinaryMatroid(LinearMatroid):
+         """
+         return 2
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<BinaryMatrix>self._A).is_nonzero(self._prow[x], y)
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         r"""
+         Replace ``self.basis() with ``self.basis() - x + y``. Internal method, does no checks.
+         """
+         cdef long p = self._prow[x]
+         self._A.pivot(p, y)   # Not a Sage matrix operation
+         self._prow[y] = p
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+     cdef  __fundamental_cocircuit(self, bitset_t C, long x):
+         r"""
+@@ -3173,18 +3173,18 @@ cdef class BinaryMatroid(LinearMatroid):
+         """
+         bitset_copy(C, (<BinaryMatrix>self._A)._M[self._prow[x]])
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``coclosure``.
+ 
+-        This function overrides the internal function BasisExchangeMatroid.__coclosure() of the parent class.
++        This function overrides the internal function BasisExchangeMatroid._coclosure_internal() of the parent class.
+         The implementation should be more efficient for BinaryMatroid, due to the fact that in this class,
+         __fundamental_cocircuit is much faster than __fundamental_circuit.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+         bitset_copy(R, F)
+         bitset_difference(self._inside, self._current_basis, F)
+@@ -3196,7 +3196,7 @@ cdef class BinaryMatroid(LinearMatroid):
+                 bitset_add(R, y)
+             y = bitset_next(self._inside, y + 1)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -3964,7 +3964,7 @@ cdef class BinaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = BinaryMatroid(groundset=self._E, matrix=self._A, basis=basis)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -3989,7 +3989,7 @@ cdef class BinaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = BinaryMatroid(groundset=deepcopy(self._E, memo), matrix=deepcopy(self._A, memo), basis=deepcopy(basis, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -4047,7 +4047,7 @@ cdef class BinaryMatroid(LinearMatroid):
+             A = self._A
+             # current basis ordered so matrix cols form identity matrix:
+             basis = self._current_rows_cols()[0]
+-        data = (A, gs, basis, getattr(self, '__custom_name'))
++        data = (A, gs, basis, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_binary_matroid, (version, data)
+ 
+ cdef class TernaryMatroid(LinearMatroid):
+@@ -4220,20 +4220,20 @@ cdef class TernaryMatroid(LinearMatroid):
+         """
+         return 3
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<TernaryMatrix>self._A).is_nonzero(self._prow[x], y)
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         r"""
+         Replace ``self.basis() with ``self.basis() - x + y``. Internal method, does no checks.
+         """
+         cdef long p = self._prow[x]
+         self._A.pivot(p, y)   # Not a Sage matrix operation
+         self._prow[y] = p
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+     cdef  __fundamental_cocircuit(self, bitset_t C, long x):
+         r"""
+@@ -4241,18 +4241,18 @@ cdef class TernaryMatroid(LinearMatroid):
+         """
+         bitset_copy(C, (<TernaryMatrix>self._A)._M0[self._prow[x]])
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``coclosure``.
+ 
+-        This function overrides the internal function BasisExchangeMatroid.__coclosure() of the parent class.
++        This function overrides the internal function BasisExchangeMatroid._coclosure_internal() of the parent class.
+         The implementation should be more efficient for TernaryMatroid, due to the fact that in this class,
+         __fundamental_cocircuit is much faster than __fundamental_circuit.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+         bitset_copy(R, F)
+         bitset_difference(self._inside, self._current_basis, F)
+@@ -4264,7 +4264,7 @@ cdef class TernaryMatroid(LinearMatroid):
+                 bitset_add(R, y)
+             y = bitset_next(self._inside, y + 1)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -4858,7 +4858,7 @@ cdef class TernaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = TernaryMatroid(groundset=self._E, matrix=self._A, basis=basis)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -4883,7 +4883,7 @@ cdef class TernaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = TernaryMatroid(groundset=deepcopy(self._E, memo), matrix=deepcopy(self._A, memo), basis=deepcopy(basis, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -4945,7 +4945,7 @@ cdef class TernaryMatroid(LinearMatroid):
+             A = self._A
+             # current basis ordered so matrix cols form identity matrix:
+             basis = self._current_rows_cols()[0]
+-        data = (A, gs, basis, getattr(self, '__custom_name'))
++        data = (A, gs, basis, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_ternary_matroid, (version, data)
+ 
+ # Quaternary Matroids
+@@ -5122,20 +5122,20 @@ cdef class QuaternaryMatroid(LinearMatroid):
+         """
+         return 2
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<QuaternaryMatrix>self._A).is_nonzero(self._prow[x], y)
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         r"""
+         Replace ``self.basis() with ``self.basis() - x + y``. Internal method, does no checks.
+         """
+         cdef long p = self._prow[x]
+         self._A.pivot(p, y)   # Not a Sage matrix operation
+         self._prow[y] = p
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+     cdef  __fundamental_cocircuit(self, bitset_t C, long x):
+         r"""
+@@ -5143,18 +5143,18 @@ cdef class QuaternaryMatroid(LinearMatroid):
+         """
+         bitset_union(C, (<QuaternaryMatrix>self._A)._M0[self._prow[x]], (<QuaternaryMatrix>self._A)._M1[self._prow[x]])
+ 
+-    cdef __coclosure(self, bitset_t R, bitset_t F):
++    cdef _coclosure_internal(self, bitset_t R, bitset_t F):
+         """
+         Bitpacked version of ``coclosure``.
+ 
+-        This function overrides the internal function BasisExchangeMatroid.__coclosure() of the parent class.
++        This function overrides the internal function BasisExchangeMatroid._coclosure_internal() of the parent class.
+         The implementation should be more efficient for QuaternaryMatroid, due to the fact that in this class,
+         __fundamental_cocircuit is much faster than __fundamental_circuit.
+         """
+         bitset_complement(R, F)
+         bitset_difference(self._inside, self._current_basis, R)
+         bitset_difference(self._outside, R, self._current_basis)
+-        self.__move(self._inside, self._outside)
++        self._move(self._inside, self._outside)
+ 
+         bitset_copy(R, F)
+         bitset_difference(self._inside, self._current_basis, F)
+@@ -5166,7 +5166,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+                 bitset_add(R, y)
+             y = bitset_next(self._inside, y + 1)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+         """
+@@ -5589,7 +5589,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = QuaternaryMatroid(groundset=self._E, matrix=self._A, basis=basis)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -5614,7 +5614,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+             for e in self.basis():
+                 basis[self._prow[self._idx[e]]] = e
+             N = QuaternaryMatroid(groundset=deepcopy(self._E, memo), matrix=deepcopy(self._A, memo), basis=deepcopy(basis, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -5672,7 +5672,7 @@ cdef class QuaternaryMatroid(LinearMatroid):
+             A = self._A
+             # current basis ordered so matrix cols form identity matrix:
+             basis = self._current_rows_cols()[0]
+-        data = (A, gs, basis, getattr(self, '__custom_name'))
++        data = (A, gs, basis, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_quaternary_matroid, (version, data)
+ 
+ # Regular Matroids
+@@ -5838,13 +5838,13 @@ cdef class RegularMatroid(LinearMatroid):
+         """
+         return 0
+ 
+-    cdef bint __is_exchange_pair(self, long x, long y) except -1:
++    cdef bint _is_exchange_pair(self, long x, long y) except -1:
+         r"""
+         Check if ``self.basis() - x + y`` is again a basis. Internal method.
+         """
+         return (<PlusMinusOneMatrix>self._A).is_nonzero(self._prow[x], self._prow[y])
+ 
+-    cdef int __exchange(self, long x, long y) except -1:
++    cdef int _exchange(self, long x, long y) except -1:
+         """
+         Put element indexed by ``x`` into basis, taking out element ``y``. Assumptions are that this is a valid basis exchange.
+ 
+@@ -5867,9 +5867,9 @@ cdef class RegularMatroid(LinearMatroid):
+         (<PlusMinusOneMatrix>self._A).set(px, py, pivi)   # Not a Sage matrix operation
+         self._prow[y] = px
+         self._prow[x] = py
+-        BasisExchangeMatroid.__exchange(self, x, y)
++        BasisExchangeMatroid._exchange(self, x, y)
+ 
+-    cdef  __exchange_value(self, long x, long y):
++    cdef  _exchange_value_internal(self, long x, long y):
+         r"""
+         Return the (x, y) entry of the current representation.
+ 
+@@ -6524,7 +6524,7 @@ cdef class RegularMatroid(LinearMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = RegularMatroid(groundset=rows + cols, reduced_matrix=self._A)
+-        N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo):
+@@ -6544,7 +6544,7 @@ cdef class RegularMatroid(LinearMatroid):
+         else:
+             rows, cols = self._current_rows_cols()
+             N = RegularMatroid(groundset=deepcopy(rows + cols, memo), reduced_matrix=deepcopy(self._A, memo))
+-        N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -6593,5 +6593,5 @@ cdef class RegularMatroid(LinearMatroid):
+             rows, cols = self._current_rows_cols()
+             gs = rows + cols
+             reduced = True
+-        data = (A, gs, reduced, getattr(self, '__custom_name'))
++        data = (A, gs, reduced, self.get_custom_name())
+         return sage.matroids.unpickling.unpickle_regular_matroid, (version, data)
+diff --git a/src/sage/matroids/matroid.pxd b/src/sage/matroids/matroid.pxd
+index fe6c07e3b71..e9ddfec96ae 100644
+--- a/src/sage/matroids/matroid.pxd
++++ b/src/sage/matroids/matroid.pxd
+@@ -1,8 +1,7 @@
+ from sage.structure.sage_object cimport SageObject
+ 
+ cdef class Matroid(SageObject):
+-    cdef public __custom_name
+-    cdef public _custom_name
++    cdef public _SageObject__custom_name
+     cdef public _cached_info
+     cdef int _stored_full_rank
+     cdef int _stored_size
+@@ -37,7 +36,7 @@ cdef class Matroid(SageObject):
+     cpdef _line_length(self, F)
+     cpdef _extension(self, element, hyperplanes)
+ 
+-    cdef inline __subset(self, X):
++    cdef inline _subset_internal(self, X):
+         """
+         Convert ``X`` to a ``frozenset`` and check that it is a subset
+         of the groundset.
+diff --git a/src/sage/matroids/matroid.pyx b/src/sage/matroids/matroid.pyx
+index dcee87ea49c..8ac5ec3f678 100644
+--- a/src/sage/matroids/matroid.pyx
++++ b/src/sage/matroids/matroid.pyx
+@@ -1307,7 +1307,7 @@ cdef class Matroid(SageObject):
+             TypeError: 'sage.rings.integer.Integer' object is not iterable
+         """
+         # Call corresponding Cython method
+-        return self.__subset(X)
++        return self._subset_internal(X)
+ 
+     def _subset_all(self, X):
+         """
+@@ -1374,7 +1374,7 @@ cdef class Matroid(SageObject):
+         """
+         if X is None:
+             return self.full_rank()
+-        return self._rank(self.__subset(X))
++        return self._rank(self._subset_internal(X))
+ 
+     cpdef full_rank(self):
+         r"""
+@@ -1453,7 +1453,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._max_independent(self.__subset(X))
++        return self._max_independent(self._subset_internal(X))
+ 
+     cpdef circuit(self, X=None):
+         """
+@@ -1558,7 +1558,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._closure(self.__subset(X))
++        return self._closure(self._subset_internal(X))
+ 
+     cpdef k_closure(self, X, k):
+         r"""
+@@ -1597,7 +1597,7 @@ cdef class Matroid(SageObject):
+             sage: sorted(M.k_closure({0,1}, 4))
+             [0, 1, 4]
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         cdef int cur
+         cdef frozenset S, cl
+         cur = 0
+@@ -1644,7 +1644,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         Y = self.__subset_all(Y)
+         return self._augment(X, Y.difference(X))
+ 
+@@ -1781,7 +1781,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._max_coindependent(self.__subset(X))
++        return self._max_coindependent(self._subset_internal(X))
+ 
+     cpdef coclosure(self, X):
+         """
+@@ -1813,7 +1813,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: ['x'] is not a subset of the groundset
+         """
+-        return self._coclosure(self.__subset(X))
++        return self._coclosure(self._subset_internal(X))
+ 
+     cpdef cocircuit(self, X=None):
+         """
+@@ -1947,7 +1947,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_independent(self.__subset(X))
++        return self._is_independent(self._subset_internal(X))
+ 
+     cpdef is_dependent(self, X):
+         r"""
+@@ -1973,7 +1973,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return not self._is_independent(self.__subset(X))
++        return not self._is_independent(self._subset_internal(X))
+ 
+     cpdef is_basis(self, X):
+         r"""
+@@ -1999,7 +1999,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         if len(X) != self.full_rank():
+             return False
+         return self._is_basis(X)
+@@ -2035,7 +2035,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_closed(self.__subset(X))
++        return self._is_closed(self._subset_internal(X))
+ 
+     cpdef is_subset_k_closed(self, X, int k):
+         r"""
+@@ -2118,7 +2118,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_circuit(self.__subset(X))
++        return self._is_circuit(self._subset_internal(X))
+ 
+     cpdef coloops(self):
+         r"""
+@@ -2178,7 +2178,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_coindependent(self.__subset(X))
++        return self._is_coindependent(self._subset_internal(X))
+ 
+     cpdef is_codependent(self, X):
+         r"""
+@@ -2211,7 +2211,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return not self._is_coindependent(self.__subset(X))
++        return not self._is_coindependent(self._subset_internal(X))
+ 
+     cpdef is_cobasis(self, X):
+         r"""
+@@ -2245,7 +2245,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        X = self.__subset(X)
++        X = self._subset_internal(X)
+         if len(X) != self.full_corank():
+             return False
+         return self._is_cobasis(X)
+@@ -2282,7 +2282,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_cocircuit(self.__subset(X))
++        return self._is_cocircuit(self._subset_internal(X))
+ 
+     cpdef is_coclosed(self, X):
+         r"""
+@@ -2315,7 +2315,7 @@ cdef class Matroid(SageObject):
+             ...
+             ValueError: 'abcx' is not a subset of the groundset
+         """
+-        return self._is_coclosed(self.__subset(X))
++        return self._is_coclosed(self._subset_internal(X))
+ 
+     # verification
+ 
+@@ -4868,10 +4868,10 @@ cdef class Matroid(SageObject):
+             sage: M.connectivity('ab', 'cd')
+             2
+         """
+-        S = self.__subset(S)
++        S = self._subset_internal(S)
+         if T is None:
+             return self._rank(S) + self._rank(self.groundset()-S) - self.full_rank()
+-        T = self.__subset(T)
++        T = self._subset_internal(T)
+         if S.intersection(T):
+             raise ValueError("S and T are not disjoint")
+         return len(self._link(S, T)[0]) - self.full_rank() + self._rank(S) + self._rank(T)
+@@ -4956,8 +4956,8 @@ cdef class Matroid(SageObject):
+             sage: N.connectivity(S)
+             2
+         """
+-        S = self.__subset(S)
+-        T = self.__subset(T)
++        S = self._subset_internal(S)
++        T = self._subset_internal(T)
+         if not S.isdisjoint(T):
+             raise ValueError("S and T are not disjoint")
+         return self._link(S, T)
+diff --git a/src/sage/matroids/minor_matroid.py b/src/sage/matroids/minor_matroid.py
+index c0e756917f5..98856348ac1 100644
+--- a/src/sage/matroids/minor_matroid.py
++++ b/src/sage/matroids/minor_matroid.py
+@@ -486,8 +486,7 @@ def __copy__(self):
+             True
+         """
+         N = MinorMatroid(self._matroid, self._contractions, self._deletions)
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -512,8 +511,7 @@ def __deepcopy__(self, memo={}):
+         from copy import deepcopy
+         # Since matroids are immutable, N cannot reference itself in correct code, so no need to worry about the recursion.
+         N = MinorMatroid(deepcopy(self._matroid, memo), deepcopy(self._contractions, memo), deepcopy(self._deletions, memo))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+@@ -534,6 +532,6 @@ def __reduce__(self):
+              4: {{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}}}
+         """
+         import sage.matroids.unpickling
+-        data = (self._matroid, self._contractions, self._deletions, getattr(self, '__custom_name'))
++        data = (self._matroid, self._contractions, self._deletions, self.get_custom_name())
+         version = 0
+         return sage.matroids.unpickling.unpickle_minor_matroid, (version, data)
+diff --git a/src/sage/matroids/rank_matroid.py b/src/sage/matroids/rank_matroid.py
+index 4633ff0a792..6c4e9470ada 100644
+--- a/src/sage/matroids/rank_matroid.py
++++ b/src/sage/matroids/rank_matroid.py
+@@ -267,9 +267,7 @@ def __copy__(self):
+         N = RankMatroid(groundset=[], rank_function=None)
+         N._groundset = self._groundset
+         N._rank_function = self._rank_function
+-        if getattr(self, '__custom_name') is not None:
+-            # because of name wrangling, this is not caught by the default copy
+-            N.rename(getattr(self, '__custom_name'))
++        N.rename(self.get_custom_name())
+         return N
+ 
+     def __deepcopy__(self, memo={}):
+@@ -293,8 +291,7 @@ def __deepcopy__(self, memo={}):
+         from copy import deepcopy
+         # Since matroids are immutable, N cannot reference itself in correct code, so no need to worry about the recursion.
+         N = RankMatroid(groundset=deepcopy(self._groundset), rank_function=deepcopy(self._rank_function))
+-        if getattr(self, '__custom_name') is not None:  # because of name wrangling, this is not caught by the default deepcopy
+-            N.rename(deepcopy(getattr(self, '__custom_name'), memo))
++        N.rename(deepcopy(self.get_custom_name(), memo))
+         return N
+ 
+     def __reduce__(self):
+diff --git a/src/sage/misc/cachefunc.pxd b/src/sage/misc/cachefunc.pxd
+index d3cc677dece..8e5d9dfa42a 100644
+--- a/src/sage/misc/cachefunc.pxd
++++ b/src/sage/misc/cachefunc.pxd
+@@ -5,7 +5,7 @@ cpdef cache_key(o)
+ 
+ cdef class CachedFunction():
+     cdef public str __name__
+-    cdef public str __module__
++    cdef public str __cached_module__
+     cdef ArgumentFixer _argument_fixer
+     cdef public f
+     cdef public cache  # not always of type <dict>
+@@ -20,7 +20,7 @@ cdef class CachedFunction():
+ cdef class CachedMethod():
+     cdef str _cache_name
+     cdef public str __name__
+-    cdef public str __module__
++    cdef public str __cached_module__
+     cdef CachedFunction _cachedfunc
+     cdef Py_ssize_t nargs
+     cpdef _get_instance_cache(self, inst)
+diff --git a/src/sage/misc/cachefunc.pyx b/src/sage/misc/cachefunc.pyx
+index a307c33e32b..8aa30a85272 100644
+--- a/src/sage/misc/cachefunc.pyx
++++ b/src/sage/misc/cachefunc.pyx
+@@ -60,7 +60,7 @@ be used::
+ 
+ We can proceed similarly for cached methods of Cython classes,
+ provided that they allow attribute assignment or have a public
+-attribute ``__cached_methods`` of type ``<dict>``. Since
++attribute ``_cached_methods`` of type ``<dict>``. Since
+ :trac:`11115`, this is the case for all classes inheriting from
+ :class:`~sage.structure.parent.Parent`. See below for a more explicit
+ example. By :trac:`12951`, cached methods of extension classes can
+@@ -301,14 +301,14 @@ ought to be chosen. A typical example is
+ 
+ By :trac:`12951`, the cached_method decorator is also supported on non-c(p)def
+ methods of extension classes, as long as they either support attribute assignment
+-or have a public attribute of type ``<dict>`` called ``__cached_methods``. The
++or have a public attribute of type ``<dict>`` called ``_cached_methods``. The
+ latter is easy::
+ 
+     sage: # needs sage.misc.cython
+     sage: cython_code = [
+     ....: "from sage.misc.cachefunc import cached_method",
+     ....: "cdef class MyClass:",
+-    ....: "    cdef public dict __cached_methods",
++    ....: "    cdef public dict _cached_methods",
+     ....: "    @cached_method",
+     ....: "    def f(self, a,b):",
+     ....: "        return a*b"]
+@@ -774,13 +774,17 @@ cdef class CachedFunction():
+         else:
+             self.__name__ = f.__name__
+         try:
+-            self.__module__ = f.__module__
++            self.__cached_module__ = f.__module__
+         except AttributeError:
+-            self.__module__ = f.__objclass__.__module__
++            self.__cached_module__ = f.__objclass__.__module__
+         if argument_fixer is not None: # it is None unless the argument fixer
+                                        # was known previously. See #15038.
+             self._argument_fixer = argument_fixer
+ 
++    @property
++    def __module__(self):
++        return self.__cached_module__
++
+     cdef get_key_args_kwds(self, tuple args, dict kwds):
+         """
+         Return the key in the cache to be used when ``args`` and
+@@ -841,7 +845,7 @@ cdef class CachedFunction():
+             sage: loads(dumps(hilbert_class_polynomial)) is hilbert_class_polynomial  #indirect doctest                 # needs sage.schemes
+             True
+         """
+-        return _cached_function_unpickle, (self.__module__, self.__name__, self.cache)
++        return _cached_function_unpickle, (self.__cached_module__, self.__name__, self.cache)
+ 
+     #########
+     ## Introspection
+@@ -2019,7 +2023,7 @@ cdef class CachedMethodCaller(CachedFunction):
+         This getter attempts to assign a bound method as an
+         attribute to the given instance. If this is not
+         possible (for example, for some extension classes),
+-        it is attempted to find an attribute ``__cached_methods``,
++        it is attempted to find an attribute ``_cached_methods``,
+         and store/retrieve the bound method there. In that
+         way, cached methods can be implemented for extension
+         classes deriving from :class:`~sage.structure.parent.Parent`
+@@ -2085,7 +2089,7 @@ cdef class CachedMethodCaller(CachedFunction):
+         """
+         # This is for Parents or Elements that do not allow attribute assignment
+         try:
+-            return (<dict>inst.__cached_methods)[self._cachedmethod._cachedfunc.__name__]
++            return (<dict>inst._cached_methods)[self._cachedmethod._cachedfunc.__name__]
+         except (AttributeError, TypeError, KeyError):
+             pass
+ 
+@@ -2100,10 +2104,10 @@ cdef class CachedMethodCaller(CachedFunction):
+         except AttributeError:
+             pass
+         try:
+-            if inst.__cached_methods is None:
+-                inst.__cached_methods = {self._cachedmethod._cachedfunc.__name__ : Caller}
++            if inst._cached_methods is None:
++                inst._cached_methods = {self._cachedmethod._cachedfunc.__name__ : Caller}
+             else:
+-                (<dict>inst.__cached_methods)[self._cachedmethod._cachedfunc.__name__] = Caller
++                (<dict>inst._cached_methods)[self._cachedmethod._cachedfunc.__name__] = Caller
+         except AttributeError:
+             pass
+         return Caller
+@@ -2421,7 +2425,7 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
+         This getter attempts to assign a bound method as an
+         attribute to the given instance. If this is not
+         possible (for example, for some extension classes),
+-        it is attempted to find an attribute ``__cached_methods``,
++        it is attempted to find an attribute ``_cached_methods``,
+         and store/retrieve the bound method there. In that
+         way, cached methods can be implemented for extension
+         classes deriving from :class:`~sage.structure.parent.Parent`
+@@ -2472,7 +2476,7 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
+         """
+         # This is for Parents or Elements that do not allow attribute assignment
+         try:
+-            return (<dict>inst.__cached_methods)[self.__name__]
++            return (<dict>inst._cached_methods)[self.__name__]
+         except (AttributeError, TypeError, KeyError):
+             pass
+         Caller = CachedMethodCallerNoArgs(inst, self.f, name=self.__name__, do_pickle=self.do_pickle)
+@@ -2482,10 +2486,10 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
+         except AttributeError:
+             pass
+         try:
+-            if inst.__cached_methods is None:
+-                inst.__cached_methods = {self.__name__ : Caller}
++            if inst._cached_methods is None:
++                inst._cached_methods = {self.__name__ : Caller}
+             else:
+-                (<dict>inst.__cached_methods)[self.__name__] = Caller
++                (<dict>inst._cached_methods)[self.__name__] = Caller
+         except AttributeError:
+             pass
+         return Caller
+@@ -2698,7 +2702,11 @@ cdef class CachedMethod():
+         self._cache_name = '_cache__' + (name or f.__name__)
+         self._cachedfunc = CachedFunction(f, classmethod=True, name=name, key=key, do_pickle=do_pickle)
+         self.__name__ = self._cachedfunc.__name__
+-        self.__module__ = self._cachedfunc.__module__
++        self.__cached_module__ = self._cachedfunc.__module__
++
++    @property
++    def __module__(self):
++        return self.__cached_module__
+ 
+     def __call__(self, inst, *args, **kwds):
+         """
+@@ -2828,7 +2836,7 @@ cdef class CachedMethod():
+         except AttributeError:
+             name = self.__name__
+         try:
+-            return (<dict>inst.__cached_methods)[name]
++            return (<dict>inst._cached_methods)[name]
+         except (AttributeError, TypeError, KeyError):
+             pass
+         # Apparently we need to construct the caller.
+@@ -2840,8 +2848,6 @@ cdef class CachedMethod():
+                 try:
+                     if METH_NOARGS&PyCFunction_GetFlags(f.__get__(inst,cls)):
+                         self.nargs = 1
+-                    else:
+-                        self.nargs = 2
+                 except Exception:
+                     pass
+             if self.nargs == 0:
+@@ -2864,10 +2870,10 @@ cdef class CachedMethod():
+         except AttributeError:
+             pass
+         try:
+-            if inst.__cached_methods is None:
+-                inst.__cached_methods = {name : Caller}
++            if inst._cached_methods is None:
++                inst._cached_methods = {name : Caller}
+             else:
+-                (<dict>inst.__cached_methods)[name] = Caller
++                (<dict>inst._cached_methods)[name] = Caller
+         except AttributeError:
+             pass
+         return Caller
+@@ -2965,12 +2971,12 @@ cdef class CachedSpecialMethod(CachedMethod):
+                 D = inst.__dict__
+             except (TypeError, AttributeError):
+                 try:
+-                    D = inst.__cached_methods
++                    D = inst._cached_methods
+                 except (TypeError, AttributeError):
+-                    raise TypeError("For a cached special method, either attribute assignment or a public '__cached_methods' attribute of type <dict> is needed")
++                    raise TypeError("For a cached special method, either attribute assignment or a public '_cached_methods' attribute of type <dict> is needed")
+             if D is None:
+-                # This can only happen in the case of __cached_methods
+-                D = inst.__cached_methods = {}
++                # This can only happen in the case of _cached_methods
++                D = inst._cached_methods = {}
+             else:
+                 try:
+                     return D[name]
+@@ -3298,13 +3304,13 @@ cdef class CachedInParentMethod(CachedMethod):
+             return P.__dict__.setdefault(self._cache_name, default)
+         except AttributeError:
+             pass
+-        if not hasattr(P,'__cached_methods'):
++        if not hasattr(P,'_cached_methods'):
+             raise TypeError("The parent of this element does not allow attribute assignment\n" +
+                             "    and does not descend from the Parent base class.\n" +
+                             "    Cannot use CachedInParentMethod.")
+-        if P.__cached_methods is None:
+-            P.__cached_methods = {}
+-        return (<dict>P.__cached_methods).setdefault(self._cache_name, default)
++        if P._cached_methods is None:
++            P._cached_methods = {}
++        return (<dict>P._cached_methods).setdefault(self._cache_name, default)
+ 
+     def __get__(self, inst, cls):
+         """
+diff --git a/src/sage/misc/cython.py b/src/sage/misc/cython.py
+index f4083f3909b..5f83f585c3a 100644
+--- a/src/sage/misc/cython.py
++++ b/src/sage/misc/cython.py
+@@ -646,9 +646,9 @@ def compile_and_load(code, **kwds):
+         ....:     cdef Polynomial_rational_flint res = f._new()
+         ....:     cdef unsigned long k
+         ....:     cdef Rational z = Rational(0)
+-        ....:     for k in range(fmpq_poly_length(f.__poly)):
+-        ....:         fmpq_poly_get_coeff_mpq(z.value, f.__poly, k)
+-        ....:         fmpq_poly_set_coeff_mpq(res.__poly, n*k, z.value)
++        ....:     for k in range(fmpq_poly_length(f._poly)):
++        ....:         fmpq_poly_get_coeff_mpq(z.value, f._poly, k)
++        ....:         fmpq_poly_set_coeff_mpq(res._poly, n*k, z.value)
+         ....:     return res
+         ....: '''
+         sage: module = compile_and_load(code)  # long time
+diff --git a/src/sage/misc/fpickle.pyx b/src/sage/misc/fpickle.pyx
+index 9f80a8f31aa..37c26e431ba 100644
+--- a/src/sage/misc/fpickle.pyx
++++ b/src/sage/misc/fpickle.pyx
+@@ -124,10 +124,12 @@ def call_pickled_function(fpargs):
+ def pickleMethod(method):
+     'support function for copyreg to pickle method refs'
+ 
+-    # Note: On Python 3 there is no .im_class but we can get the instance's
+-    # class through .__self__.__class__
+-    cls = getattr(method, 'im_class', method.__self__.__class__)
+-    return (unpickleMethod, (method.__func__.__name__, method.__self__, cls))
++    if isinstance(method.__self__, type):
++        # This is a class method, so get it from the type directly
++        return (getattr, (method.__self__, method.__func__.__name__))
++    else:
++        cls = method.__self__.__class__
++        return (unpickleMethod, (method.__func__.__name__, method.__self__, cls))
+ 
+ 
+ def unpickleMethod(im_name,
+@@ -139,10 +141,7 @@ def unpickleMethod(im_name,
+         if __self__ is None:
+             return unbound
+ 
+-        # Note: On Python 2 "unbound methods" are just functions, so they don't
+-        # have a __func__
+-        bound = types.MethodType(getattr(unbound, '__func__', unbound),
+-                                 __self__)
++        bound = types.MethodType(unbound, __self__)
+         return bound
+     except AttributeError:
+         assert __self__ is not None, "No recourse: no instance to guess from."
+@@ -150,11 +149,8 @@ def unpickleMethod(im_name,
+         # changed around since we pickled this method, we may still be
+         # able to get it by looking on the instance's current class.
+         unbound = getattr(__self__.__class__, im_name)
+-        if __self__ is None:
+-            return unbound
+ 
+-        bound = types.MethodType(getattr(unbound, '__func__', unbound),
+-                                 __self__)
++        bound = types.MethodType(unbound, __self__)
+         return bound
+ 
+ 
+diff --git a/src/sage/misc/inherit_comparison.pyx b/src/sage/misc/inherit_comparison.pyx
+index f046f5fb8ce..aa97f664496 100644
+--- a/src/sage/misc/inherit_comparison.pyx
++++ b/src/sage/misc/inherit_comparison.pyx
+@@ -54,6 +54,8 @@ cdef class InheritComparisonMetaclass(type):
+         sage: # needs sage.misc.cython
+         sage: cython(
+         ....: '''
++        ....: cimport cython
++        ....:
+         ....: from sage.misc.inherit_comparison cimport InheritComparisonMetaclass
+         ....:
+         ....: cdef class Base():
+@@ -66,6 +68,7 @@ cdef class InheritComparisonMetaclass(type):
+         ....:         return 1
+         ....:
+         ....: cdef class DerivedWithRichcmp(Base):
++        ....:     @cython.always_allow_keywords(False)
+         ....:     def __getmetaclass__(_):
+         ....:         from sage.misc.inherit_comparison import InheritComparisonMetaclass
+         ....:         return InheritComparisonMetaclass
+diff --git a/src/sage/misc/lazy_attribute.pyx b/src/sage/misc/lazy_attribute.pyx
+index 82a0f90b775..bdbec3b3ba1 100644
+--- a/src/sage/misc/lazy_attribute.pyx
++++ b/src/sage/misc/lazy_attribute.pyx
+@@ -111,12 +111,12 @@ cdef class _lazy_attribute():
+         if a is None: # when doing cls.x for cls a class and x a lazy attribute
+             return self
+         try:
+-            # __cached_methods is supposed to be a public Cython attribute.
++            # _cached_methods is supposed to be a public Cython attribute.
+             # Apparently, these are *not* subject to name mangling.
+-            CM = getattr(a, '__cached_methods')
++            CM = getattr(a, '_cached_methods')
+             if CM is None:
+                 CM = {}
+-                setattr(a, '__cached_methods', CM)
++                setattr(a, '_cached_methods', CM)
+         except AttributeError as msg:
+             CM = None
+         if CM is not None:
+diff --git a/src/sage/misc/lazy_list.pyx b/src/sage/misc/lazy_list.pyx
+index c1fa0250a95..ba62c446b69 100644
+--- a/src/sage/misc/lazy_list.pyx
++++ b/src/sage/misc/lazy_list.pyx
+@@ -1059,7 +1059,11 @@ cdef class lazy_list_from_function(lazy_list_generic):
+             step         1
+         """
+         while len(self.cache) <= i:
+-            self.cache.append(self.callable(len(self.cache)))
++            try:
++                value = self.callable(len(self.cache))
++            except StopIteration:
++                return 1
++            self.cache.append(value)
+ 
+     def __reduce__(self):
+         r"""
+diff --git a/src/sage/misc/sageinspect.py b/src/sage/misc/sageinspect.py
+index 3dd0cc0a45b..ce5e9987027 100644
+--- a/src/sage/misc/sageinspect.py
++++ b/src/sage/misc/sageinspect.py
+@@ -224,7 +224,11 @@ def isclassinstance(obj):
+     return (not inspect.isclass(obj) and
+             hasattr(obj, '__class__') and
+             hasattr(obj.__class__, '__module__') and
+-            obj.__class__.__module__ not in builtin_mods)
++            obj.__class__.__module__ not in builtin_mods and
++            # Starting with Cython 3, Cython's builtin types have __module__ set
++            # to the shared module names like _cython_3_0_0.
++            not (isinstance(obj.__class__.__module__, str) and
++                 obj.__class__.__module__.startswith('_cython_')))
+ 
+ 
+ # Parse strings of form "File: sage/rings/rational.pyx (starting at line 1080)"
+diff --git a/src/sage/misc/session.pyx b/src/sage/misc/session.pyx
+index de649f80425..31454dac993 100644
+--- a/src/sage/misc/session.pyx
++++ b/src/sage/misc/session.pyx
+@@ -80,6 +80,8 @@ from sage.misc.persist import load, save, loads, dumps
+ 
+ state_at_init = None
+ 
++CythonFunctionType = type(lambda: None)
++
+ def init(state=None):
+     """
+     Initialize some dictionaries needed by the :func:`show_identifiers`,
+@@ -311,7 +313,7 @@ def save_session(name='sage_session', verbose=False):
+     for k in show_identifiers(hidden = True):
+         try:
+             x = state[k]
+-            if isinstance(x, (types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType, type)):
++            if isinstance(x, (types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType, CythonFunctionType, type)):
+                 raise TypeError('{} is a function, method, class or type'.format(k))
+ 
+             # We attempt to pickle *and* unpickle every variable to
+diff --git a/src/sage/modular/modsym/p1list.pxd b/src/sage/modular/modsym/p1list.pxd
+index cc24a33139b..b66f28b8ad6 100644
+--- a/src/sage/modular/modsym/p1list.pxd
++++ b/src/sage/modular/modsym/p1list.pxd
+@@ -21,7 +21,7 @@ cdef class P1List:
+     # Here we use a pointer to a function, so the if logic
+     # for normalizing an element does not need to be used
+     # every time the user calls the normalize function.
+-    cdef int (*__normalize)(int N, int u, int v,
++    cdef int (*_normalize)(int N, int u, int v,
+                             int* uu, int* vv, int* ss,
+                             int compute_s) except -1
+     cpdef index(self, int u, int v)
+diff --git a/src/sage/modular/modsym/p1list.pyx b/src/sage/modular/modsym/p1list.pyx
+index 111d408cee4..30a8f7471dd 100644
+--- a/src/sage/modular/modsym/p1list.pyx
++++ b/src/sage/modular/modsym/p1list.pyx
+@@ -723,10 +723,10 @@ cdef class P1List():
+         self.__N = N
+         if N <= 46340:
+             self.__list = p1list_int(N)
+-            self.__normalize = c_p1_normalize_int
++            self._normalize = c_p1_normalize_int
+         elif N <= 2147483647:
+             self.__list = p1list_llong(N)
+-            self.__normalize = c_p1_normalize_llong
++            self._normalize = c_p1_normalize_llong
+         else:
+             raise OverflowError("p1list not defined for such large N.")
+         self.__list.sort()
+@@ -921,7 +921,7 @@ cdef class P1List():
+         """
+         cdef int u, v, uu, vv, ss
+         u,v = self.__list[i]
+-        self.__normalize(self.__N, -u, v, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, -u, v, &uu, &vv, &ss, 0)
+         _, j = search(self.__list, (uu,vv))
+         return j
+ 
+@@ -954,7 +954,7 @@ cdef class P1List():
+         """
+         cdef int u, v, uu, vv, ss
+         u,v = self.__list[i]
+-        self.__normalize(self.__N, -v, u, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, -v, u, &uu, &vv, &ss, 0)
+         _, j = search(self.__list, (uu,vv))
+         return j
+ 
+@@ -987,7 +987,7 @@ cdef class P1List():
+         """
+         cdef int u, v, uu, vv, ss
+         u,v = self.__list[i]
+-        self.__normalize(self.__N, v, -u-v, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, v, -u-v, &uu, &vv, &ss, 0)
+         _, j = search(self.__list, (uu,vv))
+         return j
+ 
+@@ -1153,7 +1153,7 @@ cdef class P1List():
+             True
+         """
+         cdef int uu, vv, ss
+-        self.__normalize(self.__N, u, v, &uu, &vv, &ss, 0)
++        self._normalize(self.__N, u, v, &uu, &vv, &ss, 0)
+         return (uu,vv)
+ 
+     def normalize_with_scalar(self, int u, int v):
+@@ -1186,7 +1186,7 @@ cdef class P1List():
+             True
+         """
+         cdef int uu, vv, ss
+-        self.__normalize(self.__N, u, v, &uu, &vv, &ss, 1)
++        self._normalize(self.__N, u, v, &uu, &vv, &ss, 1)
+         return (uu, vv, ss)
+ 
+     def N(self):
+diff --git a/src/sage/numerical/gauss_legendre.pyx b/src/sage/numerical/gauss_legendre.pyx
+index 5325797c7aa..96708c5b1ac 100644
+--- a/src/sage/numerical/gauss_legendre.pyx
++++ b/src/sage/numerical/gauss_legendre.pyx
+@@ -117,8 +117,8 @@ def nodes_uncached(degree, prec):
+         raise ValueError("degree=%s not supported (degree must be 3 or even)" % degree)
+     R = RealField(int(prec*3/2))
+     Rout = RealField(prec)
+-    mpfr_init2(u,R.__prec)
+-    mpfr_init2(v,R.__prec)
++    mpfr_init2(u,R._prec)
++    mpfr_init2(v,R._prec)
+     ZERO = R.zero()
+     ONE = R.one()
+     HALF = ONE/2
+diff --git a/src/sage/numerical/linear_functions.pyx b/src/sage/numerical/linear_functions.pyx
+index 5549ff436f5..f3fc6fe419c 100644
+--- a/src/sage/numerical/linear_functions.pyx
++++ b/src/sage/numerical/linear_functions.pyx
+@@ -1579,7 +1579,10 @@ cdef class LinearConstraint(LinearFunctionOrConstraint):
+         while True:
+             yield (lhs, rhs)
+             lhs = rhs
+-            rhs = next(term_iter)
++            try:
++                rhs = next(term_iter)
++            except StopIteration:
++                return
+ 
+     def inequalities(self):
+         """
+@@ -1612,7 +1615,10 @@ cdef class LinearConstraint(LinearFunctionOrConstraint):
+         while True:
+             yield (lhs, rhs)
+             lhs = rhs
+-            rhs = next(term_iter)
++            try:
++                rhs = next(term_iter)
++            except StopIteration:
++                return
+ 
+     def _repr_(self):
+         r"""
+diff --git a/src/sage/quivers/representation.py b/src/sage/quivers/representation.py
+index 9c11eb8ad0e..db82cbd7c86 100644
+--- a/src/sage/quivers/representation.py
++++ b/src/sage/quivers/representation.py
+@@ -1297,10 +1297,7 @@ def copy(self):
+             sage: v.get_element(1)
+             (1, 0)
+         """
+-        if hasattr(self, '__custom_name'):
+-            name = self.__custom_name
+-        else:
+-            name = None
++        name = self.get_custom_name()
+         return self.parent()(self._elems.copy(), name)
+ 
+ ####################################################################
+diff --git a/src/sage/rings/complex_arb.pyx b/src/sage/rings/complex_arb.pyx
+index ef432c1e945..95e615f3ee6 100644
+--- a/src/sage/rings/complex_arb.pyx
++++ b/src/sage/rings/complex_arb.pyx
+@@ -874,7 +874,7 @@ class ComplexBallField(UniqueRepresentation, sage.rings.abc.ComplexBallField):
+         cdef RealBall rb
+         cdef ComplexBall cb
+         acb_poly_init(rounded_poly)
+-        cdef long deg = acb_poly_degree(poly.__poly)
++        cdef long deg = acb_poly_degree(poly._poly)
+         if deg < 0:
+             raise ArithmeticError("taking the roots of the zero polynomial")
+         cdef acb_ptr roots = _acb_vec_init(deg)
+@@ -883,7 +883,7 @@ class ComplexBallField(UniqueRepresentation, sage.rings.abc.ComplexBallField):
+             while ((isolated < deg or any(acb_rel_accuracy_bits(&roots[i]) < tgtprec
+                                         for i in range(deg)))
+                 and prec < maxprec):
+-                acb_poly_set_round(rounded_poly, poly.__poly, prec)
++                acb_poly_set_round(rounded_poly, poly._poly, prec)
+                 maxiter = min(max(deg, 32), prec)
+                 if (prec == initial_prec):
+                     isolated = acb_poly_find_roots(roots, rounded_poly, NULL, maxiter, prec)
+diff --git a/src/sage/rings/complex_mpc.pxd b/src/sage/rings/complex_mpc.pxd
+index 762c38afbdc..f7d8cb9492c 100644
+--- a/src/sage/rings/complex_mpc.pxd
++++ b/src/sage/rings/complex_mpc.pxd
+@@ -11,7 +11,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+     cpdef _mul_(self, other)
+ 
+ cdef class MPComplexField_class(sage.rings.ring.Field):
+-    cdef readonly int __prec
++    cdef readonly int _prec
+     cdef mpc_rnd_t __rnd
+     cdef object __rnd_str
+     cdef object __real_field
+diff --git a/src/sage/rings/complex_mpc.pyx b/src/sage/rings/complex_mpc.pyx
+index b3681ff724f..c847a9302b5 100644
+--- a/src/sage/rings/complex_mpc.pyx
++++ b/src/sage/rings/complex_mpc.pyx
+@@ -307,7 +307,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+         if prec < mpfr_prec_min() or prec > mpfr_prec_max():
+             raise ValueError("prec (=%s) must be >= %s and <= %s." % (
+                 prec, mpfr_prec_min(), mpfr_prec_max()))
+-        self.__prec = prec
++        self._prec = prec
+         if not isinstance(rnd, str):
+             raise TypeError("rnd must be a string")
+         try:
+@@ -331,7 +331,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+         cdef MPComplexNumber z
+         z = MPComplexNumber.__new__(MPComplexNumber)
+         z._parent = self
+-        mpc_init2(z.value, self.__prec)
++        mpc_init2(z.value, self._prec)
+         z.init = 1
+         return z
+ 
+@@ -344,7 +344,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: MPComplexField(200, 'RNDDU') # indirect doctest
+             Complex Field with 200 bits of precision and rounding RNDDU
+         """
+-        s = "Complex Field with %s bits of precision"%self.__prec
++        s = "Complex Field with %s bits of precision"%self._prec
+         if self.__rnd != MPC_RNDNN:
+             s = s + " and rounding %s"%(self.__rnd_str)
+         return s
+@@ -465,13 +465,13 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+         if RR.has_coerce_map_from(S):
+             return self._coerce_map_via([RR], S)
+ 
+-        if isinstance(S, MPComplexField_class) and S.prec() >= self.__prec:
++        if isinstance(S, MPComplexField_class) and S.prec() >= self._prec:
+             #FIXME: What map when rounding modes differ but prec is the same ?
+             #       How to provide commutativity of morphisms ?
+             #       Change _cmp_ when done
+             return MPCtoMPC(S, self)
+ 
+-        if isinstance(S, ComplexField_class) and S.prec() >= self.__prec:
++        if isinstance(S, ComplexField_class) and S.prec() >= self._prec:
+             return CCtoMPC(S, self)
+ 
+         late_import()
+@@ -490,7 +490,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: loads(dumps(C)) == C
+             True
+         """
+-        return __create__MPComplexField_version0, (self.__prec, self.__rnd_str)
++        return __create__MPComplexField_version0, (self._prec, self.__rnd_str)
+ 
+     def __richcmp__(left, right, int op):
+         """
+@@ -513,7 +513,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+ 
+         cdef MPComplexField_class s = <MPComplexField_class>left
+         cdef MPComplexField_class o = <MPComplexField_class>right
+-        return richcmp(s.__prec, o.__prec, op)
++        return richcmp(s._prec, o._prec, op)
+ 
+     def gen(self, n=0):
+         """
+@@ -604,7 +604,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: C = MPComplexField(10, 'RNDNZ'); C.name()
+             'MPComplexField10_RNDNZ'
+         """
+-        return "MPComplexField%s_%s"%(self.__prec, self.__rnd_str)
++        return "MPComplexField%s_%s"%(self._prec, self.__rnd_str)
+ 
+     def __hash__(self):
+         """
+@@ -629,7 +629,7 @@ cdef class MPComplexField_class(sage.rings.ring.Field):
+             sage: MPComplexField(22).prec()
+             22
+         """
+-        return self.__prec
++        return self._prec
+ 
+     def rounding_mode(self):
+         """
+@@ -707,7 +707,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+         cdef MPComplexNumber z
+         z = MPComplexNumber.__new__(MPComplexNumber)
+         z._parent = self._parent
+-        mpc_init2(z.value, (<MPComplexField_class>self._parent).__prec)
++        mpc_init2(z.value, (<MPComplexField_class>self._parent)._prec)
+         z.init = 1
+         return z
+ 
+@@ -760,7 +760,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+         if parent is None:
+             raise TypeError
+         self._parent = parent
+-        mpc_init2(self.value, parent.__prec)
++        mpc_init2(self.value, parent._prec)
+         self.init = 1
+         if x is None: return
+         self._set(x, y, base)
+@@ -1010,7 +1010,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+             sage: i.prec()
+             2000
+         """
+-        return <MPComplexField_class>(self._parent).__prec
++        return <MPComplexField_class>(self._parent)._prec
+ 
+     def real(self):
+         """
+@@ -1571,26 +1571,6 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+         mpc_norm(x.value, self.value, (<RealField_class>x._parent).rnd)
+         return x
+ 
+-    def __rtruediv__(self, left):
+-        r"""
+-        Returns the quotient of ``left`` with ``self``, that is: ``left/self``
+-        as a complex number.
+-
+-        INPUT:
+-
+-        - ``left`` -- a complex number
+-
+-        EXAMPLES::
+-
+-            sage: MPC = MPComplexField()
+-            sage: a = MPC(2, 2)
+-            sage: a.__rtruediv__(MPC(1))
+-            0.250000000000000 - 0.250000000000000*I
+-            sage: MPC(1)/a
+-            0.250000000000000 - 0.250000000000000*I
+-        """
+-        return MPComplexNumber(self._parent, left)/self
+-
+     def __pow__(self, right, modulus):
+         """
+         Compute ``self`` raised to the power of exponent, rounded in
+@@ -2347,7 +2327,7 @@ cdef class MPComplexNumber(sage.structure.element.FieldElement):
+ 
+         cdef mpc_rnd_t rnd = (<MPComplexField_class>(self._parent)).__rnd
+ 
+-        cdef int prec = self._parent.__prec
++        cdef int prec = self._parent._prec
+ 
+         if optimal or algorithm == "principal":
+             if not isinstance(right, MPComplexNumber) or (<MPComplexNumber>right)._parent is not self._parent:
+diff --git a/src/sage/rings/complex_mpfr.pyx b/src/sage/rings/complex_mpfr.pyx
+index 33d73d81b12..61f2cadc8e4 100644
+--- a/src/sage/rings/complex_mpfr.pyx
++++ b/src/sage/rings/complex_mpfr.pyx
+@@ -1658,28 +1658,6 @@ cdef class ComplexNumber(sage.structure.element.FieldElement):
+         mpfr_clear(right_nm)
+         return x
+ 
+-    def __rtruediv__(self, left):
+-        r"""
+-        Return the quotient of left with ``self``, that is:
+-
+-        ``left/self``
+-
+-        as a complex number.
+-
+-        INPUT:
+-
+-        - ``left`` -- a complex number to divide by ``self``
+-
+-        EXAMPLES::
+-
+-            sage: a = ComplexNumber(2,0)
+-            sage: a.__rtruediv__(CC(1))
+-            0.500000000000000
+-            sage: CC(1)/a
+-            0.500000000000000
+-        """
+-        return ComplexNumber(self._parent, left)/self
+-
+     def __pow__(self, right, modulus):
+         r"""
+         Raise ``self`` to the ``right`` exponent.
+diff --git a/src/sage/rings/finite_rings/integer_mod.pxd b/src/sage/rings/finite_rings/integer_mod.pxd
+index 1e3cb81c148..351ffa25e1b 100644
+--- a/src/sage/rings/finite_rings/integer_mod.pxd
++++ b/src/sage/rings/finite_rings/integer_mod.pxd
+@@ -20,7 +20,7 @@ cdef class NativeIntStruct:
+ 
+ 
+ cdef class IntegerMod_abstract(FiniteRingElement):
+-    cdef NativeIntStruct __modulus
++    cdef NativeIntStruct _modulus
+     cdef _new_c_from_long(self, long value)
+     cdef IntegerMod_abstract _new_c_fast(self, unsigned long value)
+     cdef void set_from_mpz(self, mpz_t value)
+diff --git a/src/sage/rings/finite_rings/integer_mod.pyx b/src/sage/rings/finite_rings/integer_mod.pyx
+index b9461bd362e..d64ba5af84f 100644
+--- a/src/sage/rings/finite_rings/integer_mod.pyx
++++ b/src/sage/rings/finite_rings/integer_mod.pyx
+@@ -361,7 +361,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             ZeroDivisionError: inverse of Mod(4, 30) does not exist
+         """
+         self._parent = parent
+-        self.__modulus = parent._pyx_order
++        self._modulus = parent._pyx_order
+ 
+         if value is None:
+             return
+@@ -373,7 +373,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         if isinstance(value, Integer):
+             z = <Integer>value
+         elif isinstance(value, rational.Rational):
+-            z = value % self.__modulus.sageInteger
++            z = value % self._modulus.sageInteger
+         elif integer_check_long_py(value, &longval, &err) and not err:
+             self.set_from_long(longval)
+             return
+@@ -388,7 +388,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+                     value = py_scalar_to_element(value)
+                 if isinstance(value, Element) and value.parent().is_exact():
+                     value = sage.rings.rational_field.QQ(value)
+-                    z = value % self.__modulus.sageInteger
++                    z = value % self._modulus.sageInteger
+                 else:
+                     raise
+         self.set_from_mpz(z.value)
+@@ -397,7 +397,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         cdef type t = type(self)
+         x = <IntegerMod_abstract>t.__new__(t)
+         x._parent = self._parent
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x.set_from_ulong_fast(value)
+         return x
+ 
+@@ -405,7 +405,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         cdef type t = type(self)
+         cdef IntegerMod_abstract x = <IntegerMod_abstract>t.__new__(t)
+         x._parent = self._parent
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x.set_from_long(value)
+         return x
+ 
+@@ -529,17 +529,17 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         """
+         if self.is_zero():
+             return True
+-        m = self.__modulus.sageInteger.exact_log(2) + 1
++        m = self._modulus.sageInteger.exact_log(2) + 1
+         return (self**m).is_zero()
+ 
+     #################################################################
+     # Interfaces
+     #################################################################
+     def _pari_init_(self):
+-        return 'Mod(%s,%s)'%(str(self), self.__modulus.sageInteger)
++        return 'Mod(%s,%s)'%(str(self), self._modulus.sageInteger)
+ 
+     def __pari__(self):
+-        return self.lift().__pari__().Mod(self.__modulus.sageInteger)
++        return self.lift().__pari__().Mod(self._modulus.sageInteger)
+ 
+     def _gap_init_(self):
+         r"""
+@@ -558,7 +558,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             sage: gap(Mod(4, 48))
+             ZmodnZObj( 4, 48 )
+         """
+-        return '%s*One(ZmodnZ(%s))' % (self, self.__modulus.sageInteger)
++        return '%s*One(ZmodnZ(%s))' % (self, self._modulus.sageInteger)
+ 
+     def _magma_init_(self, magma):
+         """
+@@ -869,7 +869,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             sage: Mod(3,17).modulus()
+             17
+         """
+-        return self.__modulus.sageInteger
++        return self._modulus.sageInteger
+ 
+     def charpoly(self, var='x'):
+         """
+@@ -1229,7 +1229,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+                 modulus = R.gen()**2 - R(self)
+                 if self._parent.is_field():
+                     from .finite_field_constructor import FiniteField
+-                    Q = FiniteField(self.__modulus.sageInteger**2, y, modulus)
++                    Q = FiniteField(self._modulus.sageInteger**2, y, modulus)
+                 else:
+                     R = self.parent()['x']
+                     Q = R.quotient(modulus, names=(y,))
+@@ -1250,7 +1250,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             if all and e > 1 and not self.is_unit():
+                 if self.is_zero():
+                     # All multiples of p^ciel(e/2) vanish
+-                    return [self._parent(x) for x in range(0, self.__modulus.sageInteger, p**((e+1)/2))]
++                    return [self._parent(x) for x in range(0, self._modulus.sageInteger, p**((e+1)/2))]
+                 else:
+                     z = self.lift()
+                     val = z.valuation(p)/2  # square => valuation is even
+@@ -1272,7 +1272,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+                     p_exp = p**exp
+                     w = [self._parent(a.lift() * p_val + b)
+                             for a in u.sqrt(all=True)
+-                            for b in range(0, self.__modulus.sageInteger, p_exp)]
++                            for b in range(0, self._modulus.sageInteger, p_exp)]
+                     if p == 2:
+                         w = list(set(w))
+                     w.sort()
+@@ -1624,7 +1624,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         despite the possibly probabilistic nature of the underlying
+         algorithm.
+         """
+-        if self.lift() > self.__modulus.sageInteger >> 1:
++        if self.lift() > self._modulus.sageInteger >> 1:
+             return -self
+         return self
+ 
+@@ -1705,27 +1705,27 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         cdef int_fast64_t new_modulus
+         if not isinstance(self, IntegerMod_gmp) and not isinstance(other, IntegerMod_gmp):
+ 
+-            if other.__modulus.int64 == 1: return self
+-            new_modulus = self.__modulus.int64 * other.__modulus.int64
++            if other._modulus.int64 == 1: return self
++            new_modulus = self._modulus.int64 * other._modulus.int64
+             if new_modulus < INTEGER_MOD_INT32_LIMIT:
+-                return self.__crt(other)
++                return self._crt(other)
+ 
+             elif new_modulus < INTEGER_MOD_INT64_LIMIT:
+                 if not isinstance(self, IntegerMod_int64):
+                     self = IntegerMod_int64(self._parent, self.lift())
+                 if not isinstance(other, IntegerMod_int64):
+                     other = IntegerMod_int64(other._parent, other.lift())
+-                return self.__crt(other)
++                return self._crt(other)
+ 
+         if not isinstance(self, IntegerMod_gmp):
+-            if self.__modulus.int64 == 1: return other
++            if self._modulus.int64 == 1: return other
+             self = IntegerMod_gmp(self._parent, self.lift())
+ 
+         if not isinstance(other, IntegerMod_gmp):
+-            if other.__modulus.int64 == 1: return self
++            if other._modulus.int64 == 1: return self
+             other = IntegerMod_gmp(other._parent, other.lift())
+ 
+-        return self.__crt(other)
++        return self._crt(other)
+ 
+     def additive_order(self):
+         r"""
+@@ -1742,7 +1742,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             sage: Integers(90308402384902)(2).additive_order()
+             45154201192451
+         """
+-        n = self.__modulus.sageInteger
++        n = self._modulus.sageInteger
+         return sage.rings.integer.Integer(n // self.lift().gcd(n))
+ 
+     def is_primitive_root(self):
+@@ -1856,7 +1856,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             return sage.rings.integer.Integer(self.__pari__().znorder())
+         except PariError:
+             raise ArithmeticError("multiplicative order of %s not defined since it is not a unit modulo %s"%(
+-                self, self.__modulus.sageInteger))
++                self, self._modulus.sageInteger))
+ 
+     def valuation(self, p):
+         """
+@@ -1905,7 +1905,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+             2
+ 
+         """
+-        p=self.__modulus.sageInteger.gcd(p)
++        p=self._modulus.sageInteger.gcd(p)
+         if p==1:
+             raise ValueError("Valuation with respect to a unit is not defined.")
+         r = 0
+@@ -1913,7 +1913,7 @@ cdef class IntegerMod_abstract(FiniteRingElement):
+         while not (self % power): # self % power == 0
+             r += 1
+             power *= p
+-            if not power.divides(self.__modulus.sageInteger):
++            if not power.divides(self._modulus.sageInteger):
+                 from sage.rings.infinity import infinity
+                 return infinity
+         return r
+@@ -1980,7 +1980,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+     cdef IntegerMod_gmp _new_c(self):
+         cdef IntegerMod_gmp x
+         x = IntegerMod_gmp.__new__(IntegerMod_gmp)
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x._parent = self._parent
+         return x
+ 
+@@ -1989,7 +1989,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+ 
+     cdef void set_from_mpz(self, mpz_t value):
+         cdef sage.rings.integer.Integer modulus
+-        modulus = self.__modulus.sageInteger
++        modulus = self._modulus.sageInteger
+         mpz_mod(self.value, value, modulus.value)
+ 
+     cdef void set_from_long(self, long value):
+@@ -2001,7 +2001,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             1
+         """
+         mpz_set_si(self.value, value)
+-        mpz_mod(self.value, self.value, self.__modulus.sageInteger.value)
++        mpz_mod(self.value, self.value, self._modulus.sageInteger.value)
+ 
+     cdef void set_from_ulong_fast(self, unsigned long value):
+         mpz_set_ui(self.value, value)
+@@ -2071,7 +2071,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             x = self._new_c()
+             if k > 0:
+                 mpz_mul_2exp(x.value, self.value, k)
+-                mpz_fdiv_r(x.value, x.value, self.__modulus.sageInteger.value)
++                mpz_fdiv_r(x.value, x.value, self._modulus.sageInteger.value)
+             else:
+                 mpz_fdiv_q_2exp(x.value, self.value, -k)
+             return x
+@@ -2132,12 +2132,12 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         """
+         return self.lift().gcd(self.modulus()) == 1
+ 
+-    def __crt(IntegerMod_gmp self, IntegerMod_gmp other):
++    def _crt(IntegerMod_gmp self, IntegerMod_gmp other):
+         cdef IntegerMod_gmp lift, x
+         cdef sage.rings.integer.Integer modulus, other_modulus
+ 
+-        modulus = self.__modulus.sageInteger
+-        other_modulus = other.__modulus.sageInteger
++        modulus = self._modulus.sageInteger
++        other_modulus = other._modulus.sageInteger
+         from .integer_mod_ring import IntegerModRing
+         lift = IntegerMod_gmp(IntegerModRing(modulus*other_modulus))
+         try:
+@@ -2188,8 +2188,8 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+         mpz_add(x.value, self.value, (<IntegerMod_gmp>right).value)
+-        if mpz_cmp(x.value, self.__modulus.sageInteger.value)  >= 0:
+-            mpz_sub(x.value, x.value, self.__modulus.sageInteger.value)
++        if mpz_cmp(x.value, self._modulus.sageInteger.value)  >= 0:
++            mpz_sub(x.value, x.value, self._modulus.sageInteger.value)
+         return x
+ 
+     cpdef _sub_(self, right):
+@@ -2204,7 +2204,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         x = self._new_c()
+         mpz_sub(x.value, self.value, (<IntegerMod_gmp>right).value)
+         if mpz_sgn(x.value) == -1:
+-            mpz_add(x.value, x.value, self.__modulus.sageInteger.value)
++            mpz_add(x.value, x.value, self._modulus.sageInteger.value)
+         return x
+ 
+     cpdef _neg_(self):
+@@ -2220,7 +2220,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             return self
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+-        mpz_sub(x.value, self.__modulus.sageInteger.value, self.value)
++        mpz_sub(x.value, self._modulus.sageInteger.value, self.value)
+         return x
+ 
+     cpdef _mul_(self, right):
+@@ -2234,7 +2234,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+         mpz_mul(x.value, self.value,  (<IntegerMod_gmp>right).value)
+-        mpz_fdiv_r(x.value, x.value, self.__modulus.sageInteger.value)
++        mpz_fdiv_r(x.value, x.value, self._modulus.sageInteger.value)
+         return x
+ 
+     cpdef _div_(self, right):
+@@ -2310,7 +2310,7 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         cdef IntegerMod_gmp x = self._new_c()
+         sig_on()
+         try:
+-            mpz_pow_helper(x.value, self.value, exp, self.__modulus.sageInteger.value)
++            mpz_pow_helper(x.value, self.value, exp, self._modulus.sageInteger.value)
+         finally:
+             sig_off()
+         return x
+@@ -2331,12 +2331,12 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+             ZeroDivisionError: inverse of Mod(2, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000) does not exist
+         """
+         if self.is_zero():
+-            raise ZeroDivisionError(f"inverse of Mod(0, {self.__modulus.sageInteger}) does not exist")
++            raise ZeroDivisionError(f"inverse of Mod(0, {self._modulus.sageInteger}) does not exist")
+ 
+         cdef IntegerMod_gmp x
+         x = self._new_c()
+-        if not mpz_invert(x.value, self.value, self.__modulus.sageInteger.value):
+-            raise ZeroDivisionError(f"inverse of Mod({self}, {self.__modulus.sageInteger}) does not exist")
++        if not mpz_invert(x.value, self.value, self._modulus.sageInteger.value):
++            raise ZeroDivisionError(f"inverse of Mod({self}, {self._modulus.sageInteger}) does not exist")
+         return x
+ 
+     def lift(IntegerMod_gmp self):
+@@ -2391,10 +2391,10 @@ cdef class IntegerMod_gmp(IntegerMod_abstract):
+         """
+         cdef IntegerMod_gmp ans = self._new_c()
+         sig_on()
+-        mpz_gcd(ans.value, self.value, self.__modulus.sageInteger.value)
++        mpz_gcd(ans.value, self.value, self._modulus.sageInteger.value)
+         mpz_gcd(ans.value, ans.value, other.value)
+         sig_off()
+-        if mpz_cmp(ans.value, self.__modulus.sageInteger.value) == 0:
++        if mpz_cmp(ans.value, self._modulus.sageInteger.value) == 0:
+             # self = other = 0
+             mpz_set_ui(ans.value, 0)
+         return ans
+@@ -2422,30 +2422,30 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+     """
+ 
+     cdef IntegerMod_int _new_c(self, int_fast32_t value):
+-        if self.__modulus.table is not None:
+-            return self.__modulus.table[value]
++        if self._modulus.table is not None:
++            return self._modulus.table[value]
+         cdef IntegerMod_int x = IntegerMod_int.__new__(IntegerMod_int)
+         x._parent = self._parent
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x.ivalue = value
+         return x
+ 
+     cdef void set_from_mpz(self, mpz_t value):
+-        self.ivalue = mpz_fdiv_ui(value, self.__modulus.int32)
++        self.ivalue = mpz_fdiv_ui(value, self._modulus.int32)
+ 
+     cdef void set_from_long(self, long value):
+-        self.ivalue = value % self.__modulus.int32
++        self.ivalue = value % self._modulus.int32
+         if self.ivalue < 0:
+-            self.ivalue += self.__modulus.int32
++            self.ivalue += self._modulus.int32
+ 
+     cdef void set_from_ulong_fast(self, unsigned long value):
+         self.ivalue = value
+ 
+     cdef void set_from_int(IntegerMod_int self, int_fast32_t ivalue):
+         if ivalue < 0:
+-            self.ivalue = self.__modulus.int32 + (ivalue % self.__modulus.int32)
+-        elif ivalue >= self.__modulus.int32:
+-            self.ivalue = ivalue % self.__modulus.int32
++            self.ivalue = self._modulus.int32 + (ivalue % self._modulus.int32)
++        elif ivalue >= self._modulus.int32:
++            self.ivalue = ivalue % self._modulus.int32
+         else:
+             self.ivalue = ivalue
+ 
+@@ -2490,7 +2490,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: Zmod(1).one().is_one()
+             True
+         """
+-        return self.ivalue == 1 or self.__modulus.int32 == 1
++        return self.ivalue == 1 or self._modulus.int32 == 1
+ 
+     def __bool__(IntegerMod_int self):
+         """
+@@ -2519,9 +2519,9 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: a.is_unit()
+             False
+         """
+-        return gcd_int(self.ivalue, self.__modulus.int32) == 1
++        return gcd_int(self.ivalue, self._modulus.int32) == 1
+ 
+-    def __crt(IntegerMod_int self, IntegerMod_int other):
++    def _crt(IntegerMod_int self, IntegerMod_int other):
+         """
+         Use the Chinese Remainder Theorem to find an element of the
+         integers modulo the product of the moduli that reduces to self and
+@@ -2543,11 +2543,11 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         cdef int_fast32_t x
+ 
+         from .integer_mod_ring import IntegerModRing
+-        lift = IntegerMod_int(IntegerModRing(self.__modulus.int32 * other.__modulus.int32))
++        lift = IntegerMod_int(IntegerModRing(self._modulus.int32 * other._modulus.int32))
+ 
+         try:
+-            x = (other.ivalue - self.ivalue % other.__modulus.int32) * mod_inverse_int(self.__modulus.int32, other.__modulus.int32)
+-            lift.set_from_int( x * self.__modulus.int32 + self.ivalue )
++            x = (other.ivalue - self.ivalue % other._modulus.int32) * mod_inverse_int(self._modulus.int32, other._modulus.int32)
++            lift.set_from_int( x * self._modulus.int32 + self.ivalue )
+             return lift
+         except ZeroDivisionError:
+             raise ZeroDivisionError("moduli must be coprime")
+@@ -2586,8 +2586,8 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         """
+         cdef int_fast32_t x
+         x = self.ivalue + (<IntegerMod_int>right).ivalue
+-        if x >= self.__modulus.int32:
+-            x = x - self.__modulus.int32
++        if x >= self._modulus.int32:
++            x = x - self._modulus.int32
+         return self._new_c(x)
+ 
+     cpdef _sub_(self, right):
+@@ -2601,7 +2601,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         cdef int_fast32_t x
+         x = self.ivalue - (<IntegerMod_int>right).ivalue
+         if x < 0:
+-            x = x + self.__modulus.int32
++            x = x + self._modulus.int32
+         return self._new_c(x)
+ 
+     cpdef _neg_(self):
+@@ -2615,7 +2615,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         """
+         if self.ivalue == 0:
+             return self
+-        return self._new_c(self.__modulus.int32 - self.ivalue)
++        return self._new_c(self._modulus.int32 - self.ivalue)
+ 
+     cpdef _mul_(self, right):
+         """
+@@ -2625,7 +2625,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: R(7) * R(8)
+             6
+         """
+-        return self._new_c((self.ivalue * (<IntegerMod_int>right).ivalue) % self.__modulus.int32)
++        return self._new_c((self.ivalue * (<IntegerMod_int>right).ivalue) % self._modulus.int32)
+ 
+     cpdef _div_(self, right):
+         """
+@@ -2635,16 +2635,16 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: R(2)/3
+             4
+         """
+-        if self.__modulus.inverses is not None:
+-            right_inverse = self.__modulus.inverses[(<IntegerMod_int>right).ivalue]
++        if self._modulus.inverses is not None:
++            right_inverse = self._modulus.inverses[(<IntegerMod_int>right).ivalue]
+             if right_inverse is None:
+-                raise ZeroDivisionError(f"inverse of Mod({right}, {self.__modulus.sageInteger}) does not exist")
++                raise ZeroDivisionError(f"inverse of Mod({right}, {self._modulus.sageInteger}) does not exist")
+             else:
+-                return self._new_c((self.ivalue * (<IntegerMod_int>right_inverse).ivalue) % self.__modulus.int32)
++                return self._new_c((self.ivalue * (<IntegerMod_int>right_inverse).ivalue) % self._modulus.int32)
+ 
+         cdef int_fast32_t x
+-        x = self.ivalue * mod_inverse_int((<IntegerMod_int>right).ivalue, self.__modulus.int32)
+-        return self._new_c(x% self.__modulus.int32)
++        x = self.ivalue * mod_inverse_int((<IntegerMod_int>right).ivalue, self._modulus.int32)
++        return self._new_c(x% self._modulus.int32)
+ 
+     def __int__(IntegerMod_int self):
+         """
+@@ -2739,7 +2739,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         if k == 0:
+             return self
+         elif k > 0:
+-            return self._new_c((self.ivalue << k) % self.__modulus.int32)
++            return self._new_c((self.ivalue << k) % self._modulus.int32)
+         else:
+             return self._new_c(self.ivalue >> (-k))
+ 
+@@ -2802,7 +2802,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sig_on()
+             try:
+                 mpz_init(res_mpz)
+-                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self.__modulus.sageInteger.value)
++                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self._modulus.sageInteger.value)
+                 res = mpz_get_ui(res_mpz)
+                 mpz_clear(res_mpz)
+             finally:
+@@ -2811,12 +2811,12 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+ 
+         if long_exp == 0 and self.ivalue == 0:
+             # Return 0 if the modulus is 1, otherwise return 1.
+-            return self._new_c(self.__modulus.int32 != 1)
++            return self._new_c(self._modulus.int32 != 1)
+         cdef bint invert = False
+         if long_exp < 0:
+             invert = True
+             long_exp = -long_exp
+-        res = mod_pow_int(self.ivalue, long_exp, self.__modulus.int32)
++        res = mod_pow_int(self.ivalue, long_exp, self._modulus.int32)
+         if invert:
+             return ~self._new_c(res)
+         else:
+@@ -2833,14 +2833,14 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: Mod(0,1)^-1
+             0
+         """
+-        if self.__modulus.inverses is not None:
+-            x = self.__modulus.inverses[self.ivalue]
++        if self._modulus.inverses is not None:
++            x = self._modulus.inverses[self.ivalue]
+             if x is None:
+-                raise ZeroDivisionError(f"inverse of Mod({self}, {self.__modulus.sageInteger}) does not exist")
++                raise ZeroDivisionError(f"inverse of Mod({self}, {self._modulus.sageInteger}) does not exist")
+             else:
+                 return x
+         else:
+-            return self._new_c(mod_inverse_int(self.ivalue, self.__modulus.int32))
++            return self._new_c(mod_inverse_int(self.ivalue, self._modulus.int32))
+ 
+     def lift(IntegerMod_int self):
+         """
+@@ -3006,15 +3006,15 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: GF(103)(-1).sqrt(extend=False, all=True)
+             []
+         """
+-        cdef int_fast32_t i, n = self.__modulus.int32
++        cdef int_fast32_t i, n = self._modulus.int32
+         if n > 100:
+             moduli = self._parent.factored_order()
+         # Unless the modulus is tiny, test to see if we're in the really
+         # easy case of n prime, n = 3 mod 4.
+         if n > 100 and n % 4 == 3 and len(moduli) == 1 and moduli[0][1] == 1:
+-            if jacobi_int(self.ivalue, self.__modulus.int32) == 1:
++            if jacobi_int(self.ivalue, self._modulus.int32) == 1:
+                 # it's a non-zero square, sqrt(a) = a^(p+1)/4
+-                i = mod_pow_int(self.ivalue, (self.__modulus.int32+1)/4, n)
++                i = mod_pow_int(self.ivalue, (self._modulus.int32+1)/4, n)
+                 if i > n / 2:
+                     i = n - i
+                 if all:
+@@ -3049,7 +3049,7 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+         This function returns `x` or `-x`, whichever has a
+         positive representative in `-n/2 < x \leq n/2`.
+         """
+-        if self.ivalue > self.__modulus.int32 / 2:
++        if self.ivalue > self._modulus.int32 / 2:
+             return -self
+         return self
+ 
+@@ -3082,9 +3082,9 @@ cdef class IntegerMod_int(IntegerMod_abstract):
+             sage: mod(0,1).gcd(mod(0,1))
+             0
+         """
+-        cdef int_fast32_t g = gcd_int(self.ivalue, self.__modulus.int32)
++        cdef int_fast32_t g = gcd_int(self.ivalue, self._modulus.int32)
+         g = gcd_int(g, other.ivalue)
+-        if g == self.__modulus.int32: # self = other = 0
++        if g == self._modulus.int32: # self = other = 0
+             g = 0
+         return self._new_c(g)
+ 
+@@ -3256,27 +3256,27 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+     cdef IntegerMod_int64 _new_c(self, int_fast64_t value):
+         cdef IntegerMod_int64 x
+         x = IntegerMod_int64.__new__(IntegerMod_int64)
+-        x.__modulus = self.__modulus
++        x._modulus = self._modulus
+         x._parent = self._parent
+         x.ivalue = value
+         return x
+ 
+     cdef void set_from_mpz(self, mpz_t value):
+-        self.ivalue = mpz_fdiv_ui(value, self.__modulus.int64)
++        self.ivalue = mpz_fdiv_ui(value, self._modulus.int64)
+ 
+     cdef void set_from_long(self, long value):
+-        self.ivalue = value % self.__modulus.int64
++        self.ivalue = value % self._modulus.int64
+         if self.ivalue < 0:
+-            self.ivalue += self.__modulus.int64
++            self.ivalue += self._modulus.int64
+ 
+     cdef void set_from_ulong_fast(self, unsigned long value):
+         self.ivalue = value
+ 
+     cdef void set_from_int(IntegerMod_int64 self, int_fast64_t ivalue):
+         if ivalue < 0:
+-            self.ivalue = self.__modulus.int64 + (ivalue % self.__modulus.int64) # Is ivalue % self.__modulus.int64 actually negative?
+-        elif ivalue >= self.__modulus.int64:
+-            self.ivalue = ivalue % self.__modulus.int64
++            self.ivalue = self._modulus.int64 + (ivalue % self._modulus.int64) # Is ivalue % self._modulus.int64 actually negative?
++        elif ivalue >= self._modulus.int64:
++            self.ivalue = ivalue % self._modulus.int64
+         else:
+             self.ivalue = ivalue
+ 
+@@ -3344,9 +3344,9 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: mod(25, 5^10).is_unit()
+             False
+         """
+-        return gcd_int64(self.ivalue, self.__modulus.int64) == 1
++        return gcd_int64(self.ivalue, self._modulus.int64) == 1
+ 
+-    def __crt(IntegerMod_int64 self, IntegerMod_int64 other):
++    def _crt(IntegerMod_int64 self, IntegerMod_int64 other):
+         """
+         Use the Chinese Remainder Theorem to find an element of the
+         integers modulo the product of the moduli that reduces to self and
+@@ -3379,11 +3379,11 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         cdef int_fast64_t x
+ 
+         from .integer_mod_ring import IntegerModRing
+-        lift = IntegerMod_int64(IntegerModRing(self.__modulus.int64 * other.__modulus.int64))
++        lift = IntegerMod_int64(IntegerModRing(self._modulus.int64 * other._modulus.int64))
+ 
+         try:
+-            x = (other.ivalue - self.ivalue % other.__modulus.int64) * mod_inverse_int64(self.__modulus.int64, other.__modulus.int64)
+-            lift.set_from_int( x * self.__modulus.int64 + self.ivalue )
++            x = (other.ivalue - self.ivalue % other._modulus.int64) * mod_inverse_int64(self._modulus.int64, other._modulus.int64)
++            lift.set_from_int( x * self._modulus.int64 + self.ivalue )
+             return lift
+         except ZeroDivisionError:
+             raise ZeroDivisionError("moduli must be coprime")
+@@ -3422,8 +3422,8 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         """
+         cdef int_fast64_t x
+         x = self.ivalue + (<IntegerMod_int64>right).ivalue
+-        if x >= self.__modulus.int64:
+-            x = x - self.__modulus.int64
++        if x >= self._modulus.int64:
++            x = x - self._modulus.int64
+         return self._new_c(x)
+ 
+     cpdef _sub_(self, right):
+@@ -3437,7 +3437,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         cdef int_fast64_t x
+         x = self.ivalue - (<IntegerMod_int64>right).ivalue
+         if x < 0:
+-            x = x + self.__modulus.int64
++            x = x + self._modulus.int64
+         return self._new_c(x)
+ 
+     cpdef _neg_(self):
+@@ -3451,7 +3451,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         """
+         if self.ivalue == 0:
+             return self
+-        return self._new_c(self.__modulus.int64 - self.ivalue)
++        return self._new_c(self._modulus.int64 - self.ivalue)
+ 
+     cpdef _mul_(self, right):
+         """
+@@ -3461,7 +3461,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: R(700) * R(800)
+             60000
+         """
+-        return self._new_c((self.ivalue * (<IntegerMod_int64>right).ivalue) % self.__modulus.int64)
++        return self._new_c((self.ivalue * (<IntegerMod_int64>right).ivalue) % self._modulus.int64)
+ 
+ 
+     cpdef _div_(self, right):
+@@ -3473,7 +3473,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             33334
+         """
+         return self._new_c((self.ivalue * mod_inverse_int64((<IntegerMod_int64>right).ivalue,
+-                                   self.__modulus.int64) ) % self.__modulus.int64)
++                                   self._modulus.int64) ) % self._modulus.int64)
+ 
+     def __int__(IntegerMod_int64 self):
+         return self.ivalue
+@@ -3559,7 +3559,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         if k == 0:
+             return self
+         elif k > 0:
+-            return self._new_c((self.ivalue << k) % self.__modulus.int64)
++            return self._new_c((self.ivalue << k) % self._modulus.int64)
+         else:
+             return self._new_c(self.ivalue >> (-k))
+ 
+@@ -3633,7 +3633,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sig_on()
+             try:
+                 mpz_init(res_mpz)
+-                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self.__modulus.sageInteger.value)
++                mpz_pow_helper(res_mpz, (<Integer>base).value, exp, self._modulus.sageInteger.value)
+                 res = mpz_get_ui(res_mpz)
+                 mpz_clear(res_mpz)
+             finally:
+@@ -3642,14 +3642,14 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+ 
+         if long_exp == 0 and self.ivalue == 0:
+             # Return 0 if the modulus is 1, otherwise return 1.
+-            return self._new_c(self.__modulus.int64 != 1)
++            return self._new_c(self._modulus.int64 != 1)
+         cdef bint invert = False
+         if long_exp < 0:
+             invert = True
+             long_exp = -long_exp
+-        res = mod_pow_int64(self.ivalue, long_exp, self.__modulus.int64)
++        res = mod_pow_int64(self.ivalue, long_exp, self._modulus.int64)
+         if invert:
+-            return self._new_c(mod_inverse_int64(res, self.__modulus.int64))
++            return self._new_c(mod_inverse_int64(res, self._modulus.int64))
+         else:
+             return self._new_c(res)
+ 
+@@ -3666,7 +3666,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: a
+             7
+         """
+-        return self._new_c(mod_inverse_int64(self.ivalue, self.__modulus.int64))
++        return self._new_c(mod_inverse_int64(self.ivalue, self._modulus.int64))
+ 
+     def lift(IntegerMod_int64 self):
+         """
+@@ -3715,7 +3715,7 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+         This function returns `x` or `-x`, whichever has a
+         positive representative in `-n/2 < x \leq n/2`.
+         """
+-        if self.ivalue > self.__modulus.int64 / 2:
++        if self.ivalue > self._modulus.int64 / 2:
+             return -self
+         return self
+ 
+@@ -3738,9 +3738,9 @@ cdef class IntegerMod_int64(IntegerMod_abstract):
+             sage: mod(0,17^5).gcd(mod(0,17^5))
+             0
+         """
+-        cdef int_fast64_t g = gcd_int64(self.ivalue, self.__modulus.int64)
++        cdef int_fast64_t g = gcd_int64(self.ivalue, self._modulus.int64)
+         g = gcd_int64(g, other.ivalue)
+-        if g == self.__modulus.int64: # self = other = 0
++        if g == self._modulus.int64: # self = other = 0
+             g = 0
+         return self._new_c(g)
+ 
+diff --git a/src/sage/rings/fraction_field_FpT.pyx b/src/sage/rings/fraction_field_FpT.pyx
+index 0a25191a11c..c9bb5d5a384 100644
+--- a/src/sage/rings/fraction_field_FpT.pyx
++++ b/src/sage/rings/fraction_field_FpT.pyx
+@@ -1650,7 +1650,7 @@ cdef class FpT_Fp_section(Section):
+                 raise ValueError("not constant")
+         ans = IntegerMod_int.__new__(IntegerMod_int)
+         ans._parent = self.codomain()
+-        ans.__modulus = ans._parent._pyx_order
++        ans._modulus = ans._parent._pyx_order
+         if nmod_poly_get_coeff_ui(x._denom, 0) != 1:
+             normalize(x._numer, x._denom, self.p)
+         ans.ivalue = nmod_poly_get_coeff_ui(x._numer, 0)
+diff --git a/src/sage/rings/fraction_field_element.pyx b/src/sage/rings/fraction_field_element.pyx
+index 11a2b646d35..75e47af1299 100644
+--- a/src/sage/rings/fraction_field_element.pyx
++++ b/src/sage/rings/fraction_field_element.pyx
+@@ -78,8 +78,8 @@ cdef class FractionFieldElement(FieldElement):
+         sage: F.one().quo_rem(F.one())
+         (1, 0)
+     """
+-    cdef object __numerator
+-    cdef object __denominator
++    cdef object _numerator
++    cdef object _denominator
+     cdef bint _is_reduced
+ 
+     def __init__(self, parent, numerator, denominator=1,
+@@ -108,17 +108,17 @@ cdef class FractionFieldElement(FieldElement):
+         """
+         FieldElement.__init__(self, parent)
+         if coerce:
+-            self.__numerator   = parent.ring()(numerator)
+-            self.__denominator = parent.ring()(denominator)
++            self._numerator   = parent.ring()(numerator)
++            self._denominator = parent.ring()(denominator)
+         else:
+-            self.__numerator   = numerator
+-            self.__denominator = denominator
++            self._numerator   = numerator
++            self._denominator = denominator
+         if reduce and parent.is_exact():
+             try:
+                 self.reduce()
+             except ArithmeticError:
+                 pass
+-        if self.__denominator.is_zero():
++        if self._denominator.is_zero():
+             raise ZeroDivisionError("fraction field element division by zero")
+ 
+     def _im_gens_(self, codomain, im_gens, base_map=None):
+@@ -154,8 +154,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: phi(i/a)                                                              # optional - sage.rings.number_field
+             ((-i))/b
+         """
+-        nnum = codomain.coerce(self.__numerator._im_gens_(codomain, im_gens, base_map=base_map))
+-        nden = codomain.coerce(self.__denominator._im_gens_(codomain, im_gens, base_map=base_map))
++        nnum = codomain.coerce(self._numerator._im_gens_(codomain, im_gens, base_map=base_map))
++        nden = codomain.coerce(self._denominator._im_gens_(codomain, im_gens, base_map=base_map))
+         return codomain.coerce(nnum/nden)
+ 
+     cpdef reduce(self):
+@@ -191,10 +191,10 @@ cdef class FractionFieldElement(FieldElement):
+         if self._is_reduced:
+             return
+         try:
+-            g = self.__numerator.gcd(self.__denominator)
++            g = self._numerator.gcd(self._denominator)
+             if not g.is_unit():
+-                self.__numerator //= g
+-                self.__denominator //= g
++                self._numerator //= g
++                self._denominator //= g
+             self._is_reduced = True
+         except AttributeError:
+             raise ArithmeticError("unable to reduce because lack of gcd or quo_rem algorithm")
+@@ -202,14 +202,14 @@ cdef class FractionFieldElement(FieldElement):
+             raise ArithmeticError("unable to reduce because gcd algorithm doesn't work on input")
+         except NotImplementedError:
+             raise ArithmeticError("unable to reduce because gcd algorithm not implemented on input")
+-        if not self.__denominator.is_one() and self.__denominator.is_unit():
++        if not self._denominator.is_one() and self._denominator.is_unit():
+             try:
+-                inv = self.__denominator.inverse_of_unit()
++                inv = self._denominator.inverse_of_unit()
+             except Exception:
+                 pass
+             else:
+-                self.__numerator *= inv
+-                self.__denominator = self.__denominator.parent().one()
++                self._numerator *= inv
++                self._denominator = self._denominator.parent().one()
+ 
+     def __copy__(self):
+         """
+@@ -223,8 +223,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: copy(f)
+             (x + y)/y
+         """
+-        return self.__class__(self._parent, self.__numerator,
+-                self.__denominator, coerce=False, reduce=False)
++        return self.__class__(self._parent, self._numerator,
++                self._denominator, coerce=False, reduce=False)
+ 
+     def numerator(self):
+         """
+@@ -238,7 +238,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f.numerator()
+             x + y
+         """
+-        return self.__numerator
++        return self._numerator
+ 
+     def denominator(self):
+         """
+@@ -252,7 +252,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f.denominator()
+             y
+         """
+-        return self.__denominator
++        return self._denominator
+ 
+ 
+     def is_square(self,root=False):
+@@ -399,10 +399,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: ((x+1)/(x^2+1)).subs({x: 1})                                          # optional - sage.rings.number_field
+             1
+         """
+-        if self.__denominator.is_one():
++        if self._denominator.is_one():
+             # Handle this case even over rings that don't support reduction, to
+             # avoid breaking existing code that carelessly mixes p and p/1
+-            return hash(self.__numerator)
++            return hash(self._numerator)
+         if self._parent.is_exact():
+             # May fail; let the exception propagate then.
+             # (In contrast, over inexact rings, we hash unreduced fractions
+@@ -413,8 +413,8 @@ cdef class FractionFieldElement(FieldElement):
+             # issues even if we didn't...)
+             self.reduce()
+         # Same algorithm as for elements of QQ
+-        n = hash(self.__numerator)
+-        d = hash(self.__denominator)
++        n = hash(self._numerator)
++        d = hash(self._denominator)
+         if d == 1:
+             return n
+         else:
+@@ -443,7 +443,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: h(x0=1)
+             (-2*x1*x2 + x1 + 1)/(x1 + x2)
+         """
+-        return self.__numerator(*x, **kwds) / self.__denominator(*x, **kwds)
++        return self._numerator(*x, **kwds) / self._denominator(*x, **kwds)
+ 
+     def _is_atomic(self):
+         """
+@@ -456,7 +456,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f._is_atomic()
+             False
+         """
+-        return self.__numerator._is_atomic() and self.__denominator._is_atomic()
++        return self._numerator._is_atomic() and self._denominator._is_atomic()
+ 
+     def _repr_(self):
+         """
+@@ -476,13 +476,13 @@ cdef class FractionFieldElement(FieldElement):
+         """
+         if self.is_zero():
+             return "0"
+-        s = "%s" % self.__numerator
+-        if self.__denominator != 1:
+-            denom_string = str( self.__denominator )
+-            if self.__denominator._is_atomic() and not ('*' in denom_string or '/' in denom_string):
+-                s = "%s/%s"%(self.__numerator._coeff_repr(no_space=False),denom_string)
++        s = "%s" % self._numerator
++        if self._denominator != 1:
++            denom_string = str( self._denominator )
++            if self._denominator._is_atomic() and not ('*' in denom_string or '/' in denom_string):
++                s = "%s/%s"%(self._numerator._coeff_repr(no_space=False),denom_string)
+             else:
+-                s = "%s/(%s)"%(self.__numerator._coeff_repr(no_space=False),denom_string)
++                s = "%s/(%s)"%(self._numerator._coeff_repr(no_space=False),denom_string)
+         return s
+ 
+     def _latex_(self):
+@@ -518,10 +518,10 @@ cdef class FractionFieldElement(FieldElement):
+         """
+         if self.is_zero():
+             return "0"
+-        if self.__denominator == 1:
+-            return latex.latex(self.__numerator)
+-        return "\\frac{%s}{%s}"%(latex.latex(self.__numerator),
+-                                 latex.latex(self.__denominator))
++        if self._denominator == 1:
++            return latex.latex(self._numerator)
++        return "\\frac{%s}{%s}"%(latex.latex(self._numerator),
++                                 latex.latex(self._denominator))
+ 
+     def _magma_init_(self, magma):
+         """
+@@ -577,10 +577,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: t - 1/t # indirect doctest                                            # optional - sage.rings.finite_rings
+             (t^2 + 6)/t
+         """
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         if (rnum.is_zero()):
+             return <FractionFieldElement> right
+@@ -602,7 +602,7 @@ cdef class FractionFieldElement(FieldElement):
+                             self._parent.ring().one(), coerce=False,
+                             reduce=False)
+                     else:
+-                        tden = self.__denominator * sden
++                        tden = self._denominator * sden
+                         e    = tnum.gcd(d)
+                         if not e.is_unit():
+                             tnum = tnum // e
+@@ -624,10 +624,10 @@ cdef class FractionFieldElement(FieldElement):
+             except TypeError:
+                 pass
+ 
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         return self.__class__(self._parent, rnum*sden + rden*snum, rden*sden,
+             coerce=False, reduce=False)
+@@ -652,10 +652,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: a * b # indirect doctest                                              # optional - sage.rings.finite_rings
+             3/(t + 1)
+         """
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         if (rnum.is_zero() or snum.is_zero()):
+             return self._parent.zero()
+@@ -689,10 +689,10 @@ cdef class FractionFieldElement(FieldElement):
+             except TypeError:
+                 pass
+ 
+-        rnum = self.__numerator
+-        rden = self.__denominator
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        rnum = self._numerator
++        rden = self._denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         return self.__class__(self._parent, rnum * snum, rden * sden,
+             coerce=False, reduce=False)
+@@ -717,8 +717,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: a/b
+             (x*z - x + z - 1)/(z - 3)
+         """
+-        snum = (<FractionFieldElement> right).__numerator
+-        sden = (<FractionFieldElement> right).__denominator
++        snum = (<FractionFieldElement> right)._numerator
++        sden = (<FractionFieldElement> right)._denominator
+ 
+         if snum.is_zero():
+             raise ZeroDivisionError("fraction field element division by zero")
+@@ -743,10 +743,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: int(K(.5))
+             0
+         """
+-        if self.__denominator != 1:
++        if self._denominator != 1:
+             self.reduce()
+-        if self.__denominator == 1:
+-            return int(self.__numerator)
++        if self._denominator == 1:
++            return int(self._numerator)
+         else:
+             raise TypeError("denominator must equal 1")
+ 
+@@ -758,7 +758,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: float(x/x + y/y)
+             2.0
+         """
+-        return float(self.__numerator) / float(self.__denominator)
++        return float(self._numerator) / float(self._denominator)
+ 
+     def __complex__(self):
+         """
+@@ -768,7 +768,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: complex(x/(I*x) + (I*y)/y)
+             0j
+         """
+-        return complex(self.__numerator) / complex(self.__denominator)
++        return complex(self._numerator) / complex(self._denominator)
+ 
+     def _rational_(self):
+         r"""
+@@ -822,12 +822,12 @@ cdef class FractionFieldElement(FieldElement):
+             sage: A(C(u))                                                               # optional - sage.rings.number_field
+             u
+         """
+-        if self.__denominator.is_one():
+-            return R(self.__numerator)
++        if self._denominator.is_one():
++            return R(self._numerator)
+         else:
+             self.reduce()
+-            num = R(self.__numerator)
+-            inv_den = R(self.__denominator).inverse_of_unit()
++            num = R(self._numerator)
++            inv_den = R(self._denominator).inverse_of_unit()
+             return num * inv_den
+ 
+     _real_double_ = _conversion
+@@ -847,7 +847,7 @@ cdef class FractionFieldElement(FieldElement):
+         Returns self raised to the `right^{th}` power.
+ 
+         Note that we need to check whether or not right is negative so we
+-        don't set ``__numerator`` or ``__denominator`` to an element of the
++        don't set ``_numerator`` or ``_denominator`` to an element of the
+         fraction field instead of the underlying ring.
+ 
+         EXAMPLES::
+@@ -876,8 +876,8 @@ cdef class FractionFieldElement(FieldElement):
+             sage: ((x+y)/(x-y))^0
+             1
+         """
+-        snum = (<FractionFieldElement> self).__numerator
+-        sden = (<FractionFieldElement> self).__denominator
++        snum = (<FractionFieldElement> self)._numerator
++        sden = (<FractionFieldElement> self)._denominator
+         if right == 0:
+             R = self.parent().ring()
+             return self.__class__(self.parent(),
+@@ -904,7 +904,7 @@ cdef class FractionFieldElement(FieldElement):
+             (4*t^2 + 4*t)/(t + 2)
+         """
+         return self.__class__(self._parent,
+-            -self.__numerator, self.__denominator,
++            -self._numerator, self._denominator,
+             coerce=False, reduce=False)
+ 
+     def __abs__(self):
+@@ -915,7 +915,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: abs(FractionFieldElement(QQ, -2, 3, coerce=False))
+             2/3
+         """
+-        return abs(self.__numerator) / abs(self.__denominator)
++        return abs(self._numerator) / abs(self._denominator)
+ 
+     def __invert__(self):
+         """
+@@ -929,7 +929,7 @@ cdef class FractionFieldElement(FieldElement):
+         if self.is_zero():
+             raise ZeroDivisionError("Cannot invert 0")
+         return self.__class__(self._parent,
+-            self.__denominator, self.__numerator, coerce=False, reduce=False)
++            self._denominator, self._numerator, coerce=False, reduce=False)
+ 
+     cpdef _richcmp_(self, other, int op):
+         """
+@@ -951,10 +951,10 @@ cdef class FractionFieldElement(FieldElement):
+             sage: 1 > y
+             False
+         """
+-        return richcmp(self.__numerator *
+-                       (<FractionFieldElement>other).__denominator,
+-                       self.__denominator *
+-                       (<FractionFieldElement>other).__numerator, op)
++        return richcmp(self._numerator *
++                       (<FractionFieldElement>other)._denominator,
++                       self._denominator *
++                       (<FractionFieldElement>other)._numerator, op)
+ 
+     def valuation(self, v=None):
+         """
+@@ -972,7 +972,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: f.valuation(x^2 + 1)
+             1
+         """
+-        return self.__numerator.valuation(v) - self.__denominator.valuation(v)
++        return self._numerator.valuation(v) - self._denominator.valuation(v)
+ 
+     def __bool__(self):
+         """
+@@ -991,7 +991,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: bool(1/x)
+             True
+         """
+-        return not self.__numerator.is_zero()
++        return not self._numerator.is_zero()
+ 
+     def is_zero(self):
+         """
+@@ -1010,7 +1010,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: u.parent() is F
+             True
+         """
+-        return self.__numerator.is_zero()
++        return self._numerator.is_zero()
+ 
+     def is_one(self):
+         """
+@@ -1025,7 +1025,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: (x/y).is_one()
+             False
+         """
+-        return self.__numerator == self.__denominator
++        return self._numerator == self._denominator
+ 
+     def _symbolic_(self, ring):
+         """
+@@ -1044,7 +1044,7 @@ cdef class FractionFieldElement(FieldElement):
+             sage: symbolic_expression(elt)                                              # optional - sage.symbolic
+             2/3*(x + y)/(x - y)
+         """
+-        return ring(self.__numerator)/ring(self.__denominator)
++        return ring(self._numerator)/ring(self._denominator)
+ 
+     def __reduce__(self):
+         """
+@@ -1058,7 +1058,7 @@ cdef class FractionFieldElement(FieldElement):
+             True
+         """
+         return (make_element,
+-                (self._parent, self.__numerator, self.__denominator))
++                (self._parent, self._numerator, self._denominator))
+ 
+     def _evaluate_polynomial(self, pol):
+         """
+@@ -1170,9 +1170,9 @@ cdef class FractionFieldElement_1poly_field(FractionFieldElement):
+         """
+         See :meth:`reduce`.
+         """
+-        invlc = ~self.__denominator.leading_coefficient()
+-        self.__denominator = self.__denominator.monic()
+-        self.__numerator *= invlc
++        invlc = ~self._denominator.leading_coefficient()
++        self._denominator = self._denominator.monic()
++        self._numerator *= invlc
+ 
+     def is_integral(self):
+         """
+diff --git a/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py b/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py
+index a27e75f5fce..74ef125fb6a 100644
+--- a/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py
++++ b/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py
+@@ -804,8 +804,8 @@ def _latex_(self):
+             \phi
+             sage: phi.reset_name()
+         """
+-        if hasattr(self, '__custom_name'):
+-            return latex_variable_name(getattr(self, '__custom_name'))
++        if self.get_custom_name() is not None:
++            return latex_variable_name(self.get_custom_name())
+         else:
+             return f'\\phi: {latex(self._function_ring.gen())} \\mapsto ' \
+                    f'{latex(self._gen)}'
+diff --git a/src/sage/rings/laurent_series_ring_element.pxd b/src/sage/rings/laurent_series_ring_element.pxd
+index d190645ce52..8df5a92c9e7 100644
+--- a/src/sage/rings/laurent_series_ring_element.pxd
++++ b/src/sage/rings/laurent_series_ring_element.pxd
+@@ -4,7 +4,7 @@ cdef class LaurentSeries(AlgebraElement):
+     cdef ModuleElement __u
+     cdef long __n
+ 
+-    cdef __normalize(self)
++    cdef _normalize(self)
+     cpdef _add_(self, other)
+     cpdef _mul_(self, other)
+ 
+diff --git a/src/sage/rings/laurent_series_ring_element.pyx b/src/sage/rings/laurent_series_ring_element.pyx
+index 8e950478045..9bef72396b7 100644
+--- a/src/sage/rings/laurent_series_ring_element.pyx
++++ b/src/sage/rings/laurent_series_ring_element.pyx
+@@ -302,7 +302,7 @@ cdef class LaurentSeries(AlgebraElement):
+         x = im_gens[0]
+         return codomain(self.__u._im_gens_(codomain, im_gens, base_map=base_map) * x**self.__n)
+ 
+-    cdef __normalize(self):
++    cdef _normalize(self):
+         r"""
+         A Laurent series is a pair (u(t), n), where either u=0 (to some
+         precision) or u is a unit. This pair corresponds to
+@@ -725,7 +725,7 @@ cdef class LaurentSeries(AlgebraElement):
+                 R = self._parent.base_ring()
+                 coeffs = [value] + [R(0) for _ in range(1,-j)] + self.__u.list()
+                 self.__u = self.__u._parent(coeffs)
+-        self.__normalize()
++        self._normalize()
+ 
+     cpdef _add_(self, right_m):
+         """
+diff --git a/src/sage/rings/morphism.pxd b/src/sage/rings/morphism.pxd
+index ea6089f29b4..4b8e8d052df 100644
+--- a/src/sage/rings/morphism.pxd
++++ b/src/sage/rings/morphism.pxd
+@@ -14,7 +14,7 @@ cdef class RingMap_lift(RingMap):
+ 
+ cdef class RingHomomorphism(RingMap):
+     cdef Morphism _lift
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+ cdef class RingHomomorphism_im_gens(RingHomomorphism):
+     cdef _im_gens
+diff --git a/src/sage/rings/number_field/number_field_element.pxd b/src/sage/rings/number_field/number_field_element.pxd
+index 9b6917223a0..c3d8a8b4a4b 100644
+--- a/src/sage/rings/number_field/number_field_element.pxd
++++ b/src/sage/rings/number_field/number_field_element.pxd
+@@ -11,12 +11,12 @@ from sage.libs.ntl.ntl_ZZ cimport ntl_ZZ
+ 
+ 
+ cdef class NumberFieldElement(NumberFieldElement_base):
+-    cdef ZZX_c __numerator
+-    cdef ZZ_c __denominator
++    cdef ZZX_c _numerator
++    cdef ZZ_c _denominator
+     # Pointers to the defining polynomial (with numerator) for the field.
+     # I keep these as pointers for arithmetic speed.
+-    cdef ntl_ZZX __fld_numerator
+-    cdef ntl_ZZ __fld_denominator
++    cdef ntl_ZZX _fld_numerator
++    cdef ntl_ZZ _fld_denominator
+     cdef object __multiplicative_order
+     cdef object __pari
+     cdef object __matrix
+diff --git a/src/sage/rings/number_field/number_field_element.pyx b/src/sage/rings/number_field/number_field_element.pyx
+index 27e33ad5be0..d44fc55b70c 100644
+--- a/src/sage/rings/number_field/number_field_element.pyx
++++ b/src/sage/rings/number_field/number_field_element.pyx
+@@ -218,8 +218,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef type t = type(self)
+         cdef NumberFieldElement x = <NumberFieldElement>t.__new__(t)
+         x._parent = self._parent
+-        x.__fld_numerator = self.__fld_numerator
+-        x.__fld_denominator = self.__fld_denominator
++        x._fld_numerator = self._fld_numerator
++        x._fld_denominator = self._fld_denominator
+         return x
+ 
+     cdef number_field(self):
+@@ -317,20 +317,20 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             True
+         """
+         FieldElement.__init__(self, parent)
+-        self.__fld_numerator, self.__fld_denominator = parent.absolute_polynomial_ntl()
++        self._fld_numerator, self._fld_denominator = parent.absolute_polynomial_ntl()
+ 
+         cdef ZZ_c coeff
+         if isinstance(f, (int, Integer_sage)):
+             # set it up and exit immediately
+             # fast pathway
+             mpz_to_ZZ(&coeff, (<Integer>ZZ(f)).value)
+-            ZZX_SetCoeff( self.__numerator, 0, coeff )
+-            ZZ_conv_from_int( self.__denominator, 1 )
++            ZZX_SetCoeff( self._numerator, 0, coeff )
++            ZZ_conv_from_int( self._denominator, 1 )
+             return
+         elif isinstance(f, NumberFieldElement):
+             if type(self) is type(f):
+-                self.__numerator = (<NumberFieldElement>f).__numerator
+-                self.__denominator = (<NumberFieldElement>f).__denominator
++                self._numerator = (<NumberFieldElement>f)._numerator
++                self._denominator = (<NumberFieldElement>f)._denominator
+                 return
+             else:
+                 f = f.polynomial()
+@@ -342,11 +342,11 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+ 
+         cdef long i
+         den = f.denominator()
+-        mpz_to_ZZ(&self.__denominator, (<Integer>ZZ(den)).value)
++        mpz_to_ZZ(&self._denominator, (<Integer>ZZ(den)).value)
+         num = f * den
+         for i from 0 <= i <= num.degree():
+             mpz_to_ZZ(&coeff, (<Integer>ZZ(num[i])).value)
+-            ZZX_SetCoeff( self.__numerator, i, coeff )
++            ZZX_SetCoeff( self._numerator, i, coeff )
+ 
+     def _lift_cyclotomic_element(self, new_parent, bint check=True, int rel=0):
+         """
+@@ -417,17 +417,17 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef type t = type(self)
+         cdef NumberFieldElement x = <NumberFieldElement>t.__new__(t)
+         x._parent = <ParentWithBase>new_parent
+-        x.__fld_numerator, x.__fld_denominator = new_parent.polynomial_ntl()
+-        x.__denominator = self.__denominator
++        x._fld_numerator, x._fld_denominator = new_parent.polynomial_ntl()
++        x._denominator = self._denominator
+         cdef ZZX_c result
+         cdef ZZ_c tmp
+         cdef int i
+         cdef ntl_ZZX _num
+         cdef ntl_ZZ _den
+-        for i from 0 <= i <= ZZX_deg(self.__numerator):
+-            tmp = ZZX_coeff(self.__numerator, i)
++        for i from 0 <= i <= ZZX_deg(self._numerator):
++            tmp = ZZX_coeff(self._numerator, i)
+             ZZX_SetCoeff(result, i*rel, tmp)
+-        ZZX_rem(x.__numerator, result, x.__fld_numerator.x)
++        ZZX_rem(x._numerator, result, x._fld_numerator.x)
+         return x
+ 
+     def __reduce__(self):
+@@ -858,7 +858,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef int res
+ 
+         # fast equality check
+-        res = left.__numerator == _right.__numerator and left.__denominator == _right.__denominator
++        res = left._numerator == _right._numerator and left._denominator == _right._denominator
+         if res:
+             if op == Py_EQ or op == Py_GE or op == Py_LE:
+                 return True
+@@ -883,15 +883,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         if P._embedded_real:
+             mpz_init(ld)
+             mpz_init(rd)
+-            ZZ_to_mpz(ld, &left.__denominator)
+-            ZZ_to_mpz(rd, &_right.__denominator)
++            ZZ_to_mpz(ld, &left._denominator)
++            ZZ_to_mpz(rd, &_right._denominator)
+ 
+             v = <RealIntervalFieldElement> P._get_embedding_approx(0)
+             mpfi_init2(la, mpfi_get_prec(v.value))
+             mpfi_init2(ra, mpfi_get_prec(v.value))
+-            ZZX_evaluation_mpfi(la, left.__numerator, v.value)
++            ZZX_evaluation_mpfi(la, left._numerator, v.value)
+             mpfi_div_z(la, la, ld)
+-            ZZX_evaluation_mpfi(ra, _right.__numerator, v.value)
++            ZZX_evaluation_mpfi(ra, _right._numerator, v.value)
+             mpfi_div_z(ra, ra, rd)
+             while mpfr_greaterequal_p(&la.right, &ra.left) \
+                   and mpfr_greaterequal_p(&ra.right, &la.left):
+@@ -899,9 +899,9 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+                 v = <RealIntervalFieldElement> P._get_embedding_approx(i)
+                 mpfi_set_prec(la, mpfi_get_prec(v.value))
+                 mpfi_set_prec(ra, mpfi_get_prec(v.value))
+-                ZZX_evaluation_mpfi(la, left.__numerator, v.value)
++                ZZX_evaluation_mpfi(la, left._numerator, v.value)
+                 mpfi_div_z(la, la, ld)
+-                ZZX_evaluation_mpfi(ra, _right.__numerator, v.value)
++                ZZX_evaluation_mpfi(ra, _right._numerator, v.value)
+                 mpfi_div_z(ra, ra, rd)
+             if op == Py_LT or op == Py_LE:
+                 res = mpfr_less_p(&la.right, &ra.left)
+@@ -950,8 +950,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef Rational tmp_rational
+ 
+         # It seems like a simpler approach would be to simply generate
+-        # random integers for each coefficient of self.__numerator
+-        # and an integer for self.__denominator. However, this would
++        # random integers for each coefficient of self._numerator
++        # and an integer for self._denominator. However, this would
+         # generate things with a fairly fixed shape: in particular,
+         # we'd be very unlikely to get elements like 1/3*a^3 + 1/7,
+         # or anything where the denominators are actually unrelated
+@@ -965,19 +965,19 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+ 
+             # set the denominator
+             mpz_set_si(denom_temp.value, 1)
+-            mpz_to_ZZ(&self.__denominator, (<Integer>denom_temp).value)
+-            for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
++            mpz_to_ZZ(&self._denominator, (<Integer>denom_temp).value)
++            for i from 0 <= i < ZZX_deg(self._fld_numerator.x):
+                 tmp_integer = <Integer>(ZZ.random_element(x=num_bound,
+                                                    distribution=distribution))
+                 mpz_to_ZZ(&ntl_temp, (<Integer>tmp_integer).value)
+-                ZZX_SetCoeff(self.__numerator, i, ntl_temp)
++                ZZX_SetCoeff(self._numerator, i, ntl_temp)
+ 
+         else:
+             coeff_list = []
+             mpz_set_si(denom_temp.value, 1)
+             tmp_integer = Integer.__new__(Integer)
+ 
+-            for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
++            for i from 0 <= i < ZZX_deg(self._fld_numerator.x):
+                 tmp_rational = <Rational>(QQ.random_element(num_bound=num_bound,
+                                                             den_bound=den_bound,
+                                                             distribution=distribution))
+@@ -989,10 +989,10 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             # scale the numerators and set everything appropriately
+ 
+             # first, the denominator (easy)
+-            mpz_to_ZZ(&self.__denominator, (<Integer>denom_temp).value)
++            mpz_to_ZZ(&self._denominator, (<Integer>denom_temp).value)
+ 
+             # now the coefficients themselves.
+-            for i from 0 <= i < ZZX_deg(self.__fld_numerator.x):
++            for i from 0 <= i < ZZX_deg(self._fld_numerator.x):
+                 # calculate the new numerator. if our old entry is
+                 # p/q, and the lcm is k, it's just pk/q, which we
+                 # also know is integral -- so we can use mpz_divexact
+@@ -1006,7 +1006,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+                 # now set the coefficient of self
+                 mpz_to_ZZ(&ntl_temp, (<Integer>tmp_integer).value)
+ 
+-                ZZX_SetCoeff(self.__numerator, i, ntl_temp)
++                ZZX_SetCoeff(self._numerator, i, ntl_temp)
+ 
+         return 0  # No error
+ 
+@@ -1089,10 +1089,10 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: L.zero().sign()
+             0
+         """
+-        if ZZX_deg(self.__numerator) == -1:
++        if ZZX_deg(self._numerator) == -1:
+             return 0
+-        if ZZX_deg(self.__numerator) == 0:
+-            return ZZ_sign(ZZX_coeff(self.__numerator, 0))
++        if ZZX_deg(self._numerator) == 0:
++            return ZZ_sign(ZZX_coeff(self._numerator, 0))
+ 
+         if not (<number_field_base.NumberField> self._parent)._embedded_real:
+             raise TypeError("sign not well defined since no real embedding is specified")
+@@ -1153,12 +1153,12 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef RealIntervalFieldElement v
+ 
+ 
+-        if ZZX_deg(self.__numerator) <= 0:
++        if ZZX_deg(self._numerator) <= 0:
+             mpz_init(num)
+             mpz_init(den)
+ 
+-            ZZX_getitem_as_mpz(num, &self.__numerator, 0)
+-            ZZ_to_mpz(den, &self.__denominator)
++            ZZX_getitem_as_mpz(num, &self._numerator, 0)
++            ZZ_to_mpz(den, &self._denominator)
+ 
+             ans = PY_NEW(Integer)
+             mpz_fdiv_q(ans.value, num, den)
+@@ -1183,9 +1183,9 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         mpz_init(den)
+         mpfi_init2(a, mpfi_get_prec(v.value))
+ 
+-        ZZ_to_mpz(den, &self.__denominator)
++        ZZ_to_mpz(den, &self._denominator)
+ 
+-        ZZX_evaluation_mpfi(a, self.__numerator, v.value)
++        ZZX_evaluation_mpfi(a, self._numerator, v.value)
+         mpfi_div_z(a, a, den)
+ 
+         mpfr_floor(&a.left, &a.left)
+@@ -1197,7 +1197,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             v = <RealIntervalFieldElement> P._get_embedding_approx(i)
+ 
+             mpfi_set_prec(a, mpfi_get_prec(v.value))
+-            ZZX_evaluation_mpfi(a, self.__numerator, v.value)
++            ZZX_evaluation_mpfi(a, self._numerator, v.value)
+             mpfi_div_z(a, a, den)
+             mpfr_floor(&a.left ,&a.left)
+             mpfr_floor(&a.right, &a.right)
+@@ -1248,7 +1248,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             ...
+             TypeError: ceil not uniquely defined since no real embedding is specified
+         """
+-        if ZZX_deg(self.__numerator) <= 0:
++        if ZZX_deg(self._numerator) <= 0:
+             return self._rational_().ceil()
+ 
+         if not (<number_field_base.NumberField> self._parent)._embedded_real:
+@@ -1311,7 +1311,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             ...
+             TypeError: floor not uniquely defined since no real embedding is specified
+         """
+-        if ZZX_deg(self.__numerator) <= 0:
++        if ZZX_deg(self._numerator) <= 0:
+             return self._rational_().round()
+ 
+         return (self + QQ((1,2))).floor()
+@@ -2483,17 +2483,17 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef ZZ_c gcd
+         cdef ZZ_c t1
+         cdef ZZX_c t2
+-        if ZZ_IsOne(self.__denominator):
++        if ZZ_IsOne(self._denominator):
+             return
+-        ZZX_content(t1, self.__numerator)
+-        ZZ_GCD(gcd, t1, self.__denominator)
+-        if ZZ_sign(gcd) != ZZ_sign(self.__denominator):
++        ZZX_content(t1, self._numerator)
++        ZZ_GCD(gcd, t1, self._denominator)
++        if ZZ_sign(gcd) != ZZ_sign(self._denominator):
+             ZZ_negate(t1, gcd)
+             gcd = t1
+-        ZZX_div_ZZ(t2, self.__numerator, gcd)
+-        ZZ_div(t1, self.__denominator, gcd)
+-        self.__numerator = t2
+-        self.__denominator = t1
++        ZZX_div_ZZ(t2, self._numerator, gcd)
++        ZZ_div(t1, self._denominator, gcd)
++        self._numerator = t2
++        self._denominator = t1
+ 
+     cpdef _add_(self, right):
+         r"""
+@@ -2509,15 +2509,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef NumberFieldElement _right = right
+         cdef ZZ_c g, q1, q2
+         x = self._new()
+-        ZZ_GCD(g, self.__denominator, _right.__denominator)
+-        ZZ_div(q1, self.__denominator, g)
+-        ZZ_div(q2, _right.__denominator, g)
+-        ZZ_mul(x.__denominator, q1, q2)
+-        ZZ_mul(x.__denominator, x.__denominator, g)
++        ZZ_GCD(g, self._denominator, _right._denominator)
++        ZZ_div(q1, self._denominator, g)
++        ZZ_div(q2, _right._denominator, g)
++        ZZ_mul(x._denominator, q1, q2)
++        ZZ_mul(x._denominator, x._denominator, g)
+         cdef ZZX_c t1, t2
+-        ZZX_mul_ZZ(t1, self.__numerator, q2)
+-        ZZX_mul_ZZ(t2, _right.__numerator, q1)
+-        ZZX_add(x.__numerator, t1, t2)
++        ZZX_mul_ZZ(t1, self._numerator, q2)
++        ZZX_mul_ZZ(t2, _right._numerator, q1)
++        ZZX_add(x._numerator, t1, t2)
+         x._reduce_c_()
+         return x
+ 
+@@ -2534,15 +2534,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef NumberFieldElement _right = right
+         cdef ZZ_c g, q1, q2
+         x = self._new()
+-        ZZ_GCD(g, self.__denominator, _right.__denominator)
+-        ZZ_div(q1, self.__denominator, g)
+-        ZZ_div(q2, _right.__denominator, g)
+-        ZZ_mul(x.__denominator, q1, q2)
+-        ZZ_mul(x.__denominator, x.__denominator, g)
++        ZZ_GCD(g, self._denominator, _right._denominator)
++        ZZ_div(q1, self._denominator, g)
++        ZZ_div(q2, _right._denominator, g)
++        ZZ_mul(x._denominator, q1, q2)
++        ZZ_mul(x._denominator, x._denominator, g)
+         cdef ZZX_c t1, t2
+-        ZZX_mul_ZZ(t1, self.__numerator, q2)
+-        ZZX_mul_ZZ(t2, _right.__numerator, q1)
+-        ZZX_sub(x.__numerator, t1, t2)
++        ZZX_mul_ZZ(t1, self._numerator, q2)
++        ZZX_mul_ZZ(t2, _right._numerator, q1)
++        ZZX_sub(x._numerator, t1, t2)
+         x._reduce_c_()
+         return x
+ 
+@@ -2571,18 +2571,18 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         sig_on()
+         # MulMod doesn't handle non-monic polynomials.
+         # Therefore, we handle the non-monic case entirely separately.
+-        ZZ_mul(x.__denominator, self.__denominator, _right.__denominator)
+-        if ZZ_IsOne(ZZX_LeadCoeff(self.__fld_numerator.x)):
+-            ZZX_MulMod(x.__numerator, self.__numerator, _right.__numerator, self.__fld_numerator.x)
++        ZZ_mul(x._denominator, self._denominator, _right._denominator)
++        if ZZ_IsOne(ZZX_LeadCoeff(self._fld_numerator.x)):
++            ZZX_MulMod(x._numerator, self._numerator, _right._numerator, self._fld_numerator.x)
+         else:
+-            ZZX_mul(x.__numerator, self.__numerator, _right.__numerator)
+-            if ZZX_deg(x.__numerator) >= ZZX_deg(self.__fld_numerator.x):
+-                ZZX_mul_ZZ( x.__numerator, x.__numerator, self.__fld_denominator.x )
+-                ZZX_mul_ZZ( temp, self.__fld_numerator.x, x.__denominator )
+-                ZZ_power(temp1,ZZX_LeadCoeff(temp),ZZX_deg(x.__numerator)-ZZX_deg(self.__fld_numerator.x)+1)
+-                ZZX_PseudoRem(x.__numerator, x.__numerator, temp)
+-                ZZ_mul(x.__denominator, x.__denominator, self.__fld_denominator.x)
+-                ZZ_mul(x.__denominator, x.__denominator, temp1)
++            ZZX_mul(x._numerator, self._numerator, _right._numerator)
++            if ZZX_deg(x._numerator) >= ZZX_deg(self._fld_numerator.x):
++                ZZX_mul_ZZ( x._numerator, x._numerator, self._fld_denominator.x )
++                ZZX_mul_ZZ( temp, self._fld_numerator.x, x._denominator )
++                ZZ_power(temp1,ZZX_LeadCoeff(temp),ZZX_deg(x._numerator)-ZZX_deg(self._fld_numerator.x)+1)
++                ZZX_PseudoRem(x._numerator, x._numerator, temp)
++                ZZ_mul(x._denominator, x._denominator, self._fld_denominator.x)
++                ZZ_mul(x._denominator, x._denominator, temp1)
+         sig_off()
+         x._reduce_c_()
+         return x
+@@ -2704,7 +2704,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: bool(b + 1)
+             True
+         """
+-        return not IsZero_ZZX(self.__numerator)
++        return not IsZero_ZZX(self._numerator)
+ 
+     cpdef _neg_(self):
+         r"""
+@@ -2717,8 +2717,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         """
+         cdef NumberFieldElement x
+         x = self._new()
+-        ZZX_mul_long(x.__numerator, self.__numerator, -1)
+-        x.__denominator = self.__denominator
++        ZZX_mul_long(x._numerator, self._numerator, -1)
++        x._denominator = self._denominator
+         return x
+ 
+     cpdef _copy_for_parent(self, Parent parent):
+@@ -2738,8 +2738,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         """
+         cdef NumberFieldElement x
+         x = self._new()
+-        x.__numerator = self.__numerator
+-        x.__denominator = self.__denominator
++        x._numerator = self._numerator
++        x._denominator = self._denominator
+         x._set_parent(parent)
+         return x
+ 
+@@ -2826,7 +2826,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: L.<a> = K.extension(f)
+             sage: alpha = (a^8 + (zeta22^9 - zeta22^6 + 2*zeta22^4 + 33)*a^7)/(10**2555) #long time
+         """
+-        if IsZero_ZZX(self.__numerator):
++        if IsZero_ZZX(self._numerator):
+             raise ZeroDivisionError("number field element division by zero")
+         cdef NumberFieldElement x
+         cdef ZZX_c temp
+@@ -2835,8 +2835,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             # but may fail if NTL runs out of FFT primes.
+             x = self._new()
+             sig_on()
+-            ZZX_XGCD(x.__denominator, x.__numerator, temp, self.__numerator, self.__fld_numerator.x, 1)
+-            ZZX_mul_ZZ(x.__numerator, x.__numerator, self.__denominator)
++            ZZX_XGCD(x._denominator, x._numerator, temp, self._numerator, self._fld_numerator.x, 1)
++            ZZX_mul_ZZ(x._numerator, x._numerator, self._denominator)
+             x._reduce_c_()
+             sig_off()
+         except NTLError:
+@@ -2858,7 +2858,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: (2*I*I)._integer_()
+             -2
+         """
+-        if ZZX_deg(self.__numerator) >= 1:
++        if ZZX_deg(self._numerator) >= 1:
+             raise TypeError("Unable to coerce %s to an integer" % self)
+         return ZZ(self._rational_())
+ 
+@@ -2877,12 +2877,12 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: (I*I/2)._rational_()
+             -1/2
+         """
+-        if ZZX_deg(self.__numerator) >= 1:
++        if ZZX_deg(self._numerator) >= 1:
+             raise TypeError("Unable to coerce %s to a rational"%self)
+         cdef Integer num = Integer.__new__(Integer)
+-        ZZX_getitem_as_mpz(num.value, &self.__numerator, 0)
++        ZZX_getitem_as_mpz(num.value, &self._numerator, 0)
+         cdef Integer den = Integer.__new__(Integer)
+-        ZZ_to_mpz(den.value, &self.__denominator)
++        ZZ_to_mpz(den.value, &self._denominator)
+         return num / den
+ 
+     def _algebraic_(self, parent):
+@@ -3268,15 +3268,15 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef mpz_t z
+ 
+         mpz_init(z)
+-        ZZX_getitem_as_mpz(z, &self.__numerator, 0)
++        ZZX_getitem_as_mpz(z, &self._numerator, 0)
+         h = mpz_pythonhash(z)
+ 
+-        for i from 1 <= i <= ZZX_deg(self.__numerator):
+-            ZZX_getitem_as_mpz(z, &self.__numerator, i)
++        for i from 1 <= i <= ZZX_deg(self._numerator):
++            ZZX_getitem_as_mpz(z, &self._numerator, i)
+             # magic number below is floor(2^63 / (2+sqrt(2)))
+             h ^= mpz_pythonhash(z) + (<Py_hash_t> 2701463124188384701) + (h << 16) + (h >> 2)
+ 
+-        ZZ_to_mpz(z, &self.__denominator)
++        ZZ_to_mpz(z, &self._denominator)
+         # magic number below is floor((1+sqrt(5)) * 2^61)
+         h += (mpz_pythonhash(z) - 1) * (<Py_hash_t> 7461864723258187525)
+ 
+@@ -3305,12 +3305,12 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         cdef int i
+         cdef mpz_t den
+         mpz_init(den)
+-        ZZ_to_mpz(den, &self.__denominator)
+-        cdef int size = ZZX_deg(self.__numerator) + 1
++        ZZ_to_mpz(den, &self._denominator)
++        cdef int size = ZZX_deg(self._numerator) + 1
+         cdef list coeffs = [None]*size
+         for i in range(size):
+             coeff = Rational.__new__(Rational)
+-            ZZX_getitem_as_mpz(mpq_numref(coeff.value), &self.__numerator, i)
++            ZZX_getitem_as_mpz(mpq_numref(coeff.value), &self._numerator, i)
+             mpz_set(mpq_denref(coeff.value), den)
+             mpq_canonicalize(coeff.value)
+             coeffs[i] = coeff
+@@ -3318,14 +3318,14 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+         return coeffs
+ 
+     cdef void _ntl_coeff_as_mpz(self, mpz_t z, long i):
+-        if i > ZZX_deg(self.__numerator):
++        if i > ZZX_deg(self._numerator):
+             mpz_set_ui(z, 0)
+         else:
+-            ZZX_getitem_as_mpz(z, &self.__numerator, i)
++            ZZX_getitem_as_mpz(z, &self._numerator, i)
+ 
+     cdef void _ntl_denom_as_mpz(self, mpz_t z):
+         cdef Integer denom = Integer.__new__(Integer)
+-        ZZ_to_mpz(denom.value, &self.__denominator)
++        ZZ_to_mpz(denom.value, &self._denominator)
+         mpz_set(z, denom.value)
+ 
+     def denominator(self):
+@@ -3344,7 +3344,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             15
+         """
+         cdef Integer ans = Integer.__new__(Integer)
+-        ZZ_to_mpz(ans.value, &self.__denominator)
++        ZZ_to_mpz(ans.value, &self._denominator)
+         return ans
+ 
+     def _set_multiplicative_order(self, n):
+@@ -3474,8 +3474,8 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: a.is_one()
+             False
+         """
+-        return ZZX_IsOne(self.__numerator) == 1 and \
+-               ZZ_IsOne(self.__denominator) == 1
++        return ZZX_IsOne(self._numerator) == 1 and \
++               ZZ_IsOne(self._denominator) == 1
+ 
+     cpdef bint is_rational(self):
+         r"""
+@@ -3501,7 +3501,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: K(1/2).is_rational()
+             True
+         """
+-        return ZZX_deg(self.__numerator) <= 0
++        return ZZX_deg(self._numerator) <= 0
+ 
+     def is_integer(self):
+         r"""
+@@ -3527,7 +3527,7 @@ cdef class NumberFieldElement(NumberFieldElement_base):
+             sage: K(1/2).is_integer()
+             False
+         """
+-        return ZZX_deg(self.__numerator) <= 0 and ZZ_IsOne(self.__denominator) == 1
++        return ZZX_deg(self._numerator) <= 0 and ZZ_IsOne(self._denominator) == 1
+ 
+     def trace(self, K=None):
+         r"""
+@@ -5322,8 +5322,8 @@ cdef class OrderElement_absolute(NumberFieldElement_absolute):
+         cdef OrderElement_absolute x = <OrderElement_absolute>t.__new__(t)
+         x._parent = self._parent
+         x._number_field = self._parent.number_field()
+-        x.__fld_numerator = self.__fld_numerator
+-        x.__fld_denominator = self.__fld_denominator
++        x._fld_numerator = self._fld_numerator
++        x._fld_denominator = self._fld_denominator
+         return x
+ 
+     cdef number_field(self):
+@@ -5443,8 +5443,8 @@ cdef class OrderElement_relative(NumberFieldElement_relative):
+         cdef OrderElement_relative x = <OrderElement_relative>t.__new__(t)
+         x._parent = self._parent
+         x._number_field = self._parent.number_field()
+-        x.__fld_numerator = self.__fld_numerator
+-        x.__fld_denominator = self.__fld_denominator
++        x._fld_numerator = self._fld_numerator
++        x._fld_denominator = self._fld_denominator
+         return x
+ 
+     def __invert__(self):
+diff --git a/src/sage/rings/number_field/number_field_element_quadratic.pyx b/src/sage/rings/number_field/number_field_element_quadratic.pyx
+index 0992e7cd527..c32f6aadd10 100644
+--- a/src/sage/rings/number_field/number_field_element_quadratic.pyx
++++ b/src/sage/rings/number_field/number_field_element_quadratic.pyx
+@@ -610,8 +610,8 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+         mpz_clear(tmp_mpz)
+ 
+         x._parent = <ParentWithBase>new_parent
+-        x.__fld_numerator, x.__fld_denominator = new_parent.polynomial_ntl()
+-        x.__denominator = elt_den
++        x._fld_numerator, x._fld_denominator = new_parent.polynomial_ntl()
++        x._denominator = elt_den
+         cdef ZZX_c result
+         cdef ZZ_c tmp
+         cdef int i
+@@ -621,7 +621,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+         for i from 0 <= i <= ZZX_deg(elt_num):
+             tmp = ZZX_coeff(elt_num, i)
+             ZZX_SetCoeff(result, i*rel, tmp)
+-        ZZX_rem(x.__numerator, result, _num.x)
++        ZZX_rem(x._numerator, result, _num.x)
+         (<NumberFieldElement_absolute>x)._reduce_c_()
+         return x
+ 
+@@ -1643,7 +1643,7 @@ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+         return res
+ 
+ #################################################################################
+-# We must override everything that makes uses of self.__numerator/__denominator
++# We must override everything that makes uses of self._numerator/_denominator
+ #################################################################################
+ 
+     def __hash__(self):
+diff --git a/src/sage/rings/padics/CA_template.pxi b/src/sage/rings/padics/CA_template.pxi
+index a0a66c19621..d821b5c1576 100644
+--- a/src/sage/rings/padics/CA_template.pxi
++++ b/src/sage/rings/padics/CA_template.pxi
+@@ -1463,7 +1463,7 @@ cdef class pAdicCoercion_CA_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         ans._normalize()
+         return ans
+ 
+@@ -1516,7 +1516,7 @@ cdef class pAdicCoercion_CA_frac_field(RingHomomorphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+             pass
+         return ans
+ 
+@@ -1686,7 +1686,7 @@ cdef class pAdicConvert_CA_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 R = ans.value.base_ring()
+-                ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++                ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1741,7 +1741,7 @@ cdef class pAdicConvert_CA_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 R = ans.value.base_ring()
+-                ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++                ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/CR_template.pxi b/src/sage/rings/padics/CR_template.pxi
+index cb57bb2cb48..863c612587c 100644
+--- a/src/sage/rings/padics/CR_template.pxi
++++ b/src/sage/rings/padics/CR_template.pxi
+@@ -2184,7 +2184,7 @@ cdef class pAdicCoercion_CR_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -2241,7 +2241,7 @@ cdef class pAdicCoercion_CR_frac_field(RingHomomorphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     def section(self):
+@@ -2404,7 +2404,7 @@ cdef class pAdicConvert_CR_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -2463,7 +2463,7 @@ cdef class pAdicConvert_CR_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/FM_template.pxi b/src/sage/rings/padics/FM_template.pxi
+index ea7d4055660..f47200074ea 100644
+--- a/src/sage/rings/padics/FM_template.pxi
++++ b/src/sage/rings/padics/FM_template.pxi
+@@ -1227,7 +1227,7 @@ cdef class pAdicCoercion_FM_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1277,7 +1277,7 @@ cdef class pAdicCoercion_FM_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     def section(self):
+@@ -1435,7 +1435,7 @@ cdef class pAdicConvert_FM_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             R = ans.value.base_ring()
+-            ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++            ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1483,7 +1483,7 @@ cdef class pAdicConvert_FM_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             R = ans.value.base_ring()
+-            ans.value.__coeffs = [R(c) for c in ans.value.__coeffs]
++            ans.value._coeffs = [R(c) for c in ans.value._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/FP_template.pxi b/src/sage/rings/padics/FP_template.pxi
+index 57ec619b278..c718c0a5f8d 100644
+--- a/src/sage/rings/padics/FP_template.pxi
++++ b/src/sage/rings/padics/FP_template.pxi
+@@ -1849,7 +1849,7 @@ cdef class pAdicCoercion_FP_frac_field(RingHomomorphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -1903,7 +1903,7 @@ cdef class pAdicCoercion_FP_frac_field(RingHomomorphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     def section(self):
+@@ -2025,7 +2025,7 @@ cdef class pAdicConvert_FP_frac_field(Morphism):
+         IF CELEMENT_IS_PY_OBJECT:
+             # The base ring is wrong, so we fix it.
+             K = ans.unit.base_ring()
+-            ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++            ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cpdef Element _call_with_args(self, _x, args=(), kwds={}):
+@@ -2081,7 +2081,7 @@ cdef class pAdicConvert_FP_frac_field(Morphism):
+             IF CELEMENT_IS_PY_OBJECT:
+                 # The base ring is wrong, so we fix it.
+                 K = ans.unit.base_ring()
+-                ans.unit.__coeffs = [K(c) for c in ans.unit.__coeffs]
++                ans.unit._coeffs = [K(c) for c in ans.unit._coeffs]
+         return ans
+ 
+     cdef dict _extra_slots(self):
+diff --git a/src/sage/rings/padics/pow_computer.pxd b/src/sage/rings/padics/pow_computer.pxd
+index 2a93e42254e..8766725882e 100644
+--- a/src/sage/rings/padics/pow_computer.pxd
++++ b/src/sage/rings/padics/pow_computer.pxd
+@@ -6,7 +6,7 @@ cdef class PowComputer_class(SageObject):
+     cdef Integer prime
+     cdef Integer p2 # floor(p/2)
+     cdef bint in_field
+-    cdef int __allocated
++    cdef int _allocated
+     cdef public object _prec_type
+ 
+     cdef long ram_prec_cap # = prec_cap * e
+diff --git a/src/sage/rings/padics/pow_computer.pyx b/src/sage/rings/padics/pow_computer.pyx
+index c2fa8031086..1c5bdf86897 100644
+--- a/src/sage/rings/padics/pow_computer.pyx
++++ b/src/sage/rings/padics/pow_computer.pyx
+@@ -65,7 +65,7 @@ cdef class PowComputer_class(SageObject):
+         sig_on()
+         mpz_init(self.temp_m)
+         sig_off()
+-        self.__allocated = 1
++        self._allocated = 1
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly=None, shift_seed=None):
+         """
+@@ -485,7 +485,7 @@ cdef class PowComputer_base(PowComputer_class):
+         finally:
+             sig_off()
+ 
+-        self.__allocated = 2
++        self._allocated = 2
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly=None, shift_seed=None):
+         """
+@@ -529,7 +529,7 @@ cdef class PowComputer_base(PowComputer_class):
+         """
+         cdef Py_ssize_t i
+ 
+-        if self.__allocated >= 2:
++        if self._allocated >= 2:
+             for i in range(self.cache_limit + 1):
+                 mpz_clear(self.small_powers[i])
+             mpz_clear(self.top_power)
+diff --git a/src/sage/rings/padics/pow_computer_flint.pyx b/src/sage/rings/padics/pow_computer_flint.pyx
+index 9f914defcc6..e521ea6e078 100644
+--- a/src/sage/rings/padics/pow_computer_flint.pyx
++++ b/src/sage/rings/padics/pow_computer_flint.pyx
+@@ -59,7 +59,7 @@ cdef class PowComputer_flint(PowComputer_class):
+         finally:
+             sig_off()
+ 
+-        self.__allocated = 4
++        self._allocated = 4
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly=None, shift_seed=None):
+         """
+@@ -87,7 +87,7 @@ cdef class PowComputer_flint(PowComputer_class):
+             sage: A = PowComputer_flint(5, 20, 20, 20, False)
+             sage: del A
+         """
+-        if self.__allocated >= 4:
++        if self._allocated >= 4:
+             fmpz_clear(self.fprime)
+             fmpz_clear(self.half_prime)
+             fmpz_clear(self._fpow_variable)
+@@ -208,7 +208,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+ 
+         """
+         cdef Polynomial_integer_dense_flint poly = _poly
+-        cdef long length = fmpz_poly_length(poly.__poly)
++        cdef long length = fmpz_poly_length(poly._poly)
+ 
+         cdef Py_ssize_t i
+ 
+@@ -251,7 +251,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         finally:
+             sig_off()
+ 
+-        self.__allocated = 8
++        self._allocated = 8
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, _poly, shift_seed=None):
+         """
+@@ -268,10 +268,10 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         PowComputer_flint.__init__(self, prime, cache_limit, prec_cap, ram_prec_cap, in_field, _poly, shift_seed)
+ 
+         cdef Polynomial_integer_dense_flint poly = _poly
+-        cdef long length = fmpz_poly_length(poly.__poly)
++        cdef long length = fmpz_poly_length(poly._poly)
+         self.deg = length - 1
+ 
+-        fmpz_poly_set(self.modulus, poly.__poly)
++        fmpz_poly_set(self.modulus, poly._poly)
+ 
+         cdef Py_ssize_t i
+         cdef fmpz* coeffs = self.modulus.coeffs
+@@ -296,7 +296,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         """
+         cdef Py_ssize_t i
+ 
+-        if self.__allocated >= 8:
++        if self._allocated >= 8:
+             fmpz_clear(self.q)
+             fmpz_poly_clear(self.modulus)
+             fmpz_poly_clear(self.powhelper_oneunit)
+@@ -427,9 +427,9 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         x = R.gen()
+         cdef Polynomial_integer_dense_flint ans = (<Polynomial_integer_dense_flint?>x)._new()
+         if _n is None:
+-            fmpz_poly_set(ans.__poly, self.modulus)
++            fmpz_poly_set(ans._poly, self.modulus)
+         else:
+-            fmpz_poly_set(ans.__poly, self.get_modulus(_n)[0])
++            fmpz_poly_set(ans._poly, self.get_modulus(_n)[0])
+         return ans
+ 
+     cdef _new_fmpz_poly(self, fmpz_poly_t value, var='x'):
+@@ -440,7 +440,7 @@ cdef class PowComputer_flint_1step(PowComputer_flint):
+         R = ZZ[var]
+         x = R.gen()
+         cdef Polynomial_integer_dense_flint ans = (<Polynomial_integer_dense_flint?>x)._new()
+-        fmpz_poly_set(ans.__poly, value)
++        fmpz_poly_set(ans._poly, value)
+         return ans
+ 
+ cdef class PowComputer_flint_unram(PowComputer_flint_1step):
+@@ -501,7 +501,7 @@ cdef class PowComputer_flint_unram(PowComputer_flint_1step):
+         mpz_init(self.mpz_matmod)
+         sig_off()
+ 
+-        self.__allocated = 16
++        self._allocated = 16
+ 
+     def __dealloc__(self):
+         """
+@@ -515,7 +515,7 @@ cdef class PowComputer_flint_unram(PowComputer_flint_1step):
+             sage: del A
+ 
+         """
+-        if self.__allocated >= 16:
++        if self._allocated >= 16:
+             fmpz_clear(self.fmpz_ccmp)
+             fmpz_clear(self.fmpz_cval)
+             fmpz_clear(self.fmpz_cinv)
+diff --git a/src/sage/rings/padics/pow_computer_relative.pxd b/src/sage/rings/padics/pow_computer_relative.pxd
+index fc7d5b21f42..e0e5aa5600e 100644
+--- a/src/sage/rings/padics/pow_computer_relative.pxd
++++ b/src/sage/rings/padics/pow_computer_relative.pxd
+@@ -18,7 +18,7 @@ cdef class PowComputer_relative(PowComputer_class):
+     cdef Polynomial_generic_dense shift_rem
+     cdef Polynomial_generic_dense aliasing
+     # allow cached methods
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+     cdef unsigned long capdiv(self, unsigned long n)
+ 
+diff --git a/src/sage/rings/padics/pow_computer_relative.pyx b/src/sage/rings/padics/pow_computer_relative.pyx
+index 39051a681de..2253281bd35 100644
+--- a/src/sage/rings/padics/pow_computer_relative.pyx
++++ b/src/sage/rings/padics/pow_computer_relative.pyx
+@@ -69,7 +69,7 @@ cdef class PowComputer_relative(PowComputer_class):
+             sage: PC = PowComputer_relative_maker(3, 20, 20, 60, False, f, shift_seed, 'fixed-mod')
+ 
+         """
+-        self.__allocated = 4
++        self._allocated = 4
+ 
+     def __init__(self, Integer prime, long cache_limit, long prec_cap, long ram_prec_cap, bint in_field, poly, shift_seed):
+         r"""
+diff --git a/src/sage/rings/polynomial/hilbert.pyx b/src/sage/rings/polynomial/hilbert.pyx
+index a1f70e0c983..d2abf325fd8 100644
+--- a/src/sage/rings/polynomial/hilbert.pyx
++++ b/src/sage/rings/polynomial/hilbert.pyx
+@@ -170,7 +170,7 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+     cdef int e
+     # First, the easiest cases:
+     if not D.Id: # The zero ideal
+-        fmpz_poly_set_coeff_si(fhs.__poly, 0, 1) # = PR(1)
++        fmpz_poly_set_coeff_si(fhs._poly, 0, 1) # = PR(1)
+         return True
+     cdef ETuple m = <ETuple>PyList_GET_ITEM(D.Id, len(D.Id)-1)
+     if m._nonzero == 0: # The one ideal
+@@ -183,18 +183,18 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+     if m._nonzero == 1 and m._data[1] == 1:
+         fmpz_poly_init(poly_tmp)
+         fmpz_poly_set_coeff_si(poly_tmp, 0, 1)
+-        fmpz_poly_set_coeff_si(fhs.__poly, 0, 1) # = PR(1)
++        fmpz_poly_set_coeff_si(fhs._poly, 0, 1) # = PR(1)
+         if w is None:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).unweighted_degree()
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         else:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).weighted_degree(w)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         fmpz_poly_clear(poly_tmp)
+         return True # PR.prod([(1-t**degree(m,w)) for m in D.Id])
+@@ -210,18 +210,18 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+         # The ideal is generated by some powers of single variables, i.e., it splits.
+         fmpz_poly_init(poly_tmp)
+         fmpz_poly_set_coeff_si(poly_tmp, 0, 1)
+-        fmpz_poly_set_coeff_si(fhs.__poly, 0, 1) # = PR(1)
++        fmpz_poly_set_coeff_si(fhs._poly, 0, 1) # = PR(1)
+         if w is None:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).unweighted_degree()
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         else:
+             for i in range(len(D.Id)):
+                 exp = (<ETuple>PyList_GET_ITEM(D.Id, i)).weighted_degree(w)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, -1)
+-                fmpz_poly_mul(fhs.__poly, fhs.__poly, poly_tmp)
++                fmpz_poly_mul(fhs._poly, fhs._poly, poly_tmp)
+                 fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         fmpz_poly_clear(poly_tmp)
+         return True # PR.prod([(1-t**degree(m,w)) for m in D.Id])
+@@ -278,8 +278,8 @@ cdef bint HilbertBaseCase(Polynomial_integer_dense_flint fhs, Node D, tuple w):
+                     fmpz_poly_mul(SecondSummand, SecondSummand, poly_tmp)
+                     fmpz_poly_set_coeff_si(poly_tmp, exp, 0)
+         fmpz_poly_clear(poly_tmp)
+-        fmpz_poly_add(fhs.__poly, fhs.__poly, FirstSummand)
+-        fmpz_poly_add(fhs.__poly, fhs.__poly, SecondSummand)
++        fmpz_poly_add(fhs._poly, fhs._poly, FirstSummand)
++        fmpz_poly_add(fhs._poly, fhs._poly, SecondSummand)
+         fmpz_poly_clear(FirstSummand)
+         fmpz_poly_clear(SecondSummand)
+         return True
+@@ -532,11 +532,11 @@ def first_hilbert_series(I, grading=None, return_grading=False):
+                 if AN.Back.Right is None:
+                     AN = AN.Back
+                     #~ fhs *= AN.LMult
+-                    fmpz_poly_mul(fhs.__poly, fhs.__poly, AN.LMult)
++                    fmpz_poly_mul(fhs._poly, fhs._poly, AN.LMult)
+                     got_result = True
+                 else:
+-                    fmpz_poly_set(AN.Back.LeftFHS, fhs.__poly)
+-                    fmpz_poly_set_si(fhs.__poly, 0)
++                    fmpz_poly_set(AN.Back.LeftFHS, fhs._poly)
++                    fmpz_poly_set_si(fhs._poly, 0)
+                     AN = AN.Back.Right
+                     AN.Back.Left = None
+                     got_result = HilbertBaseCase(fhs, AN, w)
+@@ -545,8 +545,8 @@ def first_hilbert_series(I, grading=None, return_grading=False):
+                 AN.Right = None
+                 #~ fhs = AN.LMult*AN.LeftFHS + AN.RMult*fhs
+                 fmpz_poly_mul(AN.LMult, AN.LMult, AN.LeftFHS)
+-                fmpz_poly_mul(AN.RMult, AN.RMult, fhs.__poly)
+-                fmpz_poly_add(fhs.__poly, AN.LMult, AN.RMult)
++                fmpz_poly_mul(AN.RMult, AN.RMult, fhs._poly)
++                fmpz_poly_add(fhs._poly, AN.LMult, AN.RMult)
+                 got_result = True
+ 
+ def hilbert_poincare_series(I, grading=None):
+diff --git a/src/sage/rings/polynomial/laurent_polynomial.pxd b/src/sage/rings/polynomial/laurent_polynomial.pxd
+index 3648d6d1ed1..8e9107aeb47 100644
+--- a/src/sage/rings/polynomial/laurent_polynomial.pxd
++++ b/src/sage/rings/polynomial/laurent_polynomial.pxd
+@@ -12,6 +12,6 @@ cdef class LaurentPolynomial(CommutativeAlgebraElement):
+ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+     cdef ModuleElement __u
+     cdef long __n
+-    cpdef __normalize(self)
++    cpdef _normalize(self)
+     cpdef _unsafe_mutate(self, i, value)
+ 
+diff --git a/src/sage/rings/polynomial/laurent_polynomial.pyx b/src/sage/rings/polynomial/laurent_polynomial.pyx
+index 4be246c6688..cd79996eed7 100644
+--- a/src/sage/rings/polynomial/laurent_polynomial.pyx
++++ b/src/sage/rings/polynomial/laurent_polynomial.pyx
+@@ -366,7 +366,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         # self is that t^n * u:
+         self.__u = f
+         self.__n = n
+-        self.__normalize()
++        self._normalize()
+ 
+     def __reduce__(self):
+         """
+@@ -531,7 +531,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+             u = u.map_coefficients(base_map)
+         return codomain(u(x) * x**self.__n)
+ 
+-    cpdef __normalize(self):
++    cpdef _normalize(self):
+         r"""
+         A Laurent series is a pair `(u(t), n)`, where either `u = 0`
+         (to some precision) or `u` is a unit. This pair corresponds to
+@@ -763,7 +763,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+             ret = <LaurentPolynomial_univariate> self._new_c()
+             ret.__u = f
+             ret.__n = self.__n
+-            ret.__normalize()
++            ret._normalize()
+             return ret
+ 
+         return self.__u[i - self.__n]
+@@ -919,7 +919,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+                 R = self._parent.base_ring()
+                 coeffs = [value] + [R.zero() for _ in range(1,-j)] + self.__u.list()
+                 self.__u = self.__u._parent(coeffs)
+-        self.__normalize()
++        self._normalize()
+ 
+     cpdef _add_(self, right_m):
+         """
+@@ -972,7 +972,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (f1 + f2)
+         ret.__n = m
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     cpdef _sub_(self, right_m):
+@@ -1012,7 +1012,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (f1 - f2)
+         ret.__n = m
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def degree(self):
+@@ -1063,7 +1063,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (self.__u * right.__u)
+         ret.__n = self.__n + right.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     cpdef _rmul_(self, Element c):
+@@ -1079,7 +1079,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self.__u._rmul_(c)
+         ret.__n = self.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     cpdef _lmul_(self, Element c):
+@@ -1095,7 +1095,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self.__u._lmul_(c)
+         ret.__n = self.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def is_monomial(self):
+@@ -1175,7 +1175,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> (self.__u // right.__u)
+         ret.__n = self.__n - right.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def shift(self, k):
+@@ -1287,7 +1287,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+             if self.__u.is_unit():
+                 ret.__u = self.__u.inverse_of_unit()
+                 ret.__n = -self.__n
+-                ret.__normalize()
++                ret._normalize()
+                 return ret
+             # Enlarge the ring so we can divide by the coefficient
+             R = self._parent.base_ring().fraction_field()
+@@ -1362,7 +1362,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = self.__u.gcd(b.__u)
+         ret.__n = min(self.__n, b.__n)
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     @coerce_binop
+@@ -1408,11 +1408,11 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ql = <LaurentPolynomial_univariate> self._new_c()
+         ql.__u = <ModuleElement> q
+         ql.__n = self.__n - right.__n
+-        ql.__normalize()
++        ql._normalize()
+         qr = <LaurentPolynomial_univariate> self._new_c()
+         qr.__u = <ModuleElement> r
+         qr.__n = self.__n
+-        qr.__normalize()
++        qr._normalize()
+         return ql, qr
+ 
+     cpdef _richcmp_(self, right_r, int op):
+@@ -1519,7 +1519,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self.__u.truncate(n - self.__n)
+         ret.__n = self.__n
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def variable_name(self):
+@@ -1777,7 +1777,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+                 ret = <LaurentPolynomial_univariate> self._new_c()
+                 ret.__u = <ModuleElement> self._parent._R(u)
+                 ret.__n = self.__n
+-                ret.__normalize()
++                ret._normalize()
+                 return ret
+             except AttributeError:
+                 raise ValueError('cannot differentiate with respect to {}'.format(var))
+@@ -1792,7 +1792,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> self._parent._R(a)
+         ret.__n = self.__n - 1
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def integral(self):
+@@ -1857,7 +1857,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         ret = <LaurentPolynomial_univariate> self._new_c()
+         ret.__u = <ModuleElement> u
+         ret.__n = n + 1
+-        ret.__normalize()
++        ret._normalize()
+         return ret
+ 
+     def __call__(self, *x, **kwds):
+@@ -1919,14 +1919,14 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial):
+         u = <LaurentPolynomial_univariate> self._new_c()
+         u.__u = pf.unit()
+         u.__n = self.__n
+-        u.__normalize()
++        u._normalize()
+ 
+         f = []
+         for t in pf:
+             d = <LaurentPolynomial_univariate> self._new_c()
+             d.__u = t[0]
+             d.__n = 0
+-            d.__normalize()
++            d._normalize()
+             if d.is_unit():
+                 u *= d ** t[1]
+             else:
+diff --git a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx
+index d796b7f8169..83c79c39843 100644
+--- a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx
++++ b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx
+@@ -375,7 +375,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+             ...
+             NotImplementedError: polynomials in -1 variables are not supported in Singular
+         """
+-        self.__ngens = n
++        self._ngens = n
+         self._ring = singular_ring_new(base_ring, n, names, order)
+         self._zero_element = new_MP(self, NULL)
+         cdef MPolynomial_libsingular one = new_MP(self, p_ISet(1, self._ring))
+@@ -1019,7 +1019,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+             Multivariate Polynomial Ring in x, y over Rational Field
+         """
+         varstr = ", ".join(char_to_str(rRingVar(i,self._ring))
+-                           for i in range(self.__ngens))
++                           for i in range(self._ngens))
+         return "Multivariate Polynomial Ring in %s over %s" % (varstr, self.base_ring())
+ 
+     def ngens(self):
+@@ -1037,7 +1037,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+             sage: P.ngens()                                                             # needs sage.rings.finite_rings
+             1000
+         """
+-        return int(self.__ngens)
++        return int(self._ngens)
+ 
+     def gen(self, int n=0):
+         """
+@@ -1065,7 +1065,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+         cdef poly *_p
+         cdef ring *_ring = self._ring
+ 
+-        if n < 0 or n >= self.__ngens:
++        if n < 0 or n >= self._ngens:
+             raise ValueError("Generator not defined.")
+ 
+         rChangeCurrRing(_ring)
+@@ -1494,7 +1494,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
+         return unpickle_MPolynomialRing_libsingular, \
+             (self.base_ring(), self.variable_names(), self.term_order())
+ 
+-    def __temporarily_change_names(self, names, latex_names):
++    def _temporarily_change_names(self, names, latex_names):
+         """
+         This is used by the variable names context manager.
+ 
+diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd b/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd
+index fc81cf6d298..eb6f8b70917 100644
+--- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd
++++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pxd
+@@ -2,8 +2,8 @@ cimport sage.rings.ring
+ from sage.structure.parent cimport Parent
+ 
+ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+-    cdef object __ngens
+-    cdef object __term_order
++    cdef object _ngens
++    cdef object _term_order
+     cdef public object _has_singular
+     cdef public object _magma_gens
+     cdef public dict _magma_cache
+diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx
+index 1d3fbc60944..c8f66508cc2 100644
+--- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx
++++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx
+@@ -80,8 +80,8 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+             raise ValueError("Multivariate Polynomial Rings must "
+                              "have more than 0 variables.")
+         order = TermOrder(order, n)
+-        self.__ngens = n
+-        self.__term_order = order
++        self._ngens = n
++        self._term_order = order
+         self._has_singular = False  # cannot convert to Singular by default
+         self._magma_cache = {}
+         # Ring.__init__ already does assign the names.
+@@ -639,12 +639,12 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         lft = <MPolynomialRing_base>left
+         other = <MPolynomialRing_base>right
+ 
+-        lx = (lft.base_ring(), lft.__ngens,
++        lx = (lft.base_ring(), lft._ngens,
+               lft.variable_names(),
+-              lft.__term_order)
+-        rx = (other.base_ring(), other.__ngens,
++              lft._term_order)
++        rx = (other.base_ring(), other._ngens,
+               other.variable_names(),
+-              other.__term_order)
++              other._term_order)
+         return richcmp(lx, rx, op)
+ 
+     def _repr_(self):
+@@ -849,7 +849,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         return False
+ 
+     def term_order(self):
+-        return self.__term_order
++        return self._term_order
+ 
+     def characteristic(self):
+         """
+@@ -867,7 +867,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         return self.base_ring().characteristic()
+ 
+     def gen(self, n=0):
+-        if n < 0 or n >= self.__ngens:
++        if n < 0 or n >= self._ngens:
+             raise ValueError("Generator not defined.")
+         return self._gens[int(n)]
+ 
+@@ -927,7 +927,7 @@ cdef class MPolynomialRing_base(sage.rings.ring.CommutativeRing):
+         return self.base_ring().krull_dimension() + self.ngens()
+ 
+     def ngens(self):
+-        return self.__ngens
++        return self._ngens
+ 
+     def _monomial_order_function(self):
+         raise NotImplementedError
+diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pxd b/src/sage/rings/polynomial/ore_polynomial_element.pxd
+index 3a3fe0a0d54..aa36112ab90 100644
+--- a/src/sage/rings/polynomial/ore_polynomial_element.pxd
++++ b/src/sage/rings/polynomial/ore_polynomial_element.pxd
+@@ -33,7 +33,7 @@ cdef void lmul_gen(list A, Morphism m, d)
+ cdef class OrePolynomial_generic_dense(OrePolynomial):
+     cdef list _coeffs
+ 
+-    cdef void __normalize(self)
++    cdef void _normalize(self)
+     cpdef _add_(self, other)
+     cdef list _mul_list(self, list A)
+     cpdef _mul_(self, other)
+diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pyx b/src/sage/rings/polynomial/ore_polynomial_element.pyx
+index d67c63b6be8..be154ba8b1a 100644
+--- a/src/sage/rings/polynomial/ore_polynomial_element.pyx
++++ b/src/sage/rings/polynomial/ore_polynomial_element.pyx
+@@ -2269,7 +2269,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+         if isinstance(x, list):
+             if check:
+                 self._coeffs = [R(t) for t in x]
+-                self.__normalize()
++                self._normalize()
+             else:
+                 self._coeffs = x
+             return
+@@ -2288,7 +2288,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+             else:
+                 self._coeffs = [R(a, **kwds) for a in x.list()]
+                 if check:
+-                    self.__normalize()
++                    self._normalize()
+                 return
+ 
+         elif isinstance(x, int) and x == 0:
+@@ -2302,7 +2302,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+             x = [x]
+         if check:
+             self._coeffs = [R(z, **kwds) for z in x]
+-            self.__normalize()
++            self._normalize()
+         else:
+             self._coeffs = x
+ 
+@@ -2377,10 +2377,10 @@ cdef class OrePolynomial_generic_dense(OrePolynomial):
+         f._parent = P
+         f._coeffs = coeffs
+         if check:
+-            f.__normalize()
++            f._normalize()
+         return f
+ 
+-    cdef void __normalize(self):
++    cdef void _normalize(self):
+         r"""
+         Remove higher order `0`-coefficients from the representation of ``self``.
+ 
+diff --git a/src/sage/rings/polynomial/pbori/pbori.pyx b/src/sage/rings/polynomial/pbori/pbori.pyx
+index 07cc696477a..314196faa14 100644
+--- a/src/sage/rings/polynomial/pbori/pbori.pyx
++++ b/src/sage/rings/polynomial/pbori/pbori.pyx
+@@ -547,7 +547,7 @@ cdef class BooleanPolynomialRing(BooleanPolynomialRing_base):
+         """
+         return tuple(new_BP_from_PBVar(self,
+                                        self._pbring.variable(self.pbind[i]))
+-                     for i in range(self.__ngens))
++                     for i in range(self._ngens))
+ 
+     def change_ring(self, base_ring=None, names=None, order=None):
+         """
+diff --git a/src/sage/rings/polynomial/plural.pxd b/src/sage/rings/polynomial/plural.pxd
+index 41db2a144e7..d3a46f6aa0d 100644
+--- a/src/sage/rings/polynomial/plural.pxd
++++ b/src/sage/rings/polynomial/plural.pxd
+@@ -13,10 +13,10 @@ cdef extern from *:
+     ctypedef long Py_hash_t
+ 
+ cdef class NCPolynomialRing_plural(Ring):
+-    cdef object __ngens
++    cdef object _ngens
+     cdef object _c
+     cdef object _d
+-    cdef object __term_order
++    cdef object _term_order
+     cdef public object _has_singular
+     cdef public object _magma_gens, _magma_cache
+ 
+diff --git a/src/sage/rings/polynomial/plural.pyx b/src/sage/rings/polynomial/plural.pyx
+index a647d68e08d..bc432611c89 100644
+--- a/src/sage/rings/polynomial/plural.pyx
++++ b/src/sage/rings/polynomial/plural.pyx
+@@ -336,8 +336,8 @@ cdef class NCPolynomialRing_plural(Ring):
+         self._ring = singular_ring_reference(rw._ring)
+         self._ring.ShortOut = 0
+ 
+-        self.__ngens = n
+-        self.__term_order = order
++        self._ngens = n
++        self._term_order = order
+ 
+         Ring.__init__(self, base_ring, names, category=category)
+         self._populate_coercion_lists_()
+@@ -673,7 +673,7 @@ cdef class NCPolynomialRing_plural(Ring):
+             sage: P.term_order()
+             Degree reverse lexicographic term order
+         """
+-        return self.__term_order
++        return self._term_order
+ 
+     def is_commutative(self):
+         """
+@@ -727,7 +727,7 @@ cdef class NCPolynomialRing_plural(Ring):
+         from sage.repl.rich_output.backend_base import BackendBase
+         from sage.repl.display.pretty_print import SagePrettyPrinter
+         varstr = ", ".join(char_to_str(rRingVar(i, self._ring))
+-                           for i in range(self.__ngens))
++                           for i in range(self._ngens))
+         backend = BackendBase()
+         relations = backend._apply_pretty_printer(SagePrettyPrinter,
+                                                   self.relations())
+@@ -830,7 +830,7 @@ cdef class NCPolynomialRing_plural(Ring):
+             sage: P.ngens()
+             3
+         """
+-        return int(self.__ngens)
++        return int(self._ngens)
+ 
+     def gen(self, int n=0):
+         """
+@@ -857,7 +857,7 @@ cdef class NCPolynomialRing_plural(Ring):
+         cdef poly *_p
+         cdef ring *_ring = self._ring
+ 
+-        if n < 0 or n >= self.__ngens:
++        if n < 0 or n >= self._ngens:
+             raise ValueError("Generator not defined.")
+ 
+         rChangeCurrRing(_ring)
+@@ -2352,7 +2352,7 @@ cdef class NCPolynomial_plural(RingElement):
+             except TypeError:
+                 x = (x,)
+ 
+-        if len(x) != (<NCPolynomialRing_plural>self._parent).__ngens:
++        if len(x) != (<NCPolynomialRing_plural>self._parent)._ngens:
+             raise TypeError("x must have length self.ngens()")
+ 
+         m = p_ISet(1,r)
+@@ -2890,8 +2890,8 @@ cpdef MPolynomialRing_libsingular new_CRing(RingWrap rw, base_ring):
+ 
+     self._ring.ShortOut = 0
+ 
+-    self.__ngens = rw.ngens()
+-    self.__term_order =  TermOrder(rw.ordering_string(), force=True)
++    self._ngens = rw.ngens()
++    self._term_order =  TermOrder(rw.ordering_string(), force=True)
+ 
+     ParentWithGens.__init__(self, base_ring, tuple(rw.var_names()),
+                             normalize=False)
+@@ -2962,8 +2962,8 @@ cpdef NCPolynomialRing_plural new_NRing(RingWrap rw, base_ring):
+ 
+     self._ring.ShortOut = 0
+ 
+-    self.__ngens = rw.ngens()
+-    self.__term_order =  TermOrder(rw.ordering_string(), force=True)
++    self._ngens = rw.ngens()
++    self._term_order =  TermOrder(rw.ordering_string(), force=True)
+ 
+     ParentWithGens.__init__(self, base_ring, rw.var_names())
+ #    self._populate_coercion_lists_()  # ???
+diff --git a/src/sage/rings/polynomial/polynomial_complex_arb.pxd b/src/sage/rings/polynomial/polynomial_complex_arb.pxd
+index aa4e2a1c0dc..e54d85e961b 100644
+--- a/src/sage/rings/polynomial/polynomial_complex_arb.pxd
++++ b/src/sage/rings/polynomial/polynomial_complex_arb.pxd
+@@ -2,5 +2,5 @@ from sage.libs.arb.acb_poly cimport *
+ from sage.rings.polynomial.polynomial_element cimport Polynomial
+ 
+ cdef class Polynomial_complex_arb(Polynomial):
+-    cdef acb_poly_struct[1] __poly # https://github.com/cython/cython/issues/1984
++    cdef acb_poly_struct[1] _poly # https://github.com/cython/cython/issues/1984
+     cdef Polynomial_complex_arb _new(self)
+diff --git a/src/sage/rings/polynomial/polynomial_complex_arb.pyx b/src/sage/rings/polynomial/polynomial_complex_arb.pyx
+index e51268b4b54..57c1a52ede4 100644
+--- a/src/sage/rings/polynomial/polynomial_complex_arb.pyx
++++ b/src/sage/rings/polynomial/polynomial_complex_arb.pyx
+@@ -75,7 +75,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: ComplexBallField(2)['y']()
+             0
+         """
+-        acb_poly_init(self.__poly)
++        acb_poly_init(self._poly)
+ 
+     def __dealloc__(self):
+         r"""
+@@ -84,7 +84,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: pol = CBF['x']()
+             sage: del pol
+         """
+-        acb_poly_clear(self.__poly)
++        acb_poly_clear(self._poly)
+ 
+     cdef Polynomial_complex_arb _new(self):
+         r"""
+@@ -140,49 +140,49 @@ cdef class Polynomial_complex_arb(Polynomial):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+ 
+         if is_gen:
+-            acb_poly_set_coeff_si(self.__poly, 1, 1)
++            acb_poly_set_coeff_si(self._poly, 1, 1)
+         elif x is None:
+-            acb_poly_zero(self.__poly)
++            acb_poly_zero(self._poly)
+         elif isinstance(x, Polynomial_complex_arb):
+-            acb_poly_set(self.__poly, (<Polynomial_complex_arb> x).__poly)
++            acb_poly_set(self._poly, (<Polynomial_complex_arb> x)._poly)
+         elif isinstance(x, ComplexBall):
+-            acb_poly_set_coeff_acb(self.__poly, 0, (<ComplexBall> x).value)
++            acb_poly_set_coeff_acb(self._poly, 0, (<ComplexBall> x).value)
+         else:
+             Coeff = parent.base_ring()
+             if isinstance(x, list):
+                 lst = <list> x
+                 length = len(lst)
+-                sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                 for i in range(length):
+                     ball = Coeff(lst[i])
+-                    acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                    acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             elif isinstance(x, tuple):
+                 tpl = <tuple> x
+                 length = len(tpl)
+-                sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                 for i in range(length):
+                     ball = Coeff(tpl[i])
+-                    acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                    acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             elif isinstance(x, Polynomial):
+                 pol = <Polynomial> x
+                 length = pol.degree() + 1
+-                sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                 for i in range(length):
+                     ball = Coeff(pol.get_unsafe(i))
+-                    acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                    acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             elif isinstance(x, dict):
+                 dct = <dict> x
+                 if len(dct) == 0:
+-                    acb_poly_zero(self.__poly)
++                    acb_poly_zero(self._poly)
+                 else:
+                     length = max(int(i) for i in dct) + 1
+-                    sig_on(); acb_poly_fit_length(self.__poly, length); sig_off()
++                    sig_on(); acb_poly_fit_length(self._poly, length); sig_off()
+                     for i, c in dct.iteritems():
+                         ball = Coeff(c)
+-                        acb_poly_set_coeff_acb(self.__poly, i, ball.value)
++                        acb_poly_set_coeff_acb(self._poly, i, ball.value)
+             else:
+                 ball = Coeff(x)
+-                acb_poly_set_coeff_acb(self.__poly, 0, ball.value)
++                acb_poly_set_coeff_acb(self._poly, 0, ball.value)
+ 
+     def __reduce__(self):
+         r"""
+@@ -219,12 +219,12 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: Pol([1, 0, 0, 0]).degree()
+             0
+         """
+-        return smallInteger(acb_poly_degree(self.__poly))
++        return smallInteger(acb_poly_degree(self._poly))
+ 
+     cdef get_unsafe(self, Py_ssize_t n):
+         cdef ComplexBall res = ComplexBall.__new__(ComplexBall)
+         res._parent = self._parent._base
+-        acb_poly_get_coeff_acb(res.value, self.__poly, n)
++        acb_poly_get_coeff_acb(res.value, self._poly, n)
+         return res
+ 
+     cpdef list list(self, bint copy=True):
+@@ -241,7 +241,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: Pol([0, 1, RBF(0, rad=.1), 0]).list()
+             [0, 1.000000000000000, [+/- 0.101]]
+         """
+-        cdef unsigned long length = acb_poly_length(self.__poly)
++        cdef unsigned long length = acb_poly_length(self._poly)
+         return [self.get_unsafe(n) for n in range(length)]
+ 
+     def __bool__(self):
+@@ -257,7 +257,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+             sage: bool(z)
+             True
+         """
+-        return acb_poly_length(self.__poly)
++        return acb_poly_length(self._poly)
+ 
+     # Ring and Euclidean arithmetic
+ 
+@@ -274,9 +274,9 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+         acb_poly_add(
+-                res.__poly,
+-                self.__poly,
+-                (<Polynomial_complex_arb> other).__poly,
++                res._poly,
++                self._poly,
++                (<Polynomial_complex_arb> other)._poly,
+                 prec(self))
+         sig_off()
+         return res
+@@ -293,7 +293,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         """
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_neg(res.__poly, self.__poly)
++        acb_poly_neg(res._poly, self._poly)
+         sig_off()
+         return res
+ 
+@@ -310,9 +310,9 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+         acb_poly_sub(
+-                res.__poly,
+-                self.__poly,
+-                (<Polynomial_complex_arb> other).__poly,
++                res._poly,
++                self._poly,
++                (<Polynomial_complex_arb> other)._poly,
+                 prec(self))
+         sig_off()
+         return res
+@@ -331,9 +331,9 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+         acb_poly_mul(
+-                res.__poly,
+-                self.__poly,
+-                (<Polynomial_complex_arb> other).__poly,
++                res._poly,
++                self._poly,
++                (<Polynomial_complex_arb> other)._poly,
+                 prec(self))
+         sig_off()
+         return res
+@@ -354,7 +354,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         """
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_scalar_mul(res.__poly, self.__poly, (<ComplexBall> a).value, prec(self))
++        acb_poly_scalar_mul(res._poly, self._poly, (<ComplexBall> a).value, prec(self))
+         sig_off()
+         return res
+ 
+@@ -409,8 +409,8 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb quo = self._new()
+         cdef Polynomial_complex_arb rem = self._new()
+         sig_on()
+-        cdef bint success = acb_poly_divrem(quo.__poly, rem.__poly, self.__poly,
+-                div.__poly, prec(self))
++        cdef bint success = acb_poly_divrem(quo._poly, rem._poly, self._poly,
++                div._poly, prec(self))
+         sig_off()
+         if success:
+             return quo, rem
+@@ -445,15 +445,15 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_set(res.__poly, self.__poly)
+-        acb_poly_truncate(res.__poly, n)
++        acb_poly_set(res._poly, self._poly)
++        acb_poly_truncate(res._poly, n)
+         sig_off()
+         return res
+ 
+     cdef _inplace_truncate(self, long n):
+         if n < 0:
+             n = 0
+-        acb_poly_truncate(self.__poly, n)
++        acb_poly_truncate(self._poly, n)
+         return self
+ 
+     def __lshift__(val, n):
+@@ -485,7 +485,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb self = (<Polynomial_complex_arb> val)
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_shift_left(res.__poly, self.__poly, n)
++        acb_poly_shift_left(res._poly, self._poly, n)
+         sig_off()
+         return res
+ 
+@@ -518,7 +518,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb self = (<Polynomial_complex_arb> val)
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_shift_right(res.__poly, self.__poly, n)
++        acb_poly_shift_right(res._poly, self._poly, n)
+         sig_off()
+         return res
+ 
+@@ -548,7 +548,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_mullow(res.__poly, self.__poly, my_other.__poly, n, prec(self))
++        acb_poly_mullow(res._poly, self._poly, my_other._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -576,7 +576,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_inv_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_inv_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -612,7 +612,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_pow_ui_trunc_binexp(res.__poly, self.__poly, expo, n, prec(self))
++        acb_poly_pow_ui_trunc_binexp(res._poly, self._poly, expo, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -648,7 +648,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_log_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_log_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -672,7 +672,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_exp_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_exp_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -697,7 +697,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_sqrt_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_sqrt_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -716,7 +716,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_gamma_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_gamma_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -735,7 +735,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_lgamma_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_lgamma_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -754,7 +754,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_rgamma_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_rgamma_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -784,7 +784,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         if n < 0:
+             n = 0
+         sig_on()
+-        acb_poly_lambertw_series(res.__poly, self.__poly, _branch, 0, n, prec(self))
++        acb_poly_lambertw_series(res._poly, self._poly, _branch, 0, n, prec(self))
+         sig_off()
+         fmpz_clear(_branch)
+         return res
+@@ -814,7 +814,7 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef ComplexBall _a = <ComplexBall> (self._parent._base.coerce(a))
+         cdef Polynomial_complex_arb res = self._new()
+         sig_on()
+-        acb_poly_zeta_series(res.__poly, self.__poly, _a.value, deflate, n, prec(self))
++        acb_poly_zeta_series(res._poly, self._poly, _a.value, deflate, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -846,24 +846,24 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         cdef acb_poly_t self_ts, other_ts
+         cdef acb_ptr cc
+-        if acb_poly_length(other1.__poly) > 0:
+-            cc = acb_poly_get_coeff_ptr(other1.__poly, 0)
++        if acb_poly_length(other1._poly) > 0:
++            cc = acb_poly_get_coeff_ptr(other1._poly, 0)
+             if not acb_is_zero(cc):
+                 sig_on()
+                 try:
+                     acb_poly_init(self_ts)
+                     acb_poly_init(other_ts)
+-                    acb_poly_taylor_shift(self_ts, self.__poly, cc, prec(self))
+-                    acb_poly_set(other_ts, other1.__poly)
++                    acb_poly_taylor_shift(self_ts, self._poly, cc, prec(self))
++                    acb_poly_set(other_ts, other1._poly)
+                     acb_zero(acb_poly_get_coeff_ptr(other_ts, 0))
+-                    acb_poly_compose_series(res.__poly, self_ts, other_ts, n, prec(self))
++                    acb_poly_compose_series(res._poly, self_ts, other_ts, n, prec(self))
+                 finally:
+                     acb_poly_clear(other_ts)
+                     acb_poly_clear(self_ts)
+                     sig_off()
+                 return res
+         sig_on()
+-        acb_poly_compose_series(res.__poly, self.__poly, other1.__poly, n, prec(self))
++        acb_poly_compose_series(res._poly, self._poly, other1._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -895,12 +895,12 @@ cdef class Polynomial_complex_arb(Polynomial):
+         cdef Polynomial_complex_arb res = self._new()
+         if n < 0:
+             n = 0
+-        if not acb_is_zero(acb_poly_get_coeff_ptr(self.__poly, 0)):
++        if not acb_is_zero(acb_poly_get_coeff_ptr(self._poly, 0)):
+             raise ValueError("the constant coefficient must be zero")
+-        if acb_contains_zero(acb_poly_get_coeff_ptr(self.__poly, 1)):
++        if acb_contains_zero(acb_poly_get_coeff_ptr(self._poly, 1)):
+             raise ValueError("the linear term must be nonzero")
+         sig_on()
+-        acb_poly_revert_series(res.__poly, self.__poly, n, prec(self))
++        acb_poly_revert_series(res._poly, self._poly, n, prec(self))
+         sig_off()
+         return res
+ 
+@@ -938,15 +938,15 @@ cdef class Polynomial_complex_arb(Polynomial):
+                 ball = ComplexBall.__new__(ComplexBall)
+                 ball._parent = self._parent._base
+                 sig_on()
+-                acb_poly_evaluate(ball.value, self.__poly,
++                acb_poly_evaluate(ball.value, self._poly,
+                         (<ComplexBall> point).value, prec(self))
+                 sig_off()
+                 return ball
+             elif isinstance(point, Polynomial_complex_arb):
+                 poly = (<Polynomial_complex_arb> point)._new()
+                 sig_on()
+-                acb_poly_compose(poly.__poly, self.__poly,
+-                        (<Polynomial_complex_arb> point).__poly, prec(self))
++                acb_poly_compose(poly._poly, self._poly,
++                        (<Polynomial_complex_arb> point)._poly, prec(self))
+                 sig_off()
+                 return poly
+             # TODO: perhaps add more special cases, e.g. for real ball,
+diff --git a/src/sage/rings/polynomial/polynomial_element.pxd b/src/sage/rings/polynomial/polynomial_element.pxd
+index 083f506b222..5dcbf4597d0 100644
+--- a/src/sage/rings/polynomial/polynomial_element.pxd
++++ b/src/sage/rings/polynomial/polynomial_element.pxd
+@@ -45,12 +45,12 @@ cdef class Polynomial(CommutativePolynomial):
+     cpdef _mul_(self, right)
+     cpdef _floordiv_(self, right)
+ 
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+ cdef class Polynomial_generic_dense(Polynomial):
+     cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P)
+-    cdef list __coeffs
+-    cdef int __normalize(self) except -1
++    cdef list _coeffs
++    cdef int _normalize(self) except -1
+     cpdef list list(self, bint copy=*)
+ 
+ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+diff --git a/src/sage/rings/polynomial/polynomial_element.pyx b/src/sage/rings/polynomial/polynomial_element.pyx
+index 4d4b9dd10f5..d1c802835ae 100644
+--- a/src/sage/rings/polynomial/polynomial_element.pyx
++++ b/src/sage/rings/polynomial/polynomial_element.pyx
+@@ -9800,7 +9800,7 @@ cdef class Polynomial(CommutativePolynomial):
+             0
+         """
+         # __getitem__ already returns a polynomial!!
+-        # We must not have check=False, since 0 must not have __coeffs = [0].
++        # We must not have check=False, since 0 must not have _coeffs = [0].
+         return <Polynomial>self._parent(self[:n])#, check=False)
+ 
+     cdef _inplace_truncate(self, long prec):
+@@ -11541,16 +11541,16 @@ cdef class Polynomial_generic_dense(Polynomial):
+     def __init__(self, parent, x=None, int check=1, is_gen=False, int construct=0, **kwds):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+         if x is None:
+-            self.__coeffs = []
++            self._coeffs = []
+             return
+ 
+         R = parent.base_ring()
+         if isinstance(x, (list, tuple)):
+             if check:
+-                self.__coeffs = [R(t) for t in x]
+-                self.__normalize()
++                self._coeffs = [R(t) for t in x]
++                self._normalize()
+             else:
+-                self.__coeffs = x
++                self._coeffs = x
+             return
+ 
+         if sage.rings.fraction_field_element.is_FractionFieldElement(x):
+@@ -11565,19 +11565,19 @@ cdef class Polynomial_generic_dense(Polynomial):
+             elif R.has_coerce_map_from((<Element>x)._parent):# is R or (<Element>x)._parent == R:
+                 try:
+                     if x.is_zero():
+-                        self.__coeffs = []
++                        self._coeffs = []
+                         return
+                 except (AttributeError, TypeError):
+                     pass
+                 x = [x]
+             else:
+-                self.__coeffs = [R(a, **kwds) for a in x.list(copy=False)]
++                self._coeffs = [R(a, **kwds) for a in x.list(copy=False)]
+                 if check:
+-                    self.__normalize()
++                    self._normalize()
+                 return
+ 
+         elif isinstance(x, int) and x == 0:
+-            self.__coeffs = []
++            self._coeffs = []
+             return
+ 
+         elif isinstance(x, dict):
+@@ -11593,16 +11593,16 @@ cdef class Polynomial_generic_dense(Polynomial):
+ #            else:
+ #                x = []    # zero polynomial
+         if check:
+-            self.__coeffs = [R(z, **kwds) for z in x]
+-            self.__normalize()
++            self._coeffs = [R(z, **kwds) for z in x]
++            self._normalize()
+         else:
+-            self.__coeffs = x
++            self._coeffs = x
+ 
+     cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P):
+         cdef type t = type(self)
+         cdef Polynomial_generic_dense f = <Polynomial_generic_dense>t.__new__(t)
+         f._parent = P
+-        f.__coeffs = coeffs
++        f._coeffs = coeffs
+         return f
+ 
+     cpdef Polynomial _new_constant_poly(self, a, Parent P):
+@@ -11644,10 +11644,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: type(f)
+             <class 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense'>
+         """
+-        return make_generic_polynomial, (self._parent, self.__coeffs)
++        return make_generic_polynomial, (self._parent, self._coeffs)
+ 
+     def __bool__(self):
+-        return bool(self.__coeffs)
++        return bool(self._coeffs)
+ 
+     cpdef bint is_term(self) except -1:
+         """
+@@ -11667,10 +11667,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: (1 + 3*x^5).is_term()
+             False
+         """
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return False
+ 
+-        for c in self.__coeffs[:-1]:
++        for c in self._coeffs[:-1]:
+             if c:
+                 return False
+         return True
+@@ -11682,9 +11682,9 @@ cdef class Polynomial_generic_dense(Polynomial):
+         Return the product ``self * term``, where ``term`` is a polynomial
+         with a single term.
+         """
+-        cdef Py_ssize_t d = len( (<Polynomial_generic_dense> term).__coeffs ) - 1
++        cdef Py_ssize_t d = len( (<Polynomial_generic_dense> term)._coeffs ) - 1
+         cdef Py_ssize_t i
+-        cdef list x = self.__coeffs
++        cdef list x = self._coeffs
+         cdef Py_ssize_t ell = len(x)
+         c = term.get_unsafe(d)
+         cdef list v = [self.base_ring().zero()] * (d + ell)
+@@ -11697,10 +11697,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+         cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
+         #if not v[len(v)-1]:
+         # "normalize" checks this anyway...
+-        res.__normalize()
++        res._normalize()
+         return res
+ 
+-    cdef int __normalize(self) except -1:
++    cdef int _normalize(self) except -1:
+         """
+         TESTS:
+ 
+@@ -11718,7 +11718,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+             ...
+             NotImplementedError: cannot check whether number is non-zero
+         """
+-        cdef list x = self.__coeffs
++        cdef list x = self._coeffs
+         cdef Py_ssize_t n = len(x) - 1
+         while n >= 0 and not x[n]:
+             del x[n]
+@@ -11747,7 +11747,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: f[:3]
+             40.0*x^2 + 10.0*x + 1.0
+         """
+-        return self.__coeffs[n]
++        return self._coeffs[n]
+ 
+     def _unsafe_mutate(self, n, value):
+         """
+@@ -11770,17 +11770,17 @@ cdef class Polynomial_generic_dense(Polynomial):
+         """
+         n = int(n)
+         value = self.base_ring()(value)
+-        if n >= 0 and n < len(self.__coeffs):
+-            self.__coeffs[n] = value
+-            if n == len(self.__coeffs) and value == 0:
+-                self.__normalize()
++        if n >= 0 and n < len(self._coeffs):
++            self._coeffs[n] = value
++            if n == len(self._coeffs) and value == 0:
++                self._normalize()
+         elif n < 0:
+             raise IndexError("polynomial coefficient index must be nonnegative")
+         elif value != 0:
+             zero = self.base_ring().zero()
+-            for _ in range(len(self.__coeffs), n):
+-                self.__coeffs.append(zero)
+-            self.__coeffs.append(value)
++            for _ in range(len(self._coeffs), n):
++                self._coeffs.append(zero)
++            self._coeffs.append(value)
+ 
+     def __floordiv__(self, right):
+         """
+@@ -11822,8 +11822,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+             return (<Polynomial_generic_dense>self)._floordiv_(<Polynomial_generic_dense>right)
+         P = parent(self)
+         d = P.base_ring()(right)
+-        cdef Polynomial_generic_dense res = (<Polynomial_generic_dense>self)._new_c([c // d for c in (<Polynomial_generic_dense>self).__coeffs], P)
+-        res.__normalize()
++        cdef Polynomial_generic_dense res = (<Polynomial_generic_dense>self)._new_c([c // d for c in (<Polynomial_generic_dense>self)._coeffs], P)
++        res._normalize()
+         return res
+ 
+     cpdef _add_(self, right):
+@@ -11839,8 +11839,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+         """
+         cdef Polynomial_generic_dense res
+         cdef Py_ssize_t check=0, i, min
+-        x = (<Polynomial_generic_dense>self).__coeffs
+-        y = (<Polynomial_generic_dense>right).__coeffs
++        x = (<Polynomial_generic_dense>self)._coeffs
++        y = (<Polynomial_generic_dense>right)._coeffs
+         if len(x) > len(y):
+             min = len(y)
+             high = x[min:]
+@@ -11852,7 +11852,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+         cdef list low = [x[i] + y[i] for i from 0 <= i < min]
+         if len(x) == len(y):
+             res = self._new_c(low, self._parent)
+-            res.__normalize()
++            res._normalize()
+             return res
+         else:
+             return self._new_c(low + high, self._parent)
+@@ -11860,8 +11860,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+     cpdef _sub_(self, right):
+         cdef Polynomial_generic_dense res
+         cdef Py_ssize_t check=0, i, min
+-        x = (<Polynomial_generic_dense>self).__coeffs
+-        y = (<Polynomial_generic_dense>right).__coeffs
++        x = (<Polynomial_generic_dense>self)._coeffs
++        y = (<Polynomial_generic_dense>right)._coeffs
+         if len(x) > len(y):
+             min = len(y)
+             high = x[min:]
+@@ -11873,33 +11873,33 @@ cdef class Polynomial_generic_dense(Polynomial):
+         low = [x[i] - y[i] for i from 0 <= i < min]
+         if len(x) == len(y):
+             res = self._new_c(low, self._parent)
+-            res.__normalize()
++            res._normalize()
+             return res
+         else:
+             return self._new_c(low + high, self._parent)
+ 
+     cpdef _rmul_(self, Element c):
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return self
+-        if c._parent is not (<Element>self.__coeffs[0])._parent:
+-            c = (<Element>self.__coeffs[0])._parent.coerce(c)
+-        v = [c * a for a in self.__coeffs]
++        if c._parent is not (<Element>self._coeffs[0])._parent:
++            c = (<Element>self._coeffs[0])._parent.coerce(c)
++        v = [c * a for a in self._coeffs]
+         cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
+         #if not v[len(v)-1]:
+         # "normalize" checks this anyway...
+-        res.__normalize()
++        res._normalize()
+         return res
+ 
+     cpdef _lmul_(self, Element c):
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return self
+-        if c._parent is not (<Element>self.__coeffs[0])._parent:
+-            c = (<Element>self.__coeffs[0])._parent.coerce(c)
+-        v = [a * c for a in self.__coeffs]
++        if c._parent is not (<Element>self._coeffs[0])._parent:
++            c = (<Element>self._coeffs[0])._parent.coerce(c)
++        v = [a * c for a in self._coeffs]
+         cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
+         #if not v[len(v)-1]:
+         # "normalize" checks this anyway...
+-        res.__normalize()
++        res._normalize()
+         return res
+ 
+     cpdef constant_coefficient(self):
+@@ -11916,10 +11916,10 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: f.constant_coefficient()
+             t
+         """
+-        if not self.__coeffs:
++        if not self._coeffs:
+             return self.base_ring().zero()
+         else:
+-            return self.__coeffs[0]
++            return self._coeffs[0]
+ 
+     cpdef list list(self, bint copy=True):
+         """
+@@ -11934,9 +11934,9 @@ cdef class Polynomial_generic_dense(Polynomial):
+             [1, 9, 12, 8]
+         """
+         if copy:
+-            return list(self.__coeffs)
++            return list(self._coeffs)
+         else:
+-            return self.__coeffs
++            return self._coeffs
+ 
+     def degree(self, gen=None):
+         """
+@@ -11955,7 +11955,7 @@ cdef class Polynomial_generic_dense(Polynomial):
+             <class 'sage.rings.integer.Integer'>
+ 
+         """
+-        return smallInteger(len(self.__coeffs) - 1)
++        return smallInteger(len(self._coeffs) - 1)
+ 
+     def shift(self, Py_ssize_t n):
+         r"""
+@@ -11993,13 +11993,13 @@ cdef class Polynomial_generic_dense(Polynomial):
+             return self
+         if n > 0:
+             output = [self.base_ring().zero()] * n
+-            output.extend(self.__coeffs)
++            output.extend(self._coeffs)
+             return self._new_c(output, self._parent)
+         if n < 0:
+-            if n > len(self.__coeffs) - 1:
++            if n > len(self._coeffs) - 1:
+                 return self._parent([])
+             else:
+-                return self._new_c(self.__coeffs[-int(n):], self._parent)
++                return self._new_c(self._coeffs[-int(n):], self._parent)
+ 
+     @coerce_binop
+     def quo_rem(self, other):
+@@ -12073,8 +12073,8 @@ cdef class Polynomial_generic_dense(Polynomial):
+             return self, self
+ 
+         R = self._parent.base_ring()
+-        cdef list x = list((<Polynomial_generic_dense>self).__coeffs) # make a copy
+-        cdef list y = (<Polynomial_generic_dense>other).__coeffs
++        cdef list x = list((<Polynomial_generic_dense>self)._coeffs) # make a copy
++        cdef list y = (<Polynomial_generic_dense>other)._coeffs
+         cdef Py_ssize_t m = len(x)  # deg(self)=m-1
+         cdef Py_ssize_t n = len(y)  # deg(other)=n-1
+         if m < n:
+@@ -12135,18 +12135,18 @@ cdef class Polynomial_generic_dense(Polynomial):
+             sage: type(f)
+             <class 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense'>
+         """
+-        l = len(self.__coeffs)
++        l = len(self._coeffs)
+         if n > l:
+             n = l
+-        while n > 0 and not self.__coeffs[n-1]:
++        while n > 0 and not self._coeffs[n-1]:
+             n -= 1
+-        return self._new_c(self.__coeffs[:n], self._parent)
++        return self._new_c(self._coeffs[:n], self._parent)
+ 
+     cdef _inplace_truncate(self, long n):
+-        if n < len(self.__coeffs):
+-            while n > 0 and not self.__coeffs[n-1]:
++        if n < len(self._coeffs):
++            while n > 0 and not self._coeffs[n-1]:
+                 n -= 1
+-        self.__coeffs = self.__coeffs[:n]
++        self._coeffs = self._coeffs[:n]
+         return self
+ 
+ def make_generic_polynomial(parent, coeffs):
+@@ -12305,7 +12305,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+ 
+     - Xavier Caruso (2013-03)
+     """
+-    cdef int __normalize(self) except -1:
++    cdef int _normalize(self) except -1:
+         r"""
+         TESTS::
+ 
+@@ -12316,7 +12316,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+             sage: S([1, R(0, 20)])                                                      # needs sage.rings.padics
+             O(5^20)*x + 1 + O(5^20)
+         """
+-        cdef list x = self.__coeffs
++        cdef list x = self._coeffs
+         cdef Py_ssize_t n = len(x) - 1
+         cdef RingElement c
+         while n >= 0:
+@@ -12376,7 +12376,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+ 
+         - Xavier Caruso (2013-03)
+         """
+-        coeffs = self.__coeffs
++        coeffs = self._coeffs
+         d = len(coeffs) - 1
+         while d >= 0:
+             c = coeffs[d]
+@@ -12420,7 +12420,7 @@ cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense):
+ 
+         - Xavier Caruso (2013-03)
+         """
+-        return len(self.__coeffs) - 1
++        return len(self._coeffs) - 1
+ 
+ 
+ cdef class ConstantPolynomialSection(Map):
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd
+index 03c5cebbf09..b1b593d6a26 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pxd
+@@ -5,7 +5,7 @@ from sage.rings.integer cimport Integer
+ from sage.structure.parent cimport Parent
+ 
+ cdef class Polynomial_integer_dense_flint(Polynomial):
+-    cdef fmpz_poly_t __poly
++    cdef fmpz_poly_t _poly
+ 
+     cdef Polynomial_integer_dense_flint _new(self)
+     cpdef _unsafe_mutate(self, long n, value)
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx
+index e201ac843ad..194eb9263b2 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_flint.pyx
+@@ -99,14 +99,14 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         r"""
+         This calls the underlying FLINT fmpz_poly constructor
+         """
+-        fmpz_poly_init(self.__poly)
++        fmpz_poly_init(self._poly)
+ 
+ 
+     def __dealloc__(self):
+         r"""
+         calls the underlying FLINT fmpz_poly destructor
+         """
+-        fmpz_poly_clear(self.__poly)
++        fmpz_poly_clear(self._poly)
+ 
+     cdef Polynomial_integer_dense_flint _new(self):
+         r"""
+@@ -139,7 +139,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         x._is_gen = 0
+         if not isinstance(a, Integer):
+             a = ZZ(a)
+-        fmpz_poly_set_coeff_mpz(x.__poly, 0, (<Integer>a).value)
++        fmpz_poly_set_coeff_mpz(x._poly, 0, (<Integer>a).value)
+         return x
+ 
+     def __init__(self, parent, x=None, check=True, is_gen=False,
+@@ -224,8 +224,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         if isinstance(x, Polynomial):
+             if x.parent() is self.parent():
+                 sig_on()
+-                fmpz_poly_set(self.__poly,
+-                              (<Polynomial_integer_dense_flint>x).__poly)
++                fmpz_poly_set(self._poly,
++                              (<Polynomial_integer_dense_flint>x)._poly)
+                 sig_off()
+                 return
+             else:
+@@ -246,7 +246,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                     degree = i
+             try:
+                 sig_on()
+-                fmpz_poly_realloc(self.__poly, degree + 1)
++                fmpz_poly_realloc(self._poly, degree + 1)
+                 sig_off()
+             except RuntimeError:
+                 raise OverflowError("Cannot allocate memory!")
+@@ -255,13 +255,13 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 i = ii[0] if type(ii) is tuple else ii
+                 if is_small_python_int(a):
+                     sig_on()
+-                    fmpz_poly_set_coeff_si(self.__poly, i, a)
++                    fmpz_poly_set_coeff_si(self._poly, i, a)
+                     sig_off()
+                 else:
+                     if not isinstance(a, Integer):
+                         a = ZZ(a)
+                     sig_on()
+-                    fmpz_poly_set_coeff_mpz(self.__poly, i, (<Integer>a).value)
++                    fmpz_poly_set_coeff_mpz(self._poly, i, (<Integer>a).value)
+                     sig_off()
+             return
+ 
+@@ -270,7 +270,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             check = False
+ 
+         elif isinstance(x, ntl_ZZX):    # coercion from ntl.pyx object
+-            fmpz_poly_set_ZZX(self.__poly, (<ntl_ZZX>x).x)
++            fmpz_poly_set_ZZX(self._poly, (<ntl_ZZX>x).x)
+             return
+ 
+         elif isinstance(x, FractionFieldElement) and \
+@@ -278,8 +278,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if x.denominator() == 1:
+                 # fraction of the form f(x)/1
+                 sig_on()
+-                fmpz_poly_set(self.__poly,
+-                        (<Polynomial_integer_dense_flint>x.numerator()).__poly)
++                fmpz_poly_set(self._poly,
++                        (<Polynomial_integer_dense_flint>x.numerator())._poly)
+                 sig_off()
+                 return
+ 
+@@ -287,19 +287,19 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             x = [x]   # constant polynomials
+ 
+         sig_on()
+-        fmpz_poly_realloc(self.__poly, len(x))
++        fmpz_poly_realloc(self._poly, len(x))
+         sig_off()
+         for i from 0 <= i < len(x):
+             a = x[i]
+             if is_small_python_int(a):
+                 sig_on()
+-                fmpz_poly_set_coeff_si(self.__poly, i, a)
++                fmpz_poly_set_coeff_si(self._poly, i, a)
+                 sig_off()
+             else:
+                 if not isinstance(a, Integer):
+                     a = ZZ(a)
+                 sig_on()
+-                fmpz_poly_set_coeff_mpz(self.__poly, i, (<Integer>a).value)
++                fmpz_poly_set_coeff_mpz(self._poly, i, (<Integer>a).value)
+                 sig_off()
+ 
+     def _eval_mpfr_(self, RealNumber a):
+@@ -327,7 +327,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef RealNumber res = a._new()
+         sig_on()
+-        fmpz_poly_evaluation_mpfr(res.value, self.__poly, a.value)
++        fmpz_poly_evaluation_mpfr(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -357,7 +357,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef RealIntervalFieldElement res = a._new()
+         sig_on()
+-        fmpz_poly_evaluation_mpfi(res.value, self.__poly, a.value)
++        fmpz_poly_evaluation_mpfi(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -412,8 +412,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if isinstance(x, Polynomial_integer_dense_flint):
+                 f = self._new()
+                 sig_on()
+-                fmpz_poly_compose(f.__poly, self.__poly,
+-                                  (<Polynomial_integer_dense_flint> x0).__poly)
++                fmpz_poly_compose(f._poly, self._poly,
++                                  (<Polynomial_integer_dense_flint> x0)._poly)
+                 sig_off()
+                 return f
+             if is_small_python_int(x0):
+@@ -422,7 +422,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 fmpz_init(a_fmpz)
+                 fmpz_init(z_fmpz)
+                 fmpz_set_si(a_fmpz, PyInt_AS_LONG(x0))
+-                fmpz_poly_evaluate_fmpz(z_fmpz, self.__poly, a_fmpz)
++                fmpz_poly_evaluate_fmpz(z_fmpz, self._poly, a_fmpz)
+                 fmpz_get_mpz(z.value, z_fmpz)
+                 fmpz_clear(a_fmpz)
+                 fmpz_clear(z_fmpz)
+@@ -433,7 +433,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if isinstance(x0, Integer):
+                 a = <Integer> x0
+ 
+-                if fmpz_poly_length(self.__poly) == 0:
++                if fmpz_poly_length(self._poly) == 0:
+                     return ZZ.zero()
+                 if mpz_sgn(a.value) == 0:
+                     return self[0]
+@@ -444,7 +444,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 fmpz_init(a_fmpz)
+                 fmpz_init(z_fmpz)
+                 fmpz_set_mpz(a_fmpz, a.value)
+-                fmpz_poly_evaluate_fmpz(z_fmpz, self.__poly, a_fmpz)
++                fmpz_poly_evaluate_fmpz(z_fmpz, self._poly, a_fmpz)
+                 fmpz_get_mpz(z.value, z_fmpz)
+                 fmpz_clear(a_fmpz)
+                 fmpz_clear(z_fmpz)
+@@ -460,14 +460,14 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 arb_a = <RealBall> x0
+                 arb_z = arb_a._new()
+                 sig_on()
+-                arb_fmpz_poly_evaluate_arb(arb_z.value, self.__poly, arb_a.value, arb_a._parent._prec)
++                arb_fmpz_poly_evaluate_arb(arb_z.value, self._poly, arb_a.value, arb_a._parent._prec)
+                 sig_off()
+                 return arb_z
+             if isinstance(x0, ComplexBall):
+                 acb_a = <ComplexBall> x0
+                 acb_z = acb_a._new()
+                 sig_on()
+-                arb_fmpz_poly_evaluate_acb(acb_z.value, self.__poly, acb_a.value, acb_a._parent._prec)
++                arb_fmpz_poly_evaluate_acb(acb_z.value, self._poly, acb_a.value, acb_a._parent._prec)
+                 sig_off()
+                 return acb_z
+ 
+@@ -510,10 +510,10 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+         cdef fmpz_t c
+         fmpz_init(c)
+-        fmpz_poly_get_coeff_fmpz(c, self.__poly, fmpz_poly_degree(self.__poly))
++        fmpz_poly_get_coeff_fmpz(c, self._poly, fmpz_poly_degree(self._poly))
+         cdef int sign = fmpz_sgn(c)
+ 
+-        fmpz_poly_content(c, self.__poly)
++        fmpz_poly_content(c, self._poly)
+ 
+         cdef Integer z = Integer.__new__(Integer)
+         fmpz_get_mpz(z.value, c)
+@@ -561,7 +561,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             5*x^5 + 4*x^4 + 3*x^3 + 2*x^2 + x + 1
+         """
+         cdef Integer z = Integer.__new__(Integer)
+-        fmpz_poly_get_coeff_mpz(z.value, self.__poly, n)
++        fmpz_poly_get_coeff_mpz(z.value, self._poly, n)
+         return z
+ 
+     def _repr(self, name=None, bint latex=False):
+@@ -583,8 +583,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef long i
+         cdef Integer coef = Integer.__new__(Integer)
+         cdef list all = []
+-        for i from fmpz_poly_degree(self.__poly) >= i >= 0:
+-            fmpz_poly_get_coeff_mpz(coef.value, self.__poly, i)
++        for i from fmpz_poly_degree(self._poly) >= i >= 0:
++            fmpz_poly_get_coeff_mpz(coef.value, self._poly, i)
+             if coef:
+                 if coef > 0:
+                     sign_str = '+'
+@@ -649,8 +649,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_add(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_add(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -669,8 +669,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_sub(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_sub(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -688,7 +688,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_neg(x.__poly, self.__poly)
++        fmpz_poly_neg(x._poly, self._poly)
+         sig_off()
+         return x
+ 
+@@ -758,7 +758,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef Polynomial_integer_dense_flint rr = self._new()
+ 
+         sig_on()
+-        fmpz_poly_divrem(qq.__poly, rr.__poly, self.__poly, right.__poly)
++        fmpz_poly_divrem(qq._poly, rr._poly, self._poly, right._poly)
+         sig_off()
+         return qq, rr
+ 
+@@ -776,7 +776,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: x.is_zero()
+             False
+         """
+-        return (fmpz_poly_degree(self.__poly) == -1)
++        return (fmpz_poly_degree(self._poly) == -1)
+ 
+     cpdef bint is_one(self) except -1:
+         """
+@@ -792,7 +792,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: x.is_one()
+             False
+         """
+-        return fmpz_poly_is_one(self.__poly)
++        return fmpz_poly_is_one(self._poly)
+ 
+     def __bool__(self):
+         """
+@@ -808,7 +808,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: bool(x)
+             True
+         """
+-        return not (fmpz_poly_degree(self.__poly) == -1)
++        return not (fmpz_poly_degree(self._poly) == -1)
+ 
+     @coerce_binop
+     def gcd(self, right):
+@@ -831,8 +831,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             return self
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_gcd(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_gcd(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -941,8 +941,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         fmpz_init(r)
+ 
+         sig_on()
+-        fmpz_poly_xgcd(r, ss.__poly, tt.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_xgcd(r, ss._poly, tt._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         cdef Integer rr = Integer.__new__(Integer)
+         fmpz_get_mpz(rr.value, r)
+@@ -970,8 +970,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_mul(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_flint>right).__poly)
++        fmpz_poly_mul(x._poly, self._poly,
++                (<Polynomial_integer_dense_flint>right)._poly)
+         sig_off()
+         return x
+ 
+@@ -1000,8 +1000,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_mullow(x.__poly, self.__poly,
+-                    (<Polynomial_integer_dense_flint>right).__poly,
++        fmpz_poly_mullow(x._poly, self._poly,
++                    (<Polynomial_integer_dense_flint>right)._poly,
+                     n)
+         sig_off()
+         return x
+@@ -1020,7 +1020,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_scalar_mul_mpz(x.__poly, self.__poly, (<Integer>right).value)
++        fmpz_poly_scalar_mul_mpz(x._poly, self._poly, (<Integer>right).value)
+         sig_off()
+         return x
+ 
+@@ -1038,7 +1038,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint x = self._new()
+         sig_on()
+-        fmpz_poly_scalar_mul_mpz(x.__poly, self.__poly, (<Integer>right).value)
++        fmpz_poly_scalar_mul_mpz(x._poly, self._poly, (<Integer>right).value)
+         sig_off()
+         return x
+ 
+@@ -1132,7 +1132,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             num = n.numerator()
+             den = n.denominator()
+ 
+-            if fmpz_poly_degree(self.__poly) == 0:
++            if fmpz_poly_degree(self._poly) == 0:
+                 return self.parent()(self[0].nth_root(den) ** num)
+ 
+             return self.nth_root(den) ** num
+@@ -1142,7 +1142,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+             if self.is_zero():
+                 if nn == 0:
+-                    fmpz_poly_set_coeff_si(res.__poly, 0, 1)
++                    fmpz_poly_set_coeff_si(res._poly, 0, 1)
+                     return res
+                 elif nn < 0:
+                     raise ZeroDivisionError("negative exponent in power of zero")
+@@ -1150,17 +1150,17 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                     return res
+             if nn < 0:
+                 sig_on()
+-                fmpz_poly_pow(res.__poly, self.__poly, -nn)
++                fmpz_poly_pow(res._poly, self._poly, -nn)
+                 sig_off()
+                 return ~res
+             else:
+                 if self is self._parent.gen():
+                     sig_on()
+-                    fmpz_poly_set_coeff_ui(res.__poly, nn, 1)
++                    fmpz_poly_set_coeff_ui(res._poly, nn, 1)
+                     sig_off()
+                 else:
+                     sig_on()
+-                    fmpz_poly_pow(res.__poly, self.__poly, nn)
++                    fmpz_poly_pow(res._poly, self._poly, nn)
+                     sig_off()
+                 return res
+ 
+@@ -1187,7 +1187,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+         cdef Polynomial_integer_dense_flint res
+         res = self._new()
+-        fmpz_poly_pow_trunc(res.__poly, self.__poly, n, prec)
++        fmpz_poly_pow_trunc(res._poly, self._poly, n, prec)
+         return res
+ 
+     def __floordiv__(Polynomial_integer_dense_flint self, right):
+@@ -1226,14 +1226,14 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+                 else:
+                     res = self._new()
+                     sig_on()
+-                    fmpz_poly_scalar_fdiv_mpz(res.__poly, self.__poly,
++                    fmpz_poly_scalar_fdiv_mpz(res._poly, self._poly,
+                             (<Integer> right).value)
+                     sig_off()
+                 return res
+             elif right in ZZ:
+                 res = self._new()
+                 sig_on()
+-                fmpz_poly_scalar_fdiv_mpz(res.__poly, self.__poly,
++                fmpz_poly_scalar_fdiv_mpz(res._poly, self._poly,
+                         (<Integer>ZZ(right)).value)
+                 sig_off()
+                 return res
+@@ -1248,7 +1248,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         else:
+             res = self._new()
+             sig_on()
+-            fmpz_poly_div(res.__poly, self.__poly, _right.__poly)
++            fmpz_poly_div(res._poly, self._poly, _right._poly)
+             sig_off()
+             return res
+ 
+@@ -1293,9 +1293,9 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         if prec <= 0:
+             raise ValueError("the precision must be positive, got {}".format(prec))
+ 
+-        if fmpz_poly_degree(self.__poly) == -1:
++        if fmpz_poly_degree(self._poly) == -1:
+             raise ValueError("constant term is zero")
+-        cdef fmpz_t c = fmpz_poly_get_coeff_ptr(self.__poly, 0)
++        cdef fmpz_t c = fmpz_poly_get_coeff_ptr(self._poly, 0)
+         if fmpz_cmp_si(c, 1) and fmpz_cmp_si(c, -1):
+             raise ValueError("constant term {} is not a unit".format(self[0]))
+ 
+@@ -1303,7 +1303,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         if prec <= 0:
+             return res
+         sig_on()
+-        fmpz_poly_inv_series(res.__poly, self.__poly, prec)
++        fmpz_poly_inv_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1331,16 +1331,16 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             raise IndexError("n must be >= 0")
+         if isinstance(value, int):
+             sig_on()
+-            fmpz_poly_set_coeff_si(self.__poly, n, value)
++            fmpz_poly_set_coeff_si(self._poly, n, value)
+             sig_off()
+         elif isinstance(value, Integer):
+             sig_on()
+-            fmpz_poly_set_coeff_mpz(self.__poly, n, (<Integer>value).value)
++            fmpz_poly_set_coeff_mpz(self._poly, n, (<Integer>value).value)
+             sig_off()
+         else:
+             value = Integer(value)
+             sig_on()
+-            fmpz_poly_set_coeff_mpz(self.__poly, n, (<Integer>value).value)
++            fmpz_poly_set_coeff_mpz(self._poly, n, (<Integer>value).value)
+             sig_off()
+ 
+     def real_root_intervals(self):
+@@ -1364,7 +1364,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+ ##     def __copy__(self):
+ ##         f = Polynomial_integer_dense(self.parent())
+-##         f.__poly = self.__poly.copy()
++##         f._poly = self._poly.copy()
+ ##         return f
+ 
+ 
+@@ -1391,7 +1391,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             sage: type(x.degree())
+             <class 'sage.rings.integer.Integer'>
+         """
+-        return smallInteger(fmpz_poly_degree(self.__poly))
++        return smallInteger(fmpz_poly_degree(self._poly))
+ 
+     def pseudo_divrem(self, B):
+         r"""
+@@ -1426,7 +1426,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef Polynomial_integer_dense_flint Q = self._new(), R = self._new(), _B = B
+         cdef ulong d
+-        fmpz_poly_pseudo_divrem(Q.__poly, R.__poly, &d, self.__poly, _B.__poly)
++        fmpz_poly_pseudo_divrem(Q._poly, R._poly, &d, self._poly, _B._poly)
+         return Q, R, Integer(d)
+ 
+     def discriminant(self, proof=True):
+@@ -1460,7 +1460,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         """
+         cdef ZZX_c ntl_poly
+         cdef ZZ_c* temp
+-        fmpz_poly_get_ZZX(ntl_poly, self.__poly)
++        fmpz_poly_get_ZZX(ntl_poly, self._poly)
+ 
+         temp = ZZX_discriminant(&ntl_poly, proof)
+         cdef Integer x = Integer.__new__(Integer)
+@@ -1531,12 +1531,12 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+ 
+             # the primitive part returned by FLINT has positive leading
+             # coefficient
+-            fmpz_poly_primitive_part(ppart, self.__poly)
++            fmpz_poly_primitive_part(ppart, self._poly)
+ 
+             fmpz_poly_get_ZZX(ntl_poly, ppart)
+             fmpz_poly_clear(ppart)
+         else:
+-            fmpz_poly_get_ZZX(ntl_poly, self.__poly)
++            fmpz_poly_get_ZZX(ntl_poly, self._poly)
+ 
+         # input is primitive, with positive leading coefficient
+         ZZX_squarefree_decomposition(&v, &e, &n, &ntl_poly)
+@@ -1544,7 +1544,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         F = []
+         for i from 0 <= i < n:
+             fac = self._new()
+-            fmpz_poly_set_ZZX(fac.__poly, v[i][0])
++            fmpz_poly_set_ZZX(fac._poly, v[i][0])
+             F.append( (fac,e[i]) )
+             del v[i]
+         sig_free(v)
+@@ -1582,9 +1582,9 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef ZZ_c content
+         cdef vec_pair_ZZX_long_c factors
+         cdef long i
+-        cdef int sig_me = fmpz_poly_degree(self.__poly)
++        cdef int sig_me = fmpz_poly_degree(self._poly)
+ 
+-        fmpz_poly_get_ZZX(ntl_poly, self.__poly)
++        fmpz_poly_get_ZZX(ntl_poly, self._poly)
+ 
+         if sig_me > 10:
+             sig_on()
+@@ -1603,13 +1603,13 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             fac_py = self._new()
+             fmpz_init(tcontent)
+             fmpz_set_ZZ(tcontent, content)
+-            fmpz_poly_set_coeff_fmpz(fac_py.__poly, 0, tcontent)
++            fmpz_poly_set_coeff_fmpz(fac_py._poly, 0, tcontent)
+             results.append( (fac_py,1) )
+             fmpz_clear(tcontent)
+ 
+         for i from 0 <= i < factors.length():
+             fac_py = self._new()
+-            fmpz_poly_set_ZZX(fac_py.__poly, factors.RawGet(i).a)
++            fmpz_poly_set_ZZX(fac_py._poly, factors.RawGet(i).a)
+             results.append( (fac_py,factors.RawGet(i).b) )
+         return Factorization(results, unit = unit)
+ 
+@@ -1639,7 +1639,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             (-1) * 2 * 3 * 5 * x
+         """
+         cdef int i
+-        cdef long deg = fmpz_poly_degree(self.__poly)
++        cdef long deg = fmpz_poly_degree(self._poly)
+         # it appears that pari has a window from about degrees 30 and 300
+         # in which it beats NTL.
+         c = self.content()
+@@ -1783,8 +1783,8 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+         cdef Integer x = Integer.__new__(Integer)
+ 
+         sig_on()
+-        fmpz_poly_resultant(res, self.__poly,
+-                (<Polynomial_integer_dense_flint>other).__poly)
++        fmpz_poly_resultant(res, self._poly,
++                (<Polynomial_integer_dense_flint>other)._poly)
+         sig_off()
+         fmpz_get_mpz(x.value, res)
+         fmpz_clear(res)
+@@ -1830,10 +1830,10 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             if d != degree:
+                 raise ValueError("degree argument must be a non-negative integer, got %s" % degree)
+             # FLINT expects length
+-            fmpz_poly_reverse(res.__poly, self.__poly, d+1)
++            fmpz_poly_reverse(res._poly, self._poly, d+1)
+         else:
+-            fmpz_poly_reverse(res.__poly, self.__poly,
+-                    fmpz_poly_length(self.__poly))
++            fmpz_poly_reverse(res._poly, self._poly,
++                    fmpz_poly_length(self._poly))
+         return res
+ 
+     def revert_series(self, n):
+@@ -1867,7 +1867,7 @@ cdef class Polynomial_integer_dense_flint(Polynomial):
+             raise ValueError("self must have constant coefficient 0 and a unit for coefficient {}^1".format(self.parent().gen()))
+ 
+         sig_on()
+-        fmpz_poly_revert_series(res.__poly, self.__poly, m)
++        fmpz_poly_revert_series(res._poly, self._poly, m)
+         sig_off()
+ 
+         return res
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd
+index a7c380b49a2..fcd907e1abe 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pxd
+@@ -2,6 +2,6 @@ from sage.libs.ntl.types cimport ZZX_c
+ from sage.rings.polynomial.polynomial_element cimport Polynomial
+ 
+ cdef class Polynomial_integer_dense_ntl(Polynomial):
+-    cdef ZZX_c __poly
++    cdef ZZX_c _poly
+ 
+     cdef Polynomial_integer_dense_ntl _new(self)
+diff --git a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx
+index e7b708bbc51..80a1726bb4e 100644
+--- a/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx
++++ b/src/sage/rings/polynomial/polynomial_integer_dense_ntl.pyx
+@@ -172,7 +172,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         if isinstance(x, Polynomial):
+             if x.parent() is self.parent():
+                 # copy with NTL assignment operator
+-                self.__poly = (<Polynomial_integer_dense_ntl>x).__poly
++                self._poly = (<Polynomial_integer_dense_ntl>x)._poly
+                 return
+             else:
+                 # coerce coefficients into Sage integers
+@@ -191,17 +191,17 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+                     degree = i
+             if degree >= NTL_OVFBND:
+                 raise OverflowError("Dense NTL integer polynomials have a maximum degree of %s" % (NTL_OVFBND-1))
+-            ZZX_SetCoeff_long(self.__poly, degree, 1)
++            ZZX_SetCoeff_long(self._poly, degree, 1)
+             # now fill them in
+             for ii, a in x:
+                 i = ii[0] if type(ii) is tuple else ii
+                 if type(a) is int:
+-                    ZZX_SetCoeff_long(self.__poly, i, a)
++                    ZZX_SetCoeff_long(self._poly, i, a)
+                 else:
+                     if not isinstance(a, Integer):
+                         a = ZZ(a)
+                     mpz_to_ZZ(&y, (<Integer>a).value)
+-                    ZZX_SetCoeff(self.__poly, i, y)
++                    ZZX_SetCoeff(self._poly, i, y)
+             return
+ 
+         elif isinstance(x, pari_gen):
+@@ -210,14 +210,14 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+ 
+         elif isinstance(x, ntl_ZZX):    # coercion from ntl.pyx object
+             # copy with NTL assignment operator
+-            self.__poly = (<ntl_ZZX>x).x
++            self._poly = (<ntl_ZZX>x).x
+             return
+ 
+         elif isinstance(x, FractionFieldElement) and \
+                  isinstance(x.numerator(), Polynomial_integer_dense_ntl):
+             if x.denominator() == 1:
+                 # fraction of the form f(x)/1
+-                self.__poly = (<Polynomial_integer_dense_ntl>x.numerator()).__poly
++                self._poly = (<Polynomial_integer_dense_ntl>x.numerator())._poly
+                 return
+ 
+         elif not isinstance(x, (list, tuple)):
+@@ -229,12 +229,12 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         for i from 0 <= i < len(x):
+             a = x[i]
+             if type(a) is int:
+-                ZZX_SetCoeff_long(self.__poly, i, a)
++                ZZX_SetCoeff_long(self._poly, i, a)
+             else:
+                 if not isinstance(a, Integer):
+                     a = ZZ(a)
+                 mpz_to_ZZ(&y, (<Integer>a).value)
+-                ZZX_SetCoeff(self.__poly, i, y)
++                ZZX_SetCoeff(self._poly, i, y)
+ 
+ 
+     def content(self):
+@@ -259,7 +259,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef ZZ_c y
+         cdef Integer z = Integer.__new__(Integer)
+-        ZZX_content(y, self.__poly)
++        ZZX_content(y, self._poly)
+         ZZ_to_mpz(z.value, &y)
+         return z
+ 
+@@ -288,7 +288,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef RealNumber res = a._new()
+         sig_on()
+-        ZZX_evaluation_mpfr(res.value, self.__poly, a.value)
++        ZZX_evaluation_mpfr(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -318,7 +318,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef RealIntervalFieldElement res = a._new()
+         sig_on()
+-        ZZX_evaluation_mpfi(res.value, self.__poly, a.value)
++        ZZX_evaluation_mpfi(res.value, self._poly, a.value)
+         sig_off()
+         return res
+ 
+@@ -363,7 +363,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             5*x^5 + 4*x^4 + 3*x^3 + 2*x^2 + x + 1
+         """
+         cdef Integer z = Integer.__new__(Integer)
+-        ZZ_to_mpz(z.value, &self.__poly.rep.elts()[n])
++        ZZ_to_mpz(z.value, &self._poly.rep.elts()[n])
+         return z
+ 
+     def _repr(self, name=None, bint latex=False):
+@@ -380,15 +380,15 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             name = self.parent().variable_name()
+         cdef long i
+         cdef list all = []
+-        for i from ZZX_deg(self.__poly) >= i >= 0:
+-            sign = ZZ_sign(ZZX_coeff(self.__poly, i))
++        for i from ZZX_deg(self._poly) >= i >= 0:
++            sign = ZZ_sign(ZZX_coeff(self._poly, i))
+             if sign:
+                 if sign > 0:
+                     sign_str = '+'
+-                    coeff_str = ccrepr(self.__poly.rep.elts()[i])
++                    coeff_str = ccrepr(self._poly.rep.elts()[i])
+                 else:
+                     sign_str = '-'
+-                    coeff_str = ccrepr(self.__poly.rep.elts()[i])[1:]
++                    coeff_str = ccrepr(self._poly.rep.elts()[i])[1:]
+                 if i > 0:
+                     if coeff_str == '1':
+                         coeff_str = ''
+@@ -441,8 +441,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             -3*x^2 + 2*x + 7
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_add(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_ntl>right).__poly)
++        ZZX_add(x._poly, self._poly,
++                (<Polynomial_integer_dense_ntl>right)._poly)
+         return x
+ 
+ 
+@@ -459,8 +459,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             3*x^2 + 2*x - 5
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_sub(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_ntl>right).__poly)
++        ZZX_sub(x._poly, self._poly,
++                (<Polynomial_integer_dense_ntl>right)._poly)
+         return x
+ 
+ 
+@@ -476,7 +476,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             -2*x + 1
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_negate(x.__poly, self.__poly)
++        ZZX_negate(x._poly, self._poly)
+         return x
+ 
+ 
+@@ -533,10 +533,10 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         cdef Polynomial_integer_dense_ntl _right = <Polynomial_integer_dense_ntl> right
+ 
+-        if ZZX_IsZero(_right.__poly):
++        if ZZX_IsZero(_right._poly):
+             raise ArithmeticError("division by zero polynomial")
+ 
+-        if ZZX_IsZero(self.__poly):
++        if ZZX_IsZero(self._poly):
+             return self, self
+ 
+         cdef ZZX_c *q
+@@ -545,19 +545,19 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef Polynomial_integer_dense_ntl rr = self._new()
+         cdef int divisible
+ 
+-        if ZZ_IsOne(ZZX_LeadCoeff(_right.__poly)):
++        if ZZ_IsOne(ZZX_LeadCoeff(_right._poly)):
+             # divisor is monic. Just do the division and remainder
+-            ZZX_quo_rem(&self.__poly, &_right.__poly, &r, &q)
+-            ZZX_swap(qq.__poly, q[0])
+-            ZZX_swap(rr.__poly, r[0])
++            ZZX_quo_rem(&self._poly, &_right._poly, &r, &q)
++            ZZX_swap(qq._poly, q[0])
++            ZZX_swap(rr._poly, r[0])
+             del q
+             del r
+         else:
+             # Non-monic divisor. Check whether it divides exactly.
+-            q = ZZX_div(&self.__poly, &_right.__poly, &divisible)
++            q = ZZX_div(&self._poly, &_right._poly, &divisible)
+             if divisible:
+                 # exactly divisible
+-                ZZX_swap(q[0], qq.__poly)
++                ZZX_swap(q[0], qq._poly)
+                 del q
+             else:
+                 # division failed: clean up and raise exception
+@@ -584,8 +584,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         """
+         # todo: we're doing an unnecessary copy here
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        cdef ZZX_c* temp = ZZX_gcd(&self.__poly, &(<Polynomial_integer_dense_ntl>right).__poly)
+-        x.__poly = temp[0]
++        cdef ZZX_c* temp = ZZX_gcd(&self._poly, &(<Polynomial_integer_dense_ntl>right)._poly)
++        x._poly = temp[0]
+         del temp
+         return x
+ 
+@@ -658,13 +658,13 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZX_c *t
+         cdef ZZ_c *r
+ 
+-        ZZX_xgcd(&self.__poly, &(<Polynomial_integer_dense_ntl>right).__poly, &r, &s, &t, 1)    # proof = 1
++        ZZX_xgcd(&self._poly, &(<Polynomial_integer_dense_ntl>right)._poly, &r, &s, &t, 1)    # proof = 1
+         cdef Integer rr = Integer.__new__(Integer)
+         ZZ_to_mpz(rr.value, r)
+         cdef Polynomial_integer_dense_ntl ss = self._new()
+         cdef Polynomial_integer_dense_ntl tt = self._new()
+-        ss.__poly = s[0]
+-        tt.__poly = t[0]
++        ss._poly = s[0]
++        tt._poly = t[0]
+         del r
+         del s
+         del t
+@@ -691,8 +691,8 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             x^3 - 10*x^2 + 32*x - 32
+         """
+         cdef Polynomial_integer_dense_ntl x = self._new()
+-        ZZX_mul(x.__poly, self.__poly,
+-                (<Polynomial_integer_dense_ntl>right).__poly)
++        ZZX_mul(x._poly, self._poly,
++                (<Polynomial_integer_dense_ntl>right)._poly)
+         return x
+ 
+     cpdef _lmul_(self, Element right):
+@@ -711,7 +711,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZ_c _right
+ 
+         mpz_to_ZZ(&_right, (<Integer>right).value)
+-        ZZX_mul_ZZ(x.__poly, self.__poly, _right)
++        ZZX_mul_ZZ(x._poly, self._poly, _right)
+         return x
+ 
+     cpdef _rmul_(self, Element right):
+@@ -730,7 +730,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZ_c _right
+ 
+         mpz_to_ZZ(&_right, (<Integer>right).value)
+-        ZZX_mul_ZZ(x.__poly, self.__poly, _right)
++        ZZX_mul_ZZ(x._poly, self._poly, _right)
+         return x
+ 
+ 
+@@ -783,7 +783,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         value = Integer(value)
+         cdef ZZ_c y
+         mpz_to_ZZ(&y, (<Integer>value).value)
+-        ZZX_SetCoeff(self.__poly, n, y)
++        ZZX_SetCoeff(self._poly, n, y)
+ 
+ 
+     def real_root_intervals(self):
+@@ -805,7 +805,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+ 
+ ##     def __copy__(self):
+ ##         f = Polynomial_integer_dense(self.parent())
+-##         f.__poly = self.__poly.copy()
++##         f._poly = self._poly.copy()
+ ##         return f
+ 
+ 
+@@ -826,7 +826,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             sage: R(0).degree()
+             -1
+         """
+-        return ZZX_deg(self.__poly)
++        return ZZX_deg(self._poly)
+ 
+     def discriminant(self, proof=True):
+         r"""
+@@ -849,7 +849,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             sage: f.discriminant(proof=False)
+             -339
+         """
+-        cdef ZZ_c* temp = ZZX_discriminant(&self.__poly, proof)
++        cdef ZZ_c* temp = ZZX_discriminant(&self._poly, proof)
+         cdef Integer x = Integer.__new__(Integer)
+         ZZ_to_mpz(x.value, temp)
+         del temp
+@@ -904,11 +904,11 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef long* e
+         cdef long i, n
+         cdef Polynomial_integer_dense_ntl z
+-        ZZX_squarefree_decomposition(&v, &e, &n, &p.__poly)
++        ZZX_squarefree_decomposition(&v, &e, &n, &p._poly)
+         F = []
+         for i from 0 <= i < n:
+             z = self._new()
+-            z.__poly = v[i][0]
++            z._poly = v[i][0]
+             F.append((z, e[i]))
+             del v[i]
+         sig_free(v)
+@@ -950,24 +950,24 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+         cdef ZZ_c content
+         cdef vec_pair_ZZX_long_c factors
+         cdef long i
+-        cdef int sig_me = ZZX_deg(self.__poly)
++        cdef int sig_me = ZZX_deg(self._poly)
+         if sig_me > 10:
+             sig_on()
+-        ZZX_factor(content, factors, self.__poly, 0, 0)
++        ZZX_factor(content, factors, self._poly, 0, 0)
+         if sig_me > 10:
+             sig_off()
+         results = []
+         unit = None
+         if not ZZ_IsOne(content):
+             fac_py = self._new()
+-            ZZX_SetCoeff(fac_py.__poly, 0, content)
+-            if ZZX_deg(fac_py.__poly) == 0 and ZZ_to_int(fac_py.__poly.rep.elts())==-1:
++            ZZX_SetCoeff(fac_py._poly, 0, content)
++            if ZZX_deg(fac_py._poly) == 0 and ZZ_to_int(fac_py._poly.rep.elts())==-1:
+                 unit = fac_py
+             else:
+                 results.append( (fac_py,1) )
+         for i from 0 <= i < factors.length():
+             fac_py = self._new()
+-            fac_py.__poly = factors.RawGet(i).a
++            fac_py._poly = factors.RawGet(i).a
+             results.append( (fac_py,factors.RawGet(i).b) )
+         return Factorization(results, unit = unit)
+ 
+@@ -996,7 +996,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             sage: f = -30*x; f.factor()
+             (-1) * 2 * 3 * 5 * x
+         """
+-        cdef int deg = ZZX_deg(self.__poly)
++        cdef int deg = ZZX_deg(self._poly)
+         # it appears that pari has a window from about degrees 30 and 300
+         # in which it beats NTL.
+         c = self.content()
+@@ -1131,7 +1131,7 @@ cdef class Polynomial_integer_dense_ntl(Polynomial):
+             True
+         """
+         cdef Polynomial_integer_dense_ntl _other = <Polynomial_integer_dense_ntl>(self.parent().coerce(other))
+-        cdef ZZ_c* temp = ZZX_resultant(&self.__poly, &_other.__poly, proof)
++        cdef ZZ_c* temp = ZZX_resultant(&self._poly, &_other._poly, proof)
+         cdef Integer x = Integer.__new__(Integer)
+         ZZ_to_mpz(x.value, temp)
+         del temp
+diff --git a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd
+index 264f05f3c0d..6934acfee8d 100644
+--- a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd
++++ b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pxd
+@@ -16,7 +16,7 @@ from sage.libs.ntl.lzz_pX cimport *
+ 
+ 
+ cdef class Polynomial_dense_mod_n(Polynomial):
+-    cdef object __poly
++    cdef object _poly
+     cdef object __singular
+ 
+ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n):
+diff --git a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx
+index 57468e3510f..d69d5e09018 100644
+--- a/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx
++++ b/src/sage/rings/polynomial/polynomial_modn_dense_ntl.pyx
+@@ -105,19 +105,19 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+ 
+         if construct:
+             if isinstance(x, ZZ_pX):
+-                self.__poly = x
++                self._poly = x
+                 return
+-            self.__poly = ZZ_pX(x, parent.modulus())
++            self._poly = ZZ_pX(x, parent.modulus())
+             return
+ 
+-        self.__poly = ZZ_pX([], parent.modulus())
++        self._poly = ZZ_pX([], parent.modulus())
+ 
+         if x is None:
+             return         # leave initialized to 0 polynomial.
+ 
+         if isinstance(x, Polynomial):
+             if x.parent() == self.parent():
+-                self.__poly = (<Polynomial_dense_modn_ntl_zz>x).__poly.__copy__()
++                self._poly = (<Polynomial_dense_modn_ntl_zz>x)._poly.__copy__()
+                 return
+             else:
+                 R = parent.base_ring()
+@@ -130,7 +130,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+ 
+ 
+         elif isinstance(x, ZZX):
+-            self.__poly = x.copy()
++            self._poly = x.copy()
+             return
+ 
+         elif isinstance(x, pari_gen):
+@@ -142,7 +142,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             if x.denominator().is_unit():
+                 numer = x.numerator()
+                 denom = x.denominator().inverse_of_unit()
+-                x = numer.__poly * denom.__poly
++                x = numer._poly * denom._poly
+                 check = False
+             else:
+                 raise TypeError("Denominator not a unit.")
+@@ -154,13 +154,13 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             R = parent.base_ring()
+             x = [ZZ(R(a)) for a in x]
+ 
+-        self.__poly = ZZ_pX(x, parent.modulus())
++        self._poly = ZZ_pX(x, parent.modulus())
+ 
+     def __reduce__(self):
+         return make_element, (self.parent(), (self.list(), False, self.is_gen()))
+ 
+     def int_list(self):
+-        return eval(str(self.__poly).replace(' ',','))
++        return eval(str(self._poly).replace(' ',','))
+ 
+     def __pari__(self, variable=None):
+         """
+@@ -186,7 +186,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             You must call ``ntl.set_modulus(ntl.ZZ(n))`` before doing
+             arithmetic with this object!
+         """
+-        return self.__poly
++        return self._poly
+ 
+     cdef get_unsafe(self, Py_ssize_t n):
+         """
+@@ -203,13 +203,13 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             sage: f[:3]
+             13*x^2 + 10*x + 5
+         """
+-        return self._parent._base((<ntl_ZZ_pX> self.__poly)[n]._integer_())
++        return self._parent._base((<ntl_ZZ_pX> self._poly)[n]._integer_())
+ 
+     def _unsafe_mutate(self, n, value):
+         n = int(n)
+         if n < 0:
+             raise IndexError("n must be >= 0")
+-        self.__poly[n] = int(value)
++        self._poly[n] = int(value)
+ 
+     def _pow(self, n):
+         n = int(n)
+@@ -218,10 +218,10 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             return self.parent()(self[0]**n)
+         if n < 0:
+             return (~self)**(-n)
+-        return self.parent()(self.__poly**n, construct=True)
++        return self.parent()(self._poly**n, construct=True)
+ 
+     cpdef _add_(self, right):
+-        return self.parent()(self.__poly + (<Polynomial_dense_mod_n>right).__poly, construct=True)
++        return self.parent()(self._poly + (<Polynomial_dense_mod_n>right)._poly, construct=True)
+ 
+     cpdef _mul_(self, right):
+         """
+@@ -231,11 +231,11 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             sage: (x - 2)*(x^2 - 8*x + 16)
+             x^3 + 90*x^2 + 32*x + 68
+         """
+-        return self.parent()(self.__poly * (<Polynomial_dense_mod_n>right).__poly, construct=True)
++        return self.parent()(self._poly * (<Polynomial_dense_mod_n>right)._poly, construct=True)
+ 
+     cpdef _lmul_(self, Element c):
+         try:
+-            return self.parent()(ZZ_pX([c], self.parent().modulus()) * self.__poly, construct=True)
++            return self.parent()(ZZ_pX([c], self.parent().modulus()) * self._poly, construct=True)
+         except RuntimeError as msg: # should this really be a TypeError
+             raise TypeError(msg)
+ 
+@@ -245,7 +245,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+         Return a tuple ``(quotient, remainder)`` where ``self = quotient*other +
+         remainder``.
+         """
+-        v = self.__poly.quo_rem((<Polynomial_dense_mod_n>right).__poly)
++        v = self._poly.quo_rem((<Polynomial_dense_mod_n>right)._poly)
+         P = self.parent()
+         return (P(v[0], construct=True), P(v[1], construct=True) )
+ 
+@@ -281,11 +281,11 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+         """
+         if n == 0 or self.degree() < 0:
+             return self
+-        return self.parent()(self.__poly.left_shift(n),
++        return self.parent()(self._poly.left_shift(n),
+                              construct=True)
+ 
+     cpdef _sub_(self, right):
+-        return self.parent()(self.__poly - (<Polynomial_dense_mod_n>right).__poly, construct=True)
++        return self.parent()(self._poly - (<Polynomial_dense_mod_n>right)._poly, construct=True)
+ 
+     def __floordiv__(self, right):
+         q, _ = self.quo_rem(right)
+@@ -314,7 +314,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+             sage: isinstance(x.degree(), Integer)
+             True
+         """
+-        return smallInteger(max(self.__poly.degree(), -1))
++        return smallInteger(max(self._poly.degree(), -1))
+ 
+     cpdef list list(self, bint copy=True):
+         """
+@@ -358,7 +358,7 @@ cdef class Polynomial_dense_mod_n(Polynomial):
+         """
+         if self.is_gen():
+             raise TypeError("Cannot change the value of the generator.")
+-        self.__poly = ZZ_pX(v, self.parent().modulus())
++        self._poly = ZZ_pX(v, self.parent().modulus())
+ 
+     # Polynomial_singular_repr stuff, copied due to lack of multiple inheritance
+     def _singular_(self, singular=singular_default, force=False):
+@@ -654,8 +654,8 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n):
+                 return
+ 
+         Polynomial_dense_mod_n.__init__(self, parent, v, check=check, is_gen=is_gen, construct=construct)
+-        v = [a for a in self.__poly.list()]
+-        self.__poly = None # this will eventually go away
++        v = [a for a in self._poly.list()]
++        self._poly = None # this will eventually go away
+         cdef ntl_zz_pX ntl = ntl_zz_pX(v, parent.modulus()) # let it handle the hard work
+         self.x = ntl.x
+         self.c = ntl.c
+@@ -668,8 +668,8 @@ cdef class Polynomial_dense_modn_ntl_zz(Polynomial_dense_mod_n):
+         # TODO: Get rid of this
+         Polynomial_dense_mod_n.ntl_set_directly(self, v)
+         # verbatim from __init__
+-        v = [int(a) for a in self.__poly.list()]
+-        self.__poly = None # this will eventually go away
++        v = [int(a) for a in self._poly.list()]
++        self._poly = None # this will eventually go away
+         cdef ntl_zz_pX ntl = ntl_zz_pX(v, self._parent.modulus()) # let it handle the hard work
+         self.x = ntl.x
+         self.c = ntl.c
+@@ -1241,8 +1241,8 @@ cdef class Polynomial_dense_modn_ntl_ZZ(Polynomial_dense_mod_n):
+                 return
+ 
+         Polynomial_dense_mod_n.__init__(self, parent, v, check=check, is_gen=is_gen, construct=construct)
+-        cdef ntl_ZZ_pX ntl = self.__poly
+-        self.__poly = None # this will eventually go away
++        cdef ntl_ZZ_pX ntl = self._poly
++        self._poly = None # this will eventually go away
+         self.x = ntl.x
+         self.c = ntl.c
+ 
+diff --git a/src/sage/rings/polynomial/polynomial_rational_flint.pxd b/src/sage/rings/polynomial/polynomial_rational_flint.pxd
+index 055d7842668..f4644f19d04 100644
+--- a/src/sage/rings/polynomial/polynomial_rational_flint.pxd
++++ b/src/sage/rings/polynomial/polynomial_rational_flint.pxd
+@@ -11,7 +11,7 @@ from sage.libs.flint.types cimport fmpq_poly_t
+ from sage.rings.polynomial.polynomial_element cimport Polynomial
+ 
+ cdef class Polynomial_rational_flint(Polynomial):
+-    cdef fmpq_poly_t __poly
++    cdef fmpq_poly_t _poly
+ 
+     cdef Polynomial_rational_flint _new(self)
+     cpdef _mod_(self, right)
+diff --git a/src/sage/rings/polynomial/polynomial_rational_flint.pyx b/src/sage/rings/polynomial/polynomial_rational_flint.pyx
+index d0dd15522e9..26d070ac77f 100644
+--- a/src/sage/rings/polynomial/polynomial_rational_flint.pyx
++++ b/src/sage/rings/polynomial/polynomial_rational_flint.pyx
+@@ -155,16 +155,16 @@ cdef class Polynomial_rational_flint(Polynomial):
+         res._parent = P
+         res._is_gen = <char>0
+         if isinstance(x, int):
+-            fmpq_poly_set_si(res.__poly, <int> x)
++            fmpq_poly_set_si(res._poly, <int> x)
+ 
+         elif isinstance(x, Integer):
+-            fmpq_poly_set_mpz(res.__poly, (<Integer> x).value)
++            fmpq_poly_set_mpz(res._poly, (<Integer> x).value)
+ 
+         elif isinstance(x, Rational):
+-            fmpq_poly_set_mpq(res.__poly, (<Rational> x).value)
++            fmpq_poly_set_mpq(res._poly, (<Rational> x).value)
+ 
+         else:
+-            fmpq_poly_set_si(res.__poly, int(x))
++            fmpq_poly_set_si(res._poly, int(x))
+         return res
+ 
+ 
+@@ -177,7 +177,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: R.<t> = QQ[]
+             sage: f = 2/3 * t - 7  #indirect doctest
+         """
+-        fmpq_poly_init(self.__poly)
++        fmpq_poly_init(self._poly)
+ 
+     def __dealloc__(self):
+         """
+@@ -189,7 +189,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: f = 1/3 * t
+             sage: del f
+         """
+-        fmpq_poly_clear(self.__poly)
++        fmpq_poly_clear(self._poly)
+ 
+     def __init__(self, parent, x=None, check=True, is_gen=False, construct=False):
+         """
+@@ -227,19 +227,19 @@ cdef class Polynomial_rational_flint(Polynomial):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+ 
+         if is_gen:
+-            fmpq_poly_set_coeff_si(self.__poly, 1, 1)
++            fmpq_poly_set_coeff_si(self._poly, 1, 1)
+ 
+         elif isinstance(x, Polynomial_rational_flint):
+-            fmpq_poly_set(self.__poly, (<Polynomial_rational_flint> x).__poly)
++            fmpq_poly_set(self._poly, (<Polynomial_rational_flint> x)._poly)
+ 
+         elif isinstance(x, int):
+-            fmpq_poly_set_si(self.__poly, <int> x)
++            fmpq_poly_set_si(self._poly, <int> x)
+ 
+         elif isinstance(x, Integer):
+-            fmpq_poly_set_mpz(self.__poly, (<Integer> x).value)
++            fmpq_poly_set_mpz(self._poly, (<Integer> x).value)
+ 
+         elif isinstance(x, Rational):
+-            fmpq_poly_set_mpq(self.__poly, (<Rational> x).value)
++            fmpq_poly_set_mpq(self._poly, (<Rational> x).value)
+ 
+         elif isinstance(x, list) or isinstance(x, tuple):
+ 
+@@ -257,7 +257,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             for deg from 0 <= deg < n:
+                 mpq_init(L2[deg])
+                 mpq_set(L2[deg], (<Rational> L1[deg]).value)
+-            fmpq_poly_set_array_mpq(self.__poly, L2, n)
++            fmpq_poly_set_array_mpq(self._poly, L2, n)
+             for deg from 0 <= deg < n:
+                 mpq_clear(L2[deg])
+             sig_free(L2)
+@@ -266,13 +266,13 @@ cdef class Polynomial_rational_flint(Polynomial):
+ #           deg = 0
+ #           for e in x:
+ #               c = Rational(e)
+-#               fmpq_poly_set_coeff_mpq(self.__poly, deg, c.value)
++#               fmpq_poly_set_coeff_mpq(self._poly, deg, c.value)
+ #               deg += 1
+ 
+         elif isinstance(x, dict):
+             for deg, e in x.iteritems():
+                 c = Rational(e)
+-                fmpq_poly_set_coeff_mpq(self.__poly, deg, c.value)
++                fmpq_poly_set_coeff_mpq(self._poly, deg, c.value)
+ 
+         elif isinstance(x, pari_gen):
+             k = self._parent.base_ring()
+@@ -281,7 +281,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+                                              is_gen=False, construct=construct)
+ 
+         elif isinstance(x, Polynomial_integer_dense_flint):
+-            fmpq_poly_set_fmpz_poly(self.__poly, (<Polynomial_integer_dense_flint>x).__poly)
++            fmpq_poly_set_fmpz_poly(self._poly, (<Polynomial_integer_dense_flint>x)._poly)
+ 
+         elif isinstance(x, Polynomial):
+             k = self._parent.base_ring()
+@@ -329,7 +329,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             True
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        fmpq_poly_set(res.__poly, self.__poly)
++        fmpq_poly_set(res._poly, self._poly)
+         return res
+ 
+     def _singular_(self, singular=singular_default):
+@@ -364,7 +364,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: g.list()
+             []
+         """
+-        cdef unsigned long length = fmpq_poly_length(self.__poly)
++        cdef unsigned long length = fmpq_poly_length(self._poly)
+         return [self.get_unsafe(n) for n in range(length)]
+ 
+     ###########################################################################
+@@ -392,7 +392,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: type(f.degree())
+             <class 'sage.rings.integer.Integer'>
+         """
+-        return smallInteger(fmpq_poly_degree(self.__poly))
++        return smallInteger(fmpq_poly_degree(self._poly))
+ 
+     cdef get_unsafe(self, Py_ssize_t n):
+         """
+@@ -413,7 +413,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             1/2*t^2 + t + 1
+         """
+         cdef Rational z = Rational.__new__(Rational)
+-        fmpq_poly_get_coeff_mpq(z.value, self.__poly, n)
++        fmpq_poly_get_coeff_mpq(z.value, self._poly, n)
+         return z
+ 
+     cpdef _unsafe_mutate(self, unsigned long n, value):
+@@ -434,24 +434,24 @@ cdef class Polynomial_rational_flint(Polynomial):
+         rely on this convention.  This method should be used only with the
+         utmost care.
+         """
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if isinstance(value, int):
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_si(self.__poly, n, value)
++            fmpq_poly_set_coeff_si(self._poly, n, value)
+             if do_sig: sig_off()
+         elif isinstance(value, Integer):
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_mpz(self.__poly, n, (<Integer> value).value)
++            fmpq_poly_set_coeff_mpz(self._poly, n, (<Integer> value).value)
+             if do_sig: sig_off()
+         elif isinstance(value, Rational):
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_mpq(self.__poly, n, (<Rational> value).value)
++            fmpq_poly_set_coeff_mpq(self._poly, n, (<Rational> value).value)
+             if do_sig: sig_off()
+         else:
+             value = Rational(value)
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_set_coeff_mpq(self.__poly, n, (<Rational> value).value)
++            fmpq_poly_set_coeff_mpq(self._poly, n, (<Rational> value).value)
+             if do_sig: sig_off()
+ 
+     def __call__(self, *x, **kwds):
+@@ -501,20 +501,20 @@ cdef class Polynomial_rational_flint(Polynomial):
+             if isinstance(a, Polynomial_rational_flint):
+                 f = (<Polynomial_rational_flint> a)._new()
+                 sig_str("FLINT exception")
+-                fmpq_poly_compose(f.__poly, self.__poly,
+-                    (<Polynomial_rational_flint> a).__poly)
++                fmpq_poly_compose(f._poly, self._poly,
++                    (<Polynomial_rational_flint> a)._poly)
+                 sig_off()
+                 return f
+             elif isinstance(a, Rational):
+                 r = Rational.__new__(Rational)
+                 sig_str("FLINT exception")
+-                fmpq_poly_evaluate_mpq(r.value, self.__poly, (<Rational> a).value)
++                fmpq_poly_evaluate_mpq(r.value, self._poly, (<Rational> a).value)
+                 sig_off()
+                 return r
+             elif isinstance(a, Integer):
+                 r = Rational.__new__(Rational)
+                 sig_str("FLINT exception")
+-                fmpq_poly_evaluate_mpz(r.value, self.__poly, (<Integer> a).value)
++                fmpq_poly_evaluate_mpz(r.value, self._poly, (<Integer> a).value)
+                 sig_off()
+                 return r
+             elif isinstance(a, int):
+@@ -523,7 +523,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+                 fmpz_init(tmpfz)
+                 fmpq_init(tmpfq)
+                 fmpz_set_si(tmpfz, PyInt_AS_LONG(a))
+-                fmpq_poly_evaluate_fmpz(tmpfq, self.__poly, tmpfz)
++                fmpq_poly_evaluate_fmpz(tmpfq, self._poly, tmpfz)
+                 fmpq_get_mpq(r.value, tmpfq)
+                 fmpq_clear(tmpfq)
+                 fmpz_clear(tmpfz)
+@@ -533,18 +533,18 @@ cdef class Polynomial_rational_flint(Polynomial):
+                 arb_a = <RealBall> a
+                 arb_z = arb_a._new()
+                 sig_on()
+-                _arb_fmpz_poly_evaluate_arb(arb_z.value, fmpq_poly_numref(self.__poly),
+-                        fmpq_poly_length(self.__poly), arb_a.value, arb_a._parent._prec)
+-                arb_div_fmpz(arb_z.value, arb_z.value, fmpq_poly_denref(self.__poly), arb_a._parent._prec)
++                _arb_fmpz_poly_evaluate_arb(arb_z.value, fmpq_poly_numref(self._poly),
++                        fmpq_poly_length(self._poly), arb_a.value, arb_a._parent._prec)
++                arb_div_fmpz(arb_z.value, arb_z.value, fmpq_poly_denref(self._poly), arb_a._parent._prec)
+                 sig_off()
+                 return arb_z
+             if isinstance(a, ComplexBall):
+                 acb_a = <ComplexBall> a
+                 acb_z = acb_a._new()
+                 sig_on()
+-                _arb_fmpz_poly_evaluate_acb(acb_z.value, fmpq_poly_numref(self.__poly),
+-                        fmpq_poly_length(self.__poly), acb_a.value, acb_a._parent._prec)
+-                acb_div_fmpz(acb_z.value, acb_z.value, fmpq_poly_denref(self.__poly), acb_a._parent._prec)
++                _arb_fmpz_poly_evaluate_acb(acb_z.value, fmpq_poly_numref(self._poly),
++                        fmpq_poly_length(self._poly), acb_a.value, acb_a._parent._prec)
++                acb_div_fmpz(acb_z.value, acb_z.value, fmpq_poly_denref(self._poly), acb_a._parent._prec)
+                 sig_off()
+                 return acb_z
+ 
+@@ -570,14 +570,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res
+         cdef bint do_sig
+ 
+-        if (n >= fmpq_poly_length(self.__poly)):
++        if (n >= fmpq_poly_length(self._poly)):
+             return self
+         else:
+             res = self._new()
+             if n > 0:
+-                do_sig = _do_sig(self.__poly)
++                do_sig = _do_sig(self._poly)
+                 if do_sig: sig_str("FLINT exception")
+-                fmpq_poly_get_slice(res.__poly, self.__poly, 0, n)
++                fmpq_poly_get_slice(res._poly, self._poly, 0, n)
+                 if do_sig: sig_off()
+             return res
+ 
+@@ -664,7 +664,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef bint do_sig
+ 
+         if degree is None:
+-            len = fmpq_poly_length(self.__poly)
++            len = fmpq_poly_length(self._poly)
+         else:
+             try:
+                 len = <unsigned long> (degree + 1)
+@@ -672,9 +672,9 @@ cdef class Polynomial_rational_flint(Polynomial):
+                 raise ValueError('degree must be convertible to long')
+ 
+         res = self._new()
+-        do_sig = _do_sig(self.__poly)
++        do_sig = _do_sig(self._poly)
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_reverse(res.__poly, self.__poly, len)
++        fmpq_poly_reverse(res._poly, self._poly, len)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -709,7 +709,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             raise ValueError("self must have constant coefficient 0 and a unit for coefficient {}^1".format(self.parent().gen()))
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_revert_series(res.__poly, self.__poly, m)
++        fmpq_poly_revert_series(res._poly, self._poly, m)
+         sig_off()
+ 
+         return res
+@@ -731,7 +731,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: R(0).is_zero()
+             True
+         """
+-        return fmpq_poly_is_zero(self.__poly)
++        return fmpq_poly_is_zero(self._poly)
+ 
+     cpdef bint is_one(self) except -1:
+         r"""
+@@ -751,7 +751,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: R([1,1]).is_one()
+             False
+         """
+-        return fmpq_poly_is_one(self.__poly)
++        return fmpq_poly_is_one(self._poly)
+ 
+     def __bool__(self):
+         """
+@@ -766,7 +766,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: bool(R(0))
+             False
+         """
+-        return not fmpq_poly_is_zero(self.__poly)
++        return not fmpq_poly_is_zero(self._poly)
+ 
+     ###########################################################################
+     # Shifting                                                                #
+@@ -794,14 +794,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res
+         cdef bint do_sig
+ 
+-        if k == 0 or fmpq_poly_is_zero(f.__poly):
++        if k == 0 or fmpq_poly_is_zero(f._poly):
+             return self
+         else:
+             res = f._new()
+-            do_sig = fmpq_poly_length(f.__poly) > 5000 or n > 5000
++            do_sig = fmpq_poly_length(f._poly) > 5000 or n > 5000
+ 
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_shift_left(res.__poly, f.__poly, k)
++            fmpq_poly_shift_left(res._poly, f._poly, k)
+             if do_sig: sig_off()
+             return res
+ 
+@@ -822,14 +822,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res
+         cdef bint do_sig
+ 
+-        if k == 0 or fmpq_poly_is_zero(f.__poly):
++        if k == 0 or fmpq_poly_is_zero(f._poly):
+             return self
+         else:
+             res = f._new()
+-            do_sig = _do_sig(f.__poly)
++            do_sig = _do_sig(f._poly)
+ 
+             if do_sig: sig_str("FLINT exception")
+-            fmpq_poly_shift_right(res.__poly, f.__poly, k)
++            fmpq_poly_shift_right(res._poly, f._poly, k)
+             if do_sig: sig_off()
+             return res
+ 
+@@ -858,10 +858,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_add(res.__poly, self.__poly, op2.__poly)
++        fmpq_poly_add(res._poly, self._poly, op2._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -886,10 +886,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_sub(res.__poly, self.__poly, op2.__poly)
++        fmpq_poly_sub(res._poly, self._poly, op2._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -912,10 +912,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             True
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_neg(res.__poly, self.__poly)
++        fmpq_poly_neg(res._poly, self._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -945,8 +945,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint rr = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_divrem(qq.__poly, rr.__poly, self.__poly,
+-                         (<Polynomial_rational_flint> right).__poly)
++        fmpq_poly_divrem(qq._poly, rr._poly, self._poly,
++                         (<Polynomial_rational_flint> right)._poly)
+         sig_off()
+         return qq, rr
+ 
+@@ -974,8 +974,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_gcd(res.__poly, self.__poly,
+-                (<Polynomial_rational_flint> right).__poly)
++        fmpq_poly_gcd(res._poly, self._poly,
++                (<Polynomial_rational_flint> right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1001,8 +1001,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint res = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_lcm(res.__poly, self.__poly,
+-                      (<Polynomial_rational_flint> right).__poly)
++        fmpq_poly_lcm(res._poly, self._poly,
++                      (<Polynomial_rational_flint> right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1043,7 +1043,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef Polynomial_rational_flint t = self._new()
+ 
+         sig_str("FLINT exception")
+-        fmpq_poly_xgcd(d.__poly, s.__poly, t.__poly, self.__poly, (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_xgcd(d._poly, s._poly, t._poly, self._poly, (<Polynomial_rational_flint>right)._poly)
+         sig_off()
+         return d, s, t
+ 
+@@ -1069,10 +1069,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_mul(res.__poly, self.__poly, op2.__poly)
++        fmpq_poly_mul(res._poly, self._poly, op2._poly)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -1103,13 +1103,13 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         cdef Polynomial_rational_flint op2 = <Polynomial_rational_flint> right
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly) or _do_sig(op2.__poly)
++        cdef bint do_sig = _do_sig(self._poly) or _do_sig(op2._poly)
+ 
+         if n <= 0:
+             raise ValueError("n must be > 0")
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_mullow(res.__poly, self.__poly, op2.__poly, n)
++        fmpq_poly_mullow(res._poly, self._poly, op2._poly, n)
+         if do_sig: sig_off()
+         return res
+ 
+@@ -1125,10 +1125,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             9*t^3 - 6*t + 2
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_scalar_mul_mpq(res.__poly, self.__poly,
++        fmpq_poly_scalar_mul_mpq(res._poly, self._poly,
+                                  (<Rational> left).value)
+         if do_sig: sig_off()
+         return res
+@@ -1145,10 +1145,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             9*t^3 - 6*t + 2
+         """
+         cdef Polynomial_rational_flint res = self._new()
+-        cdef bint do_sig = _do_sig(self.__poly)
++        cdef bint do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_scalar_mul_mpq(res.__poly, self.__poly,
++        fmpq_poly_scalar_mul_mpq(res._poly, self._poly,
+                                  (<Rational> right).value)
+         if do_sig: sig_off()
+         return res
+@@ -1272,27 +1272,27 @@ cdef class Polynomial_rational_flint(Polynomial):
+             num = r.numerator()
+             den = r.denominator()
+ 
+-            if fmpq_poly_degree(self.__poly) == 0:
++            if fmpq_poly_degree(self._poly) == 0:
+                 return self.parent()(self[0].nth_root(den) ** num)
+ 
+             return self.nth_root(den) ** num
+ 
+         else:
+             if n < 0:
+-                if fmpq_poly_is_zero(self.__poly):
++                if fmpq_poly_is_zero(self._poly):
+                     raise ZeroDivisionError("negative exponent in power of zero")
+                 res = self._new()
+                 sig_str("FLINT exception")
+-                fmpq_poly_pow(res.__poly, self.__poly, -n)
++                fmpq_poly_pow(res._poly, self._poly, -n)
+                 sig_off()
+                 return ~res
+             else:
+                 res = self._new()
+                 sig_str("FLINT exception")
+                 if self._is_gen:
+-                    fmpq_poly_set_coeff_si(res.__poly, n, 1)
++                    fmpq_poly_set_coeff_si(res._poly, n, 1)
+                 else:
+-                    fmpq_poly_pow(res.__poly, self.__poly, n)
++                    fmpq_poly_pow(res._poly, self._poly, n)
+                 sig_off()
+                 return res
+ 
+@@ -1328,10 +1328,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+         if not isinstance(right, Polynomial_rational_flint):
+             if right in QQ:
+                 res = self._new()
+-                do_sig = _do_sig(self.__poly)
++                do_sig = _do_sig(self._poly)
+ 
+                 if do_sig: sig_str("FLINT exception")
+-                fmpq_poly_scalar_div_mpq(res.__poly, self.__poly,
++                fmpq_poly_scalar_div_mpq(res._poly, self._poly,
+                                                   (<Rational> QQ(right)).value)
+                 if do_sig: sig_off()
+                 return res
+@@ -1340,8 +1340,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+ 
+         res = self._new()
+         sig_str("FLINT exception")
+-        fmpq_poly_div(res.__poly, self.__poly,
+-                                     (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_div(res._poly, self._poly,
++                                     (<Polynomial_rational_flint>right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1381,15 +1381,15 @@ cdef class Polynomial_rational_flint(Polynomial):
+         """
+         if prec <= 0:
+             raise ValueError("the precision must be positive, got {}".format(prec))
+-        if fmpq_poly_degree(self.__poly) == -1 or \
+-           fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        if fmpq_poly_degree(self._poly) == -1 or \
++           fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term is zero")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         if prec <= 0:
+             return res
+         sig_on()
+-        fmpq_poly_inv_series(res.__poly, self.__poly, prec)
++        fmpq_poly_inv_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1423,8 +1423,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+ 
+         res = self._new()
+         sig_str("FLINT exception")
+-        fmpq_poly_rem(res.__poly, self.__poly,
+-                                     (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_rem(res._poly, self._poly,
++                                     (<Polynomial_rational_flint>right)._poly)
+         sig_off()
+         return res
+ 
+@@ -1453,7 +1453,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+         Polynomial_integer_dense_flint.__init__(num, parent, x=None,
+                                     check=False, is_gen=False, construct=False)
+         sig_str("FLINT exception")
+-        fmpq_poly_get_numerator(num.__poly, self.__poly)
++        fmpq_poly_get_numerator(num._poly, self._poly)
+         sig_off()
+         return num
+ 
+@@ -1469,10 +1469,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             3
+         """
+         cdef Integer den = Integer.__new__(Integer)
+-        if fmpq_poly_denref(self.__poly) is NULL:
++        if fmpq_poly_denref(self._poly) is NULL:
+             mpz_set_ui(den.value, 1)
+         else:
+-            fmpz_get_mpz(den.value, <fmpz *> fmpq_poly_denref(self.__poly))
++            fmpz_get_mpz(den.value, <fmpz *> fmpq_poly_denref(self._poly))
+         return den
+ 
+     def _derivative(self, var = None):
+@@ -1517,10 +1517,10 @@ cdef class Polynomial_rational_flint(Polynomial):
+             raise ValueError("cannot differentiate with respect to {}".format(var))
+ 
+         der = self._new()
+-        do_sig = _do_sig(self.__poly)
++        do_sig = _do_sig(self._poly)
+ 
+         if do_sig: sig_str("FLINT exception")
+-        fmpq_poly_derivative(der.__poly, self.__poly)
++        fmpq_poly_derivative(der._poly, self._poly)
+         if do_sig: sig_off()
+         return der
+ 
+@@ -1574,8 +1574,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+         cdef fmpq_t t
+         fmpq_init(t)
+         sig_str("FLINT exception")
+-        fmpq_poly_resultant(t, self.__poly,
+-                            (<Polynomial_rational_flint>right).__poly)
++        fmpq_poly_resultant(t, self._poly,
++                            (<Polynomial_rational_flint>right)._poly)
+         fmpq_get_mpq(res.value, t)
+         sig_off()
+         fmpq_clear(t)
+@@ -1623,7 +1623,7 @@ cdef class Polynomial_rational_flint(Polynomial):
+ 
+         """
+         cdef Polynomial_integer_dense_flint primitive
+-        cdef unsigned long length = fmpq_poly_length(self.__poly)
++        cdef unsigned long length = fmpq_poly_length(self._poly)
+ 
+         if length < 2:
+             return False
+@@ -1636,8 +1636,8 @@ cdef class Polynomial_rational_flint(Polynomial):
+                              x=None, check=True, is_gen=False, construct=False)
+ 
+             sig_str("FLINT exception")
+-            fmpq_poly_get_numerator(primitive.__poly, self.__poly)
+-            fmpz_poly_primitive_part(primitive.__poly, primitive.__poly)
++            fmpq_poly_get_numerator(primitive._poly, self._poly)
++            fmpz_poly_primitive_part(primitive._poly, primitive._poly)
+             sig_off()
+             return primitive.is_irreducible()
+ 
+@@ -1669,14 +1669,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             ...
+             ValueError: constant term should be 1 in order to take logarithm
+         """
+-        if fmpq_poly_degree(self.__poly) == -1 or \
+-           fmpz_cmp(fmpq_poly_numref(self.__poly),
+-                    fmpq_poly_denref(self.__poly)):
++        if fmpq_poly_degree(self._poly) == -1 or \
++           fmpz_cmp(fmpq_poly_numref(self._poly),
++                    fmpq_poly_denref(self._poly)):
+             raise ValueError("constant term should be 1 in order to take logarithm")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_log_series(res.__poly, self.__poly, prec)
++        fmpq_poly_log_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1703,14 +1703,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.one()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take exponential")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_exp_series(res.__poly, self.__poly, prec)
++        fmpq_poly_exp_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1737,14 +1737,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take arctangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_atan_series(res.__poly, self.__poly, prec)
++        fmpq_poly_atan_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1768,14 +1768,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic arctangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_atanh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_atanh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1802,14 +1802,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take arcsine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_asin_series(res.__poly, self.__poly, prec)
++        fmpq_poly_asin_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1837,14 +1837,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic arcsine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_asinh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_asinh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1871,14 +1871,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take tangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_tan_series(res.__poly, self.__poly, prec)
++        fmpq_poly_tan_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1905,14 +1905,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take sine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_sin_series(res.__poly, self.__poly, prec)
++        fmpq_poly_sin_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1937,14 +1937,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take cosine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_cos_series(res.__poly, self.__poly, prec)
++        fmpq_poly_cos_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -1969,14 +1969,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic sine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_sinh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_sinh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -2007,14 +2007,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.one()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic cosine")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_cosh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_cosh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+@@ -2040,14 +2040,14 @@ cdef class Polynomial_rational_flint(Polynomial):
+             sage: _.parent()
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if fmpq_poly_degree(self.__poly) == -1:
++        if fmpq_poly_degree(self._poly) == -1:
+             return self._parent.zero()
+-        elif not fmpz_is_zero(fmpq_poly_numref(self.__poly)):
++        elif not fmpz_is_zero(fmpq_poly_numref(self._poly)):
+             raise ValueError("constant term should be 0 in order to take hyperbolic tangent")
+ 
+         cdef Polynomial_rational_flint res = self._new()
+         sig_on()
+-        fmpq_poly_tanh_series(res.__poly, self.__poly, prec)
++        fmpq_poly_tanh_series(res._poly, self._poly, prec)
+         sig_off()
+         return res
+ 
+diff --git a/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx b/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx
+index fbe96d186c5..955f83468e4 100644
+--- a/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx
++++ b/src/sage/rings/polynomial/polynomial_real_mpfr_dense.pyx
+@@ -116,7 +116,7 @@ cdef class PolynomialRealDense(Polynomial):
+         Polynomial.__init__(self, parent, is_gen=is_gen)
+         self._base_ring = parent._base
+         cdef Py_ssize_t i, degree
+-        cdef int prec = self._base_ring.__prec
++        cdef int prec = self._base_ring._prec
+         cdef mpfr_rnd_t rnd = self._base_ring.rnd
+         if x is None:
+             self._coeffs = <mpfr_t*>check_allocarray(1, sizeof(mpfr_t)) # degree zero
+@@ -227,7 +227,7 @@ cdef class PolynomialRealDense(Polynomial):
+ 
+     cdef PolynomialRealDense _new(self, Py_ssize_t degree):
+         cdef Py_ssize_t i
+-        cdef int prec = self._base_ring.__prec
++        cdef int prec = self._base_ring._prec
+         cdef PolynomialRealDense f = <PolynomialRealDense>PolynomialRealDense.__new__(PolynomialRealDense)
+         f._parent = self._parent
+         f._base_ring = self._base_ring
+@@ -501,7 +501,7 @@ cdef class PolynomialRealDense(Polynomial):
+         else:
+             f = left._new(left._degree + right._degree)
+         sig_on()
+-        mpfr_init2(tmp, left._base_ring.__prec)
++        mpfr_init2(tmp, left._base_ring._prec)
+         for i from 0 <= i <= f._degree:
+             # Yes, we could make this more efficient by initializing with
+             # a multiple of left rather than all zeros...
+@@ -661,7 +661,7 @@ cdef class PolynomialRealDense(Polynomial):
+         q = self._new(self._degree - other._degree)
+         # This is the standard division algorithm
+         sig_on()
+-        mpfr_init2(tmp, self._base_ring.__prec)
++        mpfr_init2(tmp, self._base_ring._prec)
+         for i from self._degree >= i >= other._degree:
+             mpfr_set(q._coeffs[i-other._degree], r._coeffs[i], rnd)
+             for j from 0 <= j < other._degree:
+@@ -725,7 +725,7 @@ cdef class PolynomialRealDense(Polynomial):
+         cdef RealNumber x = <RealNumber>xx
+         cdef RealNumber res
+ 
+-        if (<RealField_class>x._parent).__prec < self._base_ring.__prec:
++        if (<RealField_class>x._parent)._prec < self._base_ring._prec:
+             res = RealNumber(x._parent)
+         else:
+             res = RealNumber(self._base_ring)
+diff --git a/src/sage/rings/polynomial/polynomial_zmod_flint.pyx b/src/sage/rings/polynomial/polynomial_zmod_flint.pyx
+index 253ab949fcc..4c480673861 100644
+--- a/src/sage/rings/polynomial/polynomial_zmod_flint.pyx
++++ b/src/sage/rings/polynomial/polynomial_zmod_flint.pyx
+@@ -110,7 +110,7 @@ cdef class Polynomial_zmod_flint(Polynomial_template):
+             return
+         elif isinstance(x, Polynomial_integer_dense_flint):
+             Polynomial_template.__init__(self, parent, 0, check, is_gen, construct)
+-            self._set_fmpz_poly((<Polynomial_integer_dense_flint>x).__poly)
++            self._set_fmpz_poly((<Polynomial_integer_dense_flint>x)._poly)
+             return
+         else:
+             if isinstance(x, ntl_zz_pX):
+diff --git a/src/sage/rings/power_series_mpoly.pxd b/src/sage/rings/power_series_mpoly.pxd
+index f822ecc1227..d358ada1356 100644
+--- a/src/sage/rings/power_series_mpoly.pxd
++++ b/src/sage/rings/power_series_mpoly.pxd
+@@ -3,6 +3,6 @@ from .power_series_ring_element cimport PowerSeries
+ 
+ cdef class PowerSeries_mpoly(PowerSeries):
+     cdef ModuleElement __f
+-    cdef object __poly
++    cdef object _poly
+     cdef object __list
+     cdef bint _truncated
+diff --git a/src/sage/rings/power_series_mpoly.pyx b/src/sage/rings/power_series_mpoly.pyx
+index 0c901a3557b..be59294e75b 100644
+--- a/src/sage/rings/power_series_mpoly.pyx
++++ b/src/sage/rings/power_series_mpoly.pyx
+@@ -65,7 +65,7 @@ cdef class PowerSeries_mpoly(PowerSeries):
+ 
+     def __reduce__(self):
+         # do *not* delete old versions.
+-        return make_powerseries_mpoly_v0, (self._parent, self.__f, self._prec, self.__is_gen)
++        return make_powerseries_mpoly_v0, (self._parent, self.__f, self._prec, self._is_gen)
+ 
+     def __call__(self, *args, **kwds):
+         if len(kwds) == 0 and len(args) == 1:
+@@ -92,10 +92,10 @@ cdef class PowerSeries_mpoly(PowerSeries):
+         return self.__list
+ 
+     def polynomial(self):
+-        if self.__poly is None:
++        if self._poly is None:
+             S = self.parent()._mpoly_ring()
+-            self.__poly = self.__f.polynomial(S.gens()[-1])
+-        return self.__poly
++            self._poly = self.__f.polynomial(S.gens()[-1])
++        return self._poly
+ 
+     def _mpoly(self):
+         return self.__f
+diff --git a/src/sage/rings/power_series_poly.pyx b/src/sage/rings/power_series_poly.pyx
+index 7c93168d4b1..6cacab1f0c8 100644
+--- a/src/sage/rings/power_series_poly.pyx
++++ b/src/sage/rings/power_series_poly.pyx
+@@ -97,7 +97,7 @@ cdef class PowerSeries_poly(PowerSeries):
+             sage: f == loads(dumps(f)) # indirect doctest
+             True
+         """
+-        return self.__class__, (self._parent, self.__f, self._prec, self.__is_gen)
++        return self.__class__, (self._parent, self.__f, self._prec, self._is_gen)
+ 
+     def polynomial(self):
+         """
+diff --git a/src/sage/rings/power_series_ring_element.pxd b/src/sage/rings/power_series_ring_element.pxd
+index 067c4f3c6d4..e5c031ee147 100644
+--- a/src/sage/rings/power_series_ring_element.pxd
++++ b/src/sage/rings/power_series_ring_element.pxd
+@@ -1,7 +1,7 @@
+ from sage.structure.element cimport AlgebraElement, RingElement
+ 
+ cdef class PowerSeries(AlgebraElement):
+-    cdef char __is_gen
++    cdef char _is_gen
+     cdef _prec
+     cdef common_prec_c(self, PowerSeries other)
+     #_prec(self, RingElement right_r)
+diff --git a/src/sage/rings/power_series_ring_element.pyx b/src/sage/rings/power_series_ring_element.pyx
+index 54314d538ed..e5e2df79e1b 100644
+--- a/src/sage/rings/power_series_ring_element.pyx
++++ b/src/sage/rings/power_series_ring_element.pyx
+@@ -159,7 +159,7 @@ cdef class PowerSeries(AlgebraElement):
+              over Finite Field of size 3
+         """
+         AlgebraElement.__init__(self, parent)
+-        self.__is_gen = is_gen
++        self._is_gen = is_gen
+         self._prec = prec
+ 
+     def __hash__(self):
+@@ -234,7 +234,7 @@ cdef class PowerSeries(AlgebraElement):
+             sage: 1*t == t
+             True
+         """
+-        return bool(self.__is_gen)
++        return bool(self._is_gen)
+ 
+     def _im_gens_(self, codomain, im_gens, base_map=None):
+         """
+diff --git a/src/sage/rings/real_mpfi.pxd b/src/sage/rings/real_mpfi.pxd
+index 959a650aafc..4201788d198 100644
+--- a/src/sage/rings/real_mpfi.pxd
++++ b/src/sage/rings/real_mpfi.pxd
+@@ -11,7 +11,7 @@ from .real_mpfr cimport RealField_class
+ cdef class RealIntervalFieldElement(RingElement)  # forward decl
+ 
+ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+-    cdef mpfr_prec_t __prec
++    cdef mpfr_prec_t _prec
+     cdef bint sci_not
+     # Cache RealField instances for the lower, upper, and middle bounds.
+     # These have the same precision as the interval field;
+diff --git a/src/sage/rings/real_mpfi.pyx b/src/sage/rings/real_mpfi.pyx
+index 1193a14baff..509f6f63da0 100644
+--- a/src/sage/rings/real_mpfi.pyx
++++ b/src/sage/rings/real_mpfi.pyx
+@@ -526,7 +526,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         if prec < MPFR_PREC_MIN or prec > MPFR_PREC_MAX:
+             raise ValueError("prec (=%s) must be >= %s and <= %s." % (
+                 prec, MPFR_PREC_MIN, MPFR_PREC_MAX))
+-        self.__prec = prec
++        self._prec = prec
+         self.sci_not = sci_not
+         self.__lower_field = RealField(prec, sci_not, "RNDD")
+         self.__middle_field = RealField(prec, sci_not, "RNDN")
+@@ -598,7 +598,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         elif rnd == "RNDU":
+             return self.upper_field()
+         else:
+-            return RealField(self.__prec, self.sci_not, rnd)
++            return RealField(self._prec, self.sci_not, rnd)
+ 
+     def _repr_(self):
+         """
+@@ -611,7 +611,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RealIntervalField(200) # indirect doctest
+             Real Interval Field with 200 bits of precision
+         """
+-        s = "Real Interval Field with %s bits of precision"%self.__prec
++        s = "Real Interval Field with %s bits of precision"%self._prec
+         return s
+ 
+     def _latex_(self):
+@@ -802,7 +802,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RIF.has_coerce_map_from(float)
+             False
+         """
+-        prec = self.__prec
++        prec = self._prec
+ 
+         # Direct and efficient conversions
+         if S is ZZ or S is QQ:
+@@ -810,7 +810,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         if S is int or S is long:
+             return True
+         if isinstance(S, RealIntervalField_class):
+-            return (<RealIntervalField_class>S).__prec >= prec
++            return (<RealIntervalField_class>S)._prec >= prec
+         if isinstance(S, sage.rings.abc.NumberField_quadratic):
+             return S.discriminant() > 0
+ 
+@@ -844,7 +844,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+         cdef RealIntervalField_class right
+         left = self
+         right = other  # to access C structure
+-        return richcmp(left.__prec, right.__prec, op)
++        return richcmp(left._prec, right._prec, op)
+ 
+     def __reduce__(self):
+         """
+@@ -856,7 +856,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: loads(dumps(R)) == R
+             True
+         """
+-        return __create__RealIntervalField_version0, (self.__prec, self.sci_not)
++        return __create__RealIntervalField_version0, (self._prec, self.sci_not)
+ 
+     def random_element(self, *args, **kwds):
+         """
+@@ -997,7 +997,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RealIntervalField(200).name()
+             'IntervalRealIntervalField200'
+         """
+-        return "IntervalRealIntervalField%s"%(self.__prec)
++        return "IntervalRealIntervalField%s"%(self._prec)
+ 
+     def __hash__(self):
+         """
+@@ -1023,7 +1023,7 @@ cdef class RealIntervalField_class(sage.rings.abc.RealIntervalField):
+             sage: RealIntervalField(200).precision()
+             200
+         """
+-        return self.__prec
++        return self._prec
+ 
+     prec = precision
+ 
+@@ -1187,7 +1187,7 @@ cdef class RealIntervalFieldElement(RingElement):
+             sage: TestSuite(x).run(skip=["_test_eq", "_test_pickling"])
+         """
+         cdef RealIntervalField_class p = <RealIntervalField_class?>parent
+-        mpfi_init2(self.value, p.__prec)
++        mpfi_init2(self.value, p._prec)
+         self._parent = p
+ 
+     def __init__(self, parent, x, int base=10):
+@@ -1864,7 +1864,7 @@ cdef class RealIntervalFieldElement(RingElement):
+ 
+         cdef mp_exp_t self_exp
+         cdef mpz_t self_zz
+-        cdef mpfr_prec_t prec = (<RealIntervalField_class>self._parent).__prec
++        cdef mpfr_prec_t prec = (<RealIntervalField_class>self._parent)._prec
+         cdef char *zz_str
+         cdef size_t zz_str_maxlen
+ 
+@@ -2977,7 +2977,7 @@ cdef class RealIntervalFieldElement(RingElement):
+             sage: RealIntervalField(200)(2.1).precision()
+             200
+         """
+-        return (<RealIntervalField_class>self._parent).__prec
++        return (<RealIntervalField_class>self._parent)._prec
+ 
+     prec = precision
+ 
+diff --git a/src/sage/rings/real_mpfr.pxd b/src/sage/rings/real_mpfr.pxd
+index 3549eccfd03..dd18e87715b 100644
+--- a/src/sage/rings/real_mpfr.pxd
++++ b/src/sage/rings/real_mpfr.pxd
+@@ -9,7 +9,7 @@ from sage.libs.mpfr.types cimport mpfr_prec_t
+ cdef class RealNumber(sage.structure.element.RingElement)  # forward decl
+ 
+ cdef class RealField_class(sage.rings.abc.RealField):
+-    cdef mpfr_prec_t __prec
++    cdef mpfr_prec_t _prec
+     cdef bint sci_not
+     cdef mpfr_rnd_t rnd
+     cdef object rnd_str
+diff --git a/src/sage/rings/real_mpfr.pyx b/src/sage/rings/real_mpfr.pyx
+index ea7ff07a216..7440fadd265 100644
+--- a/src/sage/rings/real_mpfr.pyx
++++ b/src/sage/rings/real_mpfr.pyx
+@@ -524,7 +524,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+         if prec < MPFR_PREC_MIN or prec > MPFR_PREC_MAX:
+             raise ValueError("prec (=%s) must be >= %s and <= %s" % (
+                 prec, MPFR_PREC_MIN, MPFR_PREC_MAX))
+-        self.__prec = prec
++        self._prec = prec
+         self.sci_not = sci_not
+ 
+         self.rnd = <mpfr_rnd_t>rnd
+@@ -561,7 +561,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: RealField(17,rnd='RNDD') # indirect doctest
+             Real Field with 17 bits of precision and rounding RNDD
+         """
+-        s = "Real Field with %s bits of precision"%self.__prec
++        s = "Real Field with %s bits of precision"%self._prec
+         if self.rnd != MPFR_RNDN:
+             s = s + " and rounding %s"%(self.rnd_str)
+         return s
+@@ -733,13 +733,13 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             return ZZtoRR(ZZ, self)
+         elif S is QQ:
+             return QQtoRR(QQ, self)
+-        elif (S is RDF or S is float) and self.__prec <= 53:
++        elif (S is RDF or S is float) and self._prec <= 53:
+             return double_toRR(S, self)
+         elif S is long:
+             return int_toRR(long, self)
+         elif S is int:
+             return int_toRR(int, self)
+-        elif isinstance(S, RealField_class) and S.prec() >= self.__prec:
++        elif isinstance(S, RealField_class) and S.prec() >= self._prec:
+             return RRtoRR(S, self)
+         elif QQ.has_coerce_map_from(S):
+             return QQtoRR(QQ, self) * QQ._internal_coerce_map_from(S)
+@@ -786,7 +786,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             return NotImplemented
+ 
+         _other = <RealField_class>other  # to access C structure
+-        return (self.__prec == _other.__prec and
++        return (self._prec == _other._prec and
+                 self.rnd == _other.rnd) == (op == Py_EQ)
+ 
+     def __reduce__(self):
+@@ -799,7 +799,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: loads(dumps(R)) == R
+             True
+         """
+-        return __create__RealField_version0, (self.__prec, self.sci_not, self.rnd_str)
++        return __create__RealField_version0, (self._prec, self.sci_not, self.rnd_str)
+ 
+     def construction(self):
+         r"""
+@@ -968,7 +968,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: RealField(100,rnd='RNDU').name()
+             'RealField100_2'
+         """
+-        return "RealField%s_%s"%(self.__prec,self.rnd)
++        return "RealField%s_%s"%(self._prec,self.rnd)
+ 
+     def __hash__(self):
+         """
+@@ -995,7 +995,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: RealField(20).precision()
+             20
+         """
+-        return Integer(self.__prec)
++        return Integer(self._prec)
+ 
+     prec=precision # an alias
+ 
+@@ -1031,7 +1031,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             sage: R.to_prec(300)
+             Real Field with 300 bits of precision and rounding RNDZ
+         """
+-        if prec == self.__prec:
++        if prec == self._prec:
+             return self
+         else:
+             return RealField(prec, self.sci_not, self.rnd)
+@@ -1052,7 +1052,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             0.88622692545275801364908374167057259139877473
+         """
+         cdef RealNumber x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD: sig_on()
+         # The docs for mpfr_free_cache say "Free the cache used by
+         # the functions computing constants if needed (currently
+         # mpfr_const_log2, mpfr_const_pi and mpfr_const_euler)", so
+@@ -1062,7 +1062,7 @@ cdef class RealField_class(sage.rings.abc.RealField):
+         # functions, but this free is needed for them too!
+         mpfr_free_cache()
+         mpfr_const_pi(x.value, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def euler_constant(self):
+@@ -1091,10 +1091,10 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             0.91596559417721901505460351493
+         """
+         cdef RealNumber x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_free_cache()
+         mpfr_const_catalan(x.value, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log2(self):
+@@ -1111,10 +1111,10 @@ cdef class RealField_class(sage.rings.abc.RealField):
+             0.69314718055994530941723212146
+         """
+         cdef RealNumber x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_free_cache()
+         mpfr_const_log2(x.value, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def random_element(self, min=-1, max=1, distribution=None):
+@@ -1181,9 +1181,9 @@ cdef class RealField_class(sage.rings.abc.RealField):
+         if n < 0:
+             raise ArithmeticError("n must be nonnegative")
+         x = self._new()
+-        if self.__prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_on()
++        if self._prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_on()
+         mpfr_fac_ui(x.value, n, self.rnd)
+-        if self.__prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_off()
++        if self._prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def rounding_mode(self):
+@@ -1346,7 +1346,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             NaN
+         """
+         cdef RealField_class p = <RealField_class?>parent
+-        mpfr_init2(self.value, p.__prec)
++        mpfr_init2(self.value, p._prec)
+         self._parent = p
+ 
+     def __init__(self, parent, x=0, int base=10):
+@@ -1446,7 +1446,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             sage: numpy.array([1.000000000000000000000000000000000000]).dtype           # optional - numpy
+             dtype('O')
+         """
+-        if (<RealField_class>self._parent).__prec <= 53:
++        if (<RealField_class>self._parent)._prec <= 53:
+             return numpy_double_interface
+         else:
+             return numpy_object_interface
+@@ -2075,7 +2075,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             # This avoids the confusion a lot of people have with the last
+             # 1-2 binary digits being wrong due to rounding coming from
+             # representing numbers in binary.
+-            digits = <size_t>(((<RealField_class>self._parent).__prec - 1) * M_LN2_LN10)
++            digits = <size_t>(((<RealField_class>self._parent)._prec - 1) * M_LN2_LN10)
+             if digits < 2:
+                 digits = 2
+ 
+@@ -2303,7 +2303,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if sgn == 0:
+             return z
+ 
+-        cdef mpfr_prec_t prec = (<RealField_class>self._parent).__prec
++        cdef mpfr_prec_t prec = (<RealField_class>self._parent)._prec
+ 
+         if mpfr_inf_p(self.value):
+             mpz_set_ui(z.value, EXP_MAX+1-EXP_MIN)
+@@ -2757,7 +2757,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             sage: RealField(101)(-1).precision()
+             101
+         """
+-        return Integer((<RealField_class>self._parent).__prec)
++        return Integer((<RealField_class>self._parent)._prec)
+ 
+     prec = precision # alias
+ 
+@@ -3364,7 +3364,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         cdef unsigned long wordsize = sizeof(long)*8
+ 
+         cdef mpfr_prec_t prec
+-        prec = (<RealField_class>self._parent).__prec
++        prec = (<RealField_class>self._parent)._prec
+ 
+         # We round up the precision to the nearest multiple of wordsize.
+         cdef int rounded_prec
+@@ -3699,7 +3699,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         from .real_mpfi import RealIntervalField
+ 
+         cdef mpfr_rnd_t rnd = (<RealField_class>self._parent).rnd
+-        cdef mpfr_prec_t prec = (<RealField_class>self._parent).__prec
++        cdef mpfr_prec_t prec = (<RealField_class>self._parent)._prec
+ 
+         cdef RealNumber low, high
+         cdef int odd
+@@ -4249,9 +4249,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         cdef RealNumber x
+         if mpfr_cmp_ui(self.value, 0) >= 0:
+             x = self._new()
+-            if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_on()
++            if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_on()
+             mpfr_sqrt(x.value, self.value, (<RealField_class>self._parent).rnd)
+-            if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_off()
++            if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_off()
+             if all:
+                 if x.is_zero():
+                     return [x]
+@@ -4295,12 +4295,12 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             -1.42108547152020e-14
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_on()
+         mpfr_cbrt(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > 10*SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+-    def __pow(self, RealNumber exponent):
++    def _pow(self, RealNumber exponent):
+         """
+         Compute ``self`` raised to the power of exponent, rounded in the
+         direction specified by the parent of ``self``.
+@@ -4309,7 +4309,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+ 
+             sage: R = RealField(30)
+             sage: a = R('1.23456')
+-            sage: a.__pow(20.0)
++            sage: a._pow(20.0)
+             67.646297
+         """
+         cdef RealNumber x
+@@ -4435,9 +4435,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+                 return self._complex_number_().log(base)
+         if base is None or base == 'e':
+             x = self._new()
+-            if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++            if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+             mpfr_log(x.value, self.value, (<RealField_class>self._parent).rnd)
+-            if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++            if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+             return x
+         elif base == 10:
+             return self.log10()
+@@ -4476,9 +4476,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if self < 0:
+             return self._complex_number_().log(2)
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_log2(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log10(self):
+@@ -4513,9 +4513,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if self < 0:
+             return self._complex_number_().log(10)
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_log10(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log1p(self):
+@@ -4562,9 +4562,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         if self < -1:
+             return (self+1.0)._complex_number_().log()
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_log1p(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def exp(self):
+@@ -4620,9 +4620,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             1.89117248253021e-10
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_exp2(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def exp10(self):
+@@ -4648,9 +4648,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             5.01187233627276e-33
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_exp10(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def expm1(self):
+@@ -4672,9 +4672,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             1.00000000000000e-16
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_expm1(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def eint(self):
+@@ -4694,9 +4694,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             -0.219383934395520
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_eint(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         return x
+ 
+     def cos(self):
+@@ -5125,9 +5125,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             _other = self._parent(other)
+ 
+         x = self._new()
+-        if (<RealField_class>self._parent).__prec > 10000: sig_on()
++        if (<RealField_class>self._parent)._prec > 10000: sig_on()
+         mpfr_agm(x.value, self.value, _other.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > 10000: sig_off()
++        if (<RealField_class>self._parent)._prec > 10000: sig_off()
+         return x
+ 
+     def erf(self):
+@@ -5280,9 +5280,9 @@ cdef class RealNumber(sage.structure.element.RingElement):
+             0.886226925452758
+         """
+         cdef RealNumber x = self._new()
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_on()
+         mpfr_gamma(x.value, self.value, (<RealField_class>self._parent).rnd)
+-        if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off()
++        if (<RealField_class>self._parent)._prec > SIG_PREC_THRESHOLD: sig_off()
+         return x
+ 
+     def log_gamma(self):
+@@ -5306,10 +5306,10 @@ cdef class RealNumber(sage.structure.element.RingElement):
+         cdef RealNumber x = self._new()
+         parent = (<RealField_class>self._parent)
+         if not mpfr_sgn(self.value) < 0:
+-            if parent.__prec > SIG_PREC_THRESHOLD:
++            if parent._prec > SIG_PREC_THRESHOLD:
+                 sig_on()
+             mpfr_lngamma(x.value, self.value, parent.rnd)
+-            if parent.__prec > SIG_PREC_THRESHOLD:
++            if parent._prec > SIG_PREC_THRESHOLD:
+                 sig_off()
+             return x
+         from sage.libs.mpmath.utils import call
+@@ -5534,7 +5534,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+ 
+         cdef RealField_class fld = <RealField_class>self._parent
+ 
+-        if algorithm == 0 and n <= 10000 / fld.__prec:
++        if algorithm == 0 and n <= 10000 / fld._prec:
+             # This is a rough estimate for when it is probably
+             # faster to call mpfr directly.  (This is a pretty
+             # good estimate on one particular machine, a
+@@ -5639,7 +5639,7 @@ cdef class RealNumber(sage.structure.element.RingElement):
+ 
+         from .real_mpfi import RealIntervalField
+ 
+-        cdef mpfr_prec_t prec = fld.__prec + 10
++        cdef mpfr_prec_t prec = fld._prec + 10
+ 
+         cdef RealNumber lower
+         cdef RealNumber upper
+diff --git a/src/sage/rings/ring.pxd b/src/sage/rings/ring.pxd
+index 9384f39f258..1322697688f 100644
+--- a/src/sage/rings/ring.pxd
++++ b/src/sage/rings/ring.pxd
+@@ -7,7 +7,7 @@ cdef class Ring(ParentWithGens):
+     cdef public object _one_element
+     cdef public object _zero_ideal
+     cdef public object _unit_ideal
+-    cdef public object __ideal_monoid
++    cdef public object _ideal_monoid
+ 
+ 
+ cdef class CommutativeRing(Ring):
+diff --git a/src/sage/rings/ring.pyx b/src/sage/rings/ring.pyx
+index 4cba2c9ba7f..8acf4383270 100644
+--- a/src/sage/rings/ring.pyx
++++ b/src/sage/rings/ring.pyx
+@@ -325,12 +325,12 @@ cdef class Ring(ParentWithGens):
+              by the ideal (x*y + y*z, x*x + x*y - y*x - y*y)
+ 
+         """
+-        if self.__ideal_monoid is not None:
+-            return self.__ideal_monoid
++        if self._ideal_monoid is not None:
++            return self._ideal_monoid
+         else:
+             from sage.rings.noncommutative_ideals import IdealMonoid_nc
+             M = IdealMonoid_nc(self)
+-            self.__ideal_monoid = M
++            self._ideal_monoid = M
+             return M
+ 
+     def ideal(self, *args, **kwds):
+@@ -1106,12 +1106,12 @@ cdef class Ring(ParentWithGens):
+             sage: R.<x>=QQ[]; R.ideal_monoid()
+             Monoid of ideals of Univariate Polynomial Ring in x over Rational Field
+         """
+-        if self.__ideal_monoid is not None:
+-            return self.__ideal_monoid
++        if self._ideal_monoid is not None:
++            return self._ideal_monoid
+         else:
+             from sage.rings.ideal_monoid import IdealMonoid
+             M = IdealMonoid(self)
+-            self.__ideal_monoid = M
++            self._ideal_monoid = M
+             return M
+ 
+     @cached_method
+@@ -1345,12 +1345,12 @@ cdef class CommutativeRing(Ring):
+             sage: R.<x>=QQ[]; R.ideal_monoid()
+             Monoid of ideals of Univariate Polynomial Ring in x over Rational Field
+         """
+-        if self.__ideal_monoid is not None:
+-            return self.__ideal_monoid
++        if self._ideal_monoid is not None:
++            return self._ideal_monoid
+         else:
+             from sage.rings.ideal_monoid import IdealMonoid
+             M = IdealMonoid(self)
+-            self.__ideal_monoid = M
++            self._ideal_monoid = M
+             return M
+ 
+     def extension(self, poly, name=None, names=None, **kwds):
+diff --git a/src/sage/schemes/elliptic_curves/mod_sym_num.pyx b/src/sage/schemes/elliptic_curves/mod_sym_num.pyx
+index 65742f28d72..296a6b5d075 100644
+--- a/src/sage/schemes/elliptic_curves/mod_sym_num.pyx
++++ b/src/sage/schemes/elliptic_curves/mod_sym_num.pyx
+@@ -730,7 +730,7 @@ cdef class ModularSymbolNumerical:
+         double _eps_plus, _eps_minus, _eps_unitary_plus, _eps_unitary_minus
+         public RealNumber _om1, _om2
+         object _E, _epsQs, _Mt, _Epari
+-        public dict __cached_methods
++        public dict _cached_methods
+         Rational _twist_q
+         Integer _D
+         int _global_sign
+@@ -785,7 +785,7 @@ cdef class ModularSymbolNumerical:
+         self._set_epsQs()
+         self._initialise_an_coefficients()
+         self._set_den_bounds()
+-        self.__cached_methods = {}
++        self._cached_methods = {}
+ 
+         # self.nc_sums = Integer(0)
+         # self.nc_direct = Integer(0)
+@@ -1357,7 +1357,7 @@ cdef class ModularSymbolNumerical:
+             sage: M(0)
+             1/5
+         """
+-        cadi = self.__cached_methods
++        cadi = self._cached_methods
+         for me in cadi:
+             cadi[me].clear_cache()
+ 
+@@ -1833,7 +1833,7 @@ cdef class ModularSymbolNumerical:
+ 
+         # if called with a previous (m,z,eps) but a larger eps,
+         # return the cached value
+-        cac = self.__cached_methods['_kappa'].cache
++        cac = self._cached_methods['_kappa'].cache
+         for ke in cac:
+             mm, zz, eeps = ke[0]
+             if mm == m and zz == z:
+@@ -2746,16 +2746,16 @@ cdef class ModularSymbolNumerical:
+             sage: ms = ModularSymbolNumerical(E)
+             sage: ms.manin_symbol(4,17)
+             1
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache # random
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache # random
+             {((1, 5, 1), ()): 1,
+             ((1, 15, 1), ()): -1,
+             ((1, 22, 1), ()): -1,
+             ((1, 32, 1), ()): 1}
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache[(1,15,1),()]
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache[(1,15,1),()]
+             -1
+             sage: ms.manin_symbol(4+17,-4)
+             0
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache # random
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache # random
+             {((1, 4, 1), ()): 0,
+             ((1, 5, 1), ()): 1,
+             ((1, 8, 1), ()): 1,
+@@ -2768,7 +2768,7 @@ cdef class ModularSymbolNumerical:
+             ((1, 29, 1), ()): 1,
+             ((1, 32, 1), ()): 1,
+             ((1, 33, 1), ()): 0}
+-            sage: ms.__cached_methods["_manin_symbol_with_cache"].cache[ (1,23,1), () ]
++            sage: ms._cached_methods["_manin_symbol_with_cache"].cache[ (1,23,1), () ]
+             -1
+         """
+         cdef:
+@@ -2903,7 +2903,7 @@ cdef class ModularSymbolNumerical:
+         #        "(%s :%s)"%(un, vn), level=3)
+ 
+         # is it already in the cache ?
+-        c = self.__cached_methods
++        c = self._cached_methods
+         if "_manin_symbol_with_cache" in c:
+             c = c["_manin_symbol_with_cache"]
+             if c.is_in_cache(un,vn,sign):
+@@ -2919,7 +2919,7 @@ cdef class ModularSymbolNumerical:
+         # we get for free additional values of Manin
+         # symbols that we cache, too.
+         # This sets 6 values in average
+-        c = self.__cached_methods["_manin_symbol_with_cache"]
++        c = self._cached_methods["_manin_symbol_with_cache"]
+ 
+         # (-v:u) = - (u:v)
+         oi = proj_normalise(self._N_E, -v, u, &un, &vn)
+diff --git a/src/sage/sets/set_from_iterator.py b/src/sage/sets/set_from_iterator.py
+index c47bb76920b..11f12e6d5ea 100644
+--- a/src/sage/sets/set_from_iterator.py
++++ b/src/sage/sets/set_from_iterator.py
+@@ -214,12 +214,12 @@ def __reduce__(self):
+             True
+         """
+         return (EnumeratedSetFromIterator,
+-                (self._func,                            # func
+-                 getattr(self, '_args', None),          # args
+-                 getattr(self, '_kwds', None),          # kwds
+-                 getattr(self, '__custom_name', None),  # name
+-                 self.category(),                       # category
+-                 hasattr(self, '_cache'))               # cache
++                (self._func,                    # func
++                 getattr(self, '_args', None),  # args
++                 getattr(self, '_kwds', None),  # kwds
++                 self.get_custom_name(),        # name
++                 self.category(),               # category
++                 hasattr(self, '_cache'))       # cache
+                 )
+ 
+     def _repr_(self):
+diff --git a/src/sage/structure/category_object.pxd b/src/sage/structure/category_object.pxd
+index ff3088ae9b6..83d3d4967d4 100644
+--- a/src/sage/structure/category_object.pxd
++++ b/src/sage/structure/category_object.pxd
+@@ -13,7 +13,7 @@ from sage.structure.sage_object cimport SageObject
+ cpdef check_default_category(default_category, category)
+ 
+ cdef class CategoryObject(SageObject):
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+     cdef _category
+     cdef public _base
+     cdef public _names
+diff --git a/src/sage/structure/category_object.pyx b/src/sage/structure/category_object.pyx
+index 3859f24095a..b6a7eaecb5b 100644
+--- a/src/sage/structure/category_object.pyx
++++ b/src/sage/structure/category_object.pyx
+@@ -113,7 +113,7 @@ cdef class CategoryObject(SageObject):
+             self._init_category_(category)
+ 
+     def __cinit__(self):
+-        self.__cached_methods = {}
++        self._cached_methods = {}
+         self._hash_value = -1
+ 
+     def _init_category_(self, category):
+@@ -491,7 +491,7 @@ cdef class CategoryObject(SageObject):
+         """
+         return self.variable_names()[0]
+ 
+-    def __temporarily_change_names(self, names, latex_names):
++    def _temporarily_change_names(self, names, latex_names):
+         """
+         This is used by the variable names context manager.
+ 
+@@ -844,7 +844,7 @@ cdef class CategoryObject(SageObject):
+         # Lookup a method or attribute from the category abstract classes.
+         # See __getattr__ above for documentation.
+         try:
+-            return self.__cached_methods[name]
++            return self._cached_methods[name]
+         except KeyError:
+             if self._category is None:
+                 # Usually, this will just raise AttributeError in
+@@ -854,7 +854,7 @@ cdef class CategoryObject(SageObject):
+                 cls = self._category.parent_class
+ 
+             attr = getattr_from_other_class(self, cls, name)
+-            self.__cached_methods[name] = attr
++            self._cached_methods[name] = attr
+             return attr
+ 
+     def __dir__(self):
+diff --git a/src/sage/structure/element.pxd b/src/sage/structure/element.pxd
+index 79e86d8a5c3..20c556b985e 100644
+--- a/src/sage/structure/element.pxd
++++ b/src/sage/structure/element.pxd
+@@ -176,7 +176,7 @@ cdef class Element(SageObject):
+ 
+ 
+ cdef class ElementWithCachedMethod(Element):
+-    cdef public dict __cached_methods
++    cdef public dict _cached_methods
+ 
+ cdef class ModuleElement(Element)       # forward declaration
+ 
+diff --git a/src/sage/structure/element.pyx b/src/sage/structure/element.pyx
+index ab6ee157a94..36da1c0cc12 100644
+--- a/src/sage/structure/element.pyx
++++ b/src/sage/structure/element.pyx
+@@ -379,6 +379,7 @@ cdef class Element(SageObject):
+     .. automethod:: __mod__
+     """
+     @cython.binding(False)
++    @cython.always_allow_keywords(False)
+     def __getmetaclass__(_):
+         from sage.misc.inherit_comparison import InheritComparisonMetaclass
+         return InheritComparisonMetaclass
+@@ -2356,18 +2357,18 @@ cdef class ElementWithCachedMethod(Element):
+             True
+         """
+         try:
+-            return self.__cached_methods[name]
++            return self._cached_methods[name]
+         except KeyError:
+             attr = getattr_from_other_class(self,
+                                         self._parent.category().element_class,
+                                         name)
+-            self.__cached_methods[name] = attr
++            self._cached_methods[name] = attr
+             return attr
+         except TypeError:
+             attr = getattr_from_other_class(self,
+                                         self._parent.category().element_class,
+                                         name)
+-            self.__cached_methods = {name : attr}
++            self._cached_methods = {name : attr}
+             return attr
+ 
+ 
+diff --git a/src/sage/structure/parent_gens.pyx b/src/sage/structure/parent_gens.pyx
+index ab531314458..cc6ffaace21 100644
+--- a/src/sage/structure/parent_gens.pyx
++++ b/src/sage/structure/parent_gens.pyx
+@@ -371,7 +371,7 @@ cdef class localvars:
+             self._latex_names = latex_names
+ 
+     def __enter__(self):
+-        self._orig = self._obj.__temporarily_change_names(self._names, self._latex_names)
++        self._orig = self._obj._temporarily_change_names(self._names, self._latex_names)
+ 
+     def __exit__(self, type, value, traceback):
+-        self._obj.__temporarily_change_names(self._orig[0], self._orig[1])
++        self._obj._temporarily_change_names(self._orig[0], self._orig[1])
+diff --git a/src/sage/structure/sage_object.pyx b/src/sage/structure/sage_object.pyx
+index 8474142eaa1..10000aef394 100644
+--- a/src/sage/structure/sage_object.pyx
++++ b/src/sage/structure/sage_object.pyx
+@@ -69,6 +69,8 @@ cdef class SageObject:
+         r"""
+         Change self so it prints as x, where x is a string.
+ 
++        If x is ``None``, the existing custom name is removed.
++
+         .. NOTE::
+ 
+            This is *only* supported for Python classes that derive
+@@ -91,6 +93,9 @@ cdef class SageObject:
+             sage: h.rename('x^300 + ...')
+             sage: h
+             x^300 + ...
++            sage: g.rename(None)
++            sage: g
++            x^3 + x - 5
+ 
+         Real numbers are not Python classes, so rename is not supported::
+ 
+@@ -110,15 +115,16 @@ cdef class SageObject:
+            a lot of memory.
+ 
+            To support them for a specific class, add a
+-           ``cdef public __custom_name`` attribute.
++           ``cdef public _SageObject__custom_name`` attribute.
+         """
+         if x is None:
+-            #if hasattr(self, '__custom_name'):
+-            # that's tested in reset_name anyway...
+             self.reset_name()
+         else:
+             try:
+-                self.__custom_name = str(x)
++                # TODO: after dropping support for Cython < 3.0.0, all
++                # the self._SageObject__custom_name in this class can be
++                # changed to self.__custom_name
++                self._SageObject__custom_name = str(x)
+             except AttributeError:
+                 raise NotImplementedError("object does not support renaming: %s" % self)
+ 
+@@ -138,8 +144,30 @@ cdef class SageObject:
+             sage: P
+             Univariate Polynomial Ring in x over Rational Field
+         """
+-        if hasattr(self, '__custom_name'):
+-            del self.__custom_name
++        if hasattr(self, '_SageObject__custom_name'):
++            del self._SageObject__custom_name
++
++    def get_custom_name(self):
++        """
++        Return the custom name of this object, or ``None`` if it is not
++        renamed.
++
++        EXAMPLES::
++
++            sage: P.<x> = QQ[]
++            sage: P.get_custom_name() is None
++            True
++            sage: P.rename('A polynomial ring')
++            sage: P.get_custom_name()
++            'A polynomial ring'
++            sage: P.reset_name()
++            sage: P.get_custom_name() is None
++            True
++        """
++        try:
++            return self._SageObject__custom_name
++        except AttributeError:
++            return None
+ 
+     def __repr__(self):
+         """
+@@ -181,7 +209,7 @@ cdef class SageObject:
+             <sage.structure.sage_object.SageObject object at ...>
+         """
+         try:
+-            name = self.__custom_name
++            name = self._SageObject__custom_name
+             if name is not None:
+                 return name
+         except AttributeError:
+diff --git a/src/sage/topology/simplicial_set.py b/src/sage/topology/simplicial_set.py
+index 42cc3f77780..3ee14ae2da8 100644
+--- a/src/sage/topology/simplicial_set.py
++++ b/src/sage/topology/simplicial_set.py
+@@ -570,13 +570,12 @@ def __lt__(self, other):
+             return True
+         if self.degeneracies() and other.degeneracies() and self.degeneracies() != other.degeneracies():
+             return self.degeneracies() < other.degeneracies()
+-        if hasattr(self.nondegenerate(), '__custom_name'):
+-            if hasattr(other.nondegenerate(), '__custom_name'):
+-                return str(self) < str(other)
++        if self.nondegenerate().get_custom_name() is not None:
++            if other.nondegenerate().get_custom_name() is not None:
++                return self.nondegenerate().get_custom_name() < other.nondegenerate().get_custom_name()
+             return True
+ 
+-        if (hasattr(other, '__custom_name')
+-                or hasattr(other.nondegenerate(), '__custom_name')):
++        if other.nondegenerate().get_custom_name() is not None:
+             return False
+         return id(self) < id(other)
+ 
+@@ -793,8 +792,8 @@ def __copy__(self):
+         # dimension, the degeneracies, and the name (with a prime
+         # added).
+         sigma = AbstractSimplex(self._dim, degeneracies=self.degeneracies())
+-        if hasattr(self, '__custom_name'):
+-            sigma.rename(str(self) + "'")
++        if self.get_custom_name() is not None:
++            sigma.rename(self.get_custom_name() + "'")
+         return sigma
+ 
+     def __deepcopy__(self, memo):
+@@ -839,8 +838,8 @@ def __deepcopy__(self, memo):
+             return memo[underlying].apply_degeneracies(*degens)
+         except KeyError:
+             sigma = AbstractSimplex(underlying._dim)
+-            if hasattr(underlying, '__custom_name'):
+-                sigma.rename(str(self) + "'")
++            if underlying.get_custom_name() is not None:
++                sigma.rename(underlying.get_custom_name() + "'")
+             memo[underlying] = sigma
+             return sigma.apply_degeneracies(*degens)
+ 
+@@ -896,12 +895,12 @@ def _latex_(self):
+         """
+         if self._latex_name is not None:
+             return self._latex_name
+-        if hasattr(self, '__custom_name'):
+-            return str(self)
++        if self.get_custom_name() is not None:
++            return self.get_custom_name()
+         if self.nondegenerate()._latex_name is not None:
+             simplex = self.nondegenerate()._latex_name
+-        elif hasattr(self.nondegenerate(), '__custom_name'):
+-            simplex = str(self.nondegenerate())
++        elif self.nondegenerate().get_custom_name() is not None:
++            simplex = self.nondegenerate().get_custom_name()
+         else:
+             simplex = "\\Delta^{{{}}}".format(self._dim)
+         if self.degeneracies():
+diff --git a/src/sage/topology/simplicial_set_constructions.py b/src/sage/topology/simplicial_set_constructions.py
+index ae98821df8a..3a217286ac5 100644
+--- a/src/sage/topology/simplicial_set_constructions.py
++++ b/src/sage/topology/simplicial_set_constructions.py
+@@ -176,8 +176,7 @@ def __init__(self, data, ambient=None):
+         else:
+             SimplicialSet_finite.__init__(self, data)
+         if self == ambient:
+-            if hasattr(ambient, '__custom_name'):
+-                self.rename(str(ambient))
++            self.rename(ambient.get_custom_name())
+             self._latex_name = latex(ambient)
+         # When constructing the inclusion map, we do not need to check
+         # the validity of the morphism, and more importantly, we
diff --git a/srcpkgs/sagemath/patches/build-cython3.patch b/srcpkgs/sagemath/patches/build-cython3.patch
new file mode 100644
index 0000000000000..57d1ade89fc77
--- /dev/null
+++ b/srcpkgs/sagemath/patches/build-cython3.patch
@@ -0,0 +1,44 @@
+diff --git a/src/sage/ext/stdsage.pxd b/src/sage/ext/stdsage.pxd
+index 15abe13b7cd..e2bf7434f35 100644
+--- a/src/sage/ext/stdsage.pxd
++++ b/src/sage/ext/stdsage.pxd
+@@ -10,7 +10,7 @@ Standard C helper code for Cython modules
+ #                  http://www.gnu.org/licenses/
+ #*****************************************************************************
+ 
+-from cpython.object cimport Py_TYPE, PyTypeObject
++from cpython.object cimport Py_TYPE, PyTypeObject, PyObject
+ 
+ 
+ cdef inline PY_NEW(type t):
+@@ -19,7 +19,7 @@ cdef inline PY_NEW(type t):
+     :class:`Integer` where we change ``tp_new`` at runtime (Cython
+     optimizations assume that ``tp_new`` doesn't change).
+     """
+-    return (<PyTypeObject*>t).tp_new(t, <object>NULL, <object>NULL)
++    return (<PyTypeObject*>t).tp_new(t, <PyObject*>NULL, <PyObject*>NULL)
+ 
+ 
+ cdef inline void PY_SET_TP_NEW(type dst, type src):
+diff --git a/src/sage_setup/cython_options.py b/src/sage_setup/cython_options.py
+index 086aa070ca9..9725ce0e1af 100644
+--- a/src/sage_setup/cython_options.py
++++ b/src/sage_setup/cython_options.py
+@@ -10,13 +10,17 @@ def compiler_directives(profile: bool):
+         auto_pickle=False,
+         # Do not create __test__ dictionary automatically from docstrings
+         autotestdict=False,
++        binding=False,
++        c_api_binop_methods=True,
+         # Do not check for division by 0 (this is about 35% quicker than with check)
+         cdivision=True,
++        cpow=True,
+         # Embed a textual copy of the call signature in the docstring (to support tools like IPython)
+         embedsignature=True,
+         fast_getattr=True,
+         # Use Python 3 (including source code semantics) for module compilation
+         language_level="3",
++        legacy_implicit_noexcept=True,
+         # Enable support for late includes (make declarations in Cython code available to C include files)
+         preliminary_late_includes_cy28=True,
+         # Add hooks for Python profilers into the compiled C code
diff --git a/srcpkgs/sagemath/patches/fix-doctest-cython3.patch b/srcpkgs/sagemath/patches/fix-doctest-cython3.patch
new file mode 100644
index 0000000000000..4cff1fb1828db
--- /dev/null
+++ b/srcpkgs/sagemath/patches/fix-doctest-cython3.patch
@@ -0,0 +1,207 @@
+diff --git a/src/doc/en/thematic_tutorials/coercion_and_categories.rst b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+index de2349a9a3f..bb23331c151 100644
+--- a/src/doc/en/thematic_tutorials/coercion_and_categories.rst
++++ b/src/doc/en/thematic_tutorials/coercion_and_categories.rst
+@@ -105,7 +105,7 @@ it makes sense to build on top of the base class
+ This base class provides a lot more methods than a general parent::
+ 
+     sage: [p for p in dir(Field) if p not in dir(Parent)]
+-    ['__fraction_field',
++    ['_CommutativeRing__fraction_field',
+      '__iter__',
+      '__len__',
+      '__rxor__',
+diff --git a/src/sage/arith/srange.pyx b/src/sage/arith/srange.pyx
+index 156e548a11a..132cf93d085 100644
+--- a/src/sage/arith/srange.pyx
++++ b/src/sage/arith/srange.pyx
+@@ -84,7 +84,7 @@ def xsrange(start, end=None, step=1, universe=None, *, coerce=True, bint include
+     EXAMPLES::
+ 
+         sage: xsrange(10)
+-        <generator object at 0x...>
++        <...generator object at 0x...>
+         sage: for i in xsrange(1,5):
+         ....:     print(i)
+         1
+diff --git a/src/sage/combinat/sloane_functions.py b/src/sage/combinat/sloane_functions.py
+index c3cf9299093..e5c99b71fe7 100644
+--- a/src/sage/combinat/sloane_functions.py
++++ b/src/sage/combinat/sloane_functions.py
+@@ -9169,7 +9169,7 @@ class Sloane(SageObject):
+         ::
+ 
+             sage: sloane.__repr__
+-            <method-wrapper '__repr__' of Sloane object at 0x...>
++            <built-in method __repr__ of Sloane object at 0x...>
+             sage: sloane.__name__
+             Traceback (most recent call last):
+             ...
+diff --git a/src/sage/misc/cachefunc.pyx b/src/sage/misc/cachefunc.pyx
+index 8aa30a85272..2b1d38c12b9 100644
+--- a/src/sage/misc/cachefunc.pyx
++++ b/src/sage/misc/cachefunc.pyx
+@@ -50,7 +50,7 @@ be used::
+     sage: cython('''cpdef test_funct(x): return -x''')                          # optional - sage.misc.cython
+     sage: wrapped_funct = cached_function(test_funct, name='wrapped_funct')     # optional - sage.misc.cython
+     sage: wrapped_funct                                                         # optional - sage.misc.cython
+-    Cached version of <built-in function test_funct>
++    Cached version of <cyfunction test_funct at ...>
+     sage: wrapped_funct.__name__                                                # optional - sage.misc.cython
+     'wrapped_funct'
+     sage: wrapped_funct(5)                                                      # optional - sage.misc.cython
+@@ -82,9 +82,9 @@ approach is still needed for cpdef methods::
+     sage: cython(os.linesep.join(cython_code))                                  # optional - sage.misc.cython
+     sage: O = MyClass()                                                         # optional - sage.misc.cython
+     sage: O.direct_method                                                       # optional - sage.misc.cython
+-    Cached version of <method 'direct_method' of '...MyClass' objects>
++    Cached version of <cyfunction MyClass.direct_method at ...>
+     sage: O.wrapped_method                                                      # optional - sage.misc.cython
+-    Cached version of <built-in function test_meth>
++    Cached version of <cyfunction test_meth at ...>
+     sage: O.wrapped_method.__name__                                             # optional - sage.misc.cython
+     'wrapped_method'
+     sage: O.wrapped_method(5)                                                   # optional - sage.misc.cython
+@@ -270,6 +270,7 @@ Introspection works::
+         "some doc for a wrapped cython method"
+         return -x
+     sage: print(sage_getsource(O.direct_method))                                # optional - sage.misc.cython
++    @cached_method
+     def direct_method(self, x):
+         "Some doc for direct method"
+         return 2*x
+diff --git a/src/sage/misc/lazy_import.pyx b/src/sage/misc/lazy_import.pyx
+index c33a1e74efd..7fc73407ace 100644
+--- a/src/sage/misc/lazy_import.pyx
++++ b/src/sage/misc/lazy_import.pyx
+@@ -1095,7 +1095,7 @@ def lazy_import(module, names, as_=None, *,
+         sage: from sage.features import PythonModule
+         sage: lazy_import('ppl', 'equation', feature=PythonModule('ppl', spkg='pplpy', type='standard'))
+         sage: equation
+-        <built-in function equation>
++        <cyfunction equation at ...>
+         sage: lazy_import('PyNormaliz', 'NmzListConeProperties', feature=PythonModule('PyNormaliz', spkg='pynormaliz'))  # optional - pynormaliz
+         sage: NmzListConeProperties  # optional - pynormaliz
+         <built-in function NmzListConeProperties>
+diff --git a/src/sage/misc/lazy_list.pyx b/src/sage/misc/lazy_list.pyx
+index ba62c446b69..cd750933860 100644
+--- a/src/sage/misc/lazy_list.pyx
++++ b/src/sage/misc/lazy_list.pyx
+@@ -678,7 +678,7 @@ cdef class lazy_list_generic():
+             sage: from itertools import count
+             sage: from sage.misc.lazy_list import lazy_list
+             sage: iter(lazy_list(count()))
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+ 
+         ::
+ 
+diff --git a/src/sage/misc/sageinspect.py b/src/sage/misc/sageinspect.py
+index ce5e9987027..df8e6bf89ac 100644
+--- a/src/sage/misc/sageinspect.py
++++ b/src/sage/misc/sageinspect.py
+@@ -76,8 +76,8 @@ Cython functions::
+     sage: sage_getdoc(sage.rings.rational.make_rational).lstrip()
+     'Make a rational number ...'
+ 
+-    sage: sage_getsource(sage.rings.rational.make_rational)[4:]
+-    'make_rational(s):...'
++    sage: sage_getsource(sage.rings.rational.make_rational)
++    '@cython.binding(True)\ndef make_rational(s):...'
+ 
+ Python functions::
+ 
+diff --git a/src/sage/modules/free_module_element.pyx b/src/sage/modules/free_module_element.pyx
+index d5e8256b68c..c9af9bcbdf7 100644
+--- a/src/sage/modules/free_module_element.pyx
++++ b/src/sage/modules/free_module_element.pyx
+@@ -1634,7 +1634,7 @@ cdef class FreeModuleElement(Vector):   # abstract base class
+ 
+             sage: v = vector([1,2/3,pi])
+             sage: v.items()
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: list(v.items())
+             [(0, 1), (1, 2/3), (2, pi)]
+ 
+diff --git a/src/sage/rings/finite_rings/finite_field_base.pyx b/src/sage/rings/finite_rings/finite_field_base.pyx
+index 7e2eed91153..3a6db8995c6 100644
+--- a/src/sage/rings/finite_rings/finite_field_base.pyx
++++ b/src/sage/rings/finite_rings/finite_field_base.pyx
+@@ -328,7 +328,7 @@ cdef class FiniteField(Field):
+             sage: p = next_prime(2^64)
+             sage: k.<a> = FiniteField(p^2, impl="pari")
+             sage: it = iter(k); it
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: [next(it) for i in range(10)]
+             [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+ 
+diff --git a/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx b/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx
+index 41951687939..c6b67cba5fb 100644
+--- a/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx
++++ b/src/sage/rings/polynomial/skew_polynomial_finite_field.pyx
+@@ -629,7 +629,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense):
+             sage: S.<x> = k['x',Frob]
+             sage: a = x^4 + 2*t*x^3 + 3*t^2*x^2 + (t^2 + t + 1)*x + 4*t + 3
+             sage: iter = a.right_irreducible_divisors(); iter
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+             sage: next(iter)   # random
+             x + 2*t^2 + 4*t + 4
+             sage: next(iter)   # random
+@@ -664,7 +664,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense):
+             sage: S.<x> = k['x',Frob]
+             sage: a = x^4 + 2*t*x^3 + 3*t^2*x^2 + (t^2 + t + 1)*x + 4*t + 3
+             sage: iter = a.left_irreducible_divisors(); iter
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+             sage: next(iter)  # random
+             x + 3*t + 3
+             sage: next(iter)  # random
+@@ -1052,7 +1052,7 @@ cdef class SkewPolynomial_finite_field_dense(SkewPolynomial_finite_order_dense):
+             sage: S.<x> = k['x',Frob]
+             sage: a = x^3 + (t^2 + 1)*x^2 + (2*t + 3)*x + t^2 + t + 2
+             sage: iter = a.factorizations(); iter
+-            <generator object at 0x...>
++            <...generator object at 0x...>
+             sage: next(iter)   # random
+             (x + 3*t^2 + 4*t) * (x + 2*t^2) * (x + 4*t^2 + 4*t + 2)
+             sage: next(iter)   # random
+diff --git a/src/sage/structure/coerce_dict.pyx b/src/sage/structure/coerce_dict.pyx
+index a2e8443084c..ef86c6af35c 100644
+--- a/src/sage/structure/coerce_dict.pyx
++++ b/src/sage/structure/coerce_dict.pyx
+@@ -777,7 +777,7 @@ cdef class MonoDict:
+             sage: L[1] = None
+             sage: L[2] = True
+             sage: L.items()
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: sorted(L.items())
+             [(1, None), (2, True)]
+         """
+@@ -1452,7 +1452,7 @@ cdef class TripleDict:
+             sage: L = TripleDict()
+             sage: L[1,2,3] = None
+             sage: L.items()
+-            <generator object at ...>
++            <...generator object at ...>
+             sage: list(L.items())
+             [((1, 2, 3), None)]
+         """
+diff --git a/src/sage/tests/cmdline.py b/src/sage/tests/cmdline.py
+index ad0c44aa274..f14cd2db768 100644
+--- a/src/sage/tests/cmdline.py
++++ b/src/sage/tests/cmdline.py
+@@ -491,9 +491,8 @@ def test_executable(args, input="", timeout=100.0, pydebug_ignore_warnings=False
+ 
+         sage: (out, err, ret) = test_executable(["sage", "--cython"])
+         sage: print(err)
+-        Cython (http://cython.org) is a compiler for code written in the
+-        Cython language.  Cython is based on Pyrex by Greg Ewing.
+         ...
++        cython: error: cython: Need at least one source file
+ 
+         sage: def has_tty():
+         ....:     try:
diff --git a/srcpkgs/sagemath/patches/get_patches b/srcpkgs/sagemath/patches/get_patches
index 95a6963432948..64ffe14d15eb5 100755
--- a/srcpkgs/sagemath/patches/get_patches
+++ b/srcpkgs/sagemath/patches/get_patches
@@ -12,7 +12,7 @@ esac
 # get_pr <PR number> <description> [ext]
 get_pr() {
 	pr=$1
-	desc=$(echo "$2" | sed -e 's/ /_/g')
+	desc=$(echo "$2" | tr ' /' '_-')
 	ext=${3-diff}
 	$DO wget "$URL_BASE_PR$pr.$ext" -O "$pr-$desc.patch"
 }
@@ -26,6 +26,7 @@ get_pr  36046   "fix memory leak"
 
 # merged in 10.2.beta1
 get_pr  35934   "singular 4.3.2p7"
+get_pr  36109   "prepare for cython 3.0" # included in #36110
 
 # merged in 10.2.beta2
 get_pr  36006   "gmp 6.3.0"
diff --git a/srcpkgs/sagemath/template b/srcpkgs/sagemath/template
index a80d8b7187ece..ba8bd94d835d6 100644
--- a/srcpkgs/sagemath/template
+++ b/srcpkgs/sagemath/template
@@ -1,12 +1,12 @@
 # Template file for 'sagemath'
 pkgname=sagemath
 version=10.1
-revision=4
+revision=5
 build_wrksrc=pkgs/sagemath-standard
 build_style=python3-module
 _bindir=/usr/lib/sagemath/$version/bin
 make_install_args="--install-scripts=$_bindir"
-hostmakedepends="m4 pkg-config python3-Cython0.29 python3-Jinja2
+hostmakedepends="m4 pkg-config python3-Cython python3-Jinja2
  python3-pkgconfig python3-setuptools"
 makedepends="arb-devel boost-devel brial-devel cliquer-devel ecl eclib-devel
  ecm-devel fflas-ffpack flintlib-devel gap-devel gd-devel giac-devel glpk-devel
@@ -18,7 +18,7 @@ makedepends="arb-devel boost-devel brial-devel cliquer-devel ecl eclib-devel
 depends="eclib-devel fflas-ffpack flintlib-devel gcc-fortran gd-devel
  gfan giac gsl-devel gzip libpng-devel linbox-devel m4ri-devel maxima-ecl
  mpfr-devel nauty ntl-devel palp pari-devel pari-elldata-small pari-galdata
- pari-galpol-small pari-seadata-small pkg-config python3-Cython0.29 python3-cypari2
+ pari-galpol-small pari-seadata-small pkg-config python3-Cython python3-cypari2
  python3-cysignals python3-devel python3-fpylll python3-ipython python3-lrcalc
  python3-ipython_ipykernel python3-jupyter_ipywidgets python3-matplotlib
  python3-memory_allocator python3-networkx python3-pip python3-pkgconfig

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
                   ` (13 preceding siblings ...)
  2023-10-10 12:42 ` [PR PATCH] [Updated] " tornaria
@ 2023-10-10 12:43 ` tornaria
  2023-10-22 14:50 ` tornaria
  2023-10-22 14:50 ` [PR PATCH] [Closed]: " tornaria
  16 siblings, 0 replies; 18+ messages in thread
From: tornaria @ 2023-10-10 12:43 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 214 bytes --]

New comment by tornaria on void-packages repository

https://github.com/void-linux/void-packages/pull/45887#issuecomment-1755338916

Comment:
It turns out #46553 is needed for sagemath to pass check with cython 3.

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
                   ` (14 preceding siblings ...)
  2023-10-10 12:43 ` tornaria
@ 2023-10-22 14:50 ` tornaria
  2023-10-22 14:50 ` [PR PATCH] [Closed]: " tornaria
  16 siblings, 0 replies; 18+ messages in thread
From: tornaria @ 2023-10-22 14:50 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 223 bytes --]

New comment by tornaria on void-packages repository

https://github.com/void-linux/void-packages/pull/45887#issuecomment-1774115101

Comment:
I won't keep up this PR anymore. If you need sagemath with cython 3, use #46832.

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PR PATCH] [Closed]: sagemath: use cython 3
  2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
                   ` (15 preceding siblings ...)
  2023-10-22 14:50 ` tornaria
@ 2023-10-22 14:50 ` tornaria
  16 siblings, 0 replies; 18+ messages in thread
From: tornaria @ 2023-10-22 14:50 UTC (permalink / raw)
  To: ml

[-- Attachment #1: Type: text/plain, Size: 2275 bytes --]

There's a closed pull request on the void-packages repository

sagemath: use cython 3
https://github.com/void-linux/void-packages/pull/45887

Description:
#### Testing the changes
- I tested the changes in this PR: **briefly**

Since https://github.com/sagemath/sage/pull/36109 was merged upstream, it's now almost trivial to build sagemath with cython 3. This PR is pretty straightforward to understand:

 - commit 7f8e6514ffa54449a80e01fbae7f9355a7739a46 rebuilds `python3-pplpy` using cython 3. Nothing fancy here and this commit was already tested and only dropped since it turned out it had to be built with the same version of cython as sagemath itself.
 - commit df0d21871ce850efea3fc01f19a3d9e8c0d5f0d4 is just adding a few patches to sagemath, switching to cython 3, and bumping.

Description of added patches:
1. patch `36109-00pre.patch`: this is hand picked trivial patch that allows us to apply https://github.com/sagemath/sage/pull/36109 cleanly on 10.1 (since that PR is based on 10.1.beta0). All changes are comments!
2. patch `36109-prepare_for_cython_3.0.patch`: this is long, taken verbatim from https://github.com/sagemath/sage/pull/36109.diff, and is already merged.
3. patch `build-cython3.patch`: this is 2 lines changed plus 4 legacy build options added to cython setup.
4. patch `fix-doctest-cython3.patch`: this is a few fixes in doctests to accomodate minor changes in cython output (`__repr__` for cython classes, functions, and generators).

CC: @ahesford 

<!--
#### New package
- This new package conforms to the [package requirements](https://github.com/void-linux/void-packages/blob/master/CONTRIBUTING.md#package-requirements): **YES**|**NO**
-->

<!-- Note: If the build is likely to take more than 2 hours, please add ci skip tag as described in
https://github.com/void-linux/void-packages/blob/master/CONTRIBUTING.md#continuous-integration
and test at least one native build and, if supported, at least one cross build.
Ignore this section if this PR is not skipping CI.
-->
<!--
#### Local build testing
- I built this PR locally for my native architecture, (ARCH-LIBC)
- I built this PR locally for these architectures (if supported. mark crossbuilds):
  - aarch64-musl
  - armv7l
  - armv6l-musl
-->


^ permalink raw reply	[flat|nested] 18+ messages in thread

end of thread, other threads:[~2023-10-22 14:50 UTC | newest]

Thread overview: 18+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2023-09-02 22:32 [PR PATCH] sagemath: use cython 3 tornaria
2023-09-02 22:37 ` [PR PATCH] [Updated] " tornaria
2023-09-02 23:33 ` ahesford
2023-09-03  1:24 ` tornaria
2023-09-03  1:59 ` ahesford
2023-09-03  2:00 ` ahesford
2023-09-04 13:21 ` tornaria
2023-09-05 11:57 ` [PR PATCH] [Updated] " tornaria
2023-09-06 14:50 ` ahesford
2023-09-07  1:32 ` ahesford
2023-09-09 15:33 ` tornaria
2023-09-11  0:02 ` ahesford
2023-10-09 21:55 ` [PR PATCH] [Updated] " tornaria
2023-10-09 22:01 ` tornaria
2023-10-10 12:42 ` [PR PATCH] [Updated] " tornaria
2023-10-10 12:43 ` tornaria
2023-10-22 14:50 ` tornaria
2023-10-22 14:50 ` [PR PATCH] [Closed]: " tornaria

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).