-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 ?

4
  • 2
    Your code has multiple syntax errors. Commented Sep 5, 2016 at 21:14
  • Did you get a maximum recursion depth error? Commented Sep 5, 2016 at 22:49
  • no, this is just an example of my code and only to explain my problem Commented Sep 6, 2016 at 9:21
  • This answer helped me to solve my problem stackoverflow.com/a/24572213/1913545 Commented Sep 7, 2016 at 18:36

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Should i put my function in a class ?
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.
Can i do something like : foo(list(myarray)) to prevent Python share 'myarray' ?
You could define it inside the function instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.