What do you call a class not intended to be instantiated

Terry Reedy tjreedy at udel.edu
Sun Sep 28 03:20:28 EDT 2008


Steven D'Aprano wrote:

> And modules aren't callable. I've often thought they should be.

Modules are not callable because their class, module, has no __call__ 
instance method.  But (in 3.0, which is all I will check) you can 
subclass module and add one.

 >>> m = type(__builtins__)
 >>> m
<class 'module'>
 >>> dir(m)
['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', 
'__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', 
'__subclasshook__']
 >>> class m2(m):
	def __call__(self, *args, **kwds):
		print(self, args, kwds)

		
 >>> mod = m2('mod') # only arg required by module.__init__
 >>> mod(1,2,3,a=4,b=5)
<module 'mod' (built-in)> (1, 2, 3) {'a': 4, 'b': 5}
 >>> mod # did not override __repr__
<module 'mod' (built-in)>

So, roll your own to your taste.

Terry Jan Reedy




More information about the Python-list mailing list