Using non-dict namespaces in functions

Eric Snow ericsnowcurrently at gmail.com
Sat Mar 17 14:42:49 EDT 2012


On Sat, Mar 17, 2012 at 4:18 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Note that it is important for my purposes that MockChainMap does not
> inherit from dict.

Care to elaborate?

> 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?

This looks like one of those cases where there is strict type checking
(of a Python object) at the C level.  You may consider bringing this
up in a tracker ticket.  Unless there are performance implications,
it's likely a case of no one having bothered to change this spot to be
more duck-type friendly.  There are quite a few of those in CPython
and I've seen at least a couple updated when someone brought it up.

Regardless, you could also implement __call__() on a function
look-alike class to get what you're after.  It may not be as
performant though.

-eric



More information about the Python-list mailing list