[Python-ideas] Allow function __globals__ to be arbitrary mapping not just dict

Steven D'Aprano steve at pearwood.info
Tue Mar 20 00:51:02 CET 2012


Terry Reedy wrote:
> On 3/18/2012 8:27 AM, Steven D'Aprano wrote:
>> Currently, if you try to construct a function from parts, the mapping
>> that becomes func.__globals__ must be an actual dict:
[...]
> The API of internal classes is intentionally not documented in the types 
> module doc. I take this to mean that the api, if not the existence, of 
> such classes, is implementation specific. Hence any such call is a 
> 'cpython' rather than generic python call.

Are you sure that they are *intentionally* not documented, or merely haven't 
been due to lack of time and interest?

The types themselves are documented as public, they aren't given _single 
underscore private names, and FunctionType has a minimal but useful doc string 
with nothing about it being implementation specific.


> Someone pointed out on python-list that FunctionType checks and rejects 
> non-dict second args because the CPython ceval loop code for CPython 
> LOAD_GLOBAL and STORE_GLOBAL opcodes directly access dicts rather than 
> using the generic mapping interface.

I expect that the existing optimization would be used whenever __globals__ is 
an actual dict, and the mapping interface would only be used when it is a 
subclass of dict or other mapping. So for normal functions, the only cost 
would be an extra type check to see whether __globals__ is a dict or not.


[...]
> Alternative proposal: write a function to replace LOAD_GLOBAL and 
> STORE_GLOBAL for non-builtin names with the opcodes to access a mapping 
> passed in as an arg to the rewrite function or the function itself.

Are you proposing that I hack the byte code of the function? Now that would be 
unsupported and implementation dependent!

If not, I'm afraid I don't understand your suggestion.



-- 
Steven



More information about the Python-ideas mailing list