append to non-existing list

Y

Yves Glodt

Hello,

if I do this:

for row in sqlsth:
________pkcolumns.append(row[0].strip())
________etc


without a prior:

pkcolumns = [];


I get this error on first iteration:
UnboundLocalError: local variable 'pkcolums' referenced before assignment



I guess that's normal as it's the way python works...?!?

My question is: Is there no way to append to a non existing list?

I am lazy for declaring it first, IMHO it bloats the code, and (don't
know if it's good to say that here) where I come from (php) I was used
to not-needing it...


regards,
Yves
 
D

dcrespo

Hi

I think there's no way to append to a non existing list.

Sorry about my question, but the English is my second language, and I
don't know what is the meaning of IHMO (or IMHO). I googled and found
that it means "In My Humbled Opinion", is that true? Thanks and accept
my appologies for not talking entirely about your problem.

Daniel
 
B

bonono

I am afraid you have to either go back to php or whatever programming
language that fits your style or change your style to fit python.

There is a lot I don't like about python but if you have to use it, you
have to cope with it.
 
J

Juho Schultz

Yves said:
Hello,

if I do this:

for row in sqlsth:
________pkcolumns.append(row[0].strip())
________etc


without a prior:

pkcolumns = [];


I get this error on first iteration:
UnboundLocalError: local variable 'pkcolums' referenced before assignment

I guess that's normal as it's the way python works...?!?

My question is: Is there no way to append to a non existing list?

I am lazy for declaring it first, IMHO it bloats the code, and (don't
know if it's good to say that here) where I come from (php) I was used
to not-needing it...


regards,
Yves

You mean you want to type "pkcolumns" only once to keep your code short?
Would something like this be useful?

pkcolumns = [row.strip() for row in sqlsth]
 
B

bonono

Juho said:
Yves said:
Hello,

if I do this:

for row in sqlsth:
________pkcolumns.append(row[0].strip())
________etc
You mean you want to type "pkcolumns" only once to keep your code short?
Would something like this be useful?

pkcolumns = [row.strip() for row in sqlsth]

I don't think this is the same as his original code though. There is an
"etc" there. Your version is cleaner and easier to understand but it
can mean another extra pass to go through the result and if sqlsth is
an iterable, it needs to be saved away before iterating it.
 
R

Roy Smith

Yves Glodt said:
My question is: Is there no way to append to a non existing list?

Nope. The problem (well, part of the problem, anyway) is that when you do:

foo.append (bar)

what's happening is you're calling foo's append method. If foo doesn't
already exist, it has no way of knowing what to call.
I am lazy for declaring it first, IMHO it bloats the code, and (don't
know if it's good to say that here) where I come from (php) I was used
to not-needing it...

Python is not php. Nor is it Perl. Nor it is a whole bunch of other
things.
 
Y

Yves Glodt

I am afraid you have to either go back to php or whatever programming
language that fits your style or change your style to fit python.

sorry for offending... I just asked a question, and now I know one more
thing about python...

And btw I really am surprised by the amount of answers that my question
rose, in so little time!

thanks all!
 
Y

Yves Glodt

Juho said:
Yves said:
Hello,

if I do this:

for row in sqlsth:
________pkcolumns.append(row[0].strip())
________etc


without a prior:

pkcolumns = [];


I get this error on first iteration:
UnboundLocalError: local variable 'pkcolums' referenced before assignment

I guess that's normal as it's the way python works...?!?

My question is: Is there no way to append to a non existing list?

I am lazy for declaring it first, IMHO it bloats the code, and (don't
know if it's good to say that here) where I come from (php) I was used
to not-needing it...


regards,
Yves

You mean you want to type "pkcolumns" only once to keep your code short?
Would something like this be useful?

pkcolumns = [row.strip() for row in sqlsth]

I will look into this, maybe it's what I need, thanks!
 
B

bruno at modulix

Yves said:
Hello,

if I do this:

for row in sqlsth:
________pkcolumns.append(row[0].strip())
________etc


without a prior:

pkcolumns = [];


I get this error on first iteration:
UnboundLocalError: local variable 'pkcolums' referenced before assignment



I guess that's normal as it's the way python works...?!?

yes sir.
My question is: Is there no way to append to a non existing list?

No. Definitively. And that's a Good Thing(tm).

How would you use something that doesn't exist ???
I am lazy for declaring it first,

s/declaring/instantiating/

If you were to use your own class Toto, would you ever hope that the
following code would work :

for v in some_seq:
toto.dothis(v)

without instantiating Toto and binding it to the name 'toto' before ?
Well, in Python, a list is an instance of class list. There are
syntactic sugar to instanciate a list (or a tuple or a string or a dict
etc), but this:

my_list = []

is strictly equivalent to this:

my_list = list()

Now let's try something else:

class Machin(object):
def append(self, value): pass

class Bidule(object):
def append(self, value): pass

for i in range(10):
m.append(i)


How should Python interpret this ? Should it create a list, or a Machin,
or a Bidule, or an instance of whatever imported class having a
append() method ?
IMHO it bloats the code,

run your python interpreter and type:
import this

Then read carefully.

Now if being explicit still hurts your personal convictions, there's
this other language with a name starting with p... !-)
and (don't
know if it's good to say that here) where I come from (php) I was used
to not-needing it...

Not creating an Array before using it is Bad Style in PHP (and generate
a Warning BTW).

There are warts in Python (as in any other languages), and there are
things that sometimes bore me but are not really warts. But having to
explicitely instanciate objects can't be seen as a wart in any language
IMHO !-)
 
R

Roy Smith

You mean you want to type "pkcolumns" only once to keep your code short?
Would something like this be useful?

pkcolumns = [row.strip() for row in sqlsth]

I will look into this, maybe it's what I need, thanks![/QUOTE]

The list comprehension format described above is handy and compact, and
there's no reason you shouldn't use it when appropriate. That being said,
compactness should not itself be a goal.

Writing clear and easy to understand code is much more important than
reducing the number of lines. Sometimes you get both at the same time, but
not always.
 
T

Thomas Bellman

Yves Glodt said:
I guess that's normal as it's the way python works...?!?

Yes, that's the way Python works.
My question is: Is there no way to append to a non existing list?

The next time you go shopping at your local super-market, do
*not* get a shopping-cart (or shopping-basket, or any similar
container). As you pick up the things you want to buy, try
to put them into the non-existing cart. Perhaps you will then
become enlightened.
I am lazy for declaring it first, IMHO it bloats the code, and (don't
know if it's good to say that here) where I come from (php) I was used
to not-needing it...

Basically you want Python to automatically create a list out of
nowhere and bind a variable to that list when you try to access
a variable that doesn't exist in a certain way. How do you
propose that Python should now that it is a *list* you want, and
not some other kind of object?


There actually is a way to do what you want:

for row in sqlsth:
try:
pkcolumns.append(row[0].strip())
except NameError:
pkcolumns = [ row[0].strip() ]

However, as you see it is much more work than to do it the right
way. It's also much more fragile; think for example about what
happens if your SQL statement (I assume that's what sqlsth is)
yields zero rows, and you then try to look at pkcolumns after
that loop.
 
B

bonono

Thomas said:
The next time you go shopping at your local super-market, do
*not* get a shopping-cart (or shopping-basket, or any similar
container). As you pick up the things you want to buy, try
to put them into the non-existing cart. Perhaps you will then
become enlightened.

But in PHP(and I believe Perl), it is more like :

"oops, I need a cart. <shout>Hello, I need a cart here, please" and
magically, someone wheel you a cart which you can put your stuff in.
The "@" is the magic calls for service. So as a customer, this sounds
like better service but that will create problems to the super market
as it need extra staff for this service and the environment is noiser,
that is another story.
 
Y

Yves Glodt

bruno said:
Yves said:
Hello,

if I do this:

for row in sqlsth:
________pkcolumns.append(row[0].strip())
________etc


without a prior:

pkcolumns = [];


I get this error on first iteration:
UnboundLocalError: local variable 'pkcolums' referenced before assignment


I guess that's normal as it's the way python works...?!?

yes sir.
My question is: Is there no way to append to a non existing list?

No. Definitively. And that's a Good Thing(tm).

How would you use something that doesn't exist ???
I am lazy for declaring it first,

s/declaring/instantiating/

If you were to use your own class Toto, would you ever hope that the
following code would work :

for v in some_seq:
toto.dothis(v)

without instantiating Toto and binding it to the name 'toto' before ?
Well, in Python, a list is an instance of class list. There are
syntactic sugar to instanciate a list (or a tuple or a string or a dict
etc), but this:

my_list = []

is strictly equivalent to this:

my_list = list()

Now let's try something else:

class Machin(object):
def append(self, value): pass

class Bidule(object):
def append(self, value): pass

for i in range(10):
m.append(i)


How should Python interpret this ? Should it create a list, or a Machin,
or a Bidule, or an instance of whatever imported class having a
append() method ?

ok I see your point, and python's...

(just FYI, and not to start a flamewar ;-):
In php, the [] means "append to an array object".

If the array does not exist yet, it's created. [] *is* explicit for
arrays, thus for php it's clear what you want.)
run your python interpreter and type:
import this

Then read carefully.

Now if being explicit still hurts your personal convictions, there's
this other language with a name starting with p... !-)

no thanks, this is the 21st century ;-)
Not creating an Array before using it is Bad Style in PHP (and generate
a Warning BTW).

an "undefined" notice, yes, not a warning... ;-)
There are warts in Python (as in any other languages), and there are
things that sometimes bore me but are not really warts. But having to
explicitely instanciate objects can't be seen as a wart in any language
IMHO !-)

Ok... I thank you for all the explanations.

It helps me to see more far. I (and will continue to) use php for web,
and wanna standardize on python for all non-web stuff we are doing, so I
might be a frequent guest on this list...

have a nice day,
Yves
 
M

Max M

Yves said:
bruno said:
Yves said:
Hello,

if I do this:

for row in sqlsth:
________pkcolumns.append(row[0].strip())
________etc


without a prior:

pkcolumns = [];


I get this error on first iteration:
UnboundLocalError: local variable 'pkcolums' referenced before
assignment


I guess that's normal as it's the way python works...?!?


Well you could do something like this. (Untested and unrecommended)

self.__dict__.setdefault('pkcolumns', []).append(row[0].strip())

Personally I find

pkcolumns = []
pkcolumns .append(row[0].strip())

to be nicer ;-)

--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
 
Y

Yves Glodt

But in PHP(and I believe Perl), it is more like :

"oops, I need a cart. <shout>Hello, I need a cart here, please" and
magically, someone wheel you a cart which you can put your stuff in.
The "@" is the magic calls for service. So as a customer, this sounds
like better service but that will create problems to the super market
as it need extra staff for this service and the environment is noiser,
that is another story.

:)

I will never mention any p-language except python in this list anymore...
 
Y

Yves Glodt

Max said:
Yves said:
bruno said:
Yves Glodt wrote:

Hello,

if I do this:

for row in sqlsth:
________pkcolumns.append(row[0].strip())
________etc


without a prior:

pkcolumns = [];


I get this error on first iteration:
UnboundLocalError: local variable 'pkcolums' referenced before
assignment


I guess that's normal as it's the way python works...?!?


Well you could do something like this. (Untested and unrecommended)

self.__dict__.setdefault('pkcolumns', []).append(row[0].strip())

Personally I find

pkcolumns = []
pkcolumns .append(row[0].strip())

to be nicer ;-)

Yes me too, I'm gonna stick to that... :)
 
S

Steven D'Aprano

My question is: Is there no way to append to a non existing list?

I am lazy for declaring it first, IMHO it bloats the code, and (don't
know if it's good to say that here) where I come from (php) I was used
to not-needing it...

But what happens if the non-existent list you try to append to is actually
a non-existent dict, or worse, a non-existent float? You'll get errors and
maybe even crash your computer and wipe the hard disk clear.

*wink*

How is appending to a non-existent object supposed to work?

something.append(0)

What object does the name "something" refer to? Does it even have an
append method? How can you tell what methods it has if it doesn't exist
yet?

No, you can't append to a non-existent list, just as you can't add two
non-existent numbers together.

If PHP allows you to append to non-existent lists, then it is a poor
design decision, and it obviously only works because PHP is much more
limited than Python. Consider the following code:

class PList(list):
def append(self, obj):
print "Appending object to PList"
self.__class__.append(self, obj) # call the superclass

class QList(list):
def append(self, obj):
print "QList append is being called"
self.__class__.append(self, obj)

class RList(QList):
def append(self, obj):
self.__class__.append(self, obj)
print "Now calling RList append"


something.append("hello world") # call append on a non-existent object


What should Python do? Should "something" be a RList, QList, PList or
ordinary list?
 
B

bruno at modulix

Yves Glodt wrote:
(snip)
ok I see your point, and python's...

(just FYI, and not to start a flamewar ;-):
In php, the [] means "append to an array object".

yes, I know this.
If the array does not exist yet, it's created.

Which is what I don't like. It should crash.
[] *is* explicit for
arrays,

IIRC, you can also use it to sbscript strings, but I wouldn't bet my
life on this.
thus for php it's clear what you want.)

Nope. You may be in the case where you think the array already exists,
and then you (well, I at least...) would prefer that PHP don't try to
second-guess you... If and when I want to create an object, I tell it.
If I dont tell "create me an array", I don't want one to come in existence.

(snip)
an "undefined" notice, yes, not a warning... ;-)
(snip)

Ok... I thank you for all the explanations.

It helps me to see more far. I (and will continue to) use php for web,
and wanna standardize on python for all non-web stuff we are doing,

You might discover that Python is just great for web programming too !-)
so I
might be a frequent guest on this list...

You're welcome !-)
And if you're a french speaker, there's also french-speaking mailing
list and newsgroups.
 
Y

Yves Glodt

bruno said:
Yves Glodt wrote:
(snip)
ok I see your point, and python's...

(just FYI, and not to start a flamewar ;-):
In php, the [] means "append to an array object".

yes, I know this.
If the array does not exist yet, it's created.

Which is what I don't like. It should crash.
[] *is* explicit for
arrays,

IIRC, you can also use it to sbscript strings, but I wouldn't bet my
life on this.
thus for php it's clear what you want.)

Nope. You may be in the case where you think the array already exists,
and then you (well, I at least...) would prefer that PHP don't try to
second-guess you... If and when I want to create an object, I tell it.
If I dont tell "create me an array", I don't want one to come in existence.
(snip)
an "undefined" notice, yes, not a warning... ;-)
(snip)
Ok... I thank you for all the explanations.

It helps me to see more far. I (and will continue to) use php for web,
and wanna standardize on python for all non-web stuff we are doing,

You might discover that Python is just great for web programming too !-)

Which raises another question... :)

Is there a possibility to bring together apache and python in a way that
I can embed python into html?

Or even, write a smallish webserver in python (using twisted maybe)
whose only purpose is to serve pages and execute the embedded code...?

You're welcome !-)
And if you're a french speaker, there's also french-speaking mailing
list and newsgroups.

Merci pour l'info, I am, but for now the volume of this list is enough
for me ... :)
 

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,270
Messages
2,571,351
Members
48,036
Latest member
nickwillsonn

Latest Threads

Top