1

I'm trying to bind a variable to a specific list within a class at runtime. The snippet below works, but I'd like to have the class name in the eval expression instead of the variable. i.e. the equivalent of:

mybin = 'bin2'
eval(foo.mybin) 

which obviously won't work... but I can't seem to figure out the syntax after various incarnations of trying to glue "foo' and "mybin' together.

class A:
    bin1 = [3,6,9]
    bin2 = [12,14,25]

foo = A()

mybin = 'foo.bin2'

for bin in eval(mybin):
    print bin

outputs:

 12
 14
 25
0

2 Answers 2

2

Don't use eval. For dynamic attribute access, python knows getattr:

mybin = 'bin2'
for bin in getattr(foo, mybin):
    print bin
Sign up to request clarification or add additional context in comments.

1 Comment

Hazards of old / other language programming habits! I'm new to python and had not run across getattr before. Thanks for the tip!
1

Maybe f-string is what you might be fond of:

class A():
  bin1 = [1, 2]
  bin2 = [12, 14, 25]

foo = A()

my_bin = 'bin2'

print(eval(f'foo.{my_bin}'))
#[12, 14, 25]

Comments

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.