stephenmurdoch
stephenmurdoch

Reputation: 34613

How can I dynamically refer to a variable in Python

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.

Upvotes: 2

Views: 1004

Answers (1)

Michael Schuller
Michael Schuller

Reputation: 494

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

Upvotes: 6

Related Questions