collection.py 1.6 KB
Newer Older
C
chenxuyi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#   Copyright (c) 2019 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.
C
chenxuyi 已提交
14 15
"""global collections"""

C
chenxuyi 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals

import sys

_global_collection = None


class Key(object):
    """predefine collection keys"""
    SUMMARY_SCALAR = 1
    SUMMARY_HISTOGRAM = 2
    SKIP_OPTIMIZE = 3


class Collections(object):
    """global collections to record everything"""

    def __init__(self):
        self.col = {}

    def __enter__(self):
        global _global_collection
        _global_collection = self
        return self

    def __exit__(self, err_type, err_value, trace):
        global _global_collection
        _global_collection = None

    def add(self, key, val):
C
chenxuyi 已提交
48
        """doc"""
C
chenxuyi 已提交
49 50 51
        self.col.setdefault(key, []).append(val)

    def get(self, key):
C
chenxuyi 已提交
52
        """doc"""
C
chenxuyi 已提交
53 54 55 56
        return self.col.get(key, None)


def default_collection():
C
chenxuyi 已提交
57
    """return global collection"""
C
chenxuyi 已提交
58 59 60 61
    global _global_collection
    if _global_collection is None:
        _global_collection = Collections()
    return _global_collection