Type unification and modules
Guido van Rossum
guido at python.org
Tue Sep 11 14:11:30 EDT 2001
Pekka Pessi <Pekka.Pessi at nokia.com> writes:
> However, I the __call__ attribute does not work (or then I have
> an old alpha):
>
> Python 2.2a2 (#1, Sep 3 2001, 23:06:29)
> [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-85)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import types
> >>> class Module(types.ModuleType):
> ... pass
> ...
> >>> m = Module()
> >>> def modulecall():
> ... print "called a module"
> ...
> >>> m.__call__ = modulecall
> >>> m()
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: object is not callable: <module '?' (built-in)>
> >>> class Class:
> ... pass
> ...
> >>> c = Class()
> >>> def instancecall():print "called an instance"
> ...
> >>> c.__call__ = instancecall
> >>> c()
> called an instance
> >>>
You are abusing a shortcut that doesn't work for new classes for a
different reason. It works if you write this the normal way:
>>> class Module(types.ModuleType):
def __call__(self):
print "hello world"
>>> m = Module()
>>> m()
hello world
>>>
> I thought that modules were exception to the rule, but only pure
> instances seem to support __call__ now. There seems to be an
> IsInstance() test somewhere preventing calling other objects.
Not exactly. (Guessing about the implementation rarely gets you where
you want to be in your understanding. :-)
> >Do you want to be able to call a module? Why?
>
> Actually, I want to call *any* object with a __call__ attribute.
Well, being callable and having a __call__ attribute are still not
entirely the same. That's just how it is. The __call__ method has to
be implemented by the type.
> Modules are only way to access other languages; if I have a
> module which just provides access to an object implemented in C,
> I'd like to create that object just by calling the module.
You can't do that in Python right now, and you must be aware of the
common workaround: define a function that you call to create the
object.
> On the other hand, now that type objects can be are used as
> constructors, I should call the type object instead. Hmmm.
Exactly.
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-list
mailing list