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

Commit

Permalink
Use open from io to support encoding parameter in python 2
Browse files Browse the repository at this point in the history
  • Loading branch information
perdasilva committed Nov 15, 2019
1 parent 177fd3e commit 44f32ad
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion python/mxnet/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"""ctypes library of mxnet and helper functions."""
from __future__ import absolute_import

import io
import re
import atexit
import ctypes
Expand All @@ -32,6 +33,7 @@
from . import libinfo

__all__ = ['MXNetError']

#----------------------------
# library loading
#----------------------------
Expand Down Expand Up @@ -76,6 +78,26 @@ def data_dir():
"""
return os.getenv('MXNET_HOME', data_dir_default())

class _Py2CompatibleUnicodeFileWriter(object):
"""
Wraps a file handle decorating the write command to unicode the content before writing.
This makes writing files opened with encoding='utf-8' compatible with Python 2
"""

def __init__(self, file_handle):
self._file_handle = file_handle
if sys.version_info[0] > 2:
self.unicode = str
else:
from functools import partial
self.unicode = partial(unicode, encoding="utf-8")

def write(self, value):
self._file_handle.write(self.unicode(value))

def __getattr__(self, name):
return getattr(self._file_handle, name)


class _NullType(object):
"""Placeholder for arguments"""
Expand Down Expand Up @@ -672,7 +694,7 @@ def get_module_file(module_name):
module_path = module_name.split('.')
module_path[-1] = 'gen_' + module_path[-1]
file_name = os.path.join(path, '..', *module_path) + '.py'
module_file = open(file_name, 'w', encoding="utf-8")
module_file = _Py2CompatibleUnicodeFileWriter(io.open(file_name, 'w', encoding="utf-8"))
dependencies = {'symbol': ['from ._internal import SymbolBase',
'from ..base import _Null'],
'ndarray': ['from ._internal import NDArrayBase',
Expand Down

0 comments on commit 44f32ad

Please sign in to comment.