简体   繁体   中英

Implicit Argument Passing in Python?

The code below is from hackermeter.com and I'm not sure what to think of it. Is the variable i being passed implicitly to run() or does it expect more modification than just where it specifies?

import sys

def run():
   # Code here!

for i in range(int(sys.stdin.readline())):
   run()

I'd argue that this is a poor coding practice. The only reason run() has access to i is that i is global.

The following is arguably better as it will force the programmer to pass i into run() explicitly (if required):

import sys

def run():
   # Code here!

def main():
   for i in range(int(sys.stdin.readline())):
      run()

if __name__ == '__main__':
   main()

This is the code in the question:

import sys

def run():
   # Code here!

for i in range(int(sys.stdin.readline())):
   run()

i is defined in global scope (that is at the top level of the module), and so is accessible inside run . This is because essentially only functions and classes introduce a new local scope, so an iteration variable is a normal variable of its enclosing scope.

If run does access i , this creates the potential for an error if i has not already been defined (eg if a conditional statement prevented the loop from being executed at all).

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