Can I get access to variable different from nonlocal or global in python3.4?

73 Views Asked by At

Can I access to other variable in specific scope? Like this:

variable = 'acces with global'
def function1:
    variable = 'function 1 variable'
    def function2:
        variable = 'I really like this name for variable'
        def function3:
            def access_to_local:
                variable = "it's another variable I can access too!"
            def access_to_global:
                global variable
                variable = 'now I have access to my global variable'
            def access_to_function2:
                nonlocal variable
                variable = 'And easy way to change function2 variable'
            def access_to_function1:
                #nonlocal^2 variable?
                variable = 'And how can I get access to variable in
                            function1?'

It's not life or death question, I'm just curios. I just learn how global and nonlocal work in python. Right now, it's definitely enough, but I wonder if what I'm asking is possible. Especially, that I read pep about this, and they was thinking about making something like "nonlocal in specific scope". But they decided to use nonlocal instead. Is it because there is way of doing this without nonlocal? Or maybe there is some trick with nonlocal, like writing it two times nonlocal nonlocal variable?

1

There are 1 best solutions below

0
On BEST ANSWER

No, you can't. There is no way to specify that Python should skip a nested scope level.

Note that using this many levels of nesting is not really natural; you rarely, if ever, will need to use this much nesting in the first place. Just use different names if you need to access variables at different levels in those rare cases.