Skip to content

Commit 905b75e

Browse files
committed
make AliasModule proxy attribute access methods to original module.
1 parent 2d0a1b8 commit 905b75e

File tree

2 files changed

+50
-21
lines changed

2 files changed

+50
-21
lines changed

apipkg.py

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -134,27 +134,27 @@ def __dict__(self):
134134
return dict
135135
__dict__ = property(__dict__)
136136

137-
class AliasModule(ModuleType):
138-
def __init__(self, name, modpath):
139-
self.__name = name
140-
self.__modpath = modpath
141137

142-
def __repr__(self):
143-
return '<AliasModule %r for %r>' % (self.__name, self.__modpath)
138+
def AliasModule(modname, modpath):
139+
mod = []
144140

145-
def __getattr__(self, name):
146-
mod = importobj(self.__modpath, None)
147-
result = getattr(mod, name)
148-
setattr(self, name, result)
149-
for k, v in mod.__dict__.items():
150-
setattr(self, k, v)
151-
return result
141+
def getmod():
142+
if not mod:
143+
mod.append(importobj(modpath, None))
144+
return mod[0]
152145

153-
def __dict__(self):
154-
# force all the content of the module to be loaded when __dict__ is read
155-
dictdescr = ModuleType.__dict__['__dict__']
156-
dict = dictdescr.__get__(self)
157-
if dict is not None:
158-
hasattr(self, 'some')
159-
return dict
160-
__dict__ = property(__dict__)
146+
class AliasModule(ModuleType):
147+
148+
def __repr__(self):
149+
return '<AliasModule %r for %r>' % (modname, modpath)
150+
151+
def __getattribute__(self, name):
152+
return getattr(getmod(), name)
153+
154+
def __setattr__(self, name, value):
155+
setattr(getmod(), name, value)
156+
157+
def __delattr__(self, name):
158+
delattr(getmod(), name)
159+
160+
return AliasModule(modname)

test_apipkg.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,35 @@ def test_aliasmodule_repr():
409409
am.version
410410
assert repr(am) == r
411411

412+
def test_aliasmodule_proxy_methods(tmpdir, monkeypatch):
413+
pkgdir = tmpdir
414+
pkgdir.join('aliasmodule_proxy.py').write(py.code.Source("""
415+
def doit():
416+
return 42
417+
"""))
418+
419+
pkgdir.join('my_aliasmodule_proxy.py').write(py.code.Source("""
420+
import apipkg
421+
apipkg.initpkg(__name__, dict(proxy='aliasmodule_proxy'))
422+
423+
def doit():
424+
return 42
425+
"""))
426+
427+
monkeypatch.syspath_prepend(tmpdir)
428+
import aliasmodule_proxy as orig
429+
from my_aliasmodule_proxy import proxy
430+
431+
doit = proxy.doit
432+
assert doit is orig.doit
433+
434+
del proxy.doit
435+
py.test.raises(AttributeError, "orig.doit")
436+
437+
proxy.doit = doit
438+
assert orig.doit is doit
439+
440+
412441
def test_initpkg_without_old_module():
413442
apipkg.initpkg("initpkg_without_old_module",
414443
dict(modules="sys:modules"))

0 commit comments

Comments
 (0)