473,405 Members | 2,445 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 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 7080
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 change when I'm building interfaces. With a bit...
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 defined in the class specification. The...
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 text color from html document I write: <body...
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. Regards,
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 intermittantly, and when it does the variable...
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 difference between these two: number = 3; n =...
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 want to randomly select one of them and get its...
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 any rules for valid names yet) - but I have a...
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 figure know to use Regular Expression to do that....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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...
0
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...
0
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.