Skip to content

Instantly share code, notes, and snippets.

@sapamja
Created August 14, 2014 23:55
Show Gist options
  • Select an option

  • Save sapamja/c158e2fb6184404ca345 to your computer and use it in GitHub Desktop.

Select an option

Save sapamja/c158e2fb6184404ca345 to your computer and use it in GitHub Desktop.

Revisions

  1. sapamja created this gist Aug 14, 2014.
    45 changes: 45 additions & 0 deletions storage_class.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    # -*- coding: utf-8 -*-
    """
    This file contains Storage class to storage data.
    """

    class Storage(dict):
    """
    A Storage object is like a dictionary except `obj.foo` can be used
    in addition to `obj['foo']`.
    >>> obj = Storage(a=1)
    >>> obj.val
    1
    >>> obj['val']
    1
    >>> obj.val = 2
    >>> obj['val']
    2
    >>> del obj.val
    >>> obj.val
    None
    """
    def __getattr__(self, key):
    try:
    return self[key]
    except KeyError:
    return None

    def __setattr__(self, key, value):
    self[key] = value

    def __delattr__(self, key):
    try:
    del self[key]
    except KeyError as error:
    raise AttributeError(error)

    def __repr__(self):
    return '<Storage ' + dict.__repr__(self) + '>'

    def __getstate__(self):
    return dict(self)

    def __setstate__(self,value):
    for k,v in value.items(): self[k]=v