Python scoping

Ben Finney ben+python at benfinney.id.au
Mon Jun 20 20:39:05 EDT 2011


gervaz <gervaz at gmail.com> writes:

> Hi all, can you explain me why this simple function works well (i.e. I
> can call the print function using txt) in py
>
> >>> def test(value):
> ...     if value%5: txt = "hello"
> ...     else: txt = "test"
> ...     print(txt)
>
> while in other languages like C the txt identifier would be undefined?

Python doesn't have variables the way C or many other languages have
them.

Instead, Python has objects, and references to those objects so you can
get at them. The Python documentation, much to my frustration, calls
these references “variables” even though that gives exactly the wrong
implication of how they'd behave.

With the assignment statements (the statements using ‘txt = …’), the
name ‘txt’ is bound as a reference to a value. It's not a C-like
variable; it doesn't have a type, it doesn't need to be declared, etc.
It's just a name, that you can bind to exactly one value any time you
like.

> Is there a way to force the scoping?

No, by binding a name to a value you are creating that binding within
the scope where the binding happens (the assignment statement, in your
example).

-- 
 \          “Instead of a trap door, what about a trap window? The guy |
  `\      looks out it, and if he leans too far, he falls out. Wait. I |
_o__)                guess that's like a regular window.” —Jack Handey |
Ben Finney



More information about the Python-list mailing list