Using non-dict namespaces in functions

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Mar 17 12:18:47 CET 2012


Inspired by the new collections.ChainMap in Python 3.3

http://docs.python.org/dev/library/collections.html#collections.ChainMap

I would like to experiment with similar non-dictionary namespaces in 
Python 3.2.

My starting point is these two recipes, adapted for Python 3.2:

http://code.activestate.com/recipes/305268/
http://code.activestate.com/recipes/577434/

Or for simplicity, here's a mock version:


from collections import Mapping
class MockChainMap(Mapping):
    def __getitem__(self, key):
        if key == 'a': return 1
        elif key == 'b': return 2
        raise KeyError(key)
    def __len__(self):
        return 2
    def __iter__(self):
        yield 'a'
        yield 'b'

Note that it is important for my purposes that MockChainMap does not 
inherit from dict.

Now I try to create a function that uses a MockChainMap instead of a dict 
for its globals:

function = type(lambda: None)
f = lambda x: (a+b+x)
g = function(f.__code__, MockChainMap(), 'g')

And that's where I get into trouble:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: function() argument 2 must be dict, not MockChainMap


How do I build a function with globals set to a non-dict mapping?

If this can't be done, any suggestions for how I might proceed?


-- 
Steven



More information about the Python-list mailing list