Page 1 of 1

use variable contents not variable name

Posted: Mon Apr 10, 2017 2:37 pm
by Davies
im trying to render a form in web.py using a user login name(carried by a variable) and a predefined form name based on the page that is been viewed (ie temperatures from around house for me and separate page with temps around house my missus would be interested in) but im stuck on stitching those 2 variables together to yield another variables name.
i think in its simplest form what im trying to do is get something like this to print the contents of the variable im calling..

Code: Select all

attempting = "it worked"
attempter = "this also worked"
variable = 'attempt'
to_print = variable+'ing'
print to_print
to_print = variable+'er'
print to_print
any help would be greatly appreciated

Re: use variable contents not variable name

Posted: Mon Apr 10, 2017 3:29 pm
by scotty101
Not really something that is recommended... but here is a hack that only works if the variable is part of the global namespace.

Code: Select all

attempting = "it worked"
attempter = "this also worked"
variable = 'attempt'

varname = variable+'ing'
print( globals()['varname'])

varname = variable+'er'
print( globals()['varname'])

Re: use variable contents not variable name

Posted: Mon Apr 10, 2017 3:40 pm
by Davies
thanks for the reply scotty,
i had to remove the apostrophes around varname ( globals()[varname]) to get the code to return correctly, but i was then able to use that method within my main script.

thanks again, but why wouldnt it be recommended?

Re: use variable contents not variable name

Posted: Mon Apr 10, 2017 4:44 pm
by EliasNystuen
I been trying to learn more about coding. This is informative.

Keep it up.

Elias, Fornye kjøkken

Re: use variable contents not variable name

Posted: Mon Apr 10, 2017 4:44 pm
by scotty101
As I said, it only works where the variable is a global. If this code was in a function or a class, it wouldn't work.

Without seeing what you are trying to achieve, it is difficult to propose what you are trying to do and how to make it more 'pythonic'. I suspect that using a dictionary would be better.