from __future__ import print_function
import sys, os
import json

class Container(dict):
    __slots__ = "__protected__",

    def __init__(self, *args, **kwargs):
        super(self.__class__, self).__init__(*args, **kwargs)
        self.__protected__ = False

    def protected(self):
        return self.__protected__

    def protected(self, v):
        self.__protected__ = bool(v)

    def __getattr__(self, item):
        if item in self:
            return self[item]
        raise AttributeError("(getattr) Attribute or key '{}' not in {}"
                             .format(item, self.__class__))

    def __setattr__(self, key, value):
        if hasattr(dict, key) or key.startswith("__"):
            return super(self.__class__, self).__setattr__(key, value)

        if self.__protected__:
            raise AttributeError("(setattr) Attribute or key '{}' not in protected {}"
                                 .format(key, self.__class__))
        self[key] = value

    def as_json(self):
        Return Containers content in json-format. 
        return json.dumps(self)

    def write(self, out=sys.stdout, overwrite=False):
        Write Container content to file (or stdout by default) 
        in json-format. 
        closeflag = False
        if isinstance(out, basestring):
            if not overwrite and os.path.exists(out):
                raise IOError("Can't overwrite: '{}'"
            out = open(out, "w")
            closeflag = True

        print(self.as_json(), file=out)
        if closeflag:

    def protect(self):
        Don't allow new keys. 
        self.protected = True

    def unprotect(self):
        Protection dismissed. 
        self.protected = False