| 1 |
""" |
| 2 |
Implementation helper: a struct that looks like a tuple. See timemodule |
| 3 |
and posixmodule for example uses. |
| 4 |
""" |
| 5 |
from __pypy__ import hidden_applevel |
| 6 |
|
| 7 |
make_none = lambda self: None |
| 8 |
|
| 9 |
class structseqfield(object): |
| 10 |
"""Definition of field of a structseq. The 'index' is for positional |
| 11 |
tuple-like indexing. Fields whose index is after a gap in the numbers |
| 12 |
cannot be accessed like this, but only by name. |
| 13 |
""" |
| 14 |
__name__ = "?" |
| 15 |
|
| 16 |
def __init__(self, index, doc=None, default=None): |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
self.index = index |
| 21 |
|
| 22 |
self.__doc__ = doc |
| 23 |
if default: |
| 24 |
self._default = default |
| 25 |
|
| 26 |
def __repr__(self): |
| 27 |
return '<field %s (%s)>' % (self.__name__, |
| 28 |
self.__doc__ or 'undocumented') |
| 29 |
|
| 30 |
@hidden_applevel |
| 31 |
def __get__(self, obj, typ=None): |
| 32 |
if obj is None: |
| 33 |
return self |
| 34 |
if not self.is_positional: |
| 35 |
return obj.__dict__[self.__name__] |
| 36 |
else: |
| 37 |
return obj[self.index] |
| 38 |
|
| 39 |
def __set__(self, obj, value): |
| 40 |
raise AttributeError("readonly attribute") |
| 41 |
|
| 42 |
|
| 43 |
class structseqtype(type): |
| 44 |
|
| 45 |
def __new__(metacls, classname, bases, dict): |
| 46 |
assert not bases |
| 47 |
fields_by_index = {} |
| 48 |
for name, field in dict.items(): |
| 49 |
if isinstance(field, structseqfield): |
| 50 |
assert field.index not in fields_by_index |
| 51 |
fields_by_index[field.index] = field |
| 52 |
field.__name__ = name |
| 53 |
dict['n_fields'] = len(fields_by_index) |
| 54 |
|
| 55 |
extra_fields = sorted(fields_by_index.items()) |
| 56 |
n_sequence_fields = 0 |
| 57 |
sequence_fields = [] |
| 58 |
while extra_fields and extra_fields[0][0] == n_sequence_fields: |
| 59 |
num, field = extra_fields.pop(0) |
| 60 |
field.is_positional = True |
| 61 |
assert not hasattr(field, "_default") |
| 62 |
sequence_fields.append(field.__name__) |
| 63 |
n_sequence_fields += 1 |
| 64 |
|
| 65 |
dict['n_sequence_fields'] = n_sequence_fields |
| 66 |
|
| 67 |
|
| 68 |
dict['n_unnamed_fields'] = sum( |
| 69 |
1 for name in sequence_fields if name.startswith('_')) |
| 70 |
|
| 71 |
extra_fields = [field for index, field in extra_fields] |
| 72 |
for field in extra_fields: |
| 73 |
field.is_positional = False |
| 74 |
if not hasattr(field, "_default"): |
| 75 |
field._default = make_none |
| 76 |
|
| 77 |
dict['_extra_fields'] = tuple(extra_fields) |
| 78 |
if '__new__' not in dict: |
| 79 |
dict['__new__'] = structseq_new |
| 80 |
dict['__reduce__'] = structseq_reduce |
| 81 |
dict['__setattr__'] = structseq_setattr |
| 82 |
dict['__repr__'] = structseq_repr |
| 83 |
dict['__str__'] = structseq_repr |
| 84 |
dict['_name'] = dict.get('name', classname) |
| 85 |
dict['__match_args__'] = tuple( |
| 86 |
name for name in sequence_fields if not name.startswith('_')) |
| 87 |
return type.__new__(metacls, classname, (tuple,), dict) |
| 88 |
|
| 89 |
|
| 90 |
builtin_dict = dict |
| 91 |
|
| 92 |
MISSING = object() |
| 93 |
|
| 94 |
@hidden_applevel |
| 95 |
def structseq_new(cls, sequence, dict=MISSING): |
| 96 |
if not getattr(cls, 'allow_instantiation', True): |
| 97 |
raise TypeError("cannot create '%s' instances" % cls._name) |
| 98 |
if dict is MISSING: |
| 99 |
dict = {} |
| 100 |
elif not isinstance(dict, builtin_dict): |
| 101 |
raise TypeError(cls._name + " takes a dict as second arg, if any") |
| 102 |
N = cls.n_sequence_fields |
| 103 |
|
| 104 |
if N == 1: |
| 105 |
sequence = tuple([sequence]) |
| 106 |
else: |
| 107 |
sequence = tuple(sequence) |
| 108 |
if len(sequence) < N: |
| 109 |
if N < cls.n_fields: |
| 110 |
msg = "at least" |
| 111 |
else: |
| 112 |
msg = "exactly" |
| 113 |
raise TypeError("expected a sequence with %s %d items. has %d" % ( |
| 114 |
msg, N, len(sequence))) |
| 115 |
if len(sequence) > N: |
| 116 |
if len(sequence) > cls.n_fields: |
| 117 |
if N < cls.n_fields: |
| 118 |
msg = "at most" |
| 119 |
else: |
| 120 |
msg = "exactly" |
| 121 |
raise TypeError("expected a sequence with %s %d items. has %d" \ |
| 122 |
% (msg, cls.n_fields, len(sequence))) |
| 123 |
result = tuple.__new__(cls, sequence[:N]) |
| 124 |
difference = len(sequence) - N |
| 125 |
for i in range(len(sequence) - N): |
| 126 |
name = cls._extra_fields[i].__name__ |
| 127 |
if name in dict: |
| 128 |
raise TypeError("duplicate value for %r" % (name,)) |
| 129 |
result.__dict__[name] = sequence[N + i] |
| 130 |
startindex = len(sequence) - N |
| 131 |
if startindex == len(cls._extra_fields): |
| 132 |
return result |
| 133 |
else: |
| 134 |
result = tuple.__new__(cls, sequence) |
| 135 |
startindex = 0 |
| 136 |
for i in range(startindex, len(cls._extra_fields)): |
| 137 |
field = cls._extra_fields[i] |
| 138 |
name = field.__name__ |
| 139 |
try: |
| 140 |
value = dict[name] |
| 141 |
except KeyError: |
| 142 |
value = field._default(result) |
| 143 |
result.__dict__[name] = value |
| 144 |
return result |
| 145 |
|
| 146 |
def structseq_reduce(self): |
| 147 |
return type(self), (tuple(self), self.__dict__) |
| 148 |
|
| 149 |
def structseq_setattr(self, attr, value): |
| 150 |
if attr not in type(self).__dict__: |
| 151 |
raise AttributeError("%r object has no attribute %r" % ( |
| 152 |
self.__class__.__name__, attr)) |
| 153 |
else: |
| 154 |
raise AttributeError("readonly attribute") |
| 155 |
|
| 156 |
def structseq_repr(self): |
| 157 |
fields = {} |
| 158 |
for field in type(self).__dict__.values(): |
| 159 |
if isinstance(field, structseqfield): |
| 160 |
fields[field.index] = field |
| 161 |
parts = ["%s=%r" % (fields[index].__name__, value) |
| 162 |
for index, value in enumerate(self)] |
| 163 |
return "%s(%s)" % (self._name, ", ".join(parts)) |
| 164 |
|
| 165 |
|
| 166 |
class SimpleNamespace: |
| 167 |
"""A simple attribute-based namespace. |
| 168 |
|
| 169 |
SimpleNamespace(**kwargs)""" |
| 170 |
|
| 171 |
def __init__(self, **kwargs): |
| 172 |
self.__dict__.update(kwargs) |
| 173 |
|
| 174 |
def __repr__(self): |
| 175 |
ident = id(self) |
| 176 |
if ident in sns_recurse: |
| 177 |
return "namespace(...)" |
| 178 |
sns_recurse.add(ident) |
| 179 |
try: |
| 180 |
pairs = ('%s=%r' % item for item in sorted(self.__dict__.items())) |
| 181 |
return "namespace(%s)" % ', '.join(pairs) |
| 182 |
finally: |
| 183 |
sns_recurse.discard(ident) |
| 184 |
|
| 185 |
def __eq__(self, other): |
| 186 |
if issubclass(type(other), SimpleNamespace): |
| 187 |
return self.__dict__ == other.__dict__ |
| 188 |
return NotImplemented |
| 189 |
|
| 190 |
def __ne__(self, other): |
| 191 |
if issubclass(type(other), SimpleNamespace): |
| 192 |
return self.__dict__ != other.__dict__ |
| 193 |
return NotImplemented |
| 194 |
|
| 195 |
sns_recurse = set() |
| 196 |
|
| 197 |
|
| 198 |
SimpleNamespace.__module__ = 'types' |