Queef
Queef

Reputation: 11

Python, Use a string argument to point to defined list/array object

Is it possible in python to have a string argument point to a defined object in the script?

For example, Lets say our argument is -layers and I have a list called convloop defined in the script as

convloop = ['conv2/3x3', 'conv2/3x3_reduce', 'conv2/3x3']

and i pass 'python example.py -layers convloop'

I need it to take that arg string(convloop) and point to the actual convloop list(array) not just the string 'convloop'

I know i can do

if args.layers == 'convloop':
    #loop over layers as set in convloop array
    endparam = convloop[frame_i % len(convloop)]

And that will call the list(array) 'convloop' if the argstring is 'convloop' and cycle through the list

However I have multiple lists in my script, and instead of rewritting this code each time for each list I want it to read the argstring and point to the matching list object so i can pass for example:

'python example.py -layers pooploop' and 'python example.py' -layers fartloop' and have them point to the pooploop and fartloop lists accordingly

I am using python 2.7 btw

Upvotes: 1

Views: 68

Answers (1)

Eric Duminil
Eric Duminil

Reputation: 54223

You could use globals() or locals() to get the corresponding object:

>>> oneloop = [1,2,3]
>>> globals()["oneloop"]
[1, 2, 3]

You probably shouldn't, though : it could be dangerous. It's also an indication that you should rethink the architecture of your script.

A dict would be a better idea:

>>> possible_loops = {"oneloop": [1,2,3], "twoloop": [4,5,6]}
>>> possible_loops
{'oneloop': [1, 2, 3], 'twoloop': [4, 5, 6]}
>>> possible_loops['oneloop']
[1, 2, 3]

Upvotes: 2

Related Questions