Atlas  0.7.0
Networking protocol for the Worldforge system.
__init__.py
1 # atlas objects
2 
3 # Copyright 2000-2002 by Aloril
4 
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License, or (at your option) any later version.
9 
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
14 
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 
19 
20 # counter = 0
21 
22 # counter = 0
23 from collections import UserDict
24 from collections import UserList
25 
26 # from gen_xml import gen_xml
27 import atlas
28 from atlas.gen_bach import gen_bach
29 # from gen_xml import gen_xml
30 from atlas.gen_bach import gen_bach
31 
32 
33 def cmp(x, y): (x > y) - (x < y)
34 
35 
36 class Object(UserDict):
37  """handles all Atlas objects"""
38 
39  def __init__(self, **kw):
40  """usage: Object(id="human", objtype="class", parents=["living"])
41  acts like normal python class and dictionary at the same time
42  in addition looks for atributes from parent objects
43  """
44  if "from_" in kw:
45  kw["from"] = kw["from_"]
46  del kw["from_"]
47  UserDict.__init__(self, kw)
48 
49  def __setattr__(self, name, value):
50  if name == "data":
51  self.__dict__ = value
52  else:
53  if name[-1] == "_":
54  name = name[:-1]
55  self.__dict__[name] = value
56 
57  def __getattr__(self, name):
58  """look first for attribute at this object
59  if not available, then go trough all parent object looking
60  for attrbiutes
61  """
62  # global counter
63  # if counter==100:
64  # raise ValueError, "counter too big"
65  # counter = counter + 1
66  # print "start:", self.__class__, name
67  if len(name) > 1 and name[-1] == "_" and name[-2] != "_":
68  return getattr(self, name[:-1])
69  if name == "data": return self.__dict__
70  # print "before __dict__:", self.__class__, name
71  if name in self.__dict__:
72  return self.__dict__[name]
73  # print "before __class__.__dict__:", self.__class__, name
74  if name in self.__class__.__dict__:
75  return self.__class__.__dict__[name]
76  # print "before parent:", self.__class__, name
77  parent = None
78  if "parent" in self.__dict__:
79  # print "getting parent_list from __dict__"
80  parent = self.__dict__["parent"]
81  elif "parent" in self.__class__.__dict__:
82  # print "getting parent_list from __class__.__dict__"
83  parent = self.__class__.__dict__["parent"]
84 
85  # try:
86  # cl = parent.__class__
87  # print "before parent:", cl
88  # except AttributeError:
89  # print "before parent:", parent
90  if (isinstance(parent, Object) or class_inherited_from_Object(parent)) \
91  and hasattr(parent, name):
92  return getattr(parent, name)
93  # print "raise AttributeError:", self.__class__, name
94  raise AttributeError(name)
95 
96  def is_plain_attribute(self, name):
97  """is attribute plain?"""
98  value = getattr(self, name)
99  return is_plain(name, value)
100 
101  def get_plain_attribute(self, name):
102  """convert all references to parents, etc.. objects to string ids"""
103  value = getattr(self, name)
104  return convert2plain(name, value)
105 
106  def get_attr_pos(self, a):
107  try:
108  orig_order = self.specification_file.attribute_order
109  except AttributeError:
110  return 0
111  try:
112  pos = orig_order.index(a[0])
113  except ValueError:
114  pos = len(orig_order)
115  if a[0] == "specification_file":
116  pos = pos + 1
117  return pos
118 
119  def key_func(self, value):
120  return self.get_attr_pos(value)
121 
122  def items(self, convert2plain_flag=1, original_order=1,
123  all=0):
124  """like dictionary items method:
125  original_order: tries to preserver specification order if possible
126  all: list also inherited attributes (if possible)
127  """
128  if all:
129  attrs = list(self.get_all_attributes(
130  convert2plain_flag=convert2plain_flag).items())
131  else:
132  attrs = list(self.get_attributes(convert2plain_flag).items())
133  if original_order:
134  attrs = sorted(attrs, key=self.key_func)
135  return attrs
136 
137  def get_attributes(self, convert2plain_flag=1):
138  """list all attributes defined in this object:
139  returns dictionary: use items() for list"""
140  if convert2plain_flag:
141  res_dict = {}
142  for name, value in list(self.__dict__.items()):
143  if name[0] == "_":
144  continue
145  res_dict[name] = convert2plain(name, value)
146  return res_dict
147  else:
148  return self.__dict__
149 
150  def get_all_attributes(self, result_dict=None, convert2plain_flag=1):
151  """list all attributes including inherited ones:
152  returns dictionary: use get_all_attributes().items() for list"""
153  if result_dict == None:
154  result_dict = {}
155  parent = self.__dict__.get("parent")
156  if isinstance(parent, Object):
157  parent.get_all_attributes(result_dict)
158  result_dict.update(self.get_attributes(convert2plain_flag))
159  return result_dict
160 
161  def attribute_definition(self, name):
162  """give object that defines given attribute"""
163  if name in self.__dict__:
164  return self
165  parent = self.__dict__.get("parent")
166  if isinstance(parent, Object) and hasattr(parent, name):
167  return parent.attribute_definition(name)
168  raise AttributeError(name)
169 
170  def has_parent(self, parent):
171  if not isinstance(parent, str): parent = parent.id
172  if self.id == parent: return 1
173  parent_obj = self.__dict__.get("parent")
174  if isinstance(parent_obj, Object) and \
175  parent_obj.has_parent(parent):
176  return 1
177  return 0
178 
179  def get_objtype(self):
180  try:
181  return self.objtype
182  except AttributeError:
183  return "object"
184 
185  def __repr__(self):
186  string_list = []
187  add = string_list.append
188  for (name, value) in list(self.get_attributes().items()):
189  add('%s = %s' % (name, repr(value)))
190  return "Object(%s)" % ", ".join(string_list)
191 
192  def __str__(self):
193  return gen_bach(self)
194 
195 
196 def Operation(parent, arg=Object(), **kw):
197  kw["parent"] = parent
198  kw["objtype"] = "op"
199  kw["arg"] = arg
200  return Object(*(), **kw)
201 
202 
203 class Messages(UserList):
204  """list of operations"""
205 
206  def __init__(self, *args):
207  # print args, len(args), isinstance(args[0], Messages), type(args[0])
208  if len(args) == 1 and (isinstance(args[0], UserList) or isinstance(args[0], list)):
209  UserList.__init__(self, args[0])
210  else:
211  UserList.__init__(self, list(args))
212 
213  def get_objtype(self):
214  return "msg"
215 
216  def __str__(self):
217  return gen_bach(self)
218 
219 
220 # return string.join(map(str,self.data),"\n")
221 
222 def class_inherited_from_Object(cl):
223  if not isinstance(cl, type):
224  return 0
225  if cl == Object: return 1
226  for base in cl.__bases__:
227  if class_inherited_from_Object(base): return 1
228  return 0
229 
230 
231 uri_type = {"from": 1, "to": 1}
232 uri_list_type = {"parent": 1, "children": 1}
233 
234 
235 def attribute_is_type(name, type):
236  """is attribute of certain type somewhere in type hierarchy?"""
237  if type == "uri" and name in uri_type:
238  return 1
239  if type == "uri_list" and name in uri_list_type:
240  return 1
241 
242 
243 def is_plain(name, value):
244  if isinstance(value, dict) and attribute_is_type(name, "uri"):
245  return 0
246  if isinstance(value, list) and attribute_is_type(name, "uri_list"):
247  return 0
248  for value2 in value:
249  if isinstance(value2, dict):
250  return 0
251  return 1
252 
253 
254 def convert2plain(name, value):
255  """convert all references to parents, etc.. objects to string ids"""
256  if not is_plain(name, value):
257  if isinstance(value, dict):
258  value = value.id
259  else:
260  value = value[:]
261  for i in range(len(value)):
262  if isinstance(value[i], atlas.Object):
263  value[i] = value[i].id
264  return value
265 
266 
267 def find_ids_in_list(id_list, objects):
268  """finds all ids in list from objects dictionary keyed by ids"""
269  for i in range(len(id_list)):
270  if isinstance(id_list[i], str):
271  id_list[i] = objects[id_list[i]]
272 
273 
274 def find_parents_children_objects(objects):
275  """replace parent and children id strings with actual objects"""
276  for obj in list(objects.values()):
277  if hasattr(obj, "parent") and isinstance(obj.parent, str) and obj.parent != "":
278  obj.parent = objects[obj.parent]
279  else:
280  obj.parent = None
281  find_ids_in_list(obj.children, objects)
282 
283 
284 def has_parent(obj, parent, objects={}):
285  """has parent somewhere in hierarchy:
286  obj can be either string or object
287  (when it's string you need to provide
288  dictionary where it can be found)
289  parent can be either string or object
290  """
291  if isinstance(obj, str): obj = objects[obj]
292  return obj.has_parent(parent)
293 
294 
295 # create an entity from a dictionary
296 def make_object_from_dict(dict):
297  return Object(*(), **dict)
298 
299 
300 def resolve_pointer2(base_dict, id):
301  id_lst = id.split(".")
302  obj = base_dict
303  while id_lst:
304  if isinstance(obj, list):
305  id = int(id_lst[0])
306  else:
307  id = id_lst[0]
308  del id_lst[0]
309  if not id_lst: return obj, id
310  obj = obj[id]
311  raise KeyError("empty id")
312 
313 
314 def resolve_pointer(base_dict, id):
315  obj, id = resolve_pointer2(base_dict, id)
316  return obj[id]
317 
318 
319 def get_base_id(id):
320  return id.split(".")[0]
321 
322 
323 def get_last_part(id):
324  return id.split(".")[-1]
325 
326 
327 def print_parents(obj):
328  print(obj.id, end=' ')
329  o2 = obj
330  if hasattr(o2, "parent"):
331  o2 = o2.parent
332  if hasattr(o2, "id"):
333  print("->", o2.id, end=' ')
334  else:
335  print("->", o2, end=' ')
336  print()
atlas.Object.get_attr_pos
def get_attr_pos(self, a)
Definition: __init__.py:106
atlas.Object.get_plain_attribute
def get_plain_attribute(self, name)
Definition: __init__.py:101
atlas.Object.is_plain_attribute
def is_plain_attribute(self, name)
Definition: __init__.py:96
atlas.Object.__getattr__
def __getattr__(self, name)
Definition: __init__.py:57
atlas.Object.key_func
def key_func(self, value)
Definition: __init__.py:119
atlas.Object.get_all_attributes
def get_all_attributes(self, result_dict=None, convert2plain_flag=1)
Definition: __init__.py:150
atlas.Object.attribute_definition
def attribute_definition(self, name)
Definition: __init__.py:161
atlas.Object.items
def items(self, convert2plain_flag=1, original_order=1, all=0)
Definition: __init__.py:122
atlas.Object.__dict__
__dict__
Definition: __init__.py:51
atlas.Object.get_attributes
def get_attributes(self, convert2plain_flag=1)
Definition: __init__.py:137
atlas.Object.__init__
def __init__(self, **kw)
Definition: __init__.py:39
atlas.gen_bach
Definition: gen_bach.py:1
atlas.Object.id
id
Definition: __init__.py:172
atlas.Messages
Definition: __init__.py:203
atlas.Object
Definition: __init__.py:36