2

Let's consider the following example:

import module

def function(param=module.value):
    pass

Is it good practice to set the default value of a function argument to an identifier imported from another module? I know it works, but I am asking rather about clean code approach and possible problems. I can see here a potential vulnerability: the value of the variable imported from module can be mutable in next release. What do you think about that?

Georgy
  • 12,464
  • 7
  • 65
  • 73
biniow
  • 391
  • 1
  • 10
  • But why setting default value for `param` in the first place? I think it would be more clear just to pass it as parameter later when you call it: `function(module.value)`. – Georgy Dec 12 '18 at 13:54
  • That's a more comment relating to the usefulness of default parameters. Default parameters are useful exactly because you don't want the caller to have to specify them (most of the times). – MrR Mar 26 '21 at 21:55

2 Answers2

4

I suggest setting the default to None then programatically test for that in your code:

import module

def function(param = None):
    if param is None:
        param = module.value

It could be that a straight assignment (which just copies a reference) is not appropriate.

For example, you mention that the class of object could change from immutable to mutable between releases. If that occurs then you probably need to use copy.deepcopy() rather than an assignment.

However, not all classes have their own __deepcopy__(), and so copying objects can be problematic. It could be that a new object should be created using the values from the original. It is hard to say what should be used without knowing the class of the object and what you are going to do with param.

cdarke
  • 42,728
  • 8
  • 80
  • 84
0

You can write wrapper for your purpose. If the library change or deprecate value, you can still get the same value.

Just write a simple wrapper moduleWrapper

def getValue():
    try:
        return module.value
    except:
        return None

Or you can set your default value that you want and then you can set this function as param.

import moduleWrapper
def function(param=moduleWrapper.getValue()):
    pass

This way if module change, you can still get your code work.

Community
  • 1
  • 1