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
5
  • That's not going to work. parameter1 in main.py is unrelated to parameter1 inside the test function in def_function.py. Commented Sep 12, 2019 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. Commented Sep 12, 2019 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. Commented Sep 12, 2019 at 15:01
  • If you want it to change, you'll have to pass it in somehow. Either as a parameter, or a global. Commented Sep 12, 2019 at 15:01
  • 1
    Am I missing something but is there a reason you can't use a default argument? def test(x, parameter1=50) and if you need a different parameter1 just use test(1, 10). Commented Sep 12, 2019 at 15:03

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect ! That was the type of answer I was looking for. Thank you !
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.