0

I am using Python3.7 and I am curious about the namespace of the dictionary. Here is My question.

Let's define a dict first:

r = {'a':[1,2,3], 'b':[4,5,6]}

then we define a function:

def fun1():
    print(r['a'])

fun1()

Output: [1, 2, 3]

then We define another function:

def fun2():
    r = {'a':[10,11,12],'c':[7,8,9]}
    fun1()

fun2()

Output:[1, 2, 3]

Why isn't the output of fun2 [10,11,12], as r is redefined inside the function func2. But it seems to be pointing to what we defined at the beginning. Does scope not apply to dictionaries?

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
shelure21
  • 3
  • 1
  • Does this answer your question? [Short description of the scoping rules?](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules) – MisterMiyagi Jul 27 '20 at 13:09
  • "Does scope not apply to dictionaries?" – it does, which is why ``fun2..r`` is not in the scope of ``fun1.``. What makes you assume the former scope is visible from the latter? – MisterMiyagi Jul 27 '20 at 13:09

2 Answers2

0

r = {'a': [10, 11, 12], 'c': [7, 8, 9]} is only visible inside fun2. fun1 will only see r that was defined in the "global" namespace.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

If you want the new r to be visible inside fun1, you have to define fun1 inside fun2 like this :

def fun2():
    r = {'a':[10,11,12],'c':[7,8,9]}
    def fun1():
      print(r['a'])
    fun1()

Otherwise you can pass r as a parameter to fun1 like this:

def fun1(r):
    print(r['a'])

def fun2():
    r = {'a':[10,11,12],'c':[7,8,9]}
    fun1(r)

fun2()
Martin J
  • 2,019
  • 1
  • 15
  • 28
  • What’s the difference between define fun1 outside and inside fun 2? – shelure21 Jul 27 '20 at 22:20
  • The difference is just that if it is outside it won’t take into account the new value of `r` that is inside, it will take into account the `r` outside. – Martin J Jul 28 '20 at 01:49