Search code examples
pythonscopeconventions

about python scopes


I've read about python scopes and browsed questions here on stackoverflow but theres something i'd like to clarify.

I'm extracting a piece of code to a function, from what i used to it should take all the variables it's using as parameters. But, in python the variable address is determined at runtime so theres actually no need for the parameters. Since i'm new to python i wanted to know if there are other implications or conventions i should know about.

x = 5
x += 1
print x

is there any difference between the following refactoring of the above code :

def f(x):
  x += 1
  return x

x = 5
x = f(x)
print x

and:

def f():
  x++

x = 5
f()
print x

If not then, is one of the ways more commonly used or preferred in python ?


Solution

  • It's preferred not to use global variables, if not absolutely necessary. That said, in the second example you'd need global x declared before you refer to x.

    So, first way:

    • f takes an argument x
    • Increments x
    • returns x + 1
    • the global x is not affected

    The second way:

    def f():
      global x
      x += 1
    
    x = 1
    f()
    
    • f has no arguments
    • Increments the global x

    P.S. Python has no ++ operator. x += 1 is used instead