fm_user8
fm_user8

Reputation: 438

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()

Upvotes: 3

Views: 3285

Answers (2)

Marcin
Marcin

Reputation: 49816

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 (e.g. if a conditional statement prevented the loop from being executed at all).

Upvotes: 3

NPE
NPE

Reputation: 500227

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()

Upvotes: 10

Related Questions