0

I would like to change the value of a parameter in an imported function without putting it as input. For instance:

# in def_function.py
def test(x):
    parameter1 = 50 # default value
    return parameter1*x

# in main.py
from def_function import test
print(test(1)) # It should give me 50
parameter1 = 10 # changing the value of parameter1 in test function
print(test(1)) # It should give me 10
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Akusa
  • 163
  • 1
  • 5
  • That's not going to work. `parameter1` in `main.py` is unrelated to `parameter1` inside the `test` function in `def_function.py`. – jonrsharpe Sep 12 '19 at 14:59
  • 1
    If you want to set a variable from outside you'll have to use a parameter as you did with `x`. – Matthias Sep 12 '19 at 15:00
  • 4
    If you want a default value use `def test(x, parameter1=50)`. If you call the function without a second parameter it will use the default value of `50`. – Matthias Sep 12 '19 at 15:01
  • If you want it to change, you'll have to pass it in somehow. Either as a parameter, or a global. – John Gordon Sep 12 '19 at 15:01
  • 1
    Am I missing something but is there a reason you can't use a [default argument](https://docs.python.org/3/tutorial/controlflow.html#default-argument-values)? `def test(x, parameter1=50)` and if you need a different `parameter1` just use `test(1, 10)`. – Chillie Sep 12 '19 at 15:03

2 Answers2

8

parameter1 inside the function is in its own scope. It's not the same as the parameter1 outside the function definition.

To do what you're trying to do, add a keyword argument to the function definition, providing a default value for the argument:

# in def_function.py
def test(x, parameter1=50):
    return parameter1*x

# in main.py
from def_function import test
print(test(1)) # It gives 50
print(test(1, parameter1=10)) # It gives 10 (as a keyword arg)
print(test(1, 10)) # It gives 10 (as a positional arg)

Don't use globals if you can help it.

Matt Hall
  • 7,614
  • 1
  • 23
  • 36
1

Another option is to use the nonlocal keyword. You could do this in your code like this:

def main():
    def test(x):
        nonlocal parameter1
        return parameter1*x

    parameter1 = 50 # default value
    print(test(1)) # It should give me 50
    parameter1 = 10 # changing the value of parameter1 in test function
    print(test(1)) # It should give me 10
    
main()

Read more here: https://www.w3schools.com/python/ref_keyword_nonlocal.asp

ucbpb
  • 21
  • 3