Davies
Posts: 150
Joined: Sat Apr 04, 2015 4:24 pm

use variable contents not variable name

Mon Apr 10, 2017 2:37 pm

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

scotty101
Posts: 3958
Joined: Fri Jun 08, 2012 6:03 pm

Re: use variable contents not variable name

Mon Apr 10, 2017 3:29 pm

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'])
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

Davies
Posts: 150
Joined: Sat Apr 04, 2015 4:24 pm

Re: use variable contents not variable name

Mon Apr 10, 2017 3:40 pm

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?

EliasNystuen
Posts: 1
Joined: Mon Apr 10, 2017 4:17 pm
Contact: Website

Re: use variable contents not variable name

Mon Apr 10, 2017 4:44 pm

I been trying to learn more about coding. This is informative.

Keep it up.

Elias, Fornye kjøkken

scotty101
Posts: 3958
Joined: Fri Jun 08, 2012 6:03 pm

Re: use variable contents not variable name

Mon Apr 10, 2017 4:44 pm

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.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

Return to “Python”