472,353 Members | 1,378 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,353 software developers and data experts.

storing variable names in a list before they are used?

If I want to have a list like this:

[(first_name, 'First Name:'), (last_name, 'Last Name:').....]

where the first part of each tuple is a variable name and the second
part is a label for the user to see, such as a form like this:

First Name: ________
Last Name: ________

(the variables would store whatever information is entered in the text
boxes to the right of each label. I'm doing it this way so I can write a
loop to construct my GUI components).

how would I go about putting these variable names in a list? I know I
can't leave them as above, but if I put them in as a string, then how do
I later "transform" them into an actual variable for assign, such as:

first_name = widget.get_text()

Is there some kind of idiom that does this sort of work?

Thanks.
Sep 29 '06 #1
10 6929
Hi John

John Salerno wrote:
how would I go about putting these variable names in a list? I know I
can't leave them as above, but if I put them in as a string, then how do
I later "transform" them into an actual variable for assign, such as:

first_name = widget.get_text()

Is there some kind of idiom that does this sort of work?
What scope do you want these variable names to show up in? For example,
if you want them to be defined in the global scope then you can do the
following:

name = 'first_name'

globals()[name] = widget.get_text()

print first_name
If you want these variables to be assigned to an object then you can use
setattr():
name = 'first_name'

setattr(obj,name,widget.get_text())

print obj.first_name
Hope this helps

-Farshid
Sep 29 '06 #2

John Salerno wrote:
If I want to have a list like this:

[(first_name, 'First Name:'), (last_name, 'Last Name:').....]

where the first part of each tuple is a variable name and the second
part is a label for the user to see, such as a form like this:

First Name: ________
Last Name: ________

(the variables would store whatever information is entered in the text
boxes to the right of each label. I'm doing it this way so I can write a
loop to construct my GUI components).

how would I go about putting these variable names in a list? I know I
can't leave them as above, but if I put them in as a string, then how do
I later "transform" them into an actual variable for assign, such as:

first_name = widget.get_text()

Is there some kind of idiom that does this sort of work?

Thanks.
Not sure but mmaybe this older post might help:
http://mail.python.org/pipermail/tut...ry/035232.html

JM

Sep 29 '06 #3
Ant

John Salerno wrote:
If I want to have a list like this:

[(first_name, 'First Name:'), (last_name, 'Last Name:').....]

where the first part of each tuple is a variable name and the second
....
can't leave them as above, but if I put them in as a string, then how do
I later "transform" them into an actual variable for assign, such as:

first_name = widget.get_text()
A better way of doing it may be to use a dictionary thus:

name_map = {"First Name": None, "Last Name": None}

and then assign the value:

name_map["First Name"] = widget.get_text()

Or alternatively if you were adamant you wanted your original format:

firstname = [None]
lastname = [None]

[(firstname, 'First Name:'), (lastname, 'Last Name:')]

firstname[0] = widget.get_text()

But that's a bit of a hack.

The problem you are having here is a conceptual one: When you put a
variable name in a list or tuple, it isn't the *name* that's stored but
the actual value. I would think about using the dictionary version
above, or if things are getting more complicated, then create a class
to produce objects that contain the structure you want:

class FormField(object):
def __init__(self, name, text=None):
self.name = name
self.text = text

firstname = FormField("First Name", "Default Text")
lastname = FormField("Last Name")

fields = [firstname, lastname]

lastname.text = widget.get_text()

The same of course could be accompished using pairs or dictionaries
(e.g. firstname = {"name": "First Name", "text": "Default Text"};
lastname = {"name": "Last Name"} ), but I think that the class based
version self documents itself a bit better.

Sep 29 '06 #4
John Salerno wrote:
If I want to have a list like this:

[(first_name, 'First Name:'), (last_name, 'Last Name:').....]
Do you need the data to be ordered? If not, just use a dictionary:

d = {'First Name:': '', 'Last Name:': ''}
d['First Name:'] = 'Bob'
d['Last Name:'] = 'Smith'
print "Hi, I'm %s %s." % (d['First Name:'], d['Last Name:'])

If so, check out the ordered dictionary module [1]:

from odict import OrderedDict as odict
od = odict([('First Name:', ''), ('Last Name:', '')])
od['First Name:'] = 'James'
od['Last Name:'] = 'Bond'
for k,v in od.items():
print "%s =%s" % (k,v)

[1] http://www.voidspace.org.uk/python/odict.html

Regards,
Jordan

Sep 29 '06 #5
John Salerno wrote:
If I want to have a list like this:

[(first_name, 'First Name:'), (last_name, 'Last Name:').....]

where the first part of each tuple is a variable name and the second
part is a label for the user to see, such as a form like this:

First Name: ________
Last Name: ________

(the variables would store whatever information is entered in the text
boxes to the right of each label. I'm doing it this way so I can write a
loop to construct my GUI components).

how would I go about putting these variable names in a list? I know I
can't leave them as above, but if I put them in as a string, then how do
I later "transform" them into an actual variable for assign, such as:

first_name = widget.get_text()

Is there some kind of idiom that does this sort of work?

Thanks.
There are ways you can do this, but the best advice is "don't". If you
are putting names into a Python namespace that aren't known in advance
then you also have to use similarly obscure techniques to access the
variables, and you are running the risk that your code will collide whit
a name of a variable already used in that namespace by your code.

What's wring with just using a dict to store the values against the
names? Dicts and namespaces have a lot of behaviour in common.

regard
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Sep 30 '06 #6
John Salerno wrote:
(the variables would store whatever information is entered in the text
boxes to the right of each label. I'm doing it this way so I can write a
loop to construct my GUI components).
Thanks very much for the responses guys. I actually tried something
similar with a dictionary already, but then I discovered the obvious: I
need them in a certain order! :)

Here is what I want to do more specifically: I am creating a single
frame (wxPython terminology for a window) and the user will be able to
click a "New" button which will open a new tab in that frame (using the
wx.Notebook class). Each time a new tab is opened, it will contain a
form to fill out, with a label widget on the left ("First Name:") and a
text box control on the right (the underlines), like this:

First Name: ________
Last Name: ________
Job Title: ________
etc.
etc.

In wxPython, you can use "sizers" for layout control, and in this case
the FlexGridSizer is ideal. You just assign the above widgets to it in
this order: first label, first textbox, second label, second textbox, etc.

Instead of manually creating these widgets and adding all of them to the
sizer (and having to add or delete code later in case something changes)
I wanted to use some type of for loop to do it for me. This is easy for
creating and adding the labels, because I need no reference for them
later. But I will need a reference for the textboxes so I can later get
the data that is in them.

So my original question involved finding a way to assign a variable name
to the textboxes while they are being automatically created in a for
loop. This seems like something that is probably done quite often and
maybe I'm just not thinking of the proper idiom that is used.

Thanks!
Sep 30 '06 #7
John Salerno wrote:
Here is what I want to do more specifically:
Ok, I'm sure you all get the idea by now, but here's a simpler way to
look at it:

Instead of

first_name = wx.TextCtrl(self)
last_name = wx.TextCtrl(self)
job_title = wx.TextCtrl(self)
etc.

and subsequently:

sizer.Add(first_name)
sizer.Add(last_name)
sizer.Add(job_title)
etc.

I want to do something like this:

for name in names:
name = wx.TextCtrl(self)
sizer.Add(name)

It's just that I don't know how to handle the "name" variable in the
"names" list.
Sep 30 '06 #8
Dennis Lee Bieber wrote:

Longer answer... "names" is a list of strings which can be used as
keys into a dictionary.
Thanks for all that! I like the idea of a dictionary, so I might try
that, although it does seem to be overcomplicating things a bit (almost
by necessity, though, given what I want to do).

