简体   繁体   中英

Python Recursion: Are there any advantages to passing all variables vs just declaring a global variable and re-declaring in the function?

When I look at python code I see two styles of handling variables in python.

  1. pass all variables.

Example

#initialize
variable1 = 1
variable2 = 1
variable3 = 1

def recursive(variable1, variable2, variable3):
    do stuff with variables
    recursive(variable1, variable2, variable3)
  1. if a variable doesn't need a separate instance inside the function, just make it global

example

#initialize
variable1 = 1
global variable2 
variable2 = 1
global variable3 
variable3 = 1

def recursive(variable1):
    global variable2
    global variable3
    do stuff variables
    recursive(variable1)

Are there any advantages to either style? Is one more 'pythonic' than the other?

Using global excessively can be tricky to debug. The pythonic way is definitely to pass everything explicitly or encapsulate the work into smaller functions so that there isn't so much verbosity messing with all three variables.

In your case, there might be an easier approach:

def recursive(*args)
    # Do stuff with args
    recursive(*args)

This eliminates a lot of the verbosity you might not have cared for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM