Created
July 10, 2014 17:36
-
-
Save sprin/4b5f832ee11d1d175d3a to your computer and use it in GitHub Desktop.
Safe and unsafe Python function calling patterns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
A demonstration of safe and unsafe ways to write and call Python functions that | |
take required and optional arguments that are likely to change over time. | |
Try performing common refactoring operations on the functions such | |
as adding/removing required/optional args and changing args to and from | |
required to optional. Also consider combinations of these operations. | |
The calling patterns marked dangerous are likely to break in some of these | |
situations, whereas the safe pattern of always calling with keywords | |
is robust against errors and will immediately produce an exception when a | |
calling error is made. | |
""" | |
def fun1(a, b, c): | |
return ' '.join([a, b, c]) | |
def call_fun1_safe(): | |
print fun1( | |
c = 'dogfood', | |
b = 'eat', | |
a = 'dog', | |
) | |
def call_fun1_dangerous(): | |
print fun1('dog', 'eat', 'dogfood') | |
def fun2(a, b, c, d='', e=''): | |
non_empty = [x for x in [a, b, e, c, d] if x] | |
return ' '.join(non_empty) | |
def call_fun2_safe(): | |
print fun2( | |
c = 'dogfood', | |
b = 'eat', | |
a = 'dog', | |
) | |
def call_fun2_still_safe(): | |
print fun2( | |
e = 'too much', | |
d = 'then sleep', | |
c = 'dogfood', | |
b = 'eat', | |
a = 'dog', | |
) | |
def call_fun2_dangerous(): | |
print fun2('dog', 'eat', 'dogfood', 'then sleep', 'too much') | |
def call_fun2_still_dangerous(): | |
print fun2('dog', 'eat', 'dogfood', d='then sleep', e='too much') | |
if __name__ == '__main__': | |
call_fun1_safe() | |
call_fun1_dangerous() | |
call_fun2_safe() | |
call_fun2_dangerous() | |
call_fun2_still_dangerous() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment