473,703 Members | 2,863 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 7112
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,nam e,widget.get_te xt())

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(objec t):
def __init__(self, name, text=None):
self.name = name
self.text = text

firstname = FormField("Firs t 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(sel f)
last_name = wx.TextCtrl(sel f)
job_title = wx.TextCtrl(sel f)
etc.

and subsequently:

sizer.Add(first _name)
sizer.Add(last_ name)
sizer.Add(job_t itle)
etc.

I want to do something like this:

for name in names:
name = wx.TextCtrl(sel f)
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 overcomplicatin g 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

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

Similar topics

11
2085
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 change when I'm building interfaces. With a bit of tweaking I have been able to give the widgets a look that rivals the best of them. However, I get tired of doing this when I'm writing code and would like a way that I could universally change them on my system. I have tried to find where in...
1
3458
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 defined in the class specification. The constructor also had a variable of the same name defined. We wondered why later on in the program things crashed. Well its obvious now, but there were absolutly no complier warnings about this variable. C++ doesn't seem to mind this and accepts it as...
22
3952
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 text color from html document I write: <body text="#dddddd"> And to define text color from css file I need to write:
15
2260
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. Regards,
5
2576
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 intermittantly, and when it does the variable list is incomplete or contains variables that do not even exist in the project being worked on. It seems like there should be a setting to turn this on and keep it up to date but I cannot find anything in MSDN. It is also a complete mystery why it...
16
6722
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 difference between these two: number = 3; n = 3; I know its setting aside storage for the variable itself; does it also use up more storage if the variable name is longer? I realize it would probably take quite a lot of long variable names to make any impact if so, but I was just curious...
5
2634
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 want to randomly select one of them and get its value.So I pick a random number between 0 and 9 and concat it with 'b' to get the name of this variable.But how do I get the value of this variable? I tried to define a macro using b##num,but it results in bnum instead of b5 for example.
4
3331
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 any rules for valid names yet) - but I have a feeling that it's unnecessary complex? Any input would be greatly appreciated. #include <stdio.h> #include <stdlib.h> int get_ops(char *sen, char ***atom, char limit);
6
1885
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 figure know to use Regular Expression to do that. Is it possible?
0
8739
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9089
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8983
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8941
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7832
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5910
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4412
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4668
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3107
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.