Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #21828

Re: Using non-dict namespaces in functions

References <4f647317$0$29981$c3e8da3$5496439d@news.astraweb.com>
Date 2012-03-17 11:42 -0700
Subject Re: Using non-dict namespaces in functions
From Eric Snow <ericsnowcurrently@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.764.1332009772.3037.python-list@python.org> (permalink)

Show all headers | View raw


On Sat, Mar 17, 2012 at 4:18 AM, Steven D'Aprano
<steve+comp.lang.python@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Using non-dict namespaces in functions Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-03-17 11:18 +0000
  Re: Using non-dict namespaces in functions Eric Snow <ericsnowcurrently@gmail.com> - 2012-03-17 11:42 -0700
    Re: Using non-dict namespaces in functions Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-03-18 01:52 +0000
      Re: Using non-dict namespaces in functions Peter Otten <__peter__@web.de> - 2012-03-18 08:50 +0100

csiph-web