problem with variable scoping

tavares at connix.com tavares at connix.com
Wed May 26 16:31:12 EDT 1999


In article <374C429D.4740B636 at mindless.com>,
  Michael Dingler <mdingler at mindless.com> wrote:
> It's...
>
> an embarassing question. Yes folks, I'm writing my first
> Python program (a text to HTML converter) and I have a
> slight misunderstanding with the variable scoping...
>
> Let me present some code fragments:
>
> last_line_empty = 0
> .
> .
> .
> def process(line):
> 	...
> 	if last_line_empty:
> 		pass
> 	else:
> 		print "<P>"
> 	last_line_empty = 1
>
> You see, I want to replace empty lines with paragraph symbols,
> but if there is more than one, I want just one <p>-tag... If
> I leave out the last statement (setting last_line_empty to one),
> it works, but otherwise I get a 'name error' on the 'if' line.
>
> As last_line_empty isn't a string it should be mutable, is my
> grasp on some Python concepts that weak or do I just have a
> 'bad brain day'?
>
> ...Michael...
>

Don't worry, it's not that bad.

It looks to me like the problem is that last_line_empty is a global
variable, and you want to assign to it inside a function, right? Here's
the missing incantation:

def process(line):
    global last_line_empty # <--- YOU NEED THIS
    ...

Without the global declaration, assignments will always go into the
local scope. So, when you do "last_line_empty = 1", it actually created
a new last_line_empty local variable that completely masked the global
one.

Now, I'll also bet you were getting an error on the "if
last_line_empty:" and wondering why. Well, the Python compiler does some
tricks to optimize local variable access. One of those tricks is that it
knows wether access to a variable will be global or local depending on
the assignments. So, what the function tried to do is check the local
last_line_empty variable, which doesn't exist yet since it hasn't been
assigned to yet.

Sufficiently confused, I hope? Don't worry, it's not Python, just my
lousy explanations.

-Chris


--== Sent via Deja.com http://www.deja.com/ ==--
---Share what you know. Learn what you don't.---




More information about the Python-list mailing list