What is the best way to do what I am trying to do here, which is to define a variable within a function that is then used in a method, but I obtain the error:
AttributeError: module 'reference_A_Z' has no attribute 'args'
Is there a better way to do this?
# Import .py
import reference_A_Z as ref
# Define function to obtain the key:value
def function(VAR1):
for key, value in ref.VAR1.items():
try:
foo = foo1
except KeyError:
print("KeyError")
# Define args.input
args = parser.parse_args('-i RefA'.split())
# Run the function
function(args.input)
I have made sure that reference_A_Z
contains a dictionary called RefA
. If I substitute with the string RefA
the function works and there are no errors.
CodePudding user response:
You want to dynamically reference objects within a module. The dot-notation won't work because the attribute will not get substituted as a variable. Instead, you can use getattr
.
def function(VAR1):
try:
obj = getattr(ref, VAR1)
except AttributeError:
print(f'No object named {VAR1} in ref.')
for key, value in obc.items():
try:
foo = foo1
except KeyError:
print("KeyError")