0

I have a class named TEST in a configuration file config.py as follows:

# file config.py
class TEST():
    alpha = 0.05

and a file run.py from which I try to access attributes of the class TEST through input argument as follows:

# file run.py
import sys
import config

if __name__ == "__main__":
    conf = sys.argv[1]   # comes from input argument conf=TEST
    obj1 = config.TEST() # this works
    print(obj1.alpha)    # prints alpha variable 0.05
    obj2 = config.conf() # AttributeError: module 'config' has no attribute 'conf'
    print(obj2.alpha)

By running it as python3 run.py TEST, it gives attribute error in obj2, as it cannot convert the conf variable to TEST and access the class TEST. Any idea how to solve this?

ABarrier
  • 888
  • 1
  • 6
  • 8

1 Answers1

0

Problem fixed by using the getattr from this thread:

Calling a function of a module by using its name (a string)

The code modification is as follows:

# file run.py
import sys
import config

if __name__ == "__main__":
    conf = sys.argv[1]             # comes from input argument conf=TEST
    obj1 = config.TEST()           # this works
    print(obj1.alpha)              # prints alpha variable 0.05
    obj2 = getattr(config, conf)() # 
    print(obj2.alpha)              # prints alpha variable 0.05

which by running it python3 run.py prints the desired.

ABarrier
  • 888
  • 1
  • 6
  • 8