But I suppose it's still a better solution than manually creating every
widget and adding it to the sizer.
Sep 30 '06 #9
Dennis Lee Bieber wrote:
Look toward the potential future... Wherein your entire GUI is
defined with something like XML. Basically you'd be parsing the XML into
some structure (of structures) in which the only real access to the data
requires looking up the substructure using some fixed identifier.
Yeah, this is supported by wxPython, but I don't fully understand it
yet. I also feel like if I start using XML before I really learn how to
hand-code all of this in wxPython, then I'm missing out on learning the
real basics of doing it myself.
Oct 1 '06 #10
"Dennis Lee Bieber" <wl*****@ix.netcom.comwrote:
On Sat, 30 Sep 2006 14:33:35 -0400, John Salerno
<jo******@NOSPAMgmail.comdeclaimed the following in comp.lang.python:

Ok, I'm sure you all get the idea by now, but here's a simpler way to
look at it:

Instead of

first_name = wx.TextCtrl(self)
last_name = wx.TextCtrl(self)
job_title = wx.TextCtrl(self)
etc.

and subsequently:

sizer.Add(first_name)
sizer.Add(last_name)
sizer.Add(job_title)
etc.

I want to do something like this:

for name in names:
name = wx.TextCtrl(self)
sizer.Add(name)

It's just that I don't know how to handle the "name" variable in the
"names" list.

Short blunt answer... You Don't
Longer, less blunt answer:

You could, if you wanted to, write:

errfile = "name_of_error_file_for_compile_statement"
expr = name+" = wx.TextCtrl(self)"
eval(compile(expr, errfile,'single'))

and the name that reads the same as the text string should be created.

To access it, you can then use:

sizer.Add(eval(name))

Example:

IDLE 1.1.3 ==== No Subprocess ====
>>banana
Traceback (most recent call last):
File "<pyshell#0>", line 1, in ?
banana
NameError: name 'banana' is not defined
>>name = "banana"
errfile='errfile'
expr = name+'="A yellow sickle shaped fruit"'
eval(compile(expr,errfile,'single'))
banana
'A yellow sickle shaped fruit'
>>name
'banana'
>>eval(name)
'A yellow sickle shaped fruit'
>>>
*ducks behind asbestos shelter to hide from the predicted flames *

But Seriously - I think eval is good for just this kind of purpose - does what
was wanted, namely creating the variable with the same name as the content of a
string... - its also useful to access a variable if you have been given its name
in a string, instead of being passed the thing itself - then you don't need the
compile bit...

Caveat Emptor

- Hendrik


Oct 1 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: Harlin Seritt | last post by:
There are certain options for Tkinter widgets that have default values that I don't much care for (borderwidth, font come to mind) and continuously...
1
by: JustSomeGuy | last post by:
I just spent a few hours trying to find a bug in a friends code. I finally found it, but I'm shocked to see what is wrong. A private variable was...
22
by: opt_inf_env | last post by:
Hello, It is strange to me that html and css use different names for variables which define the same properties. For example if I whant to define...
15
by: James | last post by:
Hi, I am finding it increasingly difficult to name my variables. I am not able to think in the right way. Expert C programmers please Help. ...
5
by: Brakeshoe | last post by:
I would like to find out how to turn on the Auto Complete variable names feature while editing source code in Visual Studio. It seems to appear on...
16
by: John | last post by:
Does the length of my C variable names have any affect, performance-wise, on my final executable program? I mean, once compiled, etc., is there any...
5
by: panthera | last post by:
Hi, I have a problem regarding generating variable names in my program.Suppose I have 10 variables b0,b1,b2...b9.They are NOT in an array.And I...
4
by: Victor Lagerkvist | last post by:
Hello, I have the need to parse variable names from a string and save them somewhere safe for future usage. Here's my first attempt (I don't have...
6
by: Academia | last post by:
I want to search for Dim and replace it with Dim That is, I want to change the first character of Dim variable names to upper case. I can't...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand....
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.