Poor Standard
Poor Standard

Reputation: 135

Python global variables : too global for me

Below, I would like the s var be global to the f function, but local to the principal function.

It seems global means "The Most Global in the Module". How can I make one less global scope ?

s="what the hell"
print(s)

def principal():
    s ="hey"
    def f():
        global s 
        if len(s) < 8:
            s += " !"
            f()

    f()
    return s
print(principal())

what the hell
hey

Upvotes: 1

Views: 66

Answers (1)

Richard Neumann
Richard Neumann

Reputation: 3361

I'm not sure if this is what you are going for, since global has an unambiguous meaning in Python. If you want to modify the variable s as defined in principal() within f() you can use nonlocal:

s="what the hell"
print(s)

def principal():
    s = "hey"
    def f():
        nonlocal s 
        if len(s) < 8:
            s += " !"
            f()

    f()
    return s
print(principal())

But the real goal here would probably be, to avoid constructs like that altogether and pass the respective variables as arguments and return the modified values from (pure) functions.

Upvotes: 3

Related Questions