Type unification and modules

Ben Wolfson rumjuggler at cryptarchy.org
Sun Sep 9 01:53:30 EDT 2001


On Sun, 09 Sep 2001 05:04:29 GMT, Guido van Rossum <guido at python.org>
wrote:

>Do you want to be able to override __getattr__ and __setattr__ in
>modules?  That has nothing to do with the type/class unification; a
>module is still not the same as a class.  But you could write a
>subclass of the module type that supported any special method you
>like.

I have a program in which I place a class instance in sys.modules, and one
of the things that bothered me when testing it in the interpreter was that
I couldn't call reload() on it because it wasn't a module.  So with this
news I tried the following:


#file modtest.py
import types, os, sys

class Mod(types.ModuleType):
    def __getattr__(self, k):
        return getattr(os, k)
    def __setattr__(self, k, v):
        setattr(os, k, v)

sys.modules['modtest'] = Mod()

#interactive IDLE session
Python 2.2a3 (#23, Sep  7 2001, 01:43:22) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> import modtest
>>> modtest
<module '?' (built-in)>
>>> modtest.sep
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in ?
    modtest.sep
  File "C:\Python22\modtest.py", line 5, in __getattr__
    return getattr(os, k)
AttributeError: 'NoneType' object has no attribute 'sep'
>>> import os
>>> getattr(os, 'sep')
'\\'
>>> import pdb
>>> pdb.run('print modtest.sep')
> <string>(0)?()
(Pdb) s
> <string>(1)?()
(Pdb) s
> C:\Python22\modtest.py(4)__getattr__()
-> def __getattr__(self, k):
(Pdb) s
> C:\Python22\modtest.py(5)__getattr__()
-> return getattr(os, k)
(Pdb) p os
None
(Pdb) q
>>> reload(modtest)
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in ?
    reload(modtest)
TypeError: reload() argument must be module
>>> modtest
<module '?' (built-in)>
>>> 

So there doesn't seem to be much point in subclassing the module type.

-- 
Barnabas T. Rumjuggler
You're going to set me up as a kind of slovenly attached pig that
Jack Kornfeld can slice down in his violent zen compassion?
 -- Larry Block



More information about the Python-list mailing list