3

When an object attribute has colon in its name, how to use the attribute? The code where I came across this situation is :

instances = nova.servers.list()
for i in instances:
        print i.id, i.OS-EXT-SRV-ATTR:hypervisor_hostname

After looking at the link Find All Elements Given Namespaced Attribute and How do I escape a colon in Python format() when using kwargs? I tried using attr as

instances = nova.servers.list()
for i in instances:
        print i.id, i.(attr={"OS-EXT-SRV-ATTR":"hypervisor_hostname"})

But it gives error as Invalid syntax. How should I use the attribute OS-EXT-SRV-ATTR:hypervisor_hostname

Community
  • 1
  • 1
Veena
  • 115
  • 1
  • 9

2 Answers2

2

Don't use objects with attributes with such names. Use a dict.

It's possible to set and get attributes with invalid Python names:

Python 2.7.5+ (default, Sep 19 2013, 13:48:49) 

>>> class A():
...     pass
... 

>>> a = A()

>>> setattr(a, 'OS-EXT-SRV-ATTR:hypervisor_hostname', 'some_string')

>>> a.OS-EXT-SRV-ATTR:hypervisor_hostname
  File "<ipython-input-5-849986a021bc>", line 1
    a.OS-EXT-SRV-ATTR:hypervisor_hostname
                     ^
SyntaxError: invalid syntax


>>> getattr(a, 'OS-EXT-SRV-ATTR:hypervisor_hostname')
>>> 'some_string'

>>> 

But don't do this, use a dict to store this info, not object's attributes.

warvariuc
  • 57,116
  • 41
  • 173
  • 227
0

With setattr(object, name, value) and read it with getattr(object, name[, default])ΒΆ

see also How do you programmatically set an attribute?

Why do you want to do this? I found myself in a situation where I needed wrap an AWS Cognito user fields within my own class rather than a dict.

        for attr in admin_get_user_dict['UserAttributes']:
            setattr(cognito_user, attr['Name'], attr['Value'])

In Cognito, custom attributes are prefixed by custom:[your_attr_name] so there you have it. And yes, you want to avoid this at any cost if you are designing your own classes.

Enrique G
  • 342
  • 2
  • 6