Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
babyhoo976 opened this issue Aug 31, 2022 · 0 comments

Comments

@babyhoo976
Copy link

babyhoo976 commented Aug 31, 2022

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant