0

I have a class instance of type <class 'openstack_dashboard.api.nova.Server'>:

 >>>print instance
 >>><Server: {'id': u'9fa3b2e9-a76b-44ae-be75-968d4010eb27', 
              'links': [{u'href': u'http://10.0.3.129:8774/v2/344f7fa036fc45008130cdf1cffac019/servers/9fa3b2e9-a76b-44ae-be75-968d4010eb27', u'rel': u'self'}, 
                        {u'href': u'http://10.0.3.129:8774/344f7fa036fc45008130cdf1cffac019/servers/9fa3b2e9-a76b-44ae-be75-968d4010eb27', u'rel': u'bookmark'}]}>
 >>> print dir(instance)
 >>> ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', 
      '__getattr__', '__getattribute__', '__hash__', '__init__', 
      '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
      '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
      '__weakref__', '_apiresource', '_attrs', 'image_name', 
      'internal_name', 'request']

I want to get the 'id' ('9fa3b2e9-a76b-44ae-be75-968d4010eb27'). What should I do ? Thank you !

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
changzhi
  • 2,641
  • 9
  • 36
  • 46

3 Answers3

2

According to what I can see in the source, Server inherits from the common APIResourceWrapper, which in turn implements __gatattr__ so that id, while it's not exactly an object's own attribute, will be taken from the internal container self._apiresource.

So, instance.id will work and will effectively return instance._apiresource.id.

bereal
  • 32,519
  • 6
  • 58
  • 104
1

Class openstack_dashboard.api.nova.Server inherits from openstack_dashboard.api.base.APIResourceWrapper and this class has defined __getattr__() method which uses self._attrs, so I think it should be possible to read id in this way:

print(instance.id)
vmario
  • 411
  • 3
  • 15
0

This might work now for you, but it's implementation-dependent:

import re
printed = instance.__str__() #might also be __repr__()
m = re.search("'id'\s*:\s*u'([\w+\-]+)'", printed)
m.groups(0)[0] #returns 9fa3b2e9-a76b-44ae-be75-968d4010eb27
MadeOfAir
  • 2,933
  • 5
  • 31
  • 39
  • Thanks for the downvote :). Well, that's why I answered in the first place. And that proves I can see into the future so i've put 'might' and 'implementaion-dependent' up-there. – MadeOfAir Jan 09 '14 at 09:13
  • The downvote is mine. Sorry, I usually don't mock anyone that straight, but this makes even better codewtf than infamous `if (boolvalue.toString().length() == 4) {...}`. – bereal Jan 09 '14 at 09:17
  • You have just given me a great code snippet that I know going to save my butt someday. Thank you bereal!. – MadeOfAir Jan 09 '14 at 09:26