Skip to content

Commit

Permalink
Trac #19733: Assignment of special methods does not work in Cython
Browse files Browse the repository at this point in the history
In Cython, you cannot do
{{{
cdef class Foo:
    __str__ = whatever
}}}
and expect it to work.

I asked upstream about this: [https://groups.google.com/forum/#!topic
/cython-users/aE7Tn-XLZnI]

-------

When deriving a `class` (not `cdef class`) this kind of assignment
suddenly works::
{{{
cdef class Base(object):
    def my_str(self):
        return "good"
    __str__ = my_str

class Derived(Base):
    pass
}}}
gives
{{{
sage: str(Base())
'<_home_jdemeyer__sage_temp_tamiyo_8430_tmp__MunIM_spyx_0.Base object at
0x7fb54ae544d0>'
sage: str(Derived())
'good'
}}}

This also explains why the `__len__ = cardinality` in
`src/sage/rings/finite_rings/finite_field_base.pyx` works. It doesn't
work on the level of
`sage.rings.finite_rings.finite_field_base.FiniteField`, but it works at
the level of the actual finite field classes (which are Python classes).

URL: http://trac.sagemath.org/19733
Reported by: jdemeyer
Ticket author(s): Jeroen Demeyer
Reviewer(s): Dima Pasechnik
  • Loading branch information
Release Manager authored and vbraun committed Dec 17, 2015
2 parents 10e9cb5 + fc92afb commit d9b5c45
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
4 changes: 2 additions & 2 deletions src/sage/libs/gap/context_managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
sage: with libgap.global_context('FooBar', 'test'):
....: print libgap.get_global('FooBar')
"test"
test
Afterward, the global variable reverts to the previous value::
Expand All @@ -27,7 +27,7 @@
....: raise ValueError(libgap.get_global('FooBar'))
Traceback (most recent call last):
...
ValueError: "test"
ValueError: test
sage: print libgap.get_global('FooBar')
123
"""
Expand Down
15 changes: 10 additions & 5 deletions src/sage/libs/gap/element.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1861,22 +1861,27 @@ cdef class GapElement_String(GapElement):
sage: s = libgap('string')
sage: type(s)
<type 'sage.libs.gap.element.GapElement_String'>
sage: s
"string"
sage: print s
string
"""

def sage(self):
def __str__(self):
r"""
Return the Sage equivalent of the :class:`GapElement`
Convert this :class:`GapElement_String` to a Python string.
OUTPUT:
A Python list.
A Python string.
EXAMPLES::
sage: s = libgap.eval(' "string" '); s
"string"
sage: type(_)
<type 'sage.libs.gap.element.GapElement_String'>
sage: str(s)
'string'
sage: s.sage()
'string'
sage: type(_)
Expand All @@ -1887,7 +1892,7 @@ cdef class GapElement_String(GapElement):
libgap_exit()
return s

__str__ = sage
sage = __str__

############################################################################
### GapElement_Function ####################################################
Expand Down

0 comments on commit d9b5c45

Please sign in to comment.