Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit Argument Passing in Python?

Tags:

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()
like image 792
user2725742 Avatar asked Dec 06 '25 03:12

user2725742


2 Answers

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()
like image 154
NPE Avatar answered Dec 08 '25 16:12

NPE


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

like image 20
Marcin Avatar answered Dec 08 '25 16:12

Marcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!