Skip to content

Instantly share code, notes, and snippets.

@giwa
Created March 7, 2016 04:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giwa/9c2467f0ab0795437129 to your computer and use it in GitHub Desktop.
Save giwa/9c2467f0ab0795437129 to your computer and use it in GitHub Desktop.
EP 15 Know How Closures Interact with Variable Scope ref: http://qiita.com/giwa/items/ef67c710fd007039c48a
def sort_priority(values, group):
def helper(x):
if x in group:
return (0, x)
return (1, x)
values.sort(key=helper)
In [2]: numbers = [8, 3, 1, 2, 4, 5, 7,6]
In [3]: group = {2, 3, 5, 7}
In [4]: sort_priority(numbers, group)
In [5]: print(numbers)
[2, 3, 5, 7, 1, 4, 6, 8]
def sort_priority2(numbers, group):
found = False # Scope: sort_priority2
def helper(x):
if x in group:
found = True # Scope: helper -- Bad
return 0, x
return 1, x
numbers.sort(key=helper)
return found
>>> l = [4, 6,2,5,7,9, 0]
>>> found = sort_priority2(l, [2,5,8])
>>> found
False
>>> l
[2, 5, 0, 4, 6, 7, 9]
def sort_priority2(numbers, group):
found = False # Scope: sort_priority2
def helper(x):
nonlocal found
if x in group:
found = True # Scope: helper -- Bad
return 0, x
return 1, x
numbers.sort(key=helper)
return found
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment