0

I have a module where some constants are defined and also used in several functions. How can I over-ride their values from my main file ?

Say this is the module, test_import.py

MY_CONST = 1

def my_func(var = MY_CONST):
    print(var)

And this is my main.py file:

import test_import

MY_CONST = 2
test_import.MY_CONST = 3

test_import.my_func()

This code still prints "1". I want it to print some other value (obviously, without passing a value when calling my_func())

horace_vr
  • 3,026
  • 6
  • 26
  • 48
  • Does this answer your question? ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) – JonSG Apr 03 '23 at 19:06
  • @JonSG : It certainly explains the "why", but not actually providing and answer on "how". But helpful, thank you! (even if counterintuitive title; for novices, at least :P) – horace_vr Apr 03 '23 at 19:23

1 Answers1

5

The default value is stored with the function itself when the function is defined; it is not looked up in the global scope when the function is called without an argument.

>>> test_import.my_func.__defaults__[0]
1

You can, if you really want to, assign a new default value to be used.

>>> test_import.my_func.__defaults__[0] = 9
>>> test_import.my_func()
9
chepner
  • 497,756
  • 71
  • 530
  • 681