0

I am a C programmer who is learning Python. Recently I have been being confused by the rules of scope and namespace in nested functions within a certain class.

Example Code:

Class CLASS_A:
  def FUNCTION_A(argument a, ..., argument n):
    max = 0
    visit = set()

    def FUNCTION_B(argument a, ..., argument n):
      visit.add(...)
      frequency = ....
      nonlocal max
      max = ... if ... frequency ... max ... else ...
      return
    
    FUNCTION_B(...)
    return max

In the example code, both "max" and "visit" are declared(?) and initialised in the outer(?) function FUNCTION_A. Therefore, so as to get access and modify the value of "max" within its own scope, FUNCTION_B must execute a non-local statement before trying to do so.

However, the same situation does not apply to "visit", a set, we can just modify its value directly as if it was declared in the FUNCTION_B itself.

I have noticed that when it comes to array, set, dictionary, etc. (all of them are classes in Python?), we don't need to give much extra care regarding the scope and namespace. We only need a non-local or global statement when we try to modify a variable like integer.

What's the underlying reason of such differences?

Robert
  • 7,394
  • 40
  • 45
  • 64
  • This has *nothing* to do with scope. `int` objects are immutable (i.e. they expose no mutator methods), assignment **never** mutates. On the other hand, `set` objects are mutable (they expose mutator methods, e.g. `.add`) – juanpa.arrivillaga Apr 10 '23 at 21:44
  • Also, `nonlocal` and `global` are only needed to **assign** to a variable. Not reference it. – juanpa.arrivillaga Apr 10 '23 at 21:45
  • You should read the following to understand Python's semantics: https://nedbatchelder.com/text/names.html I believe grokking that will remove any confusion – juanpa.arrivillaga Apr 10 '23 at 21:49
  • So, read the linked duplicate and the linked article in the comment above. But fundamentally, your confusion is over *mutating an object* and *assigning an object to a variable*. Variables work differently in python than they do in C, and it is better to jsut learn Python on it's own terms, but you can think of it as every variable is actually a pointer to a Python object that gets automatically dereferenced for you when you use it. But again, better to just learn Python on it's own terms – juanpa.arrivillaga Apr 10 '23 at 22:22

0 Answers0