osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Can global variable be passed into Python function?


On Sat, Feb 22, 2014 at 4:59 AM, Travis Griggs <travisgriggs at gmail.com> wrote:
> What makes Python variables/bindings/references/aliases/namedvalues/slots/bucketsofstuff surprising to new arrivals from other language kingdoms, is that accessing is pragmatically implicit (walks the scope tree for you) and assignment may require explicitness. IOW, for some ?variables?, you have to do something explicit to make the variable you want to refer to, vary. Some might say there is a lack of symmetry. Pros and cons.
>

What you're looking at there, I think, is actually quite tangential to
the question of Python having/not having variables, and it's to do
with scoping rules. Correct me if I'm wrong.

g = "global"
c = 0
def f():
    print(g) # References two globals
    l = "local"
    print(l) # References one global and one local
    global c
    c = 1 # References one global

As an alternative, Python could have asked us to declare the other way:

def f():
    print(g) # References two globals
    local l
    l = "local"
    print(l) # References one global and one local
    c = 1 # References one global

It would still be the same name binding / object reference model, with
just a different keyword used to change the default behaviour of name
lookups. And the difference is comparatively slight. We get an
encouragement to use locals rather than globals, but on the flip side,
we need two keywords (global/nonlocal) where a single one (local, or
as ECMAScript puts it, "var") could handle the other case. It's a lack
of symmetry, but having worked with PHP (where you have to declare
*every* global, except for the magical superglobals, and except for
functions (which are in a completely different namespace), and except
for constants), I am very much glad that Python puts everything in
together as just "names", and then allows us to reference global names
like "print" without declarations. It's a miswart.

ChrisA