1"""
2A dict subclass for Python 3 that behaves like Python 2's dict
3
4Example use:
5
6>>> from past.builtins import dict
7>>> d1 = dict() # instead of {} for an empty dict
8>>> d2 = dict(key1='value1', key2='value2')
9
10The keys, values and items methods now return lists on Python 3.x and there are
11methods for iterkeys, itervalues, iteritems, and viewkeys etc.
12
13>>> for d in (d1, d2):
14... assert isinstance(d.keys(), list)
15... assert isinstance(d.values(), list)
16... assert isinstance(d.items(), list)
17"""
18
19import sys
20
21from past.utils import with_metaclass
22
23
24_builtin_dict = dict
25ver = sys.version_info[:2]
26
27
28class BaseOldDict(type):
29 def __instancecheck__(cls, instance):
30 return isinstance(instance, _builtin_dict)
31
32
33class olddict(with_metaclass(BaseOldDict, _builtin_dict)):
34 """
35 A backport of the Python 3 dict object to Py2
36 """
37 iterkeys = _builtin_dict.keys
38 viewkeys = _builtin_dict.keys
39
40 def keys(self):
41 return list(super(olddict, self).keys())
42
43 itervalues = _builtin_dict.values
44 viewvalues = _builtin_dict.values
45
46 def values(self):
47 return list(super(olddict, self).values())
48
49 iteritems = _builtin_dict.items
50 viewitems = _builtin_dict.items
51
52 def items(self):
53 return list(super(olddict, self).items())
54
55 def has_key(self, k):
56 """
57 D.has_key(k) -> True if D has a key k, else False
58 """
59 return k in self
60
61 # def __new__(cls, *args, **kwargs):
62 # """
63 # dict() -> new empty dictionary
64 # dict(mapping) -> new dictionary initialized from a mapping object's
65 # (key, value) pairs
66 # dict(iterable) -> new dictionary initialized as if via:
67 # d = {}
68 # for k, v in iterable:
69 # d[k] = v
70 # dict(**kwargs) -> new dictionary initialized with the name=value pairs
71 # in the keyword argument list. For example: dict(one=1, two=2)
72
73 # """
74 #
75 # if len(args) == 0:
76 # return super(olddict, cls).__new__(cls)
77 # # Was: elif isinstance(args[0], newbytes):
78 # # We use type() instead of the above because we're redefining
79 # # this to be True for all unicode string subclasses. Warning:
80 # # This may render newstr un-subclassable.
81 # elif type(args[0]) == olddict:
82 # return args[0]
83 # # elif isinstance(args[0], _builtin_dict):
84 # # value = args[0]
85 # else:
86 # value = args[0]
87 # return super(olddict, cls).__new__(cls, value)
88
89 def __native__(self):
90 """
91 Hook for the past.utils.native() function
92 """
93 return super(oldbytes, self)
94
95
96__all__ = ['olddict']