Skip to content
Advertisement

Variable string inside variable name

I know this is a bad title, and I realize that dictionaries are usually the way to solve this, but I’m not sure how they would solve the issue in my particular case.

I am using argsparse to collect inputs from the user. Two of the variables we’ll call args.session_1 and args.session_2 which refer to paths.

Later in my script, I iterate through sessions 1 and 2, and I also need to iterate through the directories referred to by the args.session_{ } paths. However, I’m not sure how to do the latter.

I typically use f-strings, for example, but it wouldn’t work like this:

for session in [1, 2]:
    for file in os.listdir(f'args.session_{session}'):
        do whatever

Here, args.session_1 is a string, not a variable name, so this doesn’t work. My question is, how can I have args.session_{ } still be a variable name but also have the session itself a variable?

Would this require using a dict? I wasn’t sure how that would help since the dictionary value would have the same issue of being a string.

Advertisement

Answer

Use getattr() to access attributes dynamically.

for session in [1, 2]:
    for file in os.listdir(getattr(args, 'session_' + session)):
        # do whatever
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement