Created
May 8, 2015 04:43
-
-
Save lonetwin/8c944711cdb8d5724e42 to your computer and use it in GitHub Desktop.
Outer variables in closures evaluation - http://tech.magnetic.com/2015/05/optimize-python-with-closures.html
This file contains hidden or 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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
def page_category_filter(bid_request, config): | |
if config["mode"] == "whitelist": | |
return bool( | |
bid_request["categories"] & set(config["categories"]) | |
) | |
else: | |
return bool( | |
config["categories"] and not | |
bid_request["categories"] & set(config["categories"]) | |
) | |
def make_page_category_filter(config): | |
categories = set(config["categories"]) # This will get evaluated only once | |
mode = config["mode"] # ...as will this, at ... | |
def page_category_filter(bid_request): | |
if mode == "whitelist": | |
return bool(bid_request["categories"] & categories) | |
else: | |
return bool( | |
categories and not | |
bid_request["categories"] & categories | |
) | |
return page_category_filter | |
config = {'mode' : "whitelist", | |
'categories' : ["foo", "bar", "baz"] | |
} | |
whitelist_category_filter = make_page_category_filter(config) # ...here | |
print whitelist_category_filter({'categories' : {'foo'} }) | |
print page_category_filter({'categories' : {'foo'} }, config) | |
print whitelist_category_filter({'categories' : {'bax'} }) | |
# This will not affect the already evaluated ^local^ categories defined in | |
# make_page_category_filter() | |
config['categories'].append('bax') | |
print whitelist_category_filter({'categories' : {'bax'} }) | |
print page_category_filter({'categories' : {'bax'} }, config) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment