2

Say I have a function inside of a loop that takes several parameters, but only one of which actually changes from iteration to iteration of the loop.

Example:

for i in range(10):
   function(i, a, b, c, d, e)

Would I be losing speed by repeated passing arguments a, b, c, d, e into the function? I understand something vaguely about how all mutable types are passed in a "reference-like" manner. What would be a better way to do this?

I've tried this:

a =
b =
...

def function(i)

for i in range(10):
   function(i)

and it seems to work.

Frustratingly, the below does not seem to work and I have not been very successful in understanding online explanations of why not:

from somemodule import function 

for i in range(10):
   function(i)

where function is defined same as above. I keep getting a "global variable a, b, c ... cannot be found" ERROR.

avamsi
  • 389
  • 3
  • 16
wisdomtoothman
  • 123
  • 2
  • 6
  • 1
    well, your code is incomplete, but I will guess that in the second case the function is defined in `somemodule`, but the vars `a`, `b`, ... aren't. Since modules provide scope in Python, you should defined those vars inside `somemodule`. If I'm mistaken, could you please provide a MWE? – jorgeh Aug 18 '15 at 06:58
  • Where are `a` and `b` ASSIGNED (read defined) in your second case? – Pynchia Aug 18 '15 at 07:11

2 Answers2

0

Have you tried specifying the variable in this way:

global a
global b
.....

Otherwise those variable are considered as local variables if it's declared within any function,and it's instances can be used within the declared function only. If you specify it as global it can be used anywhere within your script.
This was the only ERROR you've came across right?

  • 1
    `global a` allows you to assign a value to the global name `a` within the function. If you just need to reference it (i.e. use it in an expression) `global` is unnecessary. Please see the LEGB scope rule. – Pynchia Aug 18 '15 at 07:08
  • While this may "solve" the error (and that is unclear), in general it is considered a bad practice to use globals. Since the OP indicates he/she is a newcomer to python, I'd advise against it. 99% of the time `global` can be avoided using proper scoping. See these posts for comments on the use of `global` in python: http://stackoverflow.com/a/4693385/1620879 http://stackoverflow.com/a/19158418/1620879 – jorgeh Aug 18 '15 at 07:11
0

Names a, b, c ... must be defined in somemodule for this to work and then function uses those values.

As your code is incomplete, I can only guess..
You should be using either default arguments or functools.partial

They produce different results, but I think one of them fits your needs.

avamsi
  • 389
  • 3
  • 16