-7

i start with Python. I like to try new language. So i've got a "simple" problem about scope and Python.

Here is a recursive function

def foo(myarray)
  if myarray == False: 
    myarray = [[0] * 5 for _ in range(5)]
    myarray[0][0] = 1
  "some code ..."
  foo(myarray)

myarray = False
foo(myarray)

I don't want to share my var "myarray" in global env. I juste want Python scope "myarray" only in the function not outside. But Python shared "myarray" as it were a global var. How can restrict the scope to the function ?

1 Answers1

1

Disregarding the myriad of syntax errors, your myarray variable seems to be declared globally and that's why it has global scope?

  • Should i put my function in a class ? –  Sep 06 '16 at 07:35
  • You could but a class isn't strictly necessary `. The 'myarray' variable is defined in global scoped due to the indentation on the second last line in your snippet. The trick is to remember that Python uses indentation to differentiate code blocks. – Dwight Gunning Sep 06 '16 at 08:02
  • Can i do something like : `foo(list(myarray))` to prevent Python share 'myarray' ? –  Sep 06 '16 at 20:43
  • You could define it inside the function instead. – Andrei-Marius Longhin Sep 07 '16 at 19:03