2

Behold my simple class:

import sys

class Foo(object):

  def __init__(self):
    self.frontend_attrs = ['name','ip_address','mode','port','max_conn']
    self.backend_attrs  = ['name','balance_method','balance_mode']

The init method above creates two lists and I want to refer to them both dynamically:

def sanity_check_data(self):
  self.check_section('frontend')
  self.check_section('backend')

def check_section(self, section):
  # HERE IS THE DYNAMIC REFERENCE
  for attr in ("self.%s_attrs" % section):
    print attr

But when I do this, python complains about the call to ("self.%s_attrs" % section).

I've read about people using get_attr to find modules dynamically...

getattr(sys.modules[__name__], "%s_attrs" % section)()

Can this be done for dictionaries.

2
  • 1
    You want getattr(self, '{}_attrs'.format(section)) Commented Oct 2, 2014 at 15:51
  • 1
    You shouldn't be keeping data in your variable names at all, really. That's just asking for trouble. You should keep those two dictionaries in another structure, maybe even another dictionary. Commented Oct 2, 2014 at 15:52

1 Answer 1

6

What you're looking for I think is getattr(). Something like this:

def check_section(self, section):
    for attr in getattr(self, '%s_attrs' % section):
        print attr

Although with that specific case, you might be better off with a dict, just to keep things simple:

class Foo(object):

  def __init__(self):
    self.my_attrs = {
      'frontend': ['name','ip_address','mode','port','max_conn'],
      'backend': ['name','balance_method','balance_mode'],
    }

  def sanity_check_data(self):
    self.check_section('frontend')
    self.check_section('backend')

  def check_section(self, section):
    # maybe use self.my_attrs.get(section) and add some error handling?
    my_attrs = self.my_attrs[section]
    for attr in my_attrs:
      print attr
Sign up to request clarification or add additional context in comments.

1 Comment

Glad to help! If you click on the check icon next to the counter, then it will mark the question as solved with that particular answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.