Skip to content

Commit

Permalink
Merge pull request #78 from fls-bioinformatics-core/AttributeDictiona…
Browse files Browse the repository at this point in the history
…ry-reimplementation

Reimplement the AttributeDictionary class so it can be pickled
  • Loading branch information
pjbriggs committed Aug 22, 2018
2 parents 0a8206e + fbeb306 commit 02466a6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 19 deletions.
12 changes: 12 additions & 0 deletions bcftbx/test/test_utils.py
Expand Up @@ -6,6 +6,7 @@
import tempfile
import shutil
import gzip
import pickle
import bcftbx.test.mock_data as mock_data
from bcftbx.utils import *

Expand Down Expand Up @@ -53,6 +54,17 @@ def test_iter(self):
self.assertTrue(key in ('salutation','valediction'),
"%s not in list" % key)

def test_can_pickle_attributedictionary(self):
"""AttributeDictionary can be pickled
"""
d = AttributeDictionary(hello="world")
self.assertEqual(d['hello'],"world")
pickled = pickle.dumps(d)
unpickled = pickle.loads(pickled)
self.assertTrue(isinstance(unpickled,AttributeDictionary))
self.assertEqual(unpickled['hello'],"world")
self.assertEqual(unpickled.hello,"world")

class TestOrderedDictionary(unittest.TestCase):
"""Unit tests for the OrderedDictionary class
"""
Expand Down
29 changes: 10 additions & 19 deletions bcftbx/utils.py
@@ -1,16 +1,14 @@
#!/usr/bin/env python
#
# utils.py: utility classes and functions shared between BCF codes
# Copyright (C) University of Manchester 2013-17 Peter Briggs
# Copyright (C) University of Manchester 2013-2018 Peter Briggs
#
########################################################################
#
# utils.py
#
#########################################################################

__version__ = "1.6.0"

"""utils
Utility classes and functions shared between BCF codes.
Expand Down Expand Up @@ -104,7 +102,7 @@
# General utility classes
#######################################################################

class AttributeDictionary:
class AttributeDictionary(dict):
"""Dictionary-like object with items accessible as attributes
AttributeDict provides a dictionary-like object where the value
Expand Down Expand Up @@ -133,25 +131,18 @@ class AttributeDictionary:
"""
def __init__(self,**args):
self.__dict = dict(args)
dict.__init__(self,**args)

def __getattr__(self,attr):
try:
return self.__dict[attr]
return dict.__getattr__(self,attr)
except AttributeError:
pass
try:
return self[attr]
except KeyError:
raise AttributeError, "No attribute '%s'" % attr

def __getitem__(self,key):
return self.__dict[key]

def __setitem__(self,key,value):
self.__dict[key] = value

def __iter__(self):
return iter(self.__dict)

def __len__(self):
return len(self.__dict)
raise AttributeError("'AttributeDictionary' has no "
"attribute '%s'" % attr)

class OrderedDictionary:
"""Augumented dictionary which keeps keys in order
Expand Down

0 comments on commit 02466a6

Please sign in to comment.