0

I attempted to use the sys.modules replacement trick described in https://stackoverflow.com/a/7668273/23845 but it does not work in the following case in Python 2:

# a/__init__.py
import sys

class AMod(object):
    def __init__(self, d):
        self.__dict__ = d

sys.modules[__name__] = AMod(sys.modules[__name__].__dict__)

And:

# a/sub.py
import a

z = True

Finally:

# b.py
import a.sub

This fails with:

pymodshenanigans ezyang$ python b.py 
Traceback (most recent call last):
  File "b.py", line 1, in <module>
    import a.sub
RuntimeError: sys.path must be a list of directory names

Is there a way to make this work? (It works on Python 3.)

Edward Z. Yang
  • 26,325
  • 16
  • 80
  • 110

1 Answers1

0

@martineau is right: you have to retain a reference to the old module. This version works:

# a/__init__.py
import sys

class AMod(object):
    def __init__(self, m):
        self.__dict__ = m.__dict__
        self.old_mod = m

sys.modules[__name__] = AMod(sys.modules[__name__])
Edward Z. Yang
  • 26,325
  • 16
  • 80
  • 110