3

In essence, I have been able to solve my issue, but I still don't feel entirely comfortable with my solution and would like to ask what the community thinks. I found a similar issue on stackoverflow as well, but it does not help me with my questions. Furthermore, I also read this answer, which did clarify some aspects, but it did not help me to understand what the best practice should be in my case.

My "issue" is the following: I have created several modules that I want to be able to execute separately (kind of like a script) each containing a specific algorithm (often divided into multiple functions). Basically to illustrate my point I was doing the following (module.py):

CONSTANT = 20


def func(arg=CONSTANT):
    print("argument= ", arg)


if __name__ == '__main__':
    func()

The constants are simulation constants, and can be different for each run, but as I run the file as a script, I can just change the constants at the top and call the file. I assume that my this is my erroneous thought, and that I should consider them as variables instead of constants, but please don't hesitate to educate me.

Later I have another file, which executes larger simulations using the multiple modules I've created before. But for some runs, I would like to change some "constants", like per the following (run.py):

import module

module.CONSTANT = 50

module.func()

When I call module.py I would expect it to print argument= 20, when I call run.py I would expect argument= 50 to be printed, but unfortunately it does not, and prints 20 in both cases.

I was able to solve it by changing module.py into the following (module2.py):

CONSTANT = 20


def func(arg=None):
    if arg is None:
        arg = CONSTANT
    print("argument= ", arg)


if __name__ == '__main__':
    func()

So I assume this is because when the functions are defined, the default values are bound, and as the constant is changed after importing the module, this has no effect, whereas in the second snippet, the value is changed dynamically after calling the function, which is done after changing the constant.

Now my actual questions and doubts:

  1. Is there a "standard" way of defining default constants in function definitions?
  2. Why are the default values for the arguments static when defined in between the parenthesis? (This is partially answered in the answer posted above)
  3. Should I in my case approach it completely differently because my "constants" are not actual constants? and if so, what would you advise?

Thanks for your advice!

JKarouta
  • 66
  • 5

0 Answers0