Skip to content
This repository has been archived by the owner on Jan 30, 2023. It is now read-only.

Commit

Permalink
new method "to_bytes" and change in pynac constant
Browse files Browse the repository at this point in the history
  • Loading branch information
Frédéric Chapoton committed Sep 14, 2017
1 parent cbfb8ff commit 069fd36
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/sage/libs/pynac/constant.pyx
Expand Up @@ -16,6 +16,7 @@ Wrapper around Pynac's constants

from __future__ import absolute_import, division, print_function

from sage.misc.six import to_bytes
from .pynac cimport *
from sage.symbolic.expression cimport new_Expression_from_GEx
from sage.symbolic.ring import SR
Expand Down Expand Up @@ -52,6 +53,8 @@ cdef class PynacConstant:
raise ValueError

self._name = name
name = to_bytes(name)
texname = to_bytes(texname)

# For the constants explicitly defined in constant.cpp in the
# Pynac library, we use those symbols. Otherwise, we create a
Expand Down
31 changes: 31 additions & 0 deletions src/sage/misc/six.py
Expand Up @@ -133,3 +133,34 @@ def u(x):
if isinstance(x, bytes):
return x.decode("utf-8")
raise TypeError('input has no conversion to unicode')


def to_bytes(x):
r"""
Convert `x` to bytes, assuming UTF-8 encoding.
Python2 behaviour:
If input is str, returns the input.
If input is unicode, convert to bytes using utf8-encoding.
Python3 behaviour:
If input is str, convert to bytes using utf8-encoding.
If input is bytes, returns the input.
EXAMPLES::
sage: from sage.misc.six import to_bytes
sage: to_bytes("500 €")
'500 \xe2\x82\xac'
sage: to_bytes(u"500 \u20ac")
'500 \xe2\x82\xac'
"""
if isinstance(x, text_type): # py2 unicode and py3 str
return x.encode("utf-8")
if isinstance(x, bytes):
return x
raise TypeError('input has no conversion to unicode')

0 comments on commit 069fd36

Please sign in to comment.