Python scoping

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Jun 20 20:57:36 EDT 2011


On Mon, 20 Jun 2011 15:35:35 -0700, gervaz wrote:

> 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?

Because Python is not C and doesn't require declarations.


> Is there a way to force the scoping?

It is scoped. txt is local to the function test. What more do you want?

If your functions are so large that you worry about name clashes between 
code in different parts of the one function, the solution is to break 
this one huge function into many small functions. That's what functions 
are for: to encapsulate a limited amount of reusable functionality into a 
namespace.



-- 
Steven



More information about the Python-list mailing list