variable hell

N

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
 
D

Diez B. Roggisch

Nx said:
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
 
R

Robert Kern

Nx said:
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
(e-mail address removed)

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

Fredrik Lundh

Nx said:
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>
 
S

Sybren Stuvel

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
 
P

Peter Maas

Nx said:
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
 
N

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,s24,s25,
s26,s27,s28,s29,s30,s31)
MYINSERTSELECT = "INSERT INTO
ADDRESS(ALIAS,COMPANY,ADDRESSLI1,ADDRESSLI2,ADDRESSCO,TOWN,ZIP,COUNTRY,TEL1,TEL2,FAX,EMAIL,INTERNET,PERSON1,TITLE1,RES1,PERSON2,TITLE2,RES2,PERSON3,TITLE3,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
 
B

bruno modulix

Nx said:
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,s24,s25,
s26,s27,s28,s29,s30,s31)
MYINSERTSELECT = "INSERT INTO
ADDRESS(ALIAS,COMPANY,ADDRESSLI1,ADDRESSLI2,ADDRESSCO,TOWN,ZIP,COUNTRY,TEL1,TEL2,FAX,EMAIL,INTERNET,PERSON1,TITLE1,RES1,PERSON2,TITLE2,RES2,PERSON3,TITLE3,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 ?
 
C

Carsten Haese

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,s24,s25,
s26,s27,s28,s29,s30,s31)

inputvalues = tuple(mylist)

Hope this helps,

Carsten.
 
C

Carsten Haese

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.
 
N

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
 
R

Robert Kern

Nx said:
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
(e-mail address removed)

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

sp1d3rx

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!
 
R

Ron Garret

Benji York said:
Peter said:
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
 
R

Robert Kern

Ron said:
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
(e-mail address removed)

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

Steve Holden

Carsten said:
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
 
B

bruno modulix

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
 
R

Robert Kern

Ron said:
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
(e-mail address removed)

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,266
Messages
2,571,318
Members
47,998
Latest member
GretaCjy4

Latest Threads

Top