Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to use a lambda as a dictionary default?

Tags:

python

I'm trying to keep a dictionary of open files for splitting data into individual files. When I request a file from the dictionary I would like it to be opened if the key isn't there. However, it doesn't look like I can use a lambda as a default.

e.g.

files = {}
for row in data:
  f = files.get(row.field1, lambda: open(row.field1, 'w'))
  f.write('stuff...')

This doesn't work because f is set to the function, rather than it's result. setdefault using the syntax above doesn't work either. Is there anything I can do besides this:

f = files.get(row.field1)
if not f:
    f = files[row.field1] = open(row.field1, 'w')
like image 538
Jacob Avatar asked Feb 20 '12 19:02

Jacob


2 Answers

This use case is too complex for a defaultdict, which is why I don't believe that something like this exists in the Python stdlib. You can however easily write a generic "extended" defaultdict yourself, which passes the missing key to the callback:

from collections import defaultdict

class BetterDefaultDict(defaultdict):
  def __missing__(self, key):
    return self.setdefault(key, self.default_factory(key))

Usage:

>>> files = BetterDefaultDict(lambda key: open(key, 'w'))
>>> files['/tmp/test.py']
<open file '/tmp/test.py', mode 'w' at 0x7ff552ad6db0>

This works in Python 2.7+, don't know about older versions :) Also, don't forget to close those files again:

finally:
  for f in files.values(): f.close()
like image 192
Niklas B. Avatar answered Nov 11 '22 21:11

Niklas B.


You could wrap the get-and-open in a class object's __getitem__() pretty easily - something like:

class FileCache(object):
    def __init__(self):
        self.map = {}

    def __getitem__(self,key):
        if key not in self.map:            
            self.map[key] = open(key,'w')
        return self.map.key
like image 20
Russell Borogove Avatar answered Nov 11 '22 23:11

Russell Borogove