I want to use a function with a default argument (as in argument with default value) in two separate scripts in which that default argument is set differently. Of course, the function may also be called with the argument set to anything other than the default value.
Below is a minimal dummy example using functions to write a message msg
to a list of files, write_list
. The functions are defined in test_write_utils.py and are imported in multiple different scripts, only for this example in only one script, test_write_main.py.
test_write_utils.py:
""" def write_func(msg, write_list=[file1, file2]):
for file in write_list:
print('Write to %s' % file)
# open(file, 'w').write(msg)
"""
def write_func2(msg, write_list=None):
if write_list is None:
write_list = [file1, file2]
for file in write_list:
print('Write to %s' % file)
# open(file, 'w').write(msg)
class writeclass:
# user can (but does not have to) provide a default write list
def __init__(self, default_write_list=[]):
self.default_write_list = default_write_list
def write(self, msg, write_list=None):
if write_list is None:
write_list = self.default_write_list
for file in write_list:
print('Write to %s' % file)
# open(file, 'w').write(msg)
test_write_main.py:
# from test_write_utils import write_func # NameError: name 'file1' is not defined
from test_write_utils import write_func2, writeclass
file1 = 'file1.txt'
file2 = 'file2.txt'
write_list = [file1, file2]
# write_func('test')
# write_func2('test') # NameError: global name 'file1' is not defined
# define variables in namespace of test_write_utils;
# import statement here instead of beginning (bad practice) only to make structure clear
import test_write_utils
test_write_utils.file1 = file1
test_write_utils.file2 = file2
write_func2('test') # works
mywriter = writeclass(write_list)
mywriter.write('test') # works
write_func
(when uncommented) raises an error during import since it must have file1
and file2
defined at import time. write_func2
, with default argument None
based on this post, can be imported, but will raise an error during the function call due to separate namespaces of the scripts. If the variables are defined in the appropriate namespace test_write_utils
(I then commented write_func
out to avoid the import error), write_func2
works. However, the flow of information is obscured, i.e. the user does not see in test_write_utils.py where the variables are actually defined. Using a method of a class writeclass
instead of functions also works and the default write list can be independently set in each script during instantiation.
Question: Is there a non-class-method-based, recommended way to use a function with a "variable" default argument in different scripts (in which the default argument is set differently)? I'm using Python 2.7.18, in case it is relevant for anything.