How to make function arguments optional?
Question:
For example, I want to be able to inject a behavior if I want to inside a function, but if I don’t have a behavior, I want it to have a default behavior
class TestDefaultParam:
def defaultBehavior(file1, file2):
return 2
def action(file1, file2, behave=defaultBehavior):
return behave(file1, file2)
if __name__ == '__main__':
some = TestDefaultParam()
print(some.action("test", "test"))
If this isn’t possible how can I change behavior of action at will?
with this code I get this error:
Traceback (most recent call last):
File ".test.py", line 10, in <module>
print(some.action("test", "test"))
File ".test.py", line 6, in action
return behave(file1, file2)
TypeError: 'str' object is not callable
Answers:
Maybe this will help. In your case,
def action(file1, file2, behavior=defaultBehavior):
return behave(file1, file2)
is okay. But of course, if an argument is passed into the “behave” parameter, you should take care of it in your function. For instance, if you called
action("somefile", "anotherfile", customBehavior)
then you’ll want something like the following to deal with it:
def action(file1, file2, behavior=defaultBehavior):
if behave != defaultBehavior: # this means that behavior was set to something
behave(file1, file2, behavior)
else: # in this case, behave == defaultBehavior
behave(file1, file2)
Something similar can be constructed for behave()
.
For example, I want to be able to inject a behavior if I want to inside a function, but if I don’t have a behavior, I want it to have a default behavior
class TestDefaultParam:
def defaultBehavior(file1, file2):
return 2
def action(file1, file2, behave=defaultBehavior):
return behave(file1, file2)
if __name__ == '__main__':
some = TestDefaultParam()
print(some.action("test", "test"))
If this isn’t possible how can I change behavior of action at will?
with this code I get this error:
Traceback (most recent call last):
File ".test.py", line 10, in <module>
print(some.action("test", "test"))
File ".test.py", line 6, in action
return behave(file1, file2)
TypeError: 'str' object is not callable
Maybe this will help. In your case,
def action(file1, file2, behavior=defaultBehavior):
return behave(file1, file2)
is okay. But of course, if an argument is passed into the “behave” parameter, you should take care of it in your function. For instance, if you called
action("somefile", "anotherfile", customBehavior)
then you’ll want something like the following to deal with it:
def action(file1, file2, behavior=defaultBehavior):
if behave != defaultBehavior: # this means that behavior was set to something
behave(file1, file2, behavior)
else: # in this case, behave == defaultBehavior
behave(file1, file2)
Something similar can be constructed for behave()
.