0

Is it possible to do the following

This works

usethismodule.LoginUsername="my value"
usethismodule.LoginPassword="another value"

But I don't know the second part of the object until the code is being run, I think what I want is this

listofthings=[]
listofthings.append('usethismodule.LoginUsername')
listofthings.append('usethismodule.LoginPassword')

for value in listofthings:
    value="A value I set"

This would have the same outcome as the above. Does that make sense?

linusg
  • 6,289
  • 4
  • 28
  • 78
mozman2
  • 911
  • 1
  • 8
  • 17
  • You might want `setattr`, for example, `setattr(usethismodule, 'LoginUsename', "my value")` – chepner Mar 03 '17 at 15:12
  • 1
    Possible duplicate of [Using a string variable as a variable name](http://stackoverflow.com/q/11553721/953482). Short answer: use a dict. – Kevin Mar 03 '17 at 15:13

2 Answers2

2

Indeed, setattr and a dictionary would do the trick.

dictofthings = {
    'usethismodule.LoginUsername': 'my value',
    'usethismodule.LoginPassword': 'my other value'
}

for k in dictofthings:
    setattr(eval(k.split('.')[0]), k.split('.')[1], dictofthings[k])

Hope this helps!

linusg
  • 6,289
  • 4
  • 28
  • 78
  • But the module name is part of the data as well. You made it part of the code. – Stefan Pochmann Mar 03 '17 at 15:27
  • OK, changed. Note that eval *may* be a security hole, but `ast.literal_eval` won't work. Is this better? – linusg Mar 03 '17 at 15:30
  • I'd say it's better because that's what they apparently want, but worse because of that eval security issue :-). Maybe a mix of your answer and Austin's answer (which assumes a single module name) would be best. – Stefan Pochmann Mar 03 '17 at 15:35
0

You keep saying usethismodule.<something>. So let's pretend you're right.

Python maintains a dict of currently imported modules in sys.modules. You can look up a module, by name, and get an "object". (A module object, in fact.)

If you have an object in hand, you can either hard-code an access to one of its attributes, or use getattr or setattr on it.

import sys

module_name = "usethismodule"   # I don't know where this come from.

utm = sys.modules[module_name]

utm.LoginUsername = "xyzzy"
utm.LoginPassword = "secret123"

# or

pw_attr_name = "passWord"       # Maybe you read this from a config file?
setattr(utm, pw_attr_name, "secret123")
aghast
  • 14,785
  • 3
  • 24
  • 56