Skip to content

RuntimeError: restricted attribute setting __doc__ when being imported in python2.7 in a restricted frame #369

@babyhoo976

Description

@babyhoo976

Hi!
I'm writing a python program where I need to hook up the __import__ function in certain modules‘ __builtins__ dict to do some stuff, so that I can manage the imports in a way meta path hooks cannot provide.
In python3+ it works just fine, but in python2.7 the interpreter I got this error

  File "six.py", line 625, in <module>
    get_unbound_function, """Get the function out of a possibly unbound function"""
  File "six.py", line 82, in _add_doc
    func.__doc__ = doc
RuntimeError: restricted attribute

It turns out the python 2.7 interpreter does not allow changing function object's __doc__ attribute in a restricted frame, which is defined by the frame's __builtins__ reference is not pointing to the internal one.

here is a repro script

#! /usr/bin/python2.7

import imp
import sys
import os

name = 'six'
dir_name = os.getcwd()  # where six.py lives

def my_import(name, globals, locals, fromlist, level):
    print(name, fromlist, level)
    return __import__(name, globals, locals, fromlist, level)

spec = imp.find_module(name, [dir_name])
module = imp.new_module(name)
my_builtins = dict(__builtins__.__dict__)
my_builtins['__import__'] = my_import
module.__builtins__ = my_builtins
sys.modules[name] = module
imp.load_module(name, *spec)

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions