473,387 Members | 1,863 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,387 software developers and data experts.

variable hell

Nx

Hi

I am unpacking a list into variables, for some reason they need to be
unpacked into variable names like a0,a1,a2....upto aN whatever is
in the list.

How to create the variables dynamically ?

I am looking for something like
pseudo code line follows :

a%s = str(value)
here below is a snippet from the mylist unpack code

#next lines cut the end of line character from each line in the list
mylist = [line[:-1] for line in mylist]

for index,value in enumerate(mylist):
if index == 0 :
a0 = str(value)
print "a0 : ",a0
elif index == 1 :
a1 = str(value)
print "a1 : ",a1

Thanks
Nx

Aug 25 '05 #1
21 1643

Nx wrote:
I am unpacking a list into variables, for some reason they need to be
unpacked into variable names like a0,a1,a2....upto aN whatever is
in the list.


Explain this "some reason". This smells, and the way to go would be to
use a dict mapping a_n to whatever is in the list - not creating
variables. How do you want to access generated variables anyway -
especially when you don't have the faintest idea how many of them there
are? Obviously there can't be code written based on that.

Regards,

Diez

Aug 25 '05 #2
Nx enlightened us with:
I am unpacking a list into variables, for some reason they need to
be unpacked into variable names like a0,a1,a2....upto aN whatever is
in the list.


You're probably doing things the wrong way. What is your ultimate goal
with this? There is probably a better way of doing it.

In the mean time, look at eval().

Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa
Aug 25 '05 #3
Nx wrote:
Hi

I am unpacking a list into variables, for some reason they need to be
unpacked into variable names like a0,a1,a2....upto aN whatever is
in the list.


Really? Why?

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Aug 25 '05 #4
"Nx" <no****@nomail.com> wrote:
I am unpacking a list into variables, for some reason they need to be
unpacked into variable names like a0,a1,a2....upto aN whatever is
in the list.


why?

</F>

Aug 25 '05 #5
Nx schrieb:
Hi

I am unpacking a list into variables, for some reason they need to be
unpacked into variable names like a0,a1,a2....upto aN whatever is
in the list.

How to create the variables dynamically ?

I am looking for something like
pseudo code line follows :

a%s = str(value)

suffix = 'var'
vars()['a%s' % suffix] = 45
avar

45

--
-------------------------------------------------------------------
Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
-------------------------------------------------------------------
Aug 25 '05 #6
Peter Maas wrote:
>>> suffix = 'var'
>>> vars()['a%s' % suffix] = 45
>>> avar

45


Quoting from http://docs.python.org/lib/built-in-funcs.html#l2h-76 about
the "vars" built in:

The returned dictionary should not be modified: the effects on the
corresponding symbol table are undefined.
--
Benji York

Aug 25 '05 #7
Nx
Thanks for the many replies

here is an example for what it will be used for , in this case
fixed at 31 fieldvalues:

inputvalues=(s0,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11 ,s12,s13,s14,s15,s16,s17,s18,s19,s20,s21,s22,s23,s 24,s25,
s26,s27,s28,s29,s30,s31)
MYINSERTSELECT = "INSERT INTO
ADDRESS(ALIAS,COMPANY,ADDRESSLI1,ADDRESSLI2,ADDRES SCO,TOWN,ZIP,COUNTRY,TEL1,TEL2,FAX,EMAIL,INTERNET, PERSON1,TITLE1,RES1,PERSON2,TITLE2,RES2,PERSON3,TI TLE3,RES3,PERSON4,TITLE4,RES4,PERSON5,TITLE5,RES5, PRODALIAS,PAGER,TLX,ADDMEMO)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? ,?,?,?,?,?,?,?,?,?,?)"

con1.commit()
cur = con1.cursor()
try :
cur.execute(MYINSERTSELECT,inputvalues)
con1.commit()
print 'Inserted 1 record'
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
I am sure there is an easier way, but I have not found it yet.

Nx
Aug 25 '05 #8
Nx wrote:
Thanks for the many replies

here is an example for what it will be used for , in this case
fixed at 31 fieldvalues:

inputvalues=(s0,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11 ,s12,s13,s14,s15,s16,s17,s18,s19,s20,s21,s22,s23,s 24,s25,
s26,s27,s28,s29,s30,s31)
MYINSERTSELECT = "INSERT INTO
ADDRESS(ALIAS,COMPANY,ADDRESSLI1,ADDRESSLI2,ADDRES SCO,TOWN,ZIP,COUNTRY,TEL1,TEL2,FAX,EMAIL,INTERNET, PERSON1,TITLE1,RES1,PERSON2,TITLE2,RES2,PERSON3,TI TLE3,RES3,PERSON4,TITLE4,RES4,PERSON5,TITLE5,RES5, PRODALIAS,PAGER,TLX,ADDMEMO)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? ,?,?,?,?,?,?,?,?,?,?)"

con1.commit()
cur = con1.cursor()
try :
cur.execute(MYINSERTSELECT,inputvalues)


If I refer to your original post, there's someting I dont understand:
"""
I am unpacking a list into variables, for some reason they need to be
unpacked into variable names like a0,a1,a2....upto aN whatever is
in the list.
"""

Why unpack inputvalues if your next step is to pack'em back again ? Or
what did I miss ?
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Aug 25 '05 #9
On Thu, 2005-08-25 at 10:43, Nx wrote:
Thanks for the many replies

here is an example for what it will be used for , in this case
fixed at 31 fieldvalues:

inputvalues=(s0,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11 ,s12,s13,s14,s15,s16,s17,s18,s19,s20,s21,s22,s23,s 24,s25,
s26,s27,s28,s29,s30,s31)


inputvalues = tuple(mylist)

Hope this helps,

Carsten.
Aug 25 '05 #10
On Thu, 2005-08-25 at 11:04, I hastily wrote:
On Thu, 2005-08-25 at 10:43, Nx wrote:
Thanks for the many replies

here is an example for what it will be used for , in this case
fixed at 31 fieldvalues:

inputvalues=(s0,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11 ,s12,s13,s14,s15,s16,s17,s18,s19,s20,s21,s22,s23,s 24,s25,
s26,s27,s28,s29,s30,s31)


inputvalues = tuple(mylist)


And actually, you probably don't have to do that, because the execute
method should be able to handle a list just as well as a tuple.

-Carsten.
Aug 25 '05 #11
Nx
"""

Why unpack inputvalues if your next step is to pack'em back again ? Or
what did I miss ?

The original values in this case are being read from a text file
with one value including a linefeed per line and the original idea was,
that having them read into a list was the best way to massage them into the
form required to be used as input values for the insert statement.

Nx

Aug 25 '05 #12
Hey, if the man wants to write it that way, let the man write it that
way. If it works for him, great... he's sure confused the heck out of
all of us, and that translates into job security for him! As you can
see, the name of the post is 'variable hell' and that is exactly what
he is creating, so "Adriaan Renting", excellent response!

Aug 25 '05 #13
Nx wrote:
"""

Why unpack inputvalues if your next step is to pack'em back again ? Or
what did I miss ?


The original values in this case are being read from a text file
with one value including a linefeed per line and the original idea was,
that having them read into a list was the best way to massage them into the
form required to be used as input values for the insert statement.


Again, why unpack them into separate variables when they are *already*
in the form that you want to use them?

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Aug 25 '05 #14
In article <ma***************************************@python. org>,
Benji York <be***@benjiyork.com> wrote:
Peter Maas wrote:
>>> suffix = 'var'
>>> vars()['a%s' % suffix] = 45
>>> avar

45


Quoting from http://docs.python.org/lib/built-in-funcs.html#l2h-76 about
the "vars" built in:

The returned dictionary should not be modified: the effects on the
corresponding symbol table are undefined.


If you really want to make something like this work you can define a
class that would work like this:

vars = funkyclass()
varname = 'x'
vars[varname] = value
vars.x

But this is clearly a design mistake. Either you know the names of the
variables when you write the code or you do not. If you know them you
can simply assign them directly. If you do not know them then you can't
put them in the code to read their values anyway, and what you need is
just a regular dictionary.

rg
Aug 25 '05 #15
Ron Garret wrote:
If you really want to make something like this work you can define a
class that would work like this:

vars = funkyclass()
varname = 'x'
vars[varname] = value
vars.x

But this is clearly a design mistake. Either you know the names of the
variables when you write the code or you do not. If you know them you
can simply assign them directly. If you do not know them then you can't
put them in the code to read their values anyway, and what you need is
just a regular dictionary.


In fact, I do this all of the time.

class Bunch(dict):
def __init__(self, *args, **kwds):
dict.__init__(self, *args, **kwds)
self.__dict__ = self

It's a lifesaver when you're working at the interactive prompt. In the
bowels of my modules, I may not know what the contents are at code-time,
but at the prompt I probably do. Bunch assists both usages.

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Aug 25 '05 #16
Carsten Haese wrote:
On Thu, 2005-08-25 at 11:04, I hastily wrote:
On Thu, 2005-08-25 at 10:43, Nx wrote:
Thanks for the many replies

here is an example for what it will be used for , in this case
fixed at 31 fieldvalues:

inputvalues=(s0,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11 ,s12,s13,s14,s15,s16,s17,s18,s19,s20,s21,s22,s23,s 24,s25,
s26,s27,s28,s29,s30,s31)


inputvalues = tuple(mylist)

And actually, you probably don't have to do that, because the execute
method should be able to handle a list just as well as a tuple.

That depends on the database module. Some will insist in tuples, IIRC.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Aug 25 '05 #17
sp*****@gmail.com wrote:
Hey, if the man wants to write it that way, let the man write it that
way. If it works for him, great... he's sure confused the heck out of
all of us, and that translates into job security for him! As you can
see, the name of the post is 'variable hell' and that is exactly what
he is creating, so "Adriaan Renting", excellent response!


http://mindprod.com/jgloss/unmain.html

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Aug 25 '05 #18
In article <ma***************************************@python. org>,
Robert Kern <rk***@ucsd.edu> wrote:
In the
bowels of my modules, I may not know what the contents are at code-time,


Then how do you write your code?

rg
Aug 25 '05 #19
Ron Garret wrote:
In article <ma***************************************@python. org>,
Robert Kern <rk***@ucsd.edu> wrote:
In the
bowels of my modules, I may not know what the contents are at code-time,


Then how do you write your code?


With style. ;-)

I use a Bunch where I might otherwise use a dictionary inside my modules
because it *is* a dictionary. Interactively, I'll usually use it as an
object with attributes. The keys are usually ideosyncratic, like station
codes for permanent GPS stations (e.g. "CAND", "USLO", "MNMC", "MIDA"),
rather than generic (e.g. "northing", "day").

So I might have a function that do some analysis on all of the GPS
stations within a Bunch. I don't know the names of the stations when I'm
writing the function, but I can iterate over the keys and values in the
Bunch.

def subtract_reference(data, refstation):
"""Subtract the motion of the reference station from the remaining
timeseries.
"""
refdata = data[refstation]
for station in data:
if station == refstation:
continue
data[station].northing -= refdata.northing
data[station].easting -= refdata.easting
# ...

At the prompt, though, I may want to plot CAND's timeseries.

In [10]: plot(data.CAND.t, data.CAND.northing)

Bunch allows me to use "data[station]" and "data.CAND" as the situation
demands rather than forcing me to use the clunkier "getattr(data,
station)" or "data['CAND']", respectively.

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Aug 25 '05 #20
Benji York schrieb:
>>> suffix = 'var'
>>> vars()['a%s' % suffix] = 45
>>> avar

45

Quoting from http://docs.python.org/lib/built-in-funcs.html#l2h-76 about
the "vars" built in:

The returned dictionary should not be modified: the effects on the
corresponding symbol table are undefined.


I tried this once and it worked. This may be too naive, so thanks
for the warning :)

--
-------------------------------------------------------------------
Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
-------------------------------------------------------------------
Aug 26 '05 #21
What you could do is to create a class for this; fill it's __dict__
instance; and use custom getattr() / setattr() methods for accessing
a0, a1, a2 etc.

cheers,

--Tim

Aug 30 '05 #22

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

Similar topics

83
by: Alexander Zatvornitskiy | last post by:
Hello All! I'am novice in python, and I find one very bad thing (from my point of view) in language. There is no keyword or syntax to declare variable, like 'var' in Pascal, or special syntax in...
15
by: | last post by:
Hi, I want to do things this way: I have a bunch of stuff that I want to keep track of while a user is connected to the site. Maybe 50 little peices of information. So I know I can make 50...
22
by: Jim Hubbard | last post by:
I am reposting a portion of a thread that I am involved in under a new topic because it seems that there are still people that believe the whole "DLL Hell" myth. I hope I can shed some light on...
1
by: GreatB | last post by:
Bill Gates died in a car accident. He found himself in Purgatory being sized up by God . .. "Well, Bill, I'm really confused on this call. I'm not sure whether to send you to Heaven or Hell....
2
by: ven | last post by:
Hello i have a question about two aspx files...I have a variable in one page called login.aspx and when user correctly loged another page is opening...this second page is called default.aspx.......
20
by: weston | last post by:
I've got a piece of code where, for all the world, it looks like this fails in IE 6: hometab = document.getElementById('hometab'); but this succeeds: hometabemt =...
11
by: Googy | last post by:
Hi friends!! As we know that the input parameters in a function is fixed when the function is defined but how does printf processes variable number of input arguments ? For example: 1....
7
by: DavidSeck.com | last post by:
Hi guys, first post :) my question: is it possible to have dynamic variable names, I mean something like this: for($i=0;$i<x;$i++){ $y_$i = blabla; }
2
by: tskrish | last post by:
Hi, In any ASP.NET application the life of the static variable sounds peculiar. Consider a scenario like this, public static int i = 0; //Static declaration protected void...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.