compat.py 2.0 KB
Newer Older
M
minqiyang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import six


#  str and bytes related functions
def to_literal_str(obj):
    if isinstance(obj, list):
        return [_to_literal_str(item) for item in obj]
    elif isinstance(obj, set):
        return set([_to_literal_str(item) for item in obj])
    else:
        return _to_literal_str(obj)


def _to_literal_str(obj):
    if isinstance(obj, six.binary_type):
M
minqiyang 已提交
30
        return obj.decode('utf-8')
M
minqiyang 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
    elif isinstance(obj, six.text_type):
        return obj
    else:
        return six.u(obj)


def to_bytes(obj):
    if isinstance(obj, list):
        return [_to_bytes(item) for item in obj]
    elif isinstance(obj, set):
        return set([_to_bytes(item) for item in obj])
    else:
        return _to_bytes(obj)


def _to_bytes(obj):
    if isinstance(obj, six.text_type):
M
minqiyang 已提交
48
        return obj.encode('utf-8')
M
minqiyang 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    elif isinstance(obj, six.binary_type):
        return obj
    else:
        return six.b(obj)


# math related functions
import math


def round(x, d=0):
    """
    Compatible round which act the same behaviour in Python3.

    Args:
        x(float) : The number to round halfway.

    Returns:
        round result of x
    """
    p = 10**d
    return float(math.floor((x * p) + math.copysign(0.5, x))) / p


def floor_division(x, y):
    return x // y
M
minqiyang 已提交
75 76 77 78 79 80 81 82

# exception related functions
def get_exception_message(exc):
    if six.PY2:
        return exc.message
    else:
        return str(exc)