Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Closures and Scope
#1
I don't like how Python handles scope. Inner functions cannot access the outer function's variables when in any other language, they can. Here is an example closure in which I had to use the nonlocal keyword in order to have access to the outer functions variable of the same name. The global, function and block namespaces should be automatic. Keywords like Global and nonlocal; are they really necessary?

def my_func():

    count = 0
    def inner_func():
        nonlocal count
        count += 1
        return count

    return inner_func

a = my_func()
print(a())
print(a())
print(a())
OUTPUT:
1
2
3
Reply
#2
They're necessary if you want to modify an outer scope variable. They're not necessary if you only want to access the variable.
Reply
#3
Yeah, I figured. :) Thanks.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to create a variable only for use inside the scope of a while loop? Radical 10 1,666 Nov-07-2023, 09:49 AM
Last Post: buran
  Library scope mike_zah 2 830 Feb-23-2023, 12:20 AM
Last Post: mike_zah
  Scope of variable confusion Mark17 10 2,823 Feb-24-2022, 06:03 PM
Last Post: deanhystad
  Variable scope issue melvin13 2 1,525 Nov-29-2021, 08:26 PM
Last Post: melvin13
  Variable scope - "global x" didn't work... ptrivino 5 3,028 Dec-28-2020, 04:52 PM
Last Post: ptrivino
  Block of code, scope of variables and surprising exception arbiel 8 3,394 Apr-06-2020, 07:57 PM
Last Post: arbiel
  Help with Global/Coerced Variable (Understanding Scope) Rev2k 6 3,470 Jan-09-2020, 03:43 AM
Last Post: Rev2k
  Solving a scope issue profconn1 4 2,559 Nov-01-2019, 07:46 PM
Last Post: profconn1
  Namespace and scope difference Uchikago 9 4,570 Jul-03-2019, 03:36 PM
Last Post: Uchikago
  what is scope for python? samexpert 2 2,231 Jun-24-2019, 01:03 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020