Last active
September 23, 2015 06:32
-
-
Save cjayb/7d43acaf3b54adca9af5 to your computer and use it in GitHub Desktop.
Call-by-object parameter passing in Python
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
# Passing a mutable object to a function is like passing a C-pointer to | |
# the memory location of the object -> mutating memory inside the function | |
# will be "visible" outside the function too. | |
# Since each function has its own _namespace_, mangling the variable | |
# is equivalent to moving the pointer away from the passed-in location | |
# so any changes to the parameter variable remain within the scope of | |
# the function. | |
outer_list = [1,2,3,4] | |
def double_last_element(inner_list): | |
inner_list[-1] *= 2 | |
print('inner_list after doubling', inner_list) | |
# Then mangle the variable in the function's namespace | |
inner_list = ['a', 'b', 'c', 'd'] | |
print('inner_list after mangling', inner_list) | |
double_last_element(outer_list) | |
print('outer_list after function call', outer_list) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment