New rules for scope in a function?

Chris Angelico rosuav at gmail.com
Mon Feb 18 12:40:21 EST 2019


On Tue, Feb 19, 2019 at 4:36 AM Steve <Gronicus at sga.ninja> wrote:
>
> I have been programming for more years than I want to admit and believe that I have a good understanding when it comes to the Scope of Variables when using functions. Are the rules different when using python?
>
> It looks as if I have to pass all variables to and from the function before it works.  Are variables used in the main program not also visible for use within the function?  Do these variables have to be declared as global?
>
> Steve
>

Functions in Python have access to everything in the surrounding
scopes, usually a module. Any name that's ever *assigned to* in the
function (including its parameters) is local to that function, and
anything that you look up without assigning comes from the outer
scope.

x = 1
def f(y):
    print(x, y)

This function is happily able to see its own parameter (a local) and
the name from outside it (a global). It's also able to see the "print"
function, which comes from the builtins - that's just another scope.

ChrisA



More information about the Python-list mailing list