Skip to content

Instantly share code, notes, and snippets.

@termith
Last active September 29, 2017 09:37
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 termith/745adf155e31535e4af7 to your computer and use it in GitHub Desktop.
Save termith/745adf155e31535e4af7 to your computer and use it in GitHub Desktop.
Effective Python
def log_missing():
   print('Key added')
   return 0
   
current = {'green': 12, 'blue': 3}
increments = [('red', 5), ('blue', 17), ('orange', 9)]
result = defaultdict(log_missing, current)
print('Before:', dict(result))
for key, amount in increments:
    result[key] += amount
print('After: ', dict(result))
>>>
Before: {'green': 12, 'blue': 3}
Key added
Key added
After:  {'orange': 9, 'green': 12, 'blue': 20, 'red': 5}
def increment_with_report(current, increments):
    added_count = 0
    def missing():
      nonlocal added_count  # Stateful closure
      added_count += 1
      return 0
    result = defaultdict(missing, current)
    for key, amount in increments:
        result[key] += amount
return result, added_count
class BetterCountMissing(object):
    def __init__(self):
        self.added = 0
        
    def __call__(self):
        self.added += 1
return 0
counter = BetterCountMissing()
result = defaultdict(counter, current)  # Relies on __call__
for key, amount in increments:
    result[key] += amount
assert counter.added == 2
# Gettattr demo
class LazyDB(object):
    def __init__(self):
        self.exists = 5
    def __getattr__(self, name):
        value = 'Value for %s' % name
        setattr(self, name, value)
       return value”
class LoggingLazyDB(LazyDB):
    def __getattr__(self, name):
        print('Called __getattr__(%s)' % name)
       return super().__getattr__(name)
data = LoggingLazyDB()
print('exists:', data.exists)
print('foo:   ', data.foo)
print('foo:   ', data.foo)
>>>
exists: 5
Called __getattr__(foo)
foo:    Value for foo
# Because of setattr called now __getattr__ isn't calling
foo:    Value for foo
def sort_priority(values, group):
    def helper(x):
        if x in group:
            return (0, x)
       return (1, x)
    values.sort(key=helper)
it = read_visits('/tmp/my_numbers.txt')
print(list(it))
print(list(it)) # Already exhausted
>>>
[15, 35, 80]
[]
even_squares = [x**2 for x in a if x % 2 == 0]
chile_ranks = {'ghost': 1, 'habanero': 2, 'cayenne': 3}
rank_dict = {rank: name for name, rank in chile_ranks.items()}
chile_len_set = {len(name) for name in rank_dict.values()}
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [x for row in matrix for x in row]
it = (len(x) for x in open('/tmp/my_file.txt'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment