[Discuss] A question for the Python gurus

Deryk Barker dbarker at camosun.bc.ca
Sun Jul 30 11:58:01 PDT 2006


Adam Parkin wrote:

> Okay before the replies, can someone explain to me this:
>
> #!/usr/bin/python
>
> import sys
>
> lines = "hello"
>
> def foo():
>         lines = sys.stdin.readline()
>
> def bar():
>         print "in bar: " + lines
>
> foo()
> bar()
>
> As I get "hello" as output.  This is like having globals passed to 
> functions by value, which seems completely bizarre and 
> counter-intutitive.  And it's not just strings: you get the same 
> semantics if "lines" is a hash, integer, etc.
>
> Or am I just missing something? 

You need to specify that a variable is global if your first use within a 
fuinction is assignment. So,

def foo():
    global lines
    lines = sys.stdin.readline()





More information about the Discuss mailing